@sentry/junior 0.317.0 → 0.319.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter-8_S6Birm.js +1833 -0
- package/dist/{admin-CAugg87B.js → admin-EsbUON1j.js} +1 -1
- package/dist/{agent-runner-AjrEV6Qe.js → agent-CtzMl32d.js} +19953 -6727
- package/dist/{agent-status-BA5x3Xtp.js → agent-status-Bq_AIpyp.js} +105 -1
- package/dist/{agent-update-delivery-B_YIZcgf.js → agent-update-delivery-pAvsbuGL.js} +4 -5
- package/dist/api/schema.d.ts +85 -51
- package/dist/api/schema.js +4 -4
- package/dist/api.js +81 -94
- package/dist/{app-MoNAsVV5.d.ts → app-tACXxJPI.d.ts} +8 -13
- package/dist/app.d.ts +2 -2
- package/dist/app.js +246 -153
- package/dist/{change-record-BzJgLsv7.d.ts → change-record-K-KsqNhT.d.ts} +9 -5
- package/dist/{channel-access-j-YAVYK4.js → channel-access-DET5hzZM.js} +1 -1
- package/dist/{chat-core-engine-aH85nEHv.js → chat-core-engine-DpM3tMVi.js} +7 -7
- package/dist/cli/chat.d.ts +1 -1
- package/dist/cli/chat.js +38 -30
- package/dist/cli/check.js +5 -5
- package/dist/cli/main.js +2 -2
- package/dist/cli/plugins.d.ts +1 -1
- package/dist/cli/plugins.js +8 -8
- package/dist/cli/snapshot-create.js +5 -6
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +3 -4
- package/dist/{continue-in-slack-D-FZ8Fin.js → continue-in-slack-CFzDyxkH.js} +3 -2
- package/dist/{conversation-feed--9S0_PXL.js → conversation-feed-DEUdD7mb.js} +2 -106
- package/dist/{conversation-privacy-B1uXn5sf.js → conversation-privacy-C2vYK55O.js} +1 -1
- package/dist/{create-DoDIYgtZ.js → create-Ta3SEIB5.js} +124 -16
- package/dist/{credential-sync-BJOqGnjV.js → credential-sync-DyRqDmY4.js} +17 -20
- package/dist/{db-BFmyYZtJ.js → db-BCaNWl9p.js} +6536 -1920
- package/dist/{deployment-DXq9ZLU4.js → deployment-CfOew1Tm.js} +3 -3
- package/dist/{engine-context-CgQ7mlHt.js → engine-context-CiExoy1B.js} +181 -155
- package/dist/{html-B3VKTGbJ.js → html-Bb2Si1bR.js} +6 -8
- package/dist/instrumentation.js +7 -23
- package/dist/list-wwDcROh9.js +5007 -0
- package/dist/{logging--smS7XRK.js → logging-BRPTXAdf.js} +10 -81
- package/dist/{mailbox-turn-uSXhUFc9.js → markers-9QoqW5ov.js} +1875 -1458
- package/dist/nitro.d.ts +2 -2
- package/dist/nitro.js +7 -8
- package/dist/{oauth-callback-server-CE4soEIY.js → oauth-callback-server-vhL9b-PZ.js} +2 -2
- package/dist/{oauth-relay-C36gX1gH.js → oauth-relay-CH2v7WiB.js} +1 -1
- package/dist/{plugins-fBrz8PCV.d.ts → plugins-DhGXZjlu.d.ts} +1 -0
- package/dist/{profile-BQ-iBDsZ.js → profile-D9LdwmZi.js} +17 -19
- package/dist/{prompt-Dv7gkpD6.js → prompt-3TqxEOtc.js} +10 -10
- package/dist/{reports-WKHfGTsU.js → reports-K-tbtEyx.js} +2 -2
- package/dist/{resolve-tony4ibz.js → resolve-BBV2qf8A.js} +5 -5
- package/dist/{result-Bta_dlWa.js → result-5IdGJP4M.js} +24 -13
- package/dist/{runner-BstDRbD9.js → runner-BK_joPlM.js} +9 -18
- package/dist/{sandbox-egress-signals-oSJMJOnn.js → sandbox-egress-signals-DXgWXXmm.js} +1 -1
- package/dist/{schema-DfqrHACA.js → schema-zWGG6VC1.js} +13 -7
- package/dist/{service-account-CTV_jaNu.js → service-account-CateFyhw.js} +4 -5
- package/dist/{skills-BCEU41zM.js → skills-Ccjw8h2P.js} +10 -9
- package/dist/{slack-conversation-unfurl-DxVmhbGP.js → slack-conversation-unfurl-ZC_TSpc4.js} +7 -7
- package/dist/storage-C9U7R5rM.js +273 -0
- package/dist/{system-prompt-table-CiXy0eNR.js → system-prompt-table-YBTHIFlP.js} +26 -84
- package/dist/topic-B2EWKKBT.js +6 -0
- package/dist/{package-discovery-DD9vencX.js → topics-DxuKurCX.js} +21 -1
- package/dist/{types-C4iC-IMC.js → types-BNHkJrOP.js} +79 -59
- package/dist/{users-ByG5RCEJ.js → users-CCRAqYb_.js} +1 -1
- package/dist/{validation-8gjfR91V.js → validation-BCUpJa8K.js} +4 -4
- package/dist/{version-BeZhWWBE.js → version-BNm0JYj3.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{worker-BqMQQNRk.js → worker-BhgpZ7_b.js} +5 -5
- package/migrations/20261127002500_turn_discarded_usage/migration.sql +2 -0
- package/migrations/20261127002500_turn_discarded_usage/snapshot.json +73 -0
- package/migrations/20261127052408_space_name_nullable/migration.sql +5 -0
- package/migrations/20261127052408_space_name_nullable/snapshot.json +29 -0
- package/migrations/20261127060000_annotation_object_id_index/migration.sql +1 -0
- package/migrations/20261127060000_annotation_object_id_index/snapshot.json +69 -0
- package/migrations/20261127060001_annotation_subjects/migration.sql +78 -0
- package/migrations/20261127060001_annotation_subjects/snapshot.json +104 -0
- package/migrations/20261127060002_annotation_subject_index/migration.sql +1 -0
- package/migrations/20261127060002_annotation_subject_index/snapshot.json +70 -0
- package/migrations/20261127060003_annotation_title_url/migration.sql +84 -0
- package/migrations/20261127060003_annotation_title_url/snapshot.json +73 -0
- package/package.json +9 -7
- package/dist/catalog-runtime-DfSpJZdY.js +0 -6
- package/dist/child-message-DHjQLEd1.js +0 -19
- package/dist/config-CHQ8X251.js +0 -2422
- package/dist/conversation-turn-BUE_7xaN.js +0 -1157
- package/dist/job-runner-A1lCkybD.js +0 -1506
- package/dist/lineage-Bktb0UcV.js +0 -36
- package/dist/list-Bxvg5wXf.js +0 -12623
- package/dist/message-BNenhsmB.js +0 -154
- package/dist/model-input-BReSnwHp.js +0 -82
- package/dist/parent-result-Ck1rFYRQ.js +0 -310
- package/dist/registry-iXMT5Jmh.js +0 -3279
- package/dist/run-conversation-DL6ru7iW.js +0 -336
- package/dist/sender-actors-CPglLd5R.js +0 -83
- package/dist/spawn-frczVPIr.js +0 -48
- package/dist/task-runner-C9Yc2_ae.js +0 -1526
- package/dist/thread-context-CqZDKErp.js +0 -166
- package/dist/topic-CRYYBYp-.js +0 -7
- package/dist/topics-SRN7IVX-.js +0 -24
- package/dist/turn-membership-CENFf3kI.js +0 -856
- package/dist/turn-wake-BhloiI2h.js +0 -151
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as JUNIOR_VERSION } from "./version-
|
|
1
|
+
import { t as JUNIOR_VERSION } from "./version-BNm0JYj3.js";
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
3
|
// src/deployment.ts
|
|
4
4
|
const JUNIOR_HEARTBEAT_ROUTE = "/api/internal/heartbeat";
|
|
@@ -13,7 +13,7 @@ const JUNIOR_WORKSPACE_SNAPSHOT_JOB_CALLBACK_ROUTE = "/api/internal/workspace/sn
|
|
|
13
13
|
const JUNIOR_CACHE_WARMUP_CALLBACK_ROUTE = "/api/internal/cache/warmups";
|
|
14
14
|
const JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE = "/api/internal/context/compactions";
|
|
15
15
|
const JUNIOR_TURN_STEP_CALLBACK_ROUTE = "/api/internal/turn/steps";
|
|
16
|
-
const
|
|
16
|
+
const JUNIOR_TURN_ENDED_CALLBACK_ROUTE = "/api/internal/turn/ended";
|
|
17
17
|
const LEGACY_JUNIOR_CONVERSATION_WORK_FUNCTION = "api/internal/agent/continue.ts";
|
|
18
18
|
/**
|
|
19
19
|
* One id per process. Fluid compute runs many invocations in one process, so
|
|
@@ -50,4 +50,4 @@ function getDeploymentTelemetryAttributes(env) {
|
|
|
50
50
|
if (deploymentId) attributes["deployment.id"] = deploymentId;
|
|
51
51
|
return attributes;
|
|
52
52
|
}
|
|
53
|
-
export { getDeploymentTelemetryAttributes as _, JUNIOR_CONVERSATION_WORK_CALLBACK_ROUTE as a,
|
|
53
|
+
export { getDeploymentTelemetryAttributes as _, JUNIOR_CONVERSATION_WORK_CALLBACK_ROUTE as a, JUNIOR_PLUGIN_TASK_CALLBACK_ROUTE as c, JUNIOR_TURN_ENDED_CALLBACK_ROUTE as d, JUNIOR_TURN_STEP_CALLBACK_ROUTE as f, getDeploymentServiceVersion as g, SERVICE_INSTANCE_ID as h, JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE as i, JUNIOR_RETENTION_CRON_SCHEDULE as l, LEGACY_JUNIOR_CONVERSATION_WORK_FUNCTION as m, JUNIOR_AUTO_ARCHIVE_ROUTE as n, JUNIOR_HEARTBEAT_CRON_SCHEDULE as o, JUNIOR_WORKSPACE_SNAPSHOT_JOB_CALLBACK_ROUTE as p, JUNIOR_CACHE_WARMUP_CALLBACK_ROUTE as r, JUNIOR_HEARTBEAT_ROUTE as s, JUNIOR_AUTO_ARCHIVE_CRON_SCHEDULE as t, JUNIOR_RETENTION_ROUTE as u };
|
|
@@ -1,22 +1,21 @@
|
|
|
1
|
-
import { $
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { h as
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import { n as TURN_STEP_TOPIC, t as DELIVERY_TOPIC } from "./topic-CRYYBYp-.js";
|
|
1
|
+
import { $ as resolveGatewayModel, L as botConfig, f as credentialContextForActor } from "./adapter-8_S6Birm.js";
|
|
2
|
+
import { $a as microUsdToUsd, Ap as juniorTurns, Bp as juniorConversations, Dd as getGatewayApiKey, Ff as addAgentTurnUsage, If as agentTurnCostUsd, Jr as verifyQueueMessage, Kr as QUEUE_SIGNATURE_MAX_AGE_MS, Lf as agentTurnTotalTokens, M as locationSchema, Ms as resolveRootVisibility, Yr as getQueueProvider, _ as unseenEvents, a as getDb, cd as requestPrefixAttributes, eo as usdToMicroUsd, g as readEventCursor, h as insertEventRows, hd as gatewayRoutingAttributes, kp as juniorConversationEvents, np as juniorTurnInbox, o as getSqlExecutor, qr as signQueueMessage, tp as juniorTurnOutbox, v as withConversationEventLock } from "./db-BCaNWl9p.js";
|
|
3
|
+
import { St as contextProvenance, dt as agentHistoryFromRow, ft as encodeAgentHistoryPayload, gt as historyItemFromPiMessage, ht as HISTORY_REPLACEMENT_TYPES, mt as AGENT_HISTORY_ITEM_TYPES, qn as usageTokensSchema, vt as isHistoryReplacement, wt as instructionProvenanceFor, yt as piMessageFromHistoryItem } from "./types-BNHkJrOP.js";
|
|
4
|
+
import { _ as serializeGenAiAttribute, f as logException, h as normalizeGenAiFinishReason, i as extractGenAiUsageSummary, m as logWarn, r as extractGenAiUsageAttributes } from "./logging-BRPTXAdf.js";
|
|
5
|
+
import { h as SERVICE_INSTANCE_ID } from "./deployment-CfOew1Tm.js";
|
|
6
|
+
import { G as mapBounded } from "./prompt-3TqxEOtc.js";
|
|
7
|
+
import { a as toCanonicalInputMessage, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-C2vYK55O.js";
|
|
8
|
+
import { $r as reviewToolActions, Fr as TURN_LIMIT_WRAP_UP_MESSAGE, Ir as TurnBudgetExceededError, J as getPersistedSandboxState, Qt as getWorkspace, Rr as TurnToolCallLimitExceededError, X as persistThreadRuntimeState, Y as getPersistedThreadState, fn as buildDeploymentSystemPrompt } from "./markers-9QoqW5ov.js";
|
|
9
|
+
import { D as createReadFileTool, E as createWriteFileTool, O as createEditFileTool, T as createSystemTimeTool, c as createAgentSandbox, k as createBashTool, l as normalizeToolResult, n as buildSandboxInput, u as capToolResult } from "./agent-CtzMl32d.js";
|
|
10
|
+
import { n as TURN_STEP_TOPIC, t as TURN_ENDED_TOPIC } from "./topic-B2EWKKBT.js";
|
|
12
11
|
import * as z from "zod";
|
|
13
12
|
import { streamSimple } from "@earendil-works/pi-ai/compat";
|
|
13
|
+
import { and, asc, eq, exists, inArray, like, lt, lte, max, ne, notExists, or, sql } from "drizzle-orm";
|
|
14
|
+
import { alias } from "drizzle-orm/pg-core";
|
|
15
|
+
import { actorSchema, markdownNodes, parseMarkdown } from "@sentry/junior-plugin-api";
|
|
14
16
|
import * as Sentry from "@sentry/node";
|
|
15
17
|
import { randomUUID } from "node:crypto";
|
|
16
18
|
import { toToolDeclaration, validateToolArguments } from "@earendil-works/pi-ai";
|
|
17
|
-
import { actorSchema, destinationSchema, markdownNodes, parseMarkdown } from "@sentry/junior-plugin-api";
|
|
18
|
-
import { and, asc, eq, exists, inArray, like, lt, lte, max, ne, notExists, or, sql } from "drizzle-orm";
|
|
19
|
-
import { alias } from "drizzle-orm/pg-core";
|
|
20
19
|
import { performance as performance$1 } from "node:perf_hooks";
|
|
21
20
|
// src/core/model/failure.ts
|
|
22
21
|
const RETRYABLE_KINDS = /* @__PURE__ */ new Set([
|
|
@@ -400,60 +399,11 @@ function inputFormatOf(item) {
|
|
|
400
399
|
return inputFormats.get(item);
|
|
401
400
|
}
|
|
402
401
|
/**
|
|
403
|
-
* Checks a layout and returns the copy
|
|
404
|
-
*
|
|
405
|
-
* fragments with one name, on one fragment used twice, on two loaders with
|
|
406
|
-
* one label, and unless the messages hold exactly one `inputs()` fragment.
|
|
407
|
-
* It freezes the system prompt sections and the messages list.
|
|
408
|
-
*
|
|
409
|
-
* The rules:
|
|
410
|
-
* - Loaders do all of the I/O. Core runs each needed loader once per step.
|
|
411
|
-
* - Fragments are pure. `enabled` and `format` do no I/O, and read no clock
|
|
412
|
-
* and no random value, so the same inputs give the same prompt. Their
|
|
413
|
-
* messages have no timestamp: core gives each one the step's time, and
|
|
414
|
-
* each input its send time.
|
|
415
|
-
* - Message fragments only append. Their messages go after the history, and
|
|
416
|
-
* a later step sees them in its history. Core builds them only for a step
|
|
417
|
-
* that sends a model request, not for a step that runs tool calls.
|
|
418
|
-
* - The `inputs()` fragment sets where the Turn's unread inputs go.
|
|
419
|
-
* - The system prompt holds no Conversation data. The host builds its
|
|
420
|
-
* sections once at startup, so the model provider can cache that part of
|
|
421
|
-
* the request.
|
|
422
|
-
* - Tools and model settings are not in the layout. They belong to the Turn,
|
|
423
|
-
* and the step gets them separately.
|
|
424
|
-
*
|
|
402
|
+
* Checks a layout (rules above) and returns the frozen copy core builds from.
|
|
403
|
+
* Throws on repeated or empty names, reused fragments, or not one `inputs()`.
|
|
425
404
|
* @example
|
|
426
|
-
*
|
|
427
|
-
*
|
|
428
|
-
* const memories = loader(
|
|
429
|
-
* "memories",
|
|
430
|
-
* (ctx, signal) => memoryStore.recall(ctx.turn.conversationId, signal),
|
|
431
|
-
* { timeoutMs: 2_000, optional: true },
|
|
432
|
-
* );
|
|
433
|
-
* const recalled = fragment("recalled-memories", {
|
|
434
|
-
* loader: memories,
|
|
435
|
-
* // Recall only for a step that has new inputs.
|
|
436
|
-
* enabled: (ctx) => ctx.inputs.length > 0,
|
|
437
|
-
* format: (notes): FragmentMessage | Skip =>
|
|
438
|
-
* notes && notes.length > 0
|
|
439
|
-
* ? { role: "user", content: notes.join("\n") }
|
|
440
|
-
* : skip("no memories"),
|
|
441
|
-
* });
|
|
442
|
-
* const layout = definePromptLayout({
|
|
443
|
-
* systemPrompt: [
|
|
444
|
-
* { name: "identity", text: "You are Junior, Sentry's Slack bot." },
|
|
445
|
-
* { name: "personality", text: soul },
|
|
446
|
-
* ],
|
|
447
|
-
* messages: [
|
|
448
|
-
* recalled,
|
|
449
|
-
* inputs({
|
|
450
|
-
* format: (input) => ({
|
|
451
|
-
* message: { role: "user", content: String(input.payload["text"]) },
|
|
452
|
-
* provenance: { authority: "instruction" },
|
|
453
|
-
* }),
|
|
454
|
-
* }),
|
|
455
|
-
* ],
|
|
456
|
-
* });
|
|
405
|
+
* const layout = definePromptLayout({ systemPrompt: [identity],
|
|
406
|
+
* messages: [recalledMemories, inputs({ format: formatInput })] });
|
|
457
407
|
*/
|
|
458
408
|
function definePromptLayout(layout) {
|
|
459
409
|
const sectionNames = /* @__PURE__ */ new Set();
|
|
@@ -680,7 +630,15 @@ async function findInputTurn({ executor }, args) {
|
|
|
680
630
|
*/
|
|
681
631
|
async function findTurnDestination({ executor }, turnId) {
|
|
682
632
|
const [input] = await executor.db().select({ destination: juniorTurnInbox.destination }).from(juniorTurnInbox).where(eq(juniorTurnInbox.turnId, turnId)).orderBy(asc(juniorTurnInbox.createdAt), asc(juniorTurnInbox.id)).limit(1);
|
|
683
|
-
return input?.destination
|
|
633
|
+
return input?.destination ?? null;
|
|
634
|
+
}
|
|
635
|
+
/**
|
|
636
|
+
* Finds who a Turn acts for: the sender of its first input. Undefined when
|
|
637
|
+
* the Turn has no input.
|
|
638
|
+
*/
|
|
639
|
+
async function findTurnActor({ executor }, turnId) {
|
|
640
|
+
const [input] = await executor.db().select({ actorIdentityId: juniorTurnInbox.actorIdentityId }).from(juniorTurnInbox).where(eq(juniorTurnInbox.turnId, turnId)).orderBy(asc(juniorTurnInbox.createdAt), asc(juniorTurnInbox.id)).limit(1);
|
|
641
|
+
return input?.actorIdentityId;
|
|
684
642
|
}
|
|
685
643
|
/** Finds every input of a Turn, oldest first. */
|
|
686
644
|
async function findTurnInputs({ executor }, turnId) {
|
|
@@ -806,17 +764,17 @@ async function publishTurnStep(ctx, turnId, options = {}) {
|
|
|
806
764
|
function createTurnStepConsumer(ctx, run) {
|
|
807
765
|
return turnStepTopic.consumer(ctx, (message, metadata) => run({ turnId: message.turnId }, metadata));
|
|
808
766
|
}
|
|
809
|
-
// src/core/
|
|
810
|
-
const
|
|
767
|
+
// src/core/turn/ended.ts
|
|
768
|
+
const turnEndedMessageSchema = z.object({
|
|
811
769
|
conversationId: z.string().min(1),
|
|
812
770
|
turnId: z.string().min(1),
|
|
813
771
|
traceContext: z.object({ sentryTrace: z.string().min(1) }).strict().optional()
|
|
814
772
|
}).strict();
|
|
815
|
-
const
|
|
816
|
-
topic:
|
|
773
|
+
const turnEndedTopic = signedTopic({
|
|
774
|
+
topic: TURN_ENDED_TOPIC,
|
|
817
775
|
sign: {
|
|
818
|
-
context: "junior.
|
|
819
|
-
schema:
|
|
776
|
+
context: "junior.turn_ended.v1",
|
|
777
|
+
schema: turnEndedMessageSchema,
|
|
820
778
|
signatureVersion: "v1",
|
|
821
779
|
parts: (message) => [
|
|
822
780
|
message.conversationId,
|
|
@@ -824,24 +782,27 @@ const deliveryTopic = signedTopic({
|
|
|
824
782
|
message.traceContext?.sentryTrace ?? ""
|
|
825
783
|
]
|
|
826
784
|
},
|
|
827
|
-
onRejected: (attributes) => logWarn("turn.
|
|
785
|
+
onRejected: (attributes) => logWarn("turn.ended.queue_message.rejected", attributes),
|
|
828
786
|
attributes: (message) => ({
|
|
829
787
|
"app.turn.id": message.turnId,
|
|
830
788
|
"gen_ai.conversation.id": message.conversationId
|
|
831
789
|
})
|
|
832
790
|
});
|
|
833
|
-
/**
|
|
834
|
-
|
|
835
|
-
|
|
791
|
+
/**
|
|
792
|
+
* Sends the message that the Turn ended, after `delayMs` if set. A handler
|
|
793
|
+
* that must try its work again later sends it again with a delay.
|
|
794
|
+
*/
|
|
795
|
+
async function publishTurnEnded(ctx, message, options = {}) {
|
|
796
|
+
await turnEndedTopic.publish(ctx, message, options);
|
|
836
797
|
}
|
|
837
798
|
/**
|
|
838
|
-
*
|
|
839
|
-
*
|
|
840
|
-
*
|
|
841
|
-
*
|
|
799
|
+
* Reads the messages that a Turn ended: it checks that core sent each one,
|
|
800
|
+
* then calls `handle`. It acknowledges a message with a bad or expired
|
|
801
|
+
* signature and retries one that cannot be checked yet. The host mounts the
|
|
802
|
+
* consumer on its queue provider.
|
|
842
803
|
*/
|
|
843
|
-
function
|
|
844
|
-
return
|
|
804
|
+
function readTurnEndedMessages(ctx, handle) {
|
|
805
|
+
return turnEndedTopic.consumer(ctx, (message, metadata) => handle({
|
|
845
806
|
conversationId: message.conversationId,
|
|
846
807
|
turnId: message.turnId
|
|
847
808
|
}, metadata));
|
|
@@ -912,7 +873,7 @@ function replyText(row) {
|
|
|
912
873
|
async function findTurnReplies({ executor }, conversationId, turnId) {
|
|
913
874
|
return (await executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "assistant_message"), like(juniorConversationEvents.idempotencyKey, `${turnEventKeyPrefix(turnId)}%`))).orderBy(asc(juniorConversationEvents.seq))).filter((row) => replyText(row) !== void 0);
|
|
914
875
|
}
|
|
915
|
-
// src/core/
|
|
876
|
+
// src/core/turn/outbox.ts
|
|
916
877
|
/**
|
|
917
878
|
* Adds an outbox row for each reply of the Turn that has none, but only while
|
|
918
879
|
* the Turn has a Destination. Call it in the transaction that commits the
|
|
@@ -932,26 +893,6 @@ async function recordReplies({ executor }, turn) {
|
|
|
932
893
|
state: "pending"
|
|
933
894
|
}))).onConflictDoNothing({ target: [juniorTurnOutbox.conversationId, juniorTurnOutbox.eventSeq] });
|
|
934
895
|
}
|
|
935
|
-
/**
|
|
936
|
-
* Finds Conversations whose first pending reply has not changed for
|
|
937
|
-
* `staleMs`, so no delivery message is likely to reach it. A row behind a
|
|
938
|
-
* first row that is still retried waits; it is not stalled.
|
|
939
|
-
*/
|
|
940
|
-
async function findStalledDeliveries({ executor }, { staleMs, limit }) {
|
|
941
|
-
const staleBefore = sql`now() - make_interval(secs => ${staleMs / 1e3})`;
|
|
942
|
-
const earlier = alias(juniorTurnOutbox, "earlier");
|
|
943
|
-
const rows = await executor.db().select({
|
|
944
|
-
conversationId: juniorTurnOutbox.conversationId,
|
|
945
|
-
turnId: juniorTurnOutbox.turnId,
|
|
946
|
-
updatedAt: juniorTurnOutbox.updatedAt
|
|
947
|
-
}).from(juniorTurnOutbox).where(and(eq(juniorTurnOutbox.state, "pending"), lt(juniorTurnOutbox.createdAt, staleBefore), lt(juniorTurnOutbox.updatedAt, staleBefore), notExists(executor.db().select({ one: sql`1` }).from(earlier).where(and(eq(earlier.conversationId, juniorTurnOutbox.conversationId), eq(earlier.state, "pending"), lt(earlier.eventSeq, juniorTurnOutbox.eventSeq)))))).limit(limit);
|
|
948
|
-
const nowMs = Date.now();
|
|
949
|
-
return rows.map((row) => ({
|
|
950
|
-
conversationId: row.conversationId,
|
|
951
|
-
turnId: row.turnId,
|
|
952
|
-
stalledMs: Math.max(0, nowMs - row.updatedAt.getTime())
|
|
953
|
-
}));
|
|
954
|
-
}
|
|
955
896
|
// src/core/turn/state.ts
|
|
956
897
|
/**
|
|
957
898
|
* Turn priorities: a lower number runs first. A Turn that supersedes the
|
|
@@ -996,10 +937,36 @@ async function findTurn({ executor }, turnId) {
|
|
|
996
937
|
conversationId: juniorTurns.conversationId,
|
|
997
938
|
failureCode: juniorTurns.failureCode,
|
|
998
939
|
failureReason: juniorTurns.failureReason,
|
|
999
|
-
failureEventId: juniorTurns.failureEventId
|
|
940
|
+
failureEventId: juniorTurns.failureEventId,
|
|
941
|
+
startedAt: juniorTurns.startedAt,
|
|
942
|
+
endedAt: juniorTurns.endedAt
|
|
1000
943
|
}).from(juniorTurns).where(eq(juniorTurns.id, turnId));
|
|
1001
944
|
return turn;
|
|
1002
945
|
}
|
|
946
|
+
/** Reads a Turn's discarded usage. Undefined when the Turn does not exist. */
|
|
947
|
+
async function findDiscardedUsage({ executor }, turnId) {
|
|
948
|
+
return selectDiscardedUsage({ executor }, eq(juniorTurns.id, turnId));
|
|
949
|
+
}
|
|
950
|
+
async function selectDiscardedUsage({ executor }, where) {
|
|
951
|
+
const [turn] = await executor.db().select({
|
|
952
|
+
costMicroUsd: juniorTurns.discardedCostMicroUsd,
|
|
953
|
+
tokens: juniorTurns.discardedTokens
|
|
954
|
+
}).from(juniorTurns).where(where);
|
|
955
|
+
if (!turn) return;
|
|
956
|
+
return turn.tokens === null ? { costMicroUsd: turn.costMicroUsd } : {
|
|
957
|
+
costMicroUsd: turn.costMicroUsd,
|
|
958
|
+
tokens: usageTokensSchema.parse(turn.tokens)
|
|
959
|
+
};
|
|
960
|
+
}
|
|
961
|
+
async function discardedUsageUpdate({ executor }, lease, usage) {
|
|
962
|
+
const current = usage ? await selectDiscardedUsage({ executor }, leaseFence(lease)) : void 0;
|
|
963
|
+
if (!current) return {};
|
|
964
|
+
const { cost: _, ...tokens } = addAgentTurnUsage(current.tokens, usage) ?? {};
|
|
965
|
+
return {
|
|
966
|
+
discardedCostMicroUsd: current.costMicroUsd + usdToMicroUsd(agentTurnCostUsd(usage) ?? 0),
|
|
967
|
+
discardedTokens: tokens
|
|
968
|
+
};
|
|
969
|
+
}
|
|
1003
970
|
const runOrder = [
|
|
1004
971
|
sql`${juniorTurns.state} = 'running' desc`,
|
|
1005
972
|
asc(juniorTurns.priority),
|
|
@@ -1043,27 +1010,30 @@ async function isSuperseded({ executor }, turnId) {
|
|
|
1043
1010
|
}
|
|
1044
1011
|
/**
|
|
1045
1012
|
* Makes way for a Turn that supersedes this one. Call it under the
|
|
1046
|
-
* Conversation lock. A queued Turn has no step in flight, so it ends now
|
|
1047
|
-
* running Turn moves behind the new Turn, and
|
|
1048
|
-
*
|
|
1013
|
+
* Conversation lock. A queued Turn has no step in flight, so it ends now and
|
|
1014
|
+
* moves `lease_epoch`. A running Turn moves behind the new Turn, and
|
|
1015
|
+
* `commitStep` or `releaseTurn` ends it, so the step's work is kept. True
|
|
1016
|
+
* when the Turn ended now.
|
|
1049
1017
|
*/
|
|
1050
1018
|
async function supersedeTurn({ executor }, turnId) {
|
|
1051
1019
|
const db = executor.db();
|
|
1052
|
-
await db.update(juniorTurns).set({
|
|
1020
|
+
const ended = await db.update(juniorTurns).set({
|
|
1053
1021
|
...SUPERSEDED_END,
|
|
1054
1022
|
leaseEpoch: sql`${juniorTurns.leaseEpoch} + 1`,
|
|
1055
1023
|
updatedAt: sql`now()`
|
|
1056
|
-
}).where(and(eq(juniorTurns.id, turnId), eq(juniorTurns.state, "queued")));
|
|
1024
|
+
}).where(and(eq(juniorTurns.id, turnId), eq(juniorTurns.state, "queued"))).returning({ id: juniorTurns.id });
|
|
1057
1025
|
await db.update(juniorTurns).set({
|
|
1058
1026
|
priority: TURN_PRIORITY.normal,
|
|
1059
1027
|
updatedAt: sql`now()`
|
|
1060
1028
|
}).where(and(eq(juniorTurns.id, turnId), eq(juniorTurns.state, "running")));
|
|
1029
|
+
return ended.length > 0;
|
|
1061
1030
|
}
|
|
1062
1031
|
/**
|
|
1063
1032
|
* Claims a Turn to run its next step: the Conversation's next queued Turn, or
|
|
1064
|
-
* a running Turn whose lease expired
|
|
1065
|
-
*
|
|
1066
|
-
*
|
|
1033
|
+
* a running Turn whose lease expired, so the queue's redelivery after a crash
|
|
1034
|
+
* resumes it. Any other Turn gets undefined, so one of two racing claims wins,
|
|
1035
|
+
* and a Conversation runs one Turn at a time, in order. Each claim moves
|
|
1036
|
+
* `lease_epoch` and `attempts` and holds the Conversation lock.
|
|
1067
1037
|
*/
|
|
1068
1038
|
async function claimTurn({ executor, owner, leaseMs }, turnId) {
|
|
1069
1039
|
const turn = await findTurn({ executor }, turnId);
|
|
@@ -1136,15 +1106,11 @@ function promptEventKey(turnId, stepSeq, index) {
|
|
|
1136
1106
|
return `prompt:${turnId}:${stepSeq}:${index}`;
|
|
1137
1107
|
}
|
|
1138
1108
|
/**
|
|
1139
|
-
* Commits a step in one transaction:
|
|
1140
|
-
*
|
|
1141
|
-
*
|
|
1142
|
-
*
|
|
1143
|
-
*
|
|
1144
|
-
* A Turn that the step completed ends, unless it still has unread inputs:
|
|
1145
|
-
* then it continues, so the next step reads them.
|
|
1146
|
-
* Returns what the Turn does next. Undefined when the lease is lost or the
|
|
1147
|
-
* step is already committed, and then nothing is written.
|
|
1109
|
+
* Commits a step in one transaction: appends the prompt's new messages, with
|
|
1110
|
+
* the inputs the step read, then the step's messages to history, adds an
|
|
1111
|
+
* outbox row per new reply, and releases the lease. A Turn that continues
|
|
1112
|
+
* queues for a new claim. A `stale` final reply is not committed. Undefined,
|
|
1113
|
+
* with no write, when the lease is lost or the step is already committed.
|
|
1148
1114
|
*/
|
|
1149
1115
|
async function commitStep({ executor }, turn, step, prompt) {
|
|
1150
1116
|
const nextStep = {
|
|
@@ -1156,6 +1122,7 @@ async function commitStep({ executor }, turn, step, prompt) {
|
|
|
1156
1122
|
};
|
|
1157
1123
|
return executor.transaction(() => withConversationEventLock(executor, turn.conversationId, async () => {
|
|
1158
1124
|
const outcome = await commitOutcome({ executor }, turn.turnId, step, prompt);
|
|
1125
|
+
if (outcome === "stale") return await requeueStep({ executor }, turn, step) ? outcome : void 0;
|
|
1159
1126
|
if ((await executor.db().update(juniorTurns).set(outcome === "completed" ? {
|
|
1160
1127
|
...nextStep,
|
|
1161
1128
|
state: "completed",
|
|
@@ -1187,22 +1154,45 @@ async function commitStep({ executor }, turn, step, prompt) {
|
|
|
1187
1154
|
/**
|
|
1188
1155
|
* A completed step ends the Turn only when the commit reads every unread
|
|
1189
1156
|
* input. The scheduler can add an input after the step read them, and the
|
|
1190
|
-
* Conversation lock keeps more out until the commit ends.
|
|
1157
|
+
* Conversation lock keeps more out until the commit ends. A final reply that
|
|
1158
|
+
* missed an input is `stale`, so the Turn ends with one reply to every input.
|
|
1191
1159
|
*/
|
|
1192
1160
|
async function commitOutcome({ executor }, turnId, step, prompt) {
|
|
1193
1161
|
if (step.outcome === "completed") {
|
|
1194
1162
|
const read = new Set(prompt.flatMap((entry) => entry.source === "input" ? [entry.inputId] : []));
|
|
1195
1163
|
if ((await findUnreadInputs({ executor }, turnId)).every((input) => read.has(input.inputId))) return "completed";
|
|
1196
1164
|
}
|
|
1197
|
-
|
|
1165
|
+
if (await isSuperseded({ executor }, turnId)) return "superseded";
|
|
1166
|
+
return step.outcome === "completed" && finalReplyOf(step) ? "stale" : "continue";
|
|
1167
|
+
}
|
|
1168
|
+
function finalReplyOf(step) {
|
|
1169
|
+
const [message] = step.messages;
|
|
1170
|
+
return message?.role === "assistant" ? message : void 0;
|
|
1171
|
+
}
|
|
1172
|
+
/**
|
|
1173
|
+
* Queues the Turn for the same step again, with nothing committed, after a
|
|
1174
|
+
* stale final reply. The attempt does not count: the step did not fail. The
|
|
1175
|
+
* dropped reply's usage adds to the Turn's discarded usage.
|
|
1176
|
+
*/
|
|
1177
|
+
async function requeueStep({ executor }, turn, step) {
|
|
1178
|
+
return (await executor.db().update(juniorTurns).set({
|
|
1179
|
+
...await discardedUsageUpdate({ executor }, turn, extractGenAiUsageSummary(finalReplyOf(step))),
|
|
1180
|
+
state: "queued",
|
|
1181
|
+
attempts: 0,
|
|
1182
|
+
leaseOwner: null,
|
|
1183
|
+
leaseExpiresAt: null,
|
|
1184
|
+
updatedAt: sql`now()`
|
|
1185
|
+
}).where(and(leaseFence(turn), eq(juniorTurns.conversationId, turn.conversationId), eq(juniorTurns.stepSeq, turn.stepSeq))).returning({ id: juniorTurns.id })).length > 0;
|
|
1198
1186
|
}
|
|
1199
1187
|
/**
|
|
1200
1188
|
* Ends a running Turn as failed, with the reason and the failure details.
|
|
1201
|
-
*
|
|
1202
|
-
*
|
|
1189
|
+
* `discarded` is the usage of the model reply that the step drops. False when
|
|
1190
|
+
* the lease is lost. The engine calls it through `endFailedTurn`, which also
|
|
1191
|
+
* moves the Turn's late inputs.
|
|
1203
1192
|
*/
|
|
1204
|
-
async function failTurn({ executor }, lease, endReason, failure) {
|
|
1193
|
+
async function failTurn({ executor }, lease, endReason, failure, discarded) {
|
|
1205
1194
|
return (await executor.db().update(juniorTurns).set({
|
|
1195
|
+
...await discardedUsageUpdate({ executor }, lease, discarded),
|
|
1206
1196
|
state: "failed",
|
|
1207
1197
|
endReason,
|
|
1208
1198
|
failureCode: failure.failureCode,
|
|
@@ -1217,12 +1207,14 @@ async function failTurn({ executor }, lease, endReason, failure) {
|
|
|
1217
1207
|
/**
|
|
1218
1208
|
* Queues a running Turn again after its invocation failed, so the queue's
|
|
1219
1209
|
* retry can claim the step at once. The failed attempt still counts. A Turn
|
|
1220
|
-
* that another Turn supersedes ends instead, like at a commit.
|
|
1221
|
-
*
|
|
1210
|
+
* that another Turn supersedes ends instead, like at a commit. `discarded` is
|
|
1211
|
+
* the usage of the failed model reply that the retry drops. Returns the
|
|
1212
|
+
* Turn's new state, or undefined when the lease is lost.
|
|
1222
1213
|
*/
|
|
1223
|
-
async function releaseTurn({ executor }, lease) {
|
|
1214
|
+
async function releaseTurn({ executor }, lease, discarded) {
|
|
1224
1215
|
return executor.transaction(() => withConversationEventLock(executor, lease.conversationId, async () => {
|
|
1225
1216
|
const released = {
|
|
1217
|
+
...await discardedUsageUpdate({ executor }, lease, discarded),
|
|
1226
1218
|
leaseOwner: null,
|
|
1227
1219
|
leaseExpiresAt: null,
|
|
1228
1220
|
updatedAt: sql`now()`
|
|
@@ -1233,7 +1225,7 @@ async function releaseTurn({ executor }, lease) {
|
|
|
1233
1225
|
} : {
|
|
1234
1226
|
...released,
|
|
1235
1227
|
state: "queued"
|
|
1236
|
-
}).where(leaseFence(lease)).returning({
|
|
1228
|
+
}).where(leaseFence(lease)).returning({ state: juniorTurns.state }))[0]?.state;
|
|
1237
1229
|
}));
|
|
1238
1230
|
}
|
|
1239
1231
|
// src/core/turn/schedule.ts
|
|
@@ -1289,7 +1281,7 @@ async function placeInput({ executor }, { delivery, ...input }) {
|
|
|
1289
1281
|
publish: false
|
|
1290
1282
|
};
|
|
1291
1283
|
}
|
|
1292
|
-
|
|
1284
|
+
const ended = choice.supersede && await supersedeTurn({ executor }, choice.supersede.turnId) ? choice.supersede.turnId : void 0;
|
|
1293
1285
|
const turn = await createTurn({ executor }, {
|
|
1294
1286
|
conversationId: input.conversationId,
|
|
1295
1287
|
priority: choice.create.priority
|
|
@@ -1301,18 +1293,22 @@ async function placeInput({ executor }, { delivery, ...input }) {
|
|
|
1301
1293
|
return {
|
|
1302
1294
|
turnId: turn.turnId,
|
|
1303
1295
|
created: true,
|
|
1304
|
-
publish: openTurns.length === 0 || choice.supersede !== void 0
|
|
1296
|
+
publish: openTurns.length === 0 || choice.supersede !== void 0,
|
|
1297
|
+
ended
|
|
1305
1298
|
};
|
|
1306
1299
|
}
|
|
1307
1300
|
/**
|
|
1308
|
-
* Puts an input into the Turn that `assignTurn` picks,
|
|
1309
|
-
*
|
|
1310
|
-
*
|
|
1311
|
-
*
|
|
1312
|
-
* reaches the caller with the input already stored.
|
|
1301
|
+
* Puts an input into the Turn that `assignTurn` picks, then publishes what
|
|
1302
|
+
* the placement calls for, such as the end of a Turn it superseded. A known
|
|
1303
|
+
* idempotency key writes nothing. Call it outside a transaction: it publishes
|
|
1304
|
+
* after its own commit, so a publish error leaves the input stored.
|
|
1313
1305
|
*/
|
|
1314
1306
|
async function scheduleInput({ executor, queue }, input) {
|
|
1315
1307
|
const placement = await withConversationEventLock(executor, input.conversationId, () => placeInput({ executor }, input));
|
|
1308
|
+
if (placement.ended) await publishTurnEnded({ queue }, {
|
|
1309
|
+
conversationId: input.conversationId,
|
|
1310
|
+
turnId: placement.ended
|
|
1311
|
+
});
|
|
1316
1312
|
if (placement.publish) await publishTurnStep({ queue }, placement.turnId);
|
|
1317
1313
|
return {
|
|
1318
1314
|
turnId: placement.turnId,
|
|
@@ -1346,26 +1342,26 @@ async function moveLeftovers({ executor }, ended) {
|
|
|
1346
1342
|
* Ends a running Turn as failed and, in the same commit, moves its inputs
|
|
1347
1343
|
* that arrived after its last claim to the next Turn. A crash after the
|
|
1348
1344
|
* commit loses no input: the next Turn is queued, so the sweep finds it.
|
|
1345
|
+
* `discarded` is the usage of a failed model reply that the Turn drops.
|
|
1349
1346
|
* False when the lease is lost, and then nothing changes.
|
|
1350
1347
|
*/
|
|
1351
|
-
async function endFailedTurn({ executor }, lease, endReason, failure) {
|
|
1348
|
+
async function endFailedTurn({ executor }, lease, endReason, failure, discarded) {
|
|
1352
1349
|
return executor.transaction(() => withConversationEventLock(executor, lease.conversationId, async () => {
|
|
1353
|
-
if (!await failTurn({ executor }, lease, endReason, failure)) return false;
|
|
1350
|
+
if (!await failTurn({ executor }, lease, endReason, failure, discarded)) return false;
|
|
1354
1351
|
await moveLeftovers({ executor }, lease);
|
|
1355
1352
|
return true;
|
|
1356
1353
|
}));
|
|
1357
1354
|
}
|
|
1358
1355
|
/**
|
|
1359
|
-
* Brings
|
|
1360
|
-
*
|
|
1361
|
-
*
|
|
1362
|
-
*
|
|
1363
|
-
* commit that it follows, so a worker that takes a message sees that commit.
|
|
1356
|
+
* Brings the queue in line with this Turn's stored state, so it is safe to
|
|
1357
|
+
* repeat: it says the Turn ended if it has, then publishes the Conversation's
|
|
1358
|
+
* open Turn if it is queued. Call it after the commit that it follows,
|
|
1359
|
+
* outside a transaction, so a worker that takes a message sees that commit.
|
|
1364
1360
|
*/
|
|
1365
1361
|
async function reconcileTurn({ executor, queue }, turnId) {
|
|
1366
1362
|
const turn = await findTurn({ executor }, turnId);
|
|
1367
1363
|
if (!turn) return;
|
|
1368
|
-
await
|
|
1364
|
+
if (turn.state !== "queued" && turn.state !== "running") await publishTurnEnded({ queue }, {
|
|
1369
1365
|
conversationId: turn.conversationId,
|
|
1370
1366
|
turnId
|
|
1371
1367
|
});
|
|
@@ -1411,10 +1407,19 @@ async function requestModel({ systemPrompt, messages, model }, { client, session
|
|
|
1411
1407
|
outcome: "continue",
|
|
1412
1408
|
messages: [reply]
|
|
1413
1409
|
};
|
|
1414
|
-
if (reply.stopReason === "stop"
|
|
1410
|
+
if (reply.stopReason === "stop") return {
|
|
1415
1411
|
outcome: "completed",
|
|
1416
1412
|
messages: [reply]
|
|
1417
1413
|
};
|
|
1414
|
+
if (reply.stopReason === "length") return {
|
|
1415
|
+
outcome: "failed",
|
|
1416
|
+
reply,
|
|
1417
|
+
failure: {
|
|
1418
|
+
kind: "cut_off_output",
|
|
1419
|
+
retryable: false,
|
|
1420
|
+
message: "The reply hit the output token limit"
|
|
1421
|
+
}
|
|
1422
|
+
};
|
|
1418
1423
|
return {
|
|
1419
1424
|
outcome: "failed",
|
|
1420
1425
|
reply,
|
|
@@ -1657,20 +1662,26 @@ async function runClaimedStep({ executor, queue }, claim, unread, { client, prom
|
|
|
1657
1662
|
}, claim.turnId);
|
|
1658
1663
|
return;
|
|
1659
1664
|
case "failed": {
|
|
1665
|
+
const usage = extractGenAiUsageSummary(result.reply);
|
|
1666
|
+
const discarded = (agentTurnTotalTokens(usage) ?? 0) > 0 || (agentTurnCostUsd(usage) ?? 0) > 0 ? usage : void 0;
|
|
1660
1667
|
const delayMs = modelRetryDelayMs(result.failure, claim.attempts, maxAttempts);
|
|
1661
1668
|
if (delayMs !== void 0) {
|
|
1662
|
-
|
|
1669
|
+
const released = await releaseTurn({ executor }, claim, discarded);
|
|
1670
|
+
if (released === "queued") {
|
|
1663
1671
|
await publishTurnStep({ queue }, claim.turnId, { delayMs });
|
|
1664
1672
|
logWarn("agent.turn.provider.retrying", {
|
|
1665
1673
|
...modelFailureAttributes(result.failure),
|
|
1666
1674
|
"app.ai.provider_error.retry_attempt": claim.attempts,
|
|
1667
1675
|
"app.turn.id": claim.turnId
|
|
1668
1676
|
});
|
|
1669
|
-
}
|
|
1677
|
+
} else if (released) await reconcileTurn({
|
|
1678
|
+
executor,
|
|
1679
|
+
queue
|
|
1680
|
+
}, claim.turnId);
|
|
1670
1681
|
return;
|
|
1671
1682
|
}
|
|
1672
1683
|
const failure = captureModelFailure(result.failure);
|
|
1673
|
-
if (await endFailedTurn({ executor }, claim, result.failure.message, failure)) await reconcileTurn({
|
|
1684
|
+
if (await endFailedTurn({ executor }, claim, result.failure.message, failure, discarded)) await reconcileTurn({
|
|
1674
1685
|
executor,
|
|
1675
1686
|
queue
|
|
1676
1687
|
}, claim.turnId);
|
|
@@ -1866,6 +1877,22 @@ async function turnStepConsumer(engineCtx, { client, bot, tools }) {
|
|
|
1866
1877
|
maxAttempts: MAX_ATTEMPTS
|
|
1867
1878
|
}));
|
|
1868
1879
|
}
|
|
1880
|
+
// src/turn-steps/usage.ts
|
|
1881
|
+
/**
|
|
1882
|
+
* Sums the usage of the model replies in `history`, the Turn's own history,
|
|
1883
|
+
* and of the replies that the Turn paid for but dropped.
|
|
1884
|
+
*/
|
|
1885
|
+
async function turnUsage(ctx, turnId, history) {
|
|
1886
|
+
const kept = extractGenAiUsageSummary(...history.filter((message) => message.role === "assistant"));
|
|
1887
|
+
const discarded = await findDiscardedUsage(ctx, turnId);
|
|
1888
|
+
const { cost: _, ...tokens } = addAgentTurnUsage(kept, discarded?.tokens) ?? {};
|
|
1889
|
+
const keptCostUsd = agentTurnCostUsd(kept);
|
|
1890
|
+
if (keptCostUsd === void 0 && !discarded?.costMicroUsd) return tokens;
|
|
1891
|
+
return {
|
|
1892
|
+
...tokens,
|
|
1893
|
+
cost: { total: (keptCostUsd ?? 0) + microUsdToUsd(discarded?.costMicroUsd ?? 0) }
|
|
1894
|
+
};
|
|
1895
|
+
}
|
|
1869
1896
|
// src/turn-steps/limits.ts
|
|
1870
1897
|
const WRAPPED_UP = "wrapped_up";
|
|
1871
1898
|
/**
|
|
@@ -1875,10 +1902,9 @@ const WRAPPED_UP = "wrapped_up";
|
|
|
1875
1902
|
*/
|
|
1876
1903
|
async function checkTurnLimits(ctx, turnId, calls) {
|
|
1877
1904
|
const history = await loadTurnAgentHistory(ctx, turnId);
|
|
1878
|
-
const
|
|
1879
|
-
const toolCallCount = replies.flatMap((reply) => reply.content).filter((part) => part.type === "toolCall").length;
|
|
1905
|
+
const toolCallCount = history.filter((message) => message.role === "assistant").flatMap((reply) => reply.content).filter((part) => part.type === "toolCall").length;
|
|
1880
1906
|
const results = history.filter((message) => message.role === "toolResult");
|
|
1881
|
-
const costUsd = agentTurnCostUsd(
|
|
1907
|
+
const costUsd = agentTurnCostUsd(await turnUsage(ctx, turnId, history)) ?? 0;
|
|
1882
1908
|
const overBudget = costUsd >= botConfig.maxTurnCostUsd;
|
|
1883
1909
|
const overToolCalls = toolCallCount > botConfig.maxToolCallsPerTurn;
|
|
1884
1910
|
const attributes = {
|
|
@@ -2028,4 +2054,4 @@ function createEngineContext(config) {
|
|
|
2028
2054
|
leaseMs: config.functionMaxDurationSeconds * 1e3
|
|
2029
2055
|
};
|
|
2030
2056
|
}
|
|
2031
|
-
export {
|
|
2057
|
+
export { turnStepConsumer as a, findTurn as c, readTurnEndedMessages as d, publishTurnStep as f, withSpan as g, countMetric as h, createGatewayModelClient as i, replyText as l, loadTurnAgentHistory as m, turnTools as n, scheduleInput as o, findTurnActor as p, turnUsage as r, findStalledTurns as s, createEngineContext as t, publishTurnEnded as u };
|
|
@@ -1,9 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { S as deleteMcpStoredOAuthCredentials, b as deleteMcpAuthSessionsForUserProvider, m as hasRequiredOAuthScope, x as deleteMcpServerSessionId } from "./registry-iXMT5Jmh.js";
|
|
6
|
-
import { n as pluginCatalogRuntime } from "./catalog-runtime-DfSpJZdY.js";
|
|
1
|
+
import { L as botConfig } from "./adapter-8_S6Birm.js";
|
|
2
|
+
import { Cc as deleteProviderIdentityForUser, Fd as getAppContext, Sc as deleteProviderIdentityForSlackUser, Xd as hasRequiredOAuthScope, if as deleteMcpStoredOAuthCredentials, nf as deleteMcpAuthSessionsForUserProvider, o as getSqlExecutor, rf as deleteMcpServerSessionId } from "./db-BCaNWl9p.js";
|
|
3
|
+
import { G as mapBounded } from "./prompt-3TqxEOtc.js";
|
|
4
|
+
import { di as startOAuthFlow } from "./markers-9QoqW5ov.js";
|
|
7
5
|
import { randomBytes } from "node:crypto";
|
|
8
6
|
// src/handlers/oauth-html.ts
|
|
9
7
|
/** Build pre-escaped callback HTML with the shared response security policy. */
|
|
@@ -188,12 +186,12 @@ async function readConnectedOAuthTokens(userId, plugin, userTokenStore) {
|
|
|
188
186
|
return stored && hasRequiredOAuthScope(stored.scope, plugin.manifest.oauth?.scope) ? stored : void 0;
|
|
189
187
|
}
|
|
190
188
|
function connectablePlugin(provider) {
|
|
191
|
-
const plugin =
|
|
189
|
+
const plugin = getAppContext().catalog.getDefinition(provider);
|
|
192
190
|
return plugin?.manifest.oauth ? plugin : void 0;
|
|
193
191
|
}
|
|
194
192
|
/** List OAuth plugins and the user's connection state for each one. */
|
|
195
193
|
async function listConnections(userId, userTokenStore) {
|
|
196
|
-
const plugins =
|
|
194
|
+
const plugins = getAppContext().catalog.getProviders().filter((plugin) => Boolean(plugin.manifest.oauth));
|
|
197
195
|
return await mapBounded(plugins, async (plugin) => {
|
|
198
196
|
const tokens = await readConnectedOAuthTokens(userId, plugin, userTokenStore);
|
|
199
197
|
const account = tokens?.account;
|