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