@sentry/junior 0.298.0 → 0.300.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{actor-6jsm_v96.js → actor-D2iXzvlN.js} +2 -1
- package/dist/{state-CSuA2J1V.js → adapter-S5UkjNK3.js} +53 -136
- package/dist/{admin-BF3DbYGf.js → admin-UrTniSPO.js} +2 -2
- package/dist/{agent-runner-Q9GkoerG.js → agent-runner-bY4_0UPm.js} +1444 -1478
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +7 -7
- package/dist/api.d.ts +1 -1
- package/dist/api.js +382 -68
- package/dist/{app-DOg_mCtV.d.ts → app-D-AcIcCV.d.ts} +17 -4
- package/dist/app.d.ts +1 -1
- package/dist/app.js +148 -483
- package/dist/{automation-Cn8qmbdr.js → automation-Dw82oQ-h.js} +2 -2
- package/dist/{background-compaction-queue-BZhGFOK6.js → background-compaction-queue-B6U3060-.js} +9 -5
- package/dist/{briefs-CQrCRF6-.js → briefs-DqiwWu-n.js} +4 -4
- package/dist/{catalog-runtime-DZeD2WbL.js → catalog-runtime-D1oYNv04.js} +1 -1
- package/dist/cli/chat.js +17 -17
- package/dist/cli/check.js +3 -3
- package/dist/cli/main.js +3 -3
- package/dist/cli/plugins.js +5 -5
- package/dist/cli/snapshot-create.js +4 -4
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +4 -4
- package/dist/{config-BOByVnxe.js → config-9nHoFiJP.js} +117 -12
- package/dist/{connections-BNN5cJam.js → connections-DZjTN3JC.js} +6 -6
- package/dist/continue-in-slack-Dtv7_U42.js +176 -0
- package/dist/{conversation-DCkzvxqB.js → conversation-Dyjq2CZ8.js} +36 -13
- package/dist/{conversation-feed-CMA12Rjs.js → conversation-feed-CcDxlrlQ.js} +109 -3
- package/dist/{conversation-privacy-C0eRxsgb.js → conversation-privacy-D-5HTXjS.js} +1 -1
- package/dist/{conversation-turn-D9qvcDX6.js → conversation-turn-Cxl8WZD7.js} +85 -68
- package/dist/{credential-sync-B_iUpxGL.js → credential-sync-C49ClwDX.js} +18 -18
- package/dist/{db-DoMcnYol.d.ts → db-2resqBh1.d.ts} +1 -1
- package/dist/{db-CoMNr2Zm.js → db-BJNo6fK5.js} +176 -12
- package/dist/{executor-C-m8VrzX.js → executor-DBIaOeJ_.js} +47 -13
- package/dist/{media-BepyEUNm.js → history-IjdmO_r6.js} +1 -85
- package/dist/instrumentation.js +14 -5
- package/dist/lineage-0dereG7H.js +37 -0
- package/dist/{logging-CJTi5niy.js → logging-BIclibct.js} +1 -1
- package/dist/{message-Q6_5DAWR.js → message-dkOl-Iii.js} +9 -10
- package/dist/model-input-CLo9TaUd.js +82 -0
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +17 -9
- package/dist/{oauth-callback-server-CH5XAyo-.js → oauth-callback-server-WmpjfJgQ.js} +2 -2
- package/dist/{plugins-HYh_JOdw.js → plugins-BBX07Jzt.js} +1 -1
- package/dist/{projection-BgwEE36_.js → projection-w_X-zi7v.js} +1035 -692
- package/dist/{prompt-DXc9DYT9.js → prompt-B1Xw46-S.js} +4 -4
- package/dist/{registry-9XwqSnM-.js → registry-BmP5vnlj.js} +4 -4
- package/dist/{resolve-DUIAbcRL.js → resolve-goo34bJK.js} +3 -3
- package/dist/{result-C2Vn8QGn.js → result-PVBeU0Wf.js} +158 -69
- package/dist/{runner-CXGtw-Mc.js → runner-DKrfvNV6.js} +9 -9
- package/dist/{sandbox-egress-signals-Di3S_dO7.js → sandbox-egress-signals-DsUcqrI0.js} +1 -1
- package/dist/{schema-Dyp7racy.js → schema-C9iNFz5n.js} +51 -7
- package/dist/{schema-BnbZ-rKv.d.ts → schema-Dns-sTas.d.ts} +1285 -761
- package/dist/{service-account-DM3KBBeG.js → service-account-CMAAloAL.js} +3 -3
- package/dist/{service-account-GzAMUQ8a.js → service-account-CmowamcB.js} +4 -4
- package/dist/session-stop-BcAXze8a.js +3330 -0
- package/dist/{skills-DCK9SD_l.js → skills-DfsazET6.js} +3 -3
- package/dist/slack-conversation-unfurl-CzQonuWz.js +370 -0
- package/dist/spawn-C7o0FDDp.js +73 -0
- package/dist/state-zSilNpbi.js +132 -0
- package/dist/{user-input-request-CXNIov9n.js → statuses-Hn-HsOph.js} +115 -26
- package/dist/{stop-Dh2DfwpK.js → stop-CFOujp8C.js} +9105 -6007
- package/dist/{store-DrA17Fbz.js → store-Dkeis_8o.js} +10 -10
- package/dist/{store-B1zepKG8.js → store-E3x2Fg_F.js} +24 -4
- package/dist/{task-queue-D1rXWfFN.js → task-queue-D-hCqdZW.js} +4 -4
- package/dist/{task-runner-CT4M8oDz.js → task-runner-vohUPLHe.js} +10 -10
- package/dist/{thread-context-DnqUkbzN.js → thread-context-BzvdkgI9.js} +18 -18
- package/dist/{turn-session-routing-VXDVXLRl.js → turn-session-routing-Bo_LxFum.js} +5 -5
- package/dist/turn-user-message-D5RnVmxQ.js +355 -0
- package/dist/users-2bggndVg.js +424 -0
- package/dist/{validation-zxAJBDDy.js → validation-BbWikeSa.js} +1 -1
- package/dist/{version-DcZ40a0g.js → version-GVBMW2jA.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-CgiGjW10.js → viewer-BpxRliyO.js} +36 -163
- package/dist/{warmup-CwKbxQLl.js → warmup-BW2qwnal.js} +1140 -145
- package/dist/{worker-CbDUzaBA.js → worker-Cbd-iuwZ.js} +25 -20
- package/migrations/0104_code_change_draft.sql +1 -0
- package/migrations/0105_attachment_uploads.sql +14 -0
- package/migrations/0106_conversation_agent_config.sql +1 -0
- package/migrations/0107_attachment_deferred_download.sql +2 -0
- package/migrations/meta/0104_snapshot.json +4516 -0
- package/migrations/meta/0105_snapshot.json +4611 -0
- package/migrations/meta/0106_snapshot.json +4617 -0
- package/migrations/meta/0107_snapshot.json +4617 -0
- package/migrations/meta/_journal.json +28 -0
- package/package.json +10 -8
- package/dist/attempt-selection-ClP3MMPr.js +0 -61
- package/dist/locks-D-0h111u.js +0 -48
- package/dist/notification-Bv25xbj0.js +0 -1284
- package/dist/prompt-input-BUr4J9RO.js +0 -1424
- package/dist/session-stop-D4i7e6iT.js +0 -181
- package/dist/spawn-6cX6xE9G.js +0 -80
- package/dist/turn-cancel-l460pfGW.js +0 -201
- package/dist/turn-user-message-BSPmkm7X.js +0 -608
- package/dist/turn-wake-DVFVXyhX.js +0 -161
- package/dist/{oauth-relay-CsfIazeF.js → oauth-relay-DRzq73b6.js} +1 -1
|
@@ -1,27 +1,29 @@
|
|
|
1
1
|
import { n as captureMessage, u as sentry_exports, v as __exportAll } from "./sentry-BRTJqumy.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { E as withSpan, h as logWarn, m as logInfo, x as setSpanStatus } from "./logging-
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { h as
|
|
8
|
-
import { u as
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import { a as getPersistedThreadState, c as coerceThreadConversationState, i as getPersistedSandboxState, s as persistThreadStateById } from "./turn-session-routing-
|
|
18
|
-
import {
|
|
19
|
-
import
|
|
2
|
+
import { $ as loadTurnCheckpoint, Cn as getTerminalAssistantMessages, Fo as FORK_INSTRUCTIONS, H as PluginCredentialFailureError, Io as loadForkHistory, K as AuthorizationFlowDisabledError, Un as escapeClosingTags, X as clearPendingAuth, _s as createPluginCache, at as failTurnRecord, dr as getPlugins, et as lostWorkerBeforeFirstSave, fn as NO_REPLY_TOOL_NAME, ho as createPluginLogger, in as REPLY_TOOL_NAME, j as markConversationMessage, nt as saveTurnCheckpoint, on as readTurnAnswer, qn as renderTag, rn as isTurnExecutionLimitExceededError, rt as abandonTurnRecord, s as openConversationProjection, st as getTurnRecord, tt as pauseLostWorkerTurn, un as getAssistantReplyText, v as hydrateConversationMessages, vi as listWatches, vn as REPORT_BLOCKED_TOOL_NAME } from "./projection-w_X-zi7v.js";
|
|
3
|
+
import { D as resolveGatewayModel, _ as TURN_REASONING_LEVELS, i as getChatConfig, n as botConfig, q as isProviderRetryError } from "./config-9nHoFiJP.js";
|
|
4
|
+
import { E as withSpan, h as logWarn, m as logInfo, x as setSpanStatus } from "./logging-BIclibct.js";
|
|
5
|
+
import { o as isUserActor } from "./actor-D2iXzvlN.js";
|
|
6
|
+
import { C as isPersonInput, D as conversationKindFromRow, E as turnBehavior, a as getConversationStore, et as rootConversationIsArchived, j as SYSTEM_IDENTITY_ID, o as getDb, r as getConversationEventStore, s as getSqlExecutor, w as isTopLevelKind, y as userMessageQueries } from "./db-BJNo6fK5.js";
|
|
7
|
+
import { g as juniorAgentInvocations, h as juniorAgentBindings, j as juniorConversations, w as juniorConversationEvents } from "./executor-DBIaOeJ_.js";
|
|
8
|
+
import { d as contextProvenance, m as sameActorIdentity, u as agentInstructionProvenance } from "./history-IjdmO_r6.js";
|
|
9
|
+
import { r as getStateAdapter } from "./adapter-S5UkjNK3.js";
|
|
10
|
+
import { p as credentialContextSchema } from "./registry-BmP5vnlj.js";
|
|
11
|
+
import { u as completeText } from "./prompt-B1Xw46-S.js";
|
|
12
|
+
import { A as agentTypeInstructions, j as agentTypeSchema } from "./conversation-Dyjq2CZ8.js";
|
|
13
|
+
import { C as getAuthPausedConversationTurnId, E as listActiveMailboxTurns, F as isEventMailboxMetadata, T as listActiveMailboxTurnSources, X as maybePostAutomatedTurnLimitNotice, at as conversationSubtreeColumns, f as buildSteeringPiMessage, g as withoutSavedSteeringMessages, i as resumeStoppedConversationTree, it as conversationSubtree, m as instructionForInputs, n as isSkippedAfterConversationStop, nt as recordFinishedTurnForAutomatedLimit, ot as buildDeploymentSystemPrompt, r as markConversationsStopped, rt as resetAutomatedTurnLimit, st as systemPromptHash, t as getConversationStoppedAtMs } from "./session-stop-BcAXze8a.js";
|
|
14
|
+
import { T as getTurnRequestDeadline, b as sendCacheWarmup, l as getVercelConversationWorkQueue } from "./background-compaction-queue-B6U3060-.js";
|
|
15
|
+
import { A as getAgentInvocationResultMessageId, C as ownAgentInvocation, I as getUnnamedAgentConversationId, N as getChildAgentLockName, O as getAgentInvocationIdForResult, P as getNamedAgentConversationId, R as buildDeterministicTurnId, S as listChildMessages, T as getAgentInvocationId, _ as ConversationTurnLifecycleService, b as hasAgentInvocationReply, d as isTurnInputCommitLostError, j as getAgentInvocationTurnId, k as getAgentInvocationMessageId, l as getConversationTurnBoundaryError, p as markTurnClosed, s as TurnInputCommitLostError, t as getTurnUserMessage, w as readChildMessageSender } from "./turn-user-message-D5RnVmxQ.js";
|
|
16
|
+
import { D as stopConversationWork, _ as getConversationWorkState, h as ensureConversationWake, m as dropPendingMessages, r as appendAndEnqueueInboundMessage, v as getConversationWorkStates, w as requestConversationWork } from "./store-E3x2Fg_F.js";
|
|
17
|
+
import { a as getPersistedThreadState, c as coerceThreadConversationState, i as getPersistedSandboxState, n as resolveTurnSessionRouting, s as persistThreadStateById } from "./turn-session-routing-Bo_LxFum.js";
|
|
18
|
+
import { C as isAgentInvocationResultEventType, b as AGENT_PARENT_MESSAGE_EVENT_TYPE, n as AGENT_INVOCATION_PARENT_MAILBOX_STATUSES, t as AGENT_INVOCATION_MAILBOX_STATUSES, v as AGENT_INVOCATION_EVENT_NAMESPACE } from "./statuses-Hn-HsOph.js";
|
|
19
|
+
import * as z from "zod";
|
|
20
20
|
import { streamSimple } from "@earendil-works/pi-ai/compat";
|
|
21
21
|
import { isDeepStrictEqual, promisify } from "node:util";
|
|
22
22
|
import { createHash, randomUUID } from "node:crypto";
|
|
23
|
-
import
|
|
24
|
-
import {
|
|
23
|
+
import { and, asc, desc, eq, exists, gt, inArray, isNotNull, ne, notExists, or, sql } from "drizzle-orm";
|
|
24
|
+
import { actorSchema, destinationSchema, sourceSchema } from "@sentry/junior-plugin-api";
|
|
25
|
+
import { alias } from "drizzle-orm/pg-core";
|
|
26
|
+
import pLimit from "p-limit";
|
|
25
27
|
import { constants, zstdCompress, zstdDecompress } from "node:zlib";
|
|
26
28
|
// src/chat/cache-warming/model.ts
|
|
27
29
|
/**
|
|
@@ -235,13 +237,18 @@ function parentGapSegment(input) {
|
|
|
235
237
|
archived: false
|
|
236
238
|
});
|
|
237
239
|
}
|
|
240
|
+
const WAITING_SEGMENT_SUFFIXES = {
|
|
241
|
+
child: "child",
|
|
242
|
+
review: "review",
|
|
243
|
+
watch: "automation"
|
|
244
|
+
};
|
|
238
245
|
/**
|
|
239
|
-
* Child of a segment for an idle period that waits on a child agent
|
|
240
|
-
* Review item. Its parent is the segment, so a
|
|
241
|
-
* segment, and a thin segment on its own parent.
|
|
246
|
+
* Child of a segment for an idle period that waits on a child agent, a
|
|
247
|
+
* Review item, or a Watch (`:automation`). Its parent is the segment, so a
|
|
248
|
+
* thin child leans on the segment, and a thin segment on its own parent.
|
|
242
249
|
*/
|
|
243
250
|
function waitingGapSegment(segment, waitingOn) {
|
|
244
|
-
return `${segment}:${waitingOn}`;
|
|
251
|
+
return `${segment}:${WAITING_SEGMENT_SUFFIXES[waitingOn]}`;
|
|
245
252
|
}
|
|
246
253
|
/** Whether a segment has too few gaps to stand without its parent. */
|
|
247
254
|
function segmentNeedsParent(segmentGaps) {
|
|
@@ -467,7 +474,9 @@ const IMAGE_REF_PREFIX = "sha256:";
|
|
|
467
474
|
const imageKey = (conversationId, sha256) => `${KEY_PREFIX}:image:${conversationId}:${sha256}`;
|
|
468
475
|
function imageParts(message) {
|
|
469
476
|
if (message.role === "assistant" || typeof message.content === "string") return [];
|
|
470
|
-
|
|
477
|
+
const images = [];
|
|
478
|
+
for (const part of message.content) if (part.type === "image") images.push(part);
|
|
479
|
+
return images;
|
|
471
480
|
}
|
|
472
481
|
function snapshotContext(context, toRef) {
|
|
473
482
|
return {
|
|
@@ -684,6 +693,354 @@ function createToolWaitWarmer(conversationId) {
|
|
|
684
693
|
}
|
|
685
694
|
};
|
|
686
695
|
}
|
|
696
|
+
// src/chat/conversations/agent-config.ts
|
|
697
|
+
/**
|
|
698
|
+
* The agent settings that every Turn of one Conversation keeps, for any
|
|
699
|
+
* kind: its Agent type, its reasoning level, and whether it started with its
|
|
700
|
+
* parent's history. A kind sets only the fields that apply to it.
|
|
701
|
+
*/
|
|
702
|
+
const agentConfigSchema = z.object({
|
|
703
|
+
agentType: agentTypeSchema.optional(),
|
|
704
|
+
fork: z.literal(true).optional(),
|
|
705
|
+
reasoningLevel: z.enum(TURN_REASONING_LEVELS).optional()
|
|
706
|
+
}).strict();
|
|
707
|
+
/**
|
|
708
|
+
* Read the agent config that one Conversation stores, or undefined when it
|
|
709
|
+
* stores none. Today only a child that a spawn created without an Agent
|
|
710
|
+
* invocation row stores one. A child that an Agent invocation names reads
|
|
711
|
+
* its settings from its row first.
|
|
712
|
+
*/
|
|
713
|
+
async function readAgentConfig(conversationId) {
|
|
714
|
+
const [row] = await getSqlExecutor().db().select({ agentConfig: juniorConversations.agentConfig }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId));
|
|
715
|
+
return row?.agentConfig ? agentConfigSchema.parse(row.agentConfig) : void 0;
|
|
716
|
+
}
|
|
717
|
+
// src/chat/runtime/turn-execution.ts
|
|
718
|
+
/** An error thrown while the agent advances a Run. */
|
|
719
|
+
var AgentRunError = class extends Error {
|
|
720
|
+
constructor(cause) {
|
|
721
|
+
super(cause instanceof Error ? cause.message : "Agent Run failed", { cause });
|
|
722
|
+
this.name = "AgentRunError";
|
|
723
|
+
}
|
|
724
|
+
};
|
|
725
|
+
/**
|
|
726
|
+
* Run the agent and finish the Turn after the caller saves its result.
|
|
727
|
+
*
|
|
728
|
+
* A paused Run, or a Run waiting for authorization, leaves the Turn open. A
|
|
729
|
+
* save error also leaves the Turn open so the worker can retry or recover it.
|
|
730
|
+
*/
|
|
731
|
+
async function executeTurn(agentRunner, run, saveResult) {
|
|
732
|
+
let outcome;
|
|
733
|
+
try {
|
|
734
|
+
outcome = await agentRunner.run(run);
|
|
735
|
+
} catch (error) {
|
|
736
|
+
throw new AgentRunError(error);
|
|
737
|
+
}
|
|
738
|
+
if (outcome.status !== "completed") return outcome;
|
|
739
|
+
const saved = await saveResult(outcome.result);
|
|
740
|
+
await finishTurn(run.conversationId, run.turnId, saved);
|
|
741
|
+
return { status: "completed" };
|
|
742
|
+
}
|
|
743
|
+
/** Record the terminal lifecycle event of a Turn from its saved result. */
|
|
744
|
+
async function finishTurn(conversationId, turnId, saved) {
|
|
745
|
+
const lifecycle = new ConversationTurnLifecycleService(getConversationEventStore());
|
|
746
|
+
const common = {
|
|
747
|
+
conversationId,
|
|
748
|
+
createdAtMs: saved.finishedAtMs ?? Date.now(),
|
|
749
|
+
turnId
|
|
750
|
+
};
|
|
751
|
+
if (saved.outcome === "failed") await lifecycle.fail({
|
|
752
|
+
...common,
|
|
753
|
+
...saved.eventId ? { eventId: saved.eventId } : void 0,
|
|
754
|
+
failureCode: saved.failureCode,
|
|
755
|
+
...saved.failureReason ? { failureReason: saved.failureReason } : void 0
|
|
756
|
+
});
|
|
757
|
+
else await lifecycle.complete({
|
|
758
|
+
...common,
|
|
759
|
+
outcome: saved.outcome
|
|
760
|
+
});
|
|
761
|
+
}
|
|
762
|
+
// src/chat/conversations/web-authorization.ts
|
|
763
|
+
const WEB_AUTHORIZATION_PREFIX = "junior:web_authorization:v1";
|
|
764
|
+
const WEB_AUTHORIZATION_TTL_MS = 864e5;
|
|
765
|
+
function authorizationKey$1(conversationId, actorId) {
|
|
766
|
+
return `${WEB_AUTHORIZATION_PREFIX}:${conversationId}:${actorId}`;
|
|
767
|
+
}
|
|
768
|
+
/** Build authorization delivery for one web turn. */
|
|
769
|
+
function createWebAuthorization(args) {
|
|
770
|
+
return {
|
|
771
|
+
createState: async () => randomUUID(),
|
|
772
|
+
deliver: async (request) => {
|
|
773
|
+
await getStateAdapter().set(authorizationKey$1(args.conversationId, args.actorId), JSON.stringify({
|
|
774
|
+
...request,
|
|
775
|
+
...args
|
|
776
|
+
}), WEB_AUTHORIZATION_TTL_MS);
|
|
777
|
+
}
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
/** Read the pending authorization request for one web actor. */
|
|
781
|
+
async function getWebAuthorization(args) {
|
|
782
|
+
const value = await getStateAdapter().get(authorizationKey$1(args.conversationId, args.actorId));
|
|
783
|
+
if (typeof value !== "string") return void 0;
|
|
784
|
+
try {
|
|
785
|
+
const parsed = JSON.parse(value);
|
|
786
|
+
if (parsed.actorId !== args.actorId || parsed.conversationId !== args.conversationId || typeof parsed.authorizationUrl !== "string" || typeof parsed.label !== "string" || typeof parsed.completionText !== "string") return;
|
|
787
|
+
return parsed;
|
|
788
|
+
} catch {
|
|
789
|
+
return;
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
/** Remove a web authorization request after the parked turn continues. */
|
|
793
|
+
async function deleteWebAuthorization(args) {
|
|
794
|
+
await getStateAdapter().delete(authorizationKey$1(args.conversationId, args.actorId));
|
|
795
|
+
}
|
|
796
|
+
// src/chat/task-execution/attempt-selection.ts
|
|
797
|
+
function inputOwner(message) {
|
|
798
|
+
return {
|
|
799
|
+
authorId: message.input.authorId,
|
|
800
|
+
identityId: message.input.authorIdentityId,
|
|
801
|
+
source: message.source
|
|
802
|
+
};
|
|
803
|
+
}
|
|
804
|
+
function turnOwner(turn) {
|
|
805
|
+
return {
|
|
806
|
+
authorId: isUserActor(turn.actor) ? turn.actor.userId : void 0,
|
|
807
|
+
identityId: turn.actorIdentityId,
|
|
808
|
+
source: turn.source?.kind
|
|
809
|
+
};
|
|
810
|
+
}
|
|
811
|
+
/**
|
|
812
|
+
* One Turn has one Actor and one Source: it runs with that Actor's
|
|
813
|
+
* credentials, so input from anyone else must not join it. Every value that
|
|
814
|
+
* both sides know must match, and they must share an Identity id or an author
|
|
815
|
+
* id. Input with no known author matches nothing.
|
|
816
|
+
*/
|
|
817
|
+
function hasSameOwner(a, b) {
|
|
818
|
+
if (a.source && b.source && a.source !== b.source) return false;
|
|
819
|
+
const sameIdentity = a.identityId && b.identityId ? a.identityId === b.identityId : void 0;
|
|
820
|
+
const sameAuthor = a.authorId && b.authorId ? a.authorId === b.authorId : void 0;
|
|
821
|
+
return sameIdentity !== false && sameAuthor !== false && (sameIdentity ?? sameAuthor) === true;
|
|
822
|
+
}
|
|
823
|
+
/** True when two Inbound messages may share one Turn. */
|
|
824
|
+
function canShareTurn(a, b) {
|
|
825
|
+
return hasSameOwner(inputOwner(a), inputOwner(b));
|
|
826
|
+
}
|
|
827
|
+
/** True when an Inbound message may join `turn`. */
|
|
828
|
+
function canJoinTurn(turn, message) {
|
|
829
|
+
return hasSameOwner(turnOwner(turn), inputOwner(message));
|
|
830
|
+
}
|
|
831
|
+
function selectContiguousTurnBatch(messages) {
|
|
832
|
+
const first = messages[0];
|
|
833
|
+
if (!first) return [];
|
|
834
|
+
const nextTurnIndex = messages.findIndex((message, index) => index > 0 && !canShareTurn(first, message));
|
|
835
|
+
return messages.slice(0, nextTurnIndex === -1 ? messages.length : nextTurnIndex);
|
|
836
|
+
}
|
|
837
|
+
/**
|
|
838
|
+
* True when an interrupt can start its own attempt.
|
|
839
|
+
*
|
|
840
|
+
* A steered web message must not start a second Turn while a yielded Turn
|
|
841
|
+
* waits to resume. It stays pending for that Turn's drain or the next attempt.
|
|
842
|
+
*/
|
|
843
|
+
function isAttemptInterrupt(message, work) {
|
|
844
|
+
return message.delivery === "interrupt" && !(work.execution.status === "paused" && message.source === "web");
|
|
845
|
+
}
|
|
846
|
+
/** Prioritize interrupts while keeping each attempt to one Actor and Source. */
|
|
847
|
+
function selectAttemptMessages(work) {
|
|
848
|
+
const messages = work.messages;
|
|
849
|
+
const interrupts = messages.filter((message) => isAttemptInterrupt(message, work));
|
|
850
|
+
if (interrupts.length > 0) return selectContiguousTurnBatch(interrupts);
|
|
851
|
+
if (work.execution.status === "paused") return [];
|
|
852
|
+
const nonEventMessages = messages.filter((message) => message.source !== "event");
|
|
853
|
+
return selectContiguousTurnBatch(nonEventMessages.length > 0 ? nonEventMessages : messages);
|
|
854
|
+
}
|
|
855
|
+
// src/chat/task-execution/authorized-turn.ts
|
|
856
|
+
/**
|
|
857
|
+
* OAuth callbacks save readiness, not agent history. The conversation worker
|
|
858
|
+
* consumes this event under its lease before it resumes the paused Turn.
|
|
859
|
+
*/
|
|
860
|
+
const authorizationSchema = z.object({
|
|
861
|
+
kind: z.enum(["mcp", "plugin"]),
|
|
862
|
+
provider: z.string().min(1),
|
|
863
|
+
actorId: z.string().min(1),
|
|
864
|
+
authorizationId: z.string().min(1),
|
|
865
|
+
authSessionId: z.string().optional(),
|
|
866
|
+
scope: z.string().optional(),
|
|
867
|
+
configuration: z.record(z.string(), z.unknown()).optional(),
|
|
868
|
+
toolChannelId: z.string().optional()
|
|
869
|
+
});
|
|
870
|
+
function authorizationKey(turn) {
|
|
871
|
+
return `turn:${turn.turnId}:authorization:${turn.version}`;
|
|
872
|
+
}
|
|
873
|
+
/** Save authorization for this parked boundary without changing model history. */
|
|
874
|
+
async function recordTurnAuthorization(args) {
|
|
875
|
+
const turn = await getTurnRecord(args.conversationId, args.turnId);
|
|
876
|
+
if (!turn || turn.state !== "paused" || turn.resumeReason !== "auth") return;
|
|
877
|
+
await getConversationEventStore().append(args.conversationId, [{
|
|
878
|
+
idempotencyKey: authorizationKey(turn),
|
|
879
|
+
createdAtMs: Date.now(),
|
|
880
|
+
data: {
|
|
881
|
+
type: "structured_event",
|
|
882
|
+
namespace: "junior",
|
|
883
|
+
name: "turn_authorized",
|
|
884
|
+
version: 1,
|
|
885
|
+
turnId: turn.turnId,
|
|
886
|
+
content: authorizationSchema.parse(args)
|
|
887
|
+
}
|
|
888
|
+
}], { activity: "preserve" });
|
|
889
|
+
return {
|
|
890
|
+
conversationId: args.conversationId,
|
|
891
|
+
destination: args.destination,
|
|
892
|
+
turnId: turn.turnId,
|
|
893
|
+
expectedVersion: turn.version
|
|
894
|
+
};
|
|
895
|
+
}
|
|
896
|
+
/** Read authorization for the exact pause; a later auth pause needs its own callback. */
|
|
897
|
+
async function getTurnAuthorization(turn) {
|
|
898
|
+
const event = await getConversationEventStore().loadByIdempotencyKey(turn.conversationId, authorizationKey(turn));
|
|
899
|
+
if (event?.data.type !== "structured_event") return void 0;
|
|
900
|
+
return authorizationSchema.parse(event.data.content);
|
|
901
|
+
}
|
|
902
|
+
// src/chat/task-execution/turn-wake.ts
|
|
903
|
+
/** Build the worker input for a paused turn. */
|
|
904
|
+
async function getPausedTurnRequest(args) {
|
|
905
|
+
const turn = (await loadTurnCheckpoint({
|
|
906
|
+
conversationId: args.conversationId,
|
|
907
|
+
turnId: args.turnId
|
|
908
|
+
})).record;
|
|
909
|
+
if (!turn || turn.state !== "paused" || turn.resumeReason !== "timeout" && turn.resumeReason !== "yield" && turn.resumeReason !== "retry" && !(turn.resumeReason === "auth" && await getTurnAuthorization(turn)) || turn.resumeReason === "timeout" && turn.sliceId < 2) return;
|
|
910
|
+
let routing;
|
|
911
|
+
try {
|
|
912
|
+
routing = await resolveTurnSessionRouting({
|
|
913
|
+
conversationId: args.conversationId,
|
|
914
|
+
conversationStore: args.conversationStore
|
|
915
|
+
});
|
|
916
|
+
} catch (error) {
|
|
917
|
+
await failTurnRecord({
|
|
918
|
+
conversationId: args.conversationId,
|
|
919
|
+
expectedVersion: turn.version,
|
|
920
|
+
turnId: args.turnId,
|
|
921
|
+
errorMessage: error instanceof Error ? error.message : String(error)
|
|
922
|
+
});
|
|
923
|
+
return;
|
|
924
|
+
}
|
|
925
|
+
return {
|
|
926
|
+
conversationId: args.conversationId,
|
|
927
|
+
destination: routing.destination,
|
|
928
|
+
turnId: args.turnId,
|
|
929
|
+
expectedVersion: turn.version,
|
|
930
|
+
traceContext: turn.traceContext
|
|
931
|
+
};
|
|
932
|
+
}
|
|
933
|
+
/** Wake the conversation worker for a paused turn. */
|
|
934
|
+
async function wakePausedTurn(request, options = {}) {
|
|
935
|
+
const nowMs = options.nowMs ?? Date.now();
|
|
936
|
+
const conversation = await (options.conversationStore ?? getConversationStore()).get({ conversationId: request.conversationId });
|
|
937
|
+
await requestConversationWork({
|
|
938
|
+
conversationId: request.conversationId,
|
|
939
|
+
destination: conversation && !isTopLevelKind(conversation.kind) ? void 0 : request.destination,
|
|
940
|
+
nowMs,
|
|
941
|
+
state: options.state
|
|
942
|
+
});
|
|
943
|
+
const queue = options.queue ?? getVercelConversationWorkQueue();
|
|
944
|
+
await ensureConversationWake({
|
|
945
|
+
conversationId: request.conversationId,
|
|
946
|
+
idempotencyKey: [
|
|
947
|
+
"agent-continue",
|
|
948
|
+
request.conversationId,
|
|
949
|
+
request.turnId,
|
|
950
|
+
request.expectedVersion,
|
|
951
|
+
nowMs
|
|
952
|
+
].join(":"),
|
|
953
|
+
nowMs,
|
|
954
|
+
queue,
|
|
955
|
+
state: options.state
|
|
956
|
+
});
|
|
957
|
+
}
|
|
958
|
+
/** Create paused Turn operations for one app. */
|
|
959
|
+
function createPausedTurns(options = {}) {
|
|
960
|
+
return {
|
|
961
|
+
get: (args) => getPausedTurnRequest({
|
|
962
|
+
...args,
|
|
963
|
+
conversationStore: options.conversationStore
|
|
964
|
+
}),
|
|
965
|
+
wake: (request) => wakePausedTurn(request, options)
|
|
966
|
+
};
|
|
967
|
+
}
|
|
968
|
+
/** Record completed authorization and wake the sole execution owner. */
|
|
969
|
+
async function wakeAuthorizedTurn(args, queue) {
|
|
970
|
+
const request = await recordTurnAuthorization(args);
|
|
971
|
+
if (request) await wakePausedTurn(request, { queue });
|
|
972
|
+
}
|
|
973
|
+
// src/chat/task-execution/supersede-turns.ts
|
|
974
|
+
/**
|
|
975
|
+
* End every open mailbox Turn other than `keepTurnId`, so new input runs in
|
|
976
|
+
* the only open Turn. New input starts only when no yielded Turn waits, so an
|
|
977
|
+
* open Turn here waits for OAuth or was left open by a failed or stopped Run.
|
|
978
|
+
* The caller persists `conversation`. Returns false when `isStopped` turns
|
|
979
|
+
* true first.
|
|
980
|
+
*/
|
|
981
|
+
async function supersedeOpenMailboxTurns(args) {
|
|
982
|
+
return await supersedeTurns({
|
|
983
|
+
...args,
|
|
984
|
+
turns: (await listActiveMailboxTurns(args.conversationId)).filter((record) => record.turnId !== args.keepTurnId)
|
|
985
|
+
});
|
|
986
|
+
}
|
|
987
|
+
/**
|
|
988
|
+
* End open Turns that new input replaces. A late resume or OAuth callback
|
|
989
|
+
* for an ended Turn is a no-op. The caller persists `conversation`. Returns
|
|
990
|
+
* false when `isStopped` turns true first.
|
|
991
|
+
*/
|
|
992
|
+
async function supersedeTurns(args) {
|
|
993
|
+
const pendingAuthorizationActorId = args.conversation.processing.pendingAuth?.actorId;
|
|
994
|
+
for (const stale of args.turns) {
|
|
995
|
+
if (args.isStopped?.()) return false;
|
|
996
|
+
await abandonTurnRecord({
|
|
997
|
+
conversationId: args.conversationId,
|
|
998
|
+
turnId: stale.turnId,
|
|
999
|
+
errorMessage: "Turn superseded by new input"
|
|
1000
|
+
});
|
|
1001
|
+
await new ConversationTurnLifecycleService(getConversationEventStore()).complete({
|
|
1002
|
+
conversationId: args.conversationId,
|
|
1003
|
+
createdAtMs: Date.now(),
|
|
1004
|
+
outcome: "cancelled",
|
|
1005
|
+
turnId: stale.turnId
|
|
1006
|
+
});
|
|
1007
|
+
markTurnClosed({
|
|
1008
|
+
conversation: args.conversation,
|
|
1009
|
+
nowMs: Date.now(),
|
|
1010
|
+
sessionId: stale.turnId
|
|
1011
|
+
});
|
|
1012
|
+
}
|
|
1013
|
+
if (args.turns.some((record) => record.state === "paused" && record.resumeReason === "auth") && pendingAuthorizationActorId) await deleteWebAuthorization({
|
|
1014
|
+
actorId: pendingAuthorizationActorId,
|
|
1015
|
+
conversationId: args.conversationId
|
|
1016
|
+
});
|
|
1017
|
+
return true;
|
|
1018
|
+
}
|
|
1019
|
+
/**
|
|
1020
|
+
* End the Turn that waits for its next Run when `message` cannot join it, so
|
|
1021
|
+
* the message starts its own Turn instead of running with that Turn's Actor.
|
|
1022
|
+
* A stored legacy Turn without an Actor keeps taking the input.
|
|
1023
|
+
*/
|
|
1024
|
+
async function supersedeTurnForInput(args) {
|
|
1025
|
+
const conversation = coerceThreadConversationState(await getPersistedThreadState(args.conversationId));
|
|
1026
|
+
const turnId = conversation.processing.activeTurnId;
|
|
1027
|
+
if (!turnId || !await getPausedTurnRequest({
|
|
1028
|
+
conversationId: args.conversationId,
|
|
1029
|
+
turnId
|
|
1030
|
+
})) return;
|
|
1031
|
+
const turn = await getTurnRecord(args.conversationId, turnId);
|
|
1032
|
+
if (!turn?.actor || canJoinTurn(turn, args.message)) return;
|
|
1033
|
+
await hydrateConversationMessages({
|
|
1034
|
+
conversation,
|
|
1035
|
+
conversationId: args.conversationId
|
|
1036
|
+
});
|
|
1037
|
+
await supersedeTurns({
|
|
1038
|
+
conversation,
|
|
1039
|
+
conversationId: args.conversationId,
|
|
1040
|
+
turns: [turn]
|
|
1041
|
+
});
|
|
1042
|
+
await persistThreadStateById(args.conversationId, { conversation });
|
|
1043
|
+
}
|
|
687
1044
|
// src/chat/agent-invocations/thread-turn.ts
|
|
688
1045
|
/**
|
|
689
1046
|
* A person's Turn in a Thread runs on the Conversation loop. A
|
|
@@ -707,6 +1064,87 @@ async function supersedeOpenMailboxTurn(conversationId) {
|
|
|
707
1064
|
});
|
|
708
1065
|
await persistThreadStateById(conversationId, { conversation });
|
|
709
1066
|
}
|
|
1067
|
+
// src/chat/agent-invocations/types.ts
|
|
1068
|
+
const exactStringSchema = z.string().min(1).refine((value) => value === value.trim());
|
|
1069
|
+
const agentNameSchema = exactStringSchema.max(64);
|
|
1070
|
+
/**
|
|
1071
|
+
* Kind of a new child Conversation. A Thread is a child that people can
|
|
1072
|
+
* message; a Task is one that only its parent messages.
|
|
1073
|
+
*/
|
|
1074
|
+
const CHILD_AGENT_KINDS = ["thread", "task"];
|
|
1075
|
+
/** `messageAgent` target for the parent of a child agent. */
|
|
1076
|
+
const PARENT_AGENT_TARGET = "parent";
|
|
1077
|
+
const agentInvocationMailboxStatusSchema = z.enum(AGENT_INVOCATION_MAILBOX_STATUSES);
|
|
1078
|
+
const agentInvocationParentMailboxStatusSchema = z.enum(AGENT_INVOCATION_PARENT_MAILBOX_STATUSES);
|
|
1079
|
+
const agentBindingSchema = z.object({
|
|
1080
|
+
childConversationId: exactStringSchema,
|
|
1081
|
+
name: agentNameSchema,
|
|
1082
|
+
parentConversationId: exactStringSchema
|
|
1083
|
+
}).strict();
|
|
1084
|
+
const agentInvocationBaseSchema = z.object({
|
|
1085
|
+
actor: actorSchema,
|
|
1086
|
+
agentName: agentNameSchema.optional(),
|
|
1087
|
+
childConversationId: exactStringSchema,
|
|
1088
|
+
createdAtMs: z.number().finite(),
|
|
1089
|
+
credentialContext: credentialContextSchema.optional(),
|
|
1090
|
+
destination: destinationSchema,
|
|
1091
|
+
input: exactStringSchema,
|
|
1092
|
+
invocationId: exactStringSchema,
|
|
1093
|
+
mailboxStatus: agentInvocationMailboxStatusSchema,
|
|
1094
|
+
parentConversationId: exactStringSchema,
|
|
1095
|
+
parentToolCallId: exactStringSchema.optional(),
|
|
1096
|
+
agentType: agentTypeSchema.optional(),
|
|
1097
|
+
/** The child starts with its parent's history. */
|
|
1098
|
+
fork: z.literal(true).optional(),
|
|
1099
|
+
reasoningLevel: z.enum(TURN_REASONING_LEVELS).optional(),
|
|
1100
|
+
source: sourceSchema,
|
|
1101
|
+
title: exactStringSchema.optional(),
|
|
1102
|
+
updatedAtMs: z.number().finite()
|
|
1103
|
+
}).strict();
|
|
1104
|
+
const agentInvocationSchema = z.discriminatedUnion("status", [
|
|
1105
|
+
agentInvocationBaseSchema.extend({ status: z.enum([
|
|
1106
|
+
"pending",
|
|
1107
|
+
"running",
|
|
1108
|
+
"paused"
|
|
1109
|
+
]) }),
|
|
1110
|
+
agentInvocationBaseSchema.extend({
|
|
1111
|
+
parentMailboxStatus: agentInvocationParentMailboxStatusSchema,
|
|
1112
|
+
result: z.string(),
|
|
1113
|
+
status: z.literal("completed"),
|
|
1114
|
+
terminalAtMs: z.number().finite()
|
|
1115
|
+
}),
|
|
1116
|
+
agentInvocationBaseSchema.extend({
|
|
1117
|
+
errorMessage: z.string(),
|
|
1118
|
+
parentMailboxStatus: agentInvocationParentMailboxStatusSchema,
|
|
1119
|
+
status: z.enum([
|
|
1120
|
+
"blocked",
|
|
1121
|
+
"failed",
|
|
1122
|
+
"stopped"
|
|
1123
|
+
]),
|
|
1124
|
+
terminalAtMs: z.number().finite()
|
|
1125
|
+
})
|
|
1126
|
+
]);
|
|
1127
|
+
const createAgentInvocationSchema = z.object({
|
|
1128
|
+
actor: actorSchema,
|
|
1129
|
+
agentName: agentNameSchema.optional(),
|
|
1130
|
+
credentialContext: credentialContextSchema.optional(),
|
|
1131
|
+
destination: destinationSchema,
|
|
1132
|
+
idempotencyKey: exactStringSchema,
|
|
1133
|
+
input: exactStringSchema,
|
|
1134
|
+
kind: z.enum(CHILD_AGENT_KINDS).default("task"),
|
|
1135
|
+
parentConversationId: exactStringSchema,
|
|
1136
|
+
parentToolCallId: exactStringSchema.optional(),
|
|
1137
|
+
agentType: agentTypeSchema.optional(),
|
|
1138
|
+
fork: z.literal(true).optional(),
|
|
1139
|
+
reasoningLevel: z.enum(TURN_REASONING_LEVELS).optional(),
|
|
1140
|
+
title: exactStringSchema.optional()
|
|
1141
|
+
}).strict();
|
|
1142
|
+
/** How a finished task of a child agent ended. A stop is not a result. */
|
|
1143
|
+
const CHILD_AGENT_RESULTS = [
|
|
1144
|
+
"completed",
|
|
1145
|
+
"blocked",
|
|
1146
|
+
"failed"
|
|
1147
|
+
];
|
|
710
1148
|
// src/chat/agent-invocations/bindings.ts
|
|
711
1149
|
function bindingFromRow(row) {
|
|
712
1150
|
return agentBindingSchema.parse({
|
|
@@ -720,14 +1158,18 @@ async function getAgentBinding(args) {
|
|
|
720
1158
|
const rows = await getSqlExecutor().db().select().from(juniorAgentBindings).where(and(eq(juniorAgentBindings.parentConversationId, args.parentConversationId), eq(juniorAgentBindings.name, args.name)));
|
|
721
1159
|
return rows[0] ? bindingFromRow(rows[0]) : void 0;
|
|
722
1160
|
}
|
|
723
|
-
/**
|
|
1161
|
+
/**
|
|
1162
|
+
* Find a direct child agent of one parent by name or child Conversation id.
|
|
1163
|
+
* A child that no Agent invocation names stores its agent config.
|
|
1164
|
+
*/
|
|
724
1165
|
async function findChildAgentConversationId(args) {
|
|
725
1166
|
const binding = await getAgentBinding({
|
|
726
1167
|
name: args.target,
|
|
727
1168
|
parentConversationId: args.parentConversationId
|
|
728
1169
|
});
|
|
729
1170
|
if (binding) return binding.childConversationId;
|
|
730
|
-
|
|
1171
|
+
const db = getSqlExecutor().db();
|
|
1172
|
+
return (await db.select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(eq(juniorConversations.parentConversationId, args.parentConversationId), eq(juniorConversations.conversationId, args.target), or(isNotNull(juniorConversations.agentConfig), exists(db.select({ invocationId: juniorAgentInvocations.invocationId }).from(juniorAgentInvocations).where(eq(juniorAgentInvocations.childConversationId, args.target)))))).limit(1))[0]?.conversationId;
|
|
731
1173
|
}
|
|
732
1174
|
// src/chat/agent-invocations/errors.ts
|
|
733
1175
|
/** A child agent already uses this name in the parent Conversation. */
|
|
@@ -818,13 +1260,13 @@ function sameCreateInput(invocation, input) {
|
|
|
818
1260
|
* A stopped child agent cannot start or give work to child agents until its
|
|
819
1261
|
* parent gives it new work. A Turn on the child's Conversation loop
|
|
820
1262
|
* has no open agent invocation, but it can. A root Conversation has no agent
|
|
821
|
-
* invocation, so it always passes. `open` is the parent's open work from
|
|
1263
|
+
* invocation or agent config, so it always passes. `open` is the parent's open work from
|
|
822
1264
|
* `listOpenAgentInvocations`.
|
|
823
1265
|
*/
|
|
824
1266
|
async function assertCanGiveChildWork(parentConversationId, open) {
|
|
825
1267
|
if (open.some((row) => row.childConversationId === parentConversationId)) return;
|
|
826
1268
|
const latest = await getLatestAgentInvocationForConversation(parentConversationId);
|
|
827
|
-
if (latest
|
|
1269
|
+
if (latest ? isStoppedAgentInvocation(latest) : await readAgentConfig(parentConversationId) !== void 0 && await getConversationStoppedAtMs(parentConversationId) !== void 0) throw new Error(`Agent conversation ${parentConversationId} is stopped and cannot give work to child agents`);
|
|
828
1270
|
}
|
|
829
1271
|
/**
|
|
830
1272
|
* Throw when giving work to one child agent would put its parent over
|
|
@@ -832,10 +1274,11 @@ async function assertCanGiveChildWork(parentConversationId, open) {
|
|
|
832
1274
|
* has open work, so a busy child already counts and messages queued for it
|
|
833
1275
|
* do not count again. A new or idle child becomes active. This is the only
|
|
834
1276
|
* place the rule for which child agents count lives. `open` is the parent's
|
|
835
|
-
* open work from `listOpenAgentInvocations`.
|
|
1277
|
+
* open work from `listOpenAgentInvocations`. A child that no agent
|
|
1278
|
+
* invocation names is active while its listing shows open work.
|
|
836
1279
|
*/
|
|
837
|
-
function assertChildAgentCapacity(open, args) {
|
|
838
|
-
const active = new Set(open.filter((row) => row.parentConversationId === args.parentConversationId).map((row) => row.childConversationId));
|
|
1280
|
+
async function assertChildAgentCapacity(open, args) {
|
|
1281
|
+
const active = /* @__PURE__ */ new Set([...open.filter((row) => row.parentConversationId === args.parentConversationId).map((row) => row.childConversationId), ...await listOpenChildAgentsWithoutAgentInvocations(args.parentConversationId)]);
|
|
839
1282
|
if (!active.has(args.childConversationId) && active.size >= 8) throw new AgentInvocationLimitError(8);
|
|
840
1283
|
}
|
|
841
1284
|
/**
|
|
@@ -862,7 +1305,7 @@ async function createAgentInvocation(rawInput, nowMs = Date.now()) {
|
|
|
862
1305
|
name: input.agentName,
|
|
863
1306
|
parentConversationId: input.parentConversationId
|
|
864
1307
|
})) throw new AgentNameInUseError(input.agentName);
|
|
865
|
-
assertChildAgentCapacity(open, {
|
|
1308
|
+
await assertChildAgentCapacity(open, {
|
|
866
1309
|
childConversationId,
|
|
867
1310
|
parentConversationId: input.parentConversationId
|
|
868
1311
|
});
|
|
@@ -916,9 +1359,11 @@ async function createAgentInvocationFromLatest(args, nowMs = Date.now()) {
|
|
|
916
1359
|
childConversationId: latest.childConversationId,
|
|
917
1360
|
credentialContext,
|
|
918
1361
|
destination: latest.destination,
|
|
1362
|
+
fork: args.runAs?.fork,
|
|
919
1363
|
input: args.input,
|
|
920
1364
|
invocationId: args.invocationId,
|
|
921
1365
|
parentConversationId: latest.parentConversationId,
|
|
1366
|
+
parentToolCallId: args.runAs?.parentToolCallId,
|
|
922
1367
|
reasoningLevel: latest.reasoningLevel,
|
|
923
1368
|
source: args.runAs?.source
|
|
924
1369
|
}, nowMs);
|
|
@@ -943,19 +1388,21 @@ async function createAgentInvocationForMessage(input, nowMs = Date.now()) {
|
|
|
943
1388
|
};
|
|
944
1389
|
}
|
|
945
1390
|
const latest = await getLatestAgentInvocationForConversation(input.childConversationId);
|
|
946
|
-
|
|
1391
|
+
const child = latest ?? await readChildConversationSender(input.childConversationId);
|
|
1392
|
+
if (!child || child.parentConversationId !== input.parentConversationId) throw new Error(`${input.childConversationId} is not a child agent of ${input.parentConversationId}`);
|
|
1393
|
+
const agentConfig = latest ?? await readAgentConfig(input.childConversationId) ?? {};
|
|
947
1394
|
const open = await listOpenAgentInvocations(input.parentConversationId);
|
|
948
1395
|
await assertCanGiveChildWork(input.parentConversationId, open);
|
|
949
|
-
const openCount = open.filter((row) => row.childConversationId === input.childConversationId).length;
|
|
1396
|
+
const openCount = open.filter((row) => row.childConversationId === input.childConversationId).length + (latest ? 0 : await countOpenParentMessages(input.childConversationId));
|
|
950
1397
|
if (openCount >= MAX_OPEN_AGENT_INVOCATIONS_PER_CHILD) throw new AgentMessageQueueFullError(MAX_OPEN_AGENT_INVOCATIONS_PER_CHILD);
|
|
951
|
-
assertChildAgentCapacity(open, {
|
|
1398
|
+
await assertChildAgentCapacity(open, {
|
|
952
1399
|
childConversationId: input.childConversationId,
|
|
953
1400
|
parentConversationId: input.parentConversationId
|
|
954
1401
|
});
|
|
955
1402
|
const invocation = await insertAgentInvocation({
|
|
956
1403
|
actor: input.actor,
|
|
957
|
-
agentName:
|
|
958
|
-
agentType:
|
|
1404
|
+
agentName: child.agentName,
|
|
1405
|
+
agentType: agentConfig.agentType,
|
|
959
1406
|
childConversationId: input.childConversationId,
|
|
960
1407
|
credentialContext: input.credentialContext,
|
|
961
1408
|
destination: input.destination,
|
|
@@ -963,7 +1410,7 @@ async function createAgentInvocationForMessage(input, nowMs = Date.now()) {
|
|
|
963
1410
|
invocationId,
|
|
964
1411
|
parentConversationId: input.parentConversationId,
|
|
965
1412
|
parentToolCallId: input.parentToolCallId,
|
|
966
|
-
reasoningLevel:
|
|
1413
|
+
reasoningLevel: agentConfig.reasoningLevel
|
|
967
1414
|
}, nowMs);
|
|
968
1415
|
if (!invocation) throw new Error(`Agent invocation creation raced for ${invocationId}`);
|
|
969
1416
|
return {
|
|
@@ -1115,6 +1562,83 @@ function savedTurnEnd(turn) {
|
|
|
1115
1562
|
status: "completed"
|
|
1116
1563
|
};
|
|
1117
1564
|
}
|
|
1565
|
+
// src/chat/task-execution/turn-cancel.ts
|
|
1566
|
+
/**
|
|
1567
|
+
* End a cancelled Turn: a stop that a worker saw, or a stop of a Turn that
|
|
1568
|
+
* waits for sign-in with no worker.
|
|
1569
|
+
*/
|
|
1570
|
+
/** Close a cancelled Turn, save it, and acknowledge its input. */
|
|
1571
|
+
async function completeCancelledConversationTurn(args) {
|
|
1572
|
+
const pendingAuthorization = args.conversation.processing.pendingAuth?.sessionId === args.turnId ? args.conversation.processing.pendingAuth : void 0;
|
|
1573
|
+
await abandonTurnRecord({
|
|
1574
|
+
conversationId: args.conversationId,
|
|
1575
|
+
turnId: args.turnId,
|
|
1576
|
+
errorMessage: "Turn cancelled"
|
|
1577
|
+
});
|
|
1578
|
+
clearPendingAuth(args.conversation, args.turnId);
|
|
1579
|
+
markConversationMessage(args.conversation, args.userMessageId, {
|
|
1580
|
+
replied: false,
|
|
1581
|
+
skippedReason: "turn cancelled"
|
|
1582
|
+
});
|
|
1583
|
+
markTurnClosed({
|
|
1584
|
+
conversation: args.conversation,
|
|
1585
|
+
nowMs: Date.now(),
|
|
1586
|
+
sessionId: args.turnId
|
|
1587
|
+
});
|
|
1588
|
+
if (pendingAuthorization) await deleteWebAuthorization({
|
|
1589
|
+
actorId: pendingAuthorization.actorId,
|
|
1590
|
+
conversationId: args.conversationId
|
|
1591
|
+
});
|
|
1592
|
+
await persistThreadStateById(args.conversationId, {
|
|
1593
|
+
conversation: args.conversation,
|
|
1594
|
+
sandboxRef: args.sandboxRef
|
|
1595
|
+
});
|
|
1596
|
+
await new ConversationTurnLifecycleService(getConversationEventStore()).complete({
|
|
1597
|
+
conversationId: args.conversationId,
|
|
1598
|
+
createdAtMs: Date.now(),
|
|
1599
|
+
outcome: "cancelled",
|
|
1600
|
+
turnId: args.turnId
|
|
1601
|
+
});
|
|
1602
|
+
await args.acknowledge();
|
|
1603
|
+
}
|
|
1604
|
+
/**
|
|
1605
|
+
* End the Turn of a stopped Conversation that waits for sign-in, so a later
|
|
1606
|
+
* sign-in cannot resume it. A web Turn waits as an auth-paused Turn record. A
|
|
1607
|
+
* Slack request waits as the thread's pending sign-in. Every stop path calls
|
|
1608
|
+
* this, because no worker holds a waiting Turn and the stop wake can go to
|
|
1609
|
+
* queued input first.
|
|
1610
|
+
*/
|
|
1611
|
+
async function cancelSignInWait(conversationId) {
|
|
1612
|
+
const turnId = await getAuthPausedConversationTurnId(conversationId) ?? coerceThreadConversationState(await getPersistedThreadState(conversationId)).processing.pendingAuth?.sessionId;
|
|
1613
|
+
if (turnId) await cancelSignInPausedTurn({
|
|
1614
|
+
conversationId,
|
|
1615
|
+
turnId
|
|
1616
|
+
});
|
|
1617
|
+
}
|
|
1618
|
+
/**
|
|
1619
|
+
* Cancel a Turn that waits for sign-in outside its worker, with the same
|
|
1620
|
+
* cleanup as a stopped resume.
|
|
1621
|
+
*/
|
|
1622
|
+
async function cancelSignInPausedTurn(args) {
|
|
1623
|
+
if (!await abandonTurnRecord({
|
|
1624
|
+
conversationId: args.conversationId,
|
|
1625
|
+
errorMessage: "Turn cancelled",
|
|
1626
|
+
onlyIfAuthPaused: true,
|
|
1627
|
+
turnId: args.turnId
|
|
1628
|
+
})) return;
|
|
1629
|
+
const conversation = coerceThreadConversationState(await getPersistedThreadState(args.conversationId));
|
|
1630
|
+
await hydrateConversationMessages({
|
|
1631
|
+
conversation,
|
|
1632
|
+
conversationId: args.conversationId
|
|
1633
|
+
});
|
|
1634
|
+
await completeCancelledConversationTurn({
|
|
1635
|
+
acknowledge: async () => {},
|
|
1636
|
+
conversation,
|
|
1637
|
+
conversationId: args.conversationId,
|
|
1638
|
+
turnId: args.turnId,
|
|
1639
|
+
userMessageId: getTurnUserMessage(conversation, args.turnId)?.id
|
|
1640
|
+
});
|
|
1641
|
+
}
|
|
1118
1642
|
// src/chat/agent-invocations/stop.ts
|
|
1119
1643
|
/**
|
|
1120
1644
|
* Stop one child agent of a parent Conversation and every child agent below
|
|
@@ -1126,8 +1650,8 @@ function savedTurnEnd(turn) {
|
|
|
1126
1650
|
* Returns undefined when the child does not belong to the parent.
|
|
1127
1651
|
*/
|
|
1128
1652
|
async function stopChildAgent(args) {
|
|
1129
|
-
const latest = await getLatestAgentInvocationForConversation(args.childConversationId);
|
|
1130
|
-
const wasStopped = latest
|
|
1653
|
+
const [latest, stoppedAtMs] = await Promise.all([getLatestAgentInvocationForConversation(args.childConversationId), getConversationStoppedAtMs(args.childConversationId)]);
|
|
1654
|
+
const wasStopped = latest ? latest.status === "stopped" || isChildAgentSessionStopped(latest, stoppedAtMs) : stoppedAtMs !== void 0;
|
|
1131
1655
|
const tree = await stopChildAgentInvocations(args);
|
|
1132
1656
|
if (!tree) return;
|
|
1133
1657
|
await finishStoppedTree(tree, tree.conversationIds, {
|
|
@@ -1208,13 +1732,16 @@ async function stopChildAgentsBelow(conversationId, options) {
|
|
|
1208
1732
|
* ack yet is marked `skipped`.
|
|
1209
1733
|
*/
|
|
1210
1734
|
async function skipUnreadResults(conversationId, nowMs, state) {
|
|
1211
|
-
const
|
|
1735
|
+
const messages = (await getConversationWorkState({
|
|
1212
1736
|
conversationId,
|
|
1213
1737
|
state
|
|
1214
|
-
}))?.messages ?? []
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1738
|
+
}))?.messages ?? [];
|
|
1739
|
+
const invocationIds = [];
|
|
1740
|
+
for (const message of messages) {
|
|
1741
|
+
const sender = await readChildMessageSender(message);
|
|
1742
|
+
const invocation = sender && ownAgentInvocation(sender);
|
|
1743
|
+
if (invocation) invocationIds.push(invocation);
|
|
1744
|
+
}
|
|
1218
1745
|
if (invocationIds.length === 0) return;
|
|
1219
1746
|
await getSqlExecutor().db().update(juniorAgentInvocations).set({
|
|
1220
1747
|
parentMailboxStatus: "skipped",
|
|
@@ -1223,11 +1750,10 @@ async function skipUnreadResults(conversationId, nowMs, state) {
|
|
|
1223
1750
|
}
|
|
1224
1751
|
/**
|
|
1225
1752
|
* Drop the unread replies that Turns on the Conversation loop of the stopped
|
|
1226
|
-
* Conversations left in each mailbox of `mailboxIds`. Such a reply names
|
|
1227
|
-
*
|
|
1228
|
-
*
|
|
1229
|
-
*
|
|
1230
|
-
* stop is stored.
|
|
1753
|
+
* Conversations left in each mailbox of `mailboxIds`. Such a reply names
|
|
1754
|
+
* no work that the stop skips, so the stop drops it by its sender fields.
|
|
1755
|
+
* A reply sent after the stop is dropped when it is read, while the sender
|
|
1756
|
+
* is stopped. Call this after the stop is stored.
|
|
1231
1757
|
*
|
|
1232
1758
|
* A reply that a running Turn already took leaves the mailbox like one that
|
|
1233
1759
|
* it read: the Turn's own ack removes nothing more.
|
|
@@ -1235,23 +1761,15 @@ async function skipUnreadResults(conversationId, nowMs, state) {
|
|
|
1235
1761
|
async function dropUnreadLoopReplies(mailboxIds, stoppedIds, state) {
|
|
1236
1762
|
const stopped = new Set(stoppedIds);
|
|
1237
1763
|
for (const conversationId of mailboxIds) {
|
|
1238
|
-
const
|
|
1764
|
+
const messages = (await getConversationWorkState({
|
|
1239
1765
|
conversationId,
|
|
1240
1766
|
state
|
|
1241
|
-
}))?.messages ?? []
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
});
|
|
1248
|
-
if (replies.length === 0) continue;
|
|
1249
|
-
const senders = await getSqlExecutor().db().select({
|
|
1250
|
-
childConversationId: juniorAgentInvocations.childConversationId,
|
|
1251
|
-
invocationId: juniorAgentInvocations.invocationId
|
|
1252
|
-
}).from(juniorAgentInvocations).where(inArray(juniorAgentInvocations.invocationId, replies.map((reply) => reply.invocationId)));
|
|
1253
|
-
const stoppedSenders = new Set(senders.filter((sender) => stopped.has(sender.childConversationId)).map((sender) => sender.invocationId));
|
|
1254
|
-
const inboundMessageIds = replies.filter((reply) => stoppedSenders.has(reply.invocationId)).map((reply) => reply.messageId);
|
|
1767
|
+
}))?.messages ?? [];
|
|
1768
|
+
const inboundMessageIds = [];
|
|
1769
|
+
for (const message of messages) {
|
|
1770
|
+
const sender = await readChildMessageSender(message);
|
|
1771
|
+
if (sender && !ownAgentInvocation(sender) && stopped.has(sender.conversationId)) inboundMessageIds.push(message.inboundMessageId);
|
|
1772
|
+
}
|
|
1255
1773
|
if (inboundMessageIds.length > 0) await dropPendingMessages({
|
|
1256
1774
|
conversationId,
|
|
1257
1775
|
inboundMessageIds,
|
|
@@ -1265,7 +1783,7 @@ async function dropUnreadLoopReplies(mailboxIds, stoppedIds, state) {
|
|
|
1265
1783
|
* is stored: the parent mailbox lock then drops a later reply.
|
|
1266
1784
|
*/
|
|
1267
1785
|
async function dropOwnUnreadLoopReplies(conversationId, state) {
|
|
1268
|
-
await dropUnreadLoopReplies((await getSqlExecutor().db().
|
|
1786
|
+
await dropUnreadLoopReplies((await getSqlExecutor().db().select({ id: juniorConversations.parentConversationId }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId))).flatMap((parent) => parent.id ? [parent.id] : []), [conversationId], state);
|
|
1269
1787
|
}
|
|
1270
1788
|
/**
|
|
1271
1789
|
* A Thread can hold a person's Turn that waits for sign-in. The stop ends
|
|
@@ -1295,7 +1813,9 @@ async function lockAgentConversationTree(childConversationId) {
|
|
|
1295
1813
|
let parents = conversationIds;
|
|
1296
1814
|
while (parents.length > 0) {
|
|
1297
1815
|
for (const parent of parents) await executor.withLock(getChildAgentLockName(parent), async () => void 0);
|
|
1298
|
-
|
|
1816
|
+
const rows = await executor.db().selectDistinct({ childConversationId: juniorAgentInvocations.childConversationId }).from(juniorAgentInvocations).where(inArray(juniorAgentInvocations.parentConversationId, parents));
|
|
1817
|
+
const withoutInvocations = await executor.db().select({ childConversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(inArray(juniorConversations.parentConversationId, parents), isNotNull(juniorConversations.agentConfig)));
|
|
1818
|
+
parents = [...new Set([...rows, ...withoutInvocations].map((row) => row.childConversationId))].filter((id) => !conversationIds.includes(id));
|
|
1299
1819
|
conversationIds.push(...parents);
|
|
1300
1820
|
}
|
|
1301
1821
|
return conversationIds;
|
|
@@ -1309,8 +1829,12 @@ async function withChildAgentsTaskedAfter(conversationId, conversationIds, taske
|
|
|
1309
1829
|
childConversationId: juniorAgentInvocations.childConversationId,
|
|
1310
1830
|
parentConversationId: juniorAgentInvocations.parentConversationId
|
|
1311
1831
|
}).from(juniorAgentInvocations).where(and(inArray(juniorAgentInvocations.parentConversationId, [...conversationIds]), or(ne(juniorAgentInvocations.parentConversationId, conversationId), gt(juniorAgentInvocations.createdAt, new Date(taskedAfterMs)))));
|
|
1832
|
+
const withoutInvocations = await getSqlExecutor().db().select({
|
|
1833
|
+
childConversationId: juniorConversations.conversationId,
|
|
1834
|
+
parentConversationId: juniorConversations.parentConversationId
|
|
1835
|
+
}).from(juniorConversations).where(and(inArray(juniorConversations.parentConversationId, [...conversationIds]), isNotNull(juniorConversations.agentConfig), or(ne(juniorConversations.parentConversationId, conversationId), gt(juniorConversations.createdAt, new Date(taskedAfterMs)))));
|
|
1312
1836
|
const kept = [conversationId];
|
|
1313
|
-
for (let index = 0; index < kept.length; index += 1) for (const link of links) if (link.parentConversationId === kept[index] && !kept.includes(link.childConversationId)) kept.push(link.childConversationId);
|
|
1837
|
+
for (let index = 0; index < kept.length; index += 1) for (const link of [...links, ...withoutInvocations]) if (link.parentConversationId === kept[index] && !kept.includes(link.childConversationId)) kept.push(link.childConversationId);
|
|
1314
1838
|
return kept;
|
|
1315
1839
|
}
|
|
1316
1840
|
/**
|
|
@@ -1319,7 +1843,9 @@ async function withChildAgentsTaskedAfter(conversationId, conversationIds, taske
|
|
|
1319
1843
|
* parent.
|
|
1320
1844
|
*/
|
|
1321
1845
|
async function stopChildAgentInvocations(args) {
|
|
1322
|
-
|
|
1846
|
+
const db = getSqlExecutor().db();
|
|
1847
|
+
const [owned, child] = await Promise.all([db.select({ invocationId: juniorAgentInvocations.invocationId }).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.parentConversationId, args.parentConversationId), eq(juniorAgentInvocations.childConversationId, args.childConversationId))).limit(1), db.select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(eq(juniorConversations.conversationId, args.childConversationId), eq(juniorConversations.parentConversationId, args.parentConversationId), isNotNull(juniorConversations.agentConfig)))]);
|
|
1848
|
+
if (owned.length === 0 && child.length === 0) return;
|
|
1323
1849
|
return await stopAgentInvocationTree(args.childConversationId, args.nowMs);
|
|
1324
1850
|
}
|
|
1325
1851
|
/**
|
|
@@ -1839,25 +2365,128 @@ function createAgentInvocationWorker(agentRunner, options = {}) {
|
|
|
1839
2365
|
return { status: "completed" };
|
|
1840
2366
|
};
|
|
1841
2367
|
}
|
|
2368
|
+
// src/chat/agent-invocations/parent-message.ts
|
|
2369
|
+
/**
|
|
2370
|
+
* A parent agent task or message to a child that no Agent invocation names.
|
|
2371
|
+
* It is an Event from the parent Conversation (`event.identifier`) with the
|
|
2372
|
+
* Actor and grants of the parent's Turn, and the `spawnAgent` or
|
|
2373
|
+
* `messageAgent` tool call that sent it. Its text is the raw task. `fork`
|
|
2374
|
+
* marks the task of a fork spawn.
|
|
2375
|
+
*/
|
|
2376
|
+
const parentMessageSchema = z.object({
|
|
2377
|
+
actor: actorSchema,
|
|
2378
|
+
credentialContext: credentialContextSchema.optional(),
|
|
2379
|
+
event: z.object({
|
|
2380
|
+
eventType: z.literal(AGENT_PARENT_MESSAGE_EVENT_TYPE),
|
|
2381
|
+
identifier: z.string().min(1),
|
|
2382
|
+
namespace: z.literal(AGENT_INVOCATION_EVENT_NAMESPACE)
|
|
2383
|
+
}),
|
|
2384
|
+
fork: z.literal(true).optional(),
|
|
2385
|
+
kind: z.literal("event"),
|
|
2386
|
+
parentToolCallId: z.string().min(1)
|
|
2387
|
+
});
|
|
2388
|
+
/**
|
|
2389
|
+
* Return the author id of every parent message from one parent. It matches
|
|
2390
|
+
* no other input, so a parent message never shares a Turn with another
|
|
2391
|
+
* sender's input.
|
|
2392
|
+
*/
|
|
2393
|
+
function parentMessageAuthorId(parentConversationId) {
|
|
2394
|
+
return `parent-agent:${parentConversationId}`;
|
|
2395
|
+
}
|
|
2396
|
+
/**
|
|
2397
|
+
* Read the parent message that one mailbox input is, if it is one. Check its
|
|
2398
|
+
* sender with `isFromStoredParent` before it gets any authority.
|
|
2399
|
+
*/
|
|
2400
|
+
function readParentMessage(message) {
|
|
2401
|
+
if (message.source !== "event") return;
|
|
2402
|
+
const parsed = parentMessageSchema.safeParse(message.input.metadata);
|
|
2403
|
+
return parsed.success ? parsed.data : void 0;
|
|
2404
|
+
}
|
|
2405
|
+
/**
|
|
2406
|
+
* Return whether a parent message names the stored parent of the child that
|
|
2407
|
+
* received it, with that parent's author id. The caller drops another
|
|
2408
|
+
* message.
|
|
2409
|
+
*/
|
|
2410
|
+
async function isFromStoredParent(message, parentMessage) {
|
|
2411
|
+
return (message.input.authorId === parentMessageAuthorId(parentMessage.event.identifier) ? await getSqlExecutor().db().select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(eq(juniorConversations.conversationId, message.conversationId), eq(juniorConversations.parentConversationId, parentMessage.event.identifier))) : []).length > 0;
|
|
2412
|
+
}
|
|
2413
|
+
/**
|
|
2414
|
+
* Log a parent message that a child dropped: its sender check failed, or a
|
|
2415
|
+
* stop skipped it. Call it once, where the child drops the message.
|
|
2416
|
+
*/
|
|
2417
|
+
function logDroppedParentMessage(message, parentMessage) {
|
|
2418
|
+
logWarn("agent.parent_message.dropped", {
|
|
2419
|
+
"app.conversation_id": message.conversationId,
|
|
2420
|
+
"app.inbound_message_id": message.inboundMessageId,
|
|
2421
|
+
"app.parent_conversation_id": parentMessage.event.identifier
|
|
2422
|
+
});
|
|
2423
|
+
}
|
|
2424
|
+
/**
|
|
2425
|
+
* Render a parent message as the child model reads it, as an Agent
|
|
2426
|
+
* invocation renders its task.
|
|
2427
|
+
*/
|
|
2428
|
+
async function parentMessageText(message, parentMessage) {
|
|
2429
|
+
return agentInvocationInputText({
|
|
2430
|
+
agentType: (await readAgentConfig(message.conversationId))?.agentType,
|
|
2431
|
+
fork: parentMessage.fork,
|
|
2432
|
+
input: message.input.text,
|
|
2433
|
+
parentToolCallId: parentMessage.parentToolCallId
|
|
2434
|
+
});
|
|
2435
|
+
}
|
|
2436
|
+
/**
|
|
2437
|
+
* Return whether a saved transcript Message is a parent message. Only the
|
|
2438
|
+
* root Turn code saves one, after its sender check.
|
|
2439
|
+
*/
|
|
2440
|
+
function isParentMessageMeta(meta) {
|
|
2441
|
+
return meta?.eventNamespace === "junior" && meta.eventType === "agent.parent_message";
|
|
2442
|
+
}
|
|
2443
|
+
/**
|
|
2444
|
+
* Read when the root Turn code last saved a parent message to one child, or
|
|
2445
|
+
* undefined when it saved none.
|
|
2446
|
+
*/
|
|
2447
|
+
async function readLastParentMessageAtMs(conversationId) {
|
|
2448
|
+
const payload = juniorConversationEvents.payload;
|
|
2449
|
+
const [row] = await getSqlExecutor().db().select({ createdAt: juniorConversationEvents.createdAt }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "message"), sql`${payload}->'meta'->>'eventNamespace' = ${AGENT_INVOCATION_EVENT_NAMESPACE}`, sql`${payload}->'meta'->>'eventType' = ${AGENT_PARENT_MESSAGE_EVENT_TYPE}`)).orderBy(desc(juniorConversationEvents.createdAt)).limit(1);
|
|
2450
|
+
return row?.createdAt.getTime();
|
|
2451
|
+
}
|
|
2452
|
+
/**
|
|
2453
|
+
* Apply the agent config of a child agent to one of its Turns on the root
|
|
2454
|
+
* Turn code. Every Turn keeps the reasoning level. A fork's first Turn
|
|
2455
|
+
* starts with its parent's history. A parent message is the child's
|
|
2456
|
+
* instruction, as on an Agent invocation, also when its Turn resumes
|
|
2457
|
+
* (`savedParentMessage`). `inputs` passed the sender check.
|
|
2458
|
+
*/
|
|
2459
|
+
async function childAgentTurnOptions(args) {
|
|
2460
|
+
const options = await readAgentConfig(args.conversationId);
|
|
2461
|
+
const parentMessage = args.inputs.map(readParentMessage).find((input) => input !== void 0);
|
|
2462
|
+
return {
|
|
2463
|
+
history: parentMessage?.fork && args.history.length === 0 ? await loadForkHistory({
|
|
2464
|
+
parentConversationId: parentMessage.event.identifier,
|
|
2465
|
+
parentToolCallId: parentMessage.parentToolCallId
|
|
2466
|
+
}) : args.history,
|
|
2467
|
+
instruction: parentMessage || args.savedParentMessage ? { provenance: agentInstructionProvenance } : {},
|
|
2468
|
+
run: options?.reasoningLevel ? { reasoning: options.reasoningLevel } : {}
|
|
2469
|
+
};
|
|
2470
|
+
}
|
|
1842
2471
|
// src/chat/agent-invocations/child-input.ts
|
|
1843
2472
|
/**
|
|
1844
|
-
* Read the
|
|
1845
|
-
* finished child work for a result, or the
|
|
2473
|
+
* Read the sender that one result, reply, or message Event names: the
|
|
2474
|
+
* finished child work for a result, or the sender for a reply or message.
|
|
1846
2475
|
*/
|
|
1847
2476
|
function childAgentInput(message) {
|
|
1848
2477
|
const metadata = message.input.metadata;
|
|
1849
2478
|
if (!isEventMailboxMetadata(metadata) || metadata.event.namespace !== "junior") return;
|
|
1850
2479
|
if (metadata.event.eventType === "agent.message") return {
|
|
1851
|
-
|
|
1852
|
-
|
|
2480
|
+
kind: "message",
|
|
2481
|
+
senderId: metadata.event.identifier
|
|
1853
2482
|
};
|
|
1854
2483
|
if (metadata.event.eventType === "agent.reply") return {
|
|
1855
|
-
|
|
1856
|
-
|
|
2484
|
+
kind: "reply",
|
|
2485
|
+
senderId: metadata.event.identifier
|
|
1857
2486
|
};
|
|
1858
2487
|
return isAgentInvocationResultEventType(metadata.event.eventType) ? {
|
|
1859
|
-
|
|
1860
|
-
|
|
2488
|
+
kind: "result",
|
|
2489
|
+
senderId: metadata.event.identifier
|
|
1861
2490
|
} : void 0;
|
|
1862
2491
|
}
|
|
1863
2492
|
/**
|
|
@@ -1865,11 +2494,14 @@ function childAgentInput(message) {
|
|
|
1865
2494
|
* agent status all read this, so they agree on which input starts work.
|
|
1866
2495
|
*
|
|
1867
2496
|
* A parent task or message goes to its agent invocation. `latest` is the
|
|
1868
|
-
* Conversation's newest agent invocation; a root has none.
|
|
1869
|
-
*
|
|
1870
|
-
*
|
|
1871
|
-
*
|
|
1872
|
-
*
|
|
2497
|
+
* Conversation's newest agent invocation; a root has none. A parent message
|
|
2498
|
+
* that no Agent invocation names is dropped when it does not come from the
|
|
2499
|
+
* stored parent. With an open Agent invocation, that parent message, a Watch
|
|
2500
|
+
* Event, and input from a child agent go to an agent invocation, and so do a
|
|
2501
|
+
* result, and input to a child that waits for its own child agents
|
|
2502
|
+
* (`replaced`). A stopped child drops input from its own child agents, also
|
|
2503
|
+
* input sent before the stop. A session stop at `stoppedAtMs` skips Events
|
|
2504
|
+
* as `skipInputAfterConversationStop` does.
|
|
1873
2505
|
*
|
|
1874
2506
|
* TODO(dcramer): Drop the agent invocation route with the legacy child worker
|
|
1875
2507
|
* (#3060 step 7).
|
|
@@ -1878,13 +2510,19 @@ async function routeChildInput(message, latest, stoppedAtMs) {
|
|
|
1878
2510
|
if (isPersonInput(message.source)) return "Conversation loop";
|
|
1879
2511
|
if (isAgentInvocationInput(message)) return "agent invocation";
|
|
1880
2512
|
const open = latest !== void 0 && !isTerminalAgentInvocation(latest);
|
|
2513
|
+
const parentMessage = readParentMessage(message);
|
|
2514
|
+
if (parentMessage) {
|
|
2515
|
+
if (!await isFromStoredParent(message, parentMessage)) return "dropped";
|
|
2516
|
+
if (open) return "agent invocation";
|
|
2517
|
+
return isSkippedAfterConversationStop(message, stoppedAtMs) ? "dropped" : "Conversation loop";
|
|
2518
|
+
}
|
|
1881
2519
|
const input = childAgentInput(message);
|
|
1882
2520
|
if (!input) {
|
|
1883
2521
|
if (open && isEventMailboxMetadata(message.input.metadata)) return "agent invocation";
|
|
1884
2522
|
return isSkippedAfterConversationStop(message, stoppedAtMs) ? "dropped" : "Conversation loop";
|
|
1885
2523
|
}
|
|
1886
2524
|
if (latest && isStoppedAgentInvocation(latest)) return "dropped";
|
|
1887
|
-
if (await isSkippedAgentResult(input,
|
|
2525
|
+
if (await isSkippedAgentResult(input, message)) return "dropped";
|
|
1888
2526
|
if (latest && (open || input.kind === "result" || latest.parentMailboxStatus === "replaced")) return "agent invocation";
|
|
1889
2527
|
return isSkippedAfterConversationStop(message, stoppedAtMs) ? "dropped" : "Conversation loop";
|
|
1890
2528
|
}
|
|
@@ -1896,29 +2534,311 @@ async function routeChildInput(message, latest, stoppedAtMs) {
|
|
|
1896
2534
|
* its own: the stop drops it from the parent's mailbox. While the sending
|
|
1897
2535
|
* child is stopped, a reply that it sent after the stop is also dropped.
|
|
1898
2536
|
*/
|
|
1899
|
-
async function isSkippedAgentResult(input,
|
|
2537
|
+
async function isSkippedAgentResult(input, message) {
|
|
1900
2538
|
if (input.kind === "message") return false;
|
|
1901
|
-
const
|
|
2539
|
+
const { invocation, sender } = await getChildAgentInputSender(message, input);
|
|
2540
|
+
const skipped = invocation !== void 0 && isTerminalAgentInvocation(invocation) && invocation.parentMailboxStatus === "skipped";
|
|
1902
2541
|
if (input.kind === "result") return skipped;
|
|
1903
|
-
if (skipped
|
|
1904
|
-
|
|
2542
|
+
if (skipped) {
|
|
2543
|
+
const fields = await readChildMessageSender(message);
|
|
2544
|
+
if (!fields || ownAgentInvocation(fields)) return true;
|
|
2545
|
+
}
|
|
2546
|
+
const senderStoppedAtMs = await getConversationStoppedAtMs(sender.childConversationId);
|
|
1905
2547
|
return senderStoppedAtMs !== void 0 && message.createdAtMs >= senderStoppedAtMs;
|
|
1906
2548
|
}
|
|
1907
2549
|
/**
|
|
1908
|
-
* Read the
|
|
1909
|
-
*
|
|
2550
|
+
* Read the sender of one child Conversation that no Agent invocation names,
|
|
2551
|
+
* from its parent edge and its binding. A Conversation without a parent has
|
|
2552
|
+
* none.
|
|
2553
|
+
*/
|
|
2554
|
+
async function readChildConversationSender(childConversationId) {
|
|
2555
|
+
const parent = alias(juniorConversations, "parent");
|
|
2556
|
+
const [row] = await getSqlExecutor().db().select({
|
|
2557
|
+
agentName: juniorAgentBindings.name,
|
|
2558
|
+
parentConversationId: parent.conversationId,
|
|
2559
|
+
title: juniorConversations.title
|
|
2560
|
+
}).from(juniorConversations).innerJoin(parent, eq(parent.conversationId, juniorConversations.parentConversationId)).leftJoin(juniorAgentBindings, eq(juniorAgentBindings.childConversationId, juniorConversations.conversationId)).where(eq(juniorConversations.conversationId, childConversationId));
|
|
2561
|
+
return row ? {
|
|
2562
|
+
...row.agentName ? { agentName: row.agentName } : void 0,
|
|
2563
|
+
childConversationId,
|
|
2564
|
+
parentConversationId: row.parentConversationId,
|
|
2565
|
+
...row.title ? { title: row.title } : void 0
|
|
2566
|
+
} : void 0;
|
|
2567
|
+
}
|
|
2568
|
+
/**
|
|
2569
|
+
* Read the sender of one result, reply, or message and check that it is a
|
|
2570
|
+
* child of the Conversation that received it. The Agent invocation that the
|
|
2571
|
+
* input names wins. A reply or message from a child that no Agent invocation
|
|
2572
|
+
* names comes from its child Conversation, and has no `invocation`.
|
|
2573
|
+
*/
|
|
2574
|
+
async function getChildAgentInputSender(message, input) {
|
|
2575
|
+
const invocation = await getAgentInvocation(input.senderId);
|
|
2576
|
+
const sender = invocation ? input.kind === "result" && !isTerminalAgentInvocation(invocation) ? void 0 : invocation : input.kind === "result" ? void 0 : await readChildConversationSender(input.senderId);
|
|
2577
|
+
if (!sender || sender.parentConversationId !== message.conversationId) throw new Error(`Agent invocation ${input.kind} ${input.senderId} does not belong to ${message.conversationId}`);
|
|
2578
|
+
return invocation ? {
|
|
2579
|
+
invocation,
|
|
2580
|
+
sender
|
|
2581
|
+
} : { sender };
|
|
2582
|
+
}
|
|
2583
|
+
// src/chat/agent-invocations/store.ts
|
|
2584
|
+
/** Statuses of a finished agent invocation. */
|
|
2585
|
+
const TERMINAL_AGENT_INVOCATION_STATUSES = [
|
|
2586
|
+
"blocked",
|
|
2587
|
+
"completed",
|
|
2588
|
+
"failed",
|
|
2589
|
+
"stopped"
|
|
2590
|
+
];
|
|
2591
|
+
/** Statuses of an agent invocation that owns its child's Turn. */
|
|
2592
|
+
const ACTIVE_AGENT_INVOCATION_STATUSES = ["running", "paused"];
|
|
2593
|
+
/** Statuses of an agent invocation that has not finished. */
|
|
2594
|
+
const NON_TERMINAL_AGENT_INVOCATION_STATUSES = [
|
|
2595
|
+
"pending",
|
|
2596
|
+
"running",
|
|
2597
|
+
"paused"
|
|
2598
|
+
];
|
|
2599
|
+
/** Parse one agent invocation row. */
|
|
2600
|
+
function invocationFromRow(row) {
|
|
2601
|
+
return agentInvocationSchema.parse({
|
|
2602
|
+
actor: row.actor,
|
|
2603
|
+
...row.agentName ? { agentName: row.agentName } : void 0,
|
|
2604
|
+
childConversationId: row.childConversationId,
|
|
2605
|
+
createdAtMs: row.createdAt.getTime(),
|
|
2606
|
+
...row.credentialContext ? { credentialContext: row.credentialContext } : void 0,
|
|
2607
|
+
destination: row.destination,
|
|
2608
|
+
...row.errorMessage !== null ? { errorMessage: row.errorMessage } : void 0,
|
|
2609
|
+
input: row.input,
|
|
2610
|
+
invocationId: row.invocationId,
|
|
2611
|
+
mailboxStatus: row.mailboxStatus,
|
|
2612
|
+
parentConversationId: row.parentConversationId,
|
|
2613
|
+
...row.parentMailboxStatus ? { parentMailboxStatus: row.parentMailboxStatus } : void 0,
|
|
2614
|
+
...row.parentToolCallId ? { parentToolCallId: row.parentToolCallId } : void 0,
|
|
2615
|
+
...row.agentType ? { agentType: row.agentType } : void 0,
|
|
2616
|
+
...row.fork ? { fork: true } : void 0,
|
|
2617
|
+
...row.reasoningLevel ? { reasoningLevel: row.reasoningLevel } : void 0,
|
|
2618
|
+
...row.result !== null ? { result: row.result } : void 0,
|
|
2619
|
+
source: row.source,
|
|
2620
|
+
status: row.status,
|
|
2621
|
+
...row.terminalAt ? { terminalAtMs: row.terminalAt.getTime() } : void 0,
|
|
2622
|
+
...row.title ? { title: row.title } : void 0,
|
|
2623
|
+
updatedAtMs: row.updatedAt.getTime()
|
|
2624
|
+
});
|
|
2625
|
+
}
|
|
2626
|
+
/** Read one durable agent invocation. */
|
|
2627
|
+
async function getAgentInvocation(invocationId) {
|
|
2628
|
+
const rows = await getSqlExecutor().db().select().from(juniorAgentInvocations).where(eq(juniorAgentInvocations.invocationId, invocationId));
|
|
2629
|
+
return rows[0] ? invocationFromRow(rows[0]) : void 0;
|
|
2630
|
+
}
|
|
2631
|
+
/** List the agent invocations of one child Conversation in the given statuses. */
|
|
2632
|
+
async function listAgentInvocationsForConversation(childConversationId, statuses) {
|
|
2633
|
+
return (await getSqlExecutor().db().select().from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.childConversationId, childConversationId), inArray(juniorAgentInvocations.status, [...statuses]))).orderBy(asc(juniorAgentInvocations.createdAt))).map(invocationFromRow);
|
|
2634
|
+
}
|
|
2635
|
+
/** Resolve the single invocation that may resume for one child conversation. */
|
|
2636
|
+
async function getActiveAgentInvocationForConversation(childConversationId) {
|
|
2637
|
+
const active = await listAgentInvocationsForConversation(childConversationId, ACTIVE_AGENT_INVOCATION_STATUSES);
|
|
2638
|
+
if (active.length > 1) throw new Error(`Child conversation ${childConversationId} has multiple active agent invocations`);
|
|
2639
|
+
return active[0];
|
|
2640
|
+
}
|
|
2641
|
+
/** Read the newest agent invocation of one child Conversation. */
|
|
2642
|
+
async function getLatestAgentInvocationForConversation(childConversationId) {
|
|
2643
|
+
const rows = await getSqlExecutor().db().select().from(juniorAgentInvocations).where(eq(juniorAgentInvocations.childConversationId, childConversationId)).orderBy(desc(juniorAgentInvocations.createdAt)).limit(1);
|
|
2644
|
+
return rows[0] ? invocationFromRow(rows[0]) : void 0;
|
|
2645
|
+
}
|
|
2646
|
+
/**
|
|
2647
|
+
* Read the name, agent type, fork flag, and newest task title of one child
|
|
2648
|
+
* Conversation, for labels. Agent invocations that give a nested result to
|
|
2649
|
+
* the child have no title, so an agent invocation with a title comes first.
|
|
2650
|
+
* Each agent invocation keeps the child's agent type, but only the one that
|
|
2651
|
+
* started a fork has `fork` set, so the flag reads every agent invocation.
|
|
2652
|
+
* A child that no Agent invocation names reads its binding, title, and
|
|
2653
|
+
* agent config.
|
|
2654
|
+
*/
|
|
2655
|
+
async function getChildAgentLabel(childConversationId) {
|
|
2656
|
+
const [row] = await getSqlExecutor().db().select({
|
|
2657
|
+
agentName: juniorAgentInvocations.agentName,
|
|
2658
|
+
agentType: juniorAgentInvocations.agentType,
|
|
2659
|
+
fork: sql`bool_or(${juniorAgentInvocations.fork}) over ()`,
|
|
2660
|
+
title: juniorAgentInvocations.title
|
|
2661
|
+
}).from(juniorAgentInvocations).where(eq(juniorAgentInvocations.childConversationId, childConversationId)).orderBy(sql`${juniorAgentInvocations.title} is null`, desc(juniorAgentInvocations.createdAt)).limit(1);
|
|
2662
|
+
if (row) return row;
|
|
2663
|
+
const [sender, options] = await Promise.all([readChildConversationSender(childConversationId), readAgentConfig(childConversationId)]);
|
|
2664
|
+
return sender && options ? {
|
|
2665
|
+
agentName: sender.agentName ?? null,
|
|
2666
|
+
agentType: options.agentType ?? null,
|
|
2667
|
+
fork: options.fork ?? false,
|
|
2668
|
+
title: sender.title ?? null
|
|
2669
|
+
} : void 0;
|
|
2670
|
+
}
|
|
2671
|
+
/**
|
|
2672
|
+
* List the open agent invocations that run on one Conversation or on its
|
|
2673
|
+
* child agents, oldest first. Open-work checks read this once and filter it.
|
|
1910
2674
|
*/
|
|
1911
|
-
async function
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
2675
|
+
async function listOpenAgentInvocations(conversationId) {
|
|
2676
|
+
return (await getSqlExecutor().db().select().from(juniorAgentInvocations).where(and(or(eq(juniorAgentInvocations.childConversationId, conversationId), eq(juniorAgentInvocations.parentConversationId, conversationId)), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES))).orderBy(asc(juniorAgentInvocations.createdAt))).map(invocationFromRow);
|
|
2677
|
+
}
|
|
2678
|
+
/**
|
|
2679
|
+
* Return whether a terminal agent invocation sends its result to the parent.
|
|
2680
|
+
* A child's final response stays in its Conversation, and a `reply` that
|
|
2681
|
+
* reached the parent (one of `parentMessages`) answered for the Agent
|
|
2682
|
+
* invocation. A failure after that, such as a lost worker before the
|
|
2683
|
+
* Turn was saved, is not sent either.
|
|
2684
|
+
*/
|
|
2685
|
+
function sendsResultToParent(invocation, parentMessages) {
|
|
2686
|
+
const replied = hasAgentInvocationReply(parentMessages, invocation.invocationId);
|
|
2687
|
+
switch (invocation.status) {
|
|
2688
|
+
case "completed": return !replied && Boolean(invocation.result?.trim());
|
|
2689
|
+
case "failed": return !replied;
|
|
2690
|
+
default: return true;
|
|
2691
|
+
}
|
|
2692
|
+
}
|
|
2693
|
+
/**
|
|
2694
|
+
* Return whether a child Conversation has work that will start another agent
|
|
2695
|
+
* invocation on it: another open agent invocation, an open child agent, or a
|
|
2696
|
+
* child agent result that is sent but still waits in its mailbox. A child
|
|
2697
|
+
* agent that no Agent invocation names is open as `listAgents` shows it,
|
|
2698
|
+
* and its unread result or reply also waits.
|
|
2699
|
+
*/
|
|
2700
|
+
async function hasOpenChildWork(invocation) {
|
|
2701
|
+
const conversationId = invocation.childConversationId;
|
|
2702
|
+
if ((await listOpenAgentInvocations(conversationId)).some((row) => row.invocationId !== invocation.invocationId) || (await listOpenChildAgentsWithoutAgentInvocations(conversationId)).length > 0) return true;
|
|
2703
|
+
const work = await getConversationWorkState({ conversationId });
|
|
2704
|
+
for (const message of work?.messages ?? []) {
|
|
2705
|
+
const sender = await readChildMessageSender(message);
|
|
2706
|
+
if (sender && !sender.agentInvocationId) return true;
|
|
2707
|
+
}
|
|
2708
|
+
const marked = await getSqlExecutor().db().select({
|
|
2709
|
+
invocationId: juniorAgentInvocations.invocationId,
|
|
2710
|
+
parentMailboxStatus: juniorAgentInvocations.parentMailboxStatus,
|
|
2711
|
+
result: juniorAgentInvocations.result,
|
|
2712
|
+
status: juniorAgentInvocations.status
|
|
2713
|
+
}).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.parentConversationId, conversationId), inArray(juniorAgentInvocations.parentMailboxStatus, ["pending", "appended"])));
|
|
2714
|
+
if (marked.length === 0) return false;
|
|
2715
|
+
const unread = new Set(work?.messages.map((message) => message.inboundMessageId));
|
|
2716
|
+
const parentMessages = await listChildMessages(work?.execution.inboundMessageIds ?? [], work?.execution.messageSenders ?? {});
|
|
2717
|
+
return marked.some((row) => sendsResultToParent(row, parentMessages) && (row.parentMailboxStatus === "pending" || unread.has(getAgentInvocationResultMessageId(row.invocationId))));
|
|
2718
|
+
}
|
|
2719
|
+
/** List bounded invocation records whose mailbox append still needs repair. */
|
|
2720
|
+
async function listPendingAgentInvocationMailboxAppends(limit = 100) {
|
|
2721
|
+
return (await getSqlExecutor().db().select().from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.mailboxStatus, "pending"), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES))).orderBy(asc(juniorAgentInvocations.createdAt)).limit(limit)).map(invocationFromRow);
|
|
2722
|
+
}
|
|
2723
|
+
/** List terminal agent invocation results that still need a parent mailbox append. */
|
|
2724
|
+
async function listPendingAgentInvocationResults(limit = 100) {
|
|
2725
|
+
return (await getSqlExecutor().db().select().from(juniorAgentInvocations).where(eq(juniorAgentInvocations.parentMailboxStatus, "pending")).orderBy(asc(juniorAgentInvocations.terminalAt)).limit(limit)).map(invocationFromRow).filter(isTerminalAgentInvocation);
|
|
2726
|
+
}
|
|
2727
|
+
/**
|
|
2728
|
+
* Send a `replaced` result to the parent now. A stop ended the open work of
|
|
2729
|
+
* the child, so no later agent invocation sends the report.
|
|
2730
|
+
*/
|
|
2731
|
+
async function reportReplacedAgentInvocation(invocationId, nowMs = Date.now()) {
|
|
2732
|
+
await getSqlExecutor().db().update(juniorAgentInvocations).set({
|
|
2733
|
+
parentMailboxStatus: "pending",
|
|
2734
|
+
updatedAt: new Date(nowMs)
|
|
2735
|
+
}).where(and(eq(juniorAgentInvocations.invocationId, invocationId), eq(juniorAgentInvocations.parentMailboxStatus, "replaced")));
|
|
2736
|
+
return await getAgentInvocation(invocationId);
|
|
2737
|
+
}
|
|
2738
|
+
/**
|
|
2739
|
+
* Send the `replaced` result of a child Conversation when its open child work
|
|
2740
|
+
* ended and sent it nothing, such as a helper that ended with `noReply`. No
|
|
2741
|
+
* later agent invocation of the child would send the report. Input from its
|
|
2742
|
+
* own child agents that still waits in its mailbox starts one, so that one
|
|
2743
|
+
* reports instead.
|
|
2744
|
+
*/
|
|
2745
|
+
async function reportReplacedWithoutOpenWork(conversationId, nowMs = Date.now()) {
|
|
2746
|
+
const latest = await getLatestAgentInvocationForConversation(conversationId);
|
|
2747
|
+
if (!latest || !isTerminalAgentInvocation(latest) || latest.parentMailboxStatus !== "replaced" || await hasOpenChildWork(latest)) return;
|
|
2748
|
+
if ((await getConversationWorkState({ conversationId }))?.messages.some(isChildAgentInputMessage)) return;
|
|
2749
|
+
return await reportReplacedAgentInvocation(latest.invocationId, nowMs);
|
|
2750
|
+
}
|
|
2751
|
+
function isChildAgentInputMessage(message) {
|
|
2752
|
+
const metadata = message.input.metadata;
|
|
2753
|
+
return isEventMailboxMetadata(metadata) && metadata.event.namespace === "junior" && metadata.event.eventType !== "agent.parent_message";
|
|
2754
|
+
}
|
|
2755
|
+
/** Record that one terminal result is in its parent mailbox. */
|
|
2756
|
+
async function markAgentInvocationParentMailboxAppended(invocationId, nowMs = Date.now()) {
|
|
2757
|
+
await getSqlExecutor().db().update(juniorAgentInvocations).set({
|
|
2758
|
+
parentMailboxStatus: "appended",
|
|
2759
|
+
updatedAt: new Date(nowMs)
|
|
2760
|
+
}).where(and(eq(juniorAgentInvocations.invocationId, invocationId), eq(juniorAgentInvocations.parentMailboxStatus, "pending")));
|
|
2761
|
+
}
|
|
2762
|
+
/** Record that the invocation's idempotent mailbox append completed. */
|
|
2763
|
+
async function markAgentInvocationMailboxAppended(invocationId, nowMs = Date.now()) {
|
|
2764
|
+
await getSqlExecutor().db().update(juniorAgentInvocations).set({
|
|
2765
|
+
mailboxStatus: "appended",
|
|
2766
|
+
updatedAt: new Date(nowMs)
|
|
2767
|
+
}).where(eq(juniorAgentInvocations.invocationId, invocationId));
|
|
2768
|
+
}
|
|
2769
|
+
/** Mark one non-terminal invocation as actively executing. */
|
|
2770
|
+
async function markAgentInvocationRunning(invocationId, nowMs = Date.now()) {
|
|
2771
|
+
await getSqlExecutor().db().update(juniorAgentInvocations).set({
|
|
2772
|
+
status: "running",
|
|
2773
|
+
updatedAt: new Date(nowMs)
|
|
2774
|
+
}).where(and(eq(juniorAgentInvocations.invocationId, invocationId), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES)));
|
|
2775
|
+
return await getAgentInvocation(invocationId);
|
|
2776
|
+
}
|
|
2777
|
+
/** Mark one invocation as waiting for another shared execution slice. */
|
|
2778
|
+
async function markAgentInvocationPaused(invocationId, nowMs = Date.now()) {
|
|
2779
|
+
await getSqlExecutor().db().update(juniorAgentInvocations).set({
|
|
2780
|
+
status: "paused",
|
|
2781
|
+
updatedAt: new Date(nowMs)
|
|
2782
|
+
}).where(and(eq(juniorAgentInvocations.invocationId, invocationId), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES)));
|
|
2783
|
+
}
|
|
2784
|
+
/**
|
|
2785
|
+
* Persist one terminal invocation result without overwriting an earlier
|
|
2786
|
+
* result. The same write marks the result for the parent mailbox. If the
|
|
2787
|
+
* child still has open work, the result is `replaced`: the parent gets one
|
|
2788
|
+
* report, from the agent invocation that finishes the child's work.
|
|
2789
|
+
* `reportNow` sends the result even then, when that open work does not
|
|
2790
|
+
* continue this task.
|
|
2791
|
+
*/
|
|
2792
|
+
async function completeAgentInvocation(args) {
|
|
2793
|
+
const nowMs = args.nowMs ?? Date.now();
|
|
2794
|
+
const current = await getAgentInvocation(args.invocationId);
|
|
2795
|
+
if (!current || isTerminalAgentInvocation(current)) return current;
|
|
2796
|
+
const parentMailboxStatus = !args.reportNow && args.status !== "stopped" && await hasOpenChildWork(current) ? "replaced" : "pending";
|
|
2797
|
+
await getSqlExecutor().db().update(juniorAgentInvocations).set({
|
|
2798
|
+
status: args.status,
|
|
2799
|
+
result: args.status === "completed" ? args.result : null,
|
|
2800
|
+
errorMessage: args.status === "completed" ? null : args.errorMessage,
|
|
2801
|
+
parentMailboxStatus,
|
|
2802
|
+
terminalAt: new Date(nowMs),
|
|
2803
|
+
updatedAt: new Date(nowMs)
|
|
2804
|
+
}).where(and(eq(juniorAgentInvocations.invocationId, args.invocationId), inArray(juniorAgentInvocations.status, NON_TERMINAL_AGENT_INVOCATION_STATUSES)));
|
|
2805
|
+
return await getAgentInvocation(args.invocationId);
|
|
2806
|
+
}
|
|
2807
|
+
/**
|
|
2808
|
+
* End a pending agent invocation whose input the running agent invocation of
|
|
2809
|
+
* the same child read as a steering message. The running agent invocation
|
|
2810
|
+
* reports for both, so this one is never sent to the parent.
|
|
2811
|
+
*/
|
|
2812
|
+
async function markAgentInvocationSteered(invocationId, nowMs = Date.now()) {
|
|
2813
|
+
await getSqlExecutor().db().update(juniorAgentInvocations).set({
|
|
2814
|
+
status: "completed",
|
|
2815
|
+
result: "",
|
|
2816
|
+
parentMailboxStatus: "steered",
|
|
2817
|
+
terminalAt: new Date(nowMs),
|
|
2818
|
+
updatedAt: new Date(nowMs)
|
|
2819
|
+
}).where(and(eq(juniorAgentInvocations.invocationId, invocationId), eq(juniorAgentInvocations.status, "pending")));
|
|
2820
|
+
return await getAgentInvocation(invocationId);
|
|
2821
|
+
}
|
|
2822
|
+
/** Return whether an agent invocation has finished. */
|
|
2823
|
+
function isTerminalAgentInvocation(invocation) {
|
|
2824
|
+
return TERMINAL_AGENT_INVOCATION_STATUSES.includes(invocation.status);
|
|
2825
|
+
}
|
|
2826
|
+
/**
|
|
2827
|
+
* Return whether the newest agent invocation of a child shows a stop. A tree
|
|
2828
|
+
* stop leaves a `replaced` agent invocation with its finished status and
|
|
2829
|
+
* marks it `skipped`, so that also means stopped.
|
|
2830
|
+
*/
|
|
2831
|
+
function isStoppedAgentInvocation(invocation) {
|
|
2832
|
+
return invocation.status === "stopped" || isTerminalAgentInvocation(invocation) && invocation.parentMailboxStatus === "skipped";
|
|
1915
2833
|
}
|
|
1916
2834
|
// src/chat/agent-invocations/list.ts
|
|
1917
2835
|
function isChildAgentResult(status) {
|
|
1918
2836
|
return CHILD_AGENT_RESULTS.includes(status);
|
|
1919
2837
|
}
|
|
2838
|
+
const childAgentKindSchema = z.enum(CHILD_AGENT_KINDS);
|
|
1920
2839
|
/** Bound the agent invocations that one child agent listing reads. */
|
|
1921
2840
|
const CHILD_AGENT_LIST_INVOCATION_LIMIT = 200;
|
|
2841
|
+
const CONVERSATION_LOOP_CHECK_CONCURRENCY = 8;
|
|
1922
2842
|
/** Return whether a child's session stopped after its latest agent invocation. */
|
|
1923
2843
|
function isChildAgentSessionStopped(latest, stoppedAtMs) {
|
|
1924
2844
|
return stoppedAtMs !== void 0 && stoppedAtMs >= latest.createdAtMs;
|
|
@@ -1949,9 +2869,14 @@ function childAgentFromInvocations(invocations, resultInvocationIds, facts) {
|
|
|
1949
2869
|
/**
|
|
1950
2870
|
* List the direct child agents of one parent Conversation, with the newest
|
|
1951
2871
|
* activity first. The state comes from SQL agent invocation records, not from
|
|
1952
|
-
* model output.
|
|
2872
|
+
* model output. A child that no agent invocation names shows the state of
|
|
2873
|
+
* its Turns and mailbox.
|
|
1953
2874
|
*/
|
|
1954
2875
|
async function listChildAgents(parentConversationId) {
|
|
2876
|
+
const [withInvocations, withoutInvocations] = await Promise.all([listChildAgentsFromInvocations(parentConversationId), listChildAgentsWithoutAgentInvocations(parentConversationId)]);
|
|
2877
|
+
return [...withInvocations, ...withoutInvocations].sort((left, right) => right.updatedAtMs - left.updatedAtMs);
|
|
2878
|
+
}
|
|
2879
|
+
async function listChildAgentsFromInvocations(parentConversationId) {
|
|
1955
2880
|
const db = getSqlExecutor().db();
|
|
1956
2881
|
const rows = await db.select().from(juniorAgentInvocations).where(eq(juniorAgentInvocations.parentConversationId, parentConversationId)).orderBy(desc(juniorAgentInvocations.createdAt)).limit(CHILD_AGENT_LIST_INVOCATION_LIMIT);
|
|
1957
2882
|
if (rows.length === 0) return [];
|
|
@@ -1971,14 +2896,77 @@ async function listChildAgents(parentConversationId) {
|
|
|
1971
2896
|
parentConversationId: juniorConversations.parentConversationId,
|
|
1972
2897
|
stoppedAt: juniorConversations.stoppedAt
|
|
1973
2898
|
}).from(juniorConversations).where(inArray(juniorConversations.conversationId, [...byChild.keys()]));
|
|
1974
|
-
const
|
|
2899
|
+
const active = conversations.filter((row) => row.executionStatus === "pending" || row.executionStatus === "running" || row.executionStatus === "paused");
|
|
2900
|
+
const activeIds = active.map((row) => row.conversationId);
|
|
2901
|
+
const [workStates, mailboxTurnSources] = await Promise.all([getConversationWorkStates(activeIds), listActiveMailboxTurnSources(activeIds)]);
|
|
2902
|
+
const limit = pLimit(CONVERSATION_LOOP_CHECK_CONCURRENCY);
|
|
2903
|
+
const onConversationLoop = new Set((await Promise.all(active.map((row) => limit(async () => await runsOnConversationLoop(conversationKindFromRow(row), byChild.get(row.conversationId)[0], row.stoppedAt?.getTime(), workStates.get(row.conversationId)?.execution.pendingMessages ?? [], mailboxTurnSources.get(row.conversationId) ?? []) ? row.conversationId : void 0)))).filter((id) => id !== void 0));
|
|
1975
2904
|
const factsByChild = new Map(conversations.map((row) => [row.conversationId, {
|
|
1976
2905
|
...row.archivedAt ? { archivedAtMs: row.archivedAt.getTime() } : void 0,
|
|
1977
2906
|
kind: conversationKindFromRow(row) === "thread" ? "thread" : "task",
|
|
1978
2907
|
...row.stoppedAt ? { stoppedAtMs: row.stoppedAt.getTime() } : void 0,
|
|
1979
2908
|
onConversationLoop: onConversationLoop.has(row.conversationId)
|
|
1980
2909
|
}]));
|
|
1981
|
-
return [...byChild.entries()].map(([childConversationId, invocations]) => childAgentFromInvocations(invocations, resultInvocationIds, factsByChild.get(childConversationId) ?? { kind: "task" }))
|
|
2910
|
+
return [...byChild.entries()].map(([childConversationId, invocations]) => childAgentFromInvocations(invocations, resultInvocationIds, factsByChild.get(childConversationId) ?? { kind: "task" }));
|
|
2911
|
+
}
|
|
2912
|
+
/**
|
|
2913
|
+
* List the ids of the child agents of one parent that no agent invocation
|
|
2914
|
+
* names and that have open work.
|
|
2915
|
+
*/
|
|
2916
|
+
async function listOpenChildAgentsWithoutAgentInvocations(parentConversationId) {
|
|
2917
|
+
return (await listChildAgentsWithoutAgentInvocations(parentConversationId)).filter((child) => NON_TERMINAL_AGENT_INVOCATION_STATUSES.includes(child.status)).map((child) => child.childConversationId);
|
|
2918
|
+
}
|
|
2919
|
+
/**
|
|
2920
|
+
* Count the open parent messages of one child that no Agent invocation
|
|
2921
|
+
* names: each one that waits in its mailbox, and each open Turn, which runs
|
|
2922
|
+
* one. This is the queue that `MAX_OPEN_AGENT_INVOCATIONS_PER_CHILD` caps.
|
|
2923
|
+
*/
|
|
2924
|
+
async function countOpenParentMessages(childConversationId) {
|
|
2925
|
+
const [turns, work] = await Promise.all([listActiveMailboxTurns(childConversationId), getConversationWorkState({ conversationId: childConversationId })]);
|
|
2926
|
+
return turns.length + (work?.messages ?? []).filter((message) => readParentMessage(message) !== void 0).length;
|
|
2927
|
+
}
|
|
2928
|
+
/**
|
|
2929
|
+
* List the child agents of one parent that no agent invocation names. Each
|
|
2930
|
+
* stores its agent config, so older children of a parent, such as ones
|
|
2931
|
+
* that a removed feature created, are not listed. A child is `running` while
|
|
2932
|
+
* a Turn or mailbox input that answers its parent is open, and is `failed`
|
|
2933
|
+
* when its last Turn failed.
|
|
2934
|
+
*
|
|
2935
|
+
* TODO(dcramer): Make this the only listing when #3060 step 7 drops the
|
|
2936
|
+
* agent invocation table.
|
|
2937
|
+
*/
|
|
2938
|
+
async function listChildAgentsWithoutAgentInvocations(parentConversationId) {
|
|
2939
|
+
const db = getSqlExecutor().db();
|
|
2940
|
+
const rows = await db.select({
|
|
2941
|
+
agentName: juniorAgentBindings.name,
|
|
2942
|
+
archivedAt: juniorConversations.archivedAt,
|
|
2943
|
+
conversationId: juniorConversations.conversationId,
|
|
2944
|
+
executionStatus: juniorConversations.executionStatus,
|
|
2945
|
+
executionUpdatedAt: juniorConversations.executionUpdatedAt,
|
|
2946
|
+
kind: juniorConversations.kind,
|
|
2947
|
+
parentConversationId: juniorConversations.parentConversationId,
|
|
2948
|
+
stoppedAt: juniorConversations.stoppedAt,
|
|
2949
|
+
title: juniorConversations.title,
|
|
2950
|
+
updatedAt: juniorConversations.updatedAt
|
|
2951
|
+
}).from(juniorConversations).leftJoin(juniorAgentBindings, eq(juniorAgentBindings.childConversationId, juniorConversations.conversationId)).where(and(eq(juniorConversations.parentConversationId, parentConversationId), isNotNull(juniorConversations.agentConfig), notExists(db.select({ invocationId: juniorAgentInvocations.invocationId }).from(juniorAgentInvocations).where(eq(juniorAgentInvocations.childConversationId, juniorConversations.conversationId))))).limit(CHILD_AGENT_LIST_INVOCATION_LIMIT);
|
|
2952
|
+
const ids = rows.map((row) => row.conversationId);
|
|
2953
|
+
const [workStates, mailboxTurnSources] = await Promise.all([getConversationWorkStates(ids), listActiveMailboxTurnSources(ids)]);
|
|
2954
|
+
const limit = pLimit(CONVERSATION_LOOP_CHECK_CONCURRENCY);
|
|
2955
|
+
return await Promise.all(rows.map(async (row) => {
|
|
2956
|
+
const kind = childAgentKindSchema.parse(row.kind);
|
|
2957
|
+
const stoppedAtMs = row.stoppedAt?.getTime();
|
|
2958
|
+
const running = stoppedAtMs === void 0 && await limit(() => runsOnConversationLoop(kind, void 0, void 0, workStates.get(row.conversationId)?.execution.pendingMessages ?? [], mailboxTurnSources.get(row.conversationId) ?? []));
|
|
2959
|
+
return {
|
|
2960
|
+
...row.agentName ? { agentName: row.agentName } : void 0,
|
|
2961
|
+
...row.archivedAt ? { archivedAtMs: row.archivedAt.getTime() } : void 0,
|
|
2962
|
+
childConversationId: row.conversationId,
|
|
2963
|
+
kind,
|
|
2964
|
+
status: stoppedAtMs !== void 0 ? "stopped" : running ? "running" : row.executionStatus === "failed" ? "failed" : "completed",
|
|
2965
|
+
task: row.title ?? "",
|
|
2966
|
+
...row.title ? { title: row.title } : void 0,
|
|
2967
|
+
updatedAtMs: (row.executionUpdatedAt ?? row.updatedAt).getTime()
|
|
2968
|
+
};
|
|
2969
|
+
}));
|
|
1982
2970
|
}
|
|
1983
2971
|
function answersParent(kind, source) {
|
|
1984
2972
|
const personInput = isPersonInput(source);
|
|
@@ -1989,14 +2977,13 @@ function answersParent(kind, source) {
|
|
|
1989
2977
|
}
|
|
1990
2978
|
/**
|
|
1991
2979
|
* Return whether a child whose `latest` agent invocation ended has work on
|
|
1992
|
-
* the Conversation loop that will answer its parent: input that
|
|
1993
|
-
* mailbox until its Turn commits it, such as a Watch Event in
|
|
1994
|
-
* window, or an open mailbox Turn that answers.
|
|
2980
|
+
* the Conversation loop that will answer its parent: `pending` input that
|
|
2981
|
+
* waits in the mailbox until its Turn commits it, such as a Watch Event in
|
|
2982
|
+
* its debounce window, or an open mailbox Turn that answers.
|
|
1995
2983
|
*/
|
|
1996
|
-
async function runsOnConversationLoop(
|
|
1997
|
-
const pending = (await getConversationWorkState({ conversationId }))?.execution.pendingMessages ?? [];
|
|
2984
|
+
async function runsOnConversationLoop(kind, latest, stoppedAtMs, pending, mailboxTurnSources) {
|
|
1998
2985
|
for (const message of pending) if (answersParent(kind, message.source) && await routeChildInput(message, latest, stoppedAtMs) === "Conversation loop") return true;
|
|
1999
|
-
return
|
|
2986
|
+
return mailboxTurnSources.some((source) => answersParent(kind, source?.kind));
|
|
2000
2987
|
}
|
|
2001
2988
|
/**
|
|
2002
2989
|
* List the ids of a child's open Turns on the Conversation loop. A Turn keeps
|
|
@@ -2008,32 +2995,21 @@ async function listOpenLoopTurnIds(conversationId) {
|
|
|
2008
2995
|
const [turns, work] = await Promise.all([listActiveMailboxTurns(conversationId), getConversationWorkState({ conversationId })]);
|
|
2009
2996
|
return [...turns.map((turn) => turn.turnId), ...(work?.execution.pendingMessages ?? []).map((message) => buildDeterministicTurnId(message.inboundMessageId))];
|
|
2010
2997
|
}
|
|
2011
|
-
async function listAnsweredLoopChildren(children,
|
|
2012
|
-
|
|
2013
|
-
const invocationId = parseAgentReplyMessageId(messageId);
|
|
2014
|
-
return invocationId ? [{
|
|
2015
|
-
invocationId,
|
|
2016
|
-
messageId
|
|
2017
|
-
}] : [];
|
|
2018
|
-
});
|
|
2019
|
-
if (children.length === 0 || replies.length === 0) return [];
|
|
2020
|
-
const senders = await getSqlExecutor().db().select({
|
|
2021
|
-
childConversationId: juniorAgentInvocations.childConversationId,
|
|
2022
|
-
invocationId: juniorAgentInvocations.invocationId
|
|
2023
|
-
}).from(juniorAgentInvocations).where(inArray(juniorAgentInvocations.invocationId, replies.map((reply) => reply.invocationId)));
|
|
2998
|
+
async function listAnsweredLoopChildren(children, parentMessages) {
|
|
2999
|
+
if (children.length === 0 || parentMessages.length === 0) return [];
|
|
2024
3000
|
return (await Promise.all(children.map(async ({ childConversationId }) => {
|
|
2025
3001
|
const turnIds = await listOpenLoopTurnIds(childConversationId);
|
|
2026
|
-
return
|
|
3002
|
+
return parentMessages.some(({ sender }) => sender.conversationId === childConversationId && turnIds.includes(sender.turnId)) ? childConversationId : void 0;
|
|
2027
3003
|
}))).filter((id) => id !== void 0);
|
|
2028
3004
|
}
|
|
2029
3005
|
/**
|
|
2030
3006
|
* List the other child agents of one parent whose results have not reached
|
|
2031
3007
|
* the parent yet. A child counts while it runs and after it finishes until its
|
|
2032
3008
|
* result is appended to the parent mailbox. A running child whose `reply` is
|
|
2033
|
-
* already
|
|
2034
|
-
* mailbox, has answered, so it does not count.
|
|
3009
|
+
* already among `parentMessages`, the child replies and results that reached
|
|
3010
|
+
* the parent's mailbox, has answered, so it does not count.
|
|
2035
3011
|
*/
|
|
2036
|
-
async function listUnreportedSiblingAgents(parentConversationId, childConversationId,
|
|
3012
|
+
async function listUnreportedSiblingAgents(parentConversationId, childConversationId, parentMessages) {
|
|
2037
3013
|
const db = getSqlExecutor().db();
|
|
2038
3014
|
const [children, pendingResults, openInvocations] = await Promise.all([
|
|
2039
3015
|
listChildAgents(parentConversationId),
|
|
@@ -2048,10 +3024,10 @@ async function listUnreportedSiblingAgents(parentConversationId, childConversati
|
|
|
2048
3024
|
invocationId: juniorAgentInvocations.invocationId
|
|
2049
3025
|
}).from(juniorAgentInvocations).where(and(eq(juniorAgentInvocations.parentConversationId, parentConversationId), inArray(juniorAgentInvocations.status, [...NON_TERMINAL_AGENT_INVOCATION_STATUSES])))
|
|
2050
3026
|
]);
|
|
2051
|
-
const withPendingResult = new Set(pendingResults.filter((row) => sendsResultToParent(row,
|
|
2052
|
-
const unanswered = new Set(openInvocations.filter((row) => !
|
|
3027
|
+
const withPendingResult = new Set(pendingResults.filter((row) => sendsResultToParent(row, parentMessages)).map((row) => row.childConversationId));
|
|
3028
|
+
const unanswered = new Set(openInvocations.filter((row) => !hasAgentInvocationReply(parentMessages, row.invocationId)).map((row) => row.childConversationId));
|
|
2053
3029
|
const answered = new Set(openInvocations.map((row) => row.childConversationId).filter((child) => !unanswered.has(child)));
|
|
2054
|
-
for (const child of await listAnsweredLoopChildren(children.filter((child) => child.status === "running" && !openInvocations.some((row) => row.childConversationId === child.childConversationId)),
|
|
3030
|
+
for (const child of await listAnsweredLoopChildren(children.filter((child) => child.status === "running" && !openInvocations.some((row) => row.childConversationId === child.childConversationId)), parentMessages)) answered.add(child);
|
|
2055
3031
|
return children.filter((child) => child.childConversationId !== childConversationId && (NON_TERMINAL_AGENT_INVOCATION_STATUSES.includes(child.status) && !answered.has(child.childConversationId) || withPendingResult.has(child.childConversationId)));
|
|
2056
3032
|
}
|
|
2057
3033
|
/**
|
|
@@ -2098,8 +3074,8 @@ async function listAgentRelatives(input) {
|
|
|
2098
3074
|
* when it is due by `maxDueIdleMs` (`timerFloorMaxDueIdleMs`). A later timer
|
|
2099
3075
|
* changes nothing, so the idle period warms as without a timer.
|
|
2100
3076
|
*/
|
|
2101
|
-
|
|
2102
|
-
const dueIdleMs = Math.min(...
|
|
3077
|
+
function earliestTimerDueIdleMs(watches, sinceMs, maxDueIdleMs) {
|
|
3078
|
+
const dueIdleMs = Math.min(...watches.map((watch) => watch.firesAtMs ?? Infinity)) - sinceMs;
|
|
2103
3079
|
return dueIdleMs <= maxDueIdleMs ? dueIdleMs : void 0;
|
|
2104
3080
|
}
|
|
2105
3081
|
function askedReviewItem(messages, final) {
|
|
@@ -2110,13 +3086,26 @@ function askedReviewItem(messages, final) {
|
|
|
2110
3086
|
return false;
|
|
2111
3087
|
}
|
|
2112
3088
|
/**
|
|
2113
|
-
*
|
|
2114
|
-
* on
|
|
2115
|
-
*
|
|
3089
|
+
* The active Watches of the Conversation, and what else its idle period
|
|
3090
|
+
* waits on. Watches include timers and the event Watches that tools such as
|
|
3091
|
+
* `createPullRequest` add. A child agent that still runs comes first: its
|
|
3092
|
+
* result starts a Turn without a person. In an Automation run, only a child
|
|
3093
|
+
* agent or a Watch can start a later Turn, so a Review item does not count.
|
|
2116
3094
|
*/
|
|
2117
|
-
async function
|
|
2118
|
-
|
|
2119
|
-
|
|
3095
|
+
async function readPendingWork(conversationId, messages, final, automation) {
|
|
3096
|
+
const [watches, children] = await Promise.all([listWatches({ conversationId }), listChildAgents(conversationId)]);
|
|
3097
|
+
if (children.some((child) => NON_TERMINAL_AGENT_INVOCATION_STATUSES.includes(child.status))) return {
|
|
3098
|
+
watches,
|
|
3099
|
+
waitingOn: "child"
|
|
3100
|
+
};
|
|
3101
|
+
if (automation) return watches.length > 0 ? {
|
|
3102
|
+
watches,
|
|
3103
|
+
waitingOn: "watch"
|
|
3104
|
+
} : { watches };
|
|
3105
|
+
return askedReviewItem(messages, final) ? {
|
|
3106
|
+
watches,
|
|
3107
|
+
waitingOn: "review"
|
|
3108
|
+
} : { watches };
|
|
2120
3109
|
}
|
|
2121
3110
|
// src/api/conversations/user-message-activity.ts
|
|
2122
3111
|
function latestIso(times) {
|
|
@@ -2303,6 +3292,7 @@ const CONVERSATION_GAPS_MAX = 50;
|
|
|
2303
3292
|
/** The Turn count of a Conversation resets after this long with no call. */
|
|
2304
3293
|
const CONVERSATION_STATE_TTL_MS = 10080 * MINUTE_MS;
|
|
2305
3294
|
const ANSWER_TOOL_ENDINGS = {
|
|
3295
|
+
[REPLY_TOOL_NAME]: "reply",
|
|
2306
3296
|
[NO_REPLY_TOOL_NAME]: "no_reply",
|
|
2307
3297
|
[REPORT_BLOCKED_TOOL_NAME]: "blocked"
|
|
2308
3298
|
};
|
|
@@ -2354,6 +3344,9 @@ async function recordGap(state, conversationId, generation, warm, gapMs) {
|
|
|
2354
3344
|
});
|
|
2355
3345
|
}
|
|
2356
3346
|
async function startIdlePeriod(state, conversationId, request, message, turn, systemPrompt, turnEnding) {
|
|
3347
|
+
const automation = systemPrompt.mode === "automation";
|
|
3348
|
+
const { watches, waitingOn } = await readPendingWork(conversationId, request.context.messages, message, automation);
|
|
3349
|
+
if (automation && !waitingOn) return void 0;
|
|
2357
3350
|
const idle = {
|
|
2358
3351
|
generation: randomUUID(),
|
|
2359
3352
|
sinceMs: request.startedAtMs
|
|
@@ -2361,7 +3354,7 @@ async function startIdlePeriod(state, conversationId, request, message, turn, sy
|
|
|
2361
3354
|
const prefixTokens = cachedPrefixTokens(message);
|
|
2362
3355
|
const ttlMs = cacheTtlMs(request);
|
|
2363
3356
|
if (ttlMs === void 0 || prefixTokens < 5e4) return idle;
|
|
2364
|
-
const timerDueIdleMs =
|
|
3357
|
+
const timerDueIdleMs = earliestTimerDueIdleMs(watches, idle.sinceMs, timerFloorMaxDueIdleMs({
|
|
2365
3358
|
cacheReadPrice: request.model.cost.cacheRead,
|
|
2366
3359
|
cacheWritePrice: request.model.cost.cacheWrite,
|
|
2367
3360
|
cacheTtlMs: ttlMs
|
|
@@ -2381,7 +3374,7 @@ async function startIdlePeriod(state, conversationId, request, message, turn, sy
|
|
|
2381
3374
|
});
|
|
2382
3375
|
return idle;
|
|
2383
3376
|
}
|
|
2384
|
-
const
|
|
3377
|
+
const segmentState = await readSegmentState(conversationId, Date.now());
|
|
2385
3378
|
const segmentInput = {
|
|
2386
3379
|
...turn,
|
|
2387
3380
|
...segmentState
|
|
@@ -2427,12 +3420,13 @@ async function recordModelCall(conversationId, userActor, systemPrompt, request,
|
|
|
2427
3420
|
});
|
|
2428
3421
|
}
|
|
2429
3422
|
const endedTurns = previous?.endedTurns ?? 0;
|
|
2430
|
-
const
|
|
3423
|
+
const nextIdle = turnEnding ? await startIdlePeriod(state, conversationId, request, message, {
|
|
3424
|
+
userActor,
|
|
3425
|
+
endedTurns
|
|
3426
|
+
}, systemPrompt, turnEnding) : void 0;
|
|
3427
|
+
const next = nextIdle ? {
|
|
2431
3428
|
endedTurns: endedTurns + 1,
|
|
2432
|
-
idle:
|
|
2433
|
-
userActor,
|
|
2434
|
-
endedTurns
|
|
2435
|
-
}, systemPrompt, turnEnding)
|
|
3429
|
+
idle: nextIdle
|
|
2436
3430
|
} : { endedTurns };
|
|
2437
3431
|
if (!idle && !next.idle) return;
|
|
2438
3432
|
await state.set(conversationKey(conversationId), next, CONVERSATION_STATE_TTL_MS);
|
|
@@ -2517,7 +3511,7 @@ function createCacheWarmingRecorder(conversationId, userActor, systemPrompt) {
|
|
|
2517
3511
|
},
|
|
2518
3512
|
toolsReturned: toolWait.toolsReturned,
|
|
2519
3513
|
answerToolEnded: (toolName) => {
|
|
2520
|
-
answerToolEnding =
|
|
3514
|
+
answerToolEnding = ANSWER_TOOL_ENDINGS[toolName];
|
|
2521
3515
|
},
|
|
2522
3516
|
stop: async () => {
|
|
2523
3517
|
try {
|
|
@@ -2564,11 +3558,12 @@ function createCacheWarmingRecorder(conversationId, userActor, systemPrompt) {
|
|
|
2564
3558
|
*
|
|
2565
3559
|
* `work_state` and `archived` are read when the idle period starts and pick
|
|
2566
3560
|
* its `gapSegment`. `turn_ending` is how the Turn before the idle period
|
|
2567
|
-
* ended: `reply` (a final response), `no_reply` (`noReply`), or
|
|
2568
|
-
* (`reportBlocked`). `waiting_on` is `child` (a child agent still
|
|
2569
|
-
* `review` (the Turn asked a Review item)
|
|
2570
|
-
*
|
|
2571
|
-
*
|
|
3561
|
+
* ended: `reply` (a final response or `reply`), `no_reply` (`noReply`), or
|
|
3562
|
+
* `blocked` (`reportBlocked`). `waiting_on` is `child` (a child agent still
|
|
3563
|
+
* ran), `review` (the Turn asked a Review item), or `watch` (an Automation
|
|
3564
|
+
* run had an active Watch and no child agent) when the idle period starts,
|
|
3565
|
+
* and picks the segment's `waitingGapSegment` child. `timer_due_ms`
|
|
3566
|
+
* is the idle time at which a timer is due, when it is due within
|
|
2572
3567
|
* `timerFloorMaxDueIdleMs`. The `conversation.returned` log has the same
|
|
2573
3568
|
* five. Decision attributes are absent when the warmup skipped before the
|
|
2574
3569
|
* decision. Of them, `timer_floor` is true for a warmup that only the timer
|
|
@@ -2695,4 +3690,4 @@ async function runCacheWarmup(message) {
|
|
|
2695
3690
|
}, startedAtMs, warm);
|
|
2696
3691
|
}, attributes);
|
|
2697
3692
|
}
|
|
2698
|
-
export { AgentDepthLimitError as A, MIN_WARMUP_PREFIX_TOKENS as B,
|
|
3693
|
+
export { AgentDepthLimitError as $, readChildConversationSender as A, MIN_WARMUP_PREFIX_TOKENS as At, endActiveAgentInvocations as B, listPendingAgentInvocationMailboxAppends as C, deleteWebAuthorization as Ct, sendsResultToParent as D, GAP_SEGMENTS as Dt, reportReplacedWithoutOpenWork as E, executeTurn as Et, parentMessageText as F, stopChildAgent as G, enqueueAgentInvocation as H, readLastParentMessageAtMs as I, cancelSignInWait as J, stopChildAgentsBelow as K, readParentMessage as L, childAgentTurnOptions as M, gapHistogramReport as Mt, isParentMessageMeta as N, gapSegment as Nt, childAgentInput as O, IDLE_HORIZON_MS as Ot, logDroppedParentMessage as P, createAgentInvocationFromLatest as Q, createAgentInvocationWorker as R, listOpenAgentInvocations as S, createWebAuthorization as St, markAgentInvocationParentMailboxAppended as T, AgentRunError as Tt, resolveAgentInvocationId as U, endAgentInvocationsOfStoppedWork as V, dropOwnUnreadLoopReplies as W, recordSubagentEnded as X, completeCancelledConversationTurn as Y, createAgentInvocationForMessage as Z, getAgentInvocation as _, getTurnAuthorization as _t, segmentGapsKey as a, findChildAgentConversationId as at, isTerminalAgentInvocation as b, isAttemptInterrupt as bt, listConversationWork as c, CHILD_AGENT_RESULTS as ct, listChildAgents as d, supersedeOpenMailboxTurns as dt, AgentInvocationLimitError as et, listDescendantAgents as f, supersedeTurnForInput as ft, getActiveAgentInvocationForConversation as g, wakePausedTurn as gt, TERMINAL_AGENT_INVOCATION_STATUSES as h, wakeAuthorizedTurn as ht, createCacheWarmingRecorder as i, AgentNameInUseError as it, routeChildInput as j, NO_REPLY_GAP_MS as jt, getChildAgentInputSender as k, MINUTE_MS as kt, readLastUserMessageAtByConversation as l, PARENT_AGENT_TARGET as lt, NON_TERMINAL_AGENT_INVOCATION_STATUSES as m, getPausedTurnRequest as mt, GLOBAL_GAPS_MAX as n, AgentMessageQueueFullError as nt, warmup_exports as o, getAgentBinding as ot, listUnreportedSiblingAgents as p, createPausedTurns as pt, stopChildAgentsOf as q, GLOBAL_GAPS_TTL_MS as r, AgentMessageTargetError as rt, isConversationWorkDone as s, CHILD_AGENT_KINDS as st, CONVERSATION_STATE_TTL_MS as t, AgentMessagePausedError as tt, listAgentRelatives as u, agentNameSchema as ut, getChildAgentLabel as v, canJoinTurn as vt, listPendingAgentInvocationResults as w, getWebAuthorization as wt, listAgentInvocationsForConversation as x, selectAttemptMessages as xt, getLatestAgentInvocationForConversation as y, canShareTurn as yt, createAndEnqueueAgentInvocation as z };
|