@sentry/junior 0.320.0 → 0.322.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-DlLLoJKj.js → adapter-CKtEUuWD.js} +23 -2
- package/dist/{admin-BzRXDVfh.js → admin-BGOiUGwR.js} +1 -1
- package/dist/{agent-DxZ7nHfD.js → agent-OUkEw6Bv.js} +276 -1648
- package/dist/{agent-status-Bq_AIpyp.js → agent-status-C_HHxO_d.js} +1 -10
- package/dist/{agent-update-delivery-CO4FU5Gg.js → agent-update-delivery-H6mnPI4q.js} +4 -4
- package/dist/api/schema.d.ts +98 -16
- package/dist/api/schema.js +6 -6
- package/dist/api.js +81 -36
- package/dist/{app-CHCFIIDu.d.ts → app-BK_vhZIq.d.ts} +1 -1
- package/dist/app.d.ts +1 -1
- package/dist/app.js +85 -48
- package/dist/{change-record-K-KsqNhT.d.ts → change-record-DdrJxahk.d.ts} +26 -15
- package/dist/{channel-access-BghWqlXx.js → channel-access-DRhVJIuQ.js} +1 -1
- package/dist/{chat-core-engine-BgfSLrDu.js → chat-core-engine-El308gYr.js} +5 -10
- package/dist/cli/chat.js +16 -16
- package/dist/cli/check.js +4 -4
- package/dist/cli/main.js +2 -2
- package/dist/cli/plugins.js +3 -3
- package/dist/cli/snapshot-create.js +4 -4
- package/dist/cli/upgrade.js +2 -2
- package/dist/{continue-in-slack-DBlQP4PC.js → continue-in-slack-DYl631oM.js} +3 -3
- package/dist/{conversation-feed-DEUdD7mb.js → conversation-feed-BUaMmSLi.js} +2 -12
- package/dist/{conversation-privacy-qoh95v90.js → conversation-privacy-DR_j5Tqf.js} +1 -1
- package/dist/{create-jZSaDrCR.js → create-ZkI-_JAs.js} +2 -2
- package/dist/{credential-sync-Bj9-UlNE.js → credential-sync-Bo6_FtCI.js} +12 -12
- package/dist/{db-BacvswT0.js → db-RDpWIeRK.js} +1744 -216
- package/dist/{deployment-BoJkRPDt.js → deployment-CeKaP0ZJ.js} +1 -1
- package/dist/{html-DW0pw5Pr.js → html-BMv4fAPu.js} +5 -5
- package/dist/instrumentation.js +2 -2
- package/dist/{list-Dz3CdP3g.js → list-CuLf7Ob2.js} +39 -70
- package/dist/{logging-DsTnMqyi.js → logging-BQsfrLHl.js} +1 -1
- package/dist/{markers-C33gNYNE.js → markers-Bh0vqJ5k.js} +3186 -1754
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +3 -4
- package/dist/{oauth-callback-server-C-pEhAQK.js → oauth-callback-server-BxuN0Jqz.js} +2 -2
- package/dist/{oauth-relay-DIXdH-io.js → oauth-relay-vyG2gOwY.js} +1 -1
- package/dist/{profile-v9vA3RvH.js → profile-DiAB4QfT.js} +39 -8
- package/dist/{prompt-C5CW2wKO.js → prompt-5PDkRQ1K.js} +2 -1
- package/dist/{reports-eBgrhPXS.js → reports-CbqB7unq.js} +2 -2
- package/dist/{resolve-HVXmbeCr.js → resolve-C7e0pwuP.js} +5 -5
- package/dist/{result-BPNzgeTl.js → result-D_D-2Adp.js} +7 -7
- package/dist/{runner-aNSDTST6.js → runner-CCVTdp0x.js} +7 -7
- package/dist/{sandbox-egress-signals-nzp9Ykf7.js → sandbox-egress-signals-D4OKOFgy.js} +1 -1
- package/dist/{schema-BlTO5M1d.js → schema-CmPO8BfI.js} +50 -12
- package/dist/{service-account-DWIf1t6p.js → service-account-CeWsFrBi.js} +2 -2
- package/dist/{skills-50izzzdK.js → skills-DfbOjWxl.js} +5 -5
- package/dist/{slack-conversation-unfurl-C6jXhVYg.js → slack-conversation-unfurl-BxF0Yb3-.js} +10 -9
- package/dist/{system-prompt-table-CIR1B44Z.js → system-prompt-table-DySHMtu0.js} +17 -17
- package/dist/{topics-DxuKurCX.js → topic-ChZe9WPj.js} +6 -1
- package/dist/{engine-context-Bi3Ync5t.js → turn-ended-DQ10G3in.js} +11 -845
- package/dist/{types-BNHkJrOP.js → types-BWAgOJtR.js} +95 -78
- package/dist/{user-customization-CvfuY9Eo.js → user-customization-DNzu_r1x.js} +10 -1
- package/dist/{users-DOVo9sdU.js → users-BmZlg_ci.js} +13 -7
- package/dist/{validation-CK0vuEHB.js → validation-BU4tXvH3.js} +1 -1
- package/dist/{version-BuLVNlxB.js → version-D9yLYOBu.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{worker-C82kHU1R.js → worker-C7EDSL3d.js} +4 -4
- package/migrations/20261127184420_question_answerer/migration.sql +36 -0
- package/migrations/20261127184420_question_answerer/snapshot.json +108 -0
- package/migrations/20261127224730_inbox_item_close_action/migration.sql +1 -0
- package/migrations/20261127224730_inbox_item_close_action/snapshot.json +42 -0
- package/package.json +6 -6
- package/skills/design-automation-skill/SKILL.md +1 -1
- package/dist/storage-BtCxXiNt.js +0 -273
- package/dist/topic-B2EWKKBT.js +0 -6
|
@@ -1,20 +1,15 @@
|
|
|
1
|
-
import { $ as resolveGatewayModel, L as botConfig, f as credentialContextForActor } from "./adapter-
|
|
2
|
-
import { $
|
|
3
|
-
import {
|
|
4
|
-
import { _ as serializeGenAiAttribute, f as logException, h as normalizeGenAiFinishReason, i as extractGenAiUsageSummary, m as logWarn, r as extractGenAiUsageAttributes } from "./logging-
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import { A as createBashTool, D as createWriteFileTool, E as createSystemTimeTool, O as createReadFileTool, c as createAgentSandbox, dn as isRetryableSlackPostError, k as createEditFileTool, l as normalizeToolResult, n as buildSandboxInput, u as capToolResult } from "./agent-DxZ7nHfD.js";
|
|
10
|
-
import { n as TURN_STEP_TOPIC, t as TURN_ENDED_TOPIC } from "./topic-B2EWKKBT.js";
|
|
1
|
+
import { $ as resolveGatewayModel, L as botConfig, f as credentialContextForActor } from "./adapter-CKtEUuWD.js";
|
|
2
|
+
import { $n as publishTurnEnded, An as turnInputPayloadSchema, Cf as getGatewayApiKey, D as startLocationThread, Em as juniorTurns, Gn as replyText, Hn as holdsLease, Im as juniorConversations, Jn as findTurnActor, Kn as createTurnStepConsumer, Ko as microUsdToUsd, Kr as sendSlackReply, Ln as claimTurn, Mp as agentTurnCostUsd, Nn as endFailedTurn, Np as agentTurnTotalTokens, O as locationSchema, P as replaceConversationMetrics, Pn as reconcileTurn, Qn as markInputsAttempted, Rn as commitStep, Tm as juniorConversationEvents, Un as releaseTurn, Vn as findTurn, Wn as findTurnReplies, Xn as findTurnInputs, Yi as runWithSlackInstallation, Yn as findTurnDestination, Zn as findUnreadInputs, Zp as juniorTurnOutbox, a as getDb, d as createSqlConversationEventStore, df as gatewayRoutingAttributes, er as readTurnEndedMessages, if as requestPrefixAttributes, jp as addAgentTurnUsage, k as claimProviderConversation, nr as setActiveSpanAttributes, o as getSqlExecutor, qn as publishTurnStep, rr as withSpan, w as withConversationMutationLock, wc as resolveRootVisibility, zn as findDiscardedUsage } from "./db-RDpWIeRK.js";
|
|
3
|
+
import { dt as agentHistoryFromRow, ht as HISTORY_REPLACEMENT_TYPES, mt as AGENT_HISTORY_ITEM_TYPES, vt as isHistoryReplacement, wt as instructionProvenanceFor, yt as piMessageFromHistoryItem } from "./types-BWAgOJtR.js";
|
|
4
|
+
import { _ as serializeGenAiAttribute, f as logException, h as normalizeGenAiFinishReason, i as extractGenAiUsageSummary, m as logWarn, r as extractGenAiUsageAttributes } from "./logging-BQsfrLHl.js";
|
|
5
|
+
import { G as mapBounded } from "./prompt-5PDkRQ1K.js";
|
|
6
|
+
import { a as toCanonicalInputMessage, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-DR_j5Tqf.js";
|
|
7
|
+
import { B as getLocationConfigurationService, Cn as getWorkspace, Di as reviewToolActions, H as getPersistedThreadState, Ln as buildDeploymentSystemPrompt, Tr as normalizeConversationText, U as persistThreadRuntimeState, V as getPersistedSandboxState, fi as TurnToolCallLimitExceededError, gr as toStoredConversationMessage, li as TURN_LIMIT_WRAP_UP_MESSAGE, oi as turnStartedKey, si as turnTerminalKey, ui as TurnBudgetExceededError } from "./markers-Bh0vqJ5k.js";
|
|
8
|
+
import { A as createBashTool, D as createWriteFileTool, E as createSystemTimeTool, O as createReadFileTool, c as createAgentSandbox, k as createEditFileTool, l as normalizeToolResult, ln as isRetryableSlackPostError, n as buildSandboxInput, u as capToolResult } from "./agent-OUkEw6Bv.js";
|
|
11
9
|
import * as z from "zod";
|
|
12
10
|
import { streamSimple } from "@earendil-works/pi-ai/compat";
|
|
13
|
-
import { and, asc, eq,
|
|
14
|
-
import {
|
|
15
|
-
import { actorSchema, destinationSchema, markdownNodes, parseMarkdown } from "@sentry/junior-plugin-api";
|
|
16
|
-
import * as Sentry from "@sentry/node";
|
|
17
|
-
import { randomUUID } from "node:crypto";
|
|
11
|
+
import { and, asc, eq, inArray, max, sql } from "drizzle-orm";
|
|
12
|
+
import { destinationSchema } from "@sentry/junior-plugin-api";
|
|
18
13
|
import { toToolDeclaration, validateToolArguments } from "@earendil-works/pi-ai";
|
|
19
14
|
import { performance as performance$1 } from "node:perf_hooks";
|
|
20
15
|
// src/core/model/failure.ts
|
|
@@ -191,62 +186,6 @@ function responseTiming(requestStartedAtMs) {
|
|
|
191
186
|
}
|
|
192
187
|
};
|
|
193
188
|
}
|
|
194
|
-
// src/core/telemetry.ts
|
|
195
|
-
const SENTRY_TRACE_PATTERN = /^([0-9a-f]{32})-([0-9a-f]{16})(?:-([01]))?$/;
|
|
196
|
-
function spanLink({ sentryTrace }) {
|
|
197
|
-
const [, traceId, spanId, sampled] = SENTRY_TRACE_PATTERN.exec(sentryTrace) ?? [];
|
|
198
|
-
return traceId && spanId ? [{ context: {
|
|
199
|
-
traceId,
|
|
200
|
-
spanId,
|
|
201
|
-
traceFlags: sampled === "1" ? 1 : 0
|
|
202
|
-
} }] : [];
|
|
203
|
-
}
|
|
204
|
-
/** Returns the trace context of the active span, so other work can link to it. */
|
|
205
|
-
function activeTraceContext() {
|
|
206
|
-
const sentryTrace = Sentry.getTraceData()["sentry-trace"];
|
|
207
|
-
return sentryTrace ? { sentryTrace } : void 0;
|
|
208
|
-
}
|
|
209
|
-
/** Sets attributes on the active span, such as ids that a step learns late. */
|
|
210
|
-
function setActiveSpanAttributes(attributes) {
|
|
211
|
-
Sentry.getActiveSpan()?.setAttributes(attributes);
|
|
212
|
-
}
|
|
213
|
-
/** Adds one to a counter metric. Metrics are not sampled, unlike spans. */
|
|
214
|
-
function countMetric(name, attributes) {
|
|
215
|
-
Sentry.metrics.count(name, 1, { attributes });
|
|
216
|
-
}
|
|
217
|
-
const SPAN_STATUS_ERROR = 2;
|
|
218
|
-
/** Runs `run` in a span whose op is `name`, and whose name is too by default. */
|
|
219
|
-
function withSpan(name, attributes, run, options = {}) {
|
|
220
|
-
const start = () => Sentry.startSpanManual({
|
|
221
|
-
name: options.spanName ?? name,
|
|
222
|
-
op: name,
|
|
223
|
-
attributes,
|
|
224
|
-
links: options.links?.flatMap(spanLink)
|
|
225
|
-
}, async (span) => {
|
|
226
|
-
try {
|
|
227
|
-
return await run({
|
|
228
|
-
setAttribute: (key, value) => span.setAttribute(key, value),
|
|
229
|
-
setAttributes: (values) => span.setAttributes(values),
|
|
230
|
-
fail: (message) => span.setStatus({
|
|
231
|
-
code: SPAN_STATUS_ERROR,
|
|
232
|
-
message
|
|
233
|
-
})
|
|
234
|
-
});
|
|
235
|
-
} catch (error) {
|
|
236
|
-
if (!options.isExpectedError?.(error)) {
|
|
237
|
-
span.setStatus({
|
|
238
|
-
code: SPAN_STATUS_ERROR,
|
|
239
|
-
message: "internal_error"
|
|
240
|
-
});
|
|
241
|
-
span.setAttribute("error.type", error instanceof Error ? error.name : typeof error);
|
|
242
|
-
}
|
|
243
|
-
throw error;
|
|
244
|
-
} finally {
|
|
245
|
-
span.end();
|
|
246
|
-
}
|
|
247
|
-
});
|
|
248
|
-
return options.newTrace ? Sentry.startNewTrace(start) : start();
|
|
249
|
-
}
|
|
250
189
|
// src/core/model/client.ts
|
|
251
190
|
function errorName(error) {
|
|
252
191
|
return error instanceof Error ? error.name : "Error";
|
|
@@ -612,763 +551,6 @@ var TurnFailedError = class extends Error {
|
|
|
612
551
|
this.failure = failure;
|
|
613
552
|
}
|
|
614
553
|
};
|
|
615
|
-
// src/core/turn/inbox.ts
|
|
616
|
-
/**
|
|
617
|
-
* Finds the Turn of the input that has this idempotency key in the
|
|
618
|
-
* Conversation. Undefined when no such input exists.
|
|
619
|
-
*/
|
|
620
|
-
async function findInputTurn({ executor }, args) {
|
|
621
|
-
const [turn] = await executor.db().select({
|
|
622
|
-
turnId: juniorTurns.id,
|
|
623
|
-
state: juniorTurns.state
|
|
624
|
-
}).from(juniorTurnInbox).innerJoin(juniorTurns, eq(juniorTurns.id, juniorTurnInbox.turnId)).where(and(eq(juniorTurnInbox.conversationId, args.conversationId), eq(juniorTurnInbox.idempotencyKey, args.idempotencyKey)));
|
|
625
|
-
return turn;
|
|
626
|
-
}
|
|
627
|
-
/**
|
|
628
|
-
* Finds where a Turn's answer goes: the Destination of its first input. Null
|
|
629
|
-
* when the Turn answers only in the Conversation history.
|
|
630
|
-
*/
|
|
631
|
-
async function findTurnDestination({ executor }, turnId) {
|
|
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);
|
|
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;
|
|
642
|
-
}
|
|
643
|
-
/** Finds every input of a Turn, oldest first. */
|
|
644
|
-
async function findTurnInputs({ executor }, turnId) {
|
|
645
|
-
return executor.db().select({
|
|
646
|
-
inputId: juniorTurnInbox.id,
|
|
647
|
-
payload: juniorTurnInbox.payload
|
|
648
|
-
}).from(juniorTurnInbox).where(eq(juniorTurnInbox.turnId, turnId)).orderBy(asc(juniorTurnInbox.sentAt), asc(juniorTurnInbox.createdAt));
|
|
649
|
-
}
|
|
650
|
-
const INPUT_EVENT_KEY_PREFIX = "inbox:";
|
|
651
|
-
/** The idempotency key of the history event that reads an input. */
|
|
652
|
-
function inputEventKey(inputId) {
|
|
653
|
-
return `${INPUT_EVENT_KEY_PREFIX}${inputId}`;
|
|
654
|
-
}
|
|
655
|
-
/** Finds the inputs of a Turn that the history has not read, oldest first. */
|
|
656
|
-
async function findUnreadInputs({ executor }, turnId) {
|
|
657
|
-
const db = executor.db();
|
|
658
|
-
const readEvent = db.select({ one: sql`1` }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, juniorTurnInbox.conversationId), eq(juniorConversationEvents.idempotencyKey, sql`${INPUT_EVENT_KEY_PREFIX}::text || ${juniorTurnInbox.id}::text`)));
|
|
659
|
-
return db.select({
|
|
660
|
-
inputId: juniorTurnInbox.id,
|
|
661
|
-
actorIdentityId: juniorTurnInbox.actorIdentityId,
|
|
662
|
-
groupKey: juniorTurnInbox.groupKey,
|
|
663
|
-
payload: juniorTurnInbox.payload,
|
|
664
|
-
sentAt: juniorTurnInbox.sentAt,
|
|
665
|
-
traceContext: juniorTurnInbox.traceContext,
|
|
666
|
-
attemptedAt: juniorTurnInbox.attemptedAt
|
|
667
|
-
}).from(juniorTurnInbox).where(and(eq(juniorTurnInbox.turnId, turnId), notExists(readEvent))).orderBy(asc(juniorTurnInbox.sentAt), asc(juniorTurnInbox.createdAt));
|
|
668
|
-
}
|
|
669
|
-
/**
|
|
670
|
-
* Records that an attempt of the Turn claimed it with these inputs unread.
|
|
671
|
-
* The first attempt keeps its time. It does not mark the inputs read.
|
|
672
|
-
*/
|
|
673
|
-
async function markInputsAttempted({ executor }, inputIds) {
|
|
674
|
-
if (inputIds.length === 0) return;
|
|
675
|
-
await executor.db().update(juniorTurnInbox).set({ attemptedAt: sql`coalesce(${juniorTurnInbox.attemptedAt}, now())` }).where(inArray(juniorTurnInbox.id, inputIds));
|
|
676
|
-
}
|
|
677
|
-
// src/core/queue.ts
|
|
678
|
-
const VISIBILITY_TIMEOUT_BUFFER_SECONDS = 30;
|
|
679
|
-
/** Defines one signed topic. Returns its publish function and its consumer. */
|
|
680
|
-
function signedTopic(def) {
|
|
681
|
-
const publish = async ({ queue }, message, options = {}) => {
|
|
682
|
-
await withSpan("queue.publish", {
|
|
683
|
-
...def.attributes(message),
|
|
684
|
-
"messaging.destination.name": def.topic,
|
|
685
|
-
"messaging.system": queue.messagingSystem
|
|
686
|
-
}, async (span) => {
|
|
687
|
-
const traceContext = activeTraceContext();
|
|
688
|
-
const payload = signQueueMessage(def.sign, traceContext ? {
|
|
689
|
-
...message,
|
|
690
|
-
traceContext
|
|
691
|
-
} : message);
|
|
692
|
-
span.setAttribute("messaging.message.body.size", Buffer.byteLength(JSON.stringify(payload)));
|
|
693
|
-
const result = await queue.send(def.topic, payload, {
|
|
694
|
-
delaySeconds: options.delayMs && options.delayMs > 0 ? Math.ceil(options.delayMs / 1e3) : void 0,
|
|
695
|
-
idempotencyKey: options.idempotencyKey,
|
|
696
|
-
retentionSeconds: QUEUE_SIGNATURE_MAX_AGE_MS / 1e3
|
|
697
|
-
});
|
|
698
|
-
if (result.messageId) span.setAttribute("messaging.message.id", result.messageId);
|
|
699
|
-
});
|
|
700
|
-
};
|
|
701
|
-
const consumer = ({ queue, leaseMs }, run) => ({
|
|
702
|
-
handler: async (value, metadata) => {
|
|
703
|
-
const checked = verifyQueueMessage(def.sign, value);
|
|
704
|
-
if (checked.status === "rejected") {
|
|
705
|
-
def.onRejected({
|
|
706
|
-
"app.queue.consumer_group": metadata.consumerGroup,
|
|
707
|
-
"app.queue.delivery_count": metadata.deliveryCount,
|
|
708
|
-
"app.queue.message_id": metadata.messageId,
|
|
709
|
-
"app.queue.reject_reason": checked.reason,
|
|
710
|
-
"app.queue.topic_name": metadata.topicName
|
|
711
|
-
});
|
|
712
|
-
return;
|
|
713
|
-
}
|
|
714
|
-
if (checked.status === "unavailable") throw new Error(`Queue message verification unavailable: ${checked.reason}`);
|
|
715
|
-
const message = checked.message;
|
|
716
|
-
await withSpan("queue.process", {
|
|
717
|
-
...def.attributes(message),
|
|
718
|
-
"messaging.destination.name": metadata.topicName,
|
|
719
|
-
"messaging.system": queue.messagingSystem,
|
|
720
|
-
"messaging.message.id": metadata.messageId,
|
|
721
|
-
"messaging.message.receive.latency": Date.now() - metadata.createdAt.getTime(),
|
|
722
|
-
"messaging.message.retry.count": metadata.deliveryCount - 1
|
|
723
|
-
}, () => run(message, metadata), {
|
|
724
|
-
links: message.traceContext ? [message.traceContext] : [],
|
|
725
|
-
newTrace: true
|
|
726
|
-
});
|
|
727
|
-
},
|
|
728
|
-
retry: () => void 0,
|
|
729
|
-
visibilityTimeoutSeconds: leaseMs / 1e3 + VISIBILITY_TIMEOUT_BUFFER_SECONDS
|
|
730
|
-
});
|
|
731
|
-
return {
|
|
732
|
-
publish,
|
|
733
|
-
consumer
|
|
734
|
-
};
|
|
735
|
-
}
|
|
736
|
-
// src/core/turn/queue.ts
|
|
737
|
-
const turnStepMessageSchema = z.object({
|
|
738
|
-
turnId: z.string().min(1),
|
|
739
|
-
traceContext: z.object({ sentryTrace: z.string().min(1) }).strict().optional()
|
|
740
|
-
}).strict();
|
|
741
|
-
const turnStepTopic = signedTopic({
|
|
742
|
-
topic: TURN_STEP_TOPIC,
|
|
743
|
-
sign: {
|
|
744
|
-
context: "junior.turn_step.v1",
|
|
745
|
-
schema: turnStepMessageSchema,
|
|
746
|
-
signatureVersion: "v1",
|
|
747
|
-
parts: (message) => [message.turnId, message.traceContext?.sentryTrace ?? ""]
|
|
748
|
-
},
|
|
749
|
-
onRejected: (attributes) => logWarn("turn.step.queue_message.rejected", attributes),
|
|
750
|
-
attributes: (message) => ({ "app.turn.id": message.turnId })
|
|
751
|
-
});
|
|
752
|
-
/**
|
|
753
|
-
* Sends a message that runs the next step of a Turn. `idempotencyKey` drops a
|
|
754
|
-
* second send with the same key.
|
|
755
|
-
*/
|
|
756
|
-
async function publishTurnStep(ctx, turnId, options = {}) {
|
|
757
|
-
await turnStepTopic.publish(ctx, { turnId }, options);
|
|
758
|
-
}
|
|
759
|
-
/**
|
|
760
|
-
* Builds the queue consumer of Turn step messages. It acknowledges a message
|
|
761
|
-
* with a bad or expired signature and retries one that cannot be checked yet.
|
|
762
|
-
* advanceTurn fails a Turn after `maxAttempts` tries of one step. The host
|
|
763
|
-
* mounts the consumer on its queue provider.
|
|
764
|
-
*/
|
|
765
|
-
function createTurnStepConsumer(ctx, run) {
|
|
766
|
-
return turnStepTopic.consumer(ctx, (message, metadata) => run({ turnId: message.turnId }, metadata));
|
|
767
|
-
}
|
|
768
|
-
// src/core/turn/ended.ts
|
|
769
|
-
const turnEndedMessageSchema = z.object({
|
|
770
|
-
conversationId: z.string().min(1),
|
|
771
|
-
turnId: z.string().min(1),
|
|
772
|
-
traceContext: z.object({ sentryTrace: z.string().min(1) }).strict().optional()
|
|
773
|
-
}).strict();
|
|
774
|
-
const turnEndedTopic = signedTopic({
|
|
775
|
-
topic: TURN_ENDED_TOPIC,
|
|
776
|
-
sign: {
|
|
777
|
-
context: "junior.turn_ended.v1",
|
|
778
|
-
schema: turnEndedMessageSchema,
|
|
779
|
-
signatureVersion: "v1",
|
|
780
|
-
parts: (message) => [
|
|
781
|
-
message.conversationId,
|
|
782
|
-
message.turnId,
|
|
783
|
-
message.traceContext?.sentryTrace ?? ""
|
|
784
|
-
]
|
|
785
|
-
},
|
|
786
|
-
onRejected: (attributes) => logWarn("turn.ended.queue_message.rejected", attributes),
|
|
787
|
-
attributes: (message) => ({
|
|
788
|
-
"app.turn.id": message.turnId,
|
|
789
|
-
"gen_ai.conversation.id": message.conversationId
|
|
790
|
-
})
|
|
791
|
-
});
|
|
792
|
-
/**
|
|
793
|
-
* Sends the message that the Turn ended, after `delayMs` if set. A handler
|
|
794
|
-
* that must try its work again later sends it again with a delay.
|
|
795
|
-
*/
|
|
796
|
-
async function publishTurnEnded(ctx, message, options = {}) {
|
|
797
|
-
await turnEndedTopic.publish(ctx, message, options);
|
|
798
|
-
}
|
|
799
|
-
/**
|
|
800
|
-
* Reads the messages that a Turn ended: it checks that core sent each one,
|
|
801
|
-
* then calls `handle`. It acknowledges a message with a bad or expired
|
|
802
|
-
* signature and retries one that cannot be checked yet. The host mounts the
|
|
803
|
-
* consumer on its queue provider.
|
|
804
|
-
*/
|
|
805
|
-
function readTurnEndedMessages(ctx, handle) {
|
|
806
|
-
return turnEndedTopic.consumer(ctx, (message, metadata) => handle({
|
|
807
|
-
conversationId: message.conversationId,
|
|
808
|
-
turnId: message.turnId
|
|
809
|
-
}, metadata));
|
|
810
|
-
}
|
|
811
|
-
// src/core/history/write.ts
|
|
812
|
-
/**
|
|
813
|
-
* Appends the agent history items that one Turn writes, in order, at the
|
|
814
|
-
* current History version. Skips an item whose idempotency key is already
|
|
815
|
-
* stored. Call it under `withConversationEventLock`.
|
|
816
|
-
*/
|
|
817
|
-
async function appendAgentHistory(executor, conversationId, turnId, items) {
|
|
818
|
-
const pending = await unseenEvents(executor, conversationId, items);
|
|
819
|
-
if (pending.length === 0) return;
|
|
820
|
-
await insertEventRows(executor, conversationId, await readEventCursor(executor, conversationId), pending.map(({ item, idempotencyKey, createdAtMs }) => ({
|
|
821
|
-
type: item.type,
|
|
822
|
-
...encodeAgentHistoryPayload(item),
|
|
823
|
-
idempotencyKey,
|
|
824
|
-
turnId,
|
|
825
|
-
createdAtMs
|
|
826
|
-
})));
|
|
827
|
-
}
|
|
828
|
-
// src/core/turn/replies.ts
|
|
829
|
-
const LEGACY_NO_REPLY_MARKERS = ["[[NO_REPLY]]", "[[QUIET]]"];
|
|
830
|
-
const THINKING_BLOCK_PATTERN = /[ \t]*<thinking\b[^>]*>[\s\S]*?<\/thinking>[ \t]*(?:\r?\n)?/gi;
|
|
831
|
-
function isClosedFence(source) {
|
|
832
|
-
const opener = source.trimStart();
|
|
833
|
-
const marker = opener.startsWith("```") ? "`" : opener.startsWith("~~~") ? "~" : void 0;
|
|
834
|
-
const lastLine = source.lastIndexOf("\n");
|
|
835
|
-
let closer = lastLine < 0 ? "" : source.slice(lastLine + 1).trim();
|
|
836
|
-
while (closer.startsWith(">")) closer = closer.slice(1).trimStart();
|
|
837
|
-
return marker !== void 0 && closer.length >= 3 && closer === marker.repeat(closer.length);
|
|
838
|
-
}
|
|
839
|
-
function stripThinking(text) {
|
|
840
|
-
let result = "";
|
|
841
|
-
let cursor = 0;
|
|
842
|
-
for (const { position } of markdownNodes(parseMarkdown(text), ["code"])) {
|
|
843
|
-
const start = position?.start.offset ?? 0;
|
|
844
|
-
const end = position?.end.offset ?? 0;
|
|
845
|
-
if (!isClosedFence(text.slice(start, end))) continue;
|
|
846
|
-
result += text.slice(cursor, start).replace(THINKING_BLOCK_PATTERN, "");
|
|
847
|
-
result += text.slice(start, end);
|
|
848
|
-
cursor = end;
|
|
849
|
-
}
|
|
850
|
-
return result + text.slice(cursor).replace(THINKING_BLOCK_PATTERN, "");
|
|
851
|
-
}
|
|
852
|
-
/**
|
|
853
|
-
* The text that an assistant message delivers to a person, or undefined when
|
|
854
|
-
* it is no reply. Text next to a tool call is the model working, not a reply.
|
|
855
|
-
*/
|
|
856
|
-
function assistantReplyText(message) {
|
|
857
|
-
if (message.content.some((part) => part.type === "toolCall")) return;
|
|
858
|
-
const text = stripThinking(message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n")).trim();
|
|
859
|
-
return text && !LEGACY_NO_REPLY_MARKERS.includes(text) ? text : void 0;
|
|
860
|
-
}
|
|
861
|
-
/** The key prefix of the message events that a Turn's steps wrote. */
|
|
862
|
-
function turnEventKeyPrefix(turnId) {
|
|
863
|
-
return `step:${turnId}:`;
|
|
864
|
-
}
|
|
865
|
-
/** The text that a message event delivers, or undefined when it is no reply. */
|
|
866
|
-
function replyText(row) {
|
|
867
|
-
if (row.type !== "assistant_message") return;
|
|
868
|
-
const data = agentHistoryFromRow(row);
|
|
869
|
-
if (data.type !== "assistant_message") return;
|
|
870
|
-
const message = piMessageFromHistoryItem(data);
|
|
871
|
-
return message.role === "assistant" ? assistantReplyText(message) : void 0;
|
|
872
|
-
}
|
|
873
|
-
/** Finds the reply events of a Turn, in history order. */
|
|
874
|
-
async function findTurnReplies({ executor }, conversationId, turnId) {
|
|
875
|
-
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);
|
|
876
|
-
}
|
|
877
|
-
// src/core/turn/outbox.ts
|
|
878
|
-
/**
|
|
879
|
-
* Adds an outbox row for each reply of the Turn that has none, but only while
|
|
880
|
-
* the Turn has a Destination. Call it in the transaction that commits the
|
|
881
|
-
* replies.
|
|
882
|
-
*/
|
|
883
|
-
async function recordReplies({ executor }, turn) {
|
|
884
|
-
const destination = await findTurnDestination({ executor }, turn.turnId);
|
|
885
|
-
if (!destination) return;
|
|
886
|
-
const replies = await findTurnReplies({ executor }, turn.conversationId, turn.turnId);
|
|
887
|
-
if (replies.length === 0) return;
|
|
888
|
-
await executor.db().insert(juniorTurnOutbox).values(replies.map((row) => ({
|
|
889
|
-
id: randomUUID(),
|
|
890
|
-
conversationId: turn.conversationId,
|
|
891
|
-
turnId: turn.turnId,
|
|
892
|
-
eventSeq: row.seq,
|
|
893
|
-
destination,
|
|
894
|
-
state: "pending"
|
|
895
|
-
}))).onConflictDoNothing({ target: [juniorTurnOutbox.conversationId, juniorTurnOutbox.eventSeq] });
|
|
896
|
-
}
|
|
897
|
-
// src/core/turn/state.ts
|
|
898
|
-
/**
|
|
899
|
-
* Turn priorities: a lower number runs first. A Turn that supersedes the
|
|
900
|
-
* running Turn runs before every other queued Turn.
|
|
901
|
-
*/
|
|
902
|
-
const TURN_PRIORITY = {
|
|
903
|
-
supersede: 0,
|
|
904
|
-
normal: 1
|
|
905
|
-
};
|
|
906
|
-
const SUPERSEDED_END = {
|
|
907
|
-
state: "cancelled",
|
|
908
|
-
endReason: "superseded",
|
|
909
|
-
endedAt: sql`now()`
|
|
910
|
-
};
|
|
911
|
-
function leaseExpiry(leaseMs) {
|
|
912
|
-
return sql`now() + ${leaseMs}::integer * interval '1 millisecond'`;
|
|
913
|
-
}
|
|
914
|
-
function leaseFence(lease) {
|
|
915
|
-
return and(eq(juniorTurns.id, lease.turnId), eq(juniorTurns.state, "running"), eq(juniorTurns.leaseEpoch, lease.leaseEpoch));
|
|
916
|
-
}
|
|
917
|
-
/**
|
|
918
|
-
* Inserts a queued Turn. It sends no step message: the caller publishes the
|
|
919
|
-
* Turn after its transaction commits, so a worker can claim it.
|
|
920
|
-
*/
|
|
921
|
-
async function createTurn({ executor }, args) {
|
|
922
|
-
const turnId = randomUUID();
|
|
923
|
-
await executor.db().insert(juniorTurns).values({
|
|
924
|
-
...args,
|
|
925
|
-
id: turnId,
|
|
926
|
-
state: "queued"
|
|
927
|
-
});
|
|
928
|
-
return {
|
|
929
|
-
turnId,
|
|
930
|
-
state: "queued"
|
|
931
|
-
};
|
|
932
|
-
}
|
|
933
|
-
/** Finds a Turn by id. Undefined when it does not exist. */
|
|
934
|
-
async function findTurn({ executor }, turnId) {
|
|
935
|
-
const [turn] = await executor.db().select({
|
|
936
|
-
turnId: juniorTurns.id,
|
|
937
|
-
state: juniorTurns.state,
|
|
938
|
-
conversationId: juniorTurns.conversationId,
|
|
939
|
-
failureCode: juniorTurns.failureCode,
|
|
940
|
-
failureReason: juniorTurns.failureReason,
|
|
941
|
-
failureEventId: juniorTurns.failureEventId,
|
|
942
|
-
startedAt: juniorTurns.startedAt,
|
|
943
|
-
endedAt: juniorTurns.endedAt
|
|
944
|
-
}).from(juniorTurns).where(eq(juniorTurns.id, turnId));
|
|
945
|
-
return turn;
|
|
946
|
-
}
|
|
947
|
-
/** Reads a Turn's discarded usage. Undefined when the Turn does not exist. */
|
|
948
|
-
async function findDiscardedUsage({ executor }, turnId) {
|
|
949
|
-
return selectDiscardedUsage({ executor }, eq(juniorTurns.id, turnId));
|
|
950
|
-
}
|
|
951
|
-
async function selectDiscardedUsage({ executor }, where) {
|
|
952
|
-
const [turn] = await executor.db().select({
|
|
953
|
-
costMicroUsd: juniorTurns.discardedCostMicroUsd,
|
|
954
|
-
tokens: juniorTurns.discardedTokens
|
|
955
|
-
}).from(juniorTurns).where(where);
|
|
956
|
-
if (!turn) return;
|
|
957
|
-
return turn.tokens === null ? { costMicroUsd: turn.costMicroUsd } : {
|
|
958
|
-
costMicroUsd: turn.costMicroUsd,
|
|
959
|
-
tokens: usageTokensSchema.parse(turn.tokens)
|
|
960
|
-
};
|
|
961
|
-
}
|
|
962
|
-
async function discardedUsageUpdate({ executor }, lease, usage) {
|
|
963
|
-
const current = usage ? await selectDiscardedUsage({ executor }, leaseFence(lease)) : void 0;
|
|
964
|
-
if (!current) return {};
|
|
965
|
-
const { cost: _, ...tokens } = addAgentTurnUsage(current.tokens, usage) ?? {};
|
|
966
|
-
return {
|
|
967
|
-
discardedCostMicroUsd: current.costMicroUsd + usdToMicroUsd(agentTurnCostUsd(usage) ?? 0),
|
|
968
|
-
discardedTokens: tokens
|
|
969
|
-
};
|
|
970
|
-
}
|
|
971
|
-
const runOrder = [
|
|
972
|
-
sql`${juniorTurns.state} = 'running' desc`,
|
|
973
|
-
asc(juniorTurns.priority),
|
|
974
|
-
asc(juniorTurns.createdAt),
|
|
975
|
-
asc(juniorTurns.id)
|
|
976
|
-
];
|
|
977
|
-
/**
|
|
978
|
-
* Finds the Turn of a Conversation that has not ended: the running Turn, else
|
|
979
|
-
* the next queued Turn by priority and age.
|
|
980
|
-
*/
|
|
981
|
-
async function findOpenTurn({ executor }, conversationId) {
|
|
982
|
-
const [turn] = await executor.db().select({
|
|
983
|
-
turnId: juniorTurns.id,
|
|
984
|
-
state: juniorTurns.state
|
|
985
|
-
}).from(juniorTurns).where(and(eq(juniorTurns.conversationId, conversationId), inArray(juniorTurns.state, ["queued", "running"]))).orderBy(...runOrder).limit(1);
|
|
986
|
-
return turn;
|
|
987
|
-
}
|
|
988
|
-
/**
|
|
989
|
-
* Finds the Turns of a Conversation that can still take inputs, in run order:
|
|
990
|
-
* those that have not ended, less a running Turn that another Turn
|
|
991
|
-
* supersedes.
|
|
992
|
-
*/
|
|
993
|
-
async function findOpenTurns({ executor }, conversationId) {
|
|
994
|
-
return (await executor.db().select({
|
|
995
|
-
turnId: juniorTurns.id,
|
|
996
|
-
state: juniorTurns.state,
|
|
997
|
-
groupKey: juniorTurnInbox.groupKey,
|
|
998
|
-
stepSeq: juniorTurns.stepSeq,
|
|
999
|
-
attempts: juniorTurns.attempts
|
|
1000
|
-
}).from(juniorTurns).innerJoin(juniorTurnInbox, eq(juniorTurnInbox.turnId, juniorTurns.id)).where(and(eq(juniorTurns.conversationId, conversationId), or(eq(juniorTurns.state, "queued"), and(eq(juniorTurns.state, "running"), notExists(turnAhead({ executor })))))).groupBy(juniorTurns.id, juniorTurnInbox.groupKey).orderBy(...runOrder)).map(({ stepSeq, attempts, ...turn }) => ({
|
|
1001
|
-
...turn,
|
|
1002
|
-
started: stepSeq > 0 || attempts > 0
|
|
1003
|
-
}));
|
|
1004
|
-
}
|
|
1005
|
-
function turnAhead({ executor }) {
|
|
1006
|
-
const ahead = alias(juniorTurns, "ahead");
|
|
1007
|
-
return executor.db().select({ one: sql`1` }).from(ahead).where(and(eq(ahead.conversationId, juniorTurns.conversationId), ne(ahead.id, juniorTurns.id), or(eq(ahead.state, "running"), and(eq(ahead.state, "queued"), sql`(${ahead.priority}, ${ahead.createdAt}, ${ahead.id}) < (${juniorTurns.priority}, ${juniorTurns.createdAt}, ${juniorTurns.id})`))));
|
|
1008
|
-
}
|
|
1009
|
-
async function isSuperseded({ executor }, turnId) {
|
|
1010
|
-
return (await executor.db().select({ id: juniorTurns.id }).from(juniorTurns).where(and(eq(juniorTurns.id, turnId), exists(turnAhead({ executor }))))).length > 0;
|
|
1011
|
-
}
|
|
1012
|
-
/**
|
|
1013
|
-
* Makes way for a Turn that supersedes this one. Call it under the
|
|
1014
|
-
* Conversation lock. A queued Turn has no step in flight, so it ends now and
|
|
1015
|
-
* moves `lease_epoch`. A running Turn moves behind the new Turn, and
|
|
1016
|
-
* `commitStep` or `releaseTurn` ends it, so the step's work is kept. True
|
|
1017
|
-
* when the Turn ended now.
|
|
1018
|
-
*/
|
|
1019
|
-
async function supersedeTurn({ executor }, turnId) {
|
|
1020
|
-
const db = executor.db();
|
|
1021
|
-
const ended = await db.update(juniorTurns).set({
|
|
1022
|
-
...SUPERSEDED_END,
|
|
1023
|
-
leaseEpoch: sql`${juniorTurns.leaseEpoch} + 1`,
|
|
1024
|
-
updatedAt: sql`now()`
|
|
1025
|
-
}).where(and(eq(juniorTurns.id, turnId), eq(juniorTurns.state, "queued"))).returning({ id: juniorTurns.id });
|
|
1026
|
-
await db.update(juniorTurns).set({
|
|
1027
|
-
priority: TURN_PRIORITY.normal,
|
|
1028
|
-
updatedAt: sql`now()`
|
|
1029
|
-
}).where(and(eq(juniorTurns.id, turnId), eq(juniorTurns.state, "running")));
|
|
1030
|
-
return ended.length > 0;
|
|
1031
|
-
}
|
|
1032
|
-
/**
|
|
1033
|
-
* Claims a Turn to run its next step: the Conversation's next queued Turn, or
|
|
1034
|
-
* a running Turn whose lease expired, so the queue's redelivery after a crash
|
|
1035
|
-
* resumes it. Any other Turn gets undefined, so one of two racing claims wins,
|
|
1036
|
-
* and a Conversation runs one Turn at a time, in order. Each claim moves
|
|
1037
|
-
* `lease_epoch` and `attempts` and holds the Conversation lock.
|
|
1038
|
-
*/
|
|
1039
|
-
async function claimTurn({ executor, owner, leaseMs }, turnId) {
|
|
1040
|
-
const turn = await findTurn({ executor }, turnId);
|
|
1041
|
-
if (!turn) return;
|
|
1042
|
-
const claim = () => executor.db().update(juniorTurns).set({
|
|
1043
|
-
state: "running",
|
|
1044
|
-
leaseOwner: owner,
|
|
1045
|
-
leaseExpiresAt: leaseExpiry(leaseMs),
|
|
1046
|
-
leaseEpoch: sql`${juniorTurns.leaseEpoch} + 1`,
|
|
1047
|
-
attempts: sql`${juniorTurns.attempts} + 1`,
|
|
1048
|
-
startedAt: sql`coalesce(${juniorTurns.startedAt}, now())`,
|
|
1049
|
-
updatedAt: sql`now()`
|
|
1050
|
-
}).where(and(eq(juniorTurns.id, turnId), or(and(eq(juniorTurns.state, "queued"), notExists(turnAhead({ executor }))), and(eq(juniorTurns.state, "running"), lte(juniorTurns.leaseExpiresAt, sql`now()`))))).returning({
|
|
1051
|
-
turnId: juniorTurns.id,
|
|
1052
|
-
leaseEpoch: juniorTurns.leaseEpoch,
|
|
1053
|
-
conversationId: juniorTurns.conversationId,
|
|
1054
|
-
stepSeq: juniorTurns.stepSeq,
|
|
1055
|
-
attempts: juniorTurns.attempts
|
|
1056
|
-
});
|
|
1057
|
-
const [claimed] = await executor.transaction(() => withConversationEventLock(executor, turn.conversationId, claim));
|
|
1058
|
-
return claimed;
|
|
1059
|
-
}
|
|
1060
|
-
/**
|
|
1061
|
-
* Checks without a write that the lease still holds: the Turn runs under the
|
|
1062
|
-
* caller's `lease_epoch`. False after a cancel or a takeover.
|
|
1063
|
-
*/
|
|
1064
|
-
async function holdsLease({ executor }, lease) {
|
|
1065
|
-
return (await executor.db().select({ id: juniorTurns.id }).from(juniorTurns).where(leaseFence(lease))).length > 0;
|
|
1066
|
-
}
|
|
1067
|
-
/**
|
|
1068
|
-
* Finds Turns that a claim could take now but that no message is likely to
|
|
1069
|
-
* reach: the next queued Turn of its Conversation, unchanged for `staleMs`,
|
|
1070
|
-
* and running Turns whose lease expired `staleMs` ago. The queue redelivers
|
|
1071
|
-
* a dead step's message soon after its lease expires, so only a Turn that
|
|
1072
|
-
* missed that redelivery is stalled.
|
|
1073
|
-
*/
|
|
1074
|
-
async function findStalledTurns({ executor }, { staleMs, limit }) {
|
|
1075
|
-
const staleBefore = sql`now() - make_interval(secs => ${staleMs / 1e3})`;
|
|
1076
|
-
const rows = await executor.db().select({
|
|
1077
|
-
turnId: juniorTurns.id,
|
|
1078
|
-
conversationId: juniorTurns.conversationId,
|
|
1079
|
-
state: juniorTurns.state,
|
|
1080
|
-
updatedAt: juniorTurns.updatedAt,
|
|
1081
|
-
leaseExpiresAt: juniorTurns.leaseExpiresAt
|
|
1082
|
-
}).from(juniorTurns).where(or(and(eq(juniorTurns.state, "queued"), lt(juniorTurns.updatedAt, staleBefore), notExists(turnAhead({ executor }))), and(eq(juniorTurns.state, "running"), lt(juniorTurns.leaseExpiresAt, staleBefore)))).limit(limit);
|
|
1083
|
-
const nowMs = Date.now();
|
|
1084
|
-
return rows.map((row) => {
|
|
1085
|
-
const since = row.state === "running" && row.leaseExpiresAt ? row.leaseExpiresAt : row.updatedAt;
|
|
1086
|
-
return {
|
|
1087
|
-
turnId: row.turnId,
|
|
1088
|
-
conversationId: row.conversationId,
|
|
1089
|
-
reason: row.state === "running" ? "lease_expired" : "queued_lost",
|
|
1090
|
-
stalledMs: Math.max(0, nowMs - since.getTime())
|
|
1091
|
-
};
|
|
1092
|
-
});
|
|
1093
|
-
}
|
|
1094
|
-
/**
|
|
1095
|
-
* The idempotency key of one message event of a step. It names the Turn and
|
|
1096
|
-
* the step that wrote it, so Delivery finds a Turn's replies without reading
|
|
1097
|
-
* the rest of the history.
|
|
1098
|
-
*/
|
|
1099
|
-
function stepEventKey(turnId, stepSeq, index) {
|
|
1100
|
-
return `${turnEventKeyPrefix(turnId)}${stepSeq}:${index}`;
|
|
1101
|
-
}
|
|
1102
|
-
/**
|
|
1103
|
-
* The idempotency key of one new message that a step's prompt added from a
|
|
1104
|
-
* message fragment. It is not a step event key, so Delivery does not read it.
|
|
1105
|
-
*/
|
|
1106
|
-
function promptEventKey(turnId, stepSeq, index) {
|
|
1107
|
-
return `prompt:${turnId}:${stepSeq}:${index}`;
|
|
1108
|
-
}
|
|
1109
|
-
/**
|
|
1110
|
-
* Commits a step in one transaction: appends the prompt's new messages, with
|
|
1111
|
-
* the inputs the step read, then the step's messages to history, adds an
|
|
1112
|
-
* outbox row per new reply, and releases the lease. A Turn that continues
|
|
1113
|
-
* queues for a new claim. A `stale` final reply is not committed. Undefined,
|
|
1114
|
-
* with no write, when the lease is lost or the step is already committed.
|
|
1115
|
-
*/
|
|
1116
|
-
async function commitStep({ executor }, turn, step, prompt) {
|
|
1117
|
-
const nextStep = {
|
|
1118
|
-
stepSeq: sql`${juniorTurns.stepSeq} + 1`,
|
|
1119
|
-
attempts: 0,
|
|
1120
|
-
leaseOwner: null,
|
|
1121
|
-
leaseExpiresAt: null,
|
|
1122
|
-
updatedAt: sql`now()`
|
|
1123
|
-
};
|
|
1124
|
-
return executor.transaction(() => withConversationEventLock(executor, turn.conversationId, async () => {
|
|
1125
|
-
const outcome = await commitOutcome({ executor }, turn.turnId, step, prompt);
|
|
1126
|
-
if (outcome === "stale") return await requeueStep({ executor }, turn, step) ? outcome : void 0;
|
|
1127
|
-
if ((await executor.db().update(juniorTurns).set(outcome === "completed" ? {
|
|
1128
|
-
...nextStep,
|
|
1129
|
-
state: "completed",
|
|
1130
|
-
endedAt: sql`now()`
|
|
1131
|
-
} : outcome === "superseded" ? {
|
|
1132
|
-
...nextStep,
|
|
1133
|
-
...SUPERSEDED_END
|
|
1134
|
-
} : {
|
|
1135
|
-
...nextStep,
|
|
1136
|
-
state: "queued"
|
|
1137
|
-
}).where(and(leaseFence(turn), eq(juniorTurns.conversationId, turn.conversationId), eq(juniorTurns.stepSeq, turn.stepSeq))).returning({ id: juniorTurns.id })).length === 0) return;
|
|
1138
|
-
await appendAgentHistory(executor, turn.conversationId, turn.turnId, [...prompt.map((entry, index) => entry.source === "input" ? {
|
|
1139
|
-
item: historyItemFromPiMessage(entry.message, entry.provenance),
|
|
1140
|
-
idempotencyKey: inputEventKey(entry.inputId),
|
|
1141
|
-
createdAtMs: entry.message.timestamp
|
|
1142
|
-
} : {
|
|
1143
|
-
item: historyItemFromPiMessage(entry.message, contextProvenance),
|
|
1144
|
-
idempotencyKey: promptEventKey(turn.turnId, turn.stepSeq, index),
|
|
1145
|
-
createdAtMs: entry.message.timestamp
|
|
1146
|
-
}), ...step.messages.map((message, index) => ({
|
|
1147
|
-
item: historyItemFromPiMessage(message, contextProvenance),
|
|
1148
|
-
idempotencyKey: stepEventKey(turn.turnId, turn.stepSeq, index),
|
|
1149
|
-
createdAtMs: message.timestamp
|
|
1150
|
-
}))]);
|
|
1151
|
-
await recordReplies({ executor }, turn);
|
|
1152
|
-
return outcome;
|
|
1153
|
-
}));
|
|
1154
|
-
}
|
|
1155
|
-
/**
|
|
1156
|
-
* A completed step ends the Turn only when the commit reads every unread
|
|
1157
|
-
* input. The scheduler can add an input after the step read them, and the
|
|
1158
|
-
* Conversation lock keeps more out until the commit ends. A final reply that
|
|
1159
|
-
* missed an input is `stale`, so the Turn ends with one reply to every input.
|
|
1160
|
-
*/
|
|
1161
|
-
async function commitOutcome({ executor }, turnId, step, prompt) {
|
|
1162
|
-
if (step.outcome === "completed") {
|
|
1163
|
-
const read = new Set(prompt.flatMap((entry) => entry.source === "input" ? [entry.inputId] : []));
|
|
1164
|
-
if ((await findUnreadInputs({ executor }, turnId)).every((input) => read.has(input.inputId))) return "completed";
|
|
1165
|
-
}
|
|
1166
|
-
if (await isSuperseded({ executor }, turnId)) return "superseded";
|
|
1167
|
-
return step.outcome === "completed" && finalReplyOf(step) ? "stale" : "continue";
|
|
1168
|
-
}
|
|
1169
|
-
function finalReplyOf(step) {
|
|
1170
|
-
const [message] = step.messages;
|
|
1171
|
-
return message?.role === "assistant" ? message : void 0;
|
|
1172
|
-
}
|
|
1173
|
-
/**
|
|
1174
|
-
* Queues the Turn for the same step again, with nothing committed, after a
|
|
1175
|
-
* stale final reply. The attempt does not count: the step did not fail. The
|
|
1176
|
-
* dropped reply's usage adds to the Turn's discarded usage.
|
|
1177
|
-
*/
|
|
1178
|
-
async function requeueStep({ executor }, turn, step) {
|
|
1179
|
-
return (await executor.db().update(juniorTurns).set({
|
|
1180
|
-
...await discardedUsageUpdate({ executor }, turn, extractGenAiUsageSummary(finalReplyOf(step))),
|
|
1181
|
-
state: "queued",
|
|
1182
|
-
attempts: 0,
|
|
1183
|
-
leaseOwner: null,
|
|
1184
|
-
leaseExpiresAt: null,
|
|
1185
|
-
updatedAt: sql`now()`
|
|
1186
|
-
}).where(and(leaseFence(turn), eq(juniorTurns.conversationId, turn.conversationId), eq(juniorTurns.stepSeq, turn.stepSeq))).returning({ id: juniorTurns.id })).length > 0;
|
|
1187
|
-
}
|
|
1188
|
-
/**
|
|
1189
|
-
* Ends a running Turn as failed, with the reason and the failure details.
|
|
1190
|
-
* `discarded` is the usage of the model reply that the step drops. False when
|
|
1191
|
-
* the lease is lost. The engine calls it through `endFailedTurn`, which also
|
|
1192
|
-
* moves the Turn's late inputs.
|
|
1193
|
-
*/
|
|
1194
|
-
async function failTurn({ executor }, lease, endReason, failure, discarded) {
|
|
1195
|
-
return (await executor.db().update(juniorTurns).set({
|
|
1196
|
-
...await discardedUsageUpdate({ executor }, lease, discarded),
|
|
1197
|
-
state: "failed",
|
|
1198
|
-
endReason,
|
|
1199
|
-
failureCode: failure.failureCode,
|
|
1200
|
-
failureReason: failure.failureReason ?? null,
|
|
1201
|
-
failureEventId: failure.eventId ?? null,
|
|
1202
|
-
leaseOwner: null,
|
|
1203
|
-
leaseExpiresAt: null,
|
|
1204
|
-
updatedAt: sql`now()`,
|
|
1205
|
-
endedAt: sql`now()`
|
|
1206
|
-
}).where(leaseFence(lease)).returning({ id: juniorTurns.id })).length > 0;
|
|
1207
|
-
}
|
|
1208
|
-
/**
|
|
1209
|
-
* Queues a running Turn again after its invocation failed, so the queue's
|
|
1210
|
-
* retry can claim the step at once. The failed attempt still counts. A Turn
|
|
1211
|
-
* that another Turn supersedes ends instead, like at a commit. `discarded` is
|
|
1212
|
-
* the usage of the failed model reply that the retry drops. Returns the
|
|
1213
|
-
* Turn's new state, or undefined when the lease is lost.
|
|
1214
|
-
*/
|
|
1215
|
-
async function releaseTurn({ executor }, lease, discarded) {
|
|
1216
|
-
return executor.transaction(() => withConversationEventLock(executor, lease.conversationId, async () => {
|
|
1217
|
-
const released = {
|
|
1218
|
-
...await discardedUsageUpdate({ executor }, lease, discarded),
|
|
1219
|
-
leaseOwner: null,
|
|
1220
|
-
leaseExpiresAt: null,
|
|
1221
|
-
updatedAt: sql`now()`
|
|
1222
|
-
};
|
|
1223
|
-
return (await executor.db().update(juniorTurns).set(await isSuperseded({ executor }, lease.turnId) ? {
|
|
1224
|
-
...released,
|
|
1225
|
-
...SUPERSEDED_END
|
|
1226
|
-
} : {
|
|
1227
|
-
...released,
|
|
1228
|
-
state: "queued"
|
|
1229
|
-
}).where(leaseFence(lease)).returning({ state: juniorTurns.state }))[0]?.state;
|
|
1230
|
-
}));
|
|
1231
|
-
}
|
|
1232
|
-
// src/core/turn/schedule.ts
|
|
1233
|
-
async function addInput({ executor }, input) {
|
|
1234
|
-
await executor.db().insert(juniorTurnInbox).values({
|
|
1235
|
-
...input,
|
|
1236
|
-
id: randomUUID()
|
|
1237
|
-
});
|
|
1238
|
-
}
|
|
1239
|
-
/**
|
|
1240
|
-
* The rule for which Turn takes an input that is not a duplicate. Core owns
|
|
1241
|
-
* it, so every Source schedules the same way, and the host decides who may
|
|
1242
|
-
* share a Turn through the group key. An input joins a Turn only when its
|
|
1243
|
-
* group key matches. An interrupt joins the Turn that has started, and an
|
|
1244
|
-
* interrupt with another group key supersedes that Turn. Any input
|
|
1245
|
-
* joins the last Turn in line while no step of it has started. Otherwise the
|
|
1246
|
-
* input waits in a new Turn at the end of the line, so A1 B1 A2 makes A2 wait
|
|
1247
|
-
* for B1. It runs under the Conversation lock, so `openTurns` cannot change
|
|
1248
|
-
* before the write.
|
|
1249
|
-
*/
|
|
1250
|
-
function assignTurn(input, openTurns) {
|
|
1251
|
-
const sameGroup = (turn) => turn.groupKey === input.groupKey;
|
|
1252
|
-
const started = openTurns.find((turn) => turn.started);
|
|
1253
|
-
if (input.delivery === "interrupt" && started) return sameGroup(started) ? { join: started } : {
|
|
1254
|
-
create: { priority: TURN_PRIORITY.supersede },
|
|
1255
|
-
supersede: started
|
|
1256
|
-
};
|
|
1257
|
-
const last = openTurns.at(-1);
|
|
1258
|
-
if (last && !last.started && sameGroup(last)) return { join: last };
|
|
1259
|
-
return { create: { priority: TURN_PRIORITY.normal } };
|
|
1260
|
-
}
|
|
1261
|
-
async function placeInput({ executor }, { delivery, ...input }) {
|
|
1262
|
-
const existing = await findInputTurn({ executor }, input);
|
|
1263
|
-
if (existing) return {
|
|
1264
|
-
turnId: existing.turnId,
|
|
1265
|
-
created: false,
|
|
1266
|
-
publish: existing.state === "queued"
|
|
1267
|
-
};
|
|
1268
|
-
const openTurns = await findOpenTurns({ executor }, input.conversationId);
|
|
1269
|
-
const choice = assignTurn({
|
|
1270
|
-
...input,
|
|
1271
|
-
delivery
|
|
1272
|
-
}, openTurns);
|
|
1273
|
-
if ("join" in choice) {
|
|
1274
|
-
const { turnId } = choice.join;
|
|
1275
|
-
await addInput({ executor }, {
|
|
1276
|
-
...input,
|
|
1277
|
-
turnId
|
|
1278
|
-
});
|
|
1279
|
-
return {
|
|
1280
|
-
turnId,
|
|
1281
|
-
created: false,
|
|
1282
|
-
publish: false
|
|
1283
|
-
};
|
|
1284
|
-
}
|
|
1285
|
-
const ended = choice.supersede && await supersedeTurn({ executor }, choice.supersede.turnId) ? choice.supersede.turnId : void 0;
|
|
1286
|
-
const turn = await createTurn({ executor }, {
|
|
1287
|
-
conversationId: input.conversationId,
|
|
1288
|
-
priority: choice.create.priority
|
|
1289
|
-
});
|
|
1290
|
-
await addInput({ executor }, {
|
|
1291
|
-
...input,
|
|
1292
|
-
turnId: turn.turnId
|
|
1293
|
-
});
|
|
1294
|
-
return {
|
|
1295
|
-
turnId: turn.turnId,
|
|
1296
|
-
created: true,
|
|
1297
|
-
publish: openTurns.length === 0 || choice.supersede !== void 0,
|
|
1298
|
-
ended
|
|
1299
|
-
};
|
|
1300
|
-
}
|
|
1301
|
-
/**
|
|
1302
|
-
* Puts an input into the Turn that `assignTurn` picks, then publishes what
|
|
1303
|
-
* the placement calls for, such as the end of a Turn it superseded. A known
|
|
1304
|
-
* idempotency key writes nothing. Call it outside a transaction: it publishes
|
|
1305
|
-
* after its own commit, so a publish error leaves the input stored.
|
|
1306
|
-
*/
|
|
1307
|
-
async function scheduleInput({ executor, queue }, input) {
|
|
1308
|
-
const placement = await withConversationEventLock(executor, input.conversationId, () => placeInput({ executor }, input));
|
|
1309
|
-
if (placement.ended) await publishTurnEnded({ queue }, {
|
|
1310
|
-
conversationId: input.conversationId,
|
|
1311
|
-
turnId: placement.ended
|
|
1312
|
-
});
|
|
1313
|
-
if (placement.publish) await publishTurnStep({ queue }, placement.turnId);
|
|
1314
|
-
return {
|
|
1315
|
-
turnId: placement.turnId,
|
|
1316
|
-
created: placement.created
|
|
1317
|
-
};
|
|
1318
|
-
}
|
|
1319
|
-
async function moveInputs({ executor }, inputIds, turnId) {
|
|
1320
|
-
await executor.db().update(juniorTurnInbox).set({ turnId }).where(inArray(juniorTurnInbox.id, inputIds));
|
|
1321
|
-
}
|
|
1322
|
-
/**
|
|
1323
|
-
* Moves the unread inputs of a failed Turn that arrived after its last claim
|
|
1324
|
-
* to the Turn that `assignTurn` picks for a deferred input. They share the
|
|
1325
|
-
* failed Turn's group key, so they move together. The failed Turn
|
|
1326
|
-
* keeps, and so drops, the inputs that an attempt claimed it with.
|
|
1327
|
-
*/
|
|
1328
|
-
async function moveLeftovers({ executor }, ended) {
|
|
1329
|
-
const leftovers = (await findUnreadInputs({ executor }, ended.turnId)).filter((input) => input.attemptedAt === null);
|
|
1330
|
-
const [first] = leftovers;
|
|
1331
|
-
if (!first) return;
|
|
1332
|
-
const choice = assignTurn({
|
|
1333
|
-
...first,
|
|
1334
|
-
delivery: "defer"
|
|
1335
|
-
}, await findOpenTurns({ executor }, ended.conversationId));
|
|
1336
|
-
const target = "join" in choice ? choice.join : await createTurn({ executor }, {
|
|
1337
|
-
conversationId: ended.conversationId,
|
|
1338
|
-
priority: choice.create.priority
|
|
1339
|
-
});
|
|
1340
|
-
await moveInputs({ executor }, leftovers.map((input) => input.inputId), target.turnId);
|
|
1341
|
-
}
|
|
1342
|
-
/**
|
|
1343
|
-
* Ends a running Turn as failed and, in the same commit, moves its inputs
|
|
1344
|
-
* that arrived after its last claim to the next Turn. A crash after the
|
|
1345
|
-
* commit loses no input: the next Turn is queued, so the sweep finds it.
|
|
1346
|
-
* `discarded` is the usage of a failed model reply that the Turn drops.
|
|
1347
|
-
* False when the lease is lost, and then nothing changes.
|
|
1348
|
-
*/
|
|
1349
|
-
async function endFailedTurn({ executor }, lease, endReason, failure, discarded) {
|
|
1350
|
-
return executor.transaction(() => withConversationEventLock(executor, lease.conversationId, async () => {
|
|
1351
|
-
if (!await failTurn({ executor }, lease, endReason, failure, discarded)) return false;
|
|
1352
|
-
await moveLeftovers({ executor }, lease);
|
|
1353
|
-
return true;
|
|
1354
|
-
}));
|
|
1355
|
-
}
|
|
1356
|
-
/**
|
|
1357
|
-
* Brings the queue in line with this Turn's stored state, so it is safe to
|
|
1358
|
-
* repeat: it says the Turn ended if it has, then publishes the Conversation's
|
|
1359
|
-
* open Turn if it is queued. Call it after the commit that it follows,
|
|
1360
|
-
* outside a transaction, so a worker that takes a message sees that commit.
|
|
1361
|
-
*/
|
|
1362
|
-
async function reconcileTurn({ executor, queue }, turnId) {
|
|
1363
|
-
const turn = await findTurn({ executor }, turnId);
|
|
1364
|
-
if (!turn) return;
|
|
1365
|
-
if (turn.state !== "queued" && turn.state !== "running") await publishTurnEnded({ queue }, {
|
|
1366
|
-
conversationId: turn.conversationId,
|
|
1367
|
-
turnId
|
|
1368
|
-
});
|
|
1369
|
-
const openTurn = await findOpenTurn({ executor }, turn.conversationId);
|
|
1370
|
-
if (openTurn?.state === "queued") await publishTurnStep({ queue }, openTurn.turnId);
|
|
1371
|
-
}
|
|
1372
554
|
// src/core/turn/step.ts
|
|
1373
555
|
/**
|
|
1374
556
|
* Runs one step of a Turn: the pending tool calls if there are any, else one
|
|
@@ -1784,12 +966,6 @@ async function whileLeased({ executor }, lease, run) {
|
|
|
1784
966
|
clearInterval(timer);
|
|
1785
967
|
}
|
|
1786
968
|
}
|
|
1787
|
-
// src/turn-steps/input-payload.ts
|
|
1788
|
-
/** Parses the payload of an inbox row that the host wrote. */
|
|
1789
|
-
const turnInputPayloadSchema = z.object({
|
|
1790
|
-
text: z.string().min(1),
|
|
1791
|
-
actor: actorSchema
|
|
1792
|
-
}).strict();
|
|
1793
969
|
// src/turn-steps/compat__message-id.ts
|
|
1794
970
|
/** The visible message id of a core Turn's input, for main's readers. */
|
|
1795
971
|
function compat__personMessageId(inputId) {
|
|
@@ -2420,14 +1596,4 @@ function turnEndedConsumer(engineCtx, delivery) {
|
|
|
2420
1596
|
await compat__writeTurnEnded(engineCtx, message);
|
|
2421
1597
|
});
|
|
2422
1598
|
}
|
|
2423
|
-
|
|
2424
|
-
/** Builds the context that core's Turn engine runs with. */
|
|
2425
|
-
function createEngineContext(config) {
|
|
2426
|
-
return {
|
|
2427
|
-
executor: getSqlExecutor(),
|
|
2428
|
-
queue: getQueueProvider(),
|
|
2429
|
-
owner: SERVICE_INSTANCE_ID,
|
|
2430
|
-
leaseMs: config.functionMaxDurationSeconds * 1e3
|
|
2431
|
-
};
|
|
2432
|
-
}
|
|
2433
|
-
export { createGatewayModelClient as a, findStalledTurns as c, countMetric as d, withSpan as f, turnTools as i, publishTurnEnded as l, createDeploymentDelivery as n, turnStepConsumer as o, turnEndedConsumer as r, scheduleInput as s, createEngineContext as t, publishTurnStep as u };
|
|
1599
|
+
export { turnStepConsumer as a, createGatewayModelClient as i, turnEndedConsumer as n, turnTools as r, createDeploymentDelivery as t };
|