@sentry/junior 0.315.0 → 0.317.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/{admin-5jUYY46p.js → admin-CAugg87B.js} +1 -1
- package/dist/{agent-runner-C7GNLRB6.js → agent-runner-AjrEV6Qe.js} +13532 -12811
- package/dist/{reporting-window-C4dbzDiR.js → agent-status-BA5x3Xtp.js} +33 -1
- package/dist/{agent-update-delivery-BNEYQsAf.js → agent-update-delivery-B_YIZcgf.js} +10 -37
- package/dist/api/schema.d.ts +609 -104
- package/dist/api/schema.js +6 -6
- package/dist/api.js +373 -469
- package/dist/{app-D_bAXRDe.d.ts → app-MoNAsVV5.d.ts} +52 -28
- package/dist/app.d.ts +1 -1
- package/dist/app.js +177 -132
- package/dist/catalog-runtime-DfSpJZdY.js +6 -0
- package/dist/{change-record-Bqsa5ZXE.d.ts → change-record-BzJgLsv7.d.ts} +60 -1
- package/dist/{adapter-context-BlSGE44V.js → channel-access-j-YAVYK4.js} +2 -42
- package/dist/{chat-core-engine-CxkwRpn9.js → chat-core-engine-aH85nEHv.js} +4 -3
- package/dist/{child-message--2G3Ft26.js → child-message-DHjQLEd1.js} +1 -1
- package/dist/cli/chat.js +23 -23
- package/dist/cli/check.js +5 -5
- package/dist/cli/main.js +2 -2
- package/dist/cli/plugins.js +5 -4
- package/dist/cli/snapshot-create.js +5 -2
- package/dist/cli/upgrade.js +27 -5
- package/dist/config-CHQ8X251.js +2422 -0
- package/dist/{continue-in-slack-BGKjIdFp.js → continue-in-slack-D-FZ8Fin.js} +2 -3
- package/dist/{conversation-feed-Sl8lKKmR.js → conversation-feed--9S0_PXL.js} +9 -4
- package/dist/{proxy-path-Dc-0jXGi.js → conversation-privacy-B1uXn5sf.js} +2 -16
- package/dist/{conversation-turn-BoLK9i6g.js → conversation-turn-BUE_7xaN.js} +102 -172
- package/dist/{create-BOycVH9h.js → create-DoDIYgtZ.js} +12 -10
- package/dist/{credential-sync-Mn4OdkEh.js → credential-sync-BJOqGnjV.js} +17 -12
- package/dist/{db-DXTOYRzR.js → db-BFmyYZtJ.js} +20276 -27398
- package/dist/{deployment-CG3TchWh.js → deployment-DXq9ZLU4.js} +17 -15
- package/dist/{engine-context-dyWlfNdD.js → engine-context-CgQ7mlHt.js} +264 -50
- package/dist/{html-CfXEwl_h.js → html-B3VKTGbJ.js} +6 -2
- package/dist/instrumentation.js +15 -7
- package/dist/{job-runner-CySgpi9v.js → job-runner-A1lCkybD.js} +397 -22
- package/dist/{lineage-tRTOcrsL.js → lineage-Bktb0UcV.js} +1 -1
- package/dist/{list-DXBz8SYL.js → list-Bxvg5wXf.js} +260 -698
- package/dist/{logging-czs0nqLC.js → logging--smS7XRK.js} +2 -2
- package/dist/{mailbox-turn-79Nv1JXv.js → mailbox-turn-uSXhUFc9.js} +648 -2957
- package/dist/{message-BTox2Cmb.js → message-BNenhsmB.js} +12 -22
- package/dist/{model-input-IRGa98V7.js → model-input-BReSnwHp.js} +3 -3
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +20 -6
- package/dist/{oauth-callback-server-NXK7AlBp.js → oauth-callback-server-CE4soEIY.js} +2 -2
- package/dist/{oauth-relay-6NBPSpFE.js → oauth-relay-C36gX1gH.js} +2 -2
- package/dist/{package-discovery-BI6T_RkD.js → package-discovery-DD9vencX.js} +1 -50
- package/dist/{parent-result-Dg6P6roR.js → parent-result-Ck1rFYRQ.js} +93 -106
- package/dist/{plugins-BXMdNdyA.js → plugins-D_Ru4CWc.js} +1 -1
- package/dist/profile-BQ-iBDsZ.js +4657 -0
- package/dist/{transcript-BHhJVY0P.js → prompt-Dv7gkpD6.js} +97 -103
- package/dist/proxy-path-BHYoKZdq.js +15 -0
- package/dist/registry-iXMT5Jmh.js +3279 -0
- package/dist/reports-WKHfGTsU.js +195 -0
- package/dist/{resolve-BUFkmxkT.js → resolve-tony4ibz.js} +9 -29
- package/dist/{result-DfATzX77.js → result-Bta_dlWa.js} +42 -117
- package/dist/run-conversation-DL6ru7iW.js +336 -0
- package/dist/{runner-CmKP3inb.js → runner-BstDRbD9.js} +7 -7
- package/dist/{sandbox-egress-signals-DYo5BsM7.js → sandbox-egress-signals-oSJMJOnn.js} +1 -1
- package/dist/{schema-DrBMdPmv.js → schema-DfqrHACA.js} +67 -84
- package/dist/sender-actors-CPglLd5R.js +83 -0
- package/dist/{service-account-CxTX7nnR.js → service-account-CTV_jaNu.js} +3 -1
- package/dist/{skills-BlHUDj7k.js → skills-BCEU41zM.js} +4 -4
- package/dist/{slack-conversation-unfurl-Dhe3lB1U.js → slack-conversation-unfurl-DxVmhbGP.js} +7 -6
- package/dist/{spawn-CfvlFdfz.js → spawn-frczVPIr.js} +11 -8
- package/dist/{system-prompt-table-CDCYVwqN.js → system-prompt-table-CiXy0eNR.js} +91 -70
- package/dist/{task-runner-DcdQJd9e.js → task-runner-C9Yc2_ae.js} +35 -49
- package/dist/{thread-context-DF5uDcWN.js → thread-context-CqZDKErp.js} +6 -6
- package/dist/topics-SRN7IVX-.js +24 -0
- package/dist/turn-membership-CENFf3kI.js +856 -0
- package/dist/{turn-wake-um5Ubd4m.js → turn-wake-BhloiI2h.js} +4 -5
- package/dist/{media-Cr9pGkzr.js → types-C4iC-IMC.js} +819 -777
- package/dist/user-customization-CvfuY9Eo.js +93 -0
- package/dist/users-ByG5RCEJ.js +181 -0
- package/dist/{validation-CJyuOPD2.js → validation-8gjfR91V.js} +1 -1
- package/dist/{version-Bhe7RPIe.js → version-BeZhWWBE.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{worker-D8PRgUqr.js → worker-BqMQQNRk.js} +5 -4
- package/migrations/20261125171254_conversation_visibility/migration.sql +4 -0
- package/migrations/20261125171254_conversation_visibility/snapshot.json +67 -0
- package/migrations/20261125171257_conversation_visibility_backfill/migration.sql +25 -0
- package/migrations/20261125171257_conversation_visibility_backfill/snapshot.json +9 -0
- package/migrations/20261125213232_drop_versions_notify/migration.sql +19 -0
- package/migrations/20261125213232_drop_versions_notify/snapshot.json +9 -0
- package/migrations/20261125225138_conversation_kind_root_thread/migration.sql +23 -0
- package/migrations/20261125225138_conversation_kind_root_thread/snapshot.json +55 -0
- package/migrations/20261125225142_conversation_kind_root_thread_backfill/migration.sql +7 -0
- package/migrations/20261125225142_conversation_kind_root_thread_backfill/snapshot.json +9 -0
- package/migrations/20261126000151_conversation_event_message_role_seq_index/migration.sql +1 -0
- package/migrations/20261126000151_conversation_event_message_role_seq_index/snapshot.json +69 -0
- package/migrations/20261126012917_merge_leaves/migration.sql +2 -0
- package/migrations/20261126012917_merge_leaves/snapshot.json +12 -0
- package/migrations/20261126025226_drop_agent_invocations/migration.sql +6 -0
- package/migrations/20261126025226_drop_agent_invocations/snapshot.json +9 -0
- package/migrations/20261126033000_space_conversations_lead_children/migration.sql +155 -0
- package/migrations/20261126033000_space_conversations_lead_children/snapshot.json +9 -0
- package/migrations/20261126144620_drop_user_message_time_index/migration.sql +1 -0
- package/migrations/20261126144620_drop_user_message_time_index/snapshot.json +38 -0
- package/migrations/20261126153100_inbox_item_subjects/migration.sql +140 -0
- package/migrations/20261126153100_inbox_item_subjects/snapshot.json +9 -0
- package/migrations/20261126153103_inbox_item_subjects_not_null/migration.sql +12 -0
- package/migrations/20261126153103_inbox_item_subjects_not_null/snapshot.json +9 -0
- package/migrations/20261126153105_inbox_item_subject_indexes/migration.sql +1 -0
- package/migrations/20261126153105_inbox_item_subject_indexes/snapshot.json +9 -0
- package/migrations/20261126153108_automation_run_conversation_index/migration.sql +1 -0
- package/migrations/20261126153108_automation_run_conversation_index/snapshot.json +9 -0
- package/migrations/20261126153159_inbox_item_subjects_schema/migration.sql +4 -0
- package/migrations/20261126153159_inbox_item_subjects_schema/snapshot.json +437 -0
- package/migrations/20261126153259_inbox_questions/migration.sql +76 -0
- package/migrations/20261126153259_inbox_questions/snapshot.json +9 -0
- package/migrations/20261126153301_inbox_questions_valid/migration.sql +3 -0
- package/migrations/20261126153301_inbox_questions_valid/snapshot.json +9 -0
- package/migrations/20261126153343_inbox_questions_schema/migration.sql +5 -0
- package/migrations/20261126153343_inbox_questions_schema/snapshot.json +407 -0
- package/migrations/20261126154025_inbox_item_owners/migration.sql +74 -0
- package/migrations/20261126154025_inbox_item_owners/snapshot.json +9 -0
- package/migrations/20261126154048_inbox_item_open_subject_key_index/migration.sql +1 -0
- package/migrations/20261126154048_inbox_item_open_subject_key_index/snapshot.json +9 -0
- package/migrations/20261126154051_drop_inbox_item_owner_indexes/migration.sql +7 -0
- package/migrations/20261126154051_drop_inbox_item_owner_indexes/snapshot.json +9 -0
- package/migrations/20261126154121_inbox_item_owners_schema/migration.sql +8 -0
- package/migrations/20261126154121_inbox_item_owners_schema/snapshot.json +311 -0
- package/migrations/20261126175601_conversation_event_turn/migration.sql +5 -0
- package/migrations/20261126175601_conversation_event_turn/snapshot.json +103 -0
- package/migrations/20261126175614_conversation_event_turn_index/migration.sql +1 -0
- package/migrations/20261126175614_conversation_event_turn_index/snapshot.json +62 -0
- package/migrations/20261126230028_merge_leaves/migration.sql +2 -0
- package/migrations/20261126230028_merge_leaves/snapshot.json +12 -0
- package/migrations/20261126231932_space_lead_holds_name/migration.sql +46 -0
- package/migrations/20261126231932_space_lead_holds_name/snapshot.json +58 -0
- package/migrations/20261127001022_merge_leaves/migration.sql +2 -0
- package/migrations/20261127001022_merge_leaves/snapshot.json +12 -0
- package/package.json +5 -5
- package/skills/jr-rpc/SKILL.md +3 -5
- package/dist/direct-url-BYgYfuIy.js +0 -22
- package/dist/markers-CE0HMXWT.js +0 -67
- package/dist/people-Cegp1Iwq.js +0 -81
- package/dist/start-conversation-Uh8Sk1EF.js +0 -162
- package/dist/turn-session-routing-GtetHsdO.js +0 -1309
- package/dist/user-customization-B27StpVQ.js +0 -9
- package/dist/web-message-id-C6P83ans.js +0 -10
|
@@ -1,23 +1,27 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
|
|
2
|
-
import { B as
|
|
3
|
-
import {
|
|
4
|
-
import { C as summarizeMessageText, E as withSpan, M as isNativeIdentityProvider, P as toOptionalString,
|
|
5
|
-
import { _ as
|
|
6
|
-
import {
|
|
2
|
+
import { A as retainRuntimeTurnContext, B as THREAD_CONTEXT_TAGS, D as isToolResultError, G as renderThreadContext, I as TURN_CONTEXT_TAG, L as mapBounded, M as trimTrailingAssistantMessages, O as isToolResultMessage, R as renderCurrentInstruction, T as isContinuablePiBoundary, V as authorAttrs, W as renderParentAgentTask, _ 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 } from "./prompt-Dv7gkpD6.js";
|
|
3
|
+
import { Bo as credentialContextForActor, Bu as agentsInstructionsUpdatedEvent, Dc as getInboxItem, Dd as juniorWorkspaceRepos, Ed as juniorSnapshots, Ei as formatSlackLink, En as traceContextSchema, Es as isUserActor, Hs as isDmChannel, Ht as appendInboundMessage, Hu as conversationNoteEvent, Io as verifyTimerWatchCredentialSubject, Ji as createPluginCache, Js as sleep, Ka as fallbackShortTitle, Ku as getStateAdapter, Mi as getPluginUserPromptContributions, Mn as readParentMessage, N as claimProviderConversation, Od as juniorWorkspaces, Os as toStoredSlackActor, Pl as projectConversationMessages, Pn as isEventMailboxMetadata, Pu as completeText, Qd as juniorConversationEvents, Ro as JUNIOR_THREAD_STATE_TTL_MS, Ss as createActor, St as getRegistrations, Ti as escapeSlackMrkdwnText, Tn as releaseInboundMessage, Ui as pluginConfigValues, Uo as credentialSubjectSchema, Vt as appendAndEnqueueInboundMessage, Vu as authenticationLinkedEvent, Wd as juniorLocationConfigurations, Yu as addAgentTurnUsage, _i as postSlackEphemeralMessage, a as getDb, bf as getConfigDefaults, d as createSqlConversationEventStore, dc as findLinkedSlackUser, dd as parseSlackUserId, dl as eventGuidance, en as dropPendingMessages, eo as getEventCatalog, eu as dispatchInstructionsInvokeSkills, fc as findSlackUserByPrimaryEmail, fs as conversationSubtree, gd as parseSlackMessageTs, gf as juniorDestinations, hf as juniorUsers, i as getConversationStore, j as startLocationThread, jr as getVercelConversationWorkQueue, lf as juniorConversations, mn as takePendingEventMessages, mo as publishAgentUpdate, n as getConversationEventStore, nu as isPersonInput, o as getSqlExecutor, oc as SYSTEM_IDENTITY_ID, pn as stopConversationWork, ps as conversationSubtreeColumns, qa as generateShortTitle, qs as withSlackRetries, qu as getStateValues, rd as nextDetailVersion, rn as getConversationWorkState, sc as resolveActorIdentityId, u as isPostgresErrorCode, v as withConversationEventLock, vi as postSlackMessage, vs as findActorTimezone, xl as ToolInputError, xt as getPlugins, zs as getSlackClient, zu as JUNIOR_NATIVE_EVENT_NAMESPACE } from "./db-BFmyYZtJ.js";
|
|
4
|
+
import { C as summarizeMessageText, E as withSpan, M as isNativeIdentityProvider, P as toOptionalString, b as setSpanAttributes, h as logWarn, k as formatSentryEventReference, m as logInfo, o as getActiveTraceContext, p as logException, t as buildTurnFailureResponse, v as serializeGenAiAttribute } from "./logging--smS7XRK.js";
|
|
5
|
+
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-CiXy0eNR.js";
|
|
6
|
+
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-BQ-iBDsZ.js";
|
|
7
|
+
import { C as resolveGatewayModel, G as isCompactionSummaryText, J as createProviderError, N as fenceLock, P as withLock, X as getProviderErrorAttributes, Y as findProviderError, Z as getProviderErrorUserMessage, f as TURN_REASONING_LEVELS, i as getSlackBotToken, j as MUTATION_LOCK_TTL_MS, k as createCache, n as getChatConfig, q as createAssistantProviderError, t as botConfig, z as estimateTextTokens } from "./config-CHQ8X251.js";
|
|
8
|
+
import { Ct as instructionActors, St as contextProvenance, Vt as messageCardRef, bn as normalizeUserInputAnswer, bt as piMessageSchema, fn as inboxItemQuestion, gt as historyItemFromPiMessage, nt as agentTypeInstructions, rt as agentTypeSchema, vn as formatUserInputAnswer, wt as instructionProvenanceFor, xt as agentInstructionProvenance, yt as piMessageFromHistoryItem } from "./types-C4iC-IMC.js";
|
|
9
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-DfSpJZdY.js";
|
|
7
10
|
import { t as isMissingVirtualModule } from "./virtual-module-BeKA_EII.js";
|
|
8
|
-
import { r as userCustomizationTextSchema } from "./user-customization-
|
|
9
|
-
import { a as parseSkillFile, i as openAiPolicyDisablesImplicitInvocation } from "./skills-
|
|
10
|
-
import {
|
|
11
|
+
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";
|
|
11
15
|
import * as z from "zod";
|
|
12
|
-
import pLimit from "p-limit";
|
|
13
16
|
import { getCurrentSystemMessage, getSystemMessageText } from "@earendil-works/pi-ai/compat";
|
|
14
17
|
import path from "node:path";
|
|
15
18
|
import { isDeepStrictEqual } from "node:util";
|
|
16
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
19
|
+
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
17
20
|
import { isRetryableAssistantError, renderSystemMessageUpdate } from "@earendil-works/pi-ai";
|
|
18
|
-
import { actorSchema, agentEventKeys, createEventSource, createLocalSource, createWebSource, destinationSchema, escapeClosingTag, escapeClosingTags, escapeTagText, escapeTagTextAndQuotes, findTag,
|
|
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";
|
|
19
22
|
import { and, asc, desc, eq, inArray, isNull, like, lt, lte, ne, or, sql } from "drizzle-orm";
|
|
20
23
|
import { alias } from "drizzle-orm/pg-core";
|
|
24
|
+
import pLimit from "p-limit";
|
|
21
25
|
// src/chat/configuration/types.ts
|
|
22
26
|
/** JSON value accepted by Location configuration. */
|
|
23
27
|
const configValueSchema = z.json();
|
|
@@ -60,10 +64,13 @@ function validateConfigValue(value) {
|
|
|
60
64
|
collectStringValues(value, stringValues);
|
|
61
65
|
for (const text of stringValues) for (const pattern of SECRET_VALUE_PATTERNS) if (pattern.test(text)) return "Configuration value appears to contain secret material and is not allowed";
|
|
62
66
|
}
|
|
63
|
-
// src/chat/pi/messages.ts
|
|
64
|
-
/** Permissive schema for durable Pi SDK messages whose content shape may evolve. */
|
|
65
|
-
const piMessageSchema = z.object({ role: z.string() }).passthrough().transform((value) => value);
|
|
66
67
|
// src/chat/pi/conversation-events.ts
|
|
68
|
+
/**
|
|
69
|
+
* Pi adapter for Junior conversation events.
|
|
70
|
+
*
|
|
71
|
+
* Conversation storage owns the ordered event log. This module turns its
|
|
72
|
+
* stored messages into the active Pi context.
|
|
73
|
+
*/
|
|
67
74
|
function authorizationObservationMessage(data, createdAtMs) {
|
|
68
75
|
const label = data.kind === "mcp" ? "MCP authorization" : "Authorization";
|
|
69
76
|
return piMessageSchema.parse({
|
|
@@ -75,56 +82,6 @@ function authorizationObservationMessage(data, createdAtMs) {
|
|
|
75
82
|
timestamp: createdAtMs
|
|
76
83
|
});
|
|
77
84
|
}
|
|
78
|
-
/** Translate one Pi message into Junior's native durable history item. */
|
|
79
|
-
function historyItemFromPiMessage(message, provenance) {
|
|
80
|
-
const { role, ...fields } = piMessageSchema.parse(message);
|
|
81
|
-
if (role === "user") return agentHistoryItemSchema.parse({
|
|
82
|
-
...fields,
|
|
83
|
-
type: "user_message",
|
|
84
|
-
provenance
|
|
85
|
-
});
|
|
86
|
-
if (role === "assistant") return agentHistoryItemSchema.parse({
|
|
87
|
-
...fields,
|
|
88
|
-
type: "assistant_message"
|
|
89
|
-
});
|
|
90
|
-
if (role === "toolResult") return agentHistoryItemSchema.parse({
|
|
91
|
-
...fields,
|
|
92
|
-
type: "tool_result"
|
|
93
|
-
});
|
|
94
|
-
return agentHistoryItemSchema.parse({
|
|
95
|
-
...fields,
|
|
96
|
-
type: "system_message"
|
|
97
|
-
});
|
|
98
|
-
}
|
|
99
|
-
/** Translate one Junior-native history item into the Pi message it represents. */
|
|
100
|
-
function piMessageFromHistoryItem(data) {
|
|
101
|
-
if (data.type === "user_message") {
|
|
102
|
-
const { type: _, provenance: __, ...fields } = data;
|
|
103
|
-
return piMessageSchema.parse({
|
|
104
|
-
...fields,
|
|
105
|
-
role: "user"
|
|
106
|
-
});
|
|
107
|
-
}
|
|
108
|
-
if (data.type === "assistant_message") {
|
|
109
|
-
const { type: _, ...fields } = data;
|
|
110
|
-
return piMessageSchema.parse({
|
|
111
|
-
...fields,
|
|
112
|
-
role: "assistant"
|
|
113
|
-
});
|
|
114
|
-
}
|
|
115
|
-
if (data.type === "system_message") {
|
|
116
|
-
const { type: _, ...fields } = data;
|
|
117
|
-
return piMessageSchema.parse({
|
|
118
|
-
...fields,
|
|
119
|
-
role: "system"
|
|
120
|
-
});
|
|
121
|
-
}
|
|
122
|
-
const { type: _, ...fields } = data;
|
|
123
|
-
return piMessageSchema.parse({
|
|
124
|
-
...fields,
|
|
125
|
-
role: "toolResult"
|
|
126
|
-
});
|
|
127
|
-
}
|
|
128
85
|
function historyItemProvenance(data) {
|
|
129
86
|
return data.type === "user_message" ? data.provenance : contextProvenance;
|
|
130
87
|
}
|
|
@@ -384,6 +341,180 @@ function createDurableLocationConfigurationService(args) {
|
|
|
384
341
|
}
|
|
385
342
|
});
|
|
386
343
|
}
|
|
344
|
+
// src/chat/slack/oauth-authorization-message.ts
|
|
345
|
+
const ACCOUNT_SCOPE_NOTE = "This connects only your account. I can see only what you can see.";
|
|
346
|
+
/** Present private OAuth authorization with a clear action and text fallback. */
|
|
347
|
+
function buildSlackOAuthAuthorizationMessage(args) {
|
|
348
|
+
return {
|
|
349
|
+
text: `${formatSlackLink(args.authorizationUrl, args.label)}. ${ACCOUNT_SCOPE_NOTE} ${args.completionText}`,
|
|
350
|
+
blocks: [{
|
|
351
|
+
type: "section",
|
|
352
|
+
text: {
|
|
353
|
+
type: "mrkdwn",
|
|
354
|
+
text: `*${escapeSlackMrkdwnText(args.label)}*\n${ACCOUNT_SCOPE_NOTE}\n${escapeSlackMrkdwnText(args.completionText)}`
|
|
355
|
+
},
|
|
356
|
+
accessory: {
|
|
357
|
+
type: "button",
|
|
358
|
+
text: {
|
|
359
|
+
type: "plain_text",
|
|
360
|
+
text: "Connect"
|
|
361
|
+
},
|
|
362
|
+
style: "primary",
|
|
363
|
+
url: args.authorizationUrl,
|
|
364
|
+
action_id: "oauth_connect"
|
|
365
|
+
}
|
|
366
|
+
}]
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
// src/chat/oauth-flow.ts
|
|
370
|
+
const OAUTH_STATE_TTL_MS = 6e5;
|
|
371
|
+
const optionalStateStringSchema = z.string().min(1).optional().catch(void 0);
|
|
372
|
+
const oauthStatePayloadSchema = z.object({
|
|
373
|
+
userId: z.string(),
|
|
374
|
+
provider: z.string(),
|
|
375
|
+
actor: actorSchema.optional(),
|
|
376
|
+
channelId: optionalStateStringSchema,
|
|
377
|
+
destination: destinationSchema.optional(),
|
|
378
|
+
source: sourceSchema.optional(),
|
|
379
|
+
threadTs: optionalStateStringSchema,
|
|
380
|
+
resumeConversationId: optionalStateStringSchema,
|
|
381
|
+
resumeSessionId: optionalStateStringSchema,
|
|
382
|
+
scope: optionalStateStringSchema
|
|
383
|
+
});
|
|
384
|
+
/** Parse OAuth callback state that was persisted before a provider redirect. */
|
|
385
|
+
function parseOAuthStatePayload(value) {
|
|
386
|
+
const parsed = oauthStatePayloadSchema.safeParse(value);
|
|
387
|
+
return parsed.success ? parsed.data : void 0;
|
|
388
|
+
}
|
|
389
|
+
/** Return the manifest-owned display label for a provider. */
|
|
390
|
+
function formatProviderLabel(provider) {
|
|
391
|
+
const displayName = pluginCatalogRuntime.getDisplayName(provider);
|
|
392
|
+
if (!displayName) throw new Error(`Unknown plugin provider display name: "${provider}"`);
|
|
393
|
+
return displayName;
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* Authorization links must only be visible to the requesting user.
|
|
397
|
+
* Try in-context private delivery first, then fall back to a DM.
|
|
398
|
+
*/
|
|
399
|
+
async function deliverPrivateMessage(input) {
|
|
400
|
+
let client;
|
|
401
|
+
try {
|
|
402
|
+
client = getSlackClient();
|
|
403
|
+
} catch {
|
|
404
|
+
logWarn("oauth.private_delivery.skipped", { "app.reason": "missing_bot_token" });
|
|
405
|
+
return false;
|
|
406
|
+
}
|
|
407
|
+
if (input.channelId) try {
|
|
408
|
+
if (isDmChannel(input.channelId)) await postSlackMessage({
|
|
409
|
+
channelId: input.channelId,
|
|
410
|
+
text: input.text,
|
|
411
|
+
blocks: input.blocks,
|
|
412
|
+
threadTs: input.threadTs
|
|
413
|
+
});
|
|
414
|
+
else await postSlackEphemeralMessage({
|
|
415
|
+
channelId: input.channelId,
|
|
416
|
+
userId: input.userId,
|
|
417
|
+
text: input.text,
|
|
418
|
+
blocks: input.blocks,
|
|
419
|
+
threadTs: input.threadTs
|
|
420
|
+
});
|
|
421
|
+
return "in_context";
|
|
422
|
+
} catch (error) {
|
|
423
|
+
logWarn("oauth.private_delivery.failed", {
|
|
424
|
+
"app.slack.error": error instanceof Error ? error.message : String(error),
|
|
425
|
+
"app.slack.channel": input.channelId
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
try {
|
|
429
|
+
const dmChannelId = (await withSlackRetries(() => client.conversations.open({ users: input.userId }), 3, {
|
|
430
|
+
action: "conversations.open",
|
|
431
|
+
spanAttributes: { "app.slack.user_id": input.userId }
|
|
432
|
+
})).channel?.id;
|
|
433
|
+
if (!dmChannelId) {
|
|
434
|
+
logWarn("oauth.dm.fallback.failed", { "app.reason": "no_dm_channel_id" });
|
|
435
|
+
return false;
|
|
436
|
+
}
|
|
437
|
+
await postSlackMessage({
|
|
438
|
+
channelId: dmChannelId,
|
|
439
|
+
text: input.text,
|
|
440
|
+
blocks: input.blocks
|
|
441
|
+
});
|
|
442
|
+
return "fallback_dm";
|
|
443
|
+
} catch (error) {
|
|
444
|
+
logWarn("oauth.dm.fallback.failed", { "app.slack.error": error instanceof Error ? error.message : String(error) });
|
|
445
|
+
return false;
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
/** Present one OAuth request through the active surface's private delivery. */
|
|
449
|
+
async function deliverOAuthAuthorization(request, input) {
|
|
450
|
+
if (input.authorization) {
|
|
451
|
+
await input.authorization.deliver(request);
|
|
452
|
+
return "in_context";
|
|
453
|
+
}
|
|
454
|
+
return await deliverPrivateMessage({
|
|
455
|
+
channelId: input.channelId,
|
|
456
|
+
threadTs: input.threadTs,
|
|
457
|
+
userId: input.userId,
|
|
458
|
+
...buildSlackOAuthAuthorizationMessage(request)
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
/** Initiate an OAuth authorization code flow for a provider and deliver the auth link to the user. */
|
|
462
|
+
async function startOAuthFlow(provider, input) {
|
|
463
|
+
const providerConfig = pluginCatalogRuntime.getOAuthConfig(provider);
|
|
464
|
+
if (!providerConfig) return {
|
|
465
|
+
ok: false,
|
|
466
|
+
error: `Provider "${provider}" does not support OAuth authorization`
|
|
467
|
+
};
|
|
468
|
+
const clientId = process.env[providerConfig.clientIdEnv]?.trim();
|
|
469
|
+
if (!clientId) return {
|
|
470
|
+
ok: false,
|
|
471
|
+
error: `Missing ${providerConfig.clientIdEnv} environment variable`
|
|
472
|
+
};
|
|
473
|
+
const baseUrl = getChatConfig().deployment.baseUrl;
|
|
474
|
+
if (!baseUrl) return {
|
|
475
|
+
ok: false,
|
|
476
|
+
error: "Cannot determine base URL (set JUNIOR_BASE_URL or deploy to Vercel)"
|
|
477
|
+
};
|
|
478
|
+
const state = input.authorization ? await input.authorization.createState() : randomBytes(32).toString("hex");
|
|
479
|
+
const requestedScope = input.scope ?? providerConfig.scope;
|
|
480
|
+
await getStateAdapter().set(`oauth-state:${state}`, {
|
|
481
|
+
userId: input.actorId,
|
|
482
|
+
provider,
|
|
483
|
+
...input.actor ? { actor: input.actor } : void 0,
|
|
484
|
+
...input.channelId ? { channelId: input.channelId } : void 0,
|
|
485
|
+
...input.destination ? { destination: input.destination } : void 0,
|
|
486
|
+
...input.source ? { source: input.source } : void 0,
|
|
487
|
+
...input.threadTs ? { threadTs: input.threadTs } : void 0,
|
|
488
|
+
...input.resumeConversationId ? { resumeConversationId: input.resumeConversationId } : void 0,
|
|
489
|
+
...input.resumeSessionId ? { resumeSessionId: input.resumeSessionId } : void 0,
|
|
490
|
+
...requestedScope ? { scope: requestedScope } : void 0
|
|
491
|
+
}, OAUTH_STATE_TTL_MS);
|
|
492
|
+
const authorizeParams = new URLSearchParams({
|
|
493
|
+
client_id: clientId,
|
|
494
|
+
state,
|
|
495
|
+
redirect_uri: `${baseUrl}${providerConfig.callbackPath}`,
|
|
496
|
+
response_type: "code"
|
|
497
|
+
});
|
|
498
|
+
if (requestedScope) authorizeParams.set("scope", requestedScope);
|
|
499
|
+
for (const [key, value] of Object.entries(providerConfig.authorizeParams ?? {})) authorizeParams.set(key, value);
|
|
500
|
+
logInfo("jr_rpc.oauth.started", {
|
|
501
|
+
"app.credential.provider": provider,
|
|
502
|
+
...input.activeSkillName ? { "app.skill.name": input.activeSkillName } : void 0
|
|
503
|
+
});
|
|
504
|
+
return {
|
|
505
|
+
ok: true,
|
|
506
|
+
delivery: await deliverOAuthAuthorization({
|
|
507
|
+
authorizationUrl: `${providerConfig.authorizeEndpoint}?${authorizeParams.toString()}`,
|
|
508
|
+
label: `Connect your ${formatProviderLabel(provider)} account`,
|
|
509
|
+
completionText: input.resumeSessionId ? "Once you've authorized, I'll continue automatically." : "Once you've authorized, you'll see a confirmation in Slack."
|
|
510
|
+
}, {
|
|
511
|
+
authorization: input.authorization,
|
|
512
|
+
channelId: input.channelId,
|
|
513
|
+
threadTs: input.threadTs,
|
|
514
|
+
userId: input.actorId
|
|
515
|
+
})
|
|
516
|
+
};
|
|
517
|
+
}
|
|
387
518
|
// src/chat/services/persist-retry.ts
|
|
388
519
|
/**
|
|
389
520
|
* Shared post-delivery persist retry.
|
|
@@ -401,7 +532,7 @@ async function persistWithRetry(persist) {
|
|
|
401
532
|
return;
|
|
402
533
|
} catch (error) {
|
|
403
534
|
lastError = error;
|
|
404
|
-
if (attempt < PERSIST_ATTEMPTS) await sleep
|
|
535
|
+
if (attempt < PERSIST_ATTEMPTS) await sleep(attempt * 100);
|
|
405
536
|
}
|
|
406
537
|
throw lastError;
|
|
407
538
|
}
|
|
@@ -678,6 +809,7 @@ function buildProposal(toolName, tool, input, resolved, context, priorRejections
|
|
|
678
809
|
conversationId: context.conversationId,
|
|
679
810
|
...credential ? { credential } : void 0,
|
|
680
811
|
destination: context.destination,
|
|
812
|
+
...context.lead ? { lead: true } : void 0,
|
|
681
813
|
source: context.source,
|
|
682
814
|
userIntent: context.userIntent()
|
|
683
815
|
},
|
|
@@ -1273,26 +1405,24 @@ async function readAnswerText(events, turn) {
|
|
|
1273
1405
|
return answer.reply.text;
|
|
1274
1406
|
}
|
|
1275
1407
|
/**
|
|
1276
|
-
*
|
|
1408
|
+
* The agent update status of a Turn that ended without a failure. A
|
|
1277
1409
|
* cancelled Turn reports nothing: new input or a stop replaced it, and each
|
|
1278
1410
|
* of them reports.
|
|
1279
1411
|
*/
|
|
1412
|
+
const TURN_OUTCOME_STATUSES = {
|
|
1413
|
+
blocked: "blocked",
|
|
1414
|
+
cancelled: void 0,
|
|
1415
|
+
no_reply: "done",
|
|
1416
|
+
success: "done"
|
|
1417
|
+
};
|
|
1418
|
+
/** Return the agent update of a Turn that ended without a failure. */
|
|
1280
1419
|
async function readTurnUpdate(events, turn) {
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
status: "done",
|
|
1288
|
-
text: turn.answerText ?? await readAnswerText(events, turn)
|
|
1289
|
-
};
|
|
1290
|
-
case "blocked": return {
|
|
1291
|
-
status: "blocked",
|
|
1292
|
-
text: turn.answerText ?? await readAnswerText(events, turn)
|
|
1293
|
-
};
|
|
1294
|
-
case "cancelled": return;
|
|
1295
|
-
}
|
|
1420
|
+
const status = TURN_OUTCOME_STATUSES[turn.outcome];
|
|
1421
|
+
if (!status) return void 0;
|
|
1422
|
+
return {
|
|
1423
|
+
status,
|
|
1424
|
+
text: turn.outcome === "success" ? await readReplyText(events, turn) : turn.answerText ?? await readAnswerText(events, turn)
|
|
1425
|
+
};
|
|
1296
1426
|
}
|
|
1297
1427
|
/**
|
|
1298
1428
|
* Return the agent update of a failed Turn. Raw error text is not stored, so
|
|
@@ -1426,7 +1556,7 @@ var ConversationTurnLifecycleService = class {
|
|
|
1426
1556
|
text: input.answer.text
|
|
1427
1557
|
};
|
|
1428
1558
|
const start = await this.events.loadByIdempotencyKey(input.conversationId, turnStartedKey(input.turnId));
|
|
1429
|
-
|
|
1559
|
+
return await readTurnUpdate(this.events, {
|
|
1430
1560
|
conversationId: input.conversationId,
|
|
1431
1561
|
outcome,
|
|
1432
1562
|
startSeq: start?.seq ?? terminalSeq,
|
|
@@ -1434,12 +1564,6 @@ var ConversationTurnLifecycleService = class {
|
|
|
1434
1564
|
turnId: input.turnId,
|
|
1435
1565
|
...input.answer ? { answerText: input.answer.text } : void 0
|
|
1436
1566
|
});
|
|
1437
|
-
if (!update || outcome !== "no_reply") return update;
|
|
1438
|
-
const { childWorkGoesOn } = await import("./parent-result-Dg6P6roR.js").then((n) => n.n);
|
|
1439
|
-
return {
|
|
1440
|
-
...update,
|
|
1441
|
-
quiet: await startedByEventsOnly() || await childWorkGoesOn(input.conversationId)
|
|
1442
|
-
};
|
|
1443
1567
|
}
|
|
1444
1568
|
});
|
|
1445
1569
|
}
|
|
@@ -1448,1608 +1572,6 @@ var ConversationTurnLifecycleService = class {
|
|
|
1448
1572
|
function getTurnLifecycle() {
|
|
1449
1573
|
return new ConversationTurnLifecycleService(getConversationEventStore(), { watchQueue: getVercelConversationWorkQueue });
|
|
1450
1574
|
}
|
|
1451
|
-
// src/chat/agent-invocations/parent-message-input.ts
|
|
1452
|
-
/**
|
|
1453
|
-
* A parent agent task or message to a child: who sent it and the
|
|
1454
|
-
* instruction. It names the parent Conversation, the
|
|
1455
|
-
* Actor and grants of the parent's Turn, and the `startAgent` or
|
|
1456
|
-
* `messageAgent` tool call that sent it. Its text is the raw task. `fork`
|
|
1457
|
-
* marks the task of a fork spawn.
|
|
1458
|
-
*/
|
|
1459
|
-
const parentMessageSchema = z.object({
|
|
1460
|
-
actor: actorSchema,
|
|
1461
|
-
credentialContext: credentialContextSchema.optional(),
|
|
1462
|
-
fork: z.literal(true).optional(),
|
|
1463
|
-
kind: z.literal("parent_message"),
|
|
1464
|
-
parentConversationId: z.string().min(1),
|
|
1465
|
-
parentToolCallId: z.string().min(1)
|
|
1466
|
-
}).strict();
|
|
1467
|
-
/**
|
|
1468
|
-
* Read the parent message that one mailbox input is, if it is one. Check its
|
|
1469
|
-
* sender with `readChildOfStoredParent` before it gets any authority.
|
|
1470
|
-
*/
|
|
1471
|
-
function readParentMessage(message) {
|
|
1472
|
-
if (message.source !== "internal") return;
|
|
1473
|
-
const parsed = parentMessageSchema.safeParse(message.input.metadata);
|
|
1474
|
-
return parsed.success ? parsed.data : void 0;
|
|
1475
|
-
}
|
|
1476
|
-
// src/chat/task-execution/attempt-selection.ts
|
|
1477
|
-
function inputOwner(message) {
|
|
1478
|
-
const parentMessage = readParentMessage(message);
|
|
1479
|
-
return {
|
|
1480
|
-
authorId: message.input.authorId,
|
|
1481
|
-
...parentMessage ? { credentials: {
|
|
1482
|
-
actor: parentMessage.actor,
|
|
1483
|
-
credentialContext: parentMessage.credentialContext
|
|
1484
|
-
} } : void 0,
|
|
1485
|
-
identityId: message.input.authorIdentityId,
|
|
1486
|
-
source: message.source
|
|
1487
|
-
};
|
|
1488
|
-
}
|
|
1489
|
-
function turnOwner(turn) {
|
|
1490
|
-
return {
|
|
1491
|
-
authorId: isUserActor(turn.actor) ? turn.actor.userId : void 0,
|
|
1492
|
-
identityId: turn.actorIdentityId,
|
|
1493
|
-
source: turn.source?.kind
|
|
1494
|
-
};
|
|
1495
|
-
}
|
|
1496
|
-
/**
|
|
1497
|
-
* One Turn has one Actor and one Source: it runs with that Actor's
|
|
1498
|
-
* credentials, so input from anyone else must not join it. Every value that
|
|
1499
|
-
* both sides know must match, and they must share an Identity id or an author
|
|
1500
|
-
* id. Input with no known author matches nothing.
|
|
1501
|
-
*/
|
|
1502
|
-
function hasSameOwner(a, b) {
|
|
1503
|
-
if (a.source && b.source && a.source !== b.source) return false;
|
|
1504
|
-
if (a.credentials && b.credentials && !hasSameCredentials(a.credentials, b.credentials)) return false;
|
|
1505
|
-
const sameIdentity = a.identityId && b.identityId ? a.identityId === b.identityId : void 0;
|
|
1506
|
-
const sameAuthor = a.authorId && b.authorId ? a.authorId === b.authorId : void 0;
|
|
1507
|
-
return sameIdentity !== false && sameAuthor !== false && (sameIdentity ?? sameAuthor) === true;
|
|
1508
|
-
}
|
|
1509
|
-
function hasSameCredentials(a, b) {
|
|
1510
|
-
return sameActorIdentity(a.actor, b.actor) && isDeepStrictEqual(a.credentialContext, b.credentialContext);
|
|
1511
|
-
}
|
|
1512
|
-
/** True when two Inbound messages may share one Turn. */
|
|
1513
|
-
function canShareTurn(a, b) {
|
|
1514
|
-
return hasSameOwner(inputOwner(a), inputOwner(b));
|
|
1515
|
-
}
|
|
1516
|
-
/** True when an Inbound message may join `turn`. */
|
|
1517
|
-
function canJoinTurn(turn, message) {
|
|
1518
|
-
return hasSameOwner(turnOwner(turn), inputOwner(message));
|
|
1519
|
-
}
|
|
1520
|
-
function selectContiguousTurnBatch(messages) {
|
|
1521
|
-
const first = messages[0];
|
|
1522
|
-
if (!first) return [];
|
|
1523
|
-
const nextTurnIndex = messages.findIndex((message, index) => index > 0 && !canShareTurn(first, message));
|
|
1524
|
-
return messages.slice(0, nextTurnIndex === -1 ? messages.length : nextTurnIndex);
|
|
1525
|
-
}
|
|
1526
|
-
/**
|
|
1527
|
-
* True when an interrupt can start its own attempt.
|
|
1528
|
-
*
|
|
1529
|
-
* A steered web message must not start a second Turn while a yielded Turn
|
|
1530
|
-
* waits to resume. It stays pending for that Turn's drain or the next attempt.
|
|
1531
|
-
*/
|
|
1532
|
-
function isAttemptInterrupt(message, work) {
|
|
1533
|
-
return message.delivery === "interrupt" && !(work.execution.status === "paused" && message.source === "web");
|
|
1534
|
-
}
|
|
1535
|
-
/** Prioritize interrupts while keeping each attempt to one Actor and Source. */
|
|
1536
|
-
function selectAttemptMessages(work) {
|
|
1537
|
-
const messages = work.messages;
|
|
1538
|
-
const interrupts = messages.filter((message) => isAttemptInterrupt(message, work));
|
|
1539
|
-
if (interrupts.length > 0) return selectContiguousTurnBatch(interrupts);
|
|
1540
|
-
if (work.execution.status === "paused") return [];
|
|
1541
|
-
const nonEventMessages = messages.filter((message) => message.source !== "event");
|
|
1542
|
-
return selectContiguousTurnBatch(nonEventMessages.length > 0 ? nonEventMessages : messages);
|
|
1543
|
-
}
|
|
1544
|
-
// src/chat/task-execution/message-sender.ts
|
|
1545
|
-
/**
|
|
1546
|
-
* The Conversation and Turn that sent one inbound message, such as a child's
|
|
1547
|
-
* reply to its parent. The sender writes it at `input.metadata.sender`, so
|
|
1548
|
-
* readers never take meaning from the message id.
|
|
1549
|
-
*/
|
|
1550
|
-
const inboundMessageSenderSchema = z.object({
|
|
1551
|
-
conversationId: z.string().min(1),
|
|
1552
|
-
turnId: z.string().min(1)
|
|
1553
|
-
}).strict();
|
|
1554
|
-
/** Read the sender fields that one inbound message stores, if any. */
|
|
1555
|
-
function readInboundMessageSender(message) {
|
|
1556
|
-
const parsed = inboundMessageSenderSchema.safeParse(message.input.metadata?.["sender"]);
|
|
1557
|
-
return parsed.success ? parsed.data : void 0;
|
|
1558
|
-
}
|
|
1559
|
-
/**
|
|
1560
|
-
* Keep the sender fields of `messages` next to their ids, so a reader still
|
|
1561
|
-
* has them after the mailbox drops the message itself.
|
|
1562
|
-
*/
|
|
1563
|
-
function withMessageSenders(senders, messages) {
|
|
1564
|
-
let next = senders;
|
|
1565
|
-
for (const message of messages) {
|
|
1566
|
-
const sender = readInboundMessageSender(message);
|
|
1567
|
-
if (sender && !next?.[message.inboundMessageId]) next = {
|
|
1568
|
-
...next,
|
|
1569
|
-
[message.inboundMessageId]: sender
|
|
1570
|
-
};
|
|
1571
|
-
}
|
|
1572
|
-
return next;
|
|
1573
|
-
}
|
|
1574
|
-
/** Decode stored sender fields. Invalid entries are dropped. */
|
|
1575
|
-
function normalizeMessageSenders(value) {
|
|
1576
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return;
|
|
1577
|
-
const senders = {};
|
|
1578
|
-
for (const [id, raw] of Object.entries(value)) {
|
|
1579
|
-
const parsed = inboundMessageSenderSchema.safeParse(raw);
|
|
1580
|
-
if (parsed.success) senders[id] = parsed.data;
|
|
1581
|
-
}
|
|
1582
|
-
return Object.keys(senders).length ? senders : void 0;
|
|
1583
|
-
}
|
|
1584
|
-
// src/chat/task-execution/state.ts
|
|
1585
|
-
/**
|
|
1586
|
-
* Expiring conversation mailbox and execution index store.
|
|
1587
|
-
*
|
|
1588
|
-
* The conversation record owns pending inbound work, execution status, and the
|
|
1589
|
-
* lease. `conversation:active` feeds heartbeat recovery and contains every
|
|
1590
|
-
* conversation with runnable work. `writeConversation` keeps it in step.
|
|
1591
|
-
* `conversation:by-activity` supports legacy SQL import only; SQL owns durable
|
|
1592
|
-
* conversation metadata in configured runtime.
|
|
1593
|
-
*/
|
|
1594
|
-
const CONVERSATION_PREFIX = "junior:conversation:v2";
|
|
1595
|
-
const CONVERSATION_SCHEMA_VERSION = 2;
|
|
1596
|
-
const CONVERSATION_ACTIVITY_INDEX_MAX_LENGTH = 1e4;
|
|
1597
|
-
const CONVERSATION_INDEX_LOCK_TTL_MS = 1e4;
|
|
1598
|
-
const CONVERSATION_INDEX_LOCK_WAIT_MS = 2e3;
|
|
1599
|
-
const CONVERSATION_INDEX_LOCK_RETRY_MS = 25;
|
|
1600
|
-
const CONVERSATION_MUTATION_LOCK_TTL_MS = 1e4;
|
|
1601
|
-
const CONVERSATION_MUTATION_WAIT_MS = 1e4;
|
|
1602
|
-
const CONVERSATION_MUTATION_RETRY_MS = 25;
|
|
1603
|
-
var InvalidConversationRecordError = class extends Error {
|
|
1604
|
-
constructor(conversationId) {
|
|
1605
|
-
super(`Conversation record is invalid for ${conversationId}`);
|
|
1606
|
-
this.name = "InvalidConversationRecordError";
|
|
1607
|
-
}
|
|
1608
|
-
};
|
|
1609
|
-
/** Return whether an error means a stored conversation record failed validation. */
|
|
1610
|
-
function isInvalidConversationRecordError(error) {
|
|
1611
|
-
return error instanceof InvalidConversationRecordError;
|
|
1612
|
-
}
|
|
1613
|
-
var ConversationMutationFencedError = class extends Error {
|
|
1614
|
-
constructor(conversationId) {
|
|
1615
|
-
super(`Conversation mutation lock was lost before write for ${conversationId}`);
|
|
1616
|
-
this.name = "ConversationMutationFencedError";
|
|
1617
|
-
}
|
|
1618
|
-
};
|
|
1619
|
-
const CONVERSATION_BY_ACTIVITY_INDEX_KEY = `${CONVERSATION_PREFIX}:by-activity`;
|
|
1620
|
-
const CONVERSATION_ACTIVE_INDEX_KEY = `${CONVERSATION_PREFIX}:active`;
|
|
1621
|
-
const CONVERSATION_WORK_LEASE_TTL_MS = 9e4;
|
|
1622
|
-
const CONVERSATION_WORK_CHECK_IN_INTERVAL_MS = 15e3;
|
|
1623
|
-
const CONVERSATION_WORK_STALE_ENQUEUE_MS = 6e4;
|
|
1624
|
-
const inboundMessageSourceSchema = z.enum([
|
|
1625
|
-
"api",
|
|
1626
|
-
"internal",
|
|
1627
|
-
"local",
|
|
1628
|
-
"plugin",
|
|
1629
|
-
"event",
|
|
1630
|
-
"scheduler",
|
|
1631
|
-
"slack",
|
|
1632
|
-
"web"
|
|
1633
|
-
]);
|
|
1634
|
-
const agentInputSchema = z.object({
|
|
1635
|
-
attachments: z.array(z.unknown()).optional(),
|
|
1636
|
-
authorId: z.string().min(1).optional(),
|
|
1637
|
-
/** Identity of the input author, resolved at ingress. */
|
|
1638
|
-
authorIdentityId: z.string().min(1).optional(),
|
|
1639
|
-
metadata: z.record(z.string(), z.unknown()).optional(),
|
|
1640
|
-
/** Inbox item change that this input reports, on any Source. */
|
|
1641
|
-
reviewItemChange: inboxItemChangeRecordSchema.optional(),
|
|
1642
|
-
text: z.string()
|
|
1643
|
-
}).strict().refine((input) => input.text.trim() || input.attachments?.length, { message: "agent input requires text or attachments" });
|
|
1644
|
-
/** Durable delivery modes for pending inbound mailbox work. */
|
|
1645
|
-
const inboundMessageDeliverySchema = z.enum(["defer", "interrupt"]);
|
|
1646
|
-
/** Sentry trace propagation headers. A malformed value is dropped, not rejected. */
|
|
1647
|
-
const traceContextSchema = z.object({
|
|
1648
|
-
baggage: z.string().optional(),
|
|
1649
|
-
sentryTrace: z.string().min(1)
|
|
1650
|
-
}).optional().catch(void 0);
|
|
1651
|
-
/** Redis mailbox shape kept for deployed workers that still require this field. */
|
|
1652
|
-
const storedInboundMessageSchema = z.object({
|
|
1653
|
-
attemptCount: z.number().finite().optional(),
|
|
1654
|
-
conversationId: z.string().refine((value) => value.trim().length > 0),
|
|
1655
|
-
createdAtMs: z.number().finite(),
|
|
1656
|
-
delivery: inboundMessageDeliverySchema,
|
|
1657
|
-
destination: destinationSchema.optional(),
|
|
1658
|
-
inboundMessageId: z.string().refine((value) => value.trim().length > 0),
|
|
1659
|
-
input: agentInputSchema,
|
|
1660
|
-
receivedAtMs: z.number().finite(),
|
|
1661
|
-
source: inboundMessageSourceSchema,
|
|
1662
|
-
traceContext: traceContextSchema
|
|
1663
|
-
}).strict().extend({ publishExternally: z.boolean() });
|
|
1664
|
-
function conversationKey(conversationId) {
|
|
1665
|
-
return `${CONVERSATION_PREFIX}:${conversationId}`;
|
|
1666
|
-
}
|
|
1667
|
-
function conversationStopKey(conversationId) {
|
|
1668
|
-
return `${CONVERSATION_PREFIX}:stop:${conversationId}`;
|
|
1669
|
-
}
|
|
1670
|
-
function deferredMoveKey(conversationId) {
|
|
1671
|
-
return `${CONVERSATION_PREFIX}:deferred-move:${conversationId}`;
|
|
1672
|
-
}
|
|
1673
|
-
function indexLockKey(indexKey) {
|
|
1674
|
-
return `${indexKey}:lock`;
|
|
1675
|
-
}
|
|
1676
|
-
function mutationLockKey(conversationId) {
|
|
1677
|
-
return `${CONVERSATION_PREFIX}:mutation:${conversationId}`;
|
|
1678
|
-
}
|
|
1679
|
-
function now$1() {
|
|
1680
|
-
return Date.now();
|
|
1681
|
-
}
|
|
1682
|
-
function compareMessages(left, right) {
|
|
1683
|
-
return left.createdAtMs - right.createdAtMs || left.receivedAtMs - right.receivedAtMs || left.inboundMessageId.localeCompare(right.inboundMessageId);
|
|
1684
|
-
}
|
|
1685
|
-
function inputHasAttachments(input) {
|
|
1686
|
-
return Array.isArray(input.attachments) && input.attachments.length > 0;
|
|
1687
|
-
}
|
|
1688
|
-
/**
|
|
1689
|
-
* Upgrade a still-pending payload when a duplicate source event carries file
|
|
1690
|
-
* attachments the stored copy lacks (Slack `app_mention`/`message` twins),
|
|
1691
|
-
* keeping the stored ordering timestamps and delivery attempts.
|
|
1692
|
-
*/
|
|
1693
|
-
function upgradedPendingMessage(stored, duplicate) {
|
|
1694
|
-
const promotesInterrupt = stored.delivery === "defer" && duplicate.delivery === "interrupt";
|
|
1695
|
-
const delivery = promotesInterrupt ? "interrupt" : stored.delivery;
|
|
1696
|
-
const input = promotesInterrupt ? {
|
|
1697
|
-
...duplicate.input,
|
|
1698
|
-
...inputHasAttachments(duplicate.input) || !inputHasAttachments(stored.input) ? void 0 : { attachments: stored.input.attachments }
|
|
1699
|
-
} : inputHasAttachments(duplicate.input) && !inputHasAttachments(stored.input) ? duplicate.input : stored.input;
|
|
1700
|
-
if (input === stored.input && delivery === stored.delivery) return stored;
|
|
1701
|
-
return {
|
|
1702
|
-
...stored,
|
|
1703
|
-
delivery,
|
|
1704
|
-
input
|
|
1705
|
-
};
|
|
1706
|
-
}
|
|
1707
|
-
function compareIndexDescending(left, right) {
|
|
1708
|
-
return right.score - left.score || right.conversationId.localeCompare(left.conversationId);
|
|
1709
|
-
}
|
|
1710
|
-
function compareIndexAscending(left, right) {
|
|
1711
|
-
return left.score - right.score || left.conversationId.localeCompare(right.conversationId);
|
|
1712
|
-
}
|
|
1713
|
-
function uniqueStrings(values) {
|
|
1714
|
-
return [...new Set(values)];
|
|
1715
|
-
}
|
|
1716
|
-
function normalizeSource(value) {
|
|
1717
|
-
const parsed = inboundMessageSourceSchema.safeParse(value);
|
|
1718
|
-
return parsed.success ? parsed.data : void 0;
|
|
1719
|
-
}
|
|
1720
|
-
function normalizeExecutionStatus(value) {
|
|
1721
|
-
if (value === "paused") return value;
|
|
1722
|
-
if (value === "failed" || value === "idle" || value === "pending" || value === "running") return value;
|
|
1723
|
-
}
|
|
1724
|
-
function normalizeMessage(value) {
|
|
1725
|
-
const parsed = storedInboundMessageSchema.safeParse(value);
|
|
1726
|
-
if (!parsed.success) return;
|
|
1727
|
-
const { publishExternally: _publishExternally, traceContext, ...message } = parsed.data;
|
|
1728
|
-
return traceContext ? {
|
|
1729
|
-
...message,
|
|
1730
|
-
traceContext
|
|
1731
|
-
} : message;
|
|
1732
|
-
}
|
|
1733
|
-
function storeMessage(message, publishExternally) {
|
|
1734
|
-
return {
|
|
1735
|
-
...message,
|
|
1736
|
-
publishExternally
|
|
1737
|
-
};
|
|
1738
|
-
}
|
|
1739
|
-
/** Whether this is the final attempt before an unacked message is dead-lettered. */
|
|
1740
|
-
function isFinalAttempt(message) {
|
|
1741
|
-
return (message.attemptCount ?? 0) >= 4;
|
|
1742
|
-
}
|
|
1743
|
-
function normalizeActor(value) {
|
|
1744
|
-
return parseStoredSlackActor(value);
|
|
1745
|
-
}
|
|
1746
|
-
const storedNonEmptyStringSchema = z.string().refine((value) => value.trim().length > 0);
|
|
1747
|
-
const storedOptionalStringSchema = storedNonEmptyStringSchema.optional().catch(void 0);
|
|
1748
|
-
const storedOptionalNumberSchema = z.number().optional().catch(void 0);
|
|
1749
|
-
const storedIdListSchema = z.array(z.unknown()).catch([]);
|
|
1750
|
-
const storedLeaseSchema = z.object({
|
|
1751
|
-
token: storedNonEmptyStringSchema,
|
|
1752
|
-
acquiredAtMs: z.number(),
|
|
1753
|
-
attemptInboundMessageIds: z.array(z.string()).optional().catch(void 0),
|
|
1754
|
-
lastCheckInAtMs: z.number(),
|
|
1755
|
-
expiresAtMs: z.number()
|
|
1756
|
-
});
|
|
1757
|
-
function normalizeLease(value) {
|
|
1758
|
-
const parsed = storedLeaseSchema.safeParse(value);
|
|
1759
|
-
return parsed.success ? parsed.data : void 0;
|
|
1760
|
-
}
|
|
1761
|
-
const storedStopSchema = z.object({
|
|
1762
|
-
inboundMessageIds: storedIdListSchema,
|
|
1763
|
-
runId: storedNonEmptyStringSchema
|
|
1764
|
-
});
|
|
1765
|
-
function normalizeStop(value) {
|
|
1766
|
-
const parsed = storedStopSchema.safeParse(value);
|
|
1767
|
-
if (!parsed.success) return;
|
|
1768
|
-
return {
|
|
1769
|
-
inboundMessageIds: uniqueStrings(parsed.data.inboundMessageIds.filter((id) => typeof id === "string")),
|
|
1770
|
-
runId: parsed.data.runId
|
|
1771
|
-
};
|
|
1772
|
-
}
|
|
1773
|
-
const storedExecutionSchema = z.object({
|
|
1774
|
-
status: z.unknown().optional(),
|
|
1775
|
-
pendingMessages: z.array(z.unknown()).catch([]),
|
|
1776
|
-
inboundMessageIds: storedIdListSchema,
|
|
1777
|
-
messageSenders: z.unknown().optional(),
|
|
1778
|
-
lease: z.unknown().optional(),
|
|
1779
|
-
heldInboundMessageIds: z.array(z.string()).optional().catch(void 0),
|
|
1780
|
-
lastCheckpointAtMs: storedOptionalNumberSchema,
|
|
1781
|
-
lastEnqueuedAtMs: storedOptionalNumberSchema,
|
|
1782
|
-
lastProgressAtMs: storedOptionalNumberSchema,
|
|
1783
|
-
retryCount: storedOptionalNumberSchema,
|
|
1784
|
-
runId: storedOptionalStringSchema,
|
|
1785
|
-
updatedAtMs: storedOptionalNumberSchema
|
|
1786
|
-
});
|
|
1787
|
-
/** Decode stored execution state. */
|
|
1788
|
-
function normalizeExecution(conversationId, value) {
|
|
1789
|
-
const parsed = storedExecutionSchema.safeParse(value);
|
|
1790
|
-
if (!parsed.success) return;
|
|
1791
|
-
const stored = parsed.data;
|
|
1792
|
-
const status = normalizeExecutionStatus(stored.status);
|
|
1793
|
-
if (!status) return;
|
|
1794
|
-
const pendingMessages = [];
|
|
1795
|
-
for (const rawMessage of stored.pendingMessages) {
|
|
1796
|
-
const message = normalizeMessage(rawMessage);
|
|
1797
|
-
if (!message || message.conversationId !== conversationId) return;
|
|
1798
|
-
pendingMessages.push(message);
|
|
1799
|
-
}
|
|
1800
|
-
pendingMessages.sort(compareMessages);
|
|
1801
|
-
const inboundMessageIds = uniqueStrings(stored.inboundMessageIds.filter((id) => typeof id === "string" && id.length > 0));
|
|
1802
|
-
const messageSenders = withMessageSenders(normalizeMessageSenders(stored.messageSenders), pendingMessages);
|
|
1803
|
-
const heldInboundMessageIds = stored.heldInboundMessageIds?.filter((id) => pendingMessages.some((message) => message.inboundMessageId === id));
|
|
1804
|
-
return {
|
|
1805
|
-
status,
|
|
1806
|
-
inboundMessageIds: uniqueStrings([...inboundMessageIds, ...pendingMessages.map((message) => message.inboundMessageId)]),
|
|
1807
|
-
...messageSenders ? { messageSenders } : void 0,
|
|
1808
|
-
pendingCount: pendingMessages.length,
|
|
1809
|
-
pendingMessages,
|
|
1810
|
-
lease: normalizeLease(stored.lease),
|
|
1811
|
-
...heldInboundMessageIds?.length ? { heldInboundMessageIds } : void 0,
|
|
1812
|
-
lastCheckpointAtMs: stored.lastCheckpointAtMs,
|
|
1813
|
-
lastEnqueuedAtMs: stored.lastEnqueuedAtMs,
|
|
1814
|
-
lastProgressAtMs: stored.lastProgressAtMs,
|
|
1815
|
-
retryCount: stored.retryCount,
|
|
1816
|
-
runId: stored.runId,
|
|
1817
|
-
updatedAtMs: stored.updatedAtMs
|
|
1818
|
-
};
|
|
1819
|
-
}
|
|
1820
|
-
const storedConversationSchema = z.object({
|
|
1821
|
-
schemaVersion: z.literal(CONVERSATION_SCHEMA_VERSION),
|
|
1822
|
-
conversationId: storedNonEmptyStringSchema,
|
|
1823
|
-
createdAtMs: z.number(),
|
|
1824
|
-
lastActivityAtMs: z.number(),
|
|
1825
|
-
updatedAtMs: z.number(),
|
|
1826
|
-
execution: z.unknown().optional(),
|
|
1827
|
-
destination: z.unknown().optional(),
|
|
1828
|
-
title: storedOptionalStringSchema,
|
|
1829
|
-
channelName: storedOptionalStringSchema,
|
|
1830
|
-
actor: z.unknown().optional(),
|
|
1831
|
-
source: z.unknown().optional()
|
|
1832
|
-
});
|
|
1833
|
-
/** Decode current conversation records. */
|
|
1834
|
-
function normalizeConversation(conversationId, value) {
|
|
1835
|
-
const parsed = storedConversationSchema.safeParse(value);
|
|
1836
|
-
if (!parsed.success) return;
|
|
1837
|
-
const stored = parsed.data;
|
|
1838
|
-
const execution = normalizeExecution(conversationId, stored.execution);
|
|
1839
|
-
const destination = stored.destination === void 0 ? void 0 : parseDestination(stored.destination);
|
|
1840
|
-
if (stored.conversationId !== conversationId || !execution || stored.destination !== void 0 && !destination) return;
|
|
1841
|
-
if (execution.pendingMessages.length > 0 && execution.pendingMessages.some((message) => {
|
|
1842
|
-
if (!message.destination) return false;
|
|
1843
|
-
return !destination || !sameDestination(message.destination, destination);
|
|
1844
|
-
})) return;
|
|
1845
|
-
return {
|
|
1846
|
-
schemaVersion: CONVERSATION_SCHEMA_VERSION,
|
|
1847
|
-
conversationId,
|
|
1848
|
-
createdAtMs: stored.createdAtMs,
|
|
1849
|
-
lastActivityAtMs: stored.lastActivityAtMs,
|
|
1850
|
-
updatedAtMs: stored.updatedAtMs,
|
|
1851
|
-
execution,
|
|
1852
|
-
...destination ? { destination } : void 0,
|
|
1853
|
-
...stored.title ? { title: stored.title } : void 0,
|
|
1854
|
-
...stored.channelName ? { channelName: stored.channelName } : void 0,
|
|
1855
|
-
...normalizeActor(stored.actor) ? { actor: normalizeActor(stored.actor) } : void 0,
|
|
1856
|
-
...normalizeSource(stored.source) ? { source: normalizeSource(stored.source) } : void 0
|
|
1857
|
-
};
|
|
1858
|
-
}
|
|
1859
|
-
function emptyConversation(args) {
|
|
1860
|
-
return {
|
|
1861
|
-
schemaVersion: CONVERSATION_SCHEMA_VERSION,
|
|
1862
|
-
conversationId: args.conversationId,
|
|
1863
|
-
createdAtMs: args.nowMs,
|
|
1864
|
-
lastActivityAtMs: args.nowMs,
|
|
1865
|
-
updatedAtMs: args.nowMs,
|
|
1866
|
-
...args.destination ? { destination: args.destination } : void 0,
|
|
1867
|
-
...args.source ? { source: args.source } : void 0,
|
|
1868
|
-
execution: {
|
|
1869
|
-
status: "idle",
|
|
1870
|
-
inboundMessageIds: [],
|
|
1871
|
-
pendingCount: 0,
|
|
1872
|
-
pendingMessages: [],
|
|
1873
|
-
updatedAtMs: args.nowMs
|
|
1874
|
-
}
|
|
1875
|
-
};
|
|
1876
|
-
}
|
|
1877
|
-
function isLeaseActive(lease, nowMs) {
|
|
1878
|
-
return Boolean(lease && lease.expiresAtMs > nowMs);
|
|
1879
|
-
}
|
|
1880
|
-
function pendingMessages(conversation) {
|
|
1881
|
-
return [...conversation.execution.pendingMessages].sort(compareMessages);
|
|
1882
|
-
}
|
|
1883
|
-
/**
|
|
1884
|
-
* The one runnable check: a worker must start or resume this Conversation.
|
|
1885
|
-
* A `failed` execution is runnable only while new input waits.
|
|
1886
|
-
*/
|
|
1887
|
-
function hasRunnableWork(conversation) {
|
|
1888
|
-
const { status } = conversation.execution;
|
|
1889
|
-
return status !== "failed" && status !== "idle" || conversation.execution.pendingMessages.length > 0;
|
|
1890
|
-
}
|
|
1891
|
-
/**
|
|
1892
|
-
* Reject an execution that no transition may write. Only a Run holds the
|
|
1893
|
-
* lease, and an `idle` Conversation has no input that waits.
|
|
1894
|
-
*/
|
|
1895
|
-
function assertLegalExecution(conversationId, execution) {
|
|
1896
|
-
const { lease, pendingMessages, status } = execution;
|
|
1897
|
-
if (lease && status !== "running" && status !== "paused") throw new Error(`Conversation execution ${status} cannot hold a lease for ${conversationId}`);
|
|
1898
|
-
if (status === "idle" && pendingMessages.length > 0) throw new Error(`Conversation execution idle cannot have pending messages for ${conversationId}`);
|
|
1899
|
-
}
|
|
1900
|
-
function executionWithPendingMessages(execution, pending) {
|
|
1901
|
-
const pendingMessages = [...pending].sort(compareMessages);
|
|
1902
|
-
const messageSenders = withMessageSenders(execution.messageSenders, pendingMessages);
|
|
1903
|
-
return {
|
|
1904
|
-
...execution,
|
|
1905
|
-
inboundMessageIds: uniqueStrings([...execution.inboundMessageIds, ...pendingMessages.map((message) => message.inboundMessageId)]),
|
|
1906
|
-
...messageSenders ? { messageSenders } : void 0,
|
|
1907
|
-
pendingMessages,
|
|
1908
|
-
pendingCount: pendingMessages.length
|
|
1909
|
-
};
|
|
1910
|
-
}
|
|
1911
|
-
function withExecutionUpdate(conversation, execution, nowMs) {
|
|
1912
|
-
return {
|
|
1913
|
-
...conversation,
|
|
1914
|
-
updatedAtMs: nowMs,
|
|
1915
|
-
execution: {
|
|
1916
|
-
...executionWithPendingMessages(execution, execution.pendingMessages),
|
|
1917
|
-
updatedAtMs: nowMs
|
|
1918
|
-
}
|
|
1919
|
-
};
|
|
1920
|
-
}
|
|
1921
|
-
async function getConnectedState(stateAdapter) {
|
|
1922
|
-
const state = stateAdapter ?? getStateAdapter();
|
|
1923
|
-
await state.connect();
|
|
1924
|
-
return state;
|
|
1925
|
-
}
|
|
1926
|
-
async function sleep(ms) {
|
|
1927
|
-
await new Promise((resolve) => {
|
|
1928
|
-
setTimeout(resolve, ms).unref?.();
|
|
1929
|
-
});
|
|
1930
|
-
}
|
|
1931
|
-
async function withIndexLock(state, indexKey, callback) {
|
|
1932
|
-
const startedAtMs = now$1();
|
|
1933
|
-
let lock;
|
|
1934
|
-
while (true) {
|
|
1935
|
-
lock = await state.acquireLock(indexLockKey(indexKey), CONVERSATION_INDEX_LOCK_TTL_MS);
|
|
1936
|
-
if (lock) break;
|
|
1937
|
-
if (now$1() - startedAtMs >= CONVERSATION_INDEX_LOCK_WAIT_MS) throw new Error(`Could not acquire conversation index lock for ${indexKey}`);
|
|
1938
|
-
await sleep(CONVERSATION_INDEX_LOCK_RETRY_MS);
|
|
1939
|
-
}
|
|
1940
|
-
try {
|
|
1941
|
-
return await callback();
|
|
1942
|
-
} finally {
|
|
1943
|
-
await state.releaseLock(lock);
|
|
1944
|
-
}
|
|
1945
|
-
}
|
|
1946
|
-
const storedIndexEntrySchema = z.object({
|
|
1947
|
-
conversationId: storedNonEmptyStringSchema,
|
|
1948
|
-
score: z.number()
|
|
1949
|
-
});
|
|
1950
|
-
function normalizeIndexEntry(value) {
|
|
1951
|
-
const parsed = storedIndexEntrySchema.safeParse(value);
|
|
1952
|
-
return parsed.success ? parsed.data : void 0;
|
|
1953
|
-
}
|
|
1954
|
-
function uniqueIndexEntries(value) {
|
|
1955
|
-
if (!Array.isArray(value)) return [];
|
|
1956
|
-
const entries = /* @__PURE__ */ new Map();
|
|
1957
|
-
for (const item of value) {
|
|
1958
|
-
const entry = normalizeIndexEntry(item);
|
|
1959
|
-
if (!entry) continue;
|
|
1960
|
-
const existing = entries.get(entry.conversationId);
|
|
1961
|
-
if (!existing || entry.score > existing.score) entries.set(entry.conversationId, entry);
|
|
1962
|
-
}
|
|
1963
|
-
return [...entries.values()];
|
|
1964
|
-
}
|
|
1965
|
-
function retainedIndexEntries(indexKey, entries) {
|
|
1966
|
-
if (indexKey === "junior:conversation:v2:by-activity") return entries.sort(compareIndexDescending).slice(0, CONVERSATION_ACTIVITY_INDEX_MAX_LENGTH);
|
|
1967
|
-
if (indexKey === "junior:conversation:v2:active") return entries.sort(compareIndexAscending);
|
|
1968
|
-
throw new Error(`Unknown conversation index ${indexKey}`);
|
|
1969
|
-
}
|
|
1970
|
-
function redisIndexKey(indexKey) {
|
|
1971
|
-
const prefix = getChatConfig().state.keyPrefix;
|
|
1972
|
-
return [...prefix ? [prefix] : [], indexKey].join(":");
|
|
1973
|
-
}
|
|
1974
|
-
function parseRedisIndexEntries(values) {
|
|
1975
|
-
if (!Array.isArray(values)) return [];
|
|
1976
|
-
const entries = [];
|
|
1977
|
-
for (let index = 0; index < values.length; index += 2) {
|
|
1978
|
-
const conversationId = toOptionalString(values[index]);
|
|
1979
|
-
const rawScore = values[index + 1];
|
|
1980
|
-
const score = typeof rawScore === "number" ? rawScore : Number(rawScore);
|
|
1981
|
-
if (!conversationId || !Number.isFinite(score)) continue;
|
|
1982
|
-
entries.push({
|
|
1983
|
-
conversationId,
|
|
1984
|
-
score
|
|
1985
|
-
});
|
|
1986
|
-
}
|
|
1987
|
-
return entries;
|
|
1988
|
-
}
|
|
1989
|
-
function redisConversationIndexStore(client) {
|
|
1990
|
-
const upsertBoundedActivityScript = `
|
|
1991
|
-
redis.call("ZADD", KEYS[1], ARGV[1], ARGV[2])
|
|
1992
|
-
redis.call("PEXPIRE", KEYS[1], ARGV[3])
|
|
1993
|
-
local extra = redis.call("ZCARD", KEYS[1]) - tonumber(ARGV[4])
|
|
1994
|
-
if extra > 0 then
|
|
1995
|
-
redis.call("ZREMRANGEBYRANK", KEYS[1], 0, extra - 1)
|
|
1996
|
-
end
|
|
1997
|
-
return 1
|
|
1998
|
-
`;
|
|
1999
|
-
return {
|
|
2000
|
-
async list(args) {
|
|
2001
|
-
const key = redisIndexKey(args.indexKey);
|
|
2002
|
-
const limit = args.limit;
|
|
2003
|
-
const offset = Math.max(0, args.offset ?? 0);
|
|
2004
|
-
if (limit === 0) return [];
|
|
2005
|
-
return parseRedisIndexEntries(args.scoreMax !== void 0 ? await client.sendCommand([
|
|
2006
|
-
"ZRANGEBYSCORE",
|
|
2007
|
-
key,
|
|
2008
|
-
"-inf",
|
|
2009
|
-
String(args.scoreMax),
|
|
2010
|
-
"WITHSCORES",
|
|
2011
|
-
...limit !== void 0 || offset > 0 ? [
|
|
2012
|
-
"LIMIT",
|
|
2013
|
-
String(offset),
|
|
2014
|
-
String(limit ?? 1e9)
|
|
2015
|
-
] : []
|
|
2016
|
-
]) : await client.sendCommand([
|
|
2017
|
-
args.order === "asc" ? "ZRANGE" : "ZREVRANGE",
|
|
2018
|
-
key,
|
|
2019
|
-
String(offset),
|
|
2020
|
-
String(limit === void 0 ? -1 : offset + Math.max(0, limit - 1)),
|
|
2021
|
-
"WITHSCORES"
|
|
2022
|
-
]));
|
|
2023
|
-
},
|
|
2024
|
-
async remove(args) {
|
|
2025
|
-
await client.sendCommand([
|
|
2026
|
-
"ZREM",
|
|
2027
|
-
redisIndexKey(args.indexKey),
|
|
2028
|
-
args.conversationId
|
|
2029
|
-
]);
|
|
2030
|
-
},
|
|
2031
|
-
async upsert(args) {
|
|
2032
|
-
const key = redisIndexKey(args.indexKey);
|
|
2033
|
-
if (args.indexKey === "junior:conversation:v2:by-activity") {
|
|
2034
|
-
await client.sendCommand([
|
|
2035
|
-
"EVAL",
|
|
2036
|
-
upsertBoundedActivityScript,
|
|
2037
|
-
"1",
|
|
2038
|
-
key,
|
|
2039
|
-
String(args.score),
|
|
2040
|
-
args.conversationId,
|
|
2041
|
-
String(JUNIOR_THREAD_STATE_TTL_MS),
|
|
2042
|
-
String(CONVERSATION_ACTIVITY_INDEX_MAX_LENGTH)
|
|
2043
|
-
]);
|
|
2044
|
-
return;
|
|
2045
|
-
}
|
|
2046
|
-
if (args.indexKey === "junior:conversation:v2:active") {
|
|
2047
|
-
await client.sendCommand([
|
|
2048
|
-
"ZADD",
|
|
2049
|
-
key,
|
|
2050
|
-
String(args.score),
|
|
2051
|
-
args.conversationId
|
|
2052
|
-
]);
|
|
2053
|
-
await client.sendCommand([
|
|
2054
|
-
"PEXPIRE",
|
|
2055
|
-
key,
|
|
2056
|
-
String(JUNIOR_THREAD_STATE_TTL_MS)
|
|
2057
|
-
]);
|
|
2058
|
-
return;
|
|
2059
|
-
}
|
|
2060
|
-
throw new Error(`Unknown conversation index ${args.indexKey}`);
|
|
2061
|
-
}
|
|
2062
|
-
};
|
|
2063
|
-
}
|
|
2064
|
-
function emulatedConversationIndexStore(state) {
|
|
2065
|
-
const readIndex = async (indexKey) => uniqueIndexEntries(await state.get(indexKey));
|
|
2066
|
-
const writeIndex = async (indexKey, entries) => {
|
|
2067
|
-
await state.set(indexKey, entries, JUNIOR_THREAD_STATE_TTL_MS);
|
|
2068
|
-
};
|
|
2069
|
-
return {
|
|
2070
|
-
async list(args) {
|
|
2071
|
-
const entries = (await readIndex(args.indexKey)).filter((entry) => args.scoreMax === void 0 ? true : entry.score <= args.scoreMax).sort(args.order === "asc" ? compareIndexAscending : compareIndexDescending);
|
|
2072
|
-
const offset = Math.max(0, args.offset ?? 0);
|
|
2073
|
-
return entries.slice(offset, args.limit === void 0 ? entries.length : offset + args.limit);
|
|
2074
|
-
},
|
|
2075
|
-
async remove(args) {
|
|
2076
|
-
await withIndexLock(state, args.indexKey, async () => {
|
|
2077
|
-
const entries = await readIndex(args.indexKey);
|
|
2078
|
-
const next = entries.filter((entry) => entry.conversationId !== args.conversationId);
|
|
2079
|
-
if (next.length === entries.length) return;
|
|
2080
|
-
await writeIndex(args.indexKey, next);
|
|
2081
|
-
});
|
|
2082
|
-
},
|
|
2083
|
-
async upsert(args) {
|
|
2084
|
-
await withIndexLock(state, args.indexKey, async () => {
|
|
2085
|
-
const withoutCurrent = (await readIndex(args.indexKey)).filter((entry) => entry.conversationId !== args.conversationId);
|
|
2086
|
-
const next = retainedIndexEntries(args.indexKey, [...withoutCurrent, {
|
|
2087
|
-
conversationId: args.conversationId,
|
|
2088
|
-
score: args.score
|
|
2089
|
-
}]);
|
|
2090
|
-
await writeIndex(args.indexKey, next);
|
|
2091
|
-
});
|
|
2092
|
-
}
|
|
2093
|
-
};
|
|
2094
|
-
}
|
|
2095
|
-
async function getConversationIndexStore(state) {
|
|
2096
|
-
const redisStateAdapter = await getDefaultRedisStateAdapterFor(state);
|
|
2097
|
-
if (redisStateAdapter) return redisConversationIndexStore(redisStateAdapter.getClient());
|
|
2098
|
-
return emulatedConversationIndexStore(state);
|
|
2099
|
-
}
|
|
2100
|
-
async function upsertIndexEntry(args) {
|
|
2101
|
-
await (await getConversationIndexStore(args.state)).upsert({
|
|
2102
|
-
conversationId: args.conversationId,
|
|
2103
|
-
indexKey: args.indexKey,
|
|
2104
|
-
score: args.score
|
|
2105
|
-
});
|
|
2106
|
-
}
|
|
2107
|
-
async function removeIndexEntry(args) {
|
|
2108
|
-
await (await getConversationIndexStore(args.state)).remove({
|
|
2109
|
-
conversationId: args.conversationId,
|
|
2110
|
-
indexKey: args.indexKey
|
|
2111
|
-
});
|
|
2112
|
-
}
|
|
2113
|
-
async function acquireMutationLock(state, conversationId) {
|
|
2114
|
-
const startedAtMs = now$1();
|
|
2115
|
-
while (true) {
|
|
2116
|
-
const lock = await state.acquireLock(mutationLockKey(conversationId), CONVERSATION_MUTATION_LOCK_TTL_MS);
|
|
2117
|
-
if (lock) return lock;
|
|
2118
|
-
if (now$1() - startedAtMs >= CONVERSATION_MUTATION_WAIT_MS) throw new Error(`Could not acquire conversation mutation lock for ${conversationId}`);
|
|
2119
|
-
await sleep(CONVERSATION_MUTATION_RETRY_MS);
|
|
2120
|
-
}
|
|
2121
|
-
}
|
|
2122
|
-
async function withConversationMutation(args, callback) {
|
|
2123
|
-
const state = await getConnectedState(args.state);
|
|
2124
|
-
const lock = await acquireMutationLock(state, args.conversationId);
|
|
2125
|
-
try {
|
|
2126
|
-
return await callback(state, lock);
|
|
2127
|
-
} finally {
|
|
2128
|
-
await state.releaseLock(lock);
|
|
2129
|
-
}
|
|
2130
|
-
}
|
|
2131
|
-
async function readConversation(state, conversationId) {
|
|
2132
|
-
return conversationFromValue(conversationId, await state.get(conversationKey(conversationId)));
|
|
2133
|
-
}
|
|
2134
|
-
function conversationFromValue(conversationId, raw) {
|
|
2135
|
-
if (raw == null) return;
|
|
2136
|
-
const conversation = normalizeConversation(conversationId, raw);
|
|
2137
|
-
if (!conversation) throw new InvalidConversationRecordError(conversationId);
|
|
2138
|
-
return conversation;
|
|
2139
|
-
}
|
|
2140
|
-
/**
|
|
2141
|
-
* Persist a conversation and refresh its reporting and active-recovery indexes.
|
|
2142
|
-
*
|
|
2143
|
-
* Conversation writes are lock-serialized blind whole-record writes, so the
|
|
2144
|
-
* mutation lock is re-validated (and extended) immediately before the write:
|
|
2145
|
-
* a stalled mutator that lost its lock must fail loudly instead of clobbering
|
|
2146
|
-
* a newer record with a stale copy.
|
|
2147
|
-
*/
|
|
2148
|
-
async function writeConversation(state, lock, conversation) {
|
|
2149
|
-
const execution = executionWithPendingMessages(conversation.execution, conversation.execution.pendingMessages);
|
|
2150
|
-
assertLegalExecution(conversation.conversationId, execution);
|
|
2151
|
-
const next = {
|
|
2152
|
-
...conversation,
|
|
2153
|
-
execution
|
|
2154
|
-
};
|
|
2155
|
-
await fenceConversationMutation(state, lock, next.conversationId);
|
|
2156
|
-
const hasSlackDestination = next.destination?.platform === "slack";
|
|
2157
|
-
const stored = {
|
|
2158
|
-
...next,
|
|
2159
|
-
execution: {
|
|
2160
|
-
...next.execution,
|
|
2161
|
-
pendingMessages: next.execution.pendingMessages.map((message) => storeMessage(message, hasSlackDestination && (message.source === "slack" || message.source === "event" || message.source === "plugin" || message.source === "scheduler")))
|
|
2162
|
-
}
|
|
2163
|
-
};
|
|
2164
|
-
await state.set(conversationKey(next.conversationId), stored, JUNIOR_THREAD_STATE_TTL_MS);
|
|
2165
|
-
await upsertIndexEntry({
|
|
2166
|
-
state,
|
|
2167
|
-
indexKey: CONVERSATION_BY_ACTIVITY_INDEX_KEY,
|
|
2168
|
-
conversationId: next.conversationId,
|
|
2169
|
-
score: next.lastActivityAtMs
|
|
2170
|
-
});
|
|
2171
|
-
if (!hasRunnableWork(next)) {
|
|
2172
|
-
await removeIndexEntry({
|
|
2173
|
-
state,
|
|
2174
|
-
indexKey: CONVERSATION_ACTIVE_INDEX_KEY,
|
|
2175
|
-
conversationId: next.conversationId
|
|
2176
|
-
});
|
|
2177
|
-
return;
|
|
2178
|
-
}
|
|
2179
|
-
await upsertIndexEntry({
|
|
2180
|
-
state,
|
|
2181
|
-
indexKey: CONVERSATION_ACTIVE_INDEX_KEY,
|
|
2182
|
-
conversationId: next.conversationId,
|
|
2183
|
-
score: next.execution.updatedAtMs ?? next.updatedAtMs
|
|
2184
|
-
});
|
|
2185
|
-
}
|
|
2186
|
-
function assertSameOptionalConversationDestination(args) {
|
|
2187
|
-
if (!args.next || !args.current) return;
|
|
2188
|
-
if (sameDestination(args.current, args.next)) return;
|
|
2189
|
-
throw new Error(`Conversation destination changed for ${args.conversationId}`);
|
|
2190
|
-
}
|
|
2191
|
-
function conversationWorkState(conversation) {
|
|
2192
|
-
const lease = conversation.execution.lease;
|
|
2193
|
-
return {
|
|
2194
|
-
...conversation,
|
|
2195
|
-
lastEnqueuedAtMs: conversation.execution.lastEnqueuedAtMs,
|
|
2196
|
-
...lease ? { lease: {
|
|
2197
|
-
acquiredAtMs: lease.acquiredAtMs,
|
|
2198
|
-
lastCheckInAtMs: lease.lastCheckInAtMs,
|
|
2199
|
-
leaseExpiresAtMs: lease.expiresAtMs,
|
|
2200
|
-
leaseToken: lease.token
|
|
2201
|
-
} } : void 0,
|
|
2202
|
-
messages: pendingMessages(conversation),
|
|
2203
|
-
needsRun: hasRunnableWork(conversation),
|
|
2204
|
-
runningInboundMessageIds: isLeaseActive(lease, now$1()) ? [...lease?.attemptInboundMessageIds ?? []] : []
|
|
2205
|
-
};
|
|
2206
|
-
}
|
|
2207
|
-
/** Return a persisted conversation record, if one exists. */
|
|
2208
|
-
async function getConversation$1(args) {
|
|
2209
|
-
return await readConversation(await getConnectedState(args.state), args.conversationId);
|
|
2210
|
-
}
|
|
2211
|
-
/** Return a persisted conversation work record, if one exists. */
|
|
2212
|
-
async function getConversationWorkState$1(args) {
|
|
2213
|
-
const conversation = await getConversation$1(args);
|
|
2214
|
-
return conversation ? conversationWorkState(conversation) : void 0;
|
|
2215
|
-
}
|
|
2216
|
-
/**
|
|
2217
|
-
* Return the persisted work records of several Conversations in one state
|
|
2218
|
-
* read. A Conversation with no record has no entry.
|
|
2219
|
-
*/
|
|
2220
|
-
async function getConversationWorkStates$1(conversationIds) {
|
|
2221
|
-
const state = await getConnectedState();
|
|
2222
|
-
const values = await getStateValues(state, conversationIds.map(conversationKey));
|
|
2223
|
-
const workStates = /* @__PURE__ */ new Map();
|
|
2224
|
-
for (const [index, conversationId] of conversationIds.entries()) {
|
|
2225
|
-
const conversation = conversationFromValue(conversationId, values[index]);
|
|
2226
|
-
if (conversation) workStates.set(conversationId, conversationWorkState(conversation));
|
|
2227
|
-
}
|
|
2228
|
-
return workStates;
|
|
2229
|
-
}
|
|
2230
|
-
/** Count mailbox messages that have not yet reached the conversation event log. */
|
|
2231
|
-
function countPendingConversationMessages(conversation) {
|
|
2232
|
-
return pendingMessages(conversation).length;
|
|
2233
|
-
}
|
|
2234
|
-
/** Return whether a conversation has pending or resumable execution work. */
|
|
2235
|
-
function hasRunnableConversationWork(conversation) {
|
|
2236
|
-
return hasRunnableWork(conversation);
|
|
2237
|
-
}
|
|
2238
|
-
/** Read the Conversation of an inbound message, or a new one for it. */
|
|
2239
|
-
async function readInboundConversation(state, message, nowMs) {
|
|
2240
|
-
const existing = await readConversation(state, message.conversationId);
|
|
2241
|
-
if (!existing) return emptyConversation({
|
|
2242
|
-
conversationId: message.conversationId,
|
|
2243
|
-
destination: message.destination,
|
|
2244
|
-
nowMs,
|
|
2245
|
-
source: message.source
|
|
2246
|
-
});
|
|
2247
|
-
assertSameOptionalConversationDestination({
|
|
2248
|
-
conversationId: message.conversationId,
|
|
2249
|
-
current: existing.destination,
|
|
2250
|
-
next: message.destination
|
|
2251
|
-
});
|
|
2252
|
-
return existing;
|
|
2253
|
-
}
|
|
2254
|
-
async function appendInboundMessageWithAdmission(args) {
|
|
2255
|
-
const nowMs = args.nowMs ?? now$1();
|
|
2256
|
-
return await withConversationMutation({
|
|
2257
|
-
conversationId: args.message.conversationId,
|
|
2258
|
-
state: args.state
|
|
2259
|
-
}, async (state, lock) => {
|
|
2260
|
-
const current = await readInboundConversation(state, args.message, nowMs);
|
|
2261
|
-
const existingPending = current.execution.pendingMessages.some((message) => message.inboundMessageId === args.message.inboundMessageId);
|
|
2262
|
-
if (current.execution.inboundMessageIds.includes(args.message.inboundMessageId)) {
|
|
2263
|
-
if (!existingPending) return { status: "duplicate" };
|
|
2264
|
-
const nextStatus = current.execution.status === "idle" ? "pending" : current.execution.status;
|
|
2265
|
-
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
2266
|
-
...current.execution,
|
|
2267
|
-
status: nextStatus,
|
|
2268
|
-
pendingMessages: current.execution.pendingMessages.map((message) => message.inboundMessageId === args.message.inboundMessageId ? upgradedPendingMessage(message, args.message) : message)
|
|
2269
|
-
}, nowMs));
|
|
2270
|
-
return { status: "duplicate" };
|
|
2271
|
-
}
|
|
2272
|
-
if (args.exclusive && hasRunnableWork(current)) return { status: "active" };
|
|
2273
|
-
const text = args.renderText ? await args.renderText(current.execution.inboundMessageIds, current.execution.messageSenders ?? {}) : args.message.input.text;
|
|
2274
|
-
if (text === void 0) {
|
|
2275
|
-
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
2276
|
-
...current.execution,
|
|
2277
|
-
inboundMessageIds: [...current.execution.inboundMessageIds, args.message.inboundMessageId],
|
|
2278
|
-
messageSenders: withMessageSenders(current.execution.messageSenders, [args.message])
|
|
2279
|
-
}, nowMs));
|
|
2280
|
-
return { status: "duplicate" };
|
|
2281
|
-
}
|
|
2282
|
-
const message = {
|
|
2283
|
-
...args.message,
|
|
2284
|
-
input: {
|
|
2285
|
-
...args.message.input,
|
|
2286
|
-
text
|
|
2287
|
-
}
|
|
2288
|
-
};
|
|
2289
|
-
let status;
|
|
2290
|
-
if (current.execution.lease) status = current.execution.status === "running" ? "running" : "paused";
|
|
2291
|
-
else if (current.execution.status === "paused" && !isAttemptInterrupt(args.message, current)) status = "paused";
|
|
2292
|
-
else status = "pending";
|
|
2293
|
-
await writeConversation(state, lock, withExecutionUpdate({
|
|
2294
|
-
...current,
|
|
2295
|
-
destination: current.destination ?? args.message.destination,
|
|
2296
|
-
source: current.source ?? args.message.source,
|
|
2297
|
-
lastActivityAtMs: nowMs
|
|
2298
|
-
}, {
|
|
2299
|
-
...current.execution,
|
|
2300
|
-
status,
|
|
2301
|
-
inboundMessageIds: [...current.execution.inboundMessageIds, args.message.inboundMessageId],
|
|
2302
|
-
pendingMessages: [...current.execution.pendingMessages, message].sort(compareMessages)
|
|
2303
|
-
}, nowMs));
|
|
2304
|
-
return { status: "appended" };
|
|
2305
|
-
});
|
|
2306
|
-
}
|
|
2307
|
-
/** Persist one inbound message idempotently in its conversation mailbox. */
|
|
2308
|
-
async function appendInboundMessage$1(args) {
|
|
2309
|
-
const result = await appendInboundMessageWithAdmission({
|
|
2310
|
-
...args,
|
|
2311
|
-
exclusive: false
|
|
2312
|
-
});
|
|
2313
|
-
if (result.status === "active") throw new Error("Non-exclusive mailbox append returned active");
|
|
2314
|
-
return result;
|
|
2315
|
-
}
|
|
2316
|
-
/**
|
|
2317
|
-
* Record an inbound message id without adding the message to the mailbox.
|
|
2318
|
-
* Ingress uses it for input that it handles itself, such as a Slack `stop`.
|
|
2319
|
-
* The id is a duplicate after that, for this claim and for the mailbox, so
|
|
2320
|
-
* one message is handled once. A claim that fails after its duplicate check
|
|
2321
|
-
* is released, so a redelivery can claim again. A claim that fails before
|
|
2322
|
-
* it keeps an id that an earlier delivery saved.
|
|
2323
|
-
*/
|
|
2324
|
-
async function claimInboundMessage$1(args) {
|
|
2325
|
-
const nowMs = args.nowMs ?? now$1();
|
|
2326
|
-
let claimWritten = false;
|
|
2327
|
-
try {
|
|
2328
|
-
return await withConversationMutation({
|
|
2329
|
-
conversationId: args.message.conversationId,
|
|
2330
|
-
state: args.state
|
|
2331
|
-
}, async (state, lock) => {
|
|
2332
|
-
const current = await readInboundConversation(state, args.message, nowMs);
|
|
2333
|
-
if (current.execution.inboundMessageIds.includes(args.message.inboundMessageId)) return { status: "duplicate" };
|
|
2334
|
-
claimWritten = true;
|
|
2335
|
-
await writeConversation(state, lock, withExecutionUpdate({
|
|
2336
|
-
...current,
|
|
2337
|
-
destination: current.destination ?? args.message.destination,
|
|
2338
|
-
source: current.source ?? args.message.source,
|
|
2339
|
-
lastActivityAtMs: nowMs
|
|
2340
|
-
}, {
|
|
2341
|
-
...current.execution,
|
|
2342
|
-
inboundMessageIds: [...current.execution.inboundMessageIds, args.message.inboundMessageId]
|
|
2343
|
-
}, nowMs));
|
|
2344
|
-
return { status: "claimed" };
|
|
2345
|
-
});
|
|
2346
|
-
} catch (error) {
|
|
2347
|
-
if (claimWritten) await releaseInboundMessage(args);
|
|
2348
|
-
throw error;
|
|
2349
|
-
}
|
|
2350
|
-
}
|
|
2351
|
-
/**
|
|
2352
|
-
* Release a claim from `claimInboundMessage`, so a redelivery of the message
|
|
2353
|
-
* is new again. A message that waits in the mailbox keeps its id. It runs
|
|
2354
|
-
* after a failure, so a failed release is logged and not thrown, and the
|
|
2355
|
-
* error that caused it wins.
|
|
2356
|
-
*/
|
|
2357
|
-
async function releaseInboundMessage(args) {
|
|
2358
|
-
const nowMs = args.nowMs ?? now$1();
|
|
2359
|
-
const id = args.message.inboundMessageId;
|
|
2360
|
-
try {
|
|
2361
|
-
await withConversationMutation({
|
|
2362
|
-
conversationId: args.message.conversationId,
|
|
2363
|
-
state: args.state
|
|
2364
|
-
}, async (state, lock) => {
|
|
2365
|
-
const current = await readInboundConversation(state, args.message, nowMs);
|
|
2366
|
-
if (!current.execution.inboundMessageIds.includes(id) || current.execution.pendingMessages.some((message) => message.inboundMessageId === id)) return;
|
|
2367
|
-
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
2368
|
-
...current.execution,
|
|
2369
|
-
inboundMessageIds: current.execution.inboundMessageIds.filter((inboundMessageId) => inboundMessageId !== id)
|
|
2370
|
-
}, nowMs));
|
|
2371
|
-
});
|
|
2372
|
-
} catch (error) {
|
|
2373
|
-
logException(error, "conversation.stop.release.failed");
|
|
2374
|
-
}
|
|
2375
|
-
}
|
|
2376
|
-
/** Append only when the Conversation has no other runnable work. */
|
|
2377
|
-
async function appendExclusiveInboundMessage(args) {
|
|
2378
|
-
return await appendInboundMessageWithAdmission({
|
|
2379
|
-
...args,
|
|
2380
|
-
exclusive: true
|
|
2381
|
-
});
|
|
2382
|
-
}
|
|
2383
|
-
/** Mark a conversation runnable when there is no new mailbox message. */
|
|
2384
|
-
async function requestConversationWork$1(args) {
|
|
2385
|
-
const nowMs = args.nowMs ?? now$1();
|
|
2386
|
-
return await withConversationMutation(args, async (state, lock) => {
|
|
2387
|
-
const existing = await readConversation(state, args.conversationId);
|
|
2388
|
-
if (existing) assertSameOptionalConversationDestination({
|
|
2389
|
-
conversationId: args.conversationId,
|
|
2390
|
-
current: existing.destination,
|
|
2391
|
-
next: args.destination
|
|
2392
|
-
});
|
|
2393
|
-
const current = existing ?? emptyConversation({
|
|
2394
|
-
conversationId: args.conversationId,
|
|
2395
|
-
destination: args.destination,
|
|
2396
|
-
nowMs
|
|
2397
|
-
});
|
|
2398
|
-
const status = current.execution.lease ? "paused" : "pending";
|
|
2399
|
-
await writeConversation(state, lock, withExecutionUpdate({
|
|
2400
|
-
...current,
|
|
2401
|
-
destination: current.destination ?? args.destination
|
|
2402
|
-
}, {
|
|
2403
|
-
...current.execution,
|
|
2404
|
-
status
|
|
2405
|
-
}, nowMs));
|
|
2406
|
-
return { status: existing === void 0 ? "created" : "updated" };
|
|
2407
|
-
});
|
|
2408
|
-
}
|
|
2409
|
-
/**
|
|
2410
|
-
* Move a Conversation that has no active Run to a new Destination.
|
|
2411
|
-
*
|
|
2412
|
-
* `move` commits the durable change while this holds the mutation lock, so
|
|
2413
|
-
* no inbound Message can join with the old Destination in between. Pending
|
|
2414
|
-
* Messages get the new Destination too. A Run that holds the lease or waits
|
|
2415
|
-
* to resume keeps its own copy, so this returns `busy` without calling
|
|
2416
|
-
* `move`.
|
|
2417
|
-
*/
|
|
2418
|
-
async function moveIdleConversationDestination(args) {
|
|
2419
|
-
return await withConversationMutation(args, async (state, lock) => {
|
|
2420
|
-
const existing = await readConversation(state, args.conversationId);
|
|
2421
|
-
if (existing && isHeldByRun(existing)) return "busy";
|
|
2422
|
-
if (!await args.move()) return "not_moved";
|
|
2423
|
-
if (existing) await writeConversation(state, lock, {
|
|
2424
|
-
...existing,
|
|
2425
|
-
destination: args.destination,
|
|
2426
|
-
execution: {
|
|
2427
|
-
...existing.execution,
|
|
2428
|
-
pendingMessages: existing.execution.pendingMessages.map((message) => ({
|
|
2429
|
-
...message,
|
|
2430
|
-
destination: args.destination
|
|
2431
|
-
}))
|
|
2432
|
-
}
|
|
2433
|
-
});
|
|
2434
|
-
return "moved";
|
|
2435
|
-
});
|
|
2436
|
-
}
|
|
2437
|
-
/**
|
|
2438
|
-
* Run `work` while no Run holds the Conversation and no work waits for one.
|
|
2439
|
-
* A Run takes its lease under the same mutation lock, so none can start until
|
|
2440
|
-
* `work` ends. Returns `busy` without calling `work` when a Run holds the
|
|
2441
|
-
* Conversation or work waits, such as a pending mailbox message: that Run
|
|
2442
|
-
* reads the history next, so `work` must not change it first. `work` calls
|
|
2443
|
-
* `fence` right before its durable write; it throws when the lock expired.
|
|
2444
|
-
*/
|
|
2445
|
-
async function withIdleConversation(args, work) {
|
|
2446
|
-
return await withConversationMutation(args, async (state, lock) => {
|
|
2447
|
-
const existing = await readConversation(state, args.conversationId);
|
|
2448
|
-
if (existing && (isHeldByRun(existing) || hasRunnableWork(existing))) return "busy";
|
|
2449
|
-
return await work(() => fenceConversationMutation(state, lock, args.conversationId));
|
|
2450
|
-
});
|
|
2451
|
-
}
|
|
2452
|
-
function isHeldByRun(conversation) {
|
|
2453
|
-
return conversation.execution.lease !== void 0 || conversation.execution.status === "running" || conversation.execution.status === "paused";
|
|
2454
|
-
}
|
|
2455
|
-
/**
|
|
2456
|
-
* Store one Destination move until the Run that holds the Conversation ends.
|
|
2457
|
-
*
|
|
2458
|
-
* The first stored move wins: a later call gets it back. With no Run, this
|
|
2459
|
-
* stores nothing and returns `idle`, so the caller moves now.
|
|
2460
|
-
*/
|
|
2461
|
-
async function deferConversationMove(args) {
|
|
2462
|
-
return await withConversationMutation(args, async (state, lock) => {
|
|
2463
|
-
const existing = await readConversation(state, args.conversationId);
|
|
2464
|
-
if (!existing || !isHeldByRun(existing)) return { status: "idle" };
|
|
2465
|
-
const key = deferredMoveKey(args.conversationId);
|
|
2466
|
-
const stored = await state.get(key);
|
|
2467
|
-
if (stored !== null) return {
|
|
2468
|
-
move: stored,
|
|
2469
|
-
status: "deferred"
|
|
2470
|
-
};
|
|
2471
|
-
await fenceConversationMutation(state, lock, args.conversationId);
|
|
2472
|
-
await state.set(key, args.move, JUNIOR_THREAD_STATE_TTL_MS);
|
|
2473
|
-
return {
|
|
2474
|
-
move: args.move,
|
|
2475
|
-
status: "deferred"
|
|
2476
|
-
};
|
|
2477
|
-
});
|
|
2478
|
-
}
|
|
2479
|
-
/**
|
|
2480
|
-
* Remove and return the deferred move once no Run holds the Conversation.
|
|
2481
|
-
* The caller runs it, and defers it again when a new Run started first.
|
|
2482
|
-
*/
|
|
2483
|
-
async function takeDeferredConversationMove(args) {
|
|
2484
|
-
const key = deferredMoveKey(args.conversationId);
|
|
2485
|
-
if (await (await getConnectedState(args.state)).get(key) === null) return;
|
|
2486
|
-
return await withConversationMutation(args, async (state, lock) => {
|
|
2487
|
-
const existing = await readConversation(state, args.conversationId);
|
|
2488
|
-
if (existing && isHeldByRun(existing)) return void 0;
|
|
2489
|
-
const stored = await state.get(key);
|
|
2490
|
-
if (stored === null) return void 0;
|
|
2491
|
-
await fenceConversationMutation(state, lock, args.conversationId);
|
|
2492
|
-
await state.delete(key);
|
|
2493
|
-
return stored;
|
|
2494
|
-
});
|
|
2495
|
-
}
|
|
2496
|
-
/** Record that a wake-up nudge was accepted for the conversation. */
|
|
2497
|
-
async function markConversationWorkEnqueued$1(args) {
|
|
2498
|
-
const nowMs = args.nowMs ?? now$1();
|
|
2499
|
-
await withConversationMutation(args, async (state, lock) => {
|
|
2500
|
-
const current = await readConversation(state, args.conversationId);
|
|
2501
|
-
if (!current) return;
|
|
2502
|
-
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
2503
|
-
...current.execution,
|
|
2504
|
-
lastEnqueuedAtMs: nowMs
|
|
2505
|
-
}, nowMs));
|
|
2506
|
-
});
|
|
2507
|
-
}
|
|
2508
|
-
/** Clear a wake marker after its queue delivery finds no runnable work. */
|
|
2509
|
-
async function clearConsumedConversationWake$1(args) {
|
|
2510
|
-
const nowMs = args.nowMs ?? now$1();
|
|
2511
|
-
return await withConversationMutation(args, async (state, lock) => {
|
|
2512
|
-
const current = await readConversation(state, args.conversationId);
|
|
2513
|
-
if (!current || hasRunnableWork(current) || current.execution.lastEnqueuedAtMs === void 0) return false;
|
|
2514
|
-
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
2515
|
-
...current.execution,
|
|
2516
|
-
lastEnqueuedAtMs: void 0
|
|
2517
|
-
}, nowMs));
|
|
2518
|
-
return true;
|
|
2519
|
-
});
|
|
2520
|
-
}
|
|
2521
|
-
/** Try to acquire the durable execution lease for one conversation. */
|
|
2522
|
-
async function startConversationWork$1(args) {
|
|
2523
|
-
const nowMs = args.nowMs ?? now$1();
|
|
2524
|
-
return await withConversationMutation(args, async (state, lock) => {
|
|
2525
|
-
const current = await readConversation(state, args.conversationId);
|
|
2526
|
-
if (!current) return { status: "no_work" };
|
|
2527
|
-
if (isLeaseActive(current.execution.lease, nowMs)) return {
|
|
2528
|
-
status: "active",
|
|
2529
|
-
leaseExpiresAtMs: current.execution.lease.expiresAtMs
|
|
2530
|
-
};
|
|
2531
|
-
if (!hasRunnableWork(current)) return { status: "no_work" };
|
|
2532
|
-
const lease = {
|
|
2533
|
-
token: randomUUID(),
|
|
2534
|
-
acquiredAtMs: nowMs,
|
|
2535
|
-
lastCheckInAtMs: nowMs,
|
|
2536
|
-
expiresAtMs: nowMs + CONVERSATION_WORK_LEASE_TTL_MS
|
|
2537
|
-
};
|
|
2538
|
-
const startsNewRun = current.execution.runId === void 0;
|
|
2539
|
-
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
2540
|
-
...current.execution,
|
|
2541
|
-
lease,
|
|
2542
|
-
status: current.execution.status === "paused" ? "paused" : "running",
|
|
2543
|
-
runId: current.execution.runId ?? randomUUID(),
|
|
2544
|
-
lastEnqueuedAtMs: void 0,
|
|
2545
|
-
retryCount: startsNewRun ? 0 : current.execution.retryCount
|
|
2546
|
-
}, nowMs));
|
|
2547
|
-
return {
|
|
2548
|
-
status: "acquired",
|
|
2549
|
-
leaseToken: lease.token,
|
|
2550
|
-
leaseExpiresAtMs: lease.expiresAtMs
|
|
2551
|
-
};
|
|
2552
|
-
});
|
|
2553
|
-
}
|
|
2554
|
-
/** Extend the durable execution lease when the worker checks in. */
|
|
2555
|
-
async function checkInConversationWork$1(args) {
|
|
2556
|
-
const nowMs = args.nowMs ?? now$1();
|
|
2557
|
-
return await withConversationMutation(args, async (state, lock) => {
|
|
2558
|
-
const current = await readConversation(state, args.conversationId);
|
|
2559
|
-
if (!current || current.execution.lease?.token !== args.leaseToken) return false;
|
|
2560
|
-
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
2561
|
-
...current.execution,
|
|
2562
|
-
lease: {
|
|
2563
|
-
...current.execution.lease,
|
|
2564
|
-
lastCheckInAtMs: nowMs,
|
|
2565
|
-
expiresAtMs: nowMs + CONVERSATION_WORK_LEASE_TTL_MS
|
|
2566
|
-
}
|
|
2567
|
-
}, nowMs));
|
|
2568
|
-
return true;
|
|
2569
|
-
});
|
|
2570
|
-
}
|
|
2571
|
-
/**
|
|
2572
|
-
* Resolve pending mailbox entries after the caller accepts responsibility.
|
|
2573
|
-
*
|
|
2574
|
-
* Returning ids acknowledges only that subset; returning nothing acknowledges
|
|
2575
|
-
* every pending entry passed to the handler.
|
|
2576
|
-
*/
|
|
2577
|
-
async function drainConversationMailbox$1(args) {
|
|
2578
|
-
const nowMs = args.nowMs ?? now$1();
|
|
2579
|
-
const pending = await withConversationMutation(args, async (state) => {
|
|
2580
|
-
const current = await readConversation(state, args.conversationId);
|
|
2581
|
-
if (!current || current.execution.lease?.token !== args.leaseToken) throw new Error(`Conversation lease is not held for ${args.conversationId}`);
|
|
2582
|
-
return pendingMessages(current);
|
|
2583
|
-
});
|
|
2584
|
-
if (pending.length === 0) return {
|
|
2585
|
-
changed: false,
|
|
2586
|
-
messages: []
|
|
2587
|
-
};
|
|
2588
|
-
const result = await args.handle(pending);
|
|
2589
|
-
const pendingIds = new Set(pending.map((message) => message.inboundMessageId));
|
|
2590
|
-
const acknowledgedIds = new Set(result ?? pending.map((message) => message.inboundMessageId));
|
|
2591
|
-
for (const inboundMessageId of acknowledgedIds) if (!pendingIds.has(inboundMessageId)) throw new Error(`Conversation mailbox drain result is not pending for ${args.conversationId}`);
|
|
2592
|
-
if (acknowledgedIds.size === 0) return {
|
|
2593
|
-
changed: false,
|
|
2594
|
-
messages: []
|
|
2595
|
-
};
|
|
2596
|
-
await withConversationMutation(args, async (state, lock) => {
|
|
2597
|
-
const current = await readConversation(state, args.conversationId);
|
|
2598
|
-
if (!current || current.execution.lease?.token !== args.leaseToken) throw new Error(`Conversation lease is not held for ${args.conversationId}`);
|
|
2599
|
-
const pendingMessages = current.execution.pendingMessages.filter((message) => !acknowledgedIds.has(message.inboundMessageId));
|
|
2600
|
-
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
2601
|
-
...current.execution,
|
|
2602
|
-
status: current.execution.status === "pending" && pendingMessages.length === 0 ? "running" : current.execution.status,
|
|
2603
|
-
lastProgressAtMs: nowMs,
|
|
2604
|
-
retryCount: 0,
|
|
2605
|
-
pendingMessages
|
|
2606
|
-
}, nowMs));
|
|
2607
|
-
});
|
|
2608
|
-
return {
|
|
2609
|
-
changed: true,
|
|
2610
|
-
messages: pending.filter((message) => acknowledgedIds.has(message.inboundMessageId))
|
|
2611
|
-
};
|
|
2612
|
-
}
|
|
2613
|
-
/** Acknowledge leased mailbox entries after the handler accepts responsibility. */
|
|
2614
|
-
async function ackMessages$1(args) {
|
|
2615
|
-
const nowMs = args.nowMs ?? now$1();
|
|
2616
|
-
const inboundMessageIds = new Set(args.inboundMessageIds);
|
|
2617
|
-
return await withConversationMutation(args, async (state, lock) => {
|
|
2618
|
-
const current = await readConversation(state, args.conversationId);
|
|
2619
|
-
if (!current || current.execution.lease?.token !== args.leaseToken) return false;
|
|
2620
|
-
if (inboundMessageIds.size === 0) return true;
|
|
2621
|
-
const pendingMessages = current.execution.pendingMessages.filter((message) => !inboundMessageIds.has(message.inboundMessageId));
|
|
2622
|
-
if (pendingMessages.length === current.execution.pendingMessages.length) return true;
|
|
2623
|
-
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
2624
|
-
...current.execution,
|
|
2625
|
-
lastProgressAtMs: nowMs,
|
|
2626
|
-
retryCount: 0,
|
|
2627
|
-
pendingMessages
|
|
2628
|
-
}, nowMs));
|
|
2629
|
-
return true;
|
|
2630
|
-
});
|
|
2631
|
-
}
|
|
2632
|
-
async function readConversationStop(state, conversationId) {
|
|
2633
|
-
return normalizeStop(await state.get(conversationStopKey(conversationId)));
|
|
2634
|
-
}
|
|
2635
|
-
async function fenceConversationMutation(state, lock, conversationId) {
|
|
2636
|
-
if (!await state.extendLock(lock, CONVERSATION_MUTATION_LOCK_TTL_MS)) throw new ConversationMutationFencedError(conversationId);
|
|
2637
|
-
}
|
|
2638
|
-
/** Return whether one Conversation run has a durable stop request. */
|
|
2639
|
-
async function hasConversationStop(args) {
|
|
2640
|
-
return (await readConversationStop(await getConnectedState(args.state), args.conversationId))?.runId === args.runId;
|
|
2641
|
-
}
|
|
2642
|
-
/** Persist a stop request for the current run without process affinity. */
|
|
2643
|
-
async function stopConversationWork$1(args) {
|
|
2644
|
-
const nowMs = args.nowMs ?? now$1();
|
|
2645
|
-
return await withConversationMutation(args, async (state, lock) => {
|
|
2646
|
-
const current = await readConversation(state, args.conversationId);
|
|
2647
|
-
if (!current || !hasRunnableWork(current)) return { status: "no_work" };
|
|
2648
|
-
const runId = current.execution.runId ?? randomUUID();
|
|
2649
|
-
const pendingMessages = current.execution.pendingMessages.filter((message) => isPersonInput(message.source) && (args.sentAtOrBeforeMs === void 0 || message.createdAtMs <= args.sentAtOrBeforeMs));
|
|
2650
|
-
const inboundMessageIds = pendingMessages.map((message) => message.inboundMessageId);
|
|
2651
|
-
if (current.execution.runId === void 0) await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
2652
|
-
...current.execution,
|
|
2653
|
-
runId
|
|
2654
|
-
}, nowMs));
|
|
2655
|
-
await fenceConversationMutation(state, lock, args.conversationId);
|
|
2656
|
-
await state.set(conversationStopKey(args.conversationId), {
|
|
2657
|
-
inboundMessageIds,
|
|
2658
|
-
runId
|
|
2659
|
-
}, JUNIOR_THREAD_STATE_TTL_MS);
|
|
2660
|
-
return {
|
|
2661
|
-
runId,
|
|
2662
|
-
status: "requested",
|
|
2663
|
-
pendingMessages
|
|
2664
|
-
};
|
|
2665
|
-
});
|
|
2666
|
-
}
|
|
2667
|
-
/** Clear one observed stop request and discard older human-facing mailbox work. */
|
|
2668
|
-
async function completeConversationStop$1(args) {
|
|
2669
|
-
const nowMs = args.nowMs ?? now$1();
|
|
2670
|
-
return await withConversationMutation(args, async (state, lock) => {
|
|
2671
|
-
const current = await readConversation(state, args.conversationId);
|
|
2672
|
-
if (!current || current.execution.lease?.token !== args.leaseToken) return {
|
|
2673
|
-
status: "lost_lease",
|
|
2674
|
-
removedInboundMessageIds: []
|
|
2675
|
-
};
|
|
2676
|
-
const stop = await readConversationStop(state, args.conversationId);
|
|
2677
|
-
if (!stop || stop.runId !== args.runId) return {
|
|
2678
|
-
status: "none",
|
|
2679
|
-
removedInboundMessageIds: []
|
|
2680
|
-
};
|
|
2681
|
-
const stoppedInboundMessageIds = new Set(stop.inboundMessageIds);
|
|
2682
|
-
const removedInboundMessageIds = [];
|
|
2683
|
-
const pendingMessages = current.execution.pendingMessages.filter((message) => {
|
|
2684
|
-
const shouldStop = stoppedInboundMessageIds.has(message.inboundMessageId);
|
|
2685
|
-
if (shouldStop) removedInboundMessageIds.push(message.inboundMessageId);
|
|
2686
|
-
return !shouldStop;
|
|
2687
|
-
});
|
|
2688
|
-
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
2689
|
-
...current.execution,
|
|
2690
|
-
lastEnqueuedAtMs: pendingMessages.length === 0 ? void 0 : current.execution.lastEnqueuedAtMs,
|
|
2691
|
-
pendingMessages
|
|
2692
|
-
}, nowMs));
|
|
2693
|
-
await fenceConversationMutation(state, lock, args.conversationId);
|
|
2694
|
-
await state.delete(conversationStopKey(args.conversationId));
|
|
2695
|
-
return {
|
|
2696
|
-
status: "cleared",
|
|
2697
|
-
removedInboundMessageIds
|
|
2698
|
-
};
|
|
2699
|
-
});
|
|
2700
|
-
}
|
|
2701
|
-
/** Cancel human-facing pending mailbox rows without requiring a worker lease. */
|
|
2702
|
-
async function cancelHumanFacingPendingMessages$1(args) {
|
|
2703
|
-
const requestedIds = args.inboundMessageIds === void 0 ? void 0 : new Set(args.inboundMessageIds);
|
|
2704
|
-
const cancelledMessages = await removePendingMessages(args, (message) => isPersonInput(message.source) && (requestedIds === void 0 || requestedIds.has(message.inboundMessageId)) && (args.receivedBeforeMs === void 0 || message.receivedAtMs <= args.receivedBeforeMs));
|
|
2705
|
-
return {
|
|
2706
|
-
cancelledInboundMessageIds: cancelledMessages.map((message) => message.inboundMessageId),
|
|
2707
|
-
cancelledMessages
|
|
2708
|
-
};
|
|
2709
|
-
}
|
|
2710
|
-
/**
|
|
2711
|
-
* Drop pending mailbox rows by id without a worker lease, such as unread
|
|
2712
|
-
* input that a stop skips. Returns the ids that were dropped.
|
|
2713
|
-
*/
|
|
2714
|
-
async function dropPendingMessages$1(args) {
|
|
2715
|
-
const ids = new Set(args.inboundMessageIds);
|
|
2716
|
-
return (await removePendingMessages(args, (message) => ids.has(message.inboundMessageId))).map((message) => message.inboundMessageId);
|
|
2717
|
-
}
|
|
2718
|
-
/**
|
|
2719
|
-
* Record the input of the attempt that the lease holder starts. Returns
|
|
2720
|
-
* `reselect` when the lease is lost or a stop already took some of the input.
|
|
2721
|
-
* Returns `held` with the input that a stop held from an attempt that ended
|
|
2722
|
-
* without saving it, so the worker saves it as held before it selects again.
|
|
2723
|
-
*/
|
|
2724
|
-
async function claimConversationAttempt$1(args) {
|
|
2725
|
-
const nowMs = args.nowMs ?? now$1();
|
|
2726
|
-
return await withConversationMutation(args, async (state, lock) => {
|
|
2727
|
-
const current = await readConversation(state, args.conversationId);
|
|
2728
|
-
const lease = current?.execution.lease;
|
|
2729
|
-
if (!current || !lease || lease.token !== args.leaseToken) return { status: "reselect" };
|
|
2730
|
-
const heldIds = new Set(current.execution.heldInboundMessageIds);
|
|
2731
|
-
if (heldIds.size > 0) {
|
|
2732
|
-
const messages = current.execution.pendingMessages.filter((message) => heldIds.has(message.inboundMessageId));
|
|
2733
|
-
const pendingMessages = current.execution.pendingMessages.filter((message) => !heldIds.has(message.inboundMessageId));
|
|
2734
|
-
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
2735
|
-
...current.execution,
|
|
2736
|
-
heldInboundMessageIds: void 0,
|
|
2737
|
-
pendingMessages
|
|
2738
|
-
}, nowMs));
|
|
2739
|
-
return {
|
|
2740
|
-
status: "held",
|
|
2741
|
-
messages,
|
|
2742
|
-
pendingCount: pendingMessages.length
|
|
2743
|
-
};
|
|
2744
|
-
}
|
|
2745
|
-
const pendingIds = new Set(current.execution.pendingMessages.map((message) => message.inboundMessageId));
|
|
2746
|
-
if (!args.inboundMessageIds.every((id) => pendingIds.has(id))) return { status: "reselect" };
|
|
2747
|
-
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
2748
|
-
...current.execution,
|
|
2749
|
-
lease: {
|
|
2750
|
-
...lease,
|
|
2751
|
-
attemptInboundMessageIds: [...args.inboundMessageIds]
|
|
2752
|
-
}
|
|
2753
|
-
}, nowMs));
|
|
2754
|
-
return { status: "claimed" };
|
|
2755
|
-
});
|
|
2756
|
-
}
|
|
2757
|
-
/**
|
|
2758
|
-
* Remove the pending Event input of a Conversation and return it, so a stop
|
|
2759
|
-
* can hold input that reached the mailbox before it. The input of a running
|
|
2760
|
-
* attempt stays and is marked held: that Turn saves it, or the next claim
|
|
2761
|
-
* holds it.
|
|
2762
|
-
*/
|
|
2763
|
-
async function takePendingEventMessages$1(args) {
|
|
2764
|
-
const nowMs = args.nowMs ?? now$1();
|
|
2765
|
-
return await withConversationMutation(args, async (state, lock) => {
|
|
2766
|
-
const current = await readConversation(state, args.conversationId);
|
|
2767
|
-
if (!current) return [];
|
|
2768
|
-
const lease = current.execution.lease;
|
|
2769
|
-
const runningIds = new Set(isLeaseActive(lease, nowMs) ? lease?.attemptInboundMessageIds : []);
|
|
2770
|
-
const events = current.execution.pendingMessages.filter((message) => message.source === "event");
|
|
2771
|
-
const removed = events.filter((message) => !runningIds.has(message.inboundMessageId));
|
|
2772
|
-
const held = events.filter((message) => runningIds.has(message.inboundMessageId)).map((message) => message.inboundMessageId);
|
|
2773
|
-
if (removed.length === 0 && held.length === 0) return [];
|
|
2774
|
-
const pendingMessages = current.execution.pendingMessages.filter((message) => !removed.includes(message));
|
|
2775
|
-
const becomesIdle = current.execution.status === "pending" && pendingMessages.length === 0;
|
|
2776
|
-
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
2777
|
-
...current.execution,
|
|
2778
|
-
heldInboundMessageIds: uniqueStrings([...current.execution.heldInboundMessageIds ?? [], ...held]),
|
|
2779
|
-
lastEnqueuedAtMs: pendingMessages.length === 0 ? void 0 : current.execution.lastEnqueuedAtMs,
|
|
2780
|
-
pendingMessages,
|
|
2781
|
-
retryCount: becomesIdle ? 0 : current.execution.retryCount,
|
|
2782
|
-
runId: becomesIdle ? void 0 : current.execution.runId,
|
|
2783
|
-
status: becomesIdle ? "idle" : current.execution.status
|
|
2784
|
-
}, nowMs));
|
|
2785
|
-
return removed;
|
|
2786
|
-
});
|
|
2787
|
-
}
|
|
2788
|
-
async function removePendingMessages(args, shouldRemove) {
|
|
2789
|
-
const nowMs = args.nowMs ?? now$1();
|
|
2790
|
-
return await withConversationMutation(args, async (state, lock) => {
|
|
2791
|
-
const current = await readConversation(state, args.conversationId);
|
|
2792
|
-
if (!current) return [];
|
|
2793
|
-
const removed = current.execution.pendingMessages.filter(shouldRemove);
|
|
2794
|
-
if (removed.length === 0) return removed;
|
|
2795
|
-
const pendingMessages = current.execution.pendingMessages.filter((message) => !removed.includes(message));
|
|
2796
|
-
const becomesIdle = current.execution.status === "pending" && pendingMessages.length === 0;
|
|
2797
|
-
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
2798
|
-
...current.execution,
|
|
2799
|
-
lastEnqueuedAtMs: pendingMessages.length === 0 ? void 0 : current.execution.lastEnqueuedAtMs,
|
|
2800
|
-
pendingMessages,
|
|
2801
|
-
retryCount: becomesIdle ? 0 : current.execution.retryCount,
|
|
2802
|
-
runId: becomesIdle ? void 0 : current.execution.runId,
|
|
2803
|
-
status: becomesIdle ? "idle" : current.execution.status
|
|
2804
|
-
}, nowMs));
|
|
2805
|
-
return removed;
|
|
2806
|
-
});
|
|
2807
|
-
}
|
|
2808
|
-
/**
|
|
2809
|
-
* Mark one author's queued web messages as interrupts without a worker lease.
|
|
2810
|
-
* `authorIds` lists every id that names the author.
|
|
2811
|
-
*
|
|
2812
|
-
* The active Turn drains them at its next model boundary when it belongs to the
|
|
2813
|
-
* same author. Otherwise they start the next Turn ahead of deferred input.
|
|
2814
|
-
*/
|
|
2815
|
-
async function steerWebPendingMessages$1(args) {
|
|
2816
|
-
const nowMs = args.nowMs ?? now$1();
|
|
2817
|
-
const requestedIds = new Set(args.inboundMessageIds);
|
|
2818
|
-
return await withConversationMutation(args, async (state, lock) => {
|
|
2819
|
-
const current = await readConversation(state, args.conversationId);
|
|
2820
|
-
if (!current) return { steeredInboundMessageIds: [] };
|
|
2821
|
-
const steeredInboundMessageIds = [];
|
|
2822
|
-
const pendingMessages = current.execution.pendingMessages.map((message) => {
|
|
2823
|
-
if (message.source !== "web" || message.delivery !== "defer" || message.input.authorId === void 0 || !args.authorIds.includes(message.input.authorId) || !requestedIds.has(message.inboundMessageId)) return message;
|
|
2824
|
-
steeredInboundMessageIds.push(message.inboundMessageId);
|
|
2825
|
-
return {
|
|
2826
|
-
...message,
|
|
2827
|
-
delivery: "interrupt"
|
|
2828
|
-
};
|
|
2829
|
-
});
|
|
2830
|
-
if (steeredInboundMessageIds.length === 0) return { steeredInboundMessageIds };
|
|
2831
|
-
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
2832
|
-
...current.execution,
|
|
2833
|
-
pendingMessages
|
|
2834
|
-
}, nowMs));
|
|
2835
|
-
return { steeredInboundMessageIds };
|
|
2836
|
-
});
|
|
2837
|
-
}
|
|
2838
|
-
/** Mark the leased conversation as needing another queue-delivered slice. */
|
|
2839
|
-
async function requestAnotherSlice$1(args) {
|
|
2840
|
-
const nowMs = args.nowMs ?? now$1();
|
|
2841
|
-
return await withConversationMutation(args, async (state, lock) => {
|
|
2842
|
-
const current = await readConversation(state, args.conversationId);
|
|
2843
|
-
if (!current || current.execution.lease?.token !== args.leaseToken) return false;
|
|
2844
|
-
assertSameOptionalConversationDestination({
|
|
2845
|
-
conversationId: args.conversationId,
|
|
2846
|
-
current: current.destination,
|
|
2847
|
-
next: args.destination
|
|
2848
|
-
});
|
|
2849
|
-
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
2850
|
-
...current.execution,
|
|
2851
|
-
status: "paused"
|
|
2852
|
-
}, nowMs));
|
|
2853
|
-
return true;
|
|
2854
|
-
});
|
|
2855
|
-
}
|
|
2856
|
-
/** Begin a requested turn resume under the worker's existing lease. */
|
|
2857
|
-
async function beginConversationResume$1(args) {
|
|
2858
|
-
const nowMs = args.nowMs ?? now$1();
|
|
2859
|
-
return await withConversationMutation(args, async (state, lock) => {
|
|
2860
|
-
const current = await readConversation(state, args.conversationId);
|
|
2861
|
-
if (!current || current.execution.lease?.token !== args.leaseToken || current.execution.status !== "paused") return false;
|
|
2862
|
-
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
2863
|
-
...current.execution,
|
|
2864
|
-
status: "running"
|
|
2865
|
-
}, nowMs));
|
|
2866
|
-
return true;
|
|
2867
|
-
});
|
|
2868
|
-
}
|
|
2869
|
-
/** Release the durable execution lease without changing completion state. */
|
|
2870
|
-
async function releaseConversationWork$1(args) {
|
|
2871
|
-
const nowMs = args.nowMs ?? now$1();
|
|
2872
|
-
return await withConversationMutation(args, async (state, lock) => {
|
|
2873
|
-
const current = await readConversation(state, args.conversationId);
|
|
2874
|
-
if (!current || current.execution.lease?.token !== args.leaseToken) return false;
|
|
2875
|
-
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
2876
|
-
...current.execution,
|
|
2877
|
-
lease: void 0,
|
|
2878
|
-
status: current.execution.status === "running" ? "pending" : current.execution.status
|
|
2879
|
-
}, nowMs));
|
|
2880
|
-
return true;
|
|
2881
|
-
});
|
|
2882
|
-
}
|
|
2883
|
-
/** Count one failed execution attempt and stop the conversation when retries are exhausted. */
|
|
2884
|
-
async function recordConversationRetry$1(args) {
|
|
2885
|
-
const nowMs = args.nowMs ?? now$1();
|
|
2886
|
-
return await withConversationMutation(args, async (state, lock) => {
|
|
2887
|
-
const current = await readConversation(state, args.conversationId);
|
|
2888
|
-
if (!current || current.execution.lease?.token !== args.leaseToken) return "lost_lease";
|
|
2889
|
-
const count = (current.execution.retryCount ?? 0) + 1;
|
|
2890
|
-
const stopped = count >= 5;
|
|
2891
|
-
if (stopped) await args.beforeWorkStops?.(args.conversationId, current.execution.inboundMessageIds);
|
|
2892
|
-
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
2893
|
-
...current.execution,
|
|
2894
|
-
lastEnqueuedAtMs: void 0,
|
|
2895
|
-
lease: stopped ? void 0 : current.execution.lease,
|
|
2896
|
-
retryCount: count,
|
|
2897
|
-
pendingMessages: stopped ? [] : current.execution.pendingMessages,
|
|
2898
|
-
runId: stopped ? void 0 : current.execution.runId,
|
|
2899
|
-
status: stopped ? "failed" : "paused"
|
|
2900
|
-
}, nowMs));
|
|
2901
|
-
return stopped ? "stopped" : "recorded";
|
|
2902
|
-
});
|
|
2903
|
-
}
|
|
2904
|
-
/** Finish a leased conversation and report whether runnable work remains. */
|
|
2905
|
-
async function completeConversationWork$1(args) {
|
|
2906
|
-
const nowMs = args.nowMs ?? now$1();
|
|
2907
|
-
return await withConversationMutation(args, async (state, lock) => {
|
|
2908
|
-
const current = await readConversation(state, args.conversationId);
|
|
2909
|
-
if (!current || current.execution.lease?.token !== args.leaseToken) return "lost_lease";
|
|
2910
|
-
const hasPending = pendingMessages(current).length > 0;
|
|
2911
|
-
const stopped = args.resumeIfStopped === true && (await readConversationStop(state, args.conversationId))?.runId === current.execution.runId;
|
|
2912
|
-
const needsRun = current.execution.status === "paused" || stopped;
|
|
2913
|
-
const runnable = needsRun || hasPending;
|
|
2914
|
-
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
2915
|
-
...current.execution,
|
|
2916
|
-
lease: void 0,
|
|
2917
|
-
status: needsRun ? "paused" : hasPending ? "pending" : "idle",
|
|
2918
|
-
lastProgressAtMs: args.madeProgress === false ? current.execution.lastProgressAtMs : nowMs,
|
|
2919
|
-
retryCount: runnable || args.madeProgress === false ? current.execution.retryCount : 0,
|
|
2920
|
-
runId: runnable ? current.execution.runId : void 0
|
|
2921
|
-
}, nowMs));
|
|
2922
|
-
return runnable ? "pending" : "completed";
|
|
2923
|
-
});
|
|
2924
|
-
}
|
|
2925
|
-
/**
|
|
2926
|
-
* Record one failed execution attempt for pending messages, dead-lettering
|
|
2927
|
-
* the conversation when its retry budget or the legacy message delivery limit
|
|
2928
|
-
* is exhausted.
|
|
2929
|
-
*
|
|
2930
|
-
* Retries are counted only when the run made no durable progress: if any
|
|
2931
|
-
* attempted message left the mailbox, the remaining pending entries may be
|
|
2932
|
-
* deliberate deferrals and are left untouched. Consumed message ids stay in
|
|
2933
|
-
* `inboundMessageIds` so source retries remain duplicates.
|
|
2934
|
-
*/
|
|
2935
|
-
async function recordAttemptFailure$1(args) {
|
|
2936
|
-
const nowMs = args.nowMs ?? now$1();
|
|
2937
|
-
return await withConversationMutation(args, async (state, lock) => {
|
|
2938
|
-
const current = await readConversation(state, args.conversationId);
|
|
2939
|
-
if (!current || current.execution.lease?.token !== args.leaseToken) return {
|
|
2940
|
-
status: "lost_lease",
|
|
2941
|
-
pendingCount: 0,
|
|
2942
|
-
deadLetteredMessages: [],
|
|
2943
|
-
retryCount: 0
|
|
2944
|
-
};
|
|
2945
|
-
const pendingIds = new Set(current.execution.pendingMessages.map((message) => message.inboundMessageId));
|
|
2946
|
-
if (args.inboundMessageIds.length === 0 || args.inboundMessageIds.some((id) => !pendingIds.has(id))) return {
|
|
2947
|
-
status: "skipped",
|
|
2948
|
-
pendingCount: current.execution.pendingMessages.length,
|
|
2949
|
-
deadLetteredMessages: [],
|
|
2950
|
-
retryCount: current.execution.retryCount ?? 0
|
|
2951
|
-
};
|
|
2952
|
-
const retryCount = (current.execution.retryCount ?? 0) + 1;
|
|
2953
|
-
const retriesExhausted = retryCount >= 5;
|
|
2954
|
-
const attemptedIds = new Set(args.inboundMessageIds);
|
|
2955
|
-
const deadLetteredMessages = [];
|
|
2956
|
-
const pendingMessages = [];
|
|
2957
|
-
for (const message of current.execution.pendingMessages) {
|
|
2958
|
-
if (!attemptedIds.has(message.inboundMessageId)) {
|
|
2959
|
-
if (retriesExhausted) deadLetteredMessages.push(message);
|
|
2960
|
-
else pendingMessages.push(message);
|
|
2961
|
-
continue;
|
|
2962
|
-
}
|
|
2963
|
-
const attempted = {
|
|
2964
|
-
...message,
|
|
2965
|
-
attemptCount: (message.attemptCount ?? 0) + 1
|
|
2966
|
-
};
|
|
2967
|
-
if (retriesExhausted || attempted.attemptCount >= 5) {
|
|
2968
|
-
deadLetteredMessages.push(attempted);
|
|
2969
|
-
continue;
|
|
2970
|
-
}
|
|
2971
|
-
pendingMessages.push(attempted);
|
|
2972
|
-
}
|
|
2973
|
-
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
2974
|
-
...current.execution,
|
|
2975
|
-
retryCount,
|
|
2976
|
-
pendingMessages
|
|
2977
|
-
}, nowMs));
|
|
2978
|
-
return {
|
|
2979
|
-
status: "recorded",
|
|
2980
|
-
pendingCount: pendingMessages.length,
|
|
2981
|
-
deadLetteredMessages,
|
|
2982
|
-
retryCount
|
|
2983
|
-
};
|
|
2984
|
-
});
|
|
2985
|
-
}
|
|
2986
|
-
/** Record a terminal failure completion for a leased conversation. */
|
|
2987
|
-
async function deadLetterAttempt$1(args) {
|
|
2988
|
-
const nowMs = args.nowMs ?? now$1();
|
|
2989
|
-
return await withConversationMutation(args, async (state, lock) => {
|
|
2990
|
-
const current = await readConversation(state, args.conversationId);
|
|
2991
|
-
if (!current || current.execution.lease?.token !== args.leaseToken) return "lost_lease";
|
|
2992
|
-
const runnable = pendingMessages(current).length > 0;
|
|
2993
|
-
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
2994
|
-
...current.execution,
|
|
2995
|
-
lease: void 0,
|
|
2996
|
-
status: runnable ? "pending" : "failed",
|
|
2997
|
-
runId: runnable ? current.execution.runId : void 0
|
|
2998
|
-
}, nowMs));
|
|
2999
|
-
return runnable ? "pending" : "failed";
|
|
3000
|
-
});
|
|
3001
|
-
}
|
|
3002
|
-
/** Recover an expired lease, consuming the retry budget under the mutation lock. */
|
|
3003
|
-
async function clearExpiredConversationLease$1(args) {
|
|
3004
|
-
const nowMs = args.nowMs ?? now$1();
|
|
3005
|
-
return await withConversationMutation(args, async (state, lock) => {
|
|
3006
|
-
const current = await readConversation(state, args.conversationId);
|
|
3007
|
-
if (!current?.execution.lease || current.execution.lease.expiresAtMs > nowMs) return "not_expired";
|
|
3008
|
-
const retryCount = (current.execution.retryCount ?? 0) + 1;
|
|
3009
|
-
const stopped = retryCount >= 5;
|
|
3010
|
-
if (stopped) await args.beforeWorkStops?.(args.conversationId, current.execution.inboundMessageIds);
|
|
3011
|
-
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
3012
|
-
...current.execution,
|
|
3013
|
-
lastEnqueuedAtMs: void 0,
|
|
3014
|
-
lease: void 0,
|
|
3015
|
-
retryCount,
|
|
3016
|
-
pendingMessages: stopped ? [] : current.execution.pendingMessages,
|
|
3017
|
-
runId: stopped ? void 0 : current.execution.runId,
|
|
3018
|
-
status: stopped ? "failed" : "paused"
|
|
3019
|
-
}, nowMs));
|
|
3020
|
-
return stopped ? "stopped" : "requeued";
|
|
3021
|
-
});
|
|
3022
|
-
}
|
|
3023
|
-
/**
|
|
3024
|
-
* Remove a stale active index entry. This holds the mutation lock and reads
|
|
3025
|
-
* the record again, so it cannot remove the entry of work that a writer just
|
|
3026
|
-
* made runnable. A missing or invalid record can never run again.
|
|
3027
|
-
*/
|
|
3028
|
-
async function pruneActiveConversation(args) {
|
|
3029
|
-
await withConversationMutation(args, async (state) => {
|
|
3030
|
-
let current;
|
|
3031
|
-
try {
|
|
3032
|
-
current = await readConversation(state, args.conversationId);
|
|
3033
|
-
} catch (error) {
|
|
3034
|
-
if (!(error instanceof InvalidConversationRecordError)) throw error;
|
|
3035
|
-
}
|
|
3036
|
-
if (current && hasRunnableWork(current)) return;
|
|
3037
|
-
await removeIndexEntry({
|
|
3038
|
-
state,
|
|
3039
|
-
indexKey: CONVERSATION_ACTIVE_INDEX_KEY,
|
|
3040
|
-
conversationId: args.conversationId
|
|
3041
|
-
});
|
|
3042
|
-
});
|
|
3043
|
-
}
|
|
3044
|
-
/** List active conversation ids by oldest execution update first. */
|
|
3045
|
-
async function listActiveConversationIds$1(args = {}) {
|
|
3046
|
-
return (await (await getConversationIndexStore(await getConnectedState(args.state))).list({
|
|
3047
|
-
indexKey: CONVERSATION_ACTIVE_INDEX_KEY,
|
|
3048
|
-
limit: args.limit,
|
|
3049
|
-
order: "asc",
|
|
3050
|
-
scoreMax: args.staleBeforeMs
|
|
3051
|
-
})).map((entry) => entry.conversationId);
|
|
3052
|
-
}
|
|
3053
1575
|
// src/chat/task-execution/turn-cursor-keys.ts
|
|
3054
1576
|
/** Redis namespace for the current turn cursor format. */
|
|
3055
1577
|
const TURN_CURSOR_PREFIX = "junior:turn_cursor:v2";
|
|
@@ -5387,9 +3909,9 @@ function gitRootCandidates(cwd) {
|
|
|
5387
3909
|
let current = cwd;
|
|
5388
3910
|
for (;;) {
|
|
5389
3911
|
candidates.push(current);
|
|
5390
|
-
if (current ===
|
|
3912
|
+
if (current === "/vercel/sandbox") return candidates;
|
|
5391
3913
|
const parent = path.posix.dirname(current);
|
|
5392
|
-
if (parent === current || parent !==
|
|
3914
|
+
if (parent === current || parent !== "/vercel/sandbox" && !parent.startsWith(`/vercel/sandbox/`)) return candidates;
|
|
5393
3915
|
current = parent;
|
|
5394
3916
|
}
|
|
5395
3917
|
}
|
|
@@ -5447,7 +3969,7 @@ function parseRepositoryTree(stdout) {
|
|
|
5447
3969
|
}
|
|
5448
3970
|
/** Read what the selected directories need with one sandbox command. */
|
|
5449
3971
|
async function readRepositoryTree(args) {
|
|
5450
|
-
const relative = (target) => path.posix.relative(
|
|
3972
|
+
const relative = (target) => path.posix.relative("/vercel/sandbox", target) || ".";
|
|
5451
3973
|
const result = await args.runCommand({
|
|
5452
3974
|
cmd: "sh",
|
|
5453
3975
|
args: [
|
|
@@ -5600,7 +4122,7 @@ function mergeRepositoryInstructions(bundles) {
|
|
|
5600
4122
|
* worktree under repos/.
|
|
5601
4123
|
*/
|
|
5602
4124
|
async function readRepositoryInstructions(args) {
|
|
5603
|
-
const selected = [...new Set((args.directories ?? []).filter((directory) => directory ===
|
|
4125
|
+
const selected = [...new Set((args.directories ?? []).filter((directory) => directory === "/vercel/sandbox" || directory.startsWith(`/vercel/sandbox/`)))].sort(compareStrings);
|
|
5604
4126
|
if (args.directories && selected.length === 0) return {
|
|
5605
4127
|
directories: args.directories,
|
|
5606
4128
|
instructions: void 0
|
|
@@ -5769,71 +4291,371 @@ function setExperimentalFeatures(config) {
|
|
|
5769
4291
|
if (!isExperimentalFeature(rawName)) throw new Error(`experimental.${rawName} is not a known experimental feature. Known features: ${EXPERIMENTAL_FEATURES.join(", ")}`);
|
|
5770
4292
|
next[rawName] = enabled;
|
|
5771
4293
|
}
|
|
5772
|
-
configuredExperimental = next;
|
|
5773
|
-
return previous;
|
|
5774
|
-
}
|
|
5775
|
-
/** Return a copy of the app-level experimental opt-ins configured by createApp(). */
|
|
5776
|
-
function getExperimentalFeatures() {
|
|
5777
|
-
return { ...configuredExperimental };
|
|
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
|
+
/** Return whether one experimental feature is enabled via createApp({ experimental }). */
|
|
4302
|
+
function isExperimentalFeatureEnabled(feature) {
|
|
4303
|
+
return configuredExperimental[feature] === true;
|
|
4304
|
+
}
|
|
4305
|
+
// src/chat/sandbox/snapshot/store.ts
|
|
4306
|
+
function builderNames(rows) {
|
|
4307
|
+
return [...new Set(rows.map((row) => row.sandboxName).filter((name) => Boolean(name)))];
|
|
4308
|
+
}
|
|
4309
|
+
function sameWorkspaceRecipe(stored, expected) {
|
|
4310
|
+
if (stored.setupScript !== expected.setupScript || stored.repos.length !== expected.repos.length) return false;
|
|
4311
|
+
const expectedRepos = new Set(expected.repos.map((repo) => JSON.stringify([repo.provider, repo.repo])));
|
|
4312
|
+
return stored.repos.every((repo) => expectedRepos.has(JSON.stringify([repo.provider, repo.repo])));
|
|
4313
|
+
}
|
|
4314
|
+
function snapshotFromRow(row) {
|
|
4315
|
+
if (row.status !== "ready" || !row.snapshotId || !row.generatedAt || row.buildDurationMs == null) throw new Error(`Invalid ready Workspace snapshot row: ${row.id}`);
|
|
4316
|
+
return {
|
|
4317
|
+
id: row.snapshotId,
|
|
4318
|
+
generatedAt: row.generatedAt,
|
|
4319
|
+
buildDurationMs: row.buildDurationMs,
|
|
4320
|
+
sizeBytes: row.sizeBytes,
|
|
4321
|
+
profileHash: row.profileHash
|
|
4322
|
+
};
|
|
4323
|
+
}
|
|
4324
|
+
function snapshotBuildFromRow(row) {
|
|
4325
|
+
if (row.status === "ready" || !row.buildStartedAt || !row.buildPhase) throw new Error(`Invalid Workspace snapshot build row: ${row.id}`);
|
|
4326
|
+
return {
|
|
4327
|
+
id: row.id,
|
|
4328
|
+
status: row.status,
|
|
4329
|
+
phase: row.buildPhase,
|
|
4330
|
+
profileHash: row.profileHash,
|
|
4331
|
+
startedAt: row.buildStartedAt,
|
|
4332
|
+
sandboxName: row.buildSandboxName,
|
|
4333
|
+
commandId: row.buildCommandId,
|
|
4334
|
+
error: row.buildError
|
|
4335
|
+
};
|
|
4336
|
+
}
|
|
4337
|
+
/** Load bounded ready and build views for one Workspace profile hash. */
|
|
4338
|
+
async function loadSnapshotsForProfile(db, workspaceId, profileHash) {
|
|
4339
|
+
const profile = and(eq(juniorSnapshots.workspaceId, workspaceId), eq(juniorSnapshots.profileHash, profileHash));
|
|
4340
|
+
const order = [
|
|
4341
|
+
desc(juniorSnapshots.updatedAt),
|
|
4342
|
+
desc(juniorSnapshots.createdAt),
|
|
4343
|
+
desc(juniorSnapshots.id)
|
|
4344
|
+
];
|
|
4345
|
+
const [readyRows, buildRows] = await Promise.all([db.select().from(juniorSnapshots).where(and(profile, eq(juniorSnapshots.status, "ready"))).orderBy(...order).limit(1), db.select().from(juniorSnapshots).where(and(profile, ne(juniorSnapshots.status, "ready"))).orderBy(asc(juniorSnapshots.status), ...order).limit(1)]);
|
|
4346
|
+
return {
|
|
4347
|
+
ready: readyRows[0] ? snapshotFromRow(readyRows[0]) : null,
|
|
4348
|
+
build: buildRows[0] ? snapshotBuildFromRow(buildRows[0]) : null
|
|
4349
|
+
};
|
|
4350
|
+
}
|
|
4351
|
+
/** Drop every snapshot row before its Workspace is deleted. */
|
|
4352
|
+
async function clearWorkspaceSnapshots(db, workspaceId) {
|
|
4353
|
+
await db.select({ id: juniorWorkspaces.id }).from(juniorWorkspaces).where(eq(juniorWorkspaces.id, workspaceId)).for("update");
|
|
4354
|
+
return builderNames(await db.delete(juniorSnapshots).where(eq(juniorSnapshots.workspaceId, workspaceId)).returning({ sandboxName: juniorSnapshots.buildSandboxName }));
|
|
4355
|
+
}
|
|
4356
|
+
/** Drop one ready snapshot and return the name of its provider owner. */
|
|
4357
|
+
async function invalidateReadySnapshot(params) {
|
|
4358
|
+
const executor = getSqlExecutor();
|
|
4359
|
+
return await executor.transaction(async () => {
|
|
4360
|
+
return (await executor.db().delete(juniorSnapshots).where(and(eq(juniorSnapshots.workspaceId, params.workspaceId), eq(juniorSnapshots.profileHash, params.profileHash), eq(juniorSnapshots.status, "ready"), eq(juniorSnapshots.snapshotId, params.snapshotId))).returning({ sandboxName: juniorSnapshots.buildSandboxName }))[0]?.sandboxName ?? null;
|
|
4361
|
+
});
|
|
4362
|
+
}
|
|
4363
|
+
/** Complete one owned build and report provider owners that it replaced. */
|
|
4364
|
+
async function setWorkspaceSnapshot(workspaceId, snapshot, options) {
|
|
4365
|
+
const executor = getSqlExecutor();
|
|
4366
|
+
return await executor.transaction(async () => {
|
|
4367
|
+
const db = executor.db();
|
|
4368
|
+
const now = /* @__PURE__ */ new Date();
|
|
4369
|
+
if ((await db.update(juniorSnapshots).set({
|
|
4370
|
+
status: "ready",
|
|
4371
|
+
snapshotId: snapshot.id,
|
|
4372
|
+
buildDurationMs: snapshot.buildDurationMs,
|
|
4373
|
+
sizeBytes: snapshot.sizeBytes,
|
|
4374
|
+
generatedAt: snapshot.generatedAt,
|
|
4375
|
+
buildStartedAt: null,
|
|
4376
|
+
buildPhase: null,
|
|
4377
|
+
buildCommandId: null,
|
|
4378
|
+
buildError: null,
|
|
4379
|
+
updatedAt: now
|
|
4380
|
+
}).where(and(eq(juniorSnapshots.id, options.buildId), eq(juniorSnapshots.workspaceId, workspaceId), eq(juniorSnapshots.profileHash, snapshot.profileHash), eq(juniorSnapshots.status, "building"))).returning({ id: juniorSnapshots.id })).length === 0) return {
|
|
4381
|
+
written: false,
|
|
4382
|
+
replacedBuilderNames: []
|
|
4383
|
+
};
|
|
4384
|
+
return {
|
|
4385
|
+
written: true,
|
|
4386
|
+
replacedBuilderNames: builderNames(await db.delete(juniorSnapshots).where(and(eq(juniorSnapshots.workspaceId, workspaceId), eq(juniorSnapshots.profileHash, snapshot.profileHash), ne(juniorSnapshots.id, options.buildId), or(eq(juniorSnapshots.status, "failed"), eq(juniorSnapshots.status, "ready")))).returning({ sandboxName: juniorSnapshots.buildSandboxName }))
|
|
4387
|
+
};
|
|
4388
|
+
});
|
|
4389
|
+
}
|
|
4390
|
+
/** Update an owned build row. Initial creation locks and verifies its Workspace. */
|
|
4391
|
+
async function setWorkspaceSnapshotBuild(workspaceId, build, options = {}) {
|
|
4392
|
+
const executor = getSqlExecutor();
|
|
4393
|
+
return await executor.transaction(async () => {
|
|
4394
|
+
const db = executor.db();
|
|
4395
|
+
const now = /* @__PURE__ */ new Date();
|
|
4396
|
+
if ((await db.update(juniorSnapshots).set({
|
|
4397
|
+
status: build.status,
|
|
4398
|
+
buildStartedAt: build.startedAt,
|
|
4399
|
+
buildPhase: build.phase,
|
|
4400
|
+
buildSandboxName: build.sandboxName,
|
|
4401
|
+
buildCommandId: build.commandId,
|
|
4402
|
+
buildError: build.error,
|
|
4403
|
+
updatedAt: now
|
|
4404
|
+
}).where(and(eq(juniorSnapshots.id, build.id), eq(juniorSnapshots.workspaceId, workspaceId), eq(juniorSnapshots.profileHash, build.profileHash), eq(juniorSnapshots.status, "building"))).returning({ id: juniorSnapshots.id })).length > 0) return true;
|
|
4405
|
+
if (!options.insertIfMissing) return false;
|
|
4406
|
+
const workspace = (await db.select({ setupScript: juniorWorkspaces.setupScript }).from(juniorWorkspaces).where(eq(juniorWorkspaces.id, workspaceId)).for("update"))[0];
|
|
4407
|
+
if (!workspace) return false;
|
|
4408
|
+
if (options.expectedRecipe) {
|
|
4409
|
+
const repos = await db.select({
|
|
4410
|
+
provider: juniorWorkspaceRepos.provider,
|
|
4411
|
+
repo: juniorWorkspaceRepos.repo
|
|
4412
|
+
}).from(juniorWorkspaceRepos).where(eq(juniorWorkspaceRepos.workspaceId, workspaceId));
|
|
4413
|
+
if (!sameWorkspaceRecipe({
|
|
4414
|
+
...workspace,
|
|
4415
|
+
repos
|
|
4416
|
+
}, options.expectedRecipe)) return false;
|
|
4417
|
+
}
|
|
4418
|
+
return (await db.insert(juniorSnapshots).values({
|
|
4419
|
+
id: build.id,
|
|
4420
|
+
workspaceId,
|
|
4421
|
+
profileHash: build.profileHash,
|
|
4422
|
+
status: build.status,
|
|
4423
|
+
snapshotId: null,
|
|
4424
|
+
buildDurationMs: null,
|
|
4425
|
+
sizeBytes: null,
|
|
4426
|
+
generatedAt: null,
|
|
4427
|
+
buildStartedAt: build.startedAt,
|
|
4428
|
+
buildPhase: build.phase,
|
|
4429
|
+
buildSandboxName: build.sandboxName,
|
|
4430
|
+
buildCommandId: build.commandId,
|
|
4431
|
+
buildError: build.error,
|
|
4432
|
+
createdAt: now,
|
|
4433
|
+
updatedAt: now
|
|
4434
|
+
}).onConflictDoNothing().returning({ id: juniorSnapshots.id })).length > 0;
|
|
4435
|
+
});
|
|
4436
|
+
}
|
|
4437
|
+
// src/chat/workspaces/checkout-path.ts
|
|
4438
|
+
/** Derive the fixed sandbox checkout path for one repository, or undefined when invalid. */
|
|
4439
|
+
function tryWorkspaceRepoCheckoutPath(repo) {
|
|
4440
|
+
const name = repo.split("/").filter(Boolean).at(-1);
|
|
4441
|
+
if (!name || name === "." || name === ".." || !/^[A-Za-z0-9._-]+$/.test(name)) return;
|
|
4442
|
+
return `repos/${name}`;
|
|
4443
|
+
}
|
|
4444
|
+
/** Derive the fixed sandbox checkout path for one repository. */
|
|
4445
|
+
function workspaceRepoCheckoutPath(repo) {
|
|
4446
|
+
const path = tryWorkspaceRepoCheckoutPath(repo);
|
|
4447
|
+
if (!path) throw new Error(`Invalid repository name for checkout path: ${repo}`);
|
|
4448
|
+
return path;
|
|
4449
|
+
}
|
|
4450
|
+
// src/chat/workspaces/validation.ts
|
|
4451
|
+
const WORKSPACE_NAME_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/;
|
|
4452
|
+
const PROVIDER_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/;
|
|
4453
|
+
const REPO_PATTERN = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/;
|
|
4454
|
+
const MAX_SETUP_SCRIPT_BYTES = 65536;
|
|
4455
|
+
const MAX_REPOS = 32;
|
|
4456
|
+
/** Validation failure for one Workspace recipe write. */
|
|
4457
|
+
var WorkspaceValidationError = class extends Error {
|
|
4458
|
+
constructor(message) {
|
|
4459
|
+
super(message);
|
|
4460
|
+
this.name = "WorkspaceValidationError";
|
|
4461
|
+
}
|
|
4462
|
+
};
|
|
4463
|
+
/** Normalize and validate one Workspace recipe write payload. */
|
|
4464
|
+
function normalizeWorkspaceRecipe(input) {
|
|
4465
|
+
const name = input.name.trim().toLowerCase();
|
|
4466
|
+
if (!WORKSPACE_NAME_PATTERN.test(name)) throw new WorkspaceValidationError("Workspace name must start with a letter and use only lowercase letters, digits, underscores, or hyphens.");
|
|
4467
|
+
const setupScript = input.setupScript ?? "";
|
|
4468
|
+
if (typeof setupScript !== "string") throw new WorkspaceValidationError("Setup script must be a string.");
|
|
4469
|
+
if (Buffer.byteLength(setupScript, "utf8") > MAX_SETUP_SCRIPT_BYTES) throw new WorkspaceValidationError(`Setup script must be at most ${MAX_SETUP_SCRIPT_BYTES} bytes.`);
|
|
4470
|
+
const vcpus = input.vcpus ?? null;
|
|
4471
|
+
if (vcpus !== null && (!Number.isSafeInteger(vcpus) || vcpus <= 0)) throw new WorkspaceValidationError("vCPUs must be a positive integer.");
|
|
4472
|
+
if (!Array.isArray(input.repos)) throw new WorkspaceValidationError("Repositories must be an array.");
|
|
4473
|
+
if (input.repos.length > MAX_REPOS) throw new WorkspaceValidationError(`A Workspace can include at most ${MAX_REPOS} repositories.`);
|
|
4474
|
+
const repos = input.repos.map((entry, index) => {
|
|
4475
|
+
const provider = entry.provider.trim().toLowerCase();
|
|
4476
|
+
if (!PROVIDER_PATTERN.test(provider)) throw new WorkspaceValidationError(`Repository ${index + 1} provider is invalid.`);
|
|
4477
|
+
const repo = entry.repo.trim();
|
|
4478
|
+
if (!REPO_PATTERN.test(repo)) throw new WorkspaceValidationError(`Repository ${index + 1} must use owner/name format.`);
|
|
4479
|
+
if (!tryWorkspaceRepoCheckoutPath(repo)) throw new WorkspaceValidationError(`Repository ${index + 1} name cannot be used as a checkout path.`);
|
|
4480
|
+
return {
|
|
4481
|
+
provider,
|
|
4482
|
+
repo
|
|
4483
|
+
};
|
|
4484
|
+
});
|
|
4485
|
+
const identities = /* @__PURE__ */ new Set();
|
|
4486
|
+
for (const repo of repos) {
|
|
4487
|
+
const identity = `${repo.provider}:${repo.repo.toLowerCase()}`;
|
|
4488
|
+
if (identities.has(identity)) throw new WorkspaceValidationError(`Duplicate repository in Workspace: ${repo.provider}:${repo.repo}`);
|
|
4489
|
+
identities.add(identity);
|
|
4490
|
+
}
|
|
4491
|
+
const checkoutPaths = /* @__PURE__ */ new Set();
|
|
4492
|
+
for (const repo of repos) {
|
|
4493
|
+
const path = tryWorkspaceRepoCheckoutPath(repo.repo);
|
|
4494
|
+
const key = path.toLowerCase();
|
|
4495
|
+
if (checkoutPaths.has(key)) throw new WorkspaceValidationError(`Workspace checkout path collision: ${path}`);
|
|
4496
|
+
checkoutPaths.add(key);
|
|
4497
|
+
}
|
|
4498
|
+
return {
|
|
4499
|
+
name,
|
|
4500
|
+
setupScript,
|
|
4501
|
+
vcpus,
|
|
4502
|
+
repos
|
|
4503
|
+
};
|
|
4504
|
+
}
|
|
4505
|
+
// src/chat/workspaces/store.ts
|
|
4506
|
+
const UNIQUE_VIOLATION = "23505";
|
|
4507
|
+
function workspaceFromRows(row, repos, snapshot) {
|
|
4508
|
+
return {
|
|
4509
|
+
id: row.id,
|
|
4510
|
+
name: row.name,
|
|
4511
|
+
setupScript: row.setupScript,
|
|
4512
|
+
vcpus: row.vcpus,
|
|
4513
|
+
repos: repos.map((repo) => ({
|
|
4514
|
+
provider: repo.provider,
|
|
4515
|
+
repo: repo.repo
|
|
4516
|
+
})),
|
|
4517
|
+
snapshot
|
|
4518
|
+
};
|
|
4519
|
+
}
|
|
4520
|
+
async function workspaceWithSnapshot(db, row, repos) {
|
|
4521
|
+
const workspace = workspaceFromRows(row, repos, null);
|
|
4522
|
+
const profileHash = hash(SANDBOX_RUNTIME, workspace);
|
|
4523
|
+
if (!profileHash) return workspace;
|
|
4524
|
+
const snapshots = await loadSnapshotsForProfile(db, workspace.id, profileHash);
|
|
4525
|
+
return {
|
|
4526
|
+
...workspace,
|
|
4527
|
+
snapshot: snapshots.ready
|
|
4528
|
+
};
|
|
4529
|
+
}
|
|
4530
|
+
async function loadWorkspaceRepos(db, workspaceId) {
|
|
4531
|
+
return await db.select().from(juniorWorkspaceRepos).where(eq(juniorWorkspaceRepos.workspaceId, workspaceId)).orderBy(asc(juniorWorkspaceRepos.provider), asc(juniorWorkspaceRepos.repo));
|
|
4532
|
+
}
|
|
4533
|
+
async function replaceWorkspaceRepos(db, workspaceId, repos) {
|
|
4534
|
+
await db.delete(juniorWorkspaceRepos).where(eq(juniorWorkspaceRepos.workspaceId, workspaceId));
|
|
4535
|
+
if (repos.length === 0) return;
|
|
4536
|
+
await db.insert(juniorWorkspaceRepos).values(repos.map((repo) => ({
|
|
4537
|
+
workspaceId,
|
|
4538
|
+
provider: repo.provider,
|
|
4539
|
+
repo: repo.repo
|
|
4540
|
+
})));
|
|
4541
|
+
}
|
|
4542
|
+
function sameWorkspaceRepos(current, next) {
|
|
4543
|
+
if (current.length !== next.length) return false;
|
|
4544
|
+
const identity = (repo) => `${repo.provider}:${repo.repo.toLowerCase()}`;
|
|
4545
|
+
const currentIds = current.map(identity).sort();
|
|
4546
|
+
const nextIds = next.map(identity).sort();
|
|
4547
|
+
return currentIds.every((value, index) => value === nextIds[index]);
|
|
4548
|
+
}
|
|
4549
|
+
async function cleanupSnapshotBuilders(workspaceId, names) {
|
|
4550
|
+
if (names.length === 0) return;
|
|
4551
|
+
try {
|
|
4552
|
+
await getSandboxProvider().deleteWorkspaceSnapshotBuilders(names);
|
|
4553
|
+
} catch (error) {
|
|
4554
|
+
logException(error, "sandbox.workspace_snapshot.builder.delete_failed", {
|
|
4555
|
+
"app.workspace.id": workspaceId,
|
|
4556
|
+
"app.sandbox.snapshot.builder_count": names.length
|
|
4557
|
+
});
|
|
4558
|
+
}
|
|
4559
|
+
}
|
|
4560
|
+
/** List Workspace recipes by stable name. */
|
|
4561
|
+
async function listWorkspaces(db) {
|
|
4562
|
+
const [workspaces, repos] = await Promise.all([db.select().from(juniorWorkspaces).orderBy(asc(juniorWorkspaces.name)), db.select().from(juniorWorkspaceRepos).orderBy(asc(juniorWorkspaceRepos.workspaceId), asc(juniorWorkspaceRepos.provider), asc(juniorWorkspaceRepos.repo))]);
|
|
4563
|
+
return workspaces.map((workspace) => workspaceFromRows(workspace, repos.filter((repo) => repo.workspaceId === workspace.id), null));
|
|
4564
|
+
}
|
|
4565
|
+
/** Find Workspace names that include one provider repository. */
|
|
4566
|
+
async function listWorkspaceNamesByRepository(db, input) {
|
|
4567
|
+
return (await listWorkspacesByRepository(db, input)).map((workspace) => workspace.name);
|
|
4568
|
+
}
|
|
4569
|
+
/** Find the Workspaces, by id and name, that include one provider repository. */
|
|
4570
|
+
async function listWorkspacesByRepository(db, input) {
|
|
4571
|
+
const provider = input.provider.trim().toLowerCase();
|
|
4572
|
+
const repo = input.repo.trim();
|
|
4573
|
+
return await db.select({
|
|
4574
|
+
id: juniorWorkspaces.id,
|
|
4575
|
+
name: juniorWorkspaces.name
|
|
4576
|
+
}).from(juniorWorkspaceRepos).innerJoin(juniorWorkspaces, eq(juniorWorkspaces.id, juniorWorkspaceRepos.workspaceId)).where(and(eq(juniorWorkspaceRepos.provider, provider), sql`lower(${juniorWorkspaceRepos.repo}) = lower(${repo})`)).orderBy(asc(juniorWorkspaces.name));
|
|
4577
|
+
}
|
|
4578
|
+
/** Resolve one Workspace recipe by name. */
|
|
4579
|
+
async function getWorkspaceByName(db, name) {
|
|
4580
|
+
const workspace = (await db.select().from(juniorWorkspaces).where(eq(juniorWorkspaces.name, name)).limit(1))[0];
|
|
4581
|
+
if (!workspace) return void 0;
|
|
4582
|
+
return await workspaceWithSnapshot(db, workspace, await loadWorkspaceRepos(db, workspace.id));
|
|
4583
|
+
}
|
|
4584
|
+
/** Resolve one Workspace recipe by id. */
|
|
4585
|
+
async function getWorkspace(db, id) {
|
|
4586
|
+
const workspace = (await db.select().from(juniorWorkspaces).where(eq(juniorWorkspaces.id, id)).limit(1))[0];
|
|
4587
|
+
if (!workspace) return void 0;
|
|
4588
|
+
return await workspaceWithSnapshot(db, workspace, await loadWorkspaceRepos(db, workspace.id));
|
|
4589
|
+
}
|
|
4590
|
+
/** Create one install-wide Workspace recipe. */
|
|
4591
|
+
async function createWorkspace(input) {
|
|
4592
|
+
const recipe = normalizeWorkspaceRecipe(input);
|
|
4593
|
+
const executor = getSqlExecutor();
|
|
4594
|
+
const now = /* @__PURE__ */ new Date();
|
|
4595
|
+
const id = randomUUID();
|
|
4596
|
+
try {
|
|
4597
|
+
await executor.transaction(async () => {
|
|
4598
|
+
const db = executor.db();
|
|
4599
|
+
await db.insert(juniorWorkspaces).values({
|
|
4600
|
+
id,
|
|
4601
|
+
name: recipe.name,
|
|
4602
|
+
setupScript: recipe.setupScript,
|
|
4603
|
+
vcpus: recipe.vcpus,
|
|
4604
|
+
createdAt: now,
|
|
4605
|
+
updatedAt: now
|
|
4606
|
+
});
|
|
4607
|
+
await replaceWorkspaceRepos(db, id, recipe.repos);
|
|
4608
|
+
});
|
|
4609
|
+
} catch (error) {
|
|
4610
|
+
if (isPostgresErrorCode(error, UNIQUE_VIOLATION)) throw new WorkspaceValidationError(`Workspace name already exists: ${recipe.name}`);
|
|
4611
|
+
throw error;
|
|
4612
|
+
}
|
|
4613
|
+
return await getWorkspace(executor.db(), id);
|
|
4614
|
+
}
|
|
4615
|
+
/** Replace one install-wide Workspace recipe. */
|
|
4616
|
+
async function updateWorkspace(id, input) {
|
|
4617
|
+
const recipe = normalizeWorkspaceRecipe(input);
|
|
4618
|
+
const executor = getSqlExecutor();
|
|
4619
|
+
const now = /* @__PURE__ */ new Date();
|
|
4620
|
+
try {
|
|
4621
|
+
const result = await executor.transaction(async () => {
|
|
4622
|
+
const db = executor.db();
|
|
4623
|
+
const existing = (await db.select().from(juniorWorkspaces).where(eq(juniorWorkspaces.id, id)).limit(1))[0];
|
|
4624
|
+
if (!existing) return void 0;
|
|
4625
|
+
const existingRepos = await loadWorkspaceRepos(db, id);
|
|
4626
|
+
const snapshotChanged = existing.setupScript !== recipe.setupScript || !sameWorkspaceRepos(existingRepos, recipe.repos);
|
|
4627
|
+
const rows = await db.update(juniorWorkspaces).set({
|
|
4628
|
+
name: recipe.name,
|
|
4629
|
+
setupScript: recipe.setupScript,
|
|
4630
|
+
vcpus: recipe.vcpus,
|
|
4631
|
+
updatedAt: now
|
|
4632
|
+
}).where(eq(juniorWorkspaces.id, id)).returning();
|
|
4633
|
+
await replaceWorkspaceRepos(db, id, recipe.repos);
|
|
4634
|
+
return {
|
|
4635
|
+
builderNames: snapshotChanged ? await clearWorkspaceSnapshots(db, id) : [],
|
|
4636
|
+
workspace: rows[0]
|
|
4637
|
+
};
|
|
4638
|
+
});
|
|
4639
|
+
if (!result) return void 0;
|
|
4640
|
+
await cleanupSnapshotBuilders(id, result.builderNames);
|
|
4641
|
+
} catch (error) {
|
|
4642
|
+
if (isPostgresErrorCode(error, UNIQUE_VIOLATION)) throw new WorkspaceValidationError(`Workspace name already exists: ${recipe.name}`);
|
|
4643
|
+
throw error;
|
|
4644
|
+
}
|
|
4645
|
+
return await getWorkspace(executor.db(), id);
|
|
5778
4646
|
}
|
|
5779
|
-
/**
|
|
5780
|
-
function
|
|
5781
|
-
|
|
5782
|
-
|
|
5783
|
-
|
|
5784
|
-
|
|
5785
|
-
|
|
5786
|
-
|
|
5787
|
-
|
|
5788
|
-
};
|
|
5789
|
-
|
|
5790
|
-
|
|
5791
|
-
* Conversation to itself and to each descendant child Conversation at any
|
|
5792
|
-
* depth. Reports use it so that a total for a Conversation always includes the
|
|
5793
|
-
* work of all its child agents.
|
|
5794
|
-
*
|
|
5795
|
-
* A descendant must have the same root as the selected Conversation. Thus a
|
|
5796
|
-
* Conversation that has no valid root gets only its own work. A selected root
|
|
5797
|
-
* gets every Conversation that stores it as their root.
|
|
5798
|
-
*/
|
|
5799
|
-
function conversationSubtree(conversationIds) {
|
|
5800
|
-
const selectedIds = sql.join(conversationIds.map((conversationId) => sql`${conversationId}`), sql`, `);
|
|
5801
|
-
return sql`(
|
|
5802
|
-
with recursive tree_member as materialized (
|
|
5803
|
-
select member.conversation_id, member.parent_conversation_id, member.root_conversation_id
|
|
5804
|
-
from junior_conversations member
|
|
5805
|
-
where member.root_conversation_id in (
|
|
5806
|
-
select selected.root_conversation_id
|
|
5807
|
-
from junior_conversations selected
|
|
5808
|
-
where selected.conversation_id in (${selectedIds})
|
|
5809
|
-
and selected.root_conversation_id is distinct from selected.conversation_id
|
|
5810
|
-
)
|
|
5811
|
-
),
|
|
5812
|
-
walk(scope_conversation_id, conversation_id, root_conversation_id) as (
|
|
5813
|
-
select selected.conversation_id, selected.conversation_id, selected.root_conversation_id
|
|
5814
|
-
from junior_conversations selected
|
|
5815
|
-
where selected.conversation_id in (${selectedIds})
|
|
5816
|
-
and selected.root_conversation_id is distinct from selected.conversation_id
|
|
5817
|
-
union
|
|
5818
|
-
select walk.scope_conversation_id, child.conversation_id, child.root_conversation_id
|
|
5819
|
-
from tree_member child
|
|
5820
|
-
join walk
|
|
5821
|
-
on child.parent_conversation_id = walk.conversation_id
|
|
5822
|
-
and child.root_conversation_id = walk.root_conversation_id
|
|
5823
|
-
)
|
|
5824
|
-
select selected.conversation_id as scope_conversation_id, selected.conversation_id
|
|
5825
|
-
from junior_conversations selected
|
|
5826
|
-
where selected.conversation_id in (${selectedIds})
|
|
5827
|
-
union
|
|
5828
|
-
select selected.conversation_id, member.conversation_id
|
|
5829
|
-
from junior_conversations selected
|
|
5830
|
-
join junior_conversations member
|
|
5831
|
-
on member.root_conversation_id = selected.conversation_id
|
|
5832
|
-
where selected.conversation_id in (${selectedIds})
|
|
5833
|
-
and selected.root_conversation_id = selected.conversation_id
|
|
5834
|
-
union
|
|
5835
|
-
select scope_conversation_id, conversation_id from walk
|
|
5836
|
-
) conversation_subtree`;
|
|
4647
|
+
/** Delete one install-wide Workspace recipe. */
|
|
4648
|
+
async function deleteWorkspace(id) {
|
|
4649
|
+
const executor = getSqlExecutor();
|
|
4650
|
+
const result = await executor.transaction(async () => {
|
|
4651
|
+
const db = executor.db();
|
|
4652
|
+
return {
|
|
4653
|
+
builderNames: await clearWorkspaceSnapshots(db, id),
|
|
4654
|
+
deleted: (await db.delete(juniorWorkspaces).where(eq(juniorWorkspaces.id, id)).returning({ id: juniorWorkspaces.id })).length > 0
|
|
4655
|
+
};
|
|
4656
|
+
});
|
|
4657
|
+
await cleanupSnapshotBuilders(id, result.builderNames);
|
|
4658
|
+
return result.deleted;
|
|
5837
4659
|
}
|
|
5838
4660
|
// src/chat/state/turn-id.ts
|
|
5839
4661
|
/** Build a stable turn identifier from a message ID. */
|
|
@@ -5844,6 +4666,45 @@ function buildDeterministicTurnId(messageId) {
|
|
|
5844
4666
|
function buildDeterministicAssistantMessageId(turnId) {
|
|
5845
4667
|
return `${turnId}:assistant:1`;
|
|
5846
4668
|
}
|
|
4669
|
+
// src/chat/plugins/prompt-history-messages.ts
|
|
4670
|
+
function textParts(message) {
|
|
4671
|
+
if (!("role" in message) || message.role !== "user") return [];
|
|
4672
|
+
const { content } = message;
|
|
4673
|
+
if (typeof content === "string") return [content];
|
|
4674
|
+
return content.flatMap((part) => part.type === "text" ? [part.text] : []);
|
|
4675
|
+
}
|
|
4676
|
+
function historyMessage(message, pluginName) {
|
|
4677
|
+
if (isToolResultMessage(message)) return {
|
|
4678
|
+
type: "tool_result",
|
|
4679
|
+
tool_name: normalizeToolNameFromResult(message) ?? "",
|
|
4680
|
+
is_error: isToolResultError(message)
|
|
4681
|
+
};
|
|
4682
|
+
const texts = textParts(message);
|
|
4683
|
+
if (texts.length === 0) return void 0;
|
|
4684
|
+
const contributions = (blockTexts) => blockTexts.flatMap((text) => readPluginContributions(text, pluginName));
|
|
4685
|
+
const contexts = texts.filter((text) => startsWithTag(text, [TURN_CONTEXT_TAG]));
|
|
4686
|
+
if (contexts.length > 0) return {
|
|
4687
|
+
type: "context",
|
|
4688
|
+
contributions: contributions(contexts)
|
|
4689
|
+
};
|
|
4690
|
+
const summaries = texts.filter(isCompactionSummaryText);
|
|
4691
|
+
if (summaries.length > 0) return {
|
|
4692
|
+
type: "summary",
|
|
4693
|
+
contributions: contributions(summaries)
|
|
4694
|
+
};
|
|
4695
|
+
return { type: "input" };
|
|
4696
|
+
}
|
|
4697
|
+
/**
|
|
4698
|
+
* Describe the model history that a new prompt replays for one plugin's
|
|
4699
|
+
* `userPrompt` hook: each input, each Turn context and compaction summary
|
|
4700
|
+
* with the plugin's contributions in it, and each tool result.
|
|
4701
|
+
*/
|
|
4702
|
+
function pluginPromptHistoryMessages(messages, pluginName) {
|
|
4703
|
+
return messages.flatMap((message) => {
|
|
4704
|
+
const described = historyMessage(message, pluginName);
|
|
4705
|
+
return described ? [described] : [];
|
|
4706
|
+
});
|
|
4707
|
+
}
|
|
5847
4708
|
// src/chat/conversations/notes.ts
|
|
5848
4709
|
/**
|
|
5849
4710
|
* Conversation notes: short facts that core attaches to a Conversation without
|
|
@@ -5862,13 +4723,6 @@ function failedTurnNote(failureCode, eventId) {
|
|
|
5862
4723
|
}
|
|
5863
4724
|
/** Most notes that one Turn shows. Older notes in the window are dropped. */
|
|
5864
4725
|
const MAX_CONVERSATION_NOTES_PER_TURN = 20;
|
|
5865
|
-
function noteIdempotencyKey(key) {
|
|
5866
|
-
return `native:${JUNIOR_NATIVE_EVENT_NAMESPACE}:conversation_note:${key}`;
|
|
5867
|
-
}
|
|
5868
|
-
/** Return whether a Conversation already has the note with this key. */
|
|
5869
|
-
async function hasConversationNote(input) {
|
|
5870
|
-
return Boolean(await getConversationEventStore().loadByIdempotencyKey(input.conversationId, noteIdempotencyKey(input.key)));
|
|
5871
|
-
}
|
|
5872
4726
|
/**
|
|
5873
4727
|
* Attach a core-written note to a Conversation. It does not start a Turn or
|
|
5874
4728
|
* change Conversation activity. The key makes a retry add nothing. Long text
|
|
@@ -5879,7 +4733,7 @@ async function addConversationNote(input) {
|
|
|
5879
4733
|
const text = line.length > 500 ? `${line.slice(0, 499)}…` : line;
|
|
5880
4734
|
await getConversationEventStore().append(input.conversationId, [{
|
|
5881
4735
|
createdAtMs: input.createdAtMs,
|
|
5882
|
-
idempotencyKey:
|
|
4736
|
+
idempotencyKey: `native:${JUNIOR_NATIVE_EVENT_NAMESPACE}:conversation_note:${input.key}`,
|
|
5883
4737
|
data: {
|
|
5884
4738
|
type: "structured_event",
|
|
5885
4739
|
namespace: JUNIOR_NATIVE_EVENT_NAMESPACE,
|
|
@@ -5926,1161 +4780,6 @@ async function loadTurnConversationNotes(input) {
|
|
|
5926
4780
|
}
|
|
5927
4781
|
return newestFirst.reverse();
|
|
5928
4782
|
}
|
|
5929
|
-
// src/chat/todos/tool-output.ts
|
|
5930
|
-
const TODO_REF_PREFIX = "TODO-";
|
|
5931
|
-
/** Render the model-facing reference of a To-do id. */
|
|
5932
|
-
function todoRef(id) {
|
|
5933
|
-
return `${TODO_REF_PREFIX}${id}`;
|
|
5934
|
-
}
|
|
5935
|
-
/** To-do reference that the model passes back to a tool, such as `TODO-12`. */
|
|
5936
|
-
const todoRefSchema = z.string().trim().regex(new RegExp(`^${TODO_REF_PREFIX}[1-9]\\d*$`), `Use a To-do reference such as ${TODO_REF_PREFIX}12.`);
|
|
5937
|
-
/** Read the To-do id from a reference that `todoRefSchema` accepted. */
|
|
5938
|
-
function parseTodoRef(ref) {
|
|
5939
|
-
return Number(ref.trim().slice(5));
|
|
5940
|
-
}
|
|
5941
|
-
/** To-do shape in tool results. */
|
|
5942
|
-
const todoOutputSchema = z.object({
|
|
5943
|
-
id: z.string(),
|
|
5944
|
-
title: z.string(),
|
|
5945
|
-
notes: z.string().optional(),
|
|
5946
|
-
status: z.enum(TODO_STATUSES),
|
|
5947
|
-
assignee: z.string()
|
|
5948
|
-
}).strict();
|
|
5949
|
-
/** Render one To-do for a tool result, with assignee text for the reader. */
|
|
5950
|
-
function outputTodo(todo, assignee) {
|
|
5951
|
-
return {
|
|
5952
|
-
id: todoRef(todo.id),
|
|
5953
|
-
title: todo.title,
|
|
5954
|
-
...todo.notes ? { notes: todo.notes } : void 0,
|
|
5955
|
-
status: todo.status,
|
|
5956
|
-
assignee
|
|
5957
|
-
};
|
|
5958
|
-
}
|
|
5959
|
-
// src/chat/todos/prompt.ts
|
|
5960
|
-
/**
|
|
5961
|
-
* Turn context section with the To-do changes that others made. Blocks are
|
|
5962
|
-
* append-only; context compaction replaces them with one `<todos>` snapshot.
|
|
5963
|
-
*/
|
|
5964
|
-
const TODO_DELTA_TAG = "todo-delta";
|
|
5965
|
-
/** Compacted context block with every open To-do. */
|
|
5966
|
-
const TODOS_TAG = "todos";
|
|
5967
|
-
const VERSION_LINE = /^To-do version (\d+)\./;
|
|
5968
|
-
/** Render an assignee as the text that `updateTodos` accepts. */
|
|
5969
|
-
function renderTodoAssignee(assignee) {
|
|
5970
|
-
switch (assignee.kind) {
|
|
5971
|
-
case "self": return SELF_TODO_ASSIGNEE;
|
|
5972
|
-
case "agent": return assignee.name ?? assignee.conversationId;
|
|
5973
|
-
case "user": return assignee.email;
|
|
5974
|
-
}
|
|
5975
|
-
}
|
|
5976
|
-
function renderAuthor(todo) {
|
|
5977
|
-
if (todo.changedBy) {
|
|
5978
|
-
const { email, name } = todo.changedBy;
|
|
5979
|
-
return name ? `${name} (${email})` : email;
|
|
5980
|
-
}
|
|
5981
|
-
if (todo.changedByAgent) return `child agent ${todo.changedByAgent.name ?? todo.changedByAgent.conversationId}`;
|
|
5982
|
-
}
|
|
5983
|
-
function renderTodo(todo, withAuthor) {
|
|
5984
|
-
const author = withAuthor ? renderAuthor(todo) : void 0;
|
|
5985
|
-
const fields = [
|
|
5986
|
-
todo.status,
|
|
5987
|
-
`assignee ${renderTodoAssignee(todo.assignee)}`,
|
|
5988
|
-
...author ? [`changed by ${author}`] : []
|
|
5989
|
-
];
|
|
5990
|
-
const notes = todo.notes ? `\n Notes: ${todo.notes}` : "";
|
|
5991
|
-
return escapeTagText(`- ${todoRef(todo.id)} (${fields.join(", ")}): ${todo.title}${notes}`);
|
|
5992
|
-
}
|
|
5993
|
-
function todosVersion(todos) {
|
|
5994
|
-
return Math.max(...todos.map((todo) => todo.version));
|
|
5995
|
-
}
|
|
5996
|
-
function textParts(message) {
|
|
5997
|
-
if (!("role" in message) || message.role !== "user") return [];
|
|
5998
|
-
const { content } = message;
|
|
5999
|
-
if (typeof content === "string") return [content];
|
|
6000
|
-
return content.flatMap((part) => part.type === "text" ? [part.text] : []);
|
|
6001
|
-
}
|
|
6002
|
-
function todosBlockVersion(message) {
|
|
6003
|
-
let seen = 0;
|
|
6004
|
-
for (const text of textParts(message)) {
|
|
6005
|
-
if (!startsWithTag(text, ["runtime-turn-context"]) && !isCompactionSummaryText(text)) continue;
|
|
6006
|
-
for (const tag of [TODOS_TAG, TODO_DELTA_TAG]) for (const block of findTags(text, tag)) {
|
|
6007
|
-
const version = VERSION_LINE.exec(block.body)?.[1];
|
|
6008
|
-
if (version) seen = Math.max(seen, Number(version));
|
|
6009
|
-
}
|
|
6010
|
-
}
|
|
6011
|
-
return seen;
|
|
6012
|
-
}
|
|
6013
|
-
/** Return the highest To-do version that the runtime blocks of history show. */
|
|
6014
|
-
function latestSeenTodosVersion(messages) {
|
|
6015
|
-
let seen = 0;
|
|
6016
|
-
for (const message of messages) seen = Math.max(seen, todosBlockVersion(message));
|
|
6017
|
-
return seen;
|
|
6018
|
-
}
|
|
6019
|
-
/**
|
|
6020
|
-
* Render the changes that people and child agents made after the version
|
|
6021
|
-
* that history shows, or null when there are none. Changes of the list's own
|
|
6022
|
-
* agent are left out: its tool calls and results are already in history.
|
|
6023
|
-
*/
|
|
6024
|
-
function renderTodoDelta(todos, seenVersion) {
|
|
6025
|
-
const changed = todos.filter((todo) => (todo.changedBy || todo.changedByAgent) && todo.version > seenVersion);
|
|
6026
|
-
if (changed.length === 0) return null;
|
|
6027
|
-
return renderTag(TODO_DELTA_TAG, {}, [`To-do version ${todosVersion(todos)}. Others changed these To-dos since you last saw them. Each To-do shows its current fields.`, ...changed.map((todo) => renderTodo(todo, true))]);
|
|
6028
|
-
}
|
|
6029
|
-
/**
|
|
6030
|
-
* Render every open To-do as one snapshot, or null when the Conversation has
|
|
6031
|
-
* no To-dos. When every To-do is closed, the block still keeps the version
|
|
6032
|
-
* in history.
|
|
6033
|
-
*/
|
|
6034
|
-
function renderTodosSnapshot(todos) {
|
|
6035
|
-
if (todos.length === 0) return null;
|
|
6036
|
-
const open = todos.filter((todo) => isOpenTodoStatus(todo.status));
|
|
6037
|
-
return renderTag(TODOS_TAG, {}, [`To-do version ${todosVersion(todos)}. ${open.length > 0 ? "Your open To-dos." : "You have no open To-dos."}`, ...open.map((todo) => renderTodo(todo, false))]);
|
|
6038
|
-
}
|
|
6039
|
-
const TODOS_REVIEW_INTERVAL = 3;
|
|
6040
|
-
function isInput(message) {
|
|
6041
|
-
const texts = textParts(message);
|
|
6042
|
-
return texts.length > 0 && !texts.some((text) => startsWithTag(text, ["runtime-turn-context"]));
|
|
6043
|
-
}
|
|
6044
|
-
function showsTodos(message) {
|
|
6045
|
-
if (isToolResultMessage(message)) return !isToolResultError(message) && normalizeToolNameFromResult(message) === "updateTodos";
|
|
6046
|
-
return todosBlockVersion(message) > 0;
|
|
6047
|
-
}
|
|
6048
|
-
/**
|
|
6049
|
-
* Render every open To-do as a `<todos>` review, or null when there are no
|
|
6050
|
-
* open To-dos or history showed the To-dos recently. The model forgets to
|
|
6051
|
-
* close To-dos whose work ended, so stale To-dos come back on a fixed
|
|
6052
|
-
* interval.
|
|
6053
|
-
*/
|
|
6054
|
-
function renderTodosReview(todos, messages) {
|
|
6055
|
-
const open = todos.filter((todo) => isOpenTodoStatus(todo.status));
|
|
6056
|
-
if (open.length === 0) return null;
|
|
6057
|
-
let inputs = 0;
|
|
6058
|
-
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
6059
|
-
const message = messages[index];
|
|
6060
|
-
if (showsTodos(message)) return null;
|
|
6061
|
-
if (isInput(message)) inputs += 1;
|
|
6062
|
-
if (inputs >= TODOS_REVIEW_INTERVAL) break;
|
|
6063
|
-
}
|
|
6064
|
-
if (inputs < TODOS_REVIEW_INTERVAL) return null;
|
|
6065
|
-
return renderTag(TODOS_TAG, {}, [`To-do version ${todosVersion(todos)}. These To-dos are still open. Close each one whose work ended.`, ...open.map((todo) => renderTodo(todo, false))]);
|
|
6066
|
-
}
|
|
6067
|
-
// src/chat/task-execution/store.ts
|
|
6068
|
-
function metadataStore(options) {
|
|
6069
|
-
return options.conversationStore ?? getConversationStore();
|
|
6070
|
-
}
|
|
6071
|
-
function duplicateInboundNudgeIdempotencyKey(message, nowMs) {
|
|
6072
|
-
return `duplicate:${message.conversationId}:${message.inboundMessageId}:${nowMs}`;
|
|
6073
|
-
}
|
|
6074
|
-
function hasRecentEnqueueMarker(conversation, nowMs) {
|
|
6075
|
-
const lastEnqueuedAtMs = conversation.execution.lastEnqueuedAtMs;
|
|
6076
|
-
return typeof lastEnqueuedAtMs === "number" && lastEnqueuedAtMs + 6e4 > nowMs;
|
|
6077
|
-
}
|
|
6078
|
-
function now() {
|
|
6079
|
-
return Date.now();
|
|
6080
|
-
}
|
|
6081
|
-
async function recordExecutionMetadata(args) {
|
|
6082
|
-
const conversation = await getConversation$1({
|
|
6083
|
-
conversationId: args.conversationId,
|
|
6084
|
-
state: args.state
|
|
6085
|
-
});
|
|
6086
|
-
if (!conversation) return;
|
|
6087
|
-
await metadataStore(args).recordExecution({
|
|
6088
|
-
channelName: conversation.channelName,
|
|
6089
|
-
conversationId: conversation.conversationId,
|
|
6090
|
-
createdAtMs: conversation.createdAtMs,
|
|
6091
|
-
destination: conversation.destination,
|
|
6092
|
-
execution: {
|
|
6093
|
-
lastCheckpointAtMs: conversation.execution.lastCheckpointAtMs,
|
|
6094
|
-
lastEnqueuedAtMs: conversation.execution.lastEnqueuedAtMs,
|
|
6095
|
-
runId: conversation.execution.runId,
|
|
6096
|
-
status: conversation.execution.status,
|
|
6097
|
-
updatedAtMs: conversation.execution.updatedAtMs
|
|
6098
|
-
},
|
|
6099
|
-
lastActivityAtMs: conversation.lastActivityAtMs,
|
|
6100
|
-
metrics: null,
|
|
6101
|
-
actor: conversation.actor,
|
|
6102
|
-
source: conversation.source,
|
|
6103
|
-
title: conversation.title,
|
|
6104
|
-
updatedAtMs: conversation.updatedAtMs
|
|
6105
|
-
});
|
|
6106
|
-
}
|
|
6107
|
-
/** Return a persisted conversation record, if one exists. */
|
|
6108
|
-
async function getConversation(args) {
|
|
6109
|
-
return await getConversation$1(args);
|
|
6110
|
-
}
|
|
6111
|
-
/** Return a persisted conversation work record, if one exists. */
|
|
6112
|
-
async function getConversationWorkState(args) {
|
|
6113
|
-
return await getConversationWorkState$1(args);
|
|
6114
|
-
}
|
|
6115
|
-
/** Return the persisted work records of several Conversations in one read. */
|
|
6116
|
-
async function getConversationWorkStates(conversationIds) {
|
|
6117
|
-
return await getConversationWorkStates$1(conversationIds);
|
|
6118
|
-
}
|
|
6119
|
-
/** Count one failed conversation execution and persist its terminal retry state. */
|
|
6120
|
-
async function recordConversationRetry(args) {
|
|
6121
|
-
const result = await recordConversationRetry$1(args);
|
|
6122
|
-
await recordExecutionMetadata(args);
|
|
6123
|
-
return result;
|
|
6124
|
-
}
|
|
6125
|
-
/**
|
|
6126
|
-
* Ensure runnable conversation work has one accepted queue wake-up nudge.
|
|
6127
|
-
*
|
|
6128
|
-
* Ordinary wakes coalesce on a recent accepted marker. A caller can ignore the
|
|
6129
|
-
* marker without replacing an active lease. Replacement is only for consumed
|
|
6130
|
-
* or known-stale deliveries where another queue nudge must exist.
|
|
6131
|
-
*/
|
|
6132
|
-
async function ensureConversationWake(args) {
|
|
6133
|
-
const nowMs = args.nowMs ?? now();
|
|
6134
|
-
const conversation = await getConversation$1({
|
|
6135
|
-
conversationId: args.conversationId,
|
|
6136
|
-
state: args.state
|
|
6137
|
-
});
|
|
6138
|
-
if (!conversation || !hasRunnableConversationWork(conversation)) return { status: "no_work" };
|
|
6139
|
-
if (args.replaceExistingWake !== true && conversation.execution.lease && conversation.execution.lease.expiresAtMs > nowMs) return { status: "lease_active" };
|
|
6140
|
-
if (args.ignoreEnqueueMarker !== true && args.replaceExistingWake !== true && hasRecentEnqueueMarker(conversation, nowMs)) return { status: "already_enqueued" };
|
|
6141
|
-
const queueResult = await args.queue.send({
|
|
6142
|
-
schemaVersion: 2,
|
|
6143
|
-
conversationId: args.conversationId
|
|
6144
|
-
}, {
|
|
6145
|
-
delayMs: args.delayMs,
|
|
6146
|
-
idempotencyKey: args.idempotencyKey
|
|
6147
|
-
});
|
|
6148
|
-
await markConversationWorkEnqueued({
|
|
6149
|
-
conversationId: args.conversationId,
|
|
6150
|
-
conversationStore: args.conversationStore,
|
|
6151
|
-
nowMs,
|
|
6152
|
-
state: args.state
|
|
6153
|
-
});
|
|
6154
|
-
return {
|
|
6155
|
-
status: "enqueued",
|
|
6156
|
-
queueMessageId: queueResult?.messageId
|
|
6157
|
-
};
|
|
6158
|
-
}
|
|
6159
|
-
/** Persist one inbound message idempotently in its conversation mailbox. */
|
|
6160
|
-
async function appendInboundMessage(args) {
|
|
6161
|
-
const result = await appendInboundMessage$1(args);
|
|
6162
|
-
await recordExecutionMetadata({
|
|
6163
|
-
conversationId: args.message.conversationId,
|
|
6164
|
-
conversationStore: args.conversationStore,
|
|
6165
|
-
state: args.state
|
|
6166
|
-
});
|
|
6167
|
-
return result;
|
|
6168
|
-
}
|
|
6169
|
-
/**
|
|
6170
|
-
* Record an inbound message id that skips the mailbox. When the claim is
|
|
6171
|
-
* saved but its metadata write fails, this releases the claim, so a
|
|
6172
|
-
* redelivery can claim it again.
|
|
6173
|
-
*/
|
|
6174
|
-
async function claimInboundMessage(args) {
|
|
6175
|
-
const result = await claimInboundMessage$1(args);
|
|
6176
|
-
if (result.status === "claimed") try {
|
|
6177
|
-
await recordExecutionMetadata({
|
|
6178
|
-
conversationId: args.message.conversationId,
|
|
6179
|
-
conversationStore: args.conversationStore,
|
|
6180
|
-
state: args.state
|
|
6181
|
-
});
|
|
6182
|
-
} catch (error) {
|
|
6183
|
-
await releaseInboundMessage({
|
|
6184
|
-
message: args.message,
|
|
6185
|
-
state: args.state
|
|
6186
|
-
});
|
|
6187
|
-
throw error;
|
|
6188
|
-
}
|
|
6189
|
-
return result;
|
|
6190
|
-
}
|
|
6191
|
-
async function enqueueAfterAppend(args) {
|
|
6192
|
-
const nowMs = args.nowMs ?? now();
|
|
6193
|
-
const appendResult = args.appendResult;
|
|
6194
|
-
if (appendResult.status === "active") return appendResult;
|
|
6195
|
-
let idempotencyKey = args.message.inboundMessageId;
|
|
6196
|
-
if (appendResult.status === "duplicate") {
|
|
6197
|
-
const conversation = await getConversation$1({
|
|
6198
|
-
conversationId: args.message.conversationId,
|
|
6199
|
-
state: args.state
|
|
6200
|
-
});
|
|
6201
|
-
if (!conversation) return appendResult;
|
|
6202
|
-
if (hasRecentEnqueueMarker(conversation, nowMs)) {
|
|
6203
|
-
await recordExecutionMetadata({
|
|
6204
|
-
conversationId: args.message.conversationId,
|
|
6205
|
-
conversationStore: args.conversationStore,
|
|
6206
|
-
state: args.state
|
|
6207
|
-
});
|
|
6208
|
-
return appendResult;
|
|
6209
|
-
}
|
|
6210
|
-
if (!conversation.execution.pendingMessages.some((message) => message.inboundMessageId === args.message.inboundMessageId)) {
|
|
6211
|
-
await recordExecutionMetadata({
|
|
6212
|
-
conversationId: args.message.conversationId,
|
|
6213
|
-
conversationStore: args.conversationStore,
|
|
6214
|
-
state: args.state
|
|
6215
|
-
});
|
|
6216
|
-
return appendResult;
|
|
6217
|
-
}
|
|
6218
|
-
idempotencyKey = duplicateInboundNudgeIdempotencyKey(args.message, nowMs);
|
|
6219
|
-
}
|
|
6220
|
-
const wake = await ensureConversationWake({
|
|
6221
|
-
conversationId: args.message.conversationId,
|
|
6222
|
-
conversationStore: args.conversationStore,
|
|
6223
|
-
delayMs: args.queueDelayMs,
|
|
6224
|
-
idempotencyKey,
|
|
6225
|
-
ignoreEnqueueMarker: args.message.source === "event" ? void 0 : true,
|
|
6226
|
-
nowMs,
|
|
6227
|
-
queue: args.queue,
|
|
6228
|
-
replaceExistingWake: args.replaceExistingWake,
|
|
6229
|
-
state: args.state
|
|
6230
|
-
});
|
|
6231
|
-
if (wake.status !== "enqueued") await recordExecutionMetadata({
|
|
6232
|
-
conversationId: args.message.conversationId,
|
|
6233
|
-
conversationStore: args.conversationStore,
|
|
6234
|
-
state: args.state
|
|
6235
|
-
});
|
|
6236
|
-
return {
|
|
6237
|
-
...appendResult,
|
|
6238
|
-
...wake.status === "enqueued" ? { queueMessageId: wake.queueMessageId } : void 0
|
|
6239
|
-
};
|
|
6240
|
-
}
|
|
6241
|
-
/** Persist inbound work and ensure a worker wake-up. */
|
|
6242
|
-
async function appendAndEnqueueInboundMessage(args) {
|
|
6243
|
-
const nowMs = args.nowMs ?? now();
|
|
6244
|
-
const result = await enqueueAfterAppend({
|
|
6245
|
-
...args,
|
|
6246
|
-
appendResult: await appendInboundMessage$1({
|
|
6247
|
-
message: args.message,
|
|
6248
|
-
nowMs,
|
|
6249
|
-
renderText: args.renderText,
|
|
6250
|
-
state: args.state
|
|
6251
|
-
}),
|
|
6252
|
-
nowMs
|
|
6253
|
-
});
|
|
6254
|
-
if (result.status === "active") throw new Error("Non-exclusive mailbox enqueue returned active");
|
|
6255
|
-
return result;
|
|
6256
|
-
}
|
|
6257
|
-
/** Persist exclusive inbound work and wake its worker when admitted. */
|
|
6258
|
-
async function appendAndEnqueueExclusiveInboundMessage(args) {
|
|
6259
|
-
const nowMs = args.nowMs ?? now();
|
|
6260
|
-
return await enqueueAfterAppend({
|
|
6261
|
-
...args,
|
|
6262
|
-
appendResult: await appendExclusiveInboundMessage({
|
|
6263
|
-
message: args.message,
|
|
6264
|
-
nowMs,
|
|
6265
|
-
state: args.state
|
|
6266
|
-
}),
|
|
6267
|
-
nowMs
|
|
6268
|
-
});
|
|
6269
|
-
}
|
|
6270
|
-
/** Persist a stop request for the current Conversation run. */
|
|
6271
|
-
async function stopConversationWork(args) {
|
|
6272
|
-
const result = await stopConversationWork$1(args);
|
|
6273
|
-
if (result.status === "requested") {
|
|
6274
|
-
args.onStopSaved?.();
|
|
6275
|
-
await recordExecutionMetadata(args);
|
|
6276
|
-
}
|
|
6277
|
-
return result;
|
|
6278
|
-
}
|
|
6279
|
-
/** Finish an observed stop request under the current worker lease. */
|
|
6280
|
-
async function completeConversationStop(args) {
|
|
6281
|
-
const result = await completeConversationStop$1(args);
|
|
6282
|
-
if (result.status === "cleared") await recordExecutionMetadata(args);
|
|
6283
|
-
return result;
|
|
6284
|
-
}
|
|
6285
|
-
/** Clear an accepted wake marker after its delivery finds no runnable work. */
|
|
6286
|
-
async function clearConsumedConversationWake(args) {
|
|
6287
|
-
const result = await clearConsumedConversationWake$1(args);
|
|
6288
|
-
if (result) await recordExecutionMetadata(args);
|
|
6289
|
-
return result;
|
|
6290
|
-
}
|
|
6291
|
-
/** Mark a conversation runnable when there is no new mailbox message. */
|
|
6292
|
-
async function requestConversationWork(args) {
|
|
6293
|
-
const result = await requestConversationWork$1(args);
|
|
6294
|
-
await recordExecutionMetadata({
|
|
6295
|
-
conversationId: args.conversationId,
|
|
6296
|
-
conversationStore: args.conversationStore,
|
|
6297
|
-
state: args.state
|
|
6298
|
-
});
|
|
6299
|
-
return result;
|
|
6300
|
-
}
|
|
6301
|
-
/** Record that a wake-up nudge was accepted for the conversation. */
|
|
6302
|
-
async function markConversationWorkEnqueued(args) {
|
|
6303
|
-
await markConversationWorkEnqueued$1(args);
|
|
6304
|
-
await recordExecutionMetadata(args);
|
|
6305
|
-
}
|
|
6306
|
-
/** Try to acquire the durable execution lease for one conversation. */
|
|
6307
|
-
async function startConversationWork(args) {
|
|
6308
|
-
const result = await startConversationWork$1(args);
|
|
6309
|
-
await recordExecutionMetadata(args);
|
|
6310
|
-
return result;
|
|
6311
|
-
}
|
|
6312
|
-
/** Extend the durable execution lease when the worker checks in. */
|
|
6313
|
-
async function checkInConversationWork(args) {
|
|
6314
|
-
const result = await checkInConversationWork$1(args);
|
|
6315
|
-
if (result) await recordExecutionMetadata(args);
|
|
6316
|
-
return result;
|
|
6317
|
-
}
|
|
6318
|
-
/** Drain pending mailbox entries after the caller accepts responsibility. */
|
|
6319
|
-
async function drainConversationMailbox(args) {
|
|
6320
|
-
const result = await drainConversationMailbox$1(args);
|
|
6321
|
-
if (result.changed) await recordExecutionMetadata(args);
|
|
6322
|
-
return result.messages;
|
|
6323
|
-
}
|
|
6324
|
-
/** Record the input of the attempt that the lease holder starts. */
|
|
6325
|
-
async function claimConversationAttempt(args) {
|
|
6326
|
-
return await claimConversationAttempt$1(args);
|
|
6327
|
-
}
|
|
6328
|
-
/** Acknowledge leased mailbox entries after the handler accepts responsibility. */
|
|
6329
|
-
async function ackMessages(args) {
|
|
6330
|
-
const result = await ackMessages$1(args);
|
|
6331
|
-
await recordExecutionMetadata(args);
|
|
6332
|
-
return result;
|
|
6333
|
-
}
|
|
6334
|
-
/** Cancel human-facing pending mailbox rows without requiring a worker lease. */
|
|
6335
|
-
async function cancelHumanFacingPendingMessages(args) {
|
|
6336
|
-
const result = await cancelHumanFacingPendingMessages$1(args);
|
|
6337
|
-
if (result.cancelledInboundMessageIds.length > 0) await recordExecutionMetadata(args);
|
|
6338
|
-
return result;
|
|
6339
|
-
}
|
|
6340
|
-
/** Drop pending mailbox rows by id without requiring a worker lease. */
|
|
6341
|
-
async function dropPendingMessages(args) {
|
|
6342
|
-
const dropped = await dropPendingMessages$1(args);
|
|
6343
|
-
if (dropped.length > 0) await recordExecutionMetadata(args);
|
|
6344
|
-
return dropped;
|
|
6345
|
-
}
|
|
6346
|
-
/** Remove and return the pending Event input of a Conversation. */
|
|
6347
|
-
async function takePendingEventMessages(args) {
|
|
6348
|
-
const taken = await takePendingEventMessages$1(args);
|
|
6349
|
-
if (taken.length > 0) await recordExecutionMetadata(args);
|
|
6350
|
-
return taken;
|
|
6351
|
-
}
|
|
6352
|
-
/** Mark one author's queued web messages as interrupts. */
|
|
6353
|
-
async function steerWebPendingMessages(args) {
|
|
6354
|
-
return await steerWebPendingMessages$1(args);
|
|
6355
|
-
}
|
|
6356
|
-
/** Mark the leased conversation as needing another queue-delivered slice. */
|
|
6357
|
-
async function requestAnotherSlice(args) {
|
|
6358
|
-
const result = await requestAnotherSlice$1(args);
|
|
6359
|
-
await recordExecutionMetadata(args);
|
|
6360
|
-
return result;
|
|
6361
|
-
}
|
|
6362
|
-
/** Begin a requested turn resume without releasing the current lease. */
|
|
6363
|
-
async function beginConversationResume(args) {
|
|
6364
|
-
const result = await beginConversationResume$1(args);
|
|
6365
|
-
if (result) await recordExecutionMetadata(args);
|
|
6366
|
-
return result;
|
|
6367
|
-
}
|
|
6368
|
-
/** Release the durable execution lease without changing completion state. */
|
|
6369
|
-
async function releaseConversationWork(args) {
|
|
6370
|
-
const result = await releaseConversationWork$1(args);
|
|
6371
|
-
await recordExecutionMetadata(args);
|
|
6372
|
-
return result;
|
|
6373
|
-
}
|
|
6374
|
-
/** Finish a leased conversation and report whether runnable work remains. */
|
|
6375
|
-
async function completeConversationWork(args) {
|
|
6376
|
-
const result = await completeConversationWork$1(args);
|
|
6377
|
-
await recordExecutionMetadata(args);
|
|
6378
|
-
if (result !== "lost_lease") await runDeferredMove(args);
|
|
6379
|
-
return result;
|
|
6380
|
-
}
|
|
6381
|
-
/**
|
|
6382
|
-
* Run the Slack "Continue here" click that waited for this Run to end. Its
|
|
6383
|
-
* failure is logged here, so it never fails the Run that already finished.
|
|
6384
|
-
*/
|
|
6385
|
-
async function runDeferredMove(args) {
|
|
6386
|
-
const move = await takeDeferredConversationMove(args);
|
|
6387
|
-
if (move === void 0) return;
|
|
6388
|
-
try {
|
|
6389
|
-
const { continueDeferredSlackClick } = await import("./slack-conversation-unfurl-Dhe3lB1U.js").then((n) => n.r);
|
|
6390
|
-
await continueDeferredSlackClick(move, args.getSlackAdapter);
|
|
6391
|
-
} catch (error) {
|
|
6392
|
-
logException(error, "slack.continue_here.deferred.failed", { "gen_ai.conversation.id": args.conversationId });
|
|
6393
|
-
}
|
|
6394
|
-
}
|
|
6395
|
-
/** Record one failed delivery attempt and dead-letter messages at their limit. */
|
|
6396
|
-
async function recordAttemptFailure(args) {
|
|
6397
|
-
const result = await recordAttemptFailure$1(args);
|
|
6398
|
-
if (result.status === "recorded") await recordExecutionMetadata(args);
|
|
6399
|
-
return result;
|
|
6400
|
-
}
|
|
6401
|
-
/** Record a terminal failure completion for a leased conversation. */
|
|
6402
|
-
async function deadLetterAttempt(args) {
|
|
6403
|
-
const result = await deadLetterAttempt$1(args);
|
|
6404
|
-
await recordExecutionMetadata(args);
|
|
6405
|
-
return result;
|
|
6406
|
-
}
|
|
6407
|
-
/** Recover an expired lease and persist the resulting retry state. */
|
|
6408
|
-
async function clearExpiredConversationLease(args) {
|
|
6409
|
-
const result = await clearExpiredConversationLease$1(args);
|
|
6410
|
-
await recordExecutionMetadata(args);
|
|
6411
|
-
return result;
|
|
6412
|
-
}
|
|
6413
|
-
/** List active conversation ids by oldest execution update first. */
|
|
6414
|
-
async function listActiveConversationIds(args = {}) {
|
|
6415
|
-
return await listActiveConversationIds$1(args);
|
|
6416
|
-
}
|
|
6417
|
-
// src/chat/notifications/inbox-item-push.ts
|
|
6418
|
-
/**
|
|
6419
|
-
* How long a Slack card waits before its item pushes. A User who saw the
|
|
6420
|
-
* card in that time answers it, which closes the item.
|
|
6421
|
-
*/
|
|
6422
|
-
const SLACK_CARD_PUSH_DELAY_MS = 3e5;
|
|
6423
|
-
/** Pending pushes after a Slack card. Each id names one item and one User. */
|
|
6424
|
-
const INBOX_ITEM_PUSH_TIMER_INDEX = {
|
|
6425
|
-
batchSize: 100,
|
|
6426
|
-
key: "junior:inbox-items:push-due"
|
|
6427
|
-
};
|
|
6428
|
-
const pushTimerSchema = z.tuple([z.string(), z.string()]);
|
|
6429
|
-
function pushTimerId(itemId, userId) {
|
|
6430
|
-
return JSON.stringify([itemId, userId]);
|
|
6431
|
-
}
|
|
6432
|
-
async function scheduleInboxItemPushTimer(id, atMs) {
|
|
6433
|
-
const state = getStateAdapter();
|
|
6434
|
-
await state.connect();
|
|
6435
|
-
await updateTimerIndex(state, INBOX_ITEM_PUSH_TIMER_INDEX, {
|
|
6436
|
-
atMs,
|
|
6437
|
-
id,
|
|
6438
|
-
kind: "add"
|
|
6439
|
-
});
|
|
6440
|
-
}
|
|
6441
|
-
/**
|
|
6442
|
-
* Record the Slack card of an open item for each assignee, and keep a push
|
|
6443
|
-
* timer from their first card for each one with no push yet. A User
|
|
6444
|
-
* assigned again after their timer fired gets it again, and a timer that
|
|
6445
|
-
* is due already fires at the next heartbeat.
|
|
6446
|
-
*/
|
|
6447
|
-
async function scheduleSlackCardPushes(db, item) {
|
|
6448
|
-
const carded = await recordInboxItemSlackCard(db, {
|
|
6449
|
-
itemId: item.id,
|
|
6450
|
-
nowMs: Date.now(),
|
|
6451
|
-
userIds: item.assignees.map((assignee) => assignee.userId)
|
|
6452
|
-
});
|
|
6453
|
-
const pushed = await listInboxItemPushUserIds(db, item.id);
|
|
6454
|
-
for (const [userId, cardedAtMs] of carded) {
|
|
6455
|
-
if (pushed.has(userId)) continue;
|
|
6456
|
-
await scheduleInboxItemPushTimer(pushTimerId(item.id, userId), cardedAtMs + SLACK_CARD_PUSH_DELAY_MS);
|
|
6457
|
-
}
|
|
6458
|
-
}
|
|
6459
|
-
async function hasSlackCard(db, itemId) {
|
|
6460
|
-
return (await db.select({ itemId: juniorInboxItemSlackCards.itemId }).from(juniorInboxItemSlackCards).where(eq(juniorInboxItemSlackCards.itemId, itemId)).limit(1)).length > 0;
|
|
6461
|
-
}
|
|
6462
|
-
async function isSnoozedBy(db, itemId, userId) {
|
|
6463
|
-
return (await db.select({ id: juniorInboxItems.id }).from(juniorInboxItems).where(and(eq(juniorInboxItems.id, itemId), inboxItemSnoozedBy(userId))).limit(1)).length > 0;
|
|
6464
|
-
}
|
|
6465
|
-
async function skipReason(db, itemId, userId, nowMs) {
|
|
6466
|
-
if (await isSnoozedBy(db, itemId, userId)) return "snoozed";
|
|
6467
|
-
return await readNotificationPause(db, userId, nowMs);
|
|
6468
|
-
}
|
|
6469
|
-
/**
|
|
6470
|
-
* Record one push of an item to one User, then send it unless the User is
|
|
6471
|
-
* paused or snoozed the item. `record` returns false when another caller
|
|
6472
|
-
* already holds this push. `afterSlackCard`: the item's Slack card posted a
|
|
6473
|
-
* while ago, so a User active in Slack got Slack's own notification and
|
|
6474
|
-
* needs no push.
|
|
6475
|
-
*/
|
|
6476
|
-
async function deliverPush(args) {
|
|
6477
|
-
const { db, item, userId } = args;
|
|
6478
|
-
const nowMs = Date.now();
|
|
6479
|
-
const reason = await skipReason(db, item.id, userId, nowMs) ?? (args.afterSlackCard && await isActiveInSlack(db, userId) ? "slack_active" : void 0);
|
|
6480
|
-
if (!await args.record({
|
|
6481
|
-
itemId: item.id,
|
|
6482
|
-
nowMs,
|
|
6483
|
-
skipReason: reason,
|
|
6484
|
-
userId
|
|
6485
|
-
})) return;
|
|
6486
|
-
if (!await isInboxItemOpen(db, item.id)) {
|
|
6487
|
-
await clearInboxItemDeliveries(db, [item.id], Date.now());
|
|
6488
|
-
return;
|
|
6489
|
-
}
|
|
6490
|
-
if (reason) {
|
|
6491
|
-
logInfo("notification.inbox_item.skipped", { "app.notification.skip_reason": reason });
|
|
6492
|
-
return;
|
|
6493
|
-
}
|
|
6494
|
-
await sendPushNotificationToUser({
|
|
6495
|
-
config: args.config,
|
|
6496
|
-
db,
|
|
6497
|
-
kind: args.kind,
|
|
6498
|
-
payload: {
|
|
6499
|
-
body: notificationPreview(item.body),
|
|
6500
|
-
tag: item.id,
|
|
6501
|
-
title: item.title,
|
|
6502
|
-
url: args.url
|
|
6503
|
-
},
|
|
6504
|
-
userId
|
|
6505
|
-
});
|
|
6506
|
-
}
|
|
6507
|
-
/**
|
|
6508
|
-
* Only an action for named Users pushes. Everyone items and notices
|
|
6509
|
-
* show only in the Inbox.
|
|
6510
|
-
*/
|
|
6511
|
-
function pushesToAssignees(item) {
|
|
6512
|
-
return item.kind === "action" && !item.assignedToEveryone && item.assignees.length > 0;
|
|
6513
|
-
}
|
|
6514
|
-
/**
|
|
6515
|
-
* Push a new open action to each of its assigned Users, once per User. The
|
|
6516
|
-
* delivery record stops a second push when the item shows again, such as
|
|
6517
|
-
* after a content change. An item with a Slack card records that card for
|
|
6518
|
-
* each User and pushes to them later, from `runInboxItemPushTimers`, unless
|
|
6519
|
-
* `slackWaited` says that its wait already ended. A
|
|
6520
|
-
* User outside their notification hours, or who snoozed the item, gets no
|
|
6521
|
-
* push for it. Push is optional UI, the same as a Slack card: a failure is
|
|
6522
|
-
* logged and never fails the change that caused it, and nothing retries
|
|
6523
|
-
* it.
|
|
6524
|
-
*/
|
|
6525
|
-
async function syncInboxItemPush(itemId, options = {}) {
|
|
6526
|
-
const config = readWebPushConfig();
|
|
6527
|
-
if (!config) return;
|
|
6528
|
-
await runBestEffort(async () => {
|
|
6529
|
-
const db = getDb();
|
|
6530
|
-
const item = await getInboxItem(db, itemId);
|
|
6531
|
-
if (!item) return;
|
|
6532
|
-
if (item.status !== "open") {
|
|
6533
|
-
await clearInboxItemDeliveries(db, [item.id], Date.now());
|
|
6534
|
-
return;
|
|
6535
|
-
}
|
|
6536
|
-
if (!pushesToAssignees(item)) return;
|
|
6537
|
-
const url = getDashboardInboxItemLink(item.id);
|
|
6538
|
-
if (!url) return;
|
|
6539
|
-
const userIds = item.assignees.map((assignee) => assignee.userId);
|
|
6540
|
-
if (!options.slackWaited && await hasSlackCard(db, item.id)) {
|
|
6541
|
-
await scheduleSlackCardPushes(db, item);
|
|
6542
|
-
return;
|
|
6543
|
-
}
|
|
6544
|
-
await withSpan("notification.inbox_item.push", "notification.inbox_item.push", {}, async () => {
|
|
6545
|
-
const pushed = await listInboxItemPushUserIds(db, item.id);
|
|
6546
|
-
await mapBounded(userIds.filter((userId) => !pushed.has(userId)), (userId) => deliverPush({
|
|
6547
|
-
config,
|
|
6548
|
-
db,
|
|
6549
|
-
item,
|
|
6550
|
-
kind: "inbox_item",
|
|
6551
|
-
record: (input) => claimInboxItemPush(db, input),
|
|
6552
|
-
url,
|
|
6553
|
-
userId
|
|
6554
|
-
}));
|
|
6555
|
-
}, { "app.inbox_item.id": item.id });
|
|
6556
|
-
}, "notification.inbox_item.push_failed", { "app.inbox_item.id": itemId });
|
|
6557
|
-
}
|
|
6558
|
-
/**
|
|
6559
|
-
* Return where the wake push of an item opens, or undefined when the
|
|
6560
|
-
* item does not push to this User: they must be a named assignee of an
|
|
6561
|
-
* action, or the starter of a reply notice. A Slack card shows nothing new
|
|
6562
|
-
* when a snooze wakes, so it does not stop this push.
|
|
6563
|
-
*/
|
|
6564
|
-
function wakePushUrl(item, userId) {
|
|
6565
|
-
if (item.status !== "open" || item.assignedToEveryone) return void 0;
|
|
6566
|
-
if (!item.assignees.some((assignee) => assignee.userId === userId)) return;
|
|
6567
|
-
if (item.kind === "action") return getDashboardInboxItemLink(item.id);
|
|
6568
|
-
const [conversationId] = item.conversationIds;
|
|
6569
|
-
if (item.dedupeKey.startsWith("reply:") && conversationId) return getDashboardConversationLink(conversationId);
|
|
6570
|
-
}
|
|
6571
|
-
/**
|
|
6572
|
-
* Push each snooze that a time or an Event woke to the User who snoozed
|
|
6573
|
-
* it. The caller passes only the snoozes that its own update woke, so one
|
|
6574
|
-
* wake pushes once. A Wake that the User picks does not come here. Push is
|
|
6575
|
-
* optional UI: a failure is logged, and nothing retries it.
|
|
6576
|
-
*/
|
|
6577
|
-
async function pushInboxSnoozeWakes(wakes) {
|
|
6578
|
-
const config = readWebPushConfig();
|
|
6579
|
-
if (!config) return;
|
|
6580
|
-
await mapBounded(wakes, (wake) => runBestEffort(async () => {
|
|
6581
|
-
const db = getDb();
|
|
6582
|
-
const item = await getInboxItem(db, wake.inboxItemId);
|
|
6583
|
-
const url = item && wakePushUrl(item, wake.userId);
|
|
6584
|
-
if (!item || !url) return;
|
|
6585
|
-
await withSpan("notification.inbox_item.push", "notification.inbox_item.push", {}, () => deliverPush({
|
|
6586
|
-
config,
|
|
6587
|
-
db,
|
|
6588
|
-
item,
|
|
6589
|
-
kind: "wake",
|
|
6590
|
-
record: async (input) => {
|
|
6591
|
-
await recordRepeatInboxItemPush(db, {
|
|
6592
|
-
...input,
|
|
6593
|
-
event: "wake"
|
|
6594
|
-
});
|
|
6595
|
-
return true;
|
|
6596
|
-
},
|
|
6597
|
-
url,
|
|
6598
|
-
userId: wake.userId
|
|
6599
|
-
}), { "app.inbox_item.id": item.id });
|
|
6600
|
-
}, "notification.inbox_item.push_failed", { "app.inbox_item.id": wake.inboxItemId }));
|
|
6601
|
-
}
|
|
6602
|
-
/**
|
|
6603
|
-
* Push the open items of a root Conversation and its child agents now,
|
|
6604
|
-
* after the root attaches to or detaches from its Slack thread. Those items
|
|
6605
|
-
* count as having waited in Slack with no answer, so they skip the rest of
|
|
6606
|
-
* the Slack card wait. A User that an item pushed to already gets no
|
|
6607
|
-
* second push.
|
|
6608
|
-
*/
|
|
6609
|
-
async function pushConversationInboxItemsNow(rootConversationId) {
|
|
6610
|
-
if (!readWebPushConfig()) return;
|
|
6611
|
-
await runBestEffort(async () => {
|
|
6612
|
-
const rows = await getDb().selectDistinct({ itemId: juniorInboxItemConversations.itemId }).from(juniorInboxItemConversations).innerJoin(juniorConversations, eq(juniorConversations.conversationId, juniorInboxItemConversations.conversationId)).innerJoin(juniorInboxItems, eq(juniorInboxItems.id, juniorInboxItemConversations.itemId)).where(and(eq(juniorInboxItems.status, "open"), or(eq(juniorConversations.conversationId, rootConversationId), eq(juniorConversations.rootConversationId, rootConversationId))));
|
|
6613
|
-
await mapBounded(rows, (row) => syncInboxItemPush(row.itemId, { slackWaited: true }));
|
|
6614
|
-
}, "notification.inbox_item.push_failed", { "app.conversation.id": rootConversationId });
|
|
6615
|
-
}
|
|
6616
|
-
/**
|
|
6617
|
-
* Push the item of one due timer to its User, after the item's Slack card
|
|
6618
|
-
* waited for them. A closed item, or a User no longer assigned, gets
|
|
6619
|
-
* nothing. An item whose User is not assigned goes in `unassigned`.
|
|
6620
|
-
*/
|
|
6621
|
-
async function pushAfterSlackCard(db, config, timerId, unassigned) {
|
|
6622
|
-
const [itemId, userId] = pushTimerSchema.parse(JSON.parse(timerId));
|
|
6623
|
-
await runBestEffort(async () => {
|
|
6624
|
-
const item = await getInboxItem(db, itemId);
|
|
6625
|
-
if (!item || item.status !== "open" || !pushesToAssignees(item)) return;
|
|
6626
|
-
if (!item.assignees.some((assignee) => assignee.userId === userId)) {
|
|
6627
|
-
unassigned.add(item.id);
|
|
6628
|
-
return;
|
|
6629
|
-
}
|
|
6630
|
-
const url = getDashboardInboxItemLink(item.id);
|
|
6631
|
-
if (!url) return;
|
|
6632
|
-
await withSpan("notification.inbox_item.push", "notification.inbox_item.push", {}, () => deliverPush({
|
|
6633
|
-
afterSlackCard: true,
|
|
6634
|
-
config,
|
|
6635
|
-
db,
|
|
6636
|
-
item,
|
|
6637
|
-
kind: "inbox_item",
|
|
6638
|
-
record: (input) => claimInboxItemPush(db, input),
|
|
6639
|
-
url,
|
|
6640
|
-
userId
|
|
6641
|
-
}), { "app.inbox_item.id": item.id });
|
|
6642
|
-
}, "notification.inbox_item.push_failed", { "app.inbox_item.id": itemId });
|
|
6643
|
-
}
|
|
6644
|
-
/**
|
|
6645
|
-
* Push the items whose Slack card waited long enough. A failed pass leaves
|
|
6646
|
-
* its claims to expire, so the next heartbeat retries them. A push that
|
|
6647
|
-
* fails is logged and not retried, the same as one that sends at once.
|
|
6648
|
-
* A User assigned again while the pass holds the claim of their timer
|
|
6649
|
-
* gets it again from the show, and the removal then drops it. So the pass
|
|
6650
|
-
* adds back the timers of each item with a User who was not assigned.
|
|
6651
|
-
*/
|
|
6652
|
-
async function runInboxItemPushTimers(db, nowMs) {
|
|
6653
|
-
const state = getStateAdapter();
|
|
6654
|
-
await state.connect();
|
|
6655
|
-
const timerIds = await updateTimerIndex(state, INBOX_ITEM_PUSH_TIMER_INDEX, {
|
|
6656
|
-
kind: "claim",
|
|
6657
|
-
nowMs
|
|
6658
|
-
});
|
|
6659
|
-
if (timerIds.length === 0) return;
|
|
6660
|
-
const config = readWebPushConfig();
|
|
6661
|
-
const unassigned = /* @__PURE__ */ new Set();
|
|
6662
|
-
if (config) await mapBounded(timerIds, (id) => pushAfterSlackCard(db, config, id, unassigned));
|
|
6663
|
-
for (const id of timerIds) await updateTimerIndex(state, INBOX_ITEM_PUSH_TIMER_INDEX, {
|
|
6664
|
-
id,
|
|
6665
|
-
kind: "remove"
|
|
6666
|
-
});
|
|
6667
|
-
for (const itemId of unassigned) await runBestEffort(async () => {
|
|
6668
|
-
const item = await getInboxItem(db, itemId);
|
|
6669
|
-
if (item?.status === "open" && pushesToAssignees(item) && await hasSlackCard(db, item.id)) await scheduleSlackCardPushes(db, item);
|
|
6670
|
-
}, "notification.inbox_item.push_failed", { "app.inbox_item.id": itemId });
|
|
6671
|
-
}
|
|
6672
|
-
// src/chat/todos/inbox-items.ts
|
|
6673
|
-
/**
|
|
6674
|
-
* A To-do for a person shows in that person's Inbox as an action item that
|
|
6675
|
-
* core owns, the way an Automation alert does. The To-do is the record; the
|
|
6676
|
-
* item follows it. Each To-do change syncs the items of its Conversation in
|
|
6677
|
-
* the same transaction, so the Inbox never shows a To-do that closed.
|
|
6678
|
-
*
|
|
6679
|
-
* The item is private and links no Conversation, so only its assignee sees
|
|
6680
|
-
* it: no other person, no agent, and no Slack thread. The Conversation owns
|
|
6681
|
-
* it, so it stacks under the Conversation's root and the Conversation's
|
|
6682
|
-
* tree waits on the person (`needs_you`). The shared status does not
|
|
6683
|
-
* change. An assignee who cannot see the
|
|
6684
|
-
* Conversation's content gets no item.
|
|
6685
|
-
*/
|
|
6686
|
-
/** The dedupe key of the Inbox item of one To-do. */
|
|
6687
|
-
function todoInboxItemKey(conversationId, todoId) {
|
|
6688
|
-
return `${TODO_INBOX_ITEM_KEY_PREFIX}${conversationId}:${todoId}`;
|
|
6689
|
-
}
|
|
6690
|
-
/** Why the item of a To-do that is still open, or that is gone, closed. */
|
|
6691
|
-
function closeReason(todo) {
|
|
6692
|
-
if (!todo) return "The To-do was removed.";
|
|
6693
|
-
if (todo.status === "done") return void 0;
|
|
6694
|
-
if (todo.status === "dropped") return "The To-do was dropped.";
|
|
6695
|
-
return "The To-do is no longer assigned to you.";
|
|
6696
|
-
}
|
|
6697
|
-
/**
|
|
6698
|
-
* Add, change, or close the Inbox items of one Conversation's To-dos, to
|
|
6699
|
-
* match the To-dos now. Each open To-do for a person who can see the
|
|
6700
|
-
* Conversation has one open item. Call it inside the transaction of each
|
|
6701
|
-
* To-do change, under the To-do lock. It writes nothing when the items are
|
|
6702
|
-
* already right. Return the ids of the open items that it added or changed,
|
|
6703
|
-
* so the caller can push them after the transaction commits.
|
|
6704
|
-
*/
|
|
6705
|
-
async function syncTodoInboxItems(db, args) {
|
|
6706
|
-
const { conversationId, nowMs } = args;
|
|
6707
|
-
const todos = await db.select({
|
|
6708
|
-
assigneeUserId: juniorTodos.assigneeUserId,
|
|
6709
|
-
changedByUserId: juniorTodos.changedByUserId,
|
|
6710
|
-
id: juniorTodos.id,
|
|
6711
|
-
notes: juniorTodos.notes,
|
|
6712
|
-
status: juniorTodos.status,
|
|
6713
|
-
title: juniorTodos.title
|
|
6714
|
-
}).from(juniorTodos).where(eq(juniorTodos.conversationId, conversationId));
|
|
6715
|
-
const openItems = await db.select({
|
|
6716
|
-
body: juniorInboxItems.body,
|
|
6717
|
-
dedupeKey: juniorInboxItems.dedupeKey,
|
|
6718
|
-
id: juniorInboxItems.id,
|
|
6719
|
-
title: juniorInboxItems.title
|
|
6720
|
-
}).from(juniorInboxItems).where(and(eq(juniorInboxItems.ownerKind, "conversation"), eq(juniorInboxItems.ownerId, conversationId), eq(juniorInboxItems.status, "open"), like(juniorInboxItems.dedupeKey, `${TODO_INBOX_ITEM_KEY_PREFIX}%`)));
|
|
6721
|
-
const assigneeOf = new Map(openItems.length === 0 ? [] : (await db.select({
|
|
6722
|
-
itemId: juniorInboxItemAssignees.itemId,
|
|
6723
|
-
userId: juniorInboxItemAssignees.userId
|
|
6724
|
-
}).from(juniorInboxItemAssignees).where(inArray(juniorInboxItemAssignees.itemId, openItems.map((item) => item.id)))).map((row) => [row.itemId, row.userId]));
|
|
6725
|
-
const itemByKey = new Map(openItems.map((item) => [item.dedupeKey, item]));
|
|
6726
|
-
const todoByKey = new Map(todos.map((todo) => [todoInboxItemKey(conversationId, todo.id), todo]));
|
|
6727
|
-
const people = [...new Set(todos.flatMap((todo) => isOpenTodoStatus(todo.status) && todo.assigneeUserId ? [todo.assigneeUserId] : []))];
|
|
6728
|
-
const canSee = /* @__PURE__ */ new Map();
|
|
6729
|
-
const accessRows = people.length > 0 ? await readConversationAccessRows(db, [conversationId]) : [];
|
|
6730
|
-
let tenant;
|
|
6731
|
-
const shown = [];
|
|
6732
|
-
for (const userId of people) {
|
|
6733
|
-
const [participantRoots, memberSpaces] = await Promise.all([conversationIdsWithParticipantUser(db, accessRows.flatMap((row) => [row.conversationId, ...row.storedRootConversationId ? [row.storedRootConversationId] : []]), userId), readPrivateSpaceMemberships(db, accessRows, userId)]);
|
|
6734
|
-
const access = conversationAccessFromRows(accessRows, participantRoots, memberSpaces).get(conversationId);
|
|
6735
|
-
canSee.set(userId, access?.canViewPrivateContent ?? false);
|
|
6736
|
-
tenant = access?.tenant;
|
|
6737
|
-
}
|
|
6738
|
-
for (const [key, todo] of todoByKey) {
|
|
6739
|
-
const item = itemByKey.get(key);
|
|
6740
|
-
const userId = isOpenTodoStatus(todo.status) && todo.assigneeUserId ? todo.assigneeUserId : void 0;
|
|
6741
|
-
if (!userId || !canSee.get(userId)) {
|
|
6742
|
-
if (item) await closeInboxItem(db, {
|
|
6743
|
-
id: item.id,
|
|
6744
|
-
nowMs,
|
|
6745
|
-
status: todo.status === "done" ? "done" : "dismissed",
|
|
6746
|
-
...todo.changedByUserId && !isOpenTodoStatus(todo.status) ? { closedByUserId: todo.changedByUserId } : void 0,
|
|
6747
|
-
reason: closeReason(todo)
|
|
6748
|
-
});
|
|
6749
|
-
continue;
|
|
6750
|
-
}
|
|
6751
|
-
const content = {
|
|
6752
|
-
assignedToEveryone: false,
|
|
6753
|
-
assigneeUserIds: [userId],
|
|
6754
|
-
body: todo.notes ?? "",
|
|
6755
|
-
conversationIds: [],
|
|
6756
|
-
kind: "action",
|
|
6757
|
-
title: todo.title,
|
|
6758
|
-
visibility: "private"
|
|
6759
|
-
};
|
|
6760
|
-
if (!item) {
|
|
6761
|
-
const inserted = await insertInboxItem(db, {
|
|
6762
|
-
...content,
|
|
6763
|
-
dedupeKey: key,
|
|
6764
|
-
nowMs,
|
|
6765
|
-
owner: {
|
|
6766
|
-
id: conversationId,
|
|
6767
|
-
kind: "conversation"
|
|
6768
|
-
},
|
|
6769
|
-
...tenant ? { tenant } : void 0
|
|
6770
|
-
});
|
|
6771
|
-
if (inserted) shown.push(inserted.id);
|
|
6772
|
-
} else if (item.title !== content.title || item.body !== content.body || assigneeOf.get(item.id) !== userId) {
|
|
6773
|
-
if (assigneeOf.get(item.id) !== userId) {
|
|
6774
|
-
await clearInboxItemDeliveries(db, [item.id], nowMs);
|
|
6775
|
-
await deleteInboxItemDeliveries(db, {
|
|
6776
|
-
itemId: item.id,
|
|
6777
|
-
userId
|
|
6778
|
-
});
|
|
6779
|
-
}
|
|
6780
|
-
await updateInboxItemContent(db, {
|
|
6781
|
-
...content,
|
|
6782
|
-
id: item.id,
|
|
6783
|
-
nowMs
|
|
6784
|
-
});
|
|
6785
|
-
shown.push(item.id);
|
|
6786
|
-
}
|
|
6787
|
-
}
|
|
6788
|
-
for (const item of openItems) {
|
|
6789
|
-
if (todoByKey.has(item.dedupeKey)) continue;
|
|
6790
|
-
await closeInboxItem(db, {
|
|
6791
|
-
id: item.id,
|
|
6792
|
-
nowMs,
|
|
6793
|
-
reason: closeReason(void 0),
|
|
6794
|
-
status: "dismissed"
|
|
6795
|
-
});
|
|
6796
|
-
}
|
|
6797
|
-
return shown;
|
|
6798
|
-
}
|
|
6799
|
-
// src/chat/todos/store.ts
|
|
6800
|
-
/**
|
|
6801
|
-
* Durable To-dos of a Conversation. The list's own agent changes them with
|
|
6802
|
-
* `updateTodos`; a person can change a status in the dashboard. A child
|
|
6803
|
-
* agent can close the To-dos assigned to it, and a read closes the rest
|
|
6804
|
-
* once the child's result has reached this Conversation. Each
|
|
6805
|
-
* change takes a new version from one global sequence, so the next Turn can
|
|
6806
|
-
* show the model only the changes that it has not seen.
|
|
6807
|
-
*/
|
|
6808
|
-
const TODOS_LOCK_PREFIX = "junior:todos";
|
|
6809
|
-
function nextVersion() {
|
|
6810
|
-
return sql`nextval(${juniorTodoVersionSeq.seqName}::regclass)`;
|
|
6811
|
-
}
|
|
6812
|
-
function assigneeColumns(assignee) {
|
|
6813
|
-
return "userId" in assignee ? {
|
|
6814
|
-
assigneeConversationId: null,
|
|
6815
|
-
assigneeUserId: assignee.userId
|
|
6816
|
-
} : {
|
|
6817
|
-
assigneeConversationId: assignee.conversationId,
|
|
6818
|
-
assigneeUserId: null
|
|
6819
|
-
};
|
|
6820
|
-
}
|
|
6821
|
-
function requireKnownIds(rows, ids) {
|
|
6822
|
-
const unknown = ids.filter((id) => !rows.has(id));
|
|
6823
|
-
if (unknown.length > 0) throw new ToolInputError(`No To-do has id ${unknown.map(todoRef).join(", ")}. Call updateTodos with no changes to list the open To-dos.`);
|
|
6824
|
-
}
|
|
6825
|
-
/** Check that each id is known and changes once. */
|
|
6826
|
-
function validateChange(rows, change) {
|
|
6827
|
-
const touched = [...change.update.map((todo) => todo.id), ...change.remove];
|
|
6828
|
-
requireKnownIds(rows, touched);
|
|
6829
|
-
if (new Set(touched).size !== touched.length) throw new ToolInputError("Change each To-do once per call: an id is in more than one update or remove.");
|
|
6830
|
-
}
|
|
6831
|
-
async function withTodosLock(executor, conversationId, callback) {
|
|
6832
|
-
let itemIds = [];
|
|
6833
|
-
const result = await executor.db().transaction(async (tx) => {
|
|
6834
|
-
await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${`${TODOS_LOCK_PREFIX}:${conversationId}`}))`);
|
|
6835
|
-
return await callback(tx, async (nowMs) => {
|
|
6836
|
-
itemIds = await syncTodoInboxItems(tx, {
|
|
6837
|
-
conversationId,
|
|
6838
|
-
nowMs
|
|
6839
|
-
});
|
|
6840
|
-
});
|
|
6841
|
-
});
|
|
6842
|
-
await mapBounded(itemIds, (itemId) => syncInboxItemPush(itemId));
|
|
6843
|
-
return result;
|
|
6844
|
-
}
|
|
6845
|
-
/**
|
|
6846
|
-
* Apply one batch of changes from the list's own agent. Return the To-dos it
|
|
6847
|
-
* added or updated, and the To-dos whose status a person set last and the
|
|
6848
|
-
* change replaced, as they were before it. Throws `ToolInputError` for an
|
|
6849
|
-
* unknown id or an id that changes twice.
|
|
6850
|
-
*/
|
|
6851
|
-
async function changeTodos(executor, args) {
|
|
6852
|
-
const { change, conversationId } = args;
|
|
6853
|
-
const now = new Date(args.nowMs);
|
|
6854
|
-
return await withTodosLock(executor, conversationId, async (db, sync) => {
|
|
6855
|
-
const rows = new Map((await db.select().from(juniorTodos).where(eq(juniorTodos.conversationId, conversationId))).map((row) => [row.id, row]));
|
|
6856
|
-
validateChange(rows, change);
|
|
6857
|
-
const replacedIds = change.update.filter((update) => {
|
|
6858
|
-
const row = rows.get(update.id);
|
|
6859
|
-
return row.changedByUserId !== null && update.status !== void 0 && update.status !== row.status;
|
|
6860
|
-
}).map((update) => update.id);
|
|
6861
|
-
const replacedPersonChanges = replacedIds.length > 0 ? (await readTodos(db, conversationId)).filter((todo) => replacedIds.includes(todo.id)) : [];
|
|
6862
|
-
if (change.remove.length > 0) await db.delete(juniorTodos).where(and(eq(juniorTodos.conversationId, conversationId), inArray(juniorTodos.id, change.remove)));
|
|
6863
|
-
const changedIds = [];
|
|
6864
|
-
for (const update of change.update) {
|
|
6865
|
-
await db.update(juniorTodos).set({
|
|
6866
|
-
...update.title !== void 0 ? { title: update.title } : void 0,
|
|
6867
|
-
...update.notes !== void 0 ? { notes: update.notes } : void 0,
|
|
6868
|
-
...update.status ? { status: update.status } : void 0,
|
|
6869
|
-
...update.assignee ? assigneeColumns(update.assignee) : void 0,
|
|
6870
|
-
changedByUserId: null,
|
|
6871
|
-
changedByConversationId: null,
|
|
6872
|
-
updatedAt: now,
|
|
6873
|
-
version: nextVersion()
|
|
6874
|
-
}).where(and(eq(juniorTodos.conversationId, conversationId), eq(juniorTodos.id, update.id)));
|
|
6875
|
-
changedIds.push(update.id);
|
|
6876
|
-
}
|
|
6877
|
-
for (const todo of change.add) {
|
|
6878
|
-
const [inserted] = await db.insert(juniorTodos).values({
|
|
6879
|
-
conversationId,
|
|
6880
|
-
id: nextVersion(),
|
|
6881
|
-
title: todo.title,
|
|
6882
|
-
notes: todo.notes ?? null,
|
|
6883
|
-
status: todo.status,
|
|
6884
|
-
...assigneeColumns(todo.assignee),
|
|
6885
|
-
version: nextVersion(),
|
|
6886
|
-
createdAt: now,
|
|
6887
|
-
updatedAt: now
|
|
6888
|
-
}).returning({ id: juniorTodos.id });
|
|
6889
|
-
changedIds.push(inserted.id);
|
|
6890
|
-
}
|
|
6891
|
-
await sync(args.nowMs);
|
|
6892
|
-
await touchConversationDetail(db, [conversationId]);
|
|
6893
|
-
const todos = await readTodos(db, conversationId);
|
|
6894
|
-
return {
|
|
6895
|
-
todos: changedIds.flatMap((id) => todos.find((todo) => todo.id === id) ?? []),
|
|
6896
|
-
replacedPersonChanges
|
|
6897
|
-
};
|
|
6898
|
-
});
|
|
6899
|
-
}
|
|
6900
|
-
/**
|
|
6901
|
-
* Set the status of one To-do for a person, and return the To-do. Returns
|
|
6902
|
-
* undefined when the Conversation has no such To-do. With `assignedOnly`,
|
|
6903
|
-
* the To-do must still be open and assigned to the person when the change
|
|
6904
|
-
* applies under the lock, so Done on a stale Inbox item cannot close a
|
|
6905
|
-
* To-do that the agent gave to someone else.
|
|
6906
|
-
*/
|
|
6907
|
-
async function setTodoStatusByUser(executor, args) {
|
|
6908
|
-
const { conversationId } = args;
|
|
6909
|
-
return await withTodosLock(executor, conversationId, async (db, sync) => {
|
|
6910
|
-
if ((await db.update(juniorTodos).set({
|
|
6911
|
-
status: args.status,
|
|
6912
|
-
changedByUserId: args.userId,
|
|
6913
|
-
changedByConversationId: null,
|
|
6914
|
-
updatedAt: new Date(args.nowMs),
|
|
6915
|
-
version: nextVersion()
|
|
6916
|
-
}).where(and(eq(juniorTodos.conversationId, conversationId), eq(juniorTodos.id, args.id), args.assignedOnly ? and(eq(juniorTodos.assigneeUserId, args.userId), inArray(juniorTodos.status, [...OPEN_TODO_STATUSES])) : void 0)).returning({ id: juniorTodos.id })).length === 0) return void 0;
|
|
6917
|
-
await sync(args.nowMs);
|
|
6918
|
-
await touchConversationDetail(db, [conversationId]);
|
|
6919
|
-
return (await readTodos(db, conversationId)).find((todo) => todo.id === args.id);
|
|
6920
|
-
});
|
|
6921
|
-
}
|
|
6922
|
-
/**
|
|
6923
|
-
* Close To-dos of one Conversation that are assigned to one of its child
|
|
6924
|
-
* agents, for that child. Each change names the child, so the parent sees it
|
|
6925
|
-
* in its next `<todo-delta>`. Returns the changed To-dos.
|
|
6926
|
-
*/
|
|
6927
|
-
async function closeChildTodos(db, args) {
|
|
6928
|
-
const ids = [...args.statuses.keys()];
|
|
6929
|
-
if (ids.length === 0) return [];
|
|
6930
|
-
for (const [id, status] of args.statuses) await db.update(juniorTodos).set({
|
|
6931
|
-
status,
|
|
6932
|
-
changedByUserId: null,
|
|
6933
|
-
changedByConversationId: args.childConversationId,
|
|
6934
|
-
updatedAt: new Date(args.nowMs),
|
|
6935
|
-
version: nextVersion()
|
|
6936
|
-
}).where(and(eq(juniorTodos.conversationId, args.conversationId), eq(juniorTodos.id, id)));
|
|
6937
|
-
await touchConversationDetail(db, [args.conversationId]);
|
|
6938
|
-
return (await readTodos(db, args.conversationId)).filter((todo) => ids.includes(todo.id));
|
|
6939
|
-
}
|
|
6940
|
-
/**
|
|
6941
|
-
* List the ids of To-dos assigned to one Conversation in other lists. Only a
|
|
6942
|
-
* parent can assign a To-do to a Conversation, so they are its parent's.
|
|
6943
|
-
*/
|
|
6944
|
-
async function listParentTodoIds(executor, conversationId) {
|
|
6945
|
-
const rows = await executor.db().select({ id: juniorTodos.id }).from(juniorTodos).where(and(eq(juniorTodos.assigneeConversationId, conversationId), ne(juniorTodos.conversationId, conversationId)));
|
|
6946
|
-
return new Set(rows.map((row) => row.id));
|
|
6947
|
-
}
|
|
6948
|
-
/**
|
|
6949
|
-
* Close To-dos of the parent that are assigned to the calling child agent.
|
|
6950
|
-
* Throws `ToolInputError` for an id that the parent did not assign to it.
|
|
6951
|
-
*/
|
|
6952
|
-
async function closeTodosForChild(executor, args) {
|
|
6953
|
-
const ids = [...args.statuses.keys()];
|
|
6954
|
-
const assigned = and(inArray(juniorTodos.id, ids), eq(juniorTodos.assigneeConversationId, args.childConversationId), ne(juniorTodos.conversationId, args.childConversationId));
|
|
6955
|
-
const [owner] = await executor.db().selectDistinct({ conversationId: juniorTodos.conversationId }).from(juniorTodos).where(assigned);
|
|
6956
|
-
if (!owner) return rejectUnassigned(ids);
|
|
6957
|
-
return await withTodosLock(executor, owner.conversationId, async (db) => {
|
|
6958
|
-
const rows = await db.select({ id: juniorTodos.id }).from(juniorTodos).where(and(eq(juniorTodos.conversationId, owner.conversationId), assigned));
|
|
6959
|
-
const found = new Set(rows.map((row) => row.id));
|
|
6960
|
-
const others = ids.filter((id) => !found.has(id));
|
|
6961
|
-
if (others.length > 0) return rejectUnassigned(others);
|
|
6962
|
-
return await closeChildTodos(db, {
|
|
6963
|
-
childConversationId: args.childConversationId,
|
|
6964
|
-
conversationId: owner.conversationId,
|
|
6965
|
-
nowMs: args.nowMs,
|
|
6966
|
-
statuses: args.statuses
|
|
6967
|
-
});
|
|
6968
|
-
});
|
|
6969
|
-
}
|
|
6970
|
-
function rejectUnassigned(ids) {
|
|
6971
|
-
throw new ToolInputError(`Your parent did not assign ${ids.map(todoRef).join(", ")} to you. You can only set your own To-dos of the parent to done or dropped.`);
|
|
6972
|
-
}
|
|
6973
|
-
/**
|
|
6974
|
-
* Read the child results that wait in a Conversation's mailbox. A done
|
|
6975
|
-
* result closes the child's To-dos as done, and a stopped one drops them.
|
|
6976
|
-
* A Turn reads its To-dos when it builds its prompt, before it takes its
|
|
6977
|
-
* input out of the mailbox, so a read sees every result there.
|
|
6978
|
-
*/
|
|
6979
|
-
async function readReceivedChildResults(conversationId) {
|
|
6980
|
-
return ((await getConversationWorkState({ conversationId }))?.execution.pendingMessages ?? []).flatMap((message) => {
|
|
6981
|
-
const sender = readInboundMessageSender(message);
|
|
6982
|
-
const metadata = message.input.metadata;
|
|
6983
|
-
const result = isEventMailboxMetadata(metadata) ? metadata.event.status : void 0;
|
|
6984
|
-
const status = result === "done" ? "done" : result === "stopped" ? "dropped" : void 0;
|
|
6985
|
-
return sender && status ? [{
|
|
6986
|
-
atMs: message.createdAtMs,
|
|
6987
|
-
childConversationId: sender.conversationId,
|
|
6988
|
-
status
|
|
6989
|
-
}] : [];
|
|
6990
|
-
});
|
|
6991
|
-
}
|
|
6992
|
-
/**
|
|
6993
|
-
* Close the open To-dos of a Conversation whose child's result reached it
|
|
6994
|
-
* after the To-do last changed: done when the child completed, dropped when
|
|
6995
|
-
* it was stopped. The received results decide it, so a repeat read changes
|
|
6996
|
-
* nothing.
|
|
6997
|
-
*/
|
|
6998
|
-
async function settleChildTodos(executor, conversationId, todos) {
|
|
6999
|
-
const assigned = todos.filter((todo) => todo.assignee.kind === "agent" && isOpenTodoStatus(todo.status));
|
|
7000
|
-
if (assigned.length === 0) return false;
|
|
7001
|
-
const results = await readReceivedChildResults(conversationId);
|
|
7002
|
-
if (results.length === 0) return false;
|
|
7003
|
-
const byChild = /* @__PURE__ */ new Map();
|
|
7004
|
-
for (const todo of assigned) {
|
|
7005
|
-
if (todo.assignee.kind !== "agent") continue;
|
|
7006
|
-
const childId = todo.assignee.conversationId;
|
|
7007
|
-
const latest = results.filter((result) => result.childConversationId === childId && result.atMs > todo.updatedAtMs).reduce((newest, result) => !newest || result.atMs >= newest.atMs ? result : newest, void 0);
|
|
7008
|
-
if (!latest) continue;
|
|
7009
|
-
const statuses = byChild.get(childId) ?? /* @__PURE__ */ new Map();
|
|
7010
|
-
statuses.set(todo.id, latest.status);
|
|
7011
|
-
byChild.set(childId, statuses);
|
|
7012
|
-
}
|
|
7013
|
-
if (byChild.size === 0) return false;
|
|
7014
|
-
const nowMs = Date.now();
|
|
7015
|
-
await withTodosLock(executor, conversationId, async (db) => {
|
|
7016
|
-
const current = new Map((await readTodos(db, conversationId)).map((todo) => [todo.id, todo.version]));
|
|
7017
|
-
for (const [childConversationId, statuses] of byChild) {
|
|
7018
|
-
const unchanged = new Map([...statuses].filter(([id]) => current.get(id) === todos.find((todo) => todo.id === id)?.version));
|
|
7019
|
-
await closeChildTodos(db, {
|
|
7020
|
-
childConversationId,
|
|
7021
|
-
conversationId,
|
|
7022
|
-
nowMs,
|
|
7023
|
-
statuses: unchanged
|
|
7024
|
-
});
|
|
7025
|
-
}
|
|
7026
|
-
});
|
|
7027
|
-
return true;
|
|
7028
|
-
}
|
|
7029
|
-
/**
|
|
7030
|
-
* List every To-do of one Conversation, oldest first, with assignees
|
|
7031
|
-
* resolved. A To-do assigned to a child agent that has finished or stopped
|
|
7032
|
-
* since it last changed is closed first.
|
|
7033
|
-
*/
|
|
7034
|
-
async function listTodos(executor, conversationId) {
|
|
7035
|
-
const todos = await readTodos(executor.db(), conversationId);
|
|
7036
|
-
return await settleChildTodos(executor, conversationId, todos) ? await readTodos(executor.db(), conversationId) : todos;
|
|
7037
|
-
}
|
|
7038
|
-
async function readTodos(db, conversationId) {
|
|
7039
|
-
const assignedUser = alias(juniorUsers, "assigned_user");
|
|
7040
|
-
const changedByUser = alias(juniorUsers, "changed_by_user");
|
|
7041
|
-
const changedByAgent = alias(juniorAgentBindings, "changed_by_agent");
|
|
7042
|
-
return (await db.select({
|
|
7043
|
-
todo: juniorTodos,
|
|
7044
|
-
agentName: juniorAgentBindings.name,
|
|
7045
|
-
assignedUserEmail: assignedUser.primaryEmail,
|
|
7046
|
-
assignedUserName: assignedUser.displayName,
|
|
7047
|
-
changedByEmail: changedByUser.primaryEmail,
|
|
7048
|
-
changedByName: changedByUser.displayName,
|
|
7049
|
-
changedByAgentName: changedByAgent.name
|
|
7050
|
-
}).from(juniorTodos).leftJoin(juniorAgentBindings, and(eq(juniorAgentBindings.parentConversationId, conversationId), eq(juniorAgentBindings.childConversationId, juniorTodos.assigneeConversationId))).leftJoin(assignedUser, eq(assignedUser.id, juniorTodos.assigneeUserId)).leftJoin(changedByUser, eq(changedByUser.id, juniorTodos.changedByUserId)).leftJoin(changedByAgent, and(eq(changedByAgent.parentConversationId, conversationId), eq(changedByAgent.childConversationId, juniorTodos.changedByConversationId))).where(eq(juniorTodos.conversationId, conversationId)).orderBy(asc(juniorTodos.id))).map(({ todo, agentName, assignedUserEmail, assignedUserName, changedByEmail, changedByName, changedByAgentName }) => ({
|
|
7051
|
-
id: todo.id,
|
|
7052
|
-
title: todo.title,
|
|
7053
|
-
...todo.notes ? { notes: todo.notes } : void 0,
|
|
7054
|
-
status: todo.status,
|
|
7055
|
-
assignee: todo.assigneeUserId ? {
|
|
7056
|
-
kind: "user",
|
|
7057
|
-
userId: todo.assigneeUserId,
|
|
7058
|
-
email: assignedUserEmail ?? "",
|
|
7059
|
-
...assignedUserName ? { name: assignedUserName } : void 0
|
|
7060
|
-
} : (todo.assigneeConversationId ?? conversationId) === conversationId ? { kind: "self" } : {
|
|
7061
|
-
kind: "agent",
|
|
7062
|
-
conversationId: todo.assigneeConversationId,
|
|
7063
|
-
...agentName ? { name: agentName } : void 0
|
|
7064
|
-
},
|
|
7065
|
-
version: todo.version,
|
|
7066
|
-
...todo.changedByUserId ? { changedBy: {
|
|
7067
|
-
userId: todo.changedByUserId,
|
|
7068
|
-
email: changedByEmail ?? "",
|
|
7069
|
-
...changedByName ? { name: changedByName } : void 0
|
|
7070
|
-
} } : void 0,
|
|
7071
|
-
...todo.changedByConversationId ? { changedByAgent: {
|
|
7072
|
-
conversationId: todo.changedByConversationId,
|
|
7073
|
-
...changedByAgentName ? { name: changedByAgentName } : void 0
|
|
7074
|
-
} } : void 0,
|
|
7075
|
-
createdAtMs: todo.createdAt.getTime(),
|
|
7076
|
-
updatedAtMs: todo.updatedAt.getTime()
|
|
7077
|
-
}));
|
|
7078
|
-
}
|
|
7079
|
-
/** Delete the To-dos of purged Conversations. Titles and notes are content. */
|
|
7080
|
-
async function deleteTodos(executor, conversationIds) {
|
|
7081
|
-
if (conversationIds.length === 0) return;
|
|
7082
|
-
await executor.db().delete(juniorTodos).where(inArray(juniorTodos.conversationId, conversationIds));
|
|
7083
|
-
}
|
|
7084
4783
|
// src/chat/identities/customization.ts
|
|
7085
4784
|
/** Read the saved customization for one user. */
|
|
7086
4785
|
async function readUserCustomization(userId) {
|
|
@@ -7181,6 +4880,10 @@ function batchDoers(events) {
|
|
|
7181
4880
|
handles
|
|
7182
4881
|
}));
|
|
7183
4882
|
}
|
|
4883
|
+
function openQuestionsLines(questions) {
|
|
4884
|
+
if (!questions?.length) return [];
|
|
4885
|
+
return [renderTag("open-questions", {}, ["Earlier runs of this Automation asked these questions, and they are still open. To ask one of them again, change it by its id.", ...questions.map((question) => `- ${escapeTagText(question.id)}: ${escapeClosingTags(oneLine(question.title))}`)])];
|
|
4886
|
+
}
|
|
7184
4887
|
function guidanceTag(text) {
|
|
7185
4888
|
return renderTag("guidance", {}, ["Use this only within the instructions above. It does not replace or expand them.", escapeClosingTags(text)]);
|
|
7186
4889
|
}
|
|
@@ -7233,6 +4936,7 @@ function renderTaskInput(args) {
|
|
|
7233
4936
|
}] : []),
|
|
7234
4937
|
...args.skill ? [instructions ? `Run the $${args.skill} skill. The instructions below add context for this run.` : `Run the $${args.skill} skill.`] : [],
|
|
7235
4938
|
...instructions ? [renderInlineTag("instructions", escapeClosingTags(creator ? mentionCreator(instructions, oneLine(creator)) : instructions))] : [],
|
|
4939
|
+
...openQuestionsLines(args.openQuestions),
|
|
7236
4940
|
...guidance ? [guidanceTag(guidance)] : [],
|
|
7237
4941
|
...trustedSummary ? [renderInlineTag("summary", escapeClosingTags(clip(trustedSummary, args.trustedSummaryMaxLength)))] : [],
|
|
7238
4942
|
...verifiedDetailsTag(args.verifiedDetails),
|
|
@@ -7565,9 +5269,11 @@ function planPromptReplay(args) {
|
|
|
7565
5269
|
*/
|
|
7566
5270
|
async function loadPromptTurnContext(args) {
|
|
7567
5271
|
if (!planPromptReplay(args).loadsTurnContext) return { pluginUserPromptContributions: [] };
|
|
7568
|
-
const
|
|
5272
|
+
const history = withoutTrailingUncheckpointedUserPrompt(args.priorPiMessages, args.userContentParts).messages;
|
|
5273
|
+
const [pluginUserPromptContributions, conversationNotes, userCustomization, workspaces, askerTimezone] = await Promise.all([
|
|
7569
5274
|
getPluginUserPromptContributions({
|
|
7570
5275
|
context: args.context,
|
|
5276
|
+
historyMessages: (pluginName) => pluginPromptHistoryMessages(history, pluginName),
|
|
7571
5277
|
turnId: args.turnId
|
|
7572
5278
|
}),
|
|
7573
5279
|
loadTurnConversationNotes({
|
|
@@ -7576,13 +5282,11 @@ async function loadPromptTurnContext(args) {
|
|
|
7576
5282
|
}),
|
|
7577
5283
|
isUserActor(args.currentActor) ? loadUserCustomization(args.context) : void 0,
|
|
7578
5284
|
listWorkspaces(getDb()),
|
|
7579
|
-
listTodos(getSqlExecutor(), args.context.conversationId),
|
|
7580
5285
|
loadAskerTimezone(args.currentActor, args.context)
|
|
7581
5286
|
]);
|
|
7582
5287
|
return {
|
|
7583
5288
|
askerTimezone,
|
|
7584
5289
|
conversationNotes,
|
|
7585
|
-
todos,
|
|
7586
5290
|
pluginUserPromptContributions,
|
|
7587
5291
|
userCustomization,
|
|
7588
5292
|
workspaces
|
|
@@ -7604,7 +5308,7 @@ async function assemblePrompt(args) {
|
|
|
7604
5308
|
const needsBootstrapContextForPrompt = shouldPromptAgent && !replayedPrompt && !hasRuntimeTurnContext(promptHistoryMessages);
|
|
7605
5309
|
const platform = promptPlatform(args.run, args.promptMode);
|
|
7606
5310
|
const baseInstructions = await buildDeploymentSystemPrompt(platform, args.promptMode);
|
|
7607
|
-
const { askerTimezone, conversationNotes,
|
|
5311
|
+
const { askerTimezone, conversationNotes, pluginUserPromptContributions, userCustomization, workspaces } = args.turnContext;
|
|
7608
5312
|
const disabledTools = loadsTurnContext ? args.disabledTools : [];
|
|
7609
5313
|
const sectionsMessage = loadsTurnContext ? systemSectionsUpdate(promptHistoryMessages, buildCapabilitySections({
|
|
7610
5314
|
availableSkills: args.availableSkills,
|
|
@@ -7618,7 +5322,6 @@ async function assemblePrompt(args) {
|
|
|
7618
5322
|
conversationNotes,
|
|
7619
5323
|
disabledTools,
|
|
7620
5324
|
includeSessionContext: needsBootstrapContextForPrompt,
|
|
7621
|
-
todos: todos ? renderTodoDelta(todos, latestSeenTodosVersion(promptHistoryMessages)) ?? renderTodosReview(todos, promptHistoryMessages) : null,
|
|
7622
5325
|
pluginPromptContributions: pluginUserPromptContributions,
|
|
7623
5326
|
...args.sender ? { turnInput: args.sender } : void 0,
|
|
7624
5327
|
userCustomization,
|
|
@@ -7722,12 +5425,13 @@ function typedAnswerText(request, answer) {
|
|
|
7722
5425
|
return [...request.fields.flatMap((field) => field.kind === "text" ? normalized.values[field.id] ?? [] : []), ...normalized.other ? [normalized.other] : []].join("\n\n");
|
|
7723
5426
|
}
|
|
7724
5427
|
function renderInboxItemAnswer(item) {
|
|
7725
|
-
|
|
7726
|
-
|
|
7727
|
-
const
|
|
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);
|
|
7728
5432
|
return {
|
|
7729
5433
|
kind: "runtime",
|
|
7730
|
-
text: renderTag("inbox-item-answer", { id: item.id }, [`Question: ${question.length > QUESTION_MAX_LENGTH ? `${question.slice(0, 511)}…` : question}`, formatUserInputAnswer(
|
|
5434
|
+
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)),
|
|
7731
5435
|
...requestText ? { requestText } : void 0
|
|
7732
5436
|
};
|
|
7733
5437
|
}
|
|
@@ -8670,16 +6374,6 @@ function eventTaskFacts(subscription, event, people = [], doneBy, author = { sta
|
|
|
8670
6374
|
...doneBy ? { doneBy } : void 0
|
|
8671
6375
|
};
|
|
8672
6376
|
}
|
|
8673
|
-
/** Whether mailbox metadata is a plain event wake. */
|
|
8674
|
-
function isEventMailboxMetadata(value) {
|
|
8675
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
8676
|
-
const record = value;
|
|
8677
|
-
if (record["kind"] !== "event") return false;
|
|
8678
|
-
const event = record["event"];
|
|
8679
|
-
if (!event || typeof event !== "object" || Array.isArray(event)) return false;
|
|
8680
|
-
const fields = event;
|
|
8681
|
-
return typeof fields["eventKey"] === "string" && typeof fields["eventType"] === "string" && typeof fields["namespace"] === "string" && typeof fields["identifier"] === "string" && (fields["subscriptionId"] === void 0 || typeof fields["subscriptionId"] === "string") && (fields["objectType"] === void 0 || objectTypeSchema.safeParse(fields["objectType"]).success) && (fields["trustedSummary"] === void 0 || typeof fields["trustedSummary"] === "string") && (fields["status"] === void 0 || typeof fields["status"] === "string");
|
|
8682
|
-
}
|
|
8683
6377
|
/**
|
|
8684
6378
|
* Return the timer creator subject when every event in the batch carries a
|
|
8685
6379
|
* valid subject for its own Watch and the same user.
|
|
@@ -8852,10 +6546,6 @@ function createEventInboundMessage(input) {
|
|
|
8852
6546
|
}
|
|
8853
6547
|
};
|
|
8854
6548
|
}
|
|
8855
|
-
/** Key of the note that a Watch adds for an Event it received quietly. */
|
|
8856
|
-
function quietEventNoteKey(watchId, eventKey) {
|
|
8857
|
-
return `quiet_event:${watchId}:${eventKey}`;
|
|
8858
|
-
}
|
|
8859
6549
|
/**
|
|
8860
6550
|
* Deliver a Quiet Event as a Conversation note. It starts no Turn, so the
|
|
8861
6551
|
* automated-turn limit does not apply. The next Turn sees the note as
|
|
@@ -8867,7 +6557,7 @@ async function addQuietEventNote(args) {
|
|
|
8867
6557
|
await addConversationNote({
|
|
8868
6558
|
conversationId: subscription.conversationId,
|
|
8869
6559
|
createdAtMs: event.occurredAtMs,
|
|
8870
|
-
key:
|
|
6560
|
+
key: `quiet_event:${subscription.id}:${event.eventKey}`,
|
|
8871
6561
|
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}`
|
|
8872
6562
|
});
|
|
8873
6563
|
}
|
|
@@ -8900,7 +6590,7 @@ async function enqueueEventNotification(args) {
|
|
|
8900
6590
|
state: args.state
|
|
8901
6591
|
});
|
|
8902
6592
|
}
|
|
8903
|
-
// src/chat/
|
|
6593
|
+
// src/chat/child-agents/fork-history.ts
|
|
8904
6594
|
/** Instructions that a fork child reads with its first task. */
|
|
8905
6595
|
const FORK_INSTRUCTIONS = "You are a fork of your parent agent. The messages before your first parent task are copied from the parent's conversation so you have its context. They are not your job: your job is the parent task below. Sandbox files, approvals, and credentials of the parent were not copied, and your sandbox is separate. Verify files in your own sandbox before you use them.";
|
|
8906
6596
|
/**
|
|
@@ -8972,20 +6662,21 @@ function notInheritedByForkChild() {
|
|
|
8972
6662
|
limit 1
|
|
8973
6663
|
), false)`;
|
|
8974
6664
|
}
|
|
8975
|
-
// src/chat/
|
|
8976
|
-
const
|
|
6665
|
+
// src/chat/child-agents/ids.ts
|
|
6666
|
+
const LOCK_PREFIX = "junior:child_agents";
|
|
8977
6667
|
/**
|
|
8978
6668
|
* Return the SQL lock that one parent Conversation takes to start, message,
|
|
8979
6669
|
* or stop its child agents.
|
|
8980
6670
|
*/
|
|
8981
6671
|
function getChildAgentLockName(parentConversationId) {
|
|
8982
|
-
return `${
|
|
6672
|
+
return `${LOCK_PREFIX}:${parentConversationId}`;
|
|
8983
6673
|
}
|
|
8984
6674
|
function stableId(prefix, ...parts) {
|
|
8985
6675
|
return `${prefix}:${createHash("sha256").update(parts.join("\0")).digest("hex").slice(0, 32)}`;
|
|
8986
6676
|
}
|
|
6677
|
+
const ID_PREFIX = "agent-invocation";
|
|
8987
6678
|
function taskKey(parentConversationId, idempotencyKey) {
|
|
8988
|
-
return stableId(
|
|
6679
|
+
return stableId(ID_PREFIX, parentConversationId, idempotencyKey);
|
|
8989
6680
|
}
|
|
8990
6681
|
/**
|
|
8991
6682
|
* Return the stable child identity for one spawn, with a name or without.
|
|
@@ -8996,7 +6687,11 @@ function getSpawnedChildConversationId(parentConversationId, idempotencyKey) {
|
|
|
8996
6687
|
}
|
|
8997
6688
|
/** Return the mailbox identity of one parent message. */
|
|
8998
6689
|
function getParentMessageId(parentConversationId, idempotencyKey) {
|
|
8999
|
-
return
|
|
6690
|
+
return `${ID_PREFIX}:${taskKey(parentConversationId, idempotencyKey)}:input`;
|
|
6691
|
+
}
|
|
6692
|
+
/** Return the parent mailbox identity of one message from a child agent. */
|
|
6693
|
+
function getAgentMessageId(childConversationId, messageKey) {
|
|
6694
|
+
return `${ID_PREFIX}:${childConversationId}:message:${messageKey}`;
|
|
9000
6695
|
}
|
|
9001
6696
|
const REPLY_MESSAGE_PREFIX = "agent-reply:";
|
|
9002
6697
|
/** Return the parent mailbox identity of one child agent Turn's result. */
|
|
@@ -9008,10 +6703,6 @@ const PERSON_STOP_TURN_PREFIX = "stopped:";
|
|
|
9008
6703
|
function getPersonStopTurnId(stoppedAtMs) {
|
|
9009
6704
|
return `${PERSON_STOP_TURN_PREFIX}${stoppedAtMs}`;
|
|
9010
6705
|
}
|
|
9011
|
-
/** Return whether a sender Turn id names a person's stop, not a Turn. */
|
|
9012
|
-
function isPersonStopTurnId(turnId) {
|
|
9013
|
-
return turnId.startsWith(PERSON_STOP_TURN_PREFIX);
|
|
9014
|
-
}
|
|
9015
6706
|
// src/chat/conversations/agent-config.ts
|
|
9016
6707
|
/**
|
|
9017
6708
|
* The agent settings that every Turn of one Conversation keeps, for any
|
|
@@ -9031,7 +6722,7 @@ async function readAgentConfig(conversationId) {
|
|
|
9031
6722
|
const [row] = await getSqlExecutor().db().select({ agentConfig: juniorConversations.agentConfig }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId));
|
|
9032
6723
|
return row?.agentConfig ? agentConfigSchema.parse(row.agentConfig) : void 0;
|
|
9033
6724
|
}
|
|
9034
|
-
// src/chat/
|
|
6725
|
+
// src/chat/child-agents/parent-message.ts
|
|
9035
6726
|
/**
|
|
9036
6727
|
* Return the author id of every parent message from one parent. It matches
|
|
9037
6728
|
* no other input, so a parent message never shares a Turn with another
|
|
@@ -9450,4 +7141,4 @@ async function resolveMailboxTurnWork(context) {
|
|
|
9450
7141
|
turnId
|
|
9451
7142
|
} : void 0;
|
|
9452
7143
|
}
|
|
9453
|
-
export {
|
|
7144
|
+
export { getTurnUserSlackMessageTs as $, calculateContextCompactionTargetTokens as $n, CODEMODE_TOOL_NAME as $r, setWorkspaceSnapshotBuild as $t, createEventInboundMessage as A, recordSubscribedReplyRoute as An, TURN_LIMIT_WRAP_UP_MESSAGE as Ar, turnRequestText as At, resolveEventAuthor as B, getConversationMessageSlackTs as Bn, requireTurnFailureEventId as Br, deleteWorkspace as Bt, getChildAgentLockName as C, recordAttachmentsDelivered as Cn, listTurnSummaries as Cr, savedInputInstruction as Ct, notInheritedByForkChild as D, recordGuardianActionReviewed as Dn, loadTurnStart as Dr, instructionActorFor as Dt, isInheritedForkHistory as E, recordAuthorizationRequested as En, getTurnLifecycle as Er, buildSteeringPiMessage as Et, eventAuthorText as F, persistConversationMessages as Fn, createTurnLimitGate as Fr, saveUserCustomization as Ft, resumeForPersonInput as G, recordDeliveredAssistantMessage as Gn, ToolActionReviewUnavailableError as Gr, listWorkspacesByRepository as Gt, resolveBotSlackTeamId as H, latestConversationMessageSeq as Hn, isCutOffStopReason as Hr, getWorkspaceByName as Ht, findTrustedUser as I, resolveConversationTitle as In, isTurnExecutionLimitExceededError as Ir, addConversationNote as It, stopConversationTree as J, upsertConversationMessage as Jn, getToolActionRejectionMarker as Jr, tryWorkspaceRepoCheckoutPath as Jt, saveHeldInput as K, trimConversationMessages as Kn, createToolActionReview as Kr, updateWorkspace as Kt, isAllowedDomain as L, settleConversationTitleWork as Ln, captureTurnFailure as Lr, buildDeterministicAssistantMessageId as Lt, eventBatchMessageMeta as M, appendConversationMessages as Mn, TurnSliceLimitExceededError as Mr, readTaskInstructions as Mt, renderEventBatchInputs as N, hydrateConversationMessages as Nn, TurnToolCallLimitExceededError as Nr, renderTaskInput as Nt, EVENT_WAIT_MS as O, recordMcpProviderConnected as On, TURN_OUTCOME_STATUSES as Or, instructionForInputs as Ot, timerWatchCredentialSubject as P, persistConversationMessageWindow as Pn, buildTurnErrorResponse as Pr, readUserCustomization as Pt, getTurnUserReplyAttachmentContext as Q, isEventConversationMessage as Qn, USER_AUTHORIZATION_LEVELS as Qr, setWorkspaceSnapshot as Qt, isTrustedSlackAuthor as R, buildConversationContext as Rn, finalizeFailedTurnReplyWithEvent as Rr, buildDeterministicTurnId as Rt, getAgentReplyMessageId as S, recordAgentsInstructionsUpdated as Sn, getTurnRecord as Sr, loadInboxItemInput as St, getSpawnedChildConversationId as T, recordAuthorizationCompleted as Tn, ConversationTurnLifecycleService as Tr, buildPromptInput as Tt, enqueueAutomatedInput as U, markConversationMessage as Un, ToolActionRejectedError as Ur, listWorkspaceNamesByRepository as Ut, setTrustConfig as V, isHumanConversationMessage as Vn, buildTurnResult as Vr, getWorkspace as Vt, getConversationStoppedAtMs as W, normalizeConversationText as Wn, ToolActionReviewLimitError as Wr, listWorkspaces as Wt, getTurnUserMessage as X, EVENT_SYSTEM_ACTOR as Xn, RISK_LEVELS as Xr, invalidateReadySnapshot as Xt, completeCancelledConversationTurn as Y, EVENT_AUTHOR_ID as Yn, restoreToolActionRejections as Yr, workspaceRepoCheckoutPath as Yt, getTurnUserMessageId as Z, isEventAuthorId as Zn, ROOT_LINE_BREAK as Zr, loadSnapshotsForProfile as Zt, readChildOfStoredParent as _, commitMessages as _n, pauseLostWorkerTurn as _r, coerceThreadConversationState as _t, resolveMailboxTurnWork as a, startOAuthFlow as ai, AGENTS_REPLACEMENT_NOTICE as an, createPluginAuthOrchestration as ar, isCooperativeTurnYieldError as at, readAgentConfig as b, loadConversationSkillNames as bn, completeTurnRecord as br, getWebAuthorization as bt, legacyWebMailboxMetadataSchema as c, validateConfigValue as ci, readRepositoryInstructions as cn, AuthorizationFlowDisabledError as cr, markTurnClosed as ct, childAgentTurnOptions as d, foldLeadingSystemMessages as dn, canReusePendingAuthLink as dr, startActiveTurn as dt, CODE_MODE_CALL_STATUS_TEXT as ei, getExperimentalFeatures as en, getAgentBackgroundCompactionMarkTokens as er, ConversationTurnBoundaryError as et, commitParentMessageFork as f, foldSystemMessages as fn, clearPendingAuth as fr, getLocationConfigurationService as ft, parentMessageText as g, commitAcceptedReply as gn, lostWorkerBeforeFirstSave as gr, persistThreadStateById as gt, logDroppedParentMessage as h, writeAgentHistory as hn, loadTurnCheckpoint as hr, persistThreadRuntimeState as ht, listActiveMailboxTurns as i, parseOAuthStatePayload as ii, AGENTS_REMOVAL_NOTICE as in, PluginCredentialFailureError as ir, getConversationTurnBoundaryError as it, enqueueEventNotification as j, recordToolExecutionStarted as jn, TurnBudgetExceededError as jr, withoutSavedSteeringMessages as jt, addQuietEventNote as k, recordSkillLoaded as kn, GATED_TURN_LIMIT_WRAP_UP_MESSAGE as kr, loadPromptTurnContext as kt, appendParentMessage as l, configValueSchema as li, renderAgentsInstructions as ln, AuthorizationPauseError as lr, markTurnCompleted as lt, isParentMessageAuthor as m, withAgentRequest as mn, continuableMessages as mr, getPersistedThreadState as mt, getEventBatchDelayMs as n, deliverOAuthAuthorization as ni, setExperimentalFeatures as nn, getAgentContextInputLimitTokens as nr, TurnInputCommitLostError as nt, sourceFromTurnInput as o, projectConversationEvents as oi, buildAgentsInstructionsMessage as on, authorizationId as or, isTurnInputCommitLostError as ot, dropWaitingParentMessages as p, readAgentHistory as pn, getConversationPendingAuth as pr, getPersistedSandboxState as pt, session_stop_exports as q, turnHasReply as qn, reviewToolActions as qr, WorkspaceValidationError as qt, listActiveMailboxTurnSources as r, formatProviderLabel as ri, buildDeploymentSystemPrompt as rn, createPluginEgress as rr, TurnInputDeferredError as rt, turnInputFactsFromConversationMessage as s, validateConfigKey as si, findVisibleAgentsInstructions as sn, AuthPausePersistenceError as sr, isTurnInputDeferredError as st, getAuthPausedConversationTurnId as t, persistWithRetry as ti, isExperimentalFeatureEnabled as tn, getAgentContextCompactionTriggerTokens as tr, CooperativeTurnYieldError as tt, buildParentMessage as u, showsAgentsInstructions as un, abandonReplacedPendingAuth as ur, markTurnFailed as ut, readLastParentMessageAtMs as v, loadConnectedMcpProviders as vn, saveTurnCheckpoint as vr, createWebAuthorization as vt, getPersonStopTurnId as w, recordAuthenticationLinked as wn, recordTurnSummary as wr, assemblePrompt as wt, getAgentMessageId as x, loadTurnProjection as xn, failTurnRecord as xr, eventInboxItemInputs as xt, agentConfigSchema as y, loadConversationProjection as yn, abandonTurnRecord as yr, deleteWebAuthorization as yt, parseEmail as z, estimateConversationMessagesTokens as zn, getAgentTurnDiagnosticsAttributes as zr, createWorkspace as zt };
|