@sentry/junior 0.317.0 → 0.319.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter-8_S6Birm.js +1833 -0
- package/dist/{admin-CAugg87B.js → admin-EsbUON1j.js} +1 -1
- package/dist/{agent-runner-AjrEV6Qe.js → agent-CtzMl32d.js} +19953 -6727
- package/dist/{agent-status-BA5x3Xtp.js → agent-status-Bq_AIpyp.js} +105 -1
- package/dist/{agent-update-delivery-B_YIZcgf.js → agent-update-delivery-pAvsbuGL.js} +4 -5
- package/dist/api/schema.d.ts +85 -51
- package/dist/api/schema.js +4 -4
- package/dist/api.js +81 -94
- package/dist/{app-MoNAsVV5.d.ts → app-tACXxJPI.d.ts} +8 -13
- package/dist/app.d.ts +2 -2
- package/dist/app.js +246 -153
- package/dist/{change-record-BzJgLsv7.d.ts → change-record-K-KsqNhT.d.ts} +9 -5
- package/dist/{channel-access-j-YAVYK4.js → channel-access-DET5hzZM.js} +1 -1
- package/dist/{chat-core-engine-aH85nEHv.js → chat-core-engine-DpM3tMVi.js} +7 -7
- package/dist/cli/chat.d.ts +1 -1
- package/dist/cli/chat.js +38 -30
- package/dist/cli/check.js +5 -5
- package/dist/cli/main.js +2 -2
- package/dist/cli/plugins.d.ts +1 -1
- package/dist/cli/plugins.js +8 -8
- package/dist/cli/snapshot-create.js +5 -6
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +3 -4
- package/dist/{continue-in-slack-D-FZ8Fin.js → continue-in-slack-CFzDyxkH.js} +3 -2
- package/dist/{conversation-feed--9S0_PXL.js → conversation-feed-DEUdD7mb.js} +2 -106
- package/dist/{conversation-privacy-B1uXn5sf.js → conversation-privacy-C2vYK55O.js} +1 -1
- package/dist/{create-DoDIYgtZ.js → create-Ta3SEIB5.js} +124 -16
- package/dist/{credential-sync-BJOqGnjV.js → credential-sync-DyRqDmY4.js} +17 -20
- package/dist/{db-BFmyYZtJ.js → db-BCaNWl9p.js} +6536 -1920
- package/dist/{deployment-DXq9ZLU4.js → deployment-CfOew1Tm.js} +3 -3
- package/dist/{engine-context-CgQ7mlHt.js → engine-context-CiExoy1B.js} +181 -155
- package/dist/{html-B3VKTGbJ.js → html-Bb2Si1bR.js} +6 -8
- package/dist/instrumentation.js +7 -23
- package/dist/list-wwDcROh9.js +5007 -0
- package/dist/{logging--smS7XRK.js → logging-BRPTXAdf.js} +10 -81
- package/dist/{mailbox-turn-uSXhUFc9.js → markers-9QoqW5ov.js} +1875 -1458
- package/dist/nitro.d.ts +2 -2
- package/dist/nitro.js +7 -8
- package/dist/{oauth-callback-server-CE4soEIY.js → oauth-callback-server-vhL9b-PZ.js} +2 -2
- package/dist/{oauth-relay-C36gX1gH.js → oauth-relay-CH2v7WiB.js} +1 -1
- package/dist/{plugins-fBrz8PCV.d.ts → plugins-DhGXZjlu.d.ts} +1 -0
- package/dist/{profile-BQ-iBDsZ.js → profile-D9LdwmZi.js} +17 -19
- package/dist/{prompt-Dv7gkpD6.js → prompt-3TqxEOtc.js} +10 -10
- package/dist/{reports-WKHfGTsU.js → reports-K-tbtEyx.js} +2 -2
- package/dist/{resolve-tony4ibz.js → resolve-BBV2qf8A.js} +5 -5
- package/dist/{result-Bta_dlWa.js → result-5IdGJP4M.js} +24 -13
- package/dist/{runner-BstDRbD9.js → runner-BK_joPlM.js} +9 -18
- package/dist/{sandbox-egress-signals-oSJMJOnn.js → sandbox-egress-signals-DXgWXXmm.js} +1 -1
- package/dist/{schema-DfqrHACA.js → schema-zWGG6VC1.js} +13 -7
- package/dist/{service-account-CTV_jaNu.js → service-account-CateFyhw.js} +4 -5
- package/dist/{skills-BCEU41zM.js → skills-Ccjw8h2P.js} +10 -9
- package/dist/{slack-conversation-unfurl-DxVmhbGP.js → slack-conversation-unfurl-ZC_TSpc4.js} +7 -7
- package/dist/storage-C9U7R5rM.js +273 -0
- package/dist/{system-prompt-table-CiXy0eNR.js → system-prompt-table-YBTHIFlP.js} +26 -84
- package/dist/topic-B2EWKKBT.js +6 -0
- package/dist/{package-discovery-DD9vencX.js → topics-DxuKurCX.js} +21 -1
- package/dist/{types-C4iC-IMC.js → types-BNHkJrOP.js} +79 -59
- package/dist/{users-ByG5RCEJ.js → users-CCRAqYb_.js} +1 -1
- package/dist/{validation-8gjfR91V.js → validation-BCUpJa8K.js} +4 -4
- package/dist/{version-BeZhWWBE.js → version-BNm0JYj3.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{worker-BqMQQNRk.js → worker-BhgpZ7_b.js} +5 -5
- package/migrations/20261127002500_turn_discarded_usage/migration.sql +2 -0
- package/migrations/20261127002500_turn_discarded_usage/snapshot.json +73 -0
- package/migrations/20261127052408_space_name_nullable/migration.sql +5 -0
- package/migrations/20261127052408_space_name_nullable/snapshot.json +29 -0
- package/migrations/20261127060000_annotation_object_id_index/migration.sql +1 -0
- package/migrations/20261127060000_annotation_object_id_index/snapshot.json +69 -0
- package/migrations/20261127060001_annotation_subjects/migration.sql +78 -0
- package/migrations/20261127060001_annotation_subjects/snapshot.json +104 -0
- package/migrations/20261127060002_annotation_subject_index/migration.sql +1 -0
- package/migrations/20261127060002_annotation_subject_index/snapshot.json +70 -0
- package/migrations/20261127060003_annotation_title_url/migration.sql +84 -0
- package/migrations/20261127060003_annotation_title_url/snapshot.json +73 -0
- package/package.json +9 -7
- package/dist/catalog-runtime-DfSpJZdY.js +0 -6
- package/dist/child-message-DHjQLEd1.js +0 -19
- package/dist/config-CHQ8X251.js +0 -2422
- package/dist/conversation-turn-BUE_7xaN.js +0 -1157
- package/dist/job-runner-A1lCkybD.js +0 -1506
- package/dist/lineage-Bktb0UcV.js +0 -36
- package/dist/list-Bxvg5wXf.js +0 -12623
- package/dist/message-BNenhsmB.js +0 -154
- package/dist/model-input-BReSnwHp.js +0 -82
- package/dist/parent-result-Ck1rFYRQ.js +0 -310
- package/dist/registry-iXMT5Jmh.js +0 -3279
- package/dist/run-conversation-DL6ru7iW.js +0 -336
- package/dist/sender-actors-CPglLd5R.js +0 -83
- package/dist/spawn-frczVPIr.js +0 -48
- package/dist/task-runner-C9Yc2_ae.js +0 -1526
- package/dist/thread-context-CqZDKErp.js +0 -166
- package/dist/topic-CRYYBYp-.js +0 -7
- package/dist/topics-SRN7IVX-.js +0 -24
- package/dist/turn-membership-CENFf3kI.js +0 -856
- package/dist/turn-wake-BhloiI2h.js +0 -151
|
@@ -1,27 +1,26 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import { n as
|
|
2
|
+
import { $ as resolveGatewayModel, B as getSlackBotToken, L as botConfig, P as parseSlackMessageTs, R as getChatConfig, S as isUserActor, T as toStoredSlackActor, Y as TURN_REASONING_LEVELS, _ as createActor, a as getStateValues, f as credentialContextForActor, h as credentialSubjectSchema, i as getStateAdapter, k as parseSlackUserId, l as fenceLock, s as MUTATION_LOCK_TTL_MS, u as withLock } from "./adapter-8_S6Birm.js";
|
|
3
|
+
import { $l as instructionAuthor, Ad as authenticationLinkedEvent, Ai as postSlackMessage, Bc as getInboxItem, Bp as juniorConversations, Cd as getProviderErrorAttributes, Do as publishAgentUpdate, Dt as getRegistrations, Es as conversationSubtreeColumns, Et as getPlugins, Fd as getAppContext, Ff as addAgentTurnUsage, Fn as readParentMessage, Gt as appendInboundMessage, In as readInboundMessageSender, Kp as juniorUsers, Li as escapeSlackMrkdwnText, Ln as isEventMailboxMetadata, Ls as findActorTimezone, N as claimProviderConversation, Od as JUNIOR_NATIVE_EVENT_NAMESPACE, On as releaseInboundMessage, Ou as ToolInputError, Pl as projectConversationMessages, Qr as formatSentryEventReference, Ri as formatSlackLink, Sd as findProviderError, Sp as juniorAgentBindings, Tc as findSlackUserByPrimaryEmail, Ts as conversationSubtree, W as conversationLastTurnOutcomeSql, Wf as nextDetailVersion, Wi as getPluginUserPromptContributions, Wt as appendAndEnqueueInboundMessage, Xu as completeText, Yo as verifyTimerWatchCredentialSubject, Zl as dispatchInstructionsInvokeSkills, Zo as JUNIOR_THREAD_STATE_TTL_MS, Zs as getSlackClient, _n as takePendingEventMessages, a as getDb, ac as withSlackRetries, ao as fallbackShortTitle, ap as juniorWorkspaces, bc as resolveActorIdentityId, bd as createAssistantProviderError, d as createSqlConversationEventStore, du as EVENT_SYSTEM_ACTOR, ec as isDmChannel, eu as isPersonInput, fd as estimateTextTokens, fr as readThroughHttpCache, fu as eventBotAuthorId, gn as stopConversationWork, i as getConversationStore, ip as juniorWorkspaceRepos, j as startLocationThread, jd as conversationNoteEvent, kd as agentsInstructionsUpdatedEvent, ki as postSlackEphemeralMessage, kn as traceContextSchema, kp as juniorConversationEvents, lu as EVENT_AUTHOR_ID, mu as isEventConversationMessage, n as getConversationEventStore, o as getSqlExecutor, oa as createPluginCache, oc as sleep, on as getConversationWorkState, oo as generateShortTitle, po as getEventCatalog, qp as juniorDestinations, rn as dropPendingMessages, rp as juniorSnapshots, sa as getConfigDefaults, sd as createCache, sn as getConversationWorkStates, ta as pluginConfigValues, u as isPostgresErrorCode, uu as EVENT_MESSAGE_AUTHOR, v as withConversationEventLock, vd as isCompactionSummaryText, vu as eventGuidance, wc as findLinkedSlackUser, wd as getProviderErrorUserMessage, xd as createProviderError, xp as juniorLocationConfigurations, yc as SYSTEM_IDENTITY_ID, zr as getVercelConversationWorkQueue } from "./db-BCaNWl9p.js";
|
|
4
|
+
import { Ct as instructionActors, St as contextProvenance, Un as isAgentUpdateEventType, Vt as messageCardRef, bt as piMessageSchema, gt as historyItemFromPiMessage, nt as agentTypeInstructions, pn as inboxItemQuestion, rt as agentTypeSchema, wt as instructionProvenanceFor, xn as normalizeUserInputAnswer, xt as agentInstructionProvenance, yn as formatUserInputAnswer, yt as piMessageFromHistoryItem } from "./types-BNHkJrOP.js";
|
|
5
|
+
import { A as toOptionalString, O as isNativeIdentityProvider, S as summarizeMessageText, T as withSpan, _ as serializeGenAiAttribute, a as getActiveTraceContext, f as logException, m as logWarn, p as logInfo, y as setSpanAttributes } from "./logging-BRPTXAdf.js";
|
|
6
|
+
import { A as retainRuntimeTurnContext, B as authorAttrs, D as isToolResultError, G as mapBounded, I as TURN_CONTEXT_TAG, L as renderCurrentInstruction, M as trimTrailingAssistantMessages, O as isToolResultMessage, T as isContinuablePiBoundary, U as renderParentAgentTask, W as renderThreadContext, _ as extractAssistantText, c as SANDBOX_REPOS_ROOT, d as SANDBOX_WORKSPACE_ROOT, h as createPluginLogger, j as stripRuntimeTurnContext, k as normalizeToolNameFromResult, w as isAssistantMessage, x as hasRuntimeTurnContext, y as getTerminalAssistantMessages, z as THREAD_CONTEXT_TAGS } from "./prompt-3TqxEOtc.js";
|
|
7
|
+
import { a as toCanonicalInputMessage } from "./conversation-privacy-C2vYK55O.js";
|
|
8
|
+
import { a as parseSkillFile, i as openAiPolicyDisablesImplicitInvocation } from "./skills-Ccjw8h2P.js";
|
|
9
|
+
import { N as resolveSandboxEgressProviderForHost, O as parseSandboxEgressAuthRequiredSignal, f as findInErrorChain, n as hash, o as getSandboxProvider, u as SANDBOX_RUNTIME, x as executeCredentialedEgressRequest } from "./profile-D9LdwmZi.js";
|
|
10
|
+
import { S as readBlockedReport, _ as NO_REPLY_TOOL_NAME, a as buildCapabilitySections, b as readNoReply, d as readTurnAnswer, g as sanitizeAssistantText, l as REPLY_TOOL_NAME, m as decideReply, n as buildPluginSections, o as buildTurnContextPrompt, s as readPluginContributions, t as buildModeSections, x as REPORT_BLOCKED_TOOL_NAME, y as isLegacyNoReplyMarker } from "./system-prompt-table-YBTHIFlP.js";
|
|
10
11
|
import { t as isMissingVirtualModule } from "./virtual-module-BeKA_EII.js";
|
|
12
|
+
import { i as lookupSlackUserProfile, t as lookupActiveSlackWorkspaceMember } from "./users-CCRAqYb_.js";
|
|
11
13
|
import { r as userCustomizationTextSchema, s as isVisionImageMediaType } from "./user-customization-CvfuY9Eo.js";
|
|
12
|
-
import { a as parseSkillFile, i as openAiPolicyDisablesImplicitInvocation } from "./skills-BCEU41zM.js";
|
|
13
|
-
import { a as toCanonicalInputMessage } from "./conversation-privacy-B1uXn5sf.js";
|
|
14
|
-
import { i as lookupSlackUserProfile, t as lookupActiveSlackWorkspaceMember } from "./users-ByG5RCEJ.js";
|
|
15
14
|
import * as z from "zod";
|
|
16
15
|
import { getCurrentSystemMessage, getSystemMessageText } from "@earendil-works/pi-ai/compat";
|
|
17
16
|
import path from "node:path";
|
|
17
|
+
import { and, asc, desc, eq, inArray, isNotNull, isNull, like, lt, lte, ne, or, sql } from "drizzle-orm";
|
|
18
|
+
import { alias } from "drizzle-orm/pg-core";
|
|
19
|
+
import { actorSchema, agentEventKeys, createEventSource, createLocalSource, createWebSource, destinationSchema, escapeClosingTag, escapeClosingTags, escapeTagText, escapeTagTextAndQuotes, findTag, readTag, renderInlineTag, renderTag, sourceSchema, startsWithTag, tagJson, unescapeClosingTag, unescapeClosingTags } from "@sentry/junior-plugin-api";
|
|
18
20
|
import { isDeepStrictEqual } from "node:util";
|
|
19
21
|
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
20
|
-
import { isRetryableAssistantError, renderSystemMessageUpdate } from "@earendil-works/pi-ai";
|
|
21
|
-
import { actorSchema, agentEventKeys, createEventSource, createLocalSource, createWebSource, destinationSchema, escapeClosingTag, escapeClosingTags, escapeTagText, escapeTagTextAndQuotes, findTag, indentTagLines, readTag, renderInlineTag, renderTag, sourceSchema, startsWithTag, tagJson, unescapeClosingTag, unescapeClosingTags } from "@sentry/junior-plugin-api";
|
|
22
|
-
import { and, asc, desc, eq, inArray, isNull, like, lt, lte, ne, or, sql } from "drizzle-orm";
|
|
23
|
-
import { alias } from "drizzle-orm/pg-core";
|
|
24
22
|
import pLimit from "p-limit";
|
|
23
|
+
import { isRetryableAssistantError, renderSystemMessageUpdate } from "@earendil-works/pi-ai";
|
|
25
24
|
// src/chat/configuration/types.ts
|
|
26
25
|
/** JSON value accepted by Location configuration. */
|
|
27
26
|
const configValueSchema = z.json();
|
|
@@ -388,7 +387,7 @@ function parseOAuthStatePayload(value) {
|
|
|
388
387
|
}
|
|
389
388
|
/** Return the manifest-owned display label for a provider. */
|
|
390
389
|
function formatProviderLabel(provider) {
|
|
391
|
-
const displayName =
|
|
390
|
+
const displayName = getAppContext().catalog.getDisplayName(provider);
|
|
392
391
|
if (!displayName) throw new Error(`Unknown plugin provider display name: "${provider}"`);
|
|
393
392
|
return displayName;
|
|
394
393
|
}
|
|
@@ -460,7 +459,7 @@ async function deliverOAuthAuthorization(request, input) {
|
|
|
460
459
|
}
|
|
461
460
|
/** Initiate an OAuth authorization code flow for a provider and deliver the auth link to the user. */
|
|
462
461
|
async function startOAuthFlow(provider, input) {
|
|
463
|
-
const providerConfig =
|
|
462
|
+
const providerConfig = getAppContext().catalog.getOAuthConfig(provider);
|
|
464
463
|
if (!providerConfig) return {
|
|
465
464
|
ok: false,
|
|
466
465
|
error: `Provider "${provider}" does not support OAuth authorization`
|
|
@@ -684,6 +683,53 @@ function restoreToolActionRejections(messages) {
|
|
|
684
683
|
}
|
|
685
684
|
return priorRejections;
|
|
686
685
|
}
|
|
686
|
+
// src/chat/guardian/request.ts
|
|
687
|
+
/**
|
|
688
|
+
* Build the Guardian request from what core knows about one batch.
|
|
689
|
+
*
|
|
690
|
+
* Code only labels and orders facts here (`facts-from-junior`). It decides
|
|
691
|
+
* who wrote each message from the Run's Source and the author labels of the
|
|
692
|
+
* root Conversation, never from what the text says.
|
|
693
|
+
*/
|
|
694
|
+
/**
|
|
695
|
+
* Whose words the current message of the Run is. An agent's brief passed
|
|
696
|
+
* Guardian when it was sent, so it is the instruction of this Run
|
|
697
|
+
* (`brief-is-instruction`). A person's Source with a system Actor, such as
|
|
698
|
+
* an Event Turn, is an Event.
|
|
699
|
+
*/
|
|
700
|
+
function currentAuthor(context) {
|
|
701
|
+
const author = instructionAuthor(context.source);
|
|
702
|
+
return author === "person" && context.actor.platform === "system" ? "event" : author;
|
|
703
|
+
}
|
|
704
|
+
/**
|
|
705
|
+
* The ordered messages of the work for one batch. Every proposal of a batch
|
|
706
|
+
* has the same context and root Conversation, so the first one is enough.
|
|
707
|
+
* Only the requester's root messages, which core labels `user`, and the
|
|
708
|
+
* current instruction are `instruction`. A gap note stays as context, so a
|
|
709
|
+
* later reply does not read as an answer to a message that is not shown.
|
|
710
|
+
*/
|
|
711
|
+
function guardianMessages(proposal) {
|
|
712
|
+
const { context, rootConversation } = proposal;
|
|
713
|
+
const author = currentAuthor(context);
|
|
714
|
+
const messages = [];
|
|
715
|
+
if (author === "automation") messages.push({
|
|
716
|
+
from: "instruction",
|
|
717
|
+
text: context.userIntent
|
|
718
|
+
});
|
|
719
|
+
if (rootConversation?.truncated) messages.push({
|
|
720
|
+
from: "context",
|
|
721
|
+
text: "[Older messages are not shown.]"
|
|
722
|
+
});
|
|
723
|
+
for (const message of rootConversation?.messages ?? []) messages.push({
|
|
724
|
+
from: message.author === "user" ? "instruction" : message.author === "other person" ? "other_person" : "context",
|
|
725
|
+
text: message.text
|
|
726
|
+
});
|
|
727
|
+
if (!rootConversation?.messages.some((message) => message.author === "user" && message.text === context.userIntent) && author !== "automation" && context.userIntent) messages.push({
|
|
728
|
+
from: author === "event" ? "context" : "instruction",
|
|
729
|
+
text: context.userIntent
|
|
730
|
+
});
|
|
731
|
+
return messages;
|
|
732
|
+
}
|
|
687
733
|
// src/chat/guardian/gate.ts
|
|
688
734
|
const ACTION_CONFIRMATION_INSTRUCTIONS = [
|
|
689
735
|
"The action was not executed because explicit user confirmation is required.",
|
|
@@ -714,9 +760,7 @@ var ToolActionRejectedError = class extends Error {
|
|
|
714
760
|
decision;
|
|
715
761
|
reason;
|
|
716
762
|
reviewedAction;
|
|
717
|
-
riskLevel;
|
|
718
763
|
rule;
|
|
719
|
-
userAuthorization;
|
|
720
764
|
constructor(decision, reason, assessment = {}) {
|
|
721
765
|
const instructions = assessment.instructions ?? (decision === "ask" ? ACTION_CONFIRMATION_INSTRUCTIONS : ACTION_DENIAL_INSTRUCTIONS);
|
|
722
766
|
super(`${instructions}\nReason: ${reason}`);
|
|
@@ -724,9 +768,7 @@ var ToolActionRejectedError = class extends Error {
|
|
|
724
768
|
this.decision = decision;
|
|
725
769
|
this.reason = reason;
|
|
726
770
|
this.reviewedAction = assessment.reviewedAction;
|
|
727
|
-
this.riskLevel = assessment.riskLevel;
|
|
728
771
|
this.rule = assessment.rule;
|
|
729
|
-
this.userAuthorization = assessment.userAuthorization;
|
|
730
772
|
}
|
|
731
773
|
};
|
|
732
774
|
/** Required review could not run, so the action was not executed. */
|
|
@@ -744,14 +786,12 @@ var ToolActionReviewLimitError = class extends Error {
|
|
|
744
786
|
}
|
|
745
787
|
};
|
|
746
788
|
/**
|
|
747
|
-
* True when an `auto` action must enter review.
|
|
748
|
-
*
|
|
749
|
-
*
|
|
750
|
-
*
|
|
751
|
-
* annotations, is unknown risk.
|
|
789
|
+
* True when an `auto` action must enter review. Only the annotations that
|
|
790
|
+
* Junior or plugin code declares on the tool can skip review: read-only and
|
|
791
|
+
* not destructive. Annotations that an MCP server sends reach Guardian only as
|
|
792
|
+
* hints, because a server can mark a write as read-only.
|
|
752
793
|
*/
|
|
753
|
-
function autoActionNeedsReview(
|
|
754
|
-
const annotations = resolved?.annotations ?? tool.annotations;
|
|
794
|
+
function autoActionNeedsReview({ annotations }) {
|
|
755
795
|
return !(annotations?.readOnlyHint === true && annotations.destructiveHint !== true);
|
|
756
796
|
}
|
|
757
797
|
function actionActor(actor) {
|
|
@@ -800,7 +840,7 @@ function assertAuthoritativeContext(context) {
|
|
|
800
840
|
}
|
|
801
841
|
if (context.actor.platform !== "system" || context.actor.name !== credentialActor.name) throw new ToolActionReviewUnavailableError();
|
|
802
842
|
}
|
|
803
|
-
/** Build the bounded wire proposal
|
|
843
|
+
/** Build the bounded wire proposal. Tool metadata is not authority. */
|
|
804
844
|
function buildProposal(toolName, tool, input, resolved, context, priorRejections, rootConversation, script) {
|
|
805
845
|
const credential = actionCredential(context.credentialContext);
|
|
806
846
|
return {
|
|
@@ -880,27 +920,40 @@ function projectedRejection(proposal, decision) {
|
|
|
880
920
|
decision: decision.decision,
|
|
881
921
|
input,
|
|
882
922
|
reason: decision.reason,
|
|
883
|
-
|
|
884
|
-
tool: proposal.tool,
|
|
885
|
-
userAuthorization: decision.userAuthorization
|
|
923
|
+
tool: proposal.tool
|
|
886
924
|
};
|
|
887
925
|
}
|
|
888
|
-
/**
|
|
926
|
+
/** Core tools skip review unless they opt in; plugin tools default `auto`. */
|
|
889
927
|
function mayNeedReview(tool) {
|
|
890
928
|
return tool.approvalMode !== void 0 && tool.approvalMode !== "approve";
|
|
891
929
|
}
|
|
892
|
-
/** Prepare the exact action that Guardian must review, when
|
|
930
|
+
/** Prepare the exact action that Guardian must review, when it must. */
|
|
893
931
|
async function prepareToolActionReview(action, context, priorRejections) {
|
|
894
932
|
const { tool, input } = action;
|
|
895
933
|
if (!mayNeedReview(tool)) return;
|
|
896
934
|
const resolved = await tool.resolveApprovalMetadata?.(input);
|
|
897
|
-
if (tool.approvalMode === "auto" && !autoActionNeedsReview(tool
|
|
935
|
+
if (tool.approvalMode === "auto" && !autoActionNeedsReview(tool)) return;
|
|
898
936
|
assertAuthoritativeContext(context);
|
|
899
|
-
|
|
937
|
+
const proposal = buildProposal(action.toolName, tool, input, resolved, context, priorRejections, await context.rootConversation?.(), action.script);
|
|
938
|
+
return {
|
|
939
|
+
action: {
|
|
940
|
+
tool: proposal.tool.name,
|
|
941
|
+
input,
|
|
942
|
+
effect: "write",
|
|
943
|
+
summary: proposal.tool.proposalDescription ?? proposal.tool.name
|
|
944
|
+
},
|
|
945
|
+
proposal
|
|
946
|
+
};
|
|
947
|
+
}
|
|
948
|
+
/** Most actions of one batch that the gate prepares or records at once. */
|
|
949
|
+
const MAX_CONCURRENT_PREPARATIONS = 4;
|
|
950
|
+
function unavailableStep(error) {
|
|
951
|
+
return {
|
|
952
|
+
kind: "unavailable",
|
|
953
|
+
error: error instanceof ToolActionReviewUnavailableError ? error : new ToolActionReviewUnavailableError({ cause: error })
|
|
954
|
+
};
|
|
900
955
|
}
|
|
901
|
-
/**
|
|
902
|
-
const MAX_CONCURRENT_REVIEWS = 4;
|
|
903
|
-
/** Create the core review path that prepares actions and enforces Guardian decisions. */
|
|
956
|
+
/** Create the review path that prepares actions and enforces decisions. */
|
|
904
957
|
function createToolActionReview(options) {
|
|
905
958
|
const priorRejections = [...options.priorRejections ?? []];
|
|
906
959
|
const pendingRejections = /* @__PURE__ */ new Map();
|
|
@@ -912,38 +965,62 @@ function createToolActionReview(options) {
|
|
|
912
965
|
*/
|
|
913
966
|
const attempts = /* @__PURE__ */ new Map();
|
|
914
967
|
/**
|
|
915
|
-
*
|
|
916
|
-
*
|
|
968
|
+
* Prepare each action, send the proposals of the batch to Guardian at
|
|
969
|
+
* once, and record each decision. Gate state does not change here.
|
|
917
970
|
*/
|
|
918
|
-
const
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
}
|
|
971
|
+
const reviewSteps = async (actions, signal) => {
|
|
972
|
+
const rejections = [...priorRejections];
|
|
973
|
+
const prepared = await mapBounded(actions, async (action) => {
|
|
974
|
+
try {
|
|
975
|
+
return await prepareToolActionReview(action, options.context, rejections) ?? { kind: "skipped" };
|
|
976
|
+
} catch (error) {
|
|
977
|
+
if (signal?.aborted) throw error;
|
|
978
|
+
return unavailableStep(error);
|
|
979
|
+
}
|
|
980
|
+
}, MAX_CONCURRENT_PREPARATIONS);
|
|
981
|
+
const reviews = prepared.filter((entry) => !("kind" in entry));
|
|
982
|
+
let decisions = [];
|
|
983
|
+
let failure;
|
|
984
|
+
if (reviews.length > 0) try {
|
|
985
|
+
decisions = await options.guardian({ proposals: reviews.map((review) => review.proposal) }).review({
|
|
986
|
+
actions: reviews.map((review) => review.action),
|
|
987
|
+
messages: guardianMessages(reviews[0].proposal)
|
|
988
|
+
}, signal ?? new AbortController().signal);
|
|
989
|
+
if (decisions.length !== reviews.length) throw new Error("Guardian must return one Review per action.");
|
|
933
990
|
} catch (error) {
|
|
934
991
|
if (signal?.aborted) throw error;
|
|
992
|
+
failure = error;
|
|
993
|
+
}
|
|
994
|
+
let next = 0;
|
|
995
|
+
const indexes = prepared.map((entry) => "kind" in entry ? void 0 : next++);
|
|
996
|
+
const steps = await mapBounded(prepared, async (entry, index) => {
|
|
997
|
+
if ("kind" in entry) return entry;
|
|
998
|
+
if (failure !== void 0) return unavailableStep(failure);
|
|
999
|
+
const decision = decisions[indexes[index]];
|
|
1000
|
+
try {
|
|
1001
|
+
await options.onDecision({
|
|
1002
|
+
toolCallId: actions[index].toolCallId,
|
|
1003
|
+
toolName: entry.proposal.tool.name,
|
|
1004
|
+
decision
|
|
1005
|
+
});
|
|
1006
|
+
} catch (error) {
|
|
1007
|
+
return unavailableStep(error);
|
|
1008
|
+
}
|
|
935
1009
|
return {
|
|
936
|
-
kind: "
|
|
937
|
-
|
|
1010
|
+
kind: "reviewed",
|
|
1011
|
+
decision,
|
|
1012
|
+
proposal: entry.proposal
|
|
938
1013
|
};
|
|
939
|
-
}
|
|
1014
|
+
}, MAX_CONCURRENT_PREPARATIONS);
|
|
1015
|
+
signal?.throwIfAborted();
|
|
1016
|
+
return steps;
|
|
940
1017
|
};
|
|
941
1018
|
/**
|
|
942
1019
|
* Count each attempt in the batch once, in batch order. An attempt with a
|
|
943
1020
|
* rejection adds one to the count from before the attempt, also when it
|
|
944
1021
|
* has allowed actions or spans several batches. An attempt with only
|
|
945
|
-
* allowed actions resets the count. Skipped and unavailable actions do
|
|
946
|
-
* change it. Return the attempt state of each action.
|
|
1022
|
+
* allowed actions resets the count. Skipped and unavailable actions do
|
|
1023
|
+
* not change it. Return the attempt state of each action.
|
|
947
1024
|
*/
|
|
948
1025
|
const countAttempts = (actions, steps) => {
|
|
949
1026
|
const states = actions.map((action) => {
|
|
@@ -972,9 +1049,7 @@ function createToolActionReview(options) {
|
|
|
972
1049
|
state.exhausted = true;
|
|
973
1050
|
logException(new ToolActionReviewLimitError(), "guardian.action_review.exhausted", {
|
|
974
1051
|
"app.guardian.decision": step.decision.decision,
|
|
975
|
-
"app.guardian.
|
|
976
|
-
...step.decision.rule ? { "app.guardian.rule": step.decision.rule } : void 0,
|
|
977
|
-
"app.guardian.user_consent": step.decision.userAuthorization,
|
|
1052
|
+
"app.guardian.rule": step.decision.rule,
|
|
978
1053
|
"gen_ai.tool.name": step.proposal.tool.name,
|
|
979
1054
|
"gen_ai.tool.call.id": actions[index].toolCallId
|
|
980
1055
|
});
|
|
@@ -1002,26 +1077,21 @@ function createToolActionReview(options) {
|
|
|
1002
1077
|
decision: decision.decision,
|
|
1003
1078
|
priorRejection: reviewedAction,
|
|
1004
1079
|
reason: reviewedAction.reason,
|
|
1005
|
-
riskLevel: decision.riskLevel,
|
|
1006
|
-
userAuthorization: decision.userAuthorization,
|
|
1007
1080
|
version: 1
|
|
1008
1081
|
});
|
|
1009
1082
|
return {
|
|
1010
1083
|
allowed: false,
|
|
1011
1084
|
error: new ToolActionRejectedError(decision.decision, decision.reason, {
|
|
1012
1085
|
instructions: rejectionInstructions(decision.decision, { exhausted }),
|
|
1013
|
-
riskLevel: decision.riskLevel,
|
|
1014
1086
|
reviewedAction,
|
|
1015
|
-
rule: decision.rule
|
|
1016
|
-
userAuthorization: decision.userAuthorization
|
|
1087
|
+
rule: decision.rule
|
|
1017
1088
|
})
|
|
1018
1089
|
};
|
|
1019
1090
|
};
|
|
1020
1091
|
return {
|
|
1021
1092
|
async review(actions, signal) {
|
|
1022
1093
|
return await withSpan("guardian.action_review", "guardian.action_review", {}, async () => {
|
|
1023
|
-
const
|
|
1024
|
-
const steps = await mapBounded(actions, (action) => reviewStep(action, rejections, signal), MAX_CONCURRENT_REVIEWS);
|
|
1094
|
+
const steps = await reviewSteps(actions, signal);
|
|
1025
1095
|
const states = countAttempts(actions, steps);
|
|
1026
1096
|
return new Map(actions.map((action, index) => [action.toolCallId, settle(action.toolCallId, steps[index], states[index].exhausted)]));
|
|
1027
1097
|
}, { "app.guardian.batch.size": actions.length });
|
|
@@ -1194,6 +1264,10 @@ function buildGatedTurnResult(input, answer) {
|
|
|
1194
1264
|
};
|
|
1195
1265
|
}
|
|
1196
1266
|
// src/chat/services/turn-failure-response.ts
|
|
1267
|
+
/** Build the static user-facing response for a failed turn. */
|
|
1268
|
+
function buildTurnFailureResponse(eventId) {
|
|
1269
|
+
return `I ran into an internal error while processing that. Reference: ${formatSentryEventReference(eventId)}.`;
|
|
1270
|
+
}
|
|
1197
1271
|
/** Require captured turn failures to carry a real Sentry event reference. */
|
|
1198
1272
|
function requireTurnFailureEventId(eventId, eventName) {
|
|
1199
1273
|
if (!eventId) throw new Error(`Sentry did not return an event ID for ${eventName}`);
|
|
@@ -2539,7 +2613,7 @@ function createPluginAuthOrchestration(input) {
|
|
|
2539
2613
|
let pendingPause;
|
|
2540
2614
|
const startAuthorizationPause = async (provider, options) => {
|
|
2541
2615
|
if (pendingPause) throw pendingPause;
|
|
2542
|
-
if (!input.actorId || !
|
|
2616
|
+
if (!input.actorId || !getAppContext().catalog.getOAuthConfig(provider)) throw new Error(`Cannot start plugin authorization for ${provider}`);
|
|
2543
2617
|
if (input.interactiveAuthEnabled === false) throw new AuthorizationFlowDisabledError("plugin", provider);
|
|
2544
2618
|
const recordPendingAuth = input.sessionId ? input.recordPendingAuth : void 0;
|
|
2545
2619
|
if (input.sessionId && !recordPendingAuth) throw new Error(`Missing pending auth recorder for plugin authorization pause "${provider}"`);
|
|
@@ -2611,7 +2685,7 @@ function createPluginAuthOrchestration(input) {
|
|
|
2611
2685
|
if (input.interactiveAuthEnabled === false) throw new AuthorizationFlowDisabledError("plugin", provider);
|
|
2612
2686
|
throw new PluginCredentialFailureError(provider, signal.message ?? `${formatProviderLabel(provider)} credentials are required. Please connect your ${formatProviderLabel(provider)} account and try again.`);
|
|
2613
2687
|
}
|
|
2614
|
-
if (!
|
|
2688
|
+
if (!getAppContext().catalog.getOAuthConfig(authorization.provider)) throw new PluginCredentialFailureError(provider, signal.message ?? `${formatProviderLabel(provider)} credentials are required but the provider is not configured for OAuth.`);
|
|
2615
2689
|
await startAuthorizationPause(authorization.provider, authorization.scope ? { scope: authorization.scope } : void 0);
|
|
2616
2690
|
},
|
|
2617
2691
|
getPendingPause: () => pendingPause
|
|
@@ -2630,7 +2704,7 @@ function credentialContextForPluginEgress(credentialContext, source) {
|
|
|
2630
2704
|
/** Create host-owned provider egress for plugin runtime tools. */
|
|
2631
2705
|
function createPluginEgress(deps) {
|
|
2632
2706
|
const credentialContext = deps.credentialContext ? credentialContextForPluginEgress(deps.credentialContext, deps.credentialAuditSource) : void 0;
|
|
2633
|
-
|
|
2707
|
+
const egress = { async fetch(input) {
|
|
2634
2708
|
const operation = input.operation.trim();
|
|
2635
2709
|
if (!operation) throw new Error("Plugin egress operation is required");
|
|
2636
2710
|
if (!credentialContext) throw new PluginCredentialFailureError(input.provider, `Cannot issue ${input.provider} credentials without a credential context.`);
|
|
@@ -2653,6 +2727,25 @@ function createPluginEgress(deps) {
|
|
|
2653
2727
|
if (result.authRequired) await deps.pluginAuth.handleAuthRequired(result.authRequired);
|
|
2654
2728
|
return result.response;
|
|
2655
2729
|
} };
|
|
2730
|
+
const { httpCache } = deps;
|
|
2731
|
+
if (!httpCache || !deps.credentialContext) return egress;
|
|
2732
|
+
const scope = `egress:${JSON.stringify([deps.credentialContext, deps.userOAuthOnly ? "user-oauth" : "any"])}`;
|
|
2733
|
+
return { async fetch(input) {
|
|
2734
|
+
if (input.request.method !== "GET") return await egress.fetch(input);
|
|
2735
|
+
return await readThroughHttpCache({
|
|
2736
|
+
...httpCache,
|
|
2737
|
+
request: input.request,
|
|
2738
|
+
scope,
|
|
2739
|
+
send: async (headers) => {
|
|
2740
|
+
const request = new Request(input.request);
|
|
2741
|
+
for (const [name, value] of Object.entries(headers)) request.headers.set(name, value);
|
|
2742
|
+
return await egress.fetch({
|
|
2743
|
+
...input,
|
|
2744
|
+
request
|
|
2745
|
+
});
|
|
2746
|
+
}
|
|
2747
|
+
});
|
|
2748
|
+
} };
|
|
2656
2749
|
}
|
|
2657
2750
|
// src/chat/plugins/conversation-title-context.ts
|
|
2658
2751
|
const TITLE_CONTEXT_TIMEOUT_MS = 5e3;
|
|
@@ -2748,51 +2841,8 @@ function getAgentContextInputLimitTokens(modelId) {
|
|
|
2748
2841
|
function getConversationContextCompactionTriggerTokens() {
|
|
2749
2842
|
return calculateContextCompactionTriggerTokens(getModelContextBudget(botConfig.fastModelId));
|
|
2750
2843
|
}
|
|
2751
|
-
// src/chat/events/actor.ts
|
|
2752
|
-
/**
|
|
2753
|
-
* System author ID stamped on event mailbox messages.
|
|
2754
|
-
*
|
|
2755
|
-
* Keep this stable so conversation history can recognize the same system input
|
|
2756
|
-
* for event Turns.
|
|
2757
|
-
*
|
|
2758
|
-
* TODO(dcramer): Delete this ID after resumes read event Source.kind
|
|
2759
|
-
* from the Turn checkpoint instead of Message author data.
|
|
2760
|
-
*/
|
|
2761
|
-
const EVENT_AUTHOR_ID = "UJRNEVENT";
|
|
2762
|
-
/** System Message author for event input. */
|
|
2763
|
-
const EVENT_MESSAGE_AUTHOR = {
|
|
2764
|
-
fullName: "System event",
|
|
2765
|
-
isBot: true,
|
|
2766
|
-
userId: EVENT_AUTHOR_ID,
|
|
2767
|
-
userName: "junior-event"
|
|
2768
|
-
};
|
|
2769
|
-
/** System execution actor for every event turn. */
|
|
2770
|
-
const EVENT_SYSTEM_ACTOR = {
|
|
2771
|
-
platform: "system",
|
|
2772
|
-
name: "event"
|
|
2773
|
-
};
|
|
2774
|
-
/**
|
|
2775
|
-
* Whether a saved Message started a event Turn.
|
|
2776
|
-
*
|
|
2777
|
-
* TODO(dcramer): Delete this marker check after deployed Turn cursors all store
|
|
2778
|
-
* Source and Actor. `eventType` only supports saved synthetic Slack input.
|
|
2779
|
-
*/
|
|
2780
|
-
function isEventConversationMessage(message) {
|
|
2781
|
-
return Boolean(message.meta?.eventType) || isEventAuthorId(message.author?.userId);
|
|
2782
|
-
}
|
|
2783
|
-
/** Author id of an Event Message by a listed bot, which has no Identity. */
|
|
2784
|
-
function eventBotAuthorId(provider, handle) {
|
|
2785
|
-
return `${EVENT_AUTHOR_ID}:${provider}:${handle.toLowerCase()}`;
|
|
2786
|
-
}
|
|
2787
|
-
/** Whether an author id belongs to an Event Message, system or listed bot. */
|
|
2788
|
-
function isEventAuthorId(id) {
|
|
2789
|
-
return id === "UJRNEVENT" || Boolean(id?.startsWith(`UJRNEVENT:`));
|
|
2790
|
-
}
|
|
2791
2844
|
// src/chat/services/conversation-memory.ts
|
|
2792
2845
|
const CONTEXT_MIN_LIVE_MESSAGES = 12;
|
|
2793
|
-
const CONTEXT_MAX_MESSAGE_CHARS = 3200;
|
|
2794
|
-
const THREAD_CONTEXT_MAX_CHARS = 6e4;
|
|
2795
|
-
const THREAD_CONTEXT_OMITTED_NOTE = "Older Messages of this thread are not shown. Find them with a searchConversationEvents query, then read them with readConversationEvent.";
|
|
2796
2846
|
const SLACK_USER_ID_DISPLAY_PATTERN = /^[UW][A-Z0-9]{5,}$/;
|
|
2797
2847
|
/** Normalize message boundaries without changing transcript formatting. */
|
|
2798
2848
|
function normalizeConversationText(text) {
|
|
@@ -2806,16 +2856,21 @@ function buildImageContextSuffix(message, conversation) {
|
|
|
2806
2856
|
if (summaries.length === 0) return "";
|
|
2807
2857
|
return ` [image context: ${escapeTagTextAndQuotes(summaries.join(" | "))}]`;
|
|
2808
2858
|
}
|
|
2809
|
-
|
|
2859
|
+
/**
|
|
2860
|
+
* Render one Message as a single escaped transcript line. `text` replaces the
|
|
2861
|
+
* Message text, such as when a caller cuts it to a budget.
|
|
2862
|
+
*/
|
|
2863
|
+
function renderConversationMessageLine(message, conversation, text = message.text) {
|
|
2810
2864
|
const displayName = escapeTagTextAndQuotes(conversationAuthorDisplayName(message));
|
|
2811
|
-
const
|
|
2865
|
+
const lineText = escapeTagTextAndQuotes(text.replace(/\s+/g, " "));
|
|
2812
2866
|
const markers = [];
|
|
2813
2867
|
if (message.meta?.replied === false) markers.push(escapeTagTextAndQuotes(`assistant skipped: ${message.meta?.skippedReason ?? "no-reply route"}`));
|
|
2814
2868
|
if (message.meta?.explicitMention) markers.push("explicit mention");
|
|
2815
2869
|
const markerSuffix = markers.length > 0 ? ` (${markers.join("; ")})` : "";
|
|
2816
2870
|
const imageContext = buildImageContextSuffix(message, conversation);
|
|
2817
|
-
return `[${message.role}] ${displayName}: ${
|
|
2871
|
+
return `[${message.role}] ${displayName}: ${lineText}${imageContext}${markerSuffix}`;
|
|
2818
2872
|
}
|
|
2873
|
+
/** Return the name to show for a Message author, never a raw Slack id. */
|
|
2819
2874
|
function conversationAuthorDisplayName(message) {
|
|
2820
2875
|
const author = message.author;
|
|
2821
2876
|
const fullName = authorDisplayField(author?.fullName, author?.userId);
|
|
@@ -2891,64 +2946,12 @@ function markConversationMessage(conversation, messageId, patch) {
|
|
|
2891
2946
|
}
|
|
2892
2947
|
};
|
|
2893
2948
|
}
|
|
2894
|
-
function isTakeOrDismissOnly(message) {
|
|
2895
|
-
const changes = message.meta?.reviewItemChanges;
|
|
2896
|
-
return Boolean(changes?.length && changes.every((change) => change.kind === "taken" || change.kind === "dismissed"));
|
|
2897
|
-
}
|
|
2898
|
-
function renderThreadContextMessage(message, conversation, index) {
|
|
2899
|
-
return indentTagLines(renderTag("message", {
|
|
2900
|
-
index,
|
|
2901
|
-
sent_at: new Date(message.createdAtMs).toISOString(),
|
|
2902
|
-
role: message.role,
|
|
2903
|
-
...authorAttrs({
|
|
2904
|
-
authorId: message.author?.userId,
|
|
2905
|
-
authorName: conversationAuthorDisplayName(message)
|
|
2906
|
-
}),
|
|
2907
|
-
slack_ts: message.meta?.slackTs
|
|
2908
|
-
}, [renderConversationMessageLine(message, conversation)]), " ");
|
|
2909
|
-
}
|
|
2910
|
-
function isUntaggedThreadMessage(message) {
|
|
2911
|
-
return message.role === "user" && !message.meta?.explicitMention && !isEventConversationMessage(message);
|
|
2912
|
-
}
|
|
2913
2949
|
/** Return the highest saved Message seq, the thread context cursor of a Turn. */
|
|
2914
2950
|
function latestConversationMessageSeq(conversation) {
|
|
2915
2951
|
let latest;
|
|
2916
2952
|
for (const message of conversation.messages) if (message.seq !== void 0 && (latest ?? -1) < message.seq) latest = message.seq;
|
|
2917
2953
|
return latest;
|
|
2918
2954
|
}
|
|
2919
|
-
/**
|
|
2920
|
-
* Render the thread Messages that this Turn needs as one evidence-only block.
|
|
2921
|
-
*
|
|
2922
|
-
* With agent history, earlier Turns already hold their thread context, Turn
|
|
2923
|
-
* input, and replies. So only untagged Messages saved after the cursor of the
|
|
2924
|
-
* previous Turn are new. Without history, show the latest Messages. Both keep
|
|
2925
|
-
* the newest Messages under one hard size cap, so the block cannot grow with
|
|
2926
|
-
* the thread.
|
|
2927
|
-
*/
|
|
2928
|
-
function buildConversationContext(conversation, options = {}) {
|
|
2929
|
-
const { history } = options;
|
|
2930
|
-
const candidates = conversation.messages.filter((entry) => !options.excludeMessageIds?.includes(entry.id) && !isTakeOrDismissOnly(entry) && (!history || isUntaggedThreadMessage(entry) && (history.afterSeq === void 0 || entry.seq === void 0 || entry.seq > history.afterSeq)));
|
|
2931
|
-
let first = candidates.length;
|
|
2932
|
-
let chars = 0;
|
|
2933
|
-
while (first > 0) {
|
|
2934
|
-
const size = renderThreadContextMessage(candidates[first - 1], conversation, first).length;
|
|
2935
|
-
if (chars + size > THREAD_CONTEXT_MAX_CHARS) break;
|
|
2936
|
-
chars += size;
|
|
2937
|
-
first -= 1;
|
|
2938
|
-
}
|
|
2939
|
-
const shown = candidates.slice(first).map((message, index) => renderThreadContextMessage(message, conversation, index + 1));
|
|
2940
|
-
const counts = {
|
|
2941
|
-
shownMessages: shown.length,
|
|
2942
|
-
omittedMessages: candidates.length - shown.length
|
|
2943
|
-
};
|
|
2944
|
-
if (shown.length === 0) return counts;
|
|
2945
|
-
const lines = [renderThreadContext(shown)];
|
|
2946
|
-
if (shown.length < candidates.length || !history && conversation.historyFromSeq !== void 0) lines.push(THREAD_CONTEXT_OMITTED_NOTE);
|
|
2947
|
-
return {
|
|
2948
|
-
...counts,
|
|
2949
|
-
text: lines.join("\n")
|
|
2950
|
-
};
|
|
2951
|
-
}
|
|
2952
2955
|
/** Return the earliest human-authored message known for a thread. */
|
|
2953
2956
|
function getThreadTitleSourceMessage(conversation) {
|
|
2954
2957
|
let firstMessage;
|
|
@@ -3714,8 +3717,8 @@ async function recordGuardianActionReviewed(args) {
|
|
|
3714
3717
|
toolName: args.toolName,
|
|
3715
3718
|
...args.costUsd !== void 0 ? { costUsd: args.costUsd } : void 0,
|
|
3716
3719
|
decision: args.decision,
|
|
3717
|
-
|
|
3718
|
-
|
|
3720
|
+
...args.rule ? { rule: args.rule } : void 0,
|
|
3721
|
+
...args.reason ? { reason: args.reason } : void 0
|
|
3719
3722
|
},
|
|
3720
3723
|
createdAtMs: Date.now()
|
|
3721
3724
|
}]);
|
|
@@ -4262,45 +4265,9 @@ async function buildDeploymentSystemPrompt(platform, mode) {
|
|
|
4262
4265
|
})).map((section) => section.text).join("\n\n");
|
|
4263
4266
|
}
|
|
4264
4267
|
// src/chat/experimental.ts
|
|
4265
|
-
/**
|
|
4266
|
-
* Known unstable product features that must be opted into explicitly.
|
|
4267
|
-
* Add new keys here as features graduate from private experiments; remove them
|
|
4268
|
-
* once they become stable defaults.
|
|
4269
|
-
*/
|
|
4270
|
-
const EXPERIMENTAL_FEATURES = [
|
|
4271
|
-
"operator-tools",
|
|
4272
|
-
"passive-routing",
|
|
4273
|
-
"user-customization"
|
|
4274
|
-
];
|
|
4275
|
-
const EXPERIMENTAL_FEATURE_SET = new Set(EXPERIMENTAL_FEATURES);
|
|
4276
|
-
let configuredExperimental = {};
|
|
4277
|
-
function isExperimentalFeature(value) {
|
|
4278
|
-
return EXPERIMENTAL_FEATURE_SET.has(value);
|
|
4279
|
-
}
|
|
4280
|
-
/** Replace app-level experimental opt-ins and return the previous setting. */
|
|
4281
|
-
function setExperimentalFeatures(config) {
|
|
4282
|
-
const previous = { ...configuredExperimental };
|
|
4283
|
-
if (config === void 0) {
|
|
4284
|
-
configuredExperimental = {};
|
|
4285
|
-
return previous;
|
|
4286
|
-
}
|
|
4287
|
-
const next = {};
|
|
4288
|
-
for (const [rawName, enabled] of Object.entries(config)) {
|
|
4289
|
-
if (enabled === void 0) continue;
|
|
4290
|
-
if (typeof enabled !== "boolean") throw new Error(`experimental.${rawName} must be a boolean when provided`);
|
|
4291
|
-
if (!isExperimentalFeature(rawName)) throw new Error(`experimental.${rawName} is not a known experimental feature. Known features: ${EXPERIMENTAL_FEATURES.join(", ")}`);
|
|
4292
|
-
next[rawName] = enabled;
|
|
4293
|
-
}
|
|
4294
|
-
configuredExperimental = next;
|
|
4295
|
-
return previous;
|
|
4296
|
-
}
|
|
4297
|
-
/** Return a copy of the app-level experimental opt-ins configured by createApp(). */
|
|
4298
|
-
function getExperimentalFeatures() {
|
|
4299
|
-
return { ...configuredExperimental };
|
|
4300
|
-
}
|
|
4301
4268
|
/** Return whether one experimental feature is enabled via createApp({ experimental }). */
|
|
4302
4269
|
function isExperimentalFeatureEnabled(feature) {
|
|
4303
|
-
return
|
|
4270
|
+
return getChatConfig().experimental[feature] === true;
|
|
4304
4271
|
}
|
|
4305
4272
|
// src/chat/sandbox/snapshot/store.ts
|
|
4306
4273
|
function builderNames(rows) {
|
|
@@ -4666,6 +4633,97 @@ function buildDeterministicTurnId(messageId) {
|
|
|
4666
4633
|
function buildDeterministicAssistantMessageId(turnId) {
|
|
4667
4634
|
return `${turnId}:assistant:1`;
|
|
4668
4635
|
}
|
|
4636
|
+
// src/chat/runtime/turn.ts
|
|
4637
|
+
/** Classified Slack turn failure carrying the owning Sentry capture outward. */
|
|
4638
|
+
var ConversationTurnBoundaryError = class extends Error {
|
|
4639
|
+
eventId;
|
|
4640
|
+
failureCode;
|
|
4641
|
+
constructor(args) {
|
|
4642
|
+
super(args.cause instanceof Error ? args.cause.message : String(args.cause), { cause: args.cause });
|
|
4643
|
+
this.name = "ConversationTurnBoundaryError";
|
|
4644
|
+
this.eventId = args.eventId;
|
|
4645
|
+
this.failureCode = args.failureCode;
|
|
4646
|
+
}
|
|
4647
|
+
};
|
|
4648
|
+
/** Return a classified Slack boundary failure without erasing its cause. */
|
|
4649
|
+
function getConversationTurnBoundaryError(error) {
|
|
4650
|
+
return error instanceof ConversationTurnBoundaryError ? error : void 0;
|
|
4651
|
+
}
|
|
4652
|
+
/**
|
|
4653
|
+
* Queue-worker yield routing: respond.ts returns a suspended AgentRunOutcome
|
|
4654
|
+
* and the Slack executor raises this at the worker boundary so the lease owner
|
|
4655
|
+
* requeues the conversation.
|
|
4656
|
+
*/
|
|
4657
|
+
var CooperativeTurnYieldError = class extends Error {
|
|
4658
|
+
code = "cooperative_turn_yield";
|
|
4659
|
+
constructor(message = "Agent turn yielded at a safe boundary") {
|
|
4660
|
+
super(message);
|
|
4661
|
+
this.name = "CooperativeTurnYieldError";
|
|
4662
|
+
}
|
|
4663
|
+
};
|
|
4664
|
+
function isCooperativeTurnYieldError(error) {
|
|
4665
|
+
return error instanceof CooperativeTurnYieldError;
|
|
4666
|
+
}
|
|
4667
|
+
/** Error indicating durable turn input could not be committed by the worker owner. */
|
|
4668
|
+
var TurnInputCommitLostError = class extends Error {
|
|
4669
|
+
code = "turn_input_commit_lost";
|
|
4670
|
+
constructor(message = "Turn input commit lost its durable owner") {
|
|
4671
|
+
super(message);
|
|
4672
|
+
this.name = "TurnInputCommitLostError";
|
|
4673
|
+
}
|
|
4674
|
+
};
|
|
4675
|
+
/** Return whether an error means the durable worker lost input ownership. */
|
|
4676
|
+
function isTurnInputCommitLostError(error) {
|
|
4677
|
+
return error instanceof TurnInputCommitLostError;
|
|
4678
|
+
}
|
|
4679
|
+
/** Error indicating durable turn input should stay pending for a later worker. */
|
|
4680
|
+
var TurnInputDeferredError = class extends Error {
|
|
4681
|
+
code = "turn_input_deferred";
|
|
4682
|
+
constructor(message = "Turn input is deferred until the active resume ends") {
|
|
4683
|
+
super(message);
|
|
4684
|
+
this.name = "TurnInputDeferredError";
|
|
4685
|
+
}
|
|
4686
|
+
};
|
|
4687
|
+
/** Return whether an error means the durable worker should redeliver input later. */
|
|
4688
|
+
function isTurnInputDeferredError(error) {
|
|
4689
|
+
return error instanceof TurnInputDeferredError;
|
|
4690
|
+
}
|
|
4691
|
+
/** Mark a turn as the active turn in conversation state. */
|
|
4692
|
+
function startActiveTurn(args) {
|
|
4693
|
+
args.conversation.processing.activeTurnId = args.nextTurnId;
|
|
4694
|
+
}
|
|
4695
|
+
function clearActiveTurn(conversation, sessionId) {
|
|
4696
|
+
if (!sessionId || conversation.processing.activeTurnId === sessionId) conversation.processing.activeTurnId = void 0;
|
|
4697
|
+
}
|
|
4698
|
+
/**
|
|
4699
|
+
* Close the active turn without marking a Pi session reusable for future
|
|
4700
|
+
* history. Use this for auth handoffs and recovery replies that end the live
|
|
4701
|
+
* turn but do not produce a completed Pi session.
|
|
4702
|
+
*/
|
|
4703
|
+
function markTurnClosed(args) {
|
|
4704
|
+
clearActiveTurn(args.conversation, args.sessionId);
|
|
4705
|
+
args.conversation.processing.lastCompletedAtMs = args.nowMs;
|
|
4706
|
+
}
|
|
4707
|
+
/**
|
|
4708
|
+
* Mark a turn as completed after its assistant output has been handled.
|
|
4709
|
+
*/
|
|
4710
|
+
function markTurnCompleted(args) {
|
|
4711
|
+
clearActiveTurn(args.conversation, args.sessionId);
|
|
4712
|
+
args.conversation.processing.lastCompletedAtMs = args.nowMs;
|
|
4713
|
+
}
|
|
4714
|
+
/**
|
|
4715
|
+
* Mark a turn as failed when execution or final user-visible reply delivery
|
|
4716
|
+
* cannot be completed. If `sessionId` is provided, `activeTurnId` is only
|
|
4717
|
+
* cleared when it still matches the failing turn.
|
|
4718
|
+
*/
|
|
4719
|
+
function markTurnFailed(args) {
|
|
4720
|
+
clearActiveTurn(args.conversation, args.sessionId);
|
|
4721
|
+
args.conversation.processing.lastCompletedAtMs = args.nowMs;
|
|
4722
|
+
args.markConversationMessage(args.conversation, args.userMessageId, {
|
|
4723
|
+
replied: false,
|
|
4724
|
+
skippedReason: "reply failed"
|
|
4725
|
+
});
|
|
4726
|
+
}
|
|
4669
4727
|
// src/chat/plugins/prompt-history-messages.ts
|
|
4670
4728
|
function textParts(message) {
|
|
4671
4729
|
if (!("role" in message) || message.role !== "user") return [];
|
|
@@ -5411,1184 +5469,1359 @@ async function assemblePrompt(args) {
|
|
|
5411
5469
|
userContentParts
|
|
5412
5470
|
};
|
|
5413
5471
|
}
|
|
5414
|
-
// src/chat/
|
|
5472
|
+
// src/chat/conversations/thread-context.ts
|
|
5473
|
+
const CURSOR_TURN_LOOKBACK = 10;
|
|
5474
|
+
/**
|
|
5475
|
+
* Return the Message seq that the latest other finished Turn covered. A failed
|
|
5476
|
+
* or cancelled Turn may not have its prompt in agent history, so its cursor
|
|
5477
|
+
* does not count. Showing a Message again is safe; skipping one that the model
|
|
5478
|
+
* never saw is not.
|
|
5479
|
+
*/
|
|
5480
|
+
async function loadThreadContextCursor(args) {
|
|
5481
|
+
const store = getConversationEventStore();
|
|
5482
|
+
const [started, completed] = await Promise.all([store.query(args.conversationId, {
|
|
5483
|
+
limit: CURSOR_TURN_LOOKBACK,
|
|
5484
|
+
types: ["turn_started"]
|
|
5485
|
+
}), store.query(args.conversationId, {
|
|
5486
|
+
limit: CURSOR_TURN_LOOKBACK,
|
|
5487
|
+
types: ["turn_completed"]
|
|
5488
|
+
})]);
|
|
5489
|
+
const finished = new Set(completed.events.flatMap((event) => event.data.type === "turn_completed" && event.data.outcome !== "cancelled" ? [event.data.turnId] : []));
|
|
5490
|
+
const previous = [...started.events].reverse().find((event) => event.data.type === "turn_started" && event.data.turnId !== args.turnId && finished.has(event.data.turnId));
|
|
5491
|
+
return previous?.data.type === "turn_started" ? previous.data.threadContextThroughSeq : void 0;
|
|
5492
|
+
}
|
|
5493
|
+
/**
|
|
5494
|
+
* Return the oldest cursor of the Turns that the cursor lookup reads. Messages
|
|
5495
|
+
* after it may still be in the thread context delta of the next Turn, also
|
|
5496
|
+
* when the latest Turns failed or the next Turn retries.
|
|
5497
|
+
*/
|
|
5498
|
+
async function loadThreadContextTrimFloor(conversationId) {
|
|
5499
|
+
const cursors = (await getConversationEventStore().query(conversationId, {
|
|
5500
|
+
limit: CURSOR_TURN_LOOKBACK,
|
|
5501
|
+
types: ["turn_started"]
|
|
5502
|
+
})).events.flatMap((event) => event.data.type === "turn_started" && event.data.threadContextThroughSeq !== void 0 ? [event.data.threadContextThroughSeq] : []);
|
|
5503
|
+
return cursors.length > 0 ? Math.min(...cursors) : void 0;
|
|
5504
|
+
}
|
|
5505
|
+
// src/chat/conversations/held-input.ts
|
|
5506
|
+
/** Skip reason on the Message that saves input a stopped Conversation holds. */
|
|
5507
|
+
const STOPPED_CONVERSATION_SKIP_REASON = "stopped conversation";
|
|
5508
|
+
/** Return whether a Message saves input that a stopped Conversation held. */
|
|
5509
|
+
function isHeldInputMessage(message) {
|
|
5510
|
+
return message.meta?.skippedReason === STOPPED_CONVERSATION_SKIP_REASON;
|
|
5511
|
+
}
|
|
5415
5512
|
/**
|
|
5416
|
-
*
|
|
5417
|
-
*
|
|
5418
|
-
*
|
|
5419
|
-
* model never reads status prose. It repeats the question, then one line for
|
|
5420
|
-
* each answered field. `input-tags.ts` lists the input tags.
|
|
5513
|
+
* Put the input that a stopped Conversation held since the previous Turn
|
|
5514
|
+
* before the inputs of this Turn, so the Turn gets it as Turn input. The
|
|
5515
|
+
* cursor is read only when the Conversation holds input.
|
|
5421
5516
|
*/
|
|
5422
|
-
|
|
5423
|
-
|
|
5424
|
-
|
|
5425
|
-
|
|
5426
|
-
|
|
5427
|
-
function renderInboxItemAnswer(item) {
|
|
5428
|
-
const request = inboxItemQuestion(item.request);
|
|
5429
|
-
if (!request || !item.answer) return void 0;
|
|
5430
|
-
const question = request.question.trim();
|
|
5431
|
-
const requestText = typedAnswerText(request, item.answer);
|
|
5432
|
-
return {
|
|
5517
|
+
async function withHeldInput(args, instruction) {
|
|
5518
|
+
const held = args.conversation.messages.filter(isHeldInputMessage);
|
|
5519
|
+
if (held.length === 0) return instruction;
|
|
5520
|
+
const afterSeq = await loadThreadContextCursor(args);
|
|
5521
|
+
const inputs = held.filter((message) => afterSeq === void 0 || message.seq === void 0 || message.seq > afterSeq).map((message) => ({
|
|
5433
5522
|
kind: "runtime",
|
|
5434
|
-
text:
|
|
5435
|
-
|
|
5436
|
-
|
|
5523
|
+
text: message.text
|
|
5524
|
+
}));
|
|
5525
|
+
if (inputs.length === 0) return instruction;
|
|
5526
|
+
return instructionForInputs([...inputs, ...instruction.inputs ?? [{
|
|
5527
|
+
kind: "person",
|
|
5528
|
+
text: instruction.text
|
|
5529
|
+
}]]);
|
|
5437
5530
|
}
|
|
5531
|
+
// src/chat/events/workspace.ts
|
|
5532
|
+
const teamIdsByToken = /* @__PURE__ */ new Map();
|
|
5438
5533
|
/**
|
|
5439
|
-
*
|
|
5440
|
-
*
|
|
5441
|
-
*
|
|
5442
|
-
*
|
|
5534
|
+
* Resolve the single-bot Slack team id for event-automation indexing, Event
|
|
5535
|
+
* people mentions, and author trust.
|
|
5536
|
+
*
|
|
5537
|
+
* Watch matching does not use this. Event automations still key by
|
|
5538
|
+
* destination team until that store is conversation-owned. System Events are
|
|
5539
|
+
* not gated on Slack. Without a Slack bot, only a listed Event author is
|
|
5540
|
+
* trusted.
|
|
5443
5541
|
*/
|
|
5444
|
-
async function
|
|
5445
|
-
|
|
5446
|
-
|
|
5447
|
-
|
|
5542
|
+
async function resolveBotSlackTeamId() {
|
|
5543
|
+
const token = getSlackBotToken();
|
|
5544
|
+
if (!token) return void 0;
|
|
5545
|
+
let pending = teamIdsByToken.get(token);
|
|
5546
|
+
if (!pending) {
|
|
5547
|
+
pending = getSlackClient().auth.test().then((result) => {
|
|
5548
|
+
const teamId = result.team_id?.trim();
|
|
5549
|
+
if (!teamId) throw new Error("Slack auth.test did not return a team id");
|
|
5550
|
+
return teamId;
|
|
5551
|
+
});
|
|
5552
|
+
teamIdsByToken.set(token, pending);
|
|
5553
|
+
pending.catch(() => teamIdsByToken.delete(token));
|
|
5554
|
+
}
|
|
5555
|
+
return await pending;
|
|
5448
5556
|
}
|
|
5557
|
+
// src/chat/identities/trust.ts
|
|
5558
|
+
const emailSchema = z.string().trim().toLowerCase().pipe(z.email());
|
|
5449
5559
|
/**
|
|
5450
|
-
*
|
|
5451
|
-
*
|
|
5452
|
-
*
|
|
5453
|
-
* in `<current-instruction>`.
|
|
5560
|
+
* Parse a value that must be an email, such as a sign-in or a verified email
|
|
5561
|
+
* from a plugin. Return the normalized email and its domain, or undefined
|
|
5562
|
+
* when the value is not a valid email.
|
|
5454
5563
|
*/
|
|
5455
|
-
|
|
5456
|
-
const
|
|
5457
|
-
if (!
|
|
5458
|
-
|
|
5459
|
-
|
|
5460
|
-
|
|
5461
|
-
|
|
5462
|
-
}
|
|
5564
|
+
function parseEmail(value) {
|
|
5565
|
+
const parsed = emailSchema.safeParse(value);
|
|
5566
|
+
if (!parsed.success) return void 0;
|
|
5567
|
+
const email = parsed.data;
|
|
5568
|
+
return {
|
|
5569
|
+
email,
|
|
5570
|
+
domain: email.slice(email.lastIndexOf("@") + 1)
|
|
5571
|
+
};
|
|
5463
5572
|
}
|
|
5464
5573
|
/**
|
|
5465
|
-
*
|
|
5466
|
-
*
|
|
5467
|
-
*
|
|
5468
|
-
*
|
|
5574
|
+
* Return whether a domain, such as the domain of a parsed email or Google's
|
|
5575
|
+
* `hd` claim, is on the allowed domains. It only compares domains.
|
|
5576
|
+
* `ifNoDomains` says what an empty list means: Slack authors allow every
|
|
5577
|
+
* domain, and sign-ins allow none.
|
|
5469
5578
|
*/
|
|
5470
|
-
|
|
5471
|
-
|
|
5472
|
-
|
|
5473
|
-
|
|
5474
|
-
// src/chat/conversations/web-authorization.ts
|
|
5475
|
-
const WEB_AUTHORIZATION_PREFIX = "junior:web_authorization:v1";
|
|
5476
|
-
const WEB_AUTHORIZATION_TTL_MS = 864e5;
|
|
5477
|
-
function authorizationKey(conversationId, actorId) {
|
|
5478
|
-
return `${WEB_AUTHORIZATION_PREFIX}:${conversationId}:${actorId}`;
|
|
5579
|
+
function isAllowedDomain(domain, options) {
|
|
5580
|
+
if (options.allowedDomains.length === 0) return options.ifNoDomains === "allow";
|
|
5581
|
+
const normalized = domain?.trim().toLowerCase();
|
|
5582
|
+
return normalized ? options.allowedDomains.includes(normalized) : false;
|
|
5479
5583
|
}
|
|
5480
|
-
|
|
5481
|
-
|
|
5482
|
-
return {
|
|
5483
|
-
createState: async () => randomUUID(),
|
|
5484
|
-
deliver: async (request) => {
|
|
5485
|
-
await getStateAdapter().set(authorizationKey(args.conversationId, args.actorId), JSON.stringify({
|
|
5486
|
-
...request,
|
|
5487
|
-
...args
|
|
5488
|
-
}), WEB_AUTHORIZATION_TTL_MS);
|
|
5489
|
-
}
|
|
5490
|
-
};
|
|
5584
|
+
function isCoreIdentityProvider(provider) {
|
|
5585
|
+
return provider === "junior" || isNativeIdentityProvider(provider);
|
|
5491
5586
|
}
|
|
5492
|
-
|
|
5493
|
-
|
|
5494
|
-
const
|
|
5495
|
-
|
|
5496
|
-
|
|
5497
|
-
|
|
5498
|
-
|
|
5499
|
-
|
|
5500
|
-
|
|
5501
|
-
return;
|
|
5502
|
-
}
|
|
5587
|
+
function isSlackProfileDomainAllowed(profile) {
|
|
5588
|
+
const email = profile.email?.trim();
|
|
5589
|
+
const separator = email?.lastIndexOf("@") ?? -1;
|
|
5590
|
+
const allowed = isAllowedDomain(separator > 0 ? email?.slice(separator + 1) : void 0, {
|
|
5591
|
+
allowedDomains: getChatConfig().trust.allowedDomains,
|
|
5592
|
+
ifNoDomains: "allow"
|
|
5593
|
+
});
|
|
5594
|
+
if (!allowed) logWarn("slack.allowed_domain.rejected", { "app.reason": email ? "domain_not_allowed" : "missing_email" });
|
|
5595
|
+
return allowed;
|
|
5503
5596
|
}
|
|
5504
|
-
|
|
5505
|
-
|
|
5506
|
-
|
|
5597
|
+
const SLACK_TRUSTED_TTL_MS = 3e5;
|
|
5598
|
+
const SLACK_UNTRUSTED_TTL_MS = 3e4;
|
|
5599
|
+
async function readActiveMember(userId, teamId) {
|
|
5600
|
+
return await createCache(getStateAdapter(), "core").getOrLoad(`slack:active-member:${teamId}:${userId}`, async () => {
|
|
5601
|
+
const member = await lookupActiveSlackWorkspaceMember(userId, teamId);
|
|
5602
|
+
const value = member ? {
|
|
5603
|
+
email: member.email,
|
|
5604
|
+
name: member.name,
|
|
5605
|
+
real_name: member.real_name
|
|
5606
|
+
} : null;
|
|
5607
|
+
return {
|
|
5608
|
+
value,
|
|
5609
|
+
ttlMs: value ? SLACK_TRUSTED_TTL_MS : SLACK_UNTRUSTED_TTL_MS
|
|
5610
|
+
};
|
|
5611
|
+
});
|
|
5507
5612
|
}
|
|
5508
|
-
|
|
5509
|
-
|
|
5510
|
-
|
|
5511
|
-
|
|
5512
|
-
|
|
5513
|
-
|
|
5514
|
-
|
|
5613
|
+
/**
|
|
5614
|
+
* Accept one stored Slack link only when it is a current human member of the
|
|
5615
|
+
* workspace whose Slack email is on the allowed domains. With `email`, the
|
|
5616
|
+
* Slack email must also still be that address, so a stale stored email does
|
|
5617
|
+
* not match.
|
|
5618
|
+
*/
|
|
5619
|
+
async function linkedMemberDecision(args) {
|
|
5620
|
+
const userId = parseSlackUserId(args.linked?.slackUserId);
|
|
5621
|
+
if (!args.linked || !userId) return {
|
|
5622
|
+
trusted: false,
|
|
5623
|
+
reason: "no_single_link"
|
|
5515
5624
|
};
|
|
5516
|
-
|
|
5517
|
-
|
|
5518
|
-
|
|
5519
|
-
|
|
5520
|
-
|
|
5521
|
-
|
|
5522
|
-
|
|
5523
|
-
|
|
5524
|
-
|
|
5525
|
-
|
|
5526
|
-
|
|
5527
|
-
|
|
5528
|
-
|
|
5529
|
-
|
|
5530
|
-
|
|
5531
|
-
}), z.object({
|
|
5532
|
-
...pendingAuthCommonFields,
|
|
5533
|
-
kind: z.literal("plugin")
|
|
5534
|
-
})]);
|
|
5535
|
-
const visionSummarySchema = z.object({
|
|
5536
|
-
summary: nonEmptyString,
|
|
5537
|
-
analyzedAtMs: z.number().refine((value) => value !== 0)
|
|
5538
|
-
});
|
|
5539
|
-
const storedThreadStateSchema = z.object({ conversation: z.object({
|
|
5540
|
-
processing: z.object({
|
|
5541
|
-
activeTurnId: optionalString,
|
|
5542
|
-
lastCompletedAtMs: optionalNumber,
|
|
5543
|
-
pendingAuth: pendingAuthSchema.optional().catch(void 0)
|
|
5544
|
-
}).catch({}),
|
|
5545
|
-
vision: z.object({
|
|
5546
|
-
backfillCompletedAtMs: optionalNumber,
|
|
5547
|
-
byFileId: z.record(z.string(), z.unknown()).catch({})
|
|
5548
|
-
}).catch({ byFileId: {} })
|
|
5549
|
-
}).catch({
|
|
5550
|
-
processing: {},
|
|
5551
|
-
vision: { byFileId: {} }
|
|
5552
|
-
}) });
|
|
5553
|
-
/** Safely coerce an unknown persisted value into a ThreadConversationState. */
|
|
5554
|
-
function coerceThreadConversationState(value) {
|
|
5555
|
-
const parsed = storedThreadStateSchema.safeParse(value);
|
|
5556
|
-
if (!parsed.success) return defaultConversationState();
|
|
5557
|
-
const { processing, vision } = parsed.data.conversation;
|
|
5558
|
-
const byFileId = {};
|
|
5559
|
-
for (const [fileId, entry] of Object.entries(vision.byFileId)) {
|
|
5560
|
-
if (fileId.trim().length === 0) continue;
|
|
5561
|
-
const summary = visionSummarySchema.safeParse(entry);
|
|
5562
|
-
if (!summary.success) continue;
|
|
5563
|
-
byFileId[fileId] = summary.data;
|
|
5564
|
-
}
|
|
5625
|
+
const member = await readActiveMember(userId, args.teamId);
|
|
5626
|
+
if (!member) return {
|
|
5627
|
+
trusted: false,
|
|
5628
|
+
reason: "inactive_member"
|
|
5629
|
+
};
|
|
5630
|
+
if (args.email && member.email?.trim().toLowerCase() !== args.email) return {
|
|
5631
|
+
trusted: false,
|
|
5632
|
+
reason: "email_changed"
|
|
5633
|
+
};
|
|
5634
|
+
if (!isSlackProfileDomainAllowed(member)) return {
|
|
5635
|
+
trusted: false,
|
|
5636
|
+
reason: "domain_not_allowed"
|
|
5637
|
+
};
|
|
5638
|
+
const fullName = member.real_name?.trim() || void 0;
|
|
5639
|
+
const userName = member.name?.trim() || void 0;
|
|
5565
5640
|
return {
|
|
5566
|
-
|
|
5567
|
-
|
|
5568
|
-
|
|
5569
|
-
|
|
5570
|
-
|
|
5571
|
-
|
|
5572
|
-
|
|
5641
|
+
trusted: true,
|
|
5642
|
+
actor: {
|
|
5643
|
+
platform: "slack",
|
|
5644
|
+
teamId: args.teamId,
|
|
5645
|
+
userId,
|
|
5646
|
+
...fullName ? { fullName } : void 0,
|
|
5647
|
+
...userName ? { userName } : void 0
|
|
5648
|
+
},
|
|
5649
|
+
user: args.linked.user
|
|
5573
5650
|
};
|
|
5574
5651
|
}
|
|
5575
5652
|
/**
|
|
5576
|
-
*
|
|
5577
|
-
*
|
|
5578
|
-
*
|
|
5579
|
-
*
|
|
5653
|
+
* A plugin account is trusted when the plugin lists it, or through its exact
|
|
5654
|
+
* `subjectId`, linked by the OAuth account-linking flow to one Slack user who
|
|
5655
|
+
* is a current human member on the allowed domains. Handles, emails, and
|
|
5656
|
+
* display names never match.
|
|
5580
5657
|
*/
|
|
5581
|
-
function
|
|
5582
|
-
|
|
5583
|
-
|
|
5584
|
-
|
|
5585
|
-
}
|
|
5586
|
-
}
|
|
5587
|
-
|
|
5588
|
-
|
|
5589
|
-
|
|
5590
|
-
}
|
|
5591
|
-
|
|
5592
|
-
return
|
|
5593
|
-
|
|
5594
|
-
|
|
5595
|
-
|
|
5596
|
-
|
|
5597
|
-
|
|
5598
|
-
|
|
5599
|
-
|
|
5600
|
-
|
|
5601
|
-
|
|
5602
|
-
|
|
5603
|
-
|
|
5604
|
-
}
|
|
5605
|
-
return payload;
|
|
5658
|
+
async function accountDecision(args) {
|
|
5659
|
+
if (isCoreIdentityProvider(args.provider)) return {
|
|
5660
|
+
trusted: false,
|
|
5661
|
+
reason: "core_provider"
|
|
5662
|
+
};
|
|
5663
|
+
if (args.listed) return { trusted: true };
|
|
5664
|
+
if (!args.subjectId) return {
|
|
5665
|
+
trusted: false,
|
|
5666
|
+
reason: "unknown_author"
|
|
5667
|
+
};
|
|
5668
|
+
const teamId = await resolveBotSlackTeamId();
|
|
5669
|
+
if (!teamId) return {
|
|
5670
|
+
trusted: false,
|
|
5671
|
+
reason: "no_workspace"
|
|
5672
|
+
};
|
|
5673
|
+
return await linkedMemberDecision({
|
|
5674
|
+
linked: await findLinkedSlackUser(getSqlExecutor(), {
|
|
5675
|
+
provider: args.provider,
|
|
5676
|
+
providerSubjectId: args.subjectId,
|
|
5677
|
+
slackTeamId: teamId
|
|
5678
|
+
}),
|
|
5679
|
+
teamId
|
|
5680
|
+
});
|
|
5606
5681
|
}
|
|
5607
5682
|
/**
|
|
5608
|
-
*
|
|
5609
|
-
*
|
|
5610
|
-
*
|
|
5611
|
-
*
|
|
5683
|
+
* Return whether a Slack author may start a Turn. The caller must have
|
|
5684
|
+
* checked that the author is a member of the workspace `teamId`. A member is
|
|
5685
|
+
* trusted when their Slack email is on the allowed domains, or when the app
|
|
5686
|
+
* lists them as a bot user. Without allowed domains, every member is.
|
|
5612
5687
|
*/
|
|
5613
|
-
async function
|
|
5614
|
-
|
|
5615
|
-
|
|
5616
|
-
|
|
5617
|
-
|
|
5618
|
-
await
|
|
5619
|
-
|
|
5620
|
-
|
|
5621
|
-
|
|
5688
|
+
async function isTrustedSlackAuthor(args) {
|
|
5689
|
+
const userId = parseSlackUserId(args.user);
|
|
5690
|
+
if (!userId || !args.teamId) return false;
|
|
5691
|
+
const { allowedBotUserIds, allowedDomains } = getChatConfig().trust;
|
|
5692
|
+
if (allowedBotUserIds.includes(userId) || allowedDomains.length === 0) return true;
|
|
5693
|
+
return await createCache(args.state, "core").getOrLoad(`slack:allowed-domain:${args.teamId}:${userId}`, async () => {
|
|
5694
|
+
const profile = await lookupSlackUserProfile(userId);
|
|
5695
|
+
const trusted = profile.id === userId && isSlackProfileDomainAllowed(profile);
|
|
5696
|
+
return {
|
|
5697
|
+
value: trusted,
|
|
5698
|
+
ttlMs: trusted ? SLACK_TRUSTED_TTL_MS : SLACK_UNTRUSTED_TTL_MS
|
|
5699
|
+
};
|
|
5700
|
+
});
|
|
5622
5701
|
}
|
|
5623
|
-
|
|
5624
|
-
|
|
5625
|
-
|
|
5626
|
-
|
|
5627
|
-
|
|
5628
|
-
const workspaceId = toOptionalString(state["app_sandbox_workspace_id"]);
|
|
5629
|
-
const toolSandboxId = toOptionalString(state["app_sandbox_tool_sandbox_id"]);
|
|
5630
|
-
const toolSessionId = toOptionalString(state["app_sandbox_tool_session_id"]);
|
|
5631
|
-
return {
|
|
5632
|
-
id,
|
|
5633
|
-
...profileHash ? { profileHash } : void 0,
|
|
5634
|
-
...workspaceId ? { workspaceId } : void 0,
|
|
5635
|
-
...toolSandboxId && toolSessionId ? { toolSession: {
|
|
5636
|
-
sandboxId: toolSandboxId,
|
|
5637
|
-
sessionId: toolSessionId
|
|
5638
|
-
} } : void 0
|
|
5702
|
+
async function verifiedEmailDecision(value) {
|
|
5703
|
+
const email = parseEmail(value)?.email;
|
|
5704
|
+
if (!email) return {
|
|
5705
|
+
trusted: false,
|
|
5706
|
+
reason: "invalid_email"
|
|
5639
5707
|
};
|
|
5640
|
-
|
|
5641
|
-
|
|
5642
|
-
|
|
5643
|
-
|
|
5644
|
-
}
|
|
5645
|
-
|
|
5646
|
-
|
|
5647
|
-
|
|
5648
|
-
|
|
5649
|
-
|
|
5650
|
-
}
|
|
5651
|
-
|
|
5652
|
-
async function persistThreadStateById(threadId, patch) {
|
|
5653
|
-
if (patch.conversation) await persistConversationMessages({
|
|
5654
|
-
conversation: patch.conversation,
|
|
5655
|
-
conversationId: threadId
|
|
5708
|
+
const teamId = await resolveBotSlackTeamId();
|
|
5709
|
+
if (!teamId) return {
|
|
5710
|
+
trusted: false,
|
|
5711
|
+
reason: "no_workspace"
|
|
5712
|
+
};
|
|
5713
|
+
return await linkedMemberDecision({
|
|
5714
|
+
email,
|
|
5715
|
+
linked: await findSlackUserByPrimaryEmail(getSqlExecutor(), {
|
|
5716
|
+
normalizedEmail: email,
|
|
5717
|
+
slackTeamId: teamId
|
|
5718
|
+
}),
|
|
5719
|
+
teamId
|
|
5656
5720
|
});
|
|
5657
|
-
await mergePersistedState(threadStateKey(threadId), buildThreadStatePayload(patch));
|
|
5658
|
-
}
|
|
5659
|
-
/** Load legacy Redis-backed channel state during the SQL cutover. */
|
|
5660
|
-
async function getLegacyChannelState(channelId) {
|
|
5661
|
-
const stateAdapter = getStateAdapter();
|
|
5662
|
-
await stateAdapter.connect();
|
|
5663
|
-
return await stateAdapter.get(channelStateKey(channelId)) ?? {};
|
|
5664
5721
|
}
|
|
5665
5722
|
/**
|
|
5666
|
-
*
|
|
5667
|
-
*
|
|
5668
|
-
*
|
|
5723
|
+
* Find the trusted person behind an account of a plugin's provider or behind
|
|
5724
|
+
* a verified email, for work that runs as that person. A verified email is
|
|
5725
|
+
* trusted when it is the primary email of the User of one Slack member on
|
|
5726
|
+
* the allowed domains, and Slack still shows that email. Slack and storage
|
|
5727
|
+
* errors propagate.
|
|
5669
5728
|
*/
|
|
5670
|
-
function
|
|
5671
|
-
|
|
5672
|
-
|
|
5673
|
-
|
|
5674
|
-
|
|
5675
|
-
loadLegacy: async () => await getLegacyChannelState(destination.channelId)
|
|
5729
|
+
async function findTrustedUser(author) {
|
|
5730
|
+
let decision;
|
|
5731
|
+
if ("subjectId" in author) decision = await accountDecision({
|
|
5732
|
+
...author,
|
|
5733
|
+
listed: false
|
|
5676
5734
|
});
|
|
5677
|
-
|
|
5678
|
-
|
|
5679
|
-
|
|
5680
|
-
|
|
5681
|
-
|
|
5682
|
-
|
|
5683
|
-
|
|
5684
|
-
|
|
5685
|
-
|
|
5686
|
-
|
|
5687
|
-
|
|
5688
|
-
}
|
|
5689
|
-
};
|
|
5690
|
-
/** Return a classified Slack boundary failure without erasing its cause. */
|
|
5691
|
-
function getConversationTurnBoundaryError(error) {
|
|
5692
|
-
return error instanceof ConversationTurnBoundaryError ? error : void 0;
|
|
5735
|
+
else decision = await verifiedEmailDecision(author.verifiedEmail);
|
|
5736
|
+
if (!decision.trusted) return {
|
|
5737
|
+
status: "untrusted",
|
|
5738
|
+
reason: decision.reason
|
|
5739
|
+
};
|
|
5740
|
+
return decision.user ? {
|
|
5741
|
+
status: "trusted",
|
|
5742
|
+
user: decision.user
|
|
5743
|
+
} : {
|
|
5744
|
+
status: "untrusted",
|
|
5745
|
+
reason: "no_single_link"
|
|
5746
|
+
};
|
|
5693
5747
|
}
|
|
5694
5748
|
/**
|
|
5695
|
-
*
|
|
5696
|
-
*
|
|
5697
|
-
*
|
|
5749
|
+
* Resolve the author of an Event, the same way Slack ingress resolves a
|
|
5750
|
+
* Slack author. It never throws: a failed check gives an untrusted author,
|
|
5751
|
+
* so the Event still runs and the author's text stays context.
|
|
5698
5752
|
*/
|
|
5699
|
-
|
|
5700
|
-
|
|
5701
|
-
|
|
5702
|
-
|
|
5703
|
-
|
|
5704
|
-
|
|
5705
|
-
|
|
5706
|
-
|
|
5707
|
-
|
|
5708
|
-
|
|
5709
|
-
|
|
5710
|
-
|
|
5711
|
-
|
|
5712
|
-
|
|
5713
|
-
|
|
5714
|
-
|
|
5715
|
-
|
|
5716
|
-
|
|
5717
|
-
|
|
5718
|
-
|
|
5719
|
-
|
|
5720
|
-
|
|
5721
|
-
|
|
5722
|
-
|
|
5723
|
-
|
|
5724
|
-
|
|
5725
|
-
|
|
5726
|
-
|
|
5753
|
+
async function resolveEventAuthor(event) {
|
|
5754
|
+
const author = event.author;
|
|
5755
|
+
if (!author) return { status: "system" };
|
|
5756
|
+
const facts = {
|
|
5757
|
+
...author.bot ? { bot: true } : void 0,
|
|
5758
|
+
handle: author.handle,
|
|
5759
|
+
provider: event.namespace,
|
|
5760
|
+
...author.text?.trim() ? { text: author.text.trim() } : void 0
|
|
5761
|
+
};
|
|
5762
|
+
try {
|
|
5763
|
+
const decision = await accountDecision({
|
|
5764
|
+
listed: author.trusted === true,
|
|
5765
|
+
provider: event.namespace,
|
|
5766
|
+
...author.subjectId ? { subjectId: author.subjectId } : void 0
|
|
5767
|
+
});
|
|
5768
|
+
if (!decision.trusted) return {
|
|
5769
|
+
status: "untrusted",
|
|
5770
|
+
reason: decision.reason,
|
|
5771
|
+
...facts
|
|
5772
|
+
};
|
|
5773
|
+
if (!decision.actor) return {
|
|
5774
|
+
status: "trusted",
|
|
5775
|
+
...facts
|
|
5776
|
+
};
|
|
5777
|
+
return {
|
|
5778
|
+
status: "trusted",
|
|
5779
|
+
actor: decision.actor,
|
|
5780
|
+
identityId: await resolveActorIdentityId(getSqlExecutor(), decision.actor),
|
|
5781
|
+
...facts
|
|
5782
|
+
};
|
|
5783
|
+
} catch (error) {
|
|
5784
|
+
logException(error, "event.author.trust_check_failed", {
|
|
5785
|
+
"app.event.event_type": event.eventType,
|
|
5786
|
+
"app.event.namespace": event.namespace
|
|
5787
|
+
});
|
|
5788
|
+
return {
|
|
5789
|
+
status: "untrusted",
|
|
5790
|
+
reason: "check_failed",
|
|
5791
|
+
...facts
|
|
5792
|
+
};
|
|
5727
5793
|
}
|
|
5728
|
-
};
|
|
5729
|
-
/** Return whether an error means the durable worker should redeliver input later. */
|
|
5730
|
-
function isTurnInputDeferredError(error) {
|
|
5731
|
-
return error instanceof TurnInputDeferredError;
|
|
5732
|
-
}
|
|
5733
|
-
/** Mark a turn as the active turn in conversation state. */
|
|
5734
|
-
function startActiveTurn(args) {
|
|
5735
|
-
args.conversation.processing.activeTurnId = args.nextTurnId;
|
|
5736
5794
|
}
|
|
5737
|
-
function
|
|
5738
|
-
|
|
5795
|
+
function safeId(value) {
|
|
5796
|
+
return value.replace(/[^A-Za-z0-9._:@/#+[\]-]/g, "_");
|
|
5739
5797
|
}
|
|
5740
5798
|
/**
|
|
5741
|
-
*
|
|
5742
|
-
*
|
|
5743
|
-
*
|
|
5799
|
+
* Return an Event author's own text and who wrote it. A linked person has
|
|
5800
|
+
* the same author ID and name as on their Slack messages. Other authors
|
|
5801
|
+
* show their handle on the provider.
|
|
5744
5802
|
*/
|
|
5745
|
-
function
|
|
5746
|
-
|
|
5747
|
-
|
|
5803
|
+
function eventAuthorText(author) {
|
|
5804
|
+
if (author.status === "system" || !author.text) return void 0;
|
|
5805
|
+
const actor = author.status === "trusted" ? author.actor : void 0;
|
|
5806
|
+
const name = actor?.fullName ?? actor?.userName ?? `${safeId(author.handle)} on ${safeId(author.provider)}${author.bot ? " (a bot)" : ""}`;
|
|
5807
|
+
return {
|
|
5808
|
+
text: author.text,
|
|
5809
|
+
...actor ? { authorId: actor.userId } : void 0,
|
|
5810
|
+
authorName: name,
|
|
5811
|
+
verified: author.status === "trusted"
|
|
5812
|
+
};
|
|
5748
5813
|
}
|
|
5814
|
+
// src/chat/events/notification.ts
|
|
5815
|
+
const EVENT_WAIT_MS = 3e4;
|
|
5816
|
+
const eventTaskFactsSchema = z.object({
|
|
5817
|
+
about: z.string().optional(),
|
|
5818
|
+
instructions: z.string().min(1),
|
|
5819
|
+
guidance: z.string().optional(),
|
|
5820
|
+
people: z.array(z.string()).optional(),
|
|
5821
|
+
trustedSummary: z.string().optional(),
|
|
5822
|
+
verifiedDetails: z.record(z.string(), z.unknown()).optional(),
|
|
5823
|
+
externalText: z.string().optional(),
|
|
5824
|
+
doneBy: z.object({
|
|
5825
|
+
mention: z.string(),
|
|
5826
|
+
handle: z.string().optional()
|
|
5827
|
+
}).optional(),
|
|
5828
|
+
/** The Event author's own text and who wrote it. It is context. */
|
|
5829
|
+
authorText: z.object({
|
|
5830
|
+
text: z.string().min(1),
|
|
5831
|
+
authorId: z.string().optional(),
|
|
5832
|
+
authorName: z.string().optional(),
|
|
5833
|
+
verified: z.boolean()
|
|
5834
|
+
}).optional()
|
|
5835
|
+
});
|
|
5749
5836
|
/**
|
|
5750
|
-
*
|
|
5837
|
+
* Collect the task facts for one subscribed Event.
|
|
5838
|
+
*
|
|
5839
|
+
* Keep this short: facts the model cannot reconstruct, plus a one-line handling
|
|
5840
|
+
* contract. Stable delivery rules live in runtime and docs, not this prompt.
|
|
5751
5841
|
*/
|
|
5752
|
-
function
|
|
5753
|
-
|
|
5754
|
-
|
|
5842
|
+
function eventTaskFacts(subscription, event, people = [], doneBy, author = { status: "system" }) {
|
|
5843
|
+
const guidance = [eventGuidance(getEventCatalog(), event.namespace, event.eventType), subscription.guidance?.[event.eventType]].filter((text) => Boolean(text?.trim())).join(" ");
|
|
5844
|
+
const authorText = eventAuthorText(author);
|
|
5845
|
+
return {
|
|
5846
|
+
about: subscription.label,
|
|
5847
|
+
instructions: subscription.intent,
|
|
5848
|
+
...guidance ? { guidance } : void 0,
|
|
5849
|
+
...people.length > 0 ? { people: [...people] } : void 0,
|
|
5850
|
+
trustedSummary: event.trustedSummary,
|
|
5851
|
+
...event.data ? { verifiedDetails: event.data } : void 0,
|
|
5852
|
+
...authorText ? { authorText } : void 0,
|
|
5853
|
+
...event.untrustedText ? { externalText: event.untrustedText } : void 0,
|
|
5854
|
+
...doneBy ? { doneBy } : void 0
|
|
5855
|
+
};
|
|
5755
5856
|
}
|
|
5756
5857
|
/**
|
|
5757
|
-
*
|
|
5758
|
-
*
|
|
5759
|
-
* cleared when it still matches the failing turn.
|
|
5858
|
+
* Return the timer creator subject when every event in the batch carries a
|
|
5859
|
+
* valid subject for its own Watch and the same user.
|
|
5760
5860
|
*/
|
|
5761
|
-
function
|
|
5762
|
-
|
|
5763
|
-
|
|
5764
|
-
|
|
5765
|
-
|
|
5766
|
-
|
|
5767
|
-
|
|
5768
|
-
|
|
5769
|
-
|
|
5770
|
-
|
|
5771
|
-
|
|
5772
|
-
|
|
5773
|
-
const message = conversation.messages[index];
|
|
5774
|
-
if (message?.role !== "user") continue;
|
|
5775
|
-
if (buildDeterministicTurnId(message.id) === sessionId) return message;
|
|
5861
|
+
function timerWatchCredentialSubject(conversationId, messages) {
|
|
5862
|
+
let shared;
|
|
5863
|
+
for (const message of messages) {
|
|
5864
|
+
const metadata = message.input.metadata;
|
|
5865
|
+
if (!isEventMailboxMetadata(metadata)) return void 0;
|
|
5866
|
+
const parsed = credentialSubjectSchema.safeParse(metadata.credentialSubject);
|
|
5867
|
+
if (!parsed.success || !metadata.event.subscriptionId || !verifyTimerWatchCredentialSubject({
|
|
5868
|
+
conversationId,
|
|
5869
|
+
subject: parsed.data,
|
|
5870
|
+
watchId: metadata.event.subscriptionId
|
|
5871
|
+
}) || shared && shared.userId !== parsed.data.userId) return;
|
|
5872
|
+
shared ??= parsed.data;
|
|
5776
5873
|
}
|
|
5874
|
+
return shared;
|
|
5777
5875
|
}
|
|
5778
|
-
/**
|
|
5779
|
-
|
|
5780
|
-
|
|
5876
|
+
/**
|
|
5877
|
+
* Read the saved Watch task facts from one Event mailbox entry. Entries
|
|
5878
|
+
* without a Watch or saved facts, such as child agent results and input queued
|
|
5879
|
+
* before facts were saved, return undefined and keep their own text.
|
|
5880
|
+
*/
|
|
5881
|
+
function readEventTaskFacts(message) {
|
|
5882
|
+
const metadata = message.input.metadata;
|
|
5883
|
+
if (!isEventMailboxMetadata(metadata)) return void 0;
|
|
5884
|
+
const watchId = metadata.event.subscriptionId;
|
|
5885
|
+
if (!watchId) return void 0;
|
|
5886
|
+
const parsed = eventTaskFactsSchema.safeParse(metadata.task);
|
|
5887
|
+
return parsed.success ? {
|
|
5888
|
+
facts: parsed.data,
|
|
5889
|
+
metadata,
|
|
5890
|
+
watchId
|
|
5891
|
+
} : void 0;
|
|
5781
5892
|
}
|
|
5782
|
-
/**
|
|
5783
|
-
|
|
5784
|
-
|
|
5893
|
+
/**
|
|
5894
|
+
* Write the agent inputs for an Event batch, one prompt content part each.
|
|
5895
|
+
*
|
|
5896
|
+
* One Event keeps its own text. Several Watch Events become one `<task>`
|
|
5897
|
+
* with one group per Watch, so shared instructions appear once. Entries
|
|
5898
|
+
* without task facts, such as child agent results, keep their own text as
|
|
5899
|
+
* their own inputs after the task. `rendered` replaces the input of an entry
|
|
5900
|
+
* by inbound message id, such as a person change to an Inbox item.
|
|
5901
|
+
*/
|
|
5902
|
+
function renderEventBatchInputs(messages, rendered = /* @__PURE__ */ new Map()) {
|
|
5903
|
+
const groups = /* @__PURE__ */ new Map();
|
|
5904
|
+
const others = [];
|
|
5905
|
+
for (const message of messages) {
|
|
5906
|
+
const saved = readEventTaskFacts(message);
|
|
5907
|
+
if (!saved) {
|
|
5908
|
+
others.push(message);
|
|
5909
|
+
continue;
|
|
5910
|
+
}
|
|
5911
|
+
const { facts, metadata, watchId } = saved;
|
|
5912
|
+
let group = groups.get(watchId);
|
|
5913
|
+
if (!group) {
|
|
5914
|
+
group = {
|
|
5915
|
+
about: facts.about,
|
|
5916
|
+
instructions: facts.instructions,
|
|
5917
|
+
people: [],
|
|
5918
|
+
events: []
|
|
5919
|
+
};
|
|
5920
|
+
groups.set(watchId, group);
|
|
5921
|
+
}
|
|
5922
|
+
for (const person of facts.people ?? []) if (!group.people.includes(person)) group.people.push(person);
|
|
5923
|
+
group.events.push({
|
|
5924
|
+
eventType: metadata.event.eventType,
|
|
5925
|
+
guidance: facts.guidance,
|
|
5926
|
+
source: metadata.event.namespace,
|
|
5927
|
+
trustedSummary: facts.trustedSummary,
|
|
5928
|
+
verifiedDetails: facts.verifiedDetails,
|
|
5929
|
+
authorText: facts.authorText,
|
|
5930
|
+
externalText: facts.externalText,
|
|
5931
|
+
doneBy: facts.doneBy
|
|
5932
|
+
});
|
|
5933
|
+
}
|
|
5934
|
+
const ownInputs = (entries) => entries.map((message) => rendered.get(message.inboundMessageId) ?? {
|
|
5935
|
+
kind: "runtime",
|
|
5936
|
+
text: message.input.text.trim()
|
|
5937
|
+
}).filter((input) => input.text);
|
|
5938
|
+
if (messages.length - others.length < 2) return ownInputs(messages);
|
|
5939
|
+
return [{
|
|
5940
|
+
kind: "runtime",
|
|
5941
|
+
text: renderTaskBatchInput({ groups: [...groups.values()] })
|
|
5942
|
+
}, ...ownInputs(others)];
|
|
5785
5943
|
}
|
|
5786
|
-
/**
|
|
5787
|
-
function
|
|
5788
|
-
const
|
|
5789
|
-
|
|
5790
|
-
const
|
|
5791
|
-
return {
|
|
5792
|
-
|
|
5793
|
-
|
|
5794
|
-
|
|
5944
|
+
/** Return the conversation message entry for one Event input. */
|
|
5945
|
+
function messageEvent(message) {
|
|
5946
|
+
const metadata = message.input.metadata;
|
|
5947
|
+
if (!isEventMailboxMetadata(metadata)) return [];
|
|
5948
|
+
const label = readEventTaskFacts(message)?.facts.about;
|
|
5949
|
+
return [{
|
|
5950
|
+
eventType: metadata.event.eventType,
|
|
5951
|
+
...label ? { label } : void 0,
|
|
5952
|
+
...metadata.event.objectType ? { objectType: metadata.event.objectType } : void 0,
|
|
5953
|
+
...metadata.event.trustedSummary ? { trustedSummary: metadata.event.trustedSummary } : void 0
|
|
5954
|
+
}];
|
|
5795
5955
|
}
|
|
5796
|
-
// src/chat/task-execution/turn-cancel.ts
|
|
5797
5956
|
/**
|
|
5798
|
-
*
|
|
5799
|
-
*
|
|
5957
|
+
* Return the saved Message fields for the Event inputs of one Turn.
|
|
5958
|
+
*
|
|
5959
|
+
* A person change to an Inbox item is not one of the Message's own Events:
|
|
5960
|
+
* its record goes to `reviewItemChanges`, and the dashboard shows it as a
|
|
5961
|
+
* change row. The Message's own Event is its first Watch Event, the
|
|
5962
|
+
* kind the task message counts, or else its first other input, such as an
|
|
5963
|
+
* agent result. `events` lists the Watch Events when several arrived. When
|
|
5964
|
+
* changes share the Message with one own Event, `events` lists that Event, so
|
|
5965
|
+
* a reader can tell it from a Message that only records changes.
|
|
5800
5966
|
*/
|
|
5801
|
-
|
|
5802
|
-
|
|
5803
|
-
const
|
|
5804
|
-
|
|
5805
|
-
|
|
5806
|
-
|
|
5807
|
-
|
|
5808
|
-
|
|
5809
|
-
|
|
5810
|
-
|
|
5811
|
-
|
|
5812
|
-
|
|
5813
|
-
|
|
5814
|
-
|
|
5815
|
-
|
|
5816
|
-
|
|
5817
|
-
|
|
5818
|
-
|
|
5819
|
-
|
|
5820
|
-
|
|
5821
|
-
|
|
5822
|
-
|
|
5823
|
-
|
|
5824
|
-
|
|
5825
|
-
|
|
5826
|
-
|
|
5827
|
-
|
|
5828
|
-
|
|
5829
|
-
|
|
5830
|
-
|
|
5831
|
-
|
|
5832
|
-
|
|
5833
|
-
|
|
5967
|
+
function eventBatchMessageMeta(messages) {
|
|
5968
|
+
const reviewItemChanges = messages.flatMap((message) => message.input.reviewItemChange ? [message.input.reviewItemChange] : []);
|
|
5969
|
+
const own = messages.filter((message) => !message.input.reviewItemChange);
|
|
5970
|
+
const watched = own.filter((message) => readEventTaskFacts(message));
|
|
5971
|
+
const primary = watched[0] ?? own[0];
|
|
5972
|
+
const metadata = (primary ?? messages[0])?.input.metadata;
|
|
5973
|
+
if (!isEventMailboxMetadata(metadata)) return {};
|
|
5974
|
+
const events = watched.length > 1 ? watched.flatMap(messageEvent) : reviewItemChanges.length && primary ? messageEvent(primary) : [];
|
|
5975
|
+
return {
|
|
5976
|
+
eventType: metadata.event.eventType,
|
|
5977
|
+
eventNamespace: metadata.event.namespace,
|
|
5978
|
+
eventIdentifier: metadata.event.identifier,
|
|
5979
|
+
eventObjectType: metadata.event.objectType,
|
|
5980
|
+
...metadata.event.status ? { eventStatus: metadata.event.status } : void 0,
|
|
5981
|
+
...metadata.event.subscriptionId ? { eventWatchId: metadata.event.subscriptionId } : void 0,
|
|
5982
|
+
...metadata.event.trustedSummary ? { trustedSummary: metadata.event.trustedSummary } : void 0,
|
|
5983
|
+
...events.length ? { events } : void 0,
|
|
5984
|
+
...reviewItemChanges.length ? { reviewItemChanges } : void 0
|
|
5985
|
+
};
|
|
5986
|
+
}
|
|
5987
|
+
function eventMessageAuthor(author) {
|
|
5988
|
+
if (author?.status !== "trusted") return {
|
|
5989
|
+
authorId: EVENT_AUTHOR_ID,
|
|
5990
|
+
authorIdentityId: SYSTEM_IDENTITY_ID
|
|
5991
|
+
};
|
|
5992
|
+
if (author.identityId) return {
|
|
5993
|
+
authorId: EVENT_AUTHOR_ID,
|
|
5994
|
+
authorIdentityId: author.identityId
|
|
5995
|
+
};
|
|
5996
|
+
return { authorId: eventBotAuthorId(author.provider, author.handle) };
|
|
5997
|
+
}
|
|
5998
|
+
/** Build plain conversation mailbox input for one matched watch. */
|
|
5999
|
+
function createEventInboundMessage(input) {
|
|
6000
|
+
const metadata = {
|
|
6001
|
+
kind: "event",
|
|
6002
|
+
...input.task ? { task: input.task } : void 0,
|
|
6003
|
+
...input.subscription.credentialSubject ? { credentialSubject: input.subscription.credentialSubject } : void 0,
|
|
6004
|
+
event: {
|
|
6005
|
+
eventKey: input.event.eventKey,
|
|
6006
|
+
eventType: input.event.eventType,
|
|
6007
|
+
namespace: input.event.namespace,
|
|
6008
|
+
identifier: input.event.identifier,
|
|
6009
|
+
subscriptionId: input.subscription.id,
|
|
6010
|
+
trustedSummary: input.event.trustedSummary,
|
|
6011
|
+
objectType: input.event.objectType,
|
|
6012
|
+
...input.status ? { status: input.status } : void 0
|
|
6013
|
+
}
|
|
6014
|
+
};
|
|
6015
|
+
return {
|
|
6016
|
+
conversationId: input.subscription.conversationId,
|
|
6017
|
+
createdAtMs: input.event.occurredAtMs,
|
|
6018
|
+
inboundMessageId: eventInboundMessageId(input.subscription.id, input.event.eventKey),
|
|
6019
|
+
delivery: "defer",
|
|
6020
|
+
source: "event",
|
|
6021
|
+
receivedAtMs: input.receivedAtMs ?? Date.now(),
|
|
6022
|
+
input: {
|
|
6023
|
+
text: input.text,
|
|
6024
|
+
...eventMessageAuthor(input.author),
|
|
6025
|
+
metadata
|
|
6026
|
+
}
|
|
6027
|
+
};
|
|
5834
6028
|
}
|
|
5835
6029
|
/**
|
|
5836
|
-
*
|
|
5837
|
-
*
|
|
5838
|
-
*
|
|
5839
|
-
*
|
|
5840
|
-
* queued input first.
|
|
6030
|
+
* Deliver a Quiet Event as a Conversation note. It starts no Turn, so the
|
|
6031
|
+
* automated-turn limit does not apply. The next Turn sees the note as
|
|
6032
|
+
* runtime context. Core writes how to use it before the Event facts, so a
|
|
6033
|
+
* long summary that the note limit cuts never loses that rule.
|
|
5841
6034
|
*/
|
|
5842
|
-
async function
|
|
5843
|
-
const
|
|
5844
|
-
|
|
5845
|
-
conversationId,
|
|
5846
|
-
|
|
6035
|
+
async function addQuietEventNote(args) {
|
|
6036
|
+
const { event, subscription } = args;
|
|
6037
|
+
await addConversationNote({
|
|
6038
|
+
conversationId: subscription.conversationId,
|
|
6039
|
+
createdAtMs: event.occurredAtMs,
|
|
6040
|
+
key: `quiet_event:${subscription.id}:${event.eventKey}`,
|
|
6041
|
+
text: `A Watch received this Event quietly: it started no Turn, and nobody was told. Use it as current state. Do not tell people about it unless they ask or your work needs it. ${subscription.label}, ${event.eventType}: ${event.trustedSummary}`
|
|
5847
6042
|
});
|
|
5848
6043
|
}
|
|
5849
6044
|
/**
|
|
5850
|
-
*
|
|
5851
|
-
*
|
|
6045
|
+
* Enqueue a event as normal conversation mailbox input.
|
|
6046
|
+
*
|
|
6047
|
+
* The watch only names the conversation. Destination stays on the conversation
|
|
6048
|
+
* and is applied when the worker runs. A stopped Conversation holds the Event.
|
|
5852
6049
|
*/
|
|
5853
|
-
async function
|
|
5854
|
-
|
|
5855
|
-
|
|
5856
|
-
|
|
5857
|
-
|
|
5858
|
-
|
|
5859
|
-
|
|
5860
|
-
|
|
5861
|
-
|
|
5862
|
-
|
|
5863
|
-
|
|
5864
|
-
|
|
5865
|
-
|
|
5866
|
-
|
|
5867
|
-
|
|
5868
|
-
|
|
5869
|
-
|
|
5870
|
-
|
|
5871
|
-
|
|
5872
|
-
|
|
5873
|
-
|
|
5874
|
-
var session_stop_exports = /* @__PURE__ */ __exportAll({ resumeForPersonInput: () => resumeForPersonInput });
|
|
5875
|
-
/** Skip reason on the Message that saves input a stopped Conversation holds. */
|
|
5876
|
-
const STOPPED_CONVERSATION_SKIP_REASON = "stopped conversation";
|
|
5877
|
-
/** Return when a Conversation stopped, or undefined when it is not stopped. */
|
|
5878
|
-
async function getConversationStoppedAtMs(conversationId) {
|
|
5879
|
-
const [row] = await getSqlExecutor().db().select({ stoppedAt: juniorConversations.stoppedAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
|
|
5880
|
-
return row?.stoppedAt?.getTime();
|
|
5881
|
-
}
|
|
5882
|
-
/**
|
|
5883
|
-
* The hold rule: a Conversation holds automated input only while it is
|
|
5884
|
-
* stopped. Status and failure do not hold input.
|
|
5885
|
-
*/
|
|
5886
|
-
async function isHeld(conversationId) {
|
|
5887
|
-
return await getConversationStoppedAtMs(conversationId) !== void 0;
|
|
5888
|
-
}
|
|
5889
|
-
/**
|
|
5890
|
-
* Accept automated input, such as a Watch Event, a message from another
|
|
5891
|
-
* agent, or a child result. This is the only place that holds input. It
|
|
5892
|
-
* checks the hold under the mailbox lock, so it cannot race a stop: held
|
|
5893
|
-
* input is saved as a skipped Message and never reaches `pending`, and the
|
|
5894
|
-
* stop holds input that was appended before it.
|
|
5895
|
-
*/
|
|
5896
|
-
async function enqueueAutomatedInput(args) {
|
|
5897
|
-
if (args.message.source !== "event") throw new Error("Automated input must be an Event");
|
|
5898
|
-
let held = false;
|
|
5899
|
-
const result = await appendAndEnqueueInboundMessage({
|
|
5900
|
-
...args,
|
|
5901
|
-
renderText: async (inboundMessageIds, messageSenders) => {
|
|
5902
|
-
const text = args.renderText ? await args.renderText(inboundMessageIds, messageSenders) : args.message.input.text;
|
|
5903
|
-
if (text === void 0 || !await isHeld(args.message.conversationId)) return text;
|
|
5904
|
-
await saveHeldInput(args.message.conversationId, [{
|
|
5905
|
-
...args.message,
|
|
5906
|
-
input: {
|
|
5907
|
-
...args.message.input,
|
|
5908
|
-
text
|
|
5909
|
-
}
|
|
5910
|
-
}]);
|
|
5911
|
-
held = true;
|
|
5912
|
-
}
|
|
6050
|
+
async function enqueueEventNotification(args) {
|
|
6051
|
+
const task = eventTaskFacts(args.subscription, args.event, args.people, args.doneBy, args.author);
|
|
6052
|
+
return await enqueueAutomatedInput({
|
|
6053
|
+
message: createEventInboundMessage({
|
|
6054
|
+
author: args.author,
|
|
6055
|
+
event: args.event,
|
|
6056
|
+
subscription: {
|
|
6057
|
+
conversationId: args.subscription.conversationId,
|
|
6058
|
+
credentialSubject: args.subscription.credentialSubject,
|
|
6059
|
+
id: args.subscription.id
|
|
6060
|
+
},
|
|
6061
|
+
task,
|
|
6062
|
+
text: renderTaskInput({
|
|
6063
|
+
...task,
|
|
6064
|
+
event: args.event.eventType,
|
|
6065
|
+
source: args.event.namespace
|
|
6066
|
+
})
|
|
6067
|
+
}),
|
|
6068
|
+
queue: args.queue,
|
|
6069
|
+
queueDelayMs: EVENT_WAIT_MS,
|
|
6070
|
+
state: args.state
|
|
5913
6071
|
});
|
|
5914
|
-
return held ? { status: "held" } : result;
|
|
5915
6072
|
}
|
|
6073
|
+
// src/chat/inbox-items/prompt-input.ts
|
|
5916
6074
|
/**
|
|
5917
|
-
*
|
|
5918
|
-
*
|
|
5919
|
-
*
|
|
5920
|
-
*
|
|
5921
|
-
*
|
|
5922
|
-
* Turn to stop. Each Turn it ends records one cancelled `turn_completed`.
|
|
5923
|
-
* Watches stay, and each Conversation that this stop starts reports
|
|
5924
|
-
* a `stopped` agent update to them. A Conversation that already stopped later
|
|
5925
|
-
* keeps that stop, so a retried or cascaded stop does not move it back.
|
|
6075
|
+
* Prompt inputs for person answers to Inbox items. An answer is its own
|
|
6076
|
+
* prompt content part, keyed by the item id that `addInboxItem` returned.
|
|
6077
|
+
* The runtime builds it from the stored change record and the item, so the
|
|
6078
|
+
* model never reads status prose. It repeats the question, then one line for
|
|
6079
|
+
* each answered field. `input-tags.ts` lists the input tags.
|
|
5926
6080
|
*/
|
|
5927
|
-
|
|
5928
|
-
|
|
5929
|
-
const
|
|
5930
|
-
|
|
5931
|
-
const tx = getDb();
|
|
5932
|
-
const locked = await tx.select({
|
|
5933
|
-
conversationId: juniorConversations.conversationId,
|
|
5934
|
-
stoppedAt: juniorConversations.stoppedAt
|
|
5935
|
-
}).from(juniorConversations).where(inArray(juniorConversations.conversationId, [...conversationIds])).orderBy(asc(juniorConversations.conversationId)).for("update");
|
|
5936
|
-
await tx.update(juniorConversations).set({
|
|
5937
|
-
stoppedAt,
|
|
5938
|
-
detailVersion: nextDetailVersion
|
|
5939
|
-
}).where(and(inArray(juniorConversations.conversationId, [...conversationIds]), or(isNull(juniorConversations.stoppedAt), lt(juniorConversations.stoppedAt, stoppedAt))));
|
|
5940
|
-
return locked.flatMap((row) => !row.stoppedAt || row.stoppedAt.getTime() === stoppedAt.getTime() ? [row.conversationId] : []);
|
|
5941
|
-
});
|
|
5942
|
-
const queue = options.queue ?? getVercelConversationWorkQueue();
|
|
5943
|
-
await mapBounded(reported, (conversationId) => publishAgentUpdate(conversationId, {
|
|
5944
|
-
type: "stopped",
|
|
5945
|
-
stoppedAtMs: stoppedAt.getTime()
|
|
5946
|
-
}, {
|
|
5947
|
-
nowMs: stoppedAt.getTime(),
|
|
5948
|
-
queue,
|
|
5949
|
-
starter: false,
|
|
5950
|
-
state: options.state,
|
|
5951
|
-
update: async () => ({
|
|
5952
|
-
status: "stopped",
|
|
5953
|
-
text: "This conversation was stopped."
|
|
5954
|
-
})
|
|
5955
|
-
}));
|
|
5956
|
-
return await mapBounded(conversationIds, async (conversationId) => {
|
|
5957
|
-
const pending = await takePendingEventMessages({
|
|
5958
|
-
conversationId,
|
|
5959
|
-
conversationStore: options.conversationStore,
|
|
5960
|
-
nowMs: options.nowMs,
|
|
5961
|
-
state: options.state
|
|
5962
|
-
});
|
|
5963
|
-
if (pending.length > 0) await saveHeldInput(conversationId, pending);
|
|
5964
|
-
await cancelSignInWait(conversationId);
|
|
5965
|
-
if (conversationId === options.finishedRunOf) return { status: "no_work" };
|
|
5966
|
-
return await stopConversationWork({
|
|
5967
|
-
conversationId,
|
|
5968
|
-
conversationStore: options.conversationStore,
|
|
5969
|
-
nowMs: options.nowMs,
|
|
5970
|
-
onStopSaved: options.onStopSaved,
|
|
5971
|
-
sentAtOrBeforeMs: options.sentAtOrBeforeMs,
|
|
5972
|
-
state: options.state
|
|
5973
|
-
});
|
|
5974
|
-
});
|
|
6081
|
+
const QUESTION_MAX_LENGTH = 512;
|
|
6082
|
+
function typedAnswerText(request, answer) {
|
|
6083
|
+
const normalized = normalizeUserInputAnswer(request, answer);
|
|
6084
|
+
return [...request.fields.flatMap((field) => field.kind === "text" ? normalized.values[field.id] ?? [] : []), ...normalized.other ? [normalized.other] : []].join("\n\n");
|
|
5975
6085
|
}
|
|
5976
|
-
|
|
5977
|
-
|
|
5978
|
-
|
|
5979
|
-
|
|
5980
|
-
|
|
5981
|
-
|
|
5982
|
-
|
|
5983
|
-
|
|
5984
|
-
|
|
5985
|
-
|
|
5986
|
-
const tx = getDb();
|
|
5987
|
-
const stoppedAt = (await tx.select({
|
|
5988
|
-
conversationId: juniorConversations.conversationId,
|
|
5989
|
-
stoppedAt: juniorConversations.stoppedAt
|
|
5990
|
-
}).from(juniorConversations).where(inArray(juniorConversations.conversationId, subtree)).orderBy(asc(juniorConversations.conversationId)).for("update")).find((row) => row.conversationId === conversationId)?.stoppedAt;
|
|
5991
|
-
if (!stoppedAt || sentAtMs <= stoppedAt.getTime()) return;
|
|
5992
|
-
await tx.update(juniorConversations).set({
|
|
5993
|
-
stoppedAt: null,
|
|
5994
|
-
detailVersion: nextDetailVersion
|
|
5995
|
-
}).where(and(inArray(juniorConversations.conversationId, subtree), lte(juniorConversations.stoppedAt, stoppedAt)));
|
|
5996
|
-
});
|
|
6086
|
+
function renderInboxItemAnswer(item) {
|
|
6087
|
+
const request = inboxItemQuestion(item.request);
|
|
6088
|
+
if (!request || !item.answer) return void 0;
|
|
6089
|
+
const question = request.question.trim();
|
|
6090
|
+
const requestText = typedAnswerText(request, item.answer);
|
|
6091
|
+
return {
|
|
6092
|
+
kind: "runtime",
|
|
6093
|
+
text: renderTag("inbox-item-answer", { id: item.id }, [`Question: ${question.length > QUESTION_MAX_LENGTH ? `${question.slice(0, 511)}…` : question}`, formatUserInputAnswer(request, item.answer)].map(escapeTagText)),
|
|
6094
|
+
...requestText ? { requestText } : void 0
|
|
6095
|
+
};
|
|
5997
6096
|
}
|
|
5998
6097
|
/**
|
|
5999
|
-
*
|
|
6000
|
-
*
|
|
6001
|
-
*
|
|
6098
|
+
* Render the prompt input of a message that records an answer, or undefined
|
|
6099
|
+
* when it has none. A take or a dismiss starts no Turn, so it has no input.
|
|
6100
|
+
* A message without an answer, or whose item is gone, goes to the model as
|
|
6101
|
+
* written.
|
|
6002
6102
|
*/
|
|
6003
|
-
async function
|
|
6004
|
-
|
|
6005
|
-
|
|
6006
|
-
|
|
6103
|
+
async function loadInboxItemInput(record) {
|
|
6104
|
+
if (record?.kind !== "submitted") return void 0;
|
|
6105
|
+
const item = await getInboxItem(getDb(), record.reviewItemId);
|
|
6106
|
+
return item ? renderInboxItemAnswer(item) : void 0;
|
|
6007
6107
|
}
|
|
6008
6108
|
/**
|
|
6009
|
-
*
|
|
6010
|
-
*
|
|
6011
|
-
*
|
|
6109
|
+
* Return the instruction of one saved input. `runtime` text, such as an
|
|
6110
|
+
* Automation dispatch or an Event Turn, is already rendered as its tags.
|
|
6111
|
+
* An answer is its Inbox item tag. It is not typed text, so it does not go
|
|
6112
|
+
* in `<current-instruction>`.
|
|
6012
6113
|
*/
|
|
6013
|
-
async function
|
|
6014
|
-
const
|
|
6015
|
-
|
|
6016
|
-
|
|
6017
|
-
|
|
6018
|
-
|
|
6019
|
-
|
|
6020
|
-
createdAtMs: first.createdAtMs,
|
|
6021
|
-
...first.input.authorIdentityId ? { authorIdentityId: first.input.authorIdentityId } : void 0,
|
|
6022
|
-
meta: {
|
|
6023
|
-
replied: false,
|
|
6024
|
-
skippedReason: STOPPED_CONVERSATION_SKIP_REASON,
|
|
6025
|
-
...eventBatchMessageMeta(messages)
|
|
6026
|
-
}
|
|
6027
|
-
});
|
|
6028
|
-
const { createdAtMs, ...data } = stored;
|
|
6029
|
-
await getConversationEventStore().append(conversationId, [{
|
|
6030
|
-
idempotencyKey: `message:${stored.messageId}`,
|
|
6031
|
-
createdAtMs,
|
|
6032
|
-
data: {
|
|
6033
|
-
type: "message",
|
|
6034
|
-
...data
|
|
6035
|
-
}
|
|
6114
|
+
async function savedInputInstruction(args) {
|
|
6115
|
+
const inboxItemInput = args.runtime ? void 0 : await loadInboxItemInput(args.reviewItemChange);
|
|
6116
|
+
if (!args.runtime && !inboxItemInput) return { text: args.text };
|
|
6117
|
+
return instructionForInputs([inboxItemInput ?? {
|
|
6118
|
+
kind: "runtime",
|
|
6119
|
+
text: args.text,
|
|
6120
|
+
...args.requestText ? { requestText: args.requestText } : void 0
|
|
6036
6121
|
}]);
|
|
6037
6122
|
}
|
|
6038
|
-
// src/chat/events/workspace.ts
|
|
6039
|
-
const teamIdsByToken = /* @__PURE__ */ new Map();
|
|
6040
6123
|
/**
|
|
6041
|
-
*
|
|
6042
|
-
*
|
|
6043
|
-
*
|
|
6044
|
-
*
|
|
6045
|
-
* destination team until that store is conversation-owned. System Events are
|
|
6046
|
-
* not gated on Slack. Without a Slack bot, only a listed Event author is
|
|
6047
|
-
* trusted.
|
|
6124
|
+
* Render the Inbox item input of each Event in a batch that records an
|
|
6125
|
+
* answer, keyed by inbound message id. A Conversation with no web identity,
|
|
6126
|
+
* such as a local CLI Conversation, gets the answer as a system Event, but
|
|
6127
|
+
* the input is the same as on web.
|
|
6048
6128
|
*/
|
|
6049
|
-
async function
|
|
6050
|
-
const
|
|
6051
|
-
|
|
6052
|
-
let pending = teamIdsByToken.get(token);
|
|
6053
|
-
if (!pending) {
|
|
6054
|
-
pending = getSlackClient().auth.test().then((result) => {
|
|
6055
|
-
const teamId = result.team_id?.trim();
|
|
6056
|
-
if (!teamId) throw new Error("Slack auth.test did not return a team id");
|
|
6057
|
-
return teamId;
|
|
6058
|
-
});
|
|
6059
|
-
teamIdsByToken.set(token, pending);
|
|
6060
|
-
pending.catch(() => teamIdsByToken.delete(token));
|
|
6061
|
-
}
|
|
6062
|
-
return await pending;
|
|
6129
|
+
async function eventInboxItemInputs(messages) {
|
|
6130
|
+
const rendered = await mapBounded(messages, async (message) => [message.inboundMessageId, await loadInboxItemInput(message.input.reviewItemChange)]);
|
|
6131
|
+
return new Map(rendered.flatMap(([id, input]) => input ? [[id, input]] : []));
|
|
6063
6132
|
}
|
|
6064
|
-
// src/chat/
|
|
6065
|
-
|
|
6066
|
-
|
|
6067
|
-
|
|
6068
|
-
}
|
|
6069
|
-
/** Apply the trust settings of one app. Return the previous settings. */
|
|
6070
|
-
function setTrustConfig(next) {
|
|
6071
|
-
const previous = trustConfig;
|
|
6072
|
-
trustConfig = {
|
|
6073
|
-
allowedBotUserIds: [...next.allowedBotUserIds],
|
|
6074
|
-
allowedDomains: [...next.allowedDomains]
|
|
6075
|
-
};
|
|
6076
|
-
return previous;
|
|
6133
|
+
// src/chat/conversations/web-authorization.ts
|
|
6134
|
+
const WEB_AUTHORIZATION_PREFIX = "junior:web_authorization:v1";
|
|
6135
|
+
const WEB_AUTHORIZATION_TTL_MS = 864e5;
|
|
6136
|
+
function authorizationKey(conversationId, actorId) {
|
|
6137
|
+
return `${WEB_AUTHORIZATION_PREFIX}:${conversationId}:${actorId}`;
|
|
6077
6138
|
}
|
|
6078
|
-
|
|
6079
|
-
|
|
6080
|
-
* Parse a value that must be an email, such as a sign-in or a verified email
|
|
6081
|
-
* from a plugin. Return the normalized email and its domain, or undefined
|
|
6082
|
-
* when the value is not a valid email.
|
|
6083
|
-
*/
|
|
6084
|
-
function parseEmail(value) {
|
|
6085
|
-
const parsed = emailSchema.safeParse(value);
|
|
6086
|
-
if (!parsed.success) return void 0;
|
|
6087
|
-
const email = parsed.data;
|
|
6139
|
+
/** Build authorization delivery for one web turn. */
|
|
6140
|
+
function createWebAuthorization(args) {
|
|
6088
6141
|
return {
|
|
6089
|
-
|
|
6090
|
-
|
|
6142
|
+
createState: async () => randomUUID(),
|
|
6143
|
+
deliver: async (request) => {
|
|
6144
|
+
await getStateAdapter().set(authorizationKey(args.conversationId, args.actorId), JSON.stringify({
|
|
6145
|
+
...request,
|
|
6146
|
+
...args
|
|
6147
|
+
}), WEB_AUTHORIZATION_TTL_MS);
|
|
6148
|
+
}
|
|
6149
|
+
};
|
|
6150
|
+
}
|
|
6151
|
+
/** Read the pending authorization request for one web actor. */
|
|
6152
|
+
async function getWebAuthorization(args) {
|
|
6153
|
+
const value = await getStateAdapter().get(authorizationKey(args.conversationId, args.actorId));
|
|
6154
|
+
if (typeof value !== "string") return void 0;
|
|
6155
|
+
try {
|
|
6156
|
+
const parsed = JSON.parse(value);
|
|
6157
|
+
if (parsed.actorId !== args.actorId || parsed.conversationId !== args.conversationId || typeof parsed.authorizationUrl !== "string" || typeof parsed.label !== "string" || typeof parsed.completionText !== "string") return;
|
|
6158
|
+
return parsed;
|
|
6159
|
+
} catch {
|
|
6160
|
+
return;
|
|
6161
|
+
}
|
|
6162
|
+
}
|
|
6163
|
+
/** Remove a web authorization request after the parked turn continues. */
|
|
6164
|
+
async function deleteWebAuthorization(args) {
|
|
6165
|
+
await getStateAdapter().delete(authorizationKey(args.conversationId, args.actorId));
|
|
6166
|
+
}
|
|
6167
|
+
// src/chat/state/conversation.ts
|
|
6168
|
+
function defaultConversationState() {
|
|
6169
|
+
return {
|
|
6170
|
+
schemaVersion: 1,
|
|
6171
|
+
messages: [],
|
|
6172
|
+
processing: {},
|
|
6173
|
+
vision: { byFileId: {} }
|
|
6174
|
+
};
|
|
6175
|
+
}
|
|
6176
|
+
const nonEmptyString = z.string().refine((value) => value.trim().length > 0);
|
|
6177
|
+
const optionalString = nonEmptyString.optional().catch(void 0);
|
|
6178
|
+
const optionalNumber = z.number().optional().catch(void 0);
|
|
6179
|
+
const pendingAuthCommonFields = {
|
|
6180
|
+
provider: nonEmptyString,
|
|
6181
|
+
actorId: nonEmptyString,
|
|
6182
|
+
sessionId: nonEmptyString,
|
|
6183
|
+
linkSentAtMs: z.number(),
|
|
6184
|
+
scope: optionalString
|
|
6185
|
+
};
|
|
6186
|
+
const pendingAuthSchema = z.discriminatedUnion("kind", [z.object({
|
|
6187
|
+
...pendingAuthCommonFields,
|
|
6188
|
+
kind: z.literal("mcp"),
|
|
6189
|
+
authSessionId: nonEmptyString
|
|
6190
|
+
}), z.object({
|
|
6191
|
+
...pendingAuthCommonFields,
|
|
6192
|
+
kind: z.literal("plugin")
|
|
6193
|
+
})]);
|
|
6194
|
+
const visionSummarySchema = z.object({
|
|
6195
|
+
summary: nonEmptyString,
|
|
6196
|
+
analyzedAtMs: z.number().refine((value) => value !== 0)
|
|
6197
|
+
});
|
|
6198
|
+
const storedThreadStateSchema = z.object({ conversation: z.object({
|
|
6199
|
+
processing: z.object({
|
|
6200
|
+
activeTurnId: optionalString,
|
|
6201
|
+
lastCompletedAtMs: optionalNumber,
|
|
6202
|
+
pendingAuth: pendingAuthSchema.optional().catch(void 0)
|
|
6203
|
+
}).catch(() => ({})),
|
|
6204
|
+
vision: z.object({
|
|
6205
|
+
backfillCompletedAtMs: optionalNumber,
|
|
6206
|
+
byFileId: z.record(z.string(), z.unknown()).catch(() => ({}))
|
|
6207
|
+
}).catch(() => ({ byFileId: {} }))
|
|
6208
|
+
}).catch(() => ({
|
|
6209
|
+
processing: {},
|
|
6210
|
+
vision: { byFileId: {} }
|
|
6211
|
+
})) });
|
|
6212
|
+
/** Safely coerce an unknown persisted value into a ThreadConversationState. */
|
|
6213
|
+
function coerceThreadConversationState(value) {
|
|
6214
|
+
const parsed = storedThreadStateSchema.safeParse(value);
|
|
6215
|
+
if (!parsed.success) return defaultConversationState();
|
|
6216
|
+
const { processing, vision } = parsed.data.conversation;
|
|
6217
|
+
const byFileId = {};
|
|
6218
|
+
for (const [fileId, entry] of Object.entries(vision.byFileId)) {
|
|
6219
|
+
if (fileId.trim().length === 0) continue;
|
|
6220
|
+
const summary = visionSummarySchema.safeParse(entry);
|
|
6221
|
+
if (!summary.success) continue;
|
|
6222
|
+
byFileId[fileId] = summary.data;
|
|
6223
|
+
}
|
|
6224
|
+
return {
|
|
6225
|
+
schemaVersion: 1,
|
|
6226
|
+
messages: [],
|
|
6227
|
+
processing,
|
|
6228
|
+
vision: {
|
|
6229
|
+
backfillCompletedAtMs: vision.backfillCompletedAtMs,
|
|
6230
|
+
byFileId
|
|
6231
|
+
}
|
|
6091
6232
|
};
|
|
6092
6233
|
}
|
|
6093
6234
|
/**
|
|
6094
|
-
*
|
|
6095
|
-
*
|
|
6096
|
-
*
|
|
6097
|
-
*
|
|
6235
|
+
* Wrap active conversation control into the thread scratch envelope.
|
|
6236
|
+
*
|
|
6237
|
+
* Visible history lives in SQL. Image summaries use a separate disposable
|
|
6238
|
+
* cache, so thread scratch does not retain them.
|
|
6098
6239
|
*/
|
|
6099
|
-
function
|
|
6100
|
-
|
|
6101
|
-
|
|
6102
|
-
|
|
6240
|
+
function buildConversationStatePatch(conversation) {
|
|
6241
|
+
return { conversation: {
|
|
6242
|
+
schemaVersion: 1,
|
|
6243
|
+
processing: { ...conversation.processing }
|
|
6244
|
+
} };
|
|
6103
6245
|
}
|
|
6104
|
-
|
|
6105
|
-
|
|
6246
|
+
// src/chat/runtime/thread-state.ts
|
|
6247
|
+
function threadStateKey(threadId) {
|
|
6248
|
+
return `thread-state:${threadId}`;
|
|
6106
6249
|
}
|
|
6107
|
-
function
|
|
6108
|
-
|
|
6109
|
-
const separator = email?.lastIndexOf("@") ?? -1;
|
|
6110
|
-
const allowed = isAllowedDomain(separator > 0 ? email?.slice(separator + 1) : void 0, {
|
|
6111
|
-
allowedDomains: trustConfig.allowedDomains,
|
|
6112
|
-
ifNoDomains: "allow"
|
|
6113
|
-
});
|
|
6114
|
-
if (!allowed) logWarn("slack.allowed_domain.rejected", { "app.reason": email ? "domain_not_allowed" : "missing_email" });
|
|
6115
|
-
return allowed;
|
|
6250
|
+
function channelStateKey(channelId) {
|
|
6251
|
+
return `channel-state:${channelId}`;
|
|
6116
6252
|
}
|
|
6117
|
-
|
|
6118
|
-
const
|
|
6119
|
-
|
|
6120
|
-
|
|
6121
|
-
|
|
6122
|
-
|
|
6123
|
-
|
|
6124
|
-
|
|
6125
|
-
|
|
6126
|
-
|
|
6127
|
-
|
|
6128
|
-
|
|
6129
|
-
ttlMs: value ? SLACK_TRUSTED_TTL_MS : SLACK_UNTRUSTED_TTL_MS
|
|
6130
|
-
};
|
|
6131
|
-
});
|
|
6253
|
+
function buildThreadStatePayload(patch) {
|
|
6254
|
+
const payload = {};
|
|
6255
|
+
if (patch.conversation) Object.assign(payload, buildConversationStatePatch(patch.conversation));
|
|
6256
|
+
if (patch.sandboxRef !== void 0) {
|
|
6257
|
+
payload["app_sandbox_id"] = patch.sandboxRef?.id ?? "";
|
|
6258
|
+
payload["app_sandbox_dependency_profile_hash"] = patch.sandboxRef?.profileHash ?? "";
|
|
6259
|
+
payload["app_sandbox_workspace_id"] = patch.sandboxRef?.workspaceId ?? "";
|
|
6260
|
+
const toolSession = patch.sandboxRef?.toolSession;
|
|
6261
|
+
payload["app_sandbox_tool_sandbox_id"] = toolSession?.sandboxId ?? "";
|
|
6262
|
+
payload["app_sandbox_tool_session_id"] = toolSession?.sessionId ?? "";
|
|
6263
|
+
}
|
|
6264
|
+
return payload;
|
|
6132
6265
|
}
|
|
6133
6266
|
/**
|
|
6134
|
-
*
|
|
6135
|
-
*
|
|
6136
|
-
*
|
|
6137
|
-
*
|
|
6267
|
+
* Merge a payload into thread scratch with Junior's TTL.
|
|
6268
|
+
*
|
|
6269
|
+
* Chat SDK state writes hardcode a 30-day TTL. This boundary owns Junior's
|
|
6270
|
+
* shorter retention policy for the same scratch keys.
|
|
6138
6271
|
*/
|
|
6139
|
-
async function
|
|
6140
|
-
|
|
6141
|
-
|
|
6142
|
-
|
|
6143
|
-
|
|
6144
|
-
|
|
6145
|
-
|
|
6146
|
-
|
|
6147
|
-
|
|
6148
|
-
|
|
6149
|
-
|
|
6150
|
-
|
|
6151
|
-
|
|
6152
|
-
|
|
6153
|
-
|
|
6154
|
-
|
|
6155
|
-
|
|
6156
|
-
|
|
6157
|
-
};
|
|
6158
|
-
const fullName = member.real_name?.trim() || void 0;
|
|
6159
|
-
const userName = member.name?.trim() || void 0;
|
|
6272
|
+
async function mergePersistedState(key, payload) {
|
|
6273
|
+
if (Object.keys(payload).length === 0) return;
|
|
6274
|
+
const stateAdapter = getStateAdapter();
|
|
6275
|
+
await stateAdapter.connect();
|
|
6276
|
+
const existing = await stateAdapter.get(key) ?? {};
|
|
6277
|
+
await stateAdapter.set(key, {
|
|
6278
|
+
...existing,
|
|
6279
|
+
...payload
|
|
6280
|
+
}, JUNIOR_THREAD_STATE_TTL_MS);
|
|
6281
|
+
}
|
|
6282
|
+
/** Extract persisted sandbox metadata from thread state payload. */
|
|
6283
|
+
function getPersistedSandboxState(state) {
|
|
6284
|
+
const id = toOptionalString(state["app_sandbox_id"]);
|
|
6285
|
+
if (!id) return;
|
|
6286
|
+
const profileHash = toOptionalString(state["app_sandbox_dependency_profile_hash"]);
|
|
6287
|
+
const workspaceId = toOptionalString(state["app_sandbox_workspace_id"]);
|
|
6288
|
+
const toolSandboxId = toOptionalString(state["app_sandbox_tool_sandbox_id"]);
|
|
6289
|
+
const toolSessionId = toOptionalString(state["app_sandbox_tool_session_id"]);
|
|
6160
6290
|
return {
|
|
6161
|
-
|
|
6162
|
-
|
|
6163
|
-
|
|
6164
|
-
|
|
6165
|
-
|
|
6166
|
-
|
|
6167
|
-
|
|
6168
|
-
},
|
|
6169
|
-
user: args.linked.user
|
|
6291
|
+
id,
|
|
6292
|
+
...profileHash ? { profileHash } : void 0,
|
|
6293
|
+
...workspaceId ? { workspaceId } : void 0,
|
|
6294
|
+
...toolSandboxId && toolSessionId ? { toolSession: {
|
|
6295
|
+
sandboxId: toolSandboxId,
|
|
6296
|
+
sessionId: toolSessionId
|
|
6297
|
+
} } : void 0
|
|
6170
6298
|
};
|
|
6171
6299
|
}
|
|
6300
|
+
/** Persist only the Redis-backed runtime scratch in a thread-state patch. */
|
|
6301
|
+
async function persistThreadRuntimeState(conversationId, patch) {
|
|
6302
|
+
await mergePersistedState(threadStateKey(conversationId), buildThreadStatePayload(patch));
|
|
6303
|
+
}
|
|
6304
|
+
/** Load the persisted state payload for a thread without requiring a Chat singleton. */
|
|
6305
|
+
async function getPersistedThreadState(threadId) {
|
|
6306
|
+
const stateAdapter = getStateAdapter();
|
|
6307
|
+
await stateAdapter.connect();
|
|
6308
|
+
return await stateAdapter.get(threadStateKey(threadId)) ?? {};
|
|
6309
|
+
}
|
|
6310
|
+
/** Persist a thread-state patch by thread id without constructing a Chat thread. */
|
|
6311
|
+
async function persistThreadStateById(threadId, patch) {
|
|
6312
|
+
if (patch.conversation) await persistConversationMessages({
|
|
6313
|
+
conversation: patch.conversation,
|
|
6314
|
+
conversationId: threadId
|
|
6315
|
+
});
|
|
6316
|
+
await mergePersistedState(threadStateKey(threadId), buildThreadStatePayload(patch));
|
|
6317
|
+
}
|
|
6318
|
+
/** Load legacy Redis-backed channel state during the SQL cutover. */
|
|
6319
|
+
async function getLegacyChannelState(channelId) {
|
|
6320
|
+
const stateAdapter = getStateAdapter();
|
|
6321
|
+
await stateAdapter.connect();
|
|
6322
|
+
return await stateAdapter.get(channelStateKey(channelId)) ?? {};
|
|
6323
|
+
}
|
|
6172
6324
|
/**
|
|
6173
|
-
*
|
|
6174
|
-
*
|
|
6175
|
-
*
|
|
6176
|
-
* display names never match.
|
|
6325
|
+
* Resolve durable location configuration.
|
|
6326
|
+
*
|
|
6327
|
+
* Slack still reads the old channel-id Redis bag once during cutover.
|
|
6177
6328
|
*/
|
|
6178
|
-
|
|
6179
|
-
if (
|
|
6180
|
-
|
|
6181
|
-
|
|
6182
|
-
|
|
6183
|
-
|
|
6184
|
-
if (!args.subjectId) return {
|
|
6185
|
-
trusted: false,
|
|
6186
|
-
reason: "unknown_author"
|
|
6187
|
-
};
|
|
6188
|
-
const teamId = await resolveBotSlackTeamId();
|
|
6189
|
-
if (!teamId) return {
|
|
6190
|
-
trusted: false,
|
|
6191
|
-
reason: "no_workspace"
|
|
6192
|
-
};
|
|
6193
|
-
return await linkedMemberDecision({
|
|
6194
|
-
linked: await findLinkedSlackUser(getSqlExecutor(), {
|
|
6195
|
-
provider: args.provider,
|
|
6196
|
-
providerSubjectId: args.subjectId,
|
|
6197
|
-
slackTeamId: teamId
|
|
6198
|
-
}),
|
|
6199
|
-
teamId
|
|
6329
|
+
function getLocationConfigurationService(destination) {
|
|
6330
|
+
if (destination.platform !== "slack") throw new Error("Location configuration requires a Slack Location");
|
|
6331
|
+
return createDurableLocationConfigurationService({
|
|
6332
|
+
destination,
|
|
6333
|
+
db: getDb(),
|
|
6334
|
+
loadLegacy: async () => await getLegacyChannelState(destination.channelId)
|
|
6200
6335
|
});
|
|
6201
6336
|
}
|
|
6202
|
-
|
|
6203
|
-
|
|
6204
|
-
|
|
6205
|
-
|
|
6206
|
-
|
|
6207
|
-
|
|
6208
|
-
|
|
6209
|
-
|
|
6210
|
-
if (!userId || !args.teamId) return false;
|
|
6211
|
-
const { allowedBotUserIds, allowedDomains } = trustConfig;
|
|
6212
|
-
if (allowedBotUserIds.includes(userId) || allowedDomains.length === 0) return true;
|
|
6213
|
-
return await createCache(args.state, "core").getOrLoad(`slack:allowed-domain:${args.teamId}:${userId}`, async () => {
|
|
6214
|
-
const profile = await lookupSlackUserProfile(userId);
|
|
6215
|
-
const trusted = profile.id === userId && isSlackProfileDomainAllowed(profile);
|
|
6216
|
-
return {
|
|
6217
|
-
value: trusted,
|
|
6218
|
-
ttlMs: trusted ? SLACK_TRUSTED_TTL_MS : SLACK_UNTRUSTED_TTL_MS
|
|
6219
|
-
};
|
|
6220
|
-
});
|
|
6337
|
+
// src/chat/runtime/turn-user-message.ts
|
|
6338
|
+
/** Return the user message for a persisted turn/session, if one exists. */
|
|
6339
|
+
function getTurnUserMessage(conversation, sessionId) {
|
|
6340
|
+
for (let index = conversation.messages.length - 1; index >= 0; index -= 1) {
|
|
6341
|
+
const message = conversation.messages[index];
|
|
6342
|
+
if (message?.role !== "user") continue;
|
|
6343
|
+
if (buildDeterministicTurnId(message.id) === sessionId) return message;
|
|
6344
|
+
}
|
|
6221
6345
|
}
|
|
6222
|
-
|
|
6223
|
-
|
|
6224
|
-
|
|
6225
|
-
|
|
6226
|
-
|
|
6227
|
-
|
|
6228
|
-
|
|
6229
|
-
|
|
6230
|
-
|
|
6231
|
-
|
|
6346
|
+
/** Return the persisted user-message id for a turn/session, if one exists. */
|
|
6347
|
+
function getTurnUserMessageId(conversation, sessionId) {
|
|
6348
|
+
return getTurnUserMessage(conversation, sessionId)?.id;
|
|
6349
|
+
}
|
|
6350
|
+
/** Return the Slack timestamp for the user message that a resumed turn acts on. */
|
|
6351
|
+
function getTurnUserSlackMessageTs(message) {
|
|
6352
|
+
return parseSlackMessageTs(message?.meta?.slackTs);
|
|
6353
|
+
}
|
|
6354
|
+
/** Rebuild attachment context for a resumed turn from the persisted user message. */
|
|
6355
|
+
function getTurnUserReplyAttachmentContext(message) {
|
|
6356
|
+
const inboundAttachmentCount = message?.meta?.attachmentCount ?? 0;
|
|
6357
|
+
const imageAttachmentCount = message?.meta?.imageAttachmentCount ?? 0;
|
|
6358
|
+
const imagesHydrated = message?.meta?.imagesHydrated === true;
|
|
6359
|
+
return {
|
|
6360
|
+
...inboundAttachmentCount > 0 ? { inboundAttachmentCount } : void 0,
|
|
6361
|
+
...!imagesHydrated && imageAttachmentCount > 0 ? { omittedImageAttachmentCount: imageAttachmentCount } : void 0
|
|
6232
6362
|
};
|
|
6233
|
-
return await linkedMemberDecision({
|
|
6234
|
-
email,
|
|
6235
|
-
linked: await findSlackUserByPrimaryEmail(getSqlExecutor(), {
|
|
6236
|
-
normalizedEmail: email,
|
|
6237
|
-
slackTeamId: teamId
|
|
6238
|
-
}),
|
|
6239
|
-
teamId
|
|
6240
|
-
});
|
|
6241
6363
|
}
|
|
6364
|
+
// src/chat/conversations/web-mailbox.ts
|
|
6365
|
+
/** Parse web mailbox metadata written before Source and Actor were complete. */
|
|
6366
|
+
const legacyWebMailboxMetadataSchema = z.object({
|
|
6367
|
+
authorEmail: z.string().email(),
|
|
6368
|
+
authorFullName: z.string().min(1).optional(),
|
|
6369
|
+
authorUserId: z.string().min(1),
|
|
6370
|
+
authorUserName: z.string().min(1).optional(),
|
|
6371
|
+
kind: z.literal("api_turn"),
|
|
6372
|
+
messageId: z.string().min(1)
|
|
6373
|
+
}).strict();
|
|
6374
|
+
// src/chat/task-execution/mailbox-turn.ts
|
|
6242
6375
|
/**
|
|
6243
|
-
*
|
|
6244
|
-
*
|
|
6245
|
-
*
|
|
6246
|
-
*
|
|
6247
|
-
* errors propagate.
|
|
6376
|
+
* Restore Turn input facts, with saved Message fallback for legacy cursors.
|
|
6377
|
+
*
|
|
6378
|
+
* TODO(dcramer): Remove Actor and Source reconstruction from the saved Message
|
|
6379
|
+
* after no deployed Turn cursor can omit either field.
|
|
6248
6380
|
*/
|
|
6249
|
-
|
|
6250
|
-
|
|
6251
|
-
|
|
6252
|
-
|
|
6253
|
-
|
|
6254
|
-
}
|
|
6255
|
-
|
|
6256
|
-
|
|
6257
|
-
|
|
6258
|
-
|
|
6381
|
+
function turnInputFactsFromConversationMessage(message, args) {
|
|
6382
|
+
if (isParentMessageAuthor(message.author)) return args.savedActor && args.savedSource ? {
|
|
6383
|
+
actor: args.savedActor,
|
|
6384
|
+
author: message.author,
|
|
6385
|
+
source: args.savedSource
|
|
6386
|
+
} : void 0;
|
|
6387
|
+
if (isEventConversationMessage(message)) return {
|
|
6388
|
+
actor: args.savedActor ?? EVENT_SYSTEM_ACTOR,
|
|
6389
|
+
author: message.author ?? EVENT_MESSAGE_AUTHOR,
|
|
6390
|
+
source: args.savedSource ?? (args.location ? createWebSource(args.conversationId, args.visibility === "private" ? "private" : "public") : createLocalSource(args.conversationId))
|
|
6259
6391
|
};
|
|
6260
|
-
|
|
6261
|
-
|
|
6262
|
-
|
|
6263
|
-
}
|
|
6264
|
-
|
|
6265
|
-
|
|
6392
|
+
const actor = args.savedActor ?? createActor(message.author, {
|
|
6393
|
+
platform: "web",
|
|
6394
|
+
userId: message.author?.userId
|
|
6395
|
+
});
|
|
6396
|
+
if (actor?.platform !== "web") return;
|
|
6397
|
+
return {
|
|
6398
|
+
actor,
|
|
6399
|
+
author: message.author ?? { userId: actor.userId },
|
|
6400
|
+
source: args.savedSource?.kind === "web" ? args.savedSource : createWebSource(args.conversationId, args.visibility === "private" ? "private" : "public")
|
|
6266
6401
|
};
|
|
6267
6402
|
}
|
|
6268
|
-
/**
|
|
6269
|
-
|
|
6270
|
-
|
|
6271
|
-
|
|
6272
|
-
*/
|
|
6273
|
-
async function resolveEventAuthor(event) {
|
|
6274
|
-
const author = event.author;
|
|
6275
|
-
if (!author) return { status: "system" };
|
|
6276
|
-
const facts = {
|
|
6277
|
-
...author.bot ? { bot: true } : void 0,
|
|
6278
|
-
handle: author.handle,
|
|
6279
|
-
provider: event.namespace,
|
|
6280
|
-
...author.text?.trim() ? { text: author.text.trim() } : void 0
|
|
6281
|
-
};
|
|
6282
|
-
try {
|
|
6283
|
-
const decision = await accountDecision({
|
|
6284
|
-
listed: author.trusted === true,
|
|
6285
|
-
provider: event.namespace,
|
|
6286
|
-
...author.subjectId ? { subjectId: author.subjectId } : void 0
|
|
6287
|
-
});
|
|
6288
|
-
if (!decision.trusted) return {
|
|
6289
|
-
status: "untrusted",
|
|
6290
|
-
reason: decision.reason,
|
|
6291
|
-
...facts
|
|
6292
|
-
};
|
|
6293
|
-
if (!decision.actor) return {
|
|
6294
|
-
status: "trusted",
|
|
6295
|
-
...facts
|
|
6296
|
-
};
|
|
6297
|
-
return {
|
|
6298
|
-
status: "trusted",
|
|
6299
|
-
actor: decision.actor,
|
|
6300
|
-
identityId: await resolveActorIdentityId(getSqlExecutor(), decision.actor),
|
|
6301
|
-
...facts
|
|
6302
|
-
};
|
|
6303
|
-
} catch (error) {
|
|
6304
|
-
logException(error, "event.author.trust_check_failed", {
|
|
6305
|
-
"app.event.event_type": event.eventType,
|
|
6306
|
-
"app.event.namespace": event.namespace
|
|
6307
|
-
});
|
|
6308
|
-
return {
|
|
6309
|
-
status: "untrusted",
|
|
6310
|
-
reason: "check_failed",
|
|
6311
|
-
...facts
|
|
6312
|
-
};
|
|
6313
|
-
}
|
|
6403
|
+
/** Normalize the selected mailbox Source with current Conversation visibility. */
|
|
6404
|
+
function sourceFromTurnInput(args) {
|
|
6405
|
+
if (args.source.kind === "web") return createWebSource(args.conversationId, args.visibility === "private" ? "private" : "public");
|
|
6406
|
+
return args.source;
|
|
6314
6407
|
}
|
|
6315
|
-
function
|
|
6316
|
-
return
|
|
6408
|
+
function hasEventActor(actors) {
|
|
6409
|
+
return Boolean(actors?.some((actor) => actor.platform === "system" && actor.name === EVENT_SYSTEM_ACTOR.name));
|
|
6317
6410
|
}
|
|
6318
|
-
/**
|
|
6319
|
-
|
|
6320
|
-
|
|
6321
|
-
|
|
6322
|
-
|
|
6323
|
-
|
|
6324
|
-
|
|
6325
|
-
|
|
6326
|
-
|
|
6327
|
-
|
|
6328
|
-
|
|
6329
|
-
|
|
6330
|
-
|
|
6331
|
-
|
|
6332
|
-
|
|
6411
|
+
/** Return the active web Turn for one Conversation, if it has one. */
|
|
6412
|
+
async function getActiveConversationTurnId(conversationId) {
|
|
6413
|
+
const active = (await listTurnSummaries(conversationId)).filter((summary) => summary.surface === "api" && !summary.dispatchId && (summary.state === "paused" || summary.state === "running"));
|
|
6414
|
+
if (active.length > 1) throw new Error(`Conversation ${conversationId} has multiple active web turns`);
|
|
6415
|
+
const turnId = active[0]?.turnId;
|
|
6416
|
+
if (!turnId) return void 0;
|
|
6417
|
+
const record = await getTurnRecord(conversationId, turnId);
|
|
6418
|
+
return record && (record.source?.kind === "web" || !record.source && record.surface === "api") && !record.dispatchId && (record.state === "paused" || record.state === "running") ? turnId : void 0;
|
|
6419
|
+
}
|
|
6420
|
+
/** Return the web and event mailbox Turns that are paused or running. */
|
|
6421
|
+
async function listActiveMailboxTurns(conversationId) {
|
|
6422
|
+
const summaries = (await listTurnSummaries(conversationId)).filter(isOpenTurnSummary);
|
|
6423
|
+
const stored = await getStoredTurnFields(summaries);
|
|
6424
|
+
const candidates = summaries.filter((_summary, index) => {
|
|
6425
|
+
const fields = stored[index];
|
|
6426
|
+
return fields !== void 0 && (isActiveMailboxTurn(fields) || !fields.source && fields.surface !== "api");
|
|
6427
|
+
});
|
|
6428
|
+
return (await mapBounded(candidates, (summary) => getTurnRecord(conversationId, summary.turnId))).filter((record) => record !== void 0 && isActiveMailboxTurn(record));
|
|
6333
6429
|
}
|
|
6334
|
-
// src/chat/events/notification.ts
|
|
6335
|
-
const EVENT_WAIT_MS = 3e4;
|
|
6336
|
-
const eventTaskFactsSchema = z.object({
|
|
6337
|
-
about: z.string().optional(),
|
|
6338
|
-
instructions: z.string().min(1),
|
|
6339
|
-
guidance: z.string().optional(),
|
|
6340
|
-
people: z.array(z.string()).optional(),
|
|
6341
|
-
trustedSummary: z.string().optional(),
|
|
6342
|
-
verifiedDetails: z.record(z.string(), z.unknown()).optional(),
|
|
6343
|
-
externalText: z.string().optional(),
|
|
6344
|
-
doneBy: z.object({
|
|
6345
|
-
mention: z.string(),
|
|
6346
|
-
handle: z.string().optional()
|
|
6347
|
-
}).optional(),
|
|
6348
|
-
/** The Event author's own text and who wrote it. It is context. */
|
|
6349
|
-
authorText: z.object({
|
|
6350
|
-
text: z.string().min(1),
|
|
6351
|
-
authorId: z.string().optional(),
|
|
6352
|
-
authorName: z.string().optional(),
|
|
6353
|
-
verified: z.boolean()
|
|
6354
|
-
}).optional()
|
|
6355
|
-
});
|
|
6356
6430
|
/**
|
|
6357
|
-
*
|
|
6358
|
-
*
|
|
6359
|
-
*
|
|
6360
|
-
* contract. Stable delivery rules live in runtime and docs, not this prompt.
|
|
6431
|
+
* List the Source of each active mailbox Turn of several Conversations. It
|
|
6432
|
+
* reads the stored Turn cursors and not their Turn history, so unlike
|
|
6433
|
+
* `listActiveMailboxTurns` it keeps a Turn whose history was deleted.
|
|
6361
6434
|
*/
|
|
6362
|
-
function
|
|
6363
|
-
const
|
|
6364
|
-
const
|
|
6435
|
+
async function listActiveMailboxTurnSources(conversationIds) {
|
|
6436
|
+
const limit = pLimit(8);
|
|
6437
|
+
const summaries = (await Promise.all(conversationIds.map((conversationId) => limit(() => listTurnSummaries(conversationId))))).flatMap((list) => list.filter(isOpenTurnSummary));
|
|
6438
|
+
const stored = await getStoredTurnFields(summaries);
|
|
6439
|
+
const sources = new Map(conversationIds.map((conversationId) => [conversationId, []]));
|
|
6440
|
+
await Promise.all(summaries.map((summary, index) => limit(async () => {
|
|
6441
|
+
const fields = stored[index];
|
|
6442
|
+
const turn = fields && !fields.source && fields.surface !== "api" ? await getTurnRecord(summary.conversationId, summary.turnId) : fields;
|
|
6443
|
+
if (turn && isActiveMailboxTurn(turn)) sources.get(summary.conversationId)?.push(turn.source);
|
|
6444
|
+
})));
|
|
6445
|
+
return sources;
|
|
6446
|
+
}
|
|
6447
|
+
function isOpenTurnSummary(summary) {
|
|
6448
|
+
return !summary.dispatchId && (summary.state === "paused" || summary.state === "running");
|
|
6449
|
+
}
|
|
6450
|
+
function isActiveMailboxTurn(record) {
|
|
6451
|
+
return !record.dispatchId && (record.source?.kind === "web" || record.source?.kind === "event" || record.source?.kind === "parent_message" || !record.source && (record.surface === "api" || hasEventActor(record.actors))) && (record.state === "paused" || record.state === "running");
|
|
6452
|
+
}
|
|
6453
|
+
/** Return the active web or event mailbox Turn. */
|
|
6454
|
+
async function getActiveMailboxTurnId(conversationId) {
|
|
6455
|
+
const active = await listActiveMailboxTurns(conversationId);
|
|
6456
|
+
if (active.length > 1) throw new Error(`Conversation ${conversationId} has multiple active mailbox Turns`);
|
|
6457
|
+
return active[0]?.turnId;
|
|
6458
|
+
}
|
|
6459
|
+
/** Return the idle auth-paused web Turn for one Conversation. */
|
|
6460
|
+
async function getAuthPausedConversationTurnId(conversationId) {
|
|
6461
|
+
const turnId = await getActiveConversationTurnId(conversationId);
|
|
6462
|
+
if (!turnId) return void 0;
|
|
6463
|
+
const record = await getTurnRecord(conversationId, turnId);
|
|
6464
|
+
return record?.state === "paused" && record.resumeReason === "auth" ? turnId : void 0;
|
|
6465
|
+
}
|
|
6466
|
+
/** Return the transcript author of a web Actor's Message. */
|
|
6467
|
+
function webMessageAuthor(actor) {
|
|
6365
6468
|
return {
|
|
6366
|
-
|
|
6367
|
-
|
|
6368
|
-
|
|
6369
|
-
...
|
|
6370
|
-
trustedSummary: event.trustedSummary,
|
|
6371
|
-
...event.data ? { verifiedDetails: event.data } : void 0,
|
|
6372
|
-
...authorText ? { authorText } : void 0,
|
|
6373
|
-
...event.untrustedText ? { externalText: event.untrustedText } : void 0,
|
|
6374
|
-
...doneBy ? { doneBy } : void 0
|
|
6469
|
+
email: actor.email,
|
|
6470
|
+
...actor.fullName ? { fullName: actor.fullName } : void 0,
|
|
6471
|
+
userId: actor.userId,
|
|
6472
|
+
...actor.userName ? { userName: actor.userName } : void 0
|
|
6375
6473
|
};
|
|
6376
6474
|
}
|
|
6475
|
+
/** Read one web input batch as Turn input. A batch with no web input gives []. */
|
|
6476
|
+
function parseWebMessages(messages) {
|
|
6477
|
+
if (messages.length === 0) return [];
|
|
6478
|
+
const parsed = messages.map((message) => ({
|
|
6479
|
+
message,
|
|
6480
|
+
metadata: legacyWebMailboxMetadataSchema.safeParse(message.input.metadata)
|
|
6481
|
+
}));
|
|
6482
|
+
if (parsed.every((entry) => !entry.metadata.success)) return [];
|
|
6483
|
+
if (parsed.some((entry) => !entry.metadata.success)) throw new Error("A Turn cannot combine different kinds of input");
|
|
6484
|
+
return parsed.map((entry) => {
|
|
6485
|
+
if (!entry.metadata.success) throw new Error("User message has invalid metadata");
|
|
6486
|
+
const metadata = entry.metadata.data;
|
|
6487
|
+
const actor = {
|
|
6488
|
+
platform: "web",
|
|
6489
|
+
userId: metadata.authorUserId,
|
|
6490
|
+
email: metadata.authorEmail.trim().toLowerCase(),
|
|
6491
|
+
...metadata.authorFullName ? { fullName: metadata.authorFullName } : void 0,
|
|
6492
|
+
...metadata.authorUserName ? { userName: metadata.authorUserName } : void 0
|
|
6493
|
+
};
|
|
6494
|
+
return {
|
|
6495
|
+
actor,
|
|
6496
|
+
author: webMessageAuthor(actor),
|
|
6497
|
+
message: entry.message,
|
|
6498
|
+
source: createWebSource(entry.message.conversationId)
|
|
6499
|
+
};
|
|
6500
|
+
});
|
|
6501
|
+
}
|
|
6502
|
+
/** Extra debounce time added per additional event already batched. */
|
|
6503
|
+
const EVENT_WAIT_PER_EXTRA_MESSAGE_MS = 5e3;
|
|
6504
|
+
/** Upper bound on the debounce window regardless of batch size. */
|
|
6505
|
+
const EVENT_MAX_WAIT_MS = 6e4;
|
|
6377
6506
|
/**
|
|
6378
|
-
* Return
|
|
6379
|
-
*
|
|
6507
|
+
* Return how long an event batch must wait before its Turn starts.
|
|
6508
|
+
*
|
|
6509
|
+
* A resource-event burst (e.g. several check runs on one PR) should produce
|
|
6510
|
+
* one Turn instead of one per event. The window grows with batch size up to
|
|
6511
|
+
* EVENT_MAX_WAIT_MS, so later events in the same burst land in this batch.
|
|
6512
|
+
* Returns 0 when the batch can run now or does not start with an event.
|
|
6380
6513
|
*/
|
|
6381
|
-
function
|
|
6382
|
-
|
|
6383
|
-
|
|
6384
|
-
|
|
6385
|
-
|
|
6386
|
-
|
|
6387
|
-
|
|
6388
|
-
|
|
6389
|
-
|
|
6390
|
-
|
|
6391
|
-
|
|
6392
|
-
|
|
6393
|
-
|
|
6394
|
-
|
|
6514
|
+
function getEventBatchDelayMs(messages, nowMs = Date.now()) {
|
|
6515
|
+
const first = messages[0];
|
|
6516
|
+
if (!first || !isEventMailboxMetadata(first.input.metadata)) return 0;
|
|
6517
|
+
const waitMs = Math.min(EVENT_MAX_WAIT_MS, EVENT_WAIT_MS + EVENT_WAIT_PER_EXTRA_MESSAGE_MS * (messages.length - 1));
|
|
6518
|
+
return Math.max(0, first.receivedAtMs + waitMs - nowMs);
|
|
6519
|
+
}
|
|
6520
|
+
/** Read an event batch as Turn input, or return [] when it is not only events. */
|
|
6521
|
+
function parseEventMessages(messages) {
|
|
6522
|
+
if (messages.length === 0) return [];
|
|
6523
|
+
if (!messages.every((message) => message.source === "event" && isEventMailboxMetadata(message.input.metadata))) return [];
|
|
6524
|
+
return messages.map((message) => {
|
|
6525
|
+
if (!isEventMailboxMetadata(message.input.metadata)) throw new Error("Event has invalid metadata");
|
|
6526
|
+
return {
|
|
6527
|
+
actor: EVENT_SYSTEM_ACTOR,
|
|
6528
|
+
author: EVENT_MESSAGE_AUTHOR,
|
|
6529
|
+
message,
|
|
6530
|
+
source: createEventSource({
|
|
6531
|
+
eventKey: message.input.metadata.event.eventKey,
|
|
6532
|
+
eventType: message.input.metadata.event.eventType,
|
|
6533
|
+
identifier: message.input.metadata.event.identifier,
|
|
6534
|
+
namespace: message.input.metadata.event.namespace
|
|
6535
|
+
})
|
|
6536
|
+
};
|
|
6537
|
+
});
|
|
6395
6538
|
}
|
|
6396
6539
|
/**
|
|
6397
|
-
* Read
|
|
6398
|
-
*
|
|
6399
|
-
*
|
|
6540
|
+
* Read a batch of parent messages as Turn input, or return [] when it is not
|
|
6541
|
+
* only parent messages. Each runs as the Actor of the parent's Turn, with its
|
|
6542
|
+
* grants, and is from the parent agent.
|
|
6400
6543
|
*/
|
|
6401
|
-
function
|
|
6402
|
-
const
|
|
6403
|
-
if (
|
|
6404
|
-
|
|
6405
|
-
|
|
6406
|
-
|
|
6407
|
-
|
|
6408
|
-
|
|
6409
|
-
|
|
6410
|
-
|
|
6411
|
-
|
|
6544
|
+
function parseParentMessages(messages) {
|
|
6545
|
+
const parentMessages = messages.map(readParentMessage);
|
|
6546
|
+
if (parentMessages.length === 0 || parentMessages.some((parentMessage) => !parentMessage)) return [];
|
|
6547
|
+
return messages.map((message, index) => {
|
|
6548
|
+
const parentMessage = parentMessages[index];
|
|
6549
|
+
return {
|
|
6550
|
+
actor: parentMessage.actor,
|
|
6551
|
+
author: parentMessageAuthor(parentMessage.parentConversationId),
|
|
6552
|
+
...parentMessage.credentialContext ? { credentialContext: parentMessage.credentialContext } : void 0,
|
|
6553
|
+
message,
|
|
6554
|
+
source: { kind: "parent_message" }
|
|
6555
|
+
};
|
|
6556
|
+
});
|
|
6412
6557
|
}
|
|
6413
6558
|
/**
|
|
6414
|
-
*
|
|
6415
|
-
*
|
|
6416
|
-
* One Event keeps its own text. Several Watch Events become one `<task>`
|
|
6417
|
-
* with one group per Watch, so shared instructions appear once. Entries
|
|
6418
|
-
* without task facts, such as child agent results, keep their own text as
|
|
6419
|
-
* their own inputs after the task. `rendered` replaces the input of an entry
|
|
6420
|
-
* by inbound message id, such as a person change to an Inbox item.
|
|
6559
|
+
* Select web, event, or parent work from new mailbox input or a saved Turn.
|
|
6560
|
+
* Saved Actor data identifies a resumed event Turn.
|
|
6421
6561
|
*/
|
|
6422
|
-
function
|
|
6423
|
-
const
|
|
6424
|
-
|
|
6425
|
-
|
|
6426
|
-
|
|
6427
|
-
|
|
6428
|
-
|
|
6429
|
-
|
|
6430
|
-
|
|
6431
|
-
|
|
6432
|
-
|
|
6433
|
-
|
|
6434
|
-
|
|
6435
|
-
|
|
6436
|
-
|
|
6437
|
-
|
|
6438
|
-
|
|
6439
|
-
|
|
6440
|
-
|
|
6441
|
-
|
|
6442
|
-
|
|
6443
|
-
|
|
6444
|
-
eventType: metadata.event.eventType,
|
|
6445
|
-
guidance: facts.guidance,
|
|
6446
|
-
source: metadata.event.namespace,
|
|
6447
|
-
trustedSummary: facts.trustedSummary,
|
|
6448
|
-
verifiedDetails: facts.verifiedDetails,
|
|
6449
|
-
authorText: facts.authorText,
|
|
6450
|
-
externalText: facts.externalText,
|
|
6451
|
-
doneBy: facts.doneBy
|
|
6452
|
-
});
|
|
6453
|
-
}
|
|
6454
|
-
const ownInputs = (entries) => entries.map((message) => rendered.get(message.inboundMessageId) ?? {
|
|
6455
|
-
kind: "runtime",
|
|
6456
|
-
text: message.input.text.trim()
|
|
6457
|
-
}).filter((input) => input.text);
|
|
6458
|
-
if (messages.length - others.length < 2) return ownInputs(messages);
|
|
6459
|
-
return [{
|
|
6460
|
-
kind: "runtime",
|
|
6461
|
-
text: renderTaskBatchInput({ groups: [...groups.values()] })
|
|
6462
|
-
}, ...ownInputs(others)];
|
|
6463
|
-
}
|
|
6464
|
-
/** Return the conversation message entry for one Event input. */
|
|
6465
|
-
function messageEvent(message) {
|
|
6466
|
-
const metadata = message.input.metadata;
|
|
6467
|
-
if (!isEventMailboxMetadata(metadata)) return [];
|
|
6468
|
-
const label = readEventTaskFacts(message)?.facts.about;
|
|
6469
|
-
return [{
|
|
6470
|
-
eventType: metadata.event.eventType,
|
|
6471
|
-
...label ? { label } : void 0,
|
|
6472
|
-
...metadata.event.objectType ? { objectType: metadata.event.objectType } : void 0,
|
|
6473
|
-
...metadata.event.trustedSummary ? { trustedSummary: metadata.event.trustedSummary } : void 0
|
|
6474
|
-
}];
|
|
6562
|
+
async function resolveMailboxTurnWork(context) {
|
|
6563
|
+
const batch = parseWebMessages(context.attempt.messages);
|
|
6564
|
+
if (batch.length > 0) return {
|
|
6565
|
+
kind: "mailbox",
|
|
6566
|
+
batch
|
|
6567
|
+
};
|
|
6568
|
+
const resourceBatch = parseEventMessages(context.attempt.messages);
|
|
6569
|
+
if (resourceBatch.length > 0) return {
|
|
6570
|
+
kind: "mailbox",
|
|
6571
|
+
batch: resourceBatch
|
|
6572
|
+
};
|
|
6573
|
+
const parentBatch = parseParentMessages(context.attempt.messages);
|
|
6574
|
+
if (parentBatch.length > 0) return {
|
|
6575
|
+
kind: "mailbox",
|
|
6576
|
+
batch: parentBatch
|
|
6577
|
+
};
|
|
6578
|
+
if (context.attempt.messages.length > 0) return;
|
|
6579
|
+
const turnId = await getActiveMailboxTurnId(context.conversationId);
|
|
6580
|
+
return turnId ? {
|
|
6581
|
+
kind: "resume",
|
|
6582
|
+
turnId
|
|
6583
|
+
} : void 0;
|
|
6475
6584
|
}
|
|
6585
|
+
// src/chat/task-execution/turn-cancel.ts
|
|
6476
6586
|
/**
|
|
6477
|
-
*
|
|
6478
|
-
*
|
|
6479
|
-
* A person change to an Inbox item is not one of the Message's own Events:
|
|
6480
|
-
* its record goes to `reviewItemChanges`, and the dashboard shows it as a
|
|
6481
|
-
* change row. The Message's own Event is its first Watch Event, the
|
|
6482
|
-
* kind the task message counts, or else its first other input, such as an
|
|
6483
|
-
* agent result. `events` lists the Watch Events when several arrived. When
|
|
6484
|
-
* changes share the Message with one own Event, `events` lists that Event, so
|
|
6485
|
-
* a reader can tell it from a Message that only records changes.
|
|
6587
|
+
* End a cancelled Turn: a stop that a worker saw, or a stop of a Turn that
|
|
6588
|
+
* waits for sign-in with no worker.
|
|
6486
6589
|
*/
|
|
6487
|
-
|
|
6488
|
-
|
|
6489
|
-
const
|
|
6490
|
-
|
|
6491
|
-
|
|
6492
|
-
|
|
6493
|
-
|
|
6494
|
-
|
|
6495
|
-
|
|
6496
|
-
|
|
6497
|
-
|
|
6498
|
-
|
|
6499
|
-
|
|
6500
|
-
|
|
6501
|
-
|
|
6502
|
-
|
|
6503
|
-
|
|
6504
|
-
|
|
6505
|
-
|
|
6590
|
+
/** Close a cancelled Turn, save it, and acknowledge its input. */
|
|
6591
|
+
async function completeCancelledConversationTurn(args) {
|
|
6592
|
+
const pendingAuthorization = args.conversation.processing.pendingAuth?.sessionId === args.turnId ? args.conversation.processing.pendingAuth : void 0;
|
|
6593
|
+
await abandonTurnRecord({
|
|
6594
|
+
conversationId: args.conversationId,
|
|
6595
|
+
turnId: args.turnId,
|
|
6596
|
+
errorMessage: "Turn cancelled"
|
|
6597
|
+
});
|
|
6598
|
+
clearPendingAuth(args.conversation, args.turnId);
|
|
6599
|
+
markConversationMessage(args.conversation, args.userMessageId, {
|
|
6600
|
+
replied: false,
|
|
6601
|
+
skippedReason: "turn cancelled"
|
|
6602
|
+
});
|
|
6603
|
+
markTurnClosed({
|
|
6604
|
+
conversation: args.conversation,
|
|
6605
|
+
nowMs: Date.now(),
|
|
6606
|
+
sessionId: args.turnId
|
|
6607
|
+
});
|
|
6608
|
+
if (pendingAuthorization) await deleteWebAuthorization({
|
|
6609
|
+
actorId: pendingAuthorization.actorId,
|
|
6610
|
+
conversationId: args.conversationId
|
|
6611
|
+
});
|
|
6612
|
+
await persistThreadStateById(args.conversationId, {
|
|
6613
|
+
conversation: args.conversation,
|
|
6614
|
+
sandboxRef: args.sandboxRef
|
|
6615
|
+
});
|
|
6616
|
+
await getTurnLifecycle().complete({
|
|
6617
|
+
conversationId: args.conversationId,
|
|
6618
|
+
createdAtMs: Date.now(),
|
|
6619
|
+
outcome: "cancelled",
|
|
6620
|
+
turnId: args.turnId
|
|
6621
|
+
});
|
|
6622
|
+
await args.acknowledge();
|
|
6506
6623
|
}
|
|
6507
|
-
|
|
6508
|
-
|
|
6509
|
-
|
|
6510
|
-
|
|
6511
|
-
|
|
6512
|
-
|
|
6513
|
-
|
|
6514
|
-
|
|
6515
|
-
|
|
6516
|
-
|
|
6624
|
+
/**
|
|
6625
|
+
* End the Turn of a stopped Conversation that waits for sign-in, so a later
|
|
6626
|
+
* sign-in cannot resume it. A web Turn waits as an auth-paused Turn record. A
|
|
6627
|
+
* Slack request waits as the thread's pending sign-in. Every stop path calls
|
|
6628
|
+
* this, because no worker holds a waiting Turn and the stop wake can go to
|
|
6629
|
+
* queued input first.
|
|
6630
|
+
*/
|
|
6631
|
+
async function cancelSignInWait(conversationId) {
|
|
6632
|
+
const turnId = await getAuthPausedConversationTurnId(conversationId) ?? coerceThreadConversationState(await getPersistedThreadState(conversationId)).processing.pendingAuth?.sessionId;
|
|
6633
|
+
if (turnId) await cancelSignInPausedTurn({
|
|
6634
|
+
conversationId,
|
|
6635
|
+
turnId
|
|
6636
|
+
});
|
|
6517
6637
|
}
|
|
6518
|
-
/**
|
|
6519
|
-
|
|
6520
|
-
|
|
6521
|
-
|
|
6522
|
-
|
|
6523
|
-
|
|
6524
|
-
|
|
6525
|
-
|
|
6526
|
-
|
|
6527
|
-
|
|
6528
|
-
|
|
6529
|
-
|
|
6530
|
-
|
|
6531
|
-
|
|
6532
|
-
|
|
6533
|
-
|
|
6534
|
-
|
|
6535
|
-
|
|
6536
|
-
|
|
6537
|
-
|
|
6538
|
-
|
|
6539
|
-
|
|
6540
|
-
|
|
6541
|
-
|
|
6542
|
-
|
|
6543
|
-
|
|
6544
|
-
|
|
6545
|
-
|
|
6638
|
+
/**
|
|
6639
|
+
* Cancel a Turn that waits for sign-in outside its worker, with the same
|
|
6640
|
+
* cleanup as a stopped resume.
|
|
6641
|
+
*/
|
|
6642
|
+
async function cancelSignInPausedTurn(args) {
|
|
6643
|
+
if (!await abandonTurnRecord({
|
|
6644
|
+
conversationId: args.conversationId,
|
|
6645
|
+
errorMessage: "Turn cancelled",
|
|
6646
|
+
onlyIfAuthPaused: true,
|
|
6647
|
+
turnId: args.turnId
|
|
6648
|
+
})) return;
|
|
6649
|
+
const conversation = coerceThreadConversationState(await getPersistedThreadState(args.conversationId));
|
|
6650
|
+
await hydrateConversationMessages({
|
|
6651
|
+
conversation,
|
|
6652
|
+
conversationId: args.conversationId
|
|
6653
|
+
});
|
|
6654
|
+
await completeCancelledConversationTurn({
|
|
6655
|
+
acknowledge: async () => {},
|
|
6656
|
+
conversation,
|
|
6657
|
+
conversationId: args.conversationId,
|
|
6658
|
+
turnId: args.turnId,
|
|
6659
|
+
userMessageId: getTurnUserMessage(conversation, args.turnId)?.id
|
|
6660
|
+
});
|
|
6661
|
+
}
|
|
6662
|
+
// src/chat/conversations/session-stop.ts
|
|
6663
|
+
var session_stop_exports = /* @__PURE__ */ __exportAll({ resumeForPersonInput: () => resumeForPersonInput });
|
|
6664
|
+
/** Return when a Conversation stopped, or undefined when it is not stopped. */
|
|
6665
|
+
async function getConversationStoppedAtMs(conversationId) {
|
|
6666
|
+
const [row] = await getSqlExecutor().db().select({ stoppedAt: juniorConversations.stoppedAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
|
|
6667
|
+
return row?.stoppedAt?.getTime();
|
|
6668
|
+
}
|
|
6669
|
+
/**
|
|
6670
|
+
* The hold rule: a Conversation holds automated input only while it is
|
|
6671
|
+
* stopped. Status and failure do not hold input.
|
|
6672
|
+
*/
|
|
6673
|
+
async function isHeld(conversationId) {
|
|
6674
|
+
return await getConversationStoppedAtMs(conversationId) !== void 0;
|
|
6675
|
+
}
|
|
6676
|
+
/**
|
|
6677
|
+
* Accept automated input, such as a Watch Event, a message from another
|
|
6678
|
+
* agent, or a child result. This is the only place that holds input. It
|
|
6679
|
+
* checks the hold under the mailbox lock, so it cannot race a stop: held
|
|
6680
|
+
* input is saved as a skipped Message and never reaches `pending`, and the
|
|
6681
|
+
* stop holds input that was appended before it.
|
|
6682
|
+
*/
|
|
6683
|
+
async function enqueueAutomatedInput(args) {
|
|
6684
|
+
if (args.message.source !== "event") throw new Error("Automated input must be an Event");
|
|
6685
|
+
let held = false;
|
|
6686
|
+
const result = await appendAndEnqueueInboundMessage({
|
|
6687
|
+
...args,
|
|
6688
|
+
renderText: async (inboundMessageIds, messageSenders) => {
|
|
6689
|
+
const text = args.renderText ? await args.renderText(inboundMessageIds, messageSenders) : args.message.input.text;
|
|
6690
|
+
if (text === void 0 || !await isHeld(args.message.conversationId)) return text;
|
|
6691
|
+
await saveHeldInput(args.message.conversationId, [{
|
|
6692
|
+
...args.message,
|
|
6693
|
+
input: {
|
|
6694
|
+
...args.message.input,
|
|
6695
|
+
text
|
|
6696
|
+
}
|
|
6697
|
+
}]);
|
|
6698
|
+
held = true;
|
|
6546
6699
|
}
|
|
6547
|
-
};
|
|
6700
|
+
});
|
|
6701
|
+
return held ? { status: "held" } : result;
|
|
6548
6702
|
}
|
|
6549
6703
|
/**
|
|
6550
|
-
*
|
|
6551
|
-
*
|
|
6552
|
-
*
|
|
6553
|
-
*
|
|
6704
|
+
* Stop each Conversation of a tree until a person sends it input or its
|
|
6705
|
+
* parent gives it new work. Every stop path ends here: a person's stop,
|
|
6706
|
+
* `stopAgent`, and the automated-turn limit. It writes the stop in one
|
|
6707
|
+
* transaction with row locks, holds the automated input that already waits
|
|
6708
|
+
* in each mailbox, ends a Turn that waits for sign-in, and asks each running
|
|
6709
|
+
* Turn to stop. Each Turn it ends records one cancelled `turn_completed`.
|
|
6710
|
+
* Watches stay, and each Conversation that this stop starts reports
|
|
6711
|
+
* a `stopped` agent update to them. A Conversation that already stopped later
|
|
6712
|
+
* keeps that stop, so a retried or cascaded stop does not move it back.
|
|
6554
6713
|
*/
|
|
6555
|
-
async function
|
|
6556
|
-
|
|
6557
|
-
|
|
6558
|
-
|
|
6559
|
-
|
|
6560
|
-
|
|
6561
|
-
|
|
6714
|
+
async function stopConversationTree(conversationIds, options) {
|
|
6715
|
+
if (conversationIds.length === 0) return [];
|
|
6716
|
+
const stoppedAt = new Date(options.stoppedAtMs);
|
|
6717
|
+
const reported = await getSqlExecutor().transaction(async () => {
|
|
6718
|
+
const tx = getDb();
|
|
6719
|
+
const locked = await tx.select({
|
|
6720
|
+
conversationId: juniorConversations.conversationId,
|
|
6721
|
+
stoppedAt: juniorConversations.stoppedAt
|
|
6722
|
+
}).from(juniorConversations).where(inArray(juniorConversations.conversationId, [...conversationIds])).orderBy(asc(juniorConversations.conversationId)).for("update");
|
|
6723
|
+
await tx.update(juniorConversations).set({
|
|
6724
|
+
stoppedAt,
|
|
6725
|
+
detailVersion: nextDetailVersion
|
|
6726
|
+
}).where(and(inArray(juniorConversations.conversationId, [...conversationIds]), or(isNull(juniorConversations.stoppedAt), lt(juniorConversations.stoppedAt, stoppedAt))));
|
|
6727
|
+
return locked.flatMap((row) => !row.stoppedAt || row.stoppedAt.getTime() === stoppedAt.getTime() ? [row.conversationId] : []);
|
|
6728
|
+
});
|
|
6729
|
+
const queue = options.queue ?? getVercelConversationWorkQueue();
|
|
6730
|
+
await mapBounded(reported, (conversationId) => publishAgentUpdate(conversationId, {
|
|
6731
|
+
type: "stopped",
|
|
6732
|
+
stoppedAtMs: stoppedAt.getTime()
|
|
6733
|
+
}, {
|
|
6734
|
+
nowMs: stoppedAt.getTime(),
|
|
6735
|
+
queue,
|
|
6736
|
+
starter: false,
|
|
6737
|
+
state: options.state,
|
|
6738
|
+
update: async () => ({
|
|
6739
|
+
status: "stopped",
|
|
6740
|
+
text: "This conversation was stopped."
|
|
6741
|
+
})
|
|
6742
|
+
}));
|
|
6743
|
+
return await mapBounded(conversationIds, async (conversationId) => {
|
|
6744
|
+
const pending = await takePendingEventMessages({
|
|
6745
|
+
conversationId,
|
|
6746
|
+
conversationStore: options.conversationStore,
|
|
6747
|
+
nowMs: options.nowMs,
|
|
6748
|
+
state: options.state
|
|
6749
|
+
});
|
|
6750
|
+
if (pending.length > 0) await saveHeldInput(conversationId, pending);
|
|
6751
|
+
await cancelSignInWait(conversationId);
|
|
6752
|
+
if (conversationId === options.finishedRunOf) return { status: "no_work" };
|
|
6753
|
+
return await stopConversationWork({
|
|
6754
|
+
conversationId,
|
|
6755
|
+
conversationStore: options.conversationStore,
|
|
6756
|
+
nowMs: options.nowMs,
|
|
6757
|
+
onStopSaved: options.onStopSaved,
|
|
6758
|
+
sentAtOrBeforeMs: options.sentAtOrBeforeMs,
|
|
6759
|
+
state: options.state
|
|
6760
|
+
});
|
|
6562
6761
|
});
|
|
6563
6762
|
}
|
|
6564
6763
|
/**
|
|
6565
|
-
*
|
|
6566
|
-
*
|
|
6567
|
-
*
|
|
6568
|
-
*
|
|
6764
|
+
* End the stop of a Conversation and of the child agents below it, for new
|
|
6765
|
+
* work sent at `sentAtMs`: a person's input, or new work from its parent.
|
|
6766
|
+
* Nothing changes for work sent at or before the stop, so the input that a
|
|
6767
|
+
* stop drops does not undo it. Only Conversations that stopped no later than
|
|
6768
|
+
* this Conversation change, so a later stop of one child agent stays.
|
|
6569
6769
|
*/
|
|
6570
|
-
async function
|
|
6571
|
-
const
|
|
6572
|
-
|
|
6573
|
-
|
|
6574
|
-
|
|
6575
|
-
|
|
6576
|
-
|
|
6577
|
-
|
|
6578
|
-
|
|
6579
|
-
|
|
6580
|
-
|
|
6581
|
-
|
|
6582
|
-
|
|
6583
|
-
|
|
6584
|
-
|
|
6585
|
-
|
|
6586
|
-
|
|
6587
|
-
|
|
6588
|
-
|
|
6589
|
-
|
|
6590
|
-
|
|
6770
|
+
async function resumeConversationTree(conversationId, sentAtMs) {
|
|
6771
|
+
const subtree = sql`(select ${conversationSubtreeColumns.conversationId} from ${conversationSubtree([conversationId])})`;
|
|
6772
|
+
await getSqlExecutor().transaction(async () => {
|
|
6773
|
+
const tx = getDb();
|
|
6774
|
+
const stoppedAt = (await tx.select({
|
|
6775
|
+
conversationId: juniorConversations.conversationId,
|
|
6776
|
+
stoppedAt: juniorConversations.stoppedAt
|
|
6777
|
+
}).from(juniorConversations).where(inArray(juniorConversations.conversationId, subtree)).orderBy(asc(juniorConversations.conversationId)).for("update")).find((row) => row.conversationId === conversationId)?.stoppedAt;
|
|
6778
|
+
if (!stoppedAt || sentAtMs <= stoppedAt.getTime()) return;
|
|
6779
|
+
await tx.update(juniorConversations).set({
|
|
6780
|
+
stoppedAt: null,
|
|
6781
|
+
detailVersion: nextDetailVersion
|
|
6782
|
+
}).where(and(inArray(juniorConversations.conversationId, subtree), lte(juniorConversations.stoppedAt, stoppedAt)));
|
|
6783
|
+
});
|
|
6784
|
+
}
|
|
6785
|
+
/**
|
|
6786
|
+
* Resume a stopped Conversation when a person sent input after the stop.
|
|
6787
|
+
* Known gap: input sent before the stop but received after it still runs,
|
|
6788
|
+
* and the Conversation stays stopped.
|
|
6789
|
+
*/
|
|
6790
|
+
async function resumeForPersonInput(conversationId, messages) {
|
|
6791
|
+
const personInput = messages.filter((message) => isPersonInput(message.source));
|
|
6792
|
+
if (personInput.length === 0) return;
|
|
6793
|
+
await resumeConversationTree(conversationId, Math.max(...personInput.map((message) => message.createdAtMs)));
|
|
6794
|
+
}
|
|
6795
|
+
/**
|
|
6796
|
+
* Save held input as one skipped Message, the Message that a Turn would save
|
|
6797
|
+
* for it. The next Turn gets it as Turn input (`withHeldInput`). The append
|
|
6798
|
+
* is idempotent by Message id, and the Message takes the id of the first
|
|
6799
|
+
* input.
|
|
6800
|
+
*/
|
|
6801
|
+
async function saveHeldInput(conversationId, messages) {
|
|
6802
|
+
const first = messages[0];
|
|
6803
|
+
const { text } = instructionForInputs(renderEventBatchInputs(messages, await eventInboxItemInputs(messages)));
|
|
6804
|
+
const stored = toStoredConversationMessage({
|
|
6805
|
+
id: first.inboundMessageId,
|
|
6806
|
+
role: "user",
|
|
6807
|
+
text: normalizeConversationText(text),
|
|
6808
|
+
createdAtMs: first.createdAtMs,
|
|
6809
|
+
...first.input.authorIdentityId ? { authorIdentityId: first.input.authorIdentityId } : void 0,
|
|
6810
|
+
meta: {
|
|
6811
|
+
replied: false,
|
|
6812
|
+
skippedReason: STOPPED_CONVERSATION_SKIP_REASON,
|
|
6813
|
+
...eventBatchMessageMeta(messages)
|
|
6814
|
+
}
|
|
6591
6815
|
});
|
|
6816
|
+
const { createdAtMs, ...data } = stored;
|
|
6817
|
+
await getConversationEventStore().append(conversationId, [{
|
|
6818
|
+
idempotencyKey: `message:${stored.messageId}`,
|
|
6819
|
+
createdAtMs,
|
|
6820
|
+
data: {
|
|
6821
|
+
type: "message",
|
|
6822
|
+
...data
|
|
6823
|
+
}
|
|
6824
|
+
}]);
|
|
6592
6825
|
}
|
|
6593
6826
|
// src/chat/child-agents/fork-history.ts
|
|
6594
6827
|
/** Instructions that a fork child reads with its first task. */
|
|
@@ -6830,14 +7063,12 @@ async function dropWaitingParentMessages(conversationId, state) {
|
|
|
6830
7063
|
for (const { message, parentMessage } of waiting) logDroppedParentMessage(message, parentMessage);
|
|
6831
7064
|
}
|
|
6832
7065
|
/**
|
|
6833
|
-
*
|
|
6834
|
-
*
|
|
6835
|
-
*
|
|
7066
|
+
* Return whether a parent message has the author id of the parent that it
|
|
7067
|
+
* names. The child must also have that parent as its stored parent before
|
|
7068
|
+
* the message gets any authority.
|
|
6836
7069
|
*/
|
|
6837
|
-
|
|
6838
|
-
|
|
6839
|
-
const [row] = await getSqlExecutor().db().select({ stoppedAt: juniorConversations.stoppedAt }).from(juniorConversations).where(and(eq(juniorConversations.conversationId, message.conversationId), eq(juniorConversations.parentConversationId, parentMessage.parentConversationId))).limit(1);
|
|
6840
|
-
return row;
|
|
7070
|
+
function hasParentMessageAuthor(message, parentMessage) {
|
|
7071
|
+
return message.input.authorId === parentMessageAuthorId(parentMessage.parentConversationId);
|
|
6841
7072
|
}
|
|
6842
7073
|
/**
|
|
6843
7074
|
* Log a parent message that a child dropped: its sender check failed, or a
|
|
@@ -6920,225 +7151,411 @@ async function childAgentTurnOptions(args) {
|
|
|
6920
7151
|
run: options?.reasoningLevel ? { reasoning: options.reasoningLevel } : {}
|
|
6921
7152
|
};
|
|
6922
7153
|
}
|
|
6923
|
-
// src/chat/
|
|
6924
|
-
|
|
6925
|
-
|
|
6926
|
-
|
|
6927
|
-
|
|
6928
|
-
|
|
6929
|
-
authorUserName: z.string().min(1).optional(),
|
|
6930
|
-
kind: z.literal("api_turn"),
|
|
6931
|
-
messageId: z.string().min(1)
|
|
6932
|
-
}).strict();
|
|
6933
|
-
// src/chat/task-execution/mailbox-turn.ts
|
|
6934
|
-
/**
|
|
6935
|
-
* Restore Turn input facts, with saved Message fallback for legacy cursors.
|
|
6936
|
-
*
|
|
6937
|
-
* TODO(dcramer): Remove Actor and Source reconstruction from the saved Message
|
|
6938
|
-
* after no deployed Turn cursor can omit either field.
|
|
6939
|
-
*/
|
|
6940
|
-
function turnInputFactsFromConversationMessage(message, args) {
|
|
6941
|
-
if (isParentMessageAuthor(message.author)) return args.savedActor && args.savedSource ? {
|
|
6942
|
-
actor: args.savedActor,
|
|
6943
|
-
author: message.author,
|
|
6944
|
-
source: args.savedSource
|
|
6945
|
-
} : void 0;
|
|
6946
|
-
if (isEventConversationMessage(message)) return {
|
|
6947
|
-
actor: args.savedActor ?? EVENT_SYSTEM_ACTOR,
|
|
6948
|
-
author: message.author ?? EVENT_MESSAGE_AUTHOR,
|
|
6949
|
-
source: args.savedSource ?? (args.location ? createWebSource(args.conversationId, args.visibility === "private" ? "private" : "public") : createLocalSource(args.conversationId))
|
|
6950
|
-
};
|
|
6951
|
-
const actor = args.savedActor ?? createActor(message.author, {
|
|
6952
|
-
platform: "web",
|
|
6953
|
-
userId: message.author?.userId
|
|
6954
|
-
});
|
|
6955
|
-
if (actor?.platform !== "web") return;
|
|
6956
|
-
return {
|
|
6957
|
-
actor,
|
|
6958
|
-
author: message.author ?? { userId: actor.userId },
|
|
6959
|
-
source: args.savedSource?.kind === "web" ? args.savedSource : createWebSource(args.conversationId, args.visibility === "private" ? "private" : "public")
|
|
6960
|
-
};
|
|
6961
|
-
}
|
|
6962
|
-
/** Normalize the selected mailbox Source with current Conversation visibility. */
|
|
6963
|
-
function sourceFromTurnInput(args) {
|
|
6964
|
-
if (args.source.kind === "web") return createWebSource(args.conversationId, args.visibility === "private" ? "private" : "public");
|
|
6965
|
-
return args.source;
|
|
6966
|
-
}
|
|
6967
|
-
function hasEventActor(actors) {
|
|
6968
|
-
return Boolean(actors?.some((actor) => actor.platform === "system" && actor.name === EVENT_SYSTEM_ACTOR.name));
|
|
6969
|
-
}
|
|
6970
|
-
/** Return the active web Turn for one Conversation, if it has one. */
|
|
6971
|
-
async function getActiveConversationTurnId(conversationId) {
|
|
6972
|
-
const active = (await listTurnSummaries(conversationId)).filter((summary) => summary.surface === "api" && !summary.dispatchId && (summary.state === "paused" || summary.state === "running"));
|
|
6973
|
-
if (active.length > 1) throw new Error(`Conversation ${conversationId} has multiple active web turns`);
|
|
6974
|
-
const turnId = active[0]?.turnId;
|
|
6975
|
-
if (!turnId) return void 0;
|
|
6976
|
-
const record = await getTurnRecord(conversationId, turnId);
|
|
6977
|
-
return record && (record.source?.kind === "web" || !record.source && record.surface === "api") && !record.dispatchId && (record.state === "paused" || record.state === "running") ? turnId : void 0;
|
|
7154
|
+
// src/chat/child-agents/child-input.ts
|
|
7155
|
+
const parent = alias(juniorConversations, "parent");
|
|
7156
|
+
function childAgentInputKind(namespace, eventType, watchId) {
|
|
7157
|
+
if (namespace !== "junior" || !eventType) return;
|
|
7158
|
+
if (eventType === "agent.message") return "message";
|
|
7159
|
+
return isAgentUpdateEventType(eventType) && watchId === void 0 ? "reply" : void 0;
|
|
6978
7160
|
}
|
|
6979
|
-
/**
|
|
6980
|
-
|
|
6981
|
-
const
|
|
6982
|
-
|
|
6983
|
-
const
|
|
6984
|
-
|
|
6985
|
-
|
|
6986
|
-
|
|
6987
|
-
|
|
7161
|
+
/** Read the child that one reply or message Event names. */
|
|
7162
|
+
function childAgentInput(message) {
|
|
7163
|
+
const metadata = message.input.metadata;
|
|
7164
|
+
if (!isEventMailboxMetadata(metadata)) return;
|
|
7165
|
+
const kind = childAgentInputKind(metadata.event.namespace, metadata.event.eventType, metadata.event.subscriptionId);
|
|
7166
|
+
return kind ? {
|
|
7167
|
+
kind,
|
|
7168
|
+
senderId: metadata.event.identifier
|
|
7169
|
+
} : void 0;
|
|
6988
7170
|
}
|
|
6989
7171
|
/**
|
|
6990
|
-
*
|
|
6991
|
-
*
|
|
6992
|
-
*
|
|
7172
|
+
* Whether one input is the `stopped` result that the stop of its sender
|
|
7173
|
+
* sends. Only a stop reports `stopped`, so the stored status tells this
|
|
7174
|
+
* result from the reply of a Turn.
|
|
6993
7175
|
*/
|
|
6994
|
-
|
|
6995
|
-
const
|
|
6996
|
-
|
|
6997
|
-
const stored = await getStoredTurnFields(summaries);
|
|
6998
|
-
const sources = new Map(conversationIds.map((conversationId) => [conversationId, []]));
|
|
6999
|
-
await Promise.all(summaries.map((summary, index) => limit(async () => {
|
|
7000
|
-
const fields = stored[index];
|
|
7001
|
-
const turn = fields && !fields.source && fields.surface !== "api" ? await getTurnRecord(summary.conversationId, summary.turnId) : fields;
|
|
7002
|
-
if (turn && isActiveMailboxTurn(turn)) sources.get(summary.conversationId)?.push(turn.source);
|
|
7003
|
-
})));
|
|
7004
|
-
return sources;
|
|
7176
|
+
function isStopResult(message) {
|
|
7177
|
+
const metadata = message.input.metadata;
|
|
7178
|
+
return isEventMailboxMetadata(metadata) && metadata.event.namespace === "junior" && isAgentUpdateEventType(metadata.event.eventType) && metadata.event.status === "stopped";
|
|
7005
7179
|
}
|
|
7006
|
-
|
|
7007
|
-
|
|
7180
|
+
/**
|
|
7181
|
+
* Whether the saved Event fields of a Turn's input Message name a child
|
|
7182
|
+
* agent's reply or message. A new and a resumed Turn read the same fields.
|
|
7183
|
+
*/
|
|
7184
|
+
function isChildAgentEvent(meta) {
|
|
7185
|
+
return Boolean(childAgentInputKind(meta?.eventNamespace, meta?.eventType, meta?.eventWatchId));
|
|
7008
7186
|
}
|
|
7009
|
-
|
|
7010
|
-
|
|
7187
|
+
/**
|
|
7188
|
+
* Return the stored parent edge that a parent message claims, or undefined
|
|
7189
|
+
* when its author id is not that parent's, so it is dropped with no read.
|
|
7190
|
+
*/
|
|
7191
|
+
function claimedParentEdge(message, parentMessage) {
|
|
7192
|
+
return hasParentMessageAuthor(message, parentMessage) ? parentEdgeKey(message.conversationId, parentMessage.parentConversationId) : void 0;
|
|
7011
7193
|
}
|
|
7012
|
-
|
|
7013
|
-
|
|
7014
|
-
const active = await listActiveMailboxTurns(conversationId);
|
|
7015
|
-
if (active.length > 1) throw new Error(`Conversation ${conversationId} has multiple active mailbox Turns`);
|
|
7016
|
-
return active[0]?.turnId;
|
|
7194
|
+
function parentEdgeKey(childConversationId, parentConversationId) {
|
|
7195
|
+
return JSON.stringify([childConversationId, parentConversationId]);
|
|
7017
7196
|
}
|
|
7018
|
-
/**
|
|
7019
|
-
|
|
7020
|
-
|
|
7021
|
-
|
|
7022
|
-
|
|
7023
|
-
|
|
7197
|
+
/**
|
|
7198
|
+
* Return the child that sent a reply that a stop can skip. A message that a
|
|
7199
|
+
* child sent is still delivered, and so is the `stopped` result that a
|
|
7200
|
+
* person's stop sends.
|
|
7201
|
+
*/
|
|
7202
|
+
function skippableReplySender(message) {
|
|
7203
|
+
if (childAgentInput(message)?.kind !== "reply" || isStopResult(message)) return;
|
|
7204
|
+
return readInboundMessageSender(message)?.conversationId;
|
|
7024
7205
|
}
|
|
7025
|
-
/**
|
|
7026
|
-
|
|
7027
|
-
|
|
7206
|
+
/**
|
|
7207
|
+
* Read the stops that `isDroppedChildInput` needs for many inputs, with one
|
|
7208
|
+
* query for the receiving children and one for the reply senders.
|
|
7209
|
+
*/
|
|
7210
|
+
async function readChildInputDropFacts(messages) {
|
|
7211
|
+
const childIds = /* @__PURE__ */ new Set();
|
|
7212
|
+
const parentIds = /* @__PURE__ */ new Set();
|
|
7213
|
+
const senderIds = /* @__PURE__ */ new Set();
|
|
7214
|
+
for (const message of messages) {
|
|
7215
|
+
const parentMessage = readParentMessage(message);
|
|
7216
|
+
if (parentMessage) {
|
|
7217
|
+
if (claimedParentEdge(message, parentMessage)) {
|
|
7218
|
+
childIds.add(message.conversationId);
|
|
7219
|
+
parentIds.add(parentMessage.parentConversationId);
|
|
7220
|
+
}
|
|
7221
|
+
continue;
|
|
7222
|
+
}
|
|
7223
|
+
const sender = skippableReplySender(message);
|
|
7224
|
+
if (sender) senderIds.add(sender);
|
|
7225
|
+
}
|
|
7226
|
+
const db = getSqlExecutor().db();
|
|
7227
|
+
const [children, senders] = await Promise.all([childIds.size > 0 ? db.select({
|
|
7228
|
+
conversationId: juniorConversations.conversationId,
|
|
7229
|
+
parentConversationId: parent.conversationId,
|
|
7230
|
+
stoppedAt: juniorConversations.stoppedAt
|
|
7231
|
+
}).from(juniorConversations).innerJoin(parent, eq(parent.conversationId, juniorConversations.parentConversationId)).where(and(inArray(juniorConversations.conversationId, [...childIds]), inArray(parent.conversationId, [...parentIds]))) : [], senderIds.size > 0 ? db.select({
|
|
7232
|
+
conversationId: juniorConversations.conversationId,
|
|
7233
|
+
stoppedAt: juniorConversations.stoppedAt
|
|
7234
|
+
}).from(juniorConversations).where(inArray(juniorConversations.conversationId, [...senderIds])) : []]);
|
|
7028
7235
|
return {
|
|
7029
|
-
|
|
7030
|
-
|
|
7031
|
-
userId: actor.userId,
|
|
7032
|
-
...actor.userName ? { userName: actor.userName } : void 0
|
|
7236
|
+
childStops: new Map(children.map((row) => [parentEdgeKey(row.conversationId, row.parentConversationId), row.stoppedAt])),
|
|
7237
|
+
senderStops: new Map(senders.flatMap((row) => row.stoppedAt ? [[row.conversationId, row.stoppedAt]] : []))
|
|
7033
7238
|
};
|
|
7034
7239
|
}
|
|
7035
|
-
|
|
7036
|
-
|
|
7037
|
-
|
|
7038
|
-
|
|
7039
|
-
|
|
7040
|
-
|
|
7041
|
-
|
|
7042
|
-
|
|
7043
|
-
|
|
7044
|
-
|
|
7045
|
-
|
|
7046
|
-
|
|
7047
|
-
|
|
7048
|
-
|
|
7049
|
-
|
|
7050
|
-
|
|
7051
|
-
|
|
7240
|
+
/**
|
|
7241
|
+
* Return whether a Conversation drops one input, so it starts no work. Routing
|
|
7242
|
+
* and child status both read it, so they agree. `facts` are from
|
|
7243
|
+
* `readChildInputDropFacts`. A parent message is dropped when it is not from
|
|
7244
|
+
* the stored parent, or was sent before the child's stop. A stop drops unread
|
|
7245
|
+
* replies from the parent's mailbox. One sent before the stop can reach the
|
|
7246
|
+
* mailbox after that drop, so while the sending child is stopped, a reply that
|
|
7247
|
+
* it sent after the stop is dropped too. A stopped Conversation never reads
|
|
7248
|
+
* other automated input: `enqueueAutomatedInput` and the stop hold it first.
|
|
7249
|
+
*/
|
|
7250
|
+
function isDroppedChildInput(message, facts) {
|
|
7251
|
+
if (isPersonInput(message.source)) return false;
|
|
7252
|
+
const parentMessage = readParentMessage(message);
|
|
7253
|
+
if (parentMessage) {
|
|
7254
|
+
const edge = claimedParentEdge(message, parentMessage);
|
|
7255
|
+
if (!edge || !facts.childStops.has(edge)) return true;
|
|
7256
|
+
const stoppedAtMs = facts.childStops.get(edge)?.getTime();
|
|
7257
|
+
return stoppedAtMs !== void 0 && message.receivedAtMs <= stoppedAtMs;
|
|
7258
|
+
}
|
|
7259
|
+
const sender = skippableReplySender(message);
|
|
7260
|
+
const senderStoppedAtMs = sender ? facts.senderStops.get(sender)?.getTime() : void 0;
|
|
7261
|
+
return senderStoppedAtMs !== void 0 && message.createdAtMs >= senderStoppedAtMs;
|
|
7262
|
+
}
|
|
7263
|
+
/**
|
|
7264
|
+
* Read the sender of one child Conversation from its parent edge and its
|
|
7265
|
+
* binding. A Conversation without a parent has none.
|
|
7266
|
+
*/
|
|
7267
|
+
async function readChildConversationSender(childConversationId) {
|
|
7268
|
+
const [row] = await getSqlExecutor().db().select({
|
|
7269
|
+
agentName: juniorAgentBindings.name,
|
|
7270
|
+
parentConversationId: parent.conversationId,
|
|
7271
|
+
parentKind: parent.kind,
|
|
7272
|
+
title: juniorConversations.title
|
|
7273
|
+
}).from(juniorConversations).innerJoin(parent, eq(parent.conversationId, juniorConversations.parentConversationId)).leftJoin(juniorAgentBindings, eq(juniorAgentBindings.childConversationId, juniorConversations.conversationId)).where(eq(juniorConversations.conversationId, childConversationId));
|
|
7274
|
+
return row ? {
|
|
7275
|
+
...row.agentName ? { agentName: row.agentName } : void 0,
|
|
7276
|
+
childConversationId,
|
|
7277
|
+
parentConversationId: row.parentConversationId,
|
|
7278
|
+
...row.parentKind ? { parentKind: row.parentKind } : void 0,
|
|
7279
|
+
...row.title ? { title: row.title } : void 0
|
|
7280
|
+
} : void 0;
|
|
7281
|
+
}
|
|
7282
|
+
/**
|
|
7283
|
+
* Read the sender of one reply or message, when it is a child of the
|
|
7284
|
+
* Conversation that received it. Input that names no child of this
|
|
7285
|
+
* Conversation has no sender, so `withSenderActors` runs it as the Event
|
|
7286
|
+
* system Actor and it gets no child's authority.
|
|
7287
|
+
*/
|
|
7288
|
+
async function getChildAgentInputSender(message, input) {
|
|
7289
|
+
const sender = await readChildConversationSender(input.senderId);
|
|
7290
|
+
return sender?.parentConversationId === message.conversationId ? sender : void 0;
|
|
7291
|
+
}
|
|
7292
|
+
// src/chat/child-agents/sender-actors.ts
|
|
7293
|
+
const senderActorMetadataSchema = z.object({ actor: actorSchema });
|
|
7294
|
+
/**
|
|
7295
|
+
* Return the Inbound message author id for results sent by one Actor.
|
|
7296
|
+
* `selectContiguousTurnBatch` in `task-execution/worker.ts` puts messages in
|
|
7297
|
+
* one attempt only when their author ids and sources match. Mid-Turn drains
|
|
7298
|
+
* take only `interrupt` messages, and results are `defer`. So results never
|
|
7299
|
+
* share a Turn and its credentials with another Actor or with watch Events.
|
|
7300
|
+
* Keep this id unique per Actor if either rule changes. The id is opaque.
|
|
7301
|
+
* It keeps the value that earlier releases wrote, because a queued result
|
|
7302
|
+
* from before a deploy is checked against it.
|
|
7303
|
+
*/
|
|
7304
|
+
function resultAuthorId(actor) {
|
|
7305
|
+
switch (actor.platform) {
|
|
7306
|
+
case "system": return `agent-invocation:system:${actor.name}`;
|
|
7307
|
+
case "slack": return `agent-invocation:slack:${actor.teamId}:${actor.userId}`;
|
|
7308
|
+
default: return `agent-invocation:${actor.platform}:${actor.userId}`;
|
|
7309
|
+
}
|
|
7310
|
+
}
|
|
7311
|
+
/** Read the Actor of the child Turn that a reply or message carries. */
|
|
7312
|
+
function senderActorFromMetadata(metadata) {
|
|
7313
|
+
const parsed = senderActorMetadataSchema.safeParse(metadata);
|
|
7314
|
+
return parsed.success ? parsed.data.actor : void 0;
|
|
7315
|
+
}
|
|
7316
|
+
/**
|
|
7317
|
+
* Run each child reply or message as the Actor of the child Turn that sent
|
|
7318
|
+
* it, which the input carries, so the parent never gets more authority than
|
|
7319
|
+
* that Turn. A parent message from the stored parent runs as the Actor of the
|
|
7320
|
+
* parent's Turn, with its grants and text. Input that a Turn with another
|
|
7321
|
+
* Actor sent, or that names no child of this Conversation, runs as the Event
|
|
7322
|
+
* system Actor. Input that `isDroppedChildInput` drops is left out. Returns
|
|
7323
|
+
* undefined when no input is left.
|
|
7324
|
+
*/
|
|
7325
|
+
async function withSenderActors(work) {
|
|
7326
|
+
if (work.kind !== "mailbox") return work;
|
|
7327
|
+
const dropFacts = await readChildInputDropFacts(work.batch.map((entry) => entry.message));
|
|
7328
|
+
const kept = (await mapBounded(work.batch, async (entry) => {
|
|
7329
|
+
const parentMessage = readParentMessage(entry.message);
|
|
7330
|
+
if (parentMessage) {
|
|
7331
|
+
if (isDroppedChildInput(entry.message, dropFacts)) {
|
|
7332
|
+
logDroppedParentMessage(entry.message, parentMessage);
|
|
7333
|
+
return;
|
|
7334
|
+
}
|
|
7335
|
+
const text = await parentMessageText(entry.message, parentMessage);
|
|
7336
|
+
return {
|
|
7337
|
+
...entry,
|
|
7338
|
+
actor: parentMessage.actor,
|
|
7339
|
+
requestText: entry.message.input.text.trim(),
|
|
7340
|
+
...parentMessage.credentialContext ? { credentialContext: parentMessage.credentialContext } : void 0,
|
|
7341
|
+
message: {
|
|
7342
|
+
...entry.message,
|
|
7343
|
+
input: {
|
|
7344
|
+
...entry.message.input,
|
|
7345
|
+
text
|
|
7346
|
+
}
|
|
7347
|
+
}
|
|
7348
|
+
};
|
|
7349
|
+
}
|
|
7350
|
+
const input = childAgentInput(entry.message);
|
|
7351
|
+
if (!input) return entry;
|
|
7352
|
+
if (isDroppedChildInput(entry.message, dropFacts)) return;
|
|
7353
|
+
const sender = await getChildAgentInputSender(entry.message, input);
|
|
7354
|
+
const actor = senderActorFromMetadata(entry.message.input.metadata);
|
|
7355
|
+
if (!sender || !actor || entry.message.input.authorId !== resultAuthorId(actor)) return {
|
|
7356
|
+
...entry,
|
|
7357
|
+
actor: EVENT_SYSTEM_ACTOR
|
|
7052
7358
|
};
|
|
7053
7359
|
return {
|
|
7054
|
-
|
|
7055
|
-
|
|
7056
|
-
message: entry.message,
|
|
7057
|
-
source: createWebSource(entry.message.conversationId)
|
|
7360
|
+
...entry,
|
|
7361
|
+
actor
|
|
7058
7362
|
};
|
|
7059
|
-
});
|
|
7363
|
+
})).filter((entry) => entry !== void 0);
|
|
7364
|
+
return kept.length > 0 ? {
|
|
7365
|
+
kind: "mailbox",
|
|
7366
|
+
batch: kept
|
|
7367
|
+
} : void 0;
|
|
7368
|
+
}
|
|
7369
|
+
// src/chat/child-agents/list.ts
|
|
7370
|
+
const childConversationKindSchema = z.enum(["thread", "task"]);
|
|
7371
|
+
/** Bound the child agents that one listing reads. */
|
|
7372
|
+
const CHILD_AGENT_LIST_LIMIT = 200;
|
|
7373
|
+
/**
|
|
7374
|
+
* List the direct child agents of one parent Conversation, with the newest
|
|
7375
|
+
* activity first. The state comes from each child's Turns and mailbox, not
|
|
7376
|
+
* from model output. Each child agent stores its agent config, so older
|
|
7377
|
+
* children of a parent, such as ones that a removed feature created, are not
|
|
7378
|
+
* listed. A child is `stopped` while stopped, `running` while a Turn or
|
|
7379
|
+
* mailbox input that answers its parent is open, `failed` when its stored
|
|
7380
|
+
* execution failed, such as when its worker gave up and no Turn ended, and
|
|
7381
|
+
* else `idle`.
|
|
7382
|
+
* `lastResult` is how its newest finished Turn that was not stopped ended:
|
|
7383
|
+
* the status that `readTurnUpdate` gives it, or `failed`.
|
|
7384
|
+
*/
|
|
7385
|
+
async function listChildAgents(parentConversationId) {
|
|
7386
|
+
const rows = await getSqlExecutor().db().select({
|
|
7387
|
+
agentName: juniorAgentBindings.name,
|
|
7388
|
+
archivedAt: juniorConversations.archivedAt,
|
|
7389
|
+
conversationId: juniorConversations.conversationId,
|
|
7390
|
+
executionStatus: juniorConversations.executionStatus,
|
|
7391
|
+
executionUpdatedAt: juniorConversations.executionUpdatedAt,
|
|
7392
|
+
kind: juniorConversations.kind,
|
|
7393
|
+
lastTurnOutcome: conversationLastTurnOutcomeSql(juniorConversations),
|
|
7394
|
+
stoppedAt: juniorConversations.stoppedAt,
|
|
7395
|
+
title: juniorConversations.title,
|
|
7396
|
+
updatedAt: juniorConversations.updatedAt
|
|
7397
|
+
}).from(juniorConversations).leftJoin(juniorAgentBindings, eq(juniorAgentBindings.childConversationId, juniorConversations.conversationId)).where(and(eq(juniorConversations.parentConversationId, parentConversationId), isNotNull(juniorConversations.agentConfig))).orderBy(desc(sql`coalesce(${juniorConversations.executionUpdatedAt}, ${juniorConversations.updatedAt})`)).limit(CHILD_AGENT_LIST_LIMIT);
|
|
7398
|
+
const ids = rows.map((row) => row.conversationId);
|
|
7399
|
+
const [workStates, mailboxTurnSources] = await Promise.all([getConversationWorkStates(ids), listActiveMailboxTurnSources(ids)]);
|
|
7400
|
+
const pendingInput = (conversationId) => workStates.get(conversationId)?.execution.pendingMessages ?? [];
|
|
7401
|
+
const dropFacts = await readChildInputDropFacts(rows.flatMap((row) => row.stoppedAt ? [] : pendingInput(row.conversationId)));
|
|
7402
|
+
return rows.map((row) => {
|
|
7403
|
+
const kind = childConversationKindSchema.parse(row.kind);
|
|
7404
|
+
const stoppedAtMs = row.stoppedAt?.getTime();
|
|
7405
|
+
const running = stoppedAtMs === void 0 && runsOnConversationLoop(pendingInput(row.conversationId), mailboxTurnSources.get(row.conversationId) ?? [], dropFacts);
|
|
7406
|
+
const outcome = row.lastTurnOutcome;
|
|
7407
|
+
const lastResult = outcome === "failed" ? "failed" : outcome ? TURN_OUTCOME_STATUSES[outcome] : void 0;
|
|
7408
|
+
return {
|
|
7409
|
+
...row.agentName ? { agentName: row.agentName } : void 0,
|
|
7410
|
+
...row.archivedAt ? { archivedAtMs: row.archivedAt.getTime() } : void 0,
|
|
7411
|
+
childConversationId: row.conversationId,
|
|
7412
|
+
kind,
|
|
7413
|
+
...lastResult ? { lastResult } : void 0,
|
|
7414
|
+
status: stoppedAtMs !== void 0 ? "stopped" : running ? "running" : row.executionStatus === "failed" ? "failed" : "idle",
|
|
7415
|
+
...row.title ? { title: row.title } : void 0,
|
|
7416
|
+
updatedAtMs: (row.executionUpdatedAt ?? row.updatedAt).getTime()
|
|
7417
|
+
};
|
|
7418
|
+
}).sort((left, right) => right.updatedAtMs - left.updatedAtMs);
|
|
7419
|
+
}
|
|
7420
|
+
/** List the ids of the child agents of one parent that have open work. */
|
|
7421
|
+
async function listOpenChildAgents(parentConversationId) {
|
|
7422
|
+
return (await listChildAgents(parentConversationId)).filter((child) => child.status === "running").map((child) => child.childConversationId);
|
|
7060
7423
|
}
|
|
7061
|
-
/** Extra debounce time added per additional event already batched. */
|
|
7062
|
-
const EVENT_WAIT_PER_EXTRA_MESSAGE_MS = 5e3;
|
|
7063
|
-
/** Upper bound on the debounce window regardless of batch size. */
|
|
7064
|
-
const EVENT_MAX_WAIT_MS = 6e4;
|
|
7065
7424
|
/**
|
|
7066
|
-
* Return
|
|
7067
|
-
*
|
|
7068
|
-
*
|
|
7069
|
-
*
|
|
7070
|
-
* EVENT_MAX_WAIT_MS, so later events in the same burst land in this batch.
|
|
7071
|
-
* Returns 0 when the batch can run now or does not start with an event.
|
|
7425
|
+
* Return whether a child has work that will answer its parent: `pending`
|
|
7426
|
+
* input that waits in the mailbox until its Turn commits it, such as a Watch
|
|
7427
|
+
* Event in its debounce window, or an open mailbox Turn. Every Turn of a
|
|
7428
|
+
* child answers its parent, whoever started it.
|
|
7072
7429
|
*/
|
|
7073
|
-
function
|
|
7074
|
-
|
|
7075
|
-
if (!first || !isEventMailboxMetadata(first.input.metadata)) return 0;
|
|
7076
|
-
const waitMs = Math.min(EVENT_MAX_WAIT_MS, EVENT_WAIT_MS + EVENT_WAIT_PER_EXTRA_MESSAGE_MS * (messages.length - 1));
|
|
7077
|
-
return Math.max(0, first.receivedAtMs + waitMs - nowMs);
|
|
7430
|
+
function runsOnConversationLoop(pending, mailboxTurnSources, dropFacts) {
|
|
7431
|
+
return mailboxTurnSources.length > 0 || pending.some((message) => !isDroppedChildInput(message, dropFacts));
|
|
7078
7432
|
}
|
|
7079
|
-
/**
|
|
7080
|
-
|
|
7081
|
-
|
|
7082
|
-
|
|
7083
|
-
|
|
7084
|
-
|
|
7085
|
-
|
|
7086
|
-
|
|
7087
|
-
|
|
7088
|
-
|
|
7089
|
-
|
|
7090
|
-
|
|
7091
|
-
|
|
7092
|
-
|
|
7093
|
-
|
|
7094
|
-
|
|
7095
|
-
};
|
|
7096
|
-
});
|
|
7433
|
+
/**
|
|
7434
|
+
* List the ids of a child's open Turns on the Conversation loop. A Turn keeps
|
|
7435
|
+
* its input in the mailbox until it commits it, so before its first
|
|
7436
|
+
* checkpoint its id comes from its first input. Attempt selection can take
|
|
7437
|
+
* any pending input first, so each one gives a candidate id.
|
|
7438
|
+
*/
|
|
7439
|
+
async function listOpenLoopTurnIds(conversationId) {
|
|
7440
|
+
const [turns, work] = await Promise.all([listActiveMailboxTurns(conversationId), getConversationWorkState({ conversationId })]);
|
|
7441
|
+
return [...turns.map((turn) => turn.turnId), ...(work?.execution.pendingMessages ?? []).map((message) => buildDeterministicTurnId(message.inboundMessageId))];
|
|
7442
|
+
}
|
|
7443
|
+
async function listAnsweredLoopChildren(children, parentMessages) {
|
|
7444
|
+
if (children.length === 0 || parentMessages.length === 0) return [];
|
|
7445
|
+
return (await mapBounded(children, async ({ childConversationId }) => {
|
|
7446
|
+
const turnIds = await listOpenLoopTurnIds(childConversationId);
|
|
7447
|
+
return parentMessages.some(({ sender }) => sender.conversationId === childConversationId && turnIds.includes(sender.turnId)) ? childConversationId : void 0;
|
|
7448
|
+
})).filter((id) => id !== void 0);
|
|
7097
7449
|
}
|
|
7098
7450
|
/**
|
|
7099
|
-
*
|
|
7100
|
-
*
|
|
7101
|
-
*
|
|
7451
|
+
* List the other child agents of one parent that still run and have not
|
|
7452
|
+
* answered. A running child whose open Turn's result is already among
|
|
7453
|
+
* `parentMessages`, the child replies and results that reached the parent's
|
|
7454
|
+
* mailbox, has answered, so it does not count.
|
|
7102
7455
|
*/
|
|
7103
|
-
function
|
|
7104
|
-
const
|
|
7105
|
-
|
|
7106
|
-
return
|
|
7107
|
-
const parentMessage = parentMessages[index];
|
|
7108
|
-
return {
|
|
7109
|
-
actor: parentMessage.actor,
|
|
7110
|
-
author: parentMessageAuthor(parentMessage.parentConversationId),
|
|
7111
|
-
...parentMessage.credentialContext ? { credentialContext: parentMessage.credentialContext } : void 0,
|
|
7112
|
-
message,
|
|
7113
|
-
source: { kind: "parent_message" }
|
|
7114
|
-
};
|
|
7115
|
-
});
|
|
7456
|
+
async function listUnreportedSiblingAgents(parentConversationId, childConversationId, parentMessages) {
|
|
7457
|
+
const running = (await listChildAgents(parentConversationId)).filter((child) => child.childConversationId !== childConversationId && child.status === "running");
|
|
7458
|
+
const answered = new Set(await listAnsweredLoopChildren(running, parentMessages));
|
|
7459
|
+
return running.filter((child) => !answered.has(child.childConversationId));
|
|
7116
7460
|
}
|
|
7117
7461
|
/**
|
|
7118
|
-
*
|
|
7119
|
-
*
|
|
7462
|
+
* List every child agent below one Conversation, at any depth. A parent owns
|
|
7463
|
+
* the work of its child agents and of their child agents. The list never has
|
|
7464
|
+
* the Conversation itself, its parent, or a sibling.
|
|
7120
7465
|
*/
|
|
7121
|
-
async function
|
|
7122
|
-
|
|
7123
|
-
|
|
7124
|
-
|
|
7125
|
-
|
|
7126
|
-
|
|
7127
|
-
|
|
7128
|
-
|
|
7129
|
-
|
|
7130
|
-
|
|
7131
|
-
|
|
7132
|
-
|
|
7133
|
-
|
|
7134
|
-
|
|
7135
|
-
|
|
7466
|
+
async function listDescendantAgents(conversationId) {
|
|
7467
|
+
return (await getSqlExecutor().db().select({
|
|
7468
|
+
conversationId: juniorConversations.conversationId,
|
|
7469
|
+
name: juniorAgentBindings.name
|
|
7470
|
+
}).from(juniorConversations).innerJoin(conversationSubtree([conversationId]), eq(conversationSubtreeColumns.conversationId, juniorConversations.conversationId)).leftJoin(juniorAgentBindings, eq(juniorAgentBindings.childConversationId, juniorConversations.conversationId)).where(ne(juniorConversations.conversationId, conversationId)).orderBy(juniorConversations.conversationId)).map((row) => ({
|
|
7471
|
+
conversationId: row.conversationId,
|
|
7472
|
+
...row.name ? { name: row.name } : void 0
|
|
7473
|
+
}));
|
|
7474
|
+
}
|
|
7475
|
+
/**
|
|
7476
|
+
* List the agents that one Conversation can see. A root Conversation sees
|
|
7477
|
+
* only its child agents. A child agent also sees itself, its parent, and the
|
|
7478
|
+
* other child agents of its parent.
|
|
7479
|
+
*/
|
|
7480
|
+
async function listAgentRelatives(input) {
|
|
7481
|
+
const { conversationId, parentConversationId } = input;
|
|
7482
|
+
const [children, family, parent] = await Promise.all([
|
|
7483
|
+
listChildAgents(conversationId),
|
|
7484
|
+
parentConversationId ? listChildAgents(parentConversationId) : [],
|
|
7485
|
+
parentConversationId ? getConversationStore().get({ conversationId: parentConversationId }) : void 0
|
|
7486
|
+
]);
|
|
7487
|
+
const self = family.find((agent) => agent.childConversationId === conversationId);
|
|
7488
|
+
return {
|
|
7489
|
+
children,
|
|
7490
|
+
...parent ? { parent: {
|
|
7491
|
+
conversationId: parent.conversationId,
|
|
7492
|
+
status: parent.execution.status,
|
|
7493
|
+
updatedAtMs: parent.execution.updatedAtMs ?? parent.updatedAtMs
|
|
7494
|
+
} } : void 0,
|
|
7495
|
+
...self ? { self } : void 0,
|
|
7496
|
+
siblings: family.filter((agent) => agent.childConversationId !== conversationId)
|
|
7136
7497
|
};
|
|
7137
|
-
if (context.attempt.messages.length > 0) return;
|
|
7138
|
-
const turnId = await getActiveMailboxTurnId(context.conversationId);
|
|
7139
|
-
return turnId ? {
|
|
7140
|
-
kind: "resume",
|
|
7141
|
-
turnId
|
|
7142
|
-
} : void 0;
|
|
7143
7498
|
}
|
|
7144
|
-
|
|
7499
|
+
// src/chat/child-agents/markers.ts
|
|
7500
|
+
const SUBAGENT_KIND = "agent";
|
|
7501
|
+
const SUBAGENT_STARTED_KEY_PREFIX = "subagent_started:";
|
|
7502
|
+
const SUBAGENT_ENDED_KEY_PREFIX = "subagent_ended:";
|
|
7503
|
+
/**
|
|
7504
|
+
* Record in the parent Conversation that a child agent got one task or
|
|
7505
|
+
* message. Write it before the input reaches the child's mailbox, so the
|
|
7506
|
+
* child cannot end first.
|
|
7507
|
+
*/
|
|
7508
|
+
async function recordSubagentStartedMarker(start) {
|
|
7509
|
+
await getConversationEventStore().append(start.parentConversationId, [{
|
|
7510
|
+
idempotencyKey: `${SUBAGENT_STARTED_KEY_PREFIX}${start.markerId}`,
|
|
7511
|
+
data: {
|
|
7512
|
+
type: "subagent_started",
|
|
7513
|
+
subagentInvocationId: start.markerId,
|
|
7514
|
+
subagentKind: SUBAGENT_KIND,
|
|
7515
|
+
childConversationId: start.childConversationId,
|
|
7516
|
+
...start.agentName ? { agentName: start.agentName } : void 0,
|
|
7517
|
+
parentToolCallId: start.parentToolCallId,
|
|
7518
|
+
task: start.input,
|
|
7519
|
+
...start.title ? { title: start.title } : void 0,
|
|
7520
|
+
...start.reasoningLevel ? { reasoningLevel: start.reasoningLevel } : void 0
|
|
7521
|
+
},
|
|
7522
|
+
createdAtMs: start.createdAtMs
|
|
7523
|
+
}]);
|
|
7524
|
+
}
|
|
7525
|
+
/**
|
|
7526
|
+
* Record in the parent Conversation how the work of a child agent ended.
|
|
7527
|
+
* Each parent message has its own `subagent_started` marker, named by the
|
|
7528
|
+
* message id, and each one that the child already took ends with `outcome`.
|
|
7529
|
+
* A parent message that still waits in the child's mailbox stays open,
|
|
7530
|
+
* because later work reads it, unless `includeWaiting` is set, as for a stop
|
|
7531
|
+
* that skips it. Write it before the child's result reaches the parent.
|
|
7532
|
+
*/
|
|
7533
|
+
async function recordChildAgentEnded(childConversationId, outcome, options = {}) {
|
|
7534
|
+
if (!await readAgentConfig(childConversationId)) return;
|
|
7535
|
+
const work = await getConversationWorkState({
|
|
7536
|
+
conversationId: childConversationId,
|
|
7537
|
+
state: options.state
|
|
7538
|
+
});
|
|
7539
|
+
const running = new Set(work?.runningInboundMessageIds);
|
|
7540
|
+
const waiting = new Set(options.includeWaiting ? [] : (work?.messages ?? []).map((message) => message.inboundMessageId).filter((id) => !running.has(id)));
|
|
7541
|
+
const taken = (work?.execution.inboundMessageIds ?? []).filter((id) => !waiting.has(id));
|
|
7542
|
+
if (taken.length === 0) return;
|
|
7543
|
+
const sender = await readChildConversationSender(childConversationId);
|
|
7544
|
+
if (!sender) return;
|
|
7545
|
+
const keys = await getSqlExecutor().db().select({ idempotencyKey: juniorConversationEvents.idempotencyKey }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, sender.parentConversationId), inArray(juniorConversationEvents.idempotencyKey, taken.flatMap((id) => [`${SUBAGENT_STARTED_KEY_PREFIX}${id}`, `${SUBAGENT_ENDED_KEY_PREFIX}${id}`]))));
|
|
7546
|
+
const found = new Set(keys.map((row) => row.idempotencyKey));
|
|
7547
|
+
const open = taken.filter((id) => found.has(`${SUBAGENT_STARTED_KEY_PREFIX}${id}`) && !found.has(`${SUBAGENT_ENDED_KEY_PREFIX}${id}`));
|
|
7548
|
+
if (open.length > 0) await appendSubagentEnded(sender.parentConversationId, open, outcome, options.nowMs ?? Date.now());
|
|
7549
|
+
}
|
|
7550
|
+
async function appendSubagentEnded(parentConversationId, markerIds, outcome, createdAtMs) {
|
|
7551
|
+
await getConversationEventStore().append(parentConversationId, markerIds.map((id) => ({
|
|
7552
|
+
idempotencyKey: `${SUBAGENT_ENDED_KEY_PREFIX}${id}`,
|
|
7553
|
+
data: {
|
|
7554
|
+
type: "subagent_ended",
|
|
7555
|
+
subagentInvocationId: id,
|
|
7556
|
+
outcome
|
|
7557
|
+
},
|
|
7558
|
+
createdAtMs
|
|
7559
|
+
})));
|
|
7560
|
+
}
|
|
7561
|
+
export { createWebAuthorization as $, normalizeConversationText as $n, reviewToolActions as $r, getWorkspaceByName as $t, getConversationStoppedAtMs as A, loadTurnProjection as An, recordTurnSummary as Ar, withoutSavedSteeringMessages as At, sourceFromTurnInput as B, recordToolExecutionStarted as Bn, createTurnLimitGate as Br, getConversationTurnBoundaryError as Bt, getAgentReplyMessageId as C, withAgentRequest as Cn, pauseLostWorkerTurn as Cr, assemblePrompt as Ct, isInheritedForkHistory as D, loadConnectedMcpProviders as Dn, failTurnRecord as Dr, instructionForInputs as Dt, getSpawnedChildConversationId as E, commitMessages as En, completeTurnRecord as Er, instructionActorFor as Et, completeCancelledConversationTurn as F, recordAuthorizationRequested as Fn, TURN_LIMIT_WRAP_UP_MESSAGE as Fr, addConversationNote as Ft, getTurnUserReplyAttachmentContext as G, resolveConversationTitle as Gn, getAgentTurnDiagnosticsAttributes as Gr, markTurnCompleted as Gt, legacyWebMailboxMetadataSchema as H, hydrateConversationMessages as Hn, buildTurnFailureResponse as Hr, isTurnInputCommitLostError as Ht, getAuthPausedConversationTurnId as I, recordGuardianActionReviewed as In, TurnBudgetExceededError as Ir, ConversationTurnBoundaryError as It, getPersistedSandboxState as J, estimateConversationMessagesTokens as Jn, isCutOffStopReason as Jr, buildDeterministicAssistantMessageId as Jt, getTurnUserSlackMessageTs as K, settleConversationTitleWork as Kn, requireTurnFailureEventId as Kr, markTurnFailed as Kt, getEventBatchDelayMs as L, recordMcpProviderConnected as Ln, TurnSliceLimitExceededError as Lr, CooperativeTurnYieldError as Lt, saveHeldInput as M, recordAttachmentsDelivered as Mn, getTurnLifecycle as Mr, renderTaskInput as Mt, session_stop_exports as N, recordAuthenticationLinked as Nn, loadTurnStart as Nr, readUserCustomization as Nt, notInheritedByForkChild as O, loadConversationProjection as On, getTurnRecord as Or, loadPromptTurnContext as Ot, stopConversationTree as P, recordAuthorizationCompleted as Pn, GATED_TURN_LIMIT_WRAP_UP_MESSAGE as Pr, saveUserCustomization as Pt, coerceThreadConversationState as Q, markConversationMessage as Qn, createToolActionReview as Qr, getWorkspace as Qt, listActiveMailboxTurns as R, recordSkillLoaded as Rn, TurnToolCallLimitExceededError as Rr, TurnInputCommitLostError as Rt, getAgentMessageId as S, readAgentHistory as Sn, lostWorkerBeforeFirstSave as Sr, loadThreadContextTrimFloor as St, getPersonStopTurnId as T, commitAcceptedReply as Tn, abandonTurnRecord as Tr, buildSteeringPiMessage as Tt, getTurnUserMessage as U, persistConversationMessageWindow as Un, captureTurnFailure as Ur, isTurnInputDeferredError as Ut, turnInputFactsFromConversationMessage as V, appendConversationMessages as Vn, isTurnExecutionLimitExceededError as Vr, isCooperativeTurnYieldError as Vt, getTurnUserMessageId as W, persistConversationMessages as Wn, finalizeFailedTurnReplyWithEvent as Wr, markTurnClosed as Wt, persistThreadRuntimeState as X, isHumanConversationMessage as Xn, ToolActionReviewLimitError as Xr, createWorkspace as Xt, getPersistedThreadState as Y, getConversationMessageSlackTs as Yn, ToolActionRejectedError as Yr, buildDeterministicTurnId as Yt, persistThreadStateById as Z, latestConversationMessageSeq as Zn, ToolActionReviewUnavailableError as Zr, deleteWorkspace as Zt, dropWaitingParentMessages as _, readRepositoryInstructions as _n, canReusePendingAuthLink as _r, resolveEventAuthor as _t, listDescendantAgents as a, CODEMODE_TOOL_NAME as ai, tryWorkspaceRepoCheckoutPath as an, calculateContextCompactionTargetTokens as ar, EVENT_WAIT_MS as at, agentConfigSchema as b, foldLeadingSystemMessages as bn, continuableMessages as br, withHeldInput as bt, resultAuthorId as c, deliverOAuthAuthorization as ci, loadSnapshotsForProfile as cn, getAgentContextInputLimitTokens as cr, enqueueEventNotification as ct, isStopResult as d, startOAuthFlow as di, isExperimentalFeatureEnabled as dn, createPluginAuthOrchestration as dr, timerWatchCredentialSubject as dt, getToolActionRejectionMarker as ei, listWorkspaceNamesByRepository as en, recordDeliveredAssistantMessage as er, deleteWebAuthorization as et, readChildConversationSender as f, projectConversationEvents as fi, buildDeploymentSystemPrompt as fn, authorizationId as fr, eventAuthorText as ft, commitParentMessageFork as g, findVisibleAgentsInstructions as gn, abandonReplacedPendingAuth as gr, parseEmail as gt, childAgentTurnOptions as h, configValueSchema as hi, buildAgentsInstructionsMessage as hn, AuthorizationPauseError as hr, isTrustedSlackAuthor as ht, listChildAgents as i, USER_AUTHORIZATION_LEVELS as ii, WorkspaceValidationError as in, upsertConversationMessage as ir, savedInputInstruction as it, resumeForPersonInput as j, recordAgentsInstructionsUpdated as jn, ConversationTurnLifecycleService as jr, readTaskInstructions as jt, enqueueAutomatedInput as k, loadConversationSkillNames as kn, listTurnSummaries as kr, turnRequestText as kt, withSenderActors as l, formatProviderLabel as li, setWorkspaceSnapshot as ln, createPluginEgress as lr, eventBatchMessageMeta as lt, buildParentMessage as m, validateConfigValue as mi, AGENTS_REPLACEMENT_NOTICE as mn, AuthorizationFlowDisabledError as mr, isAllowedDomain as mt, recordSubagentStartedMarker as n, RISK_LEVELS as ni, listWorkspacesByRepository as nn, trimConversationMessages as nr, eventInboxItemInputs as nt, listOpenChildAgents as o, CODE_MODE_CALL_STATUS_TEXT as oi, workspaceRepoCheckoutPath as on, getAgentBackgroundCompactionMarkTokens as or, addQuietEventNote as ot, appendParentMessage as p, validateConfigKey as pi, AGENTS_REMOVAL_NOTICE as pn, AuthPausePersistenceError as pr, findTrustedUser as pt, getLocationConfigurationService as q, conversationAuthorDisplayName as qn, buildTurnResult as qr, startActiveTurn as qt, listAgentRelatives as r, ROOT_LINE_BREAK as ri, updateWorkspace as rn, turnHasReply as rr, loadInboxItemInput as rt, listUnreportedSiblingAgents as s, persistWithRetry as si, invalidateReadySnapshot as sn, getAgentContextCompactionTriggerTokens as sr, createEventInboundMessage as st, recordChildAgentEnded as t, restoreToolActionRejections as ti, listWorkspaces as tn, renderConversationMessageLine as tr, getWebAuthorization as tt, isChildAgentEvent as u, parseOAuthStatePayload as ui, setWorkspaceSnapshotBuild as un, PluginCredentialFailureError as ur, renderEventBatchInputs as ut, isParentMessageAuthor as v, renderAgentsInstructions as vn, clearPendingAuth as vr, resolveBotSlackTeamId as vt, getChildAgentLockName as w, writeAgentHistory as wn, saveTurnCheckpoint as wr, buildPromptInput as wt, readAgentConfig as x, foldSystemMessages as xn, loadTurnCheckpoint as xr, loadThreadContextCursor as xt, readLastParentMessageAtMs as y, showsAgentsInstructions as yn, getConversationPendingAuth as yr, isHeldInputMessage as yt, resolveMailboxTurnWork as z, recordSubscribedReplyRoute as zn, buildTurnErrorResponse as zr, TurnInputDeferredError as zt };
|