stitchkit 0.63.0 → 0.65.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/agent-runtime/coordinator.d.ts +6 -7
- package/dist/agent-runtime/coordinator.d.ts.map +1 -1
- package/dist/agent-runtime/events.d.ts +12 -18
- package/dist/agent-runtime/events.d.ts.map +1 -1
- package/dist/agent-runtime/history.d.ts +13 -0
- package/dist/agent-runtime/history.d.ts.map +1 -1
- package/dist/agent-runtime/observability.d.ts +327 -14
- package/dist/agent-runtime/observability.d.ts.map +1 -1
- package/dist/agent-runtime/prompt.d.ts +3 -1
- package/dist/agent-runtime/prompt.d.ts.map +1 -1
- package/dist/agent-runtime/run-execution.d.ts +0 -4
- package/dist/agent-runtime/run-execution.d.ts.map +1 -1
- package/dist/agent-runtime/runtime.d.ts +11 -1
- package/dist/agent-runtime/runtime.d.ts.map +1 -1
- package/dist/agent-runtime/schemas.d.ts +24 -10
- package/dist/agent-runtime/schemas.d.ts.map +1 -1
- package/dist/agent-runtime/store-driver.d.ts +15 -10
- package/dist/agent-runtime/store-driver.d.ts.map +1 -1
- package/dist/agent-runtime/store.d.ts +8 -43
- package/dist/agent-runtime/store.d.ts.map +1 -1
- package/dist/agent-runtime/terminal-commit.d.ts +2 -3
- package/dist/agent-runtime/terminal-commit.d.ts.map +1 -1
- package/dist/agent-runtime.d.ts +2 -2
- package/dist/agent-runtime.d.ts.map +1 -1
- package/dist/agent-runtime.js +109 -181
- package/dist/{index-b1k33127.js → index-sbkyvacf.js} +54 -6
- package/dist/testing/agent-store-conformance.d.ts.map +1 -1
- package/dist/testing.js +64 -3
- package/llms-full.txt +207 -47
- package/package.json +1 -1
package/dist/agent-runtime.d.ts
CHANGED
|
@@ -4,13 +4,13 @@ export { AgentAdmissionEventSchema, AgentCheckpointEventSchema, AgentReasoningDe
|
|
|
4
4
|
export { type AgentHistoryProjectionDecision, type AgentHistoryProjectionOptions, type AgentHistoryProjectionResult, projectAgentHistory, projectAgentHistoryDetailed, } from './agent-runtime/history';
|
|
5
5
|
export { type AgentToolFenceConfig, type AgentToolFenceContext, createAgentToolFenceLifecycle, } from './agent-runtime/managed-tools';
|
|
6
6
|
export { type AgentLanguageModelProvider, type AgentModelCapability, AgentModelCapabilitySchema, type AgentModelDescriptor, AgentModelDescriptorSchema, type AgentModelRegistry, type AgentModelRegistryConfig, type AgentModelRegistrySnapshot, AgentModelRegistrySnapshotSchema, type AgentModelSnapshotPolicy, type AgentResolvedModel, defineModelRegistry, validateAgentModelSnapshot, } from './agent-runtime/models';
|
|
7
|
-
export { type AgentObservability, type AgentRunEvent, AgentRunEventSchema, type AgentRunSinkConfig, type AgentRunSinkDrop, type AgentRunSinkError, createAgentObservability, } from './agent-runtime/observability';
|
|
7
|
+
export { type AgentObservability, type AgentRunEvent, AgentRunEventSchema, type AgentRunSinkConfig, type AgentRunSinkDrop, type AgentRunSinkError, type AgentRunStartedEvent, AgentRunStartedEventSchema, type AgentRunTerminalEvent, AgentRunTerminalEventSchema, type AgentStepFinishedEvent, AgentStepFinishedEventSchema, createAgentObservability, } from './agent-runtime/observability';
|
|
8
8
|
export { type AgentHistoryBudgetDecision, type AgentHistoryBudgetResult, type AgentPromptBudget, type AgentPromptSection, type AgentPromptSectionContext, type AgentTokenCount, AgentTokenCountSchema, type ComposeAgentPromptOptions, type ComposedAgentPrompt, composeAgentPrompt, type SelectAgentHistoryOptions, selectAgentHistory, } from './agent-runtime/prompt';
|
|
9
9
|
export { type AgentProtocol, type AgentProtocolConfig, defineAgentProtocol, } from './agent-runtime/protocol';
|
|
10
10
|
export { type AgentRuntime, type AgentRuntimeAdmission, type AgentRuntimeConfig, type AgentRuntimeInput, type AgentRuntimeInterruptInput, type AgentRuntimePrepareStep, type AgentRuntimeProtocolInput, type AgentRuntimeRecordIds, type AgentRuntimeRecoverOptions, type AgentRuntimeRecoveryDecision, type AgentRuntimeRecoveryInput, type AgentRuntimeRecoveryOutcome, type AgentRuntimeRunContext, type AgentRuntimeStopPolicy, createAgentRuntime, } from './agent-runtime/runtime';
|
|
11
11
|
export type { AgentRuntimeResult } from './agent-runtime/runtime-result';
|
|
12
12
|
export * from './agent-runtime/schemas';
|
|
13
|
-
export { type
|
|
13
|
+
export { type AcceptInputAndAssignRun, AcceptInputAndAssignRunSchema, type AcquireAgentRun, AcquireAgentRunSchema, type AgentRuntimeStore, AgentStoreAppliedSchema, AgentStoreConflictSchema, AgentStoreDuplicateSchema, type AgentStoreMutationResult, AgentStoreMutationResultSchema, AgentStoreNotFoundSchema, type CheckpointRunAssistant, CheckpointRunAssistantSchema, type CommitRunTerminal, CommitRunTerminalSchema, type RecoverAgentRun, RecoverAgentRunSchema, type ReplaceCompactedRange, ReplaceCompactedRangeSchema, type RequestRunInterrupt, RequestRunInterruptSchema, } from './agent-runtime/store';
|
|
14
14
|
export { type AgentAdmissionReceipt, AgentAdmissionReceiptSchema, type AgentHistoryMutation, AgentHistoryMutationSchema, type AgentRecoverableDescriptor, AgentRecoverableDescriptorSchema, type AgentRecoverablePage, AgentRecoverablePageSchema, type AgentRuntimeHead, AgentRuntimeHeadSchema, type AgentRuntimeStoreDriver, type AgentStoreCompareAndSwapResult, type AgentStoredRun, AgentStoredRunSchema, createAgentRuntimeStore, createMemoryAgentRuntimeStore, } from './agent-runtime/store-driver';
|
|
15
15
|
export { AgentRuntimeConflictError } from './agent-runtime/terminal-commit';
|
|
16
16
|
//# sourceMappingURL=agent-runtime.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-runtime.d.ts","sourceRoot":"","sources":["../src/agent-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,sBAAsB,EAC3B,KAAK,qBAAqB,EAC1B,KAAK,0BAA0B,EAC/B,oBAAoB,GACrB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,KAAK,mBAAmB,EACxB,KAAK,gBAAgB,EACrB,KAAK,cAAc,EACnB,KAAK,wBAAwB,EAC7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A8B,EACnC,KAAK,cAAc,EACnB,oBAAoB,EACpB,uBAAuB,EACvB,6BAA6B,GAC9B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,yBAAyB,EAAE,MAAM,iCAAiC,CAAC"}
|
package/dist/agent-runtime.js
CHANGED
|
@@ -28,8 +28,9 @@ import {
|
|
|
28
28
|
AgentToolCallPartSchema,
|
|
29
29
|
AgentToolResultPartSchema,
|
|
30
30
|
AgentUsageSchema,
|
|
31
|
-
AgentUsageValueSchema
|
|
32
|
-
|
|
31
|
+
AgentUsageValueSchema,
|
|
32
|
+
runStateForTerminalReason
|
|
33
|
+
} from "./index-sbkyvacf.js";
|
|
33
34
|
import"./index-6djpbnda.js";
|
|
34
35
|
import"./index-cby4ar3v.js";
|
|
35
36
|
import {
|
|
@@ -395,7 +396,7 @@ function advanceAgentRuntimeEventCursor(rawCursor, event) {
|
|
|
395
396
|
return { status: "duplicate", cursor };
|
|
396
397
|
}
|
|
397
398
|
return {
|
|
398
|
-
status:
|
|
399
|
+
status: "accepted",
|
|
399
400
|
cursor: {
|
|
400
401
|
...cursor,
|
|
401
402
|
snapshotVersion: event.snapshotVersion,
|
|
@@ -561,13 +562,7 @@ function interruptedSystemNote(message) {
|
|
|
561
562
|
return { rendered };
|
|
562
563
|
rendered.add("text");
|
|
563
564
|
rendered.add("control");
|
|
564
|
-
return {
|
|
565
|
-
message: modelMessageSchema.parse({
|
|
566
|
-
role: "system",
|
|
567
|
-
content: `[interrupted] partial response: ${text}`
|
|
568
|
-
}),
|
|
569
|
-
rendered
|
|
570
|
-
};
|
|
565
|
+
return { text: `[interrupted] partial response: ${text}`, rendered };
|
|
571
566
|
}
|
|
572
567
|
function completeToolChronology(message) {
|
|
573
568
|
const calls = new Set(message.parts.filter((part) => part.type === "tool-call").map((part) => part.callId));
|
|
@@ -576,12 +571,13 @@ function completeToolChronology(message) {
|
|
|
576
571
|
}
|
|
577
572
|
async function projectAgentHistoryDetailed(messages, options = {}) {
|
|
578
573
|
const projected = [];
|
|
574
|
+
const system = [];
|
|
579
575
|
const decisions = [];
|
|
580
576
|
const interruptedRule = options.interruptedAssistant ?? "assistant-marked";
|
|
581
577
|
let observedUser = false;
|
|
582
578
|
for (const message of messages) {
|
|
583
|
-
if (message.
|
|
584
|
-
decisions.push(decide(message, "omitted", "superseded"));
|
|
579
|
+
if (message.role === "assistant" && !isSpeakableAssistantStatus(message.status)) {
|
|
580
|
+
decisions.push(decide(message, "omitted", message.status === "superseded" ? "superseded" : "draft-or-failed"));
|
|
585
581
|
continue;
|
|
586
582
|
}
|
|
587
583
|
if (message.status === "streaming" || message.status === "failed") {
|
|
@@ -602,7 +598,7 @@ async function projectAgentHistoryDetailed(messages, options = {}) {
|
|
|
602
598
|
if (message.role === "system" || message.role === "summary") {
|
|
603
599
|
const content = textContent(message.parts);
|
|
604
600
|
if (content) {
|
|
605
|
-
|
|
601
|
+
system.push(content);
|
|
606
602
|
decisions.push(decide(message, "projected", "projected", new Set(["text"])));
|
|
607
603
|
} else {
|
|
608
604
|
decisions.push(decide(message, "omitted", "empty"));
|
|
@@ -623,8 +619,8 @@ async function projectAgentHistoryDetailed(messages, options = {}) {
|
|
|
623
619
|
}
|
|
624
620
|
if (interrupted && interruptedRule === "system-note") {
|
|
625
621
|
const note = interruptedSystemNote(message);
|
|
626
|
-
if (note.
|
|
627
|
-
|
|
622
|
+
if (note.text) {
|
|
623
|
+
system.push(note.text);
|
|
628
624
|
decisions.push(decide(message, "projected", "projected", note.rendered));
|
|
629
625
|
} else {
|
|
630
626
|
decisions.push(decide(message, "omitted", "empty"));
|
|
@@ -642,7 +638,7 @@ async function projectAgentHistoryDetailed(messages, options = {}) {
|
|
|
642
638
|
projected.push(...assistant.messages);
|
|
643
639
|
decisions.push(assistant.messages.length > 0 ? decide(message, "projected", "projected", assistant.rendered) : decide(message, "omitted", "empty"));
|
|
644
640
|
}
|
|
645
|
-
return { messages: projected, decisions };
|
|
641
|
+
return { messages: projected, decisions, system };
|
|
646
642
|
}
|
|
647
643
|
async function projectAgentHistory(messages, options = {}) {
|
|
648
644
|
return [...(await projectAgentHistoryDetailed(messages, options)).messages];
|
|
@@ -758,26 +754,41 @@ function validateAgentModelSnapshot(input, policy) {
|
|
|
758
754
|
}
|
|
759
755
|
// src/agent-runtime/observability.ts
|
|
760
756
|
import { z as z3 } from "zod";
|
|
761
|
-
var
|
|
757
|
+
var AgentRunEventBaseSchema = z3.object({
|
|
762
758
|
schemaVersion: z3.literal(1),
|
|
763
759
|
eventId: AgentRecordIdSchema,
|
|
764
|
-
type: z3.enum(["run-started", "step-finished", "run-terminal"]),
|
|
765
760
|
conversationId: AgentRecordIdSchema,
|
|
766
761
|
runId: AgentRecordIdSchema,
|
|
767
762
|
traceId: z3.string().min(1),
|
|
768
763
|
spanId: z3.string().min(1),
|
|
769
764
|
parentSpanId: z3.string().min(1).optional(),
|
|
770
765
|
state: AgentRunStateSchema,
|
|
771
|
-
terminalReason: AgentTerminalReasonSchema.optional(),
|
|
772
766
|
modelId: z3.string().min(1).optional(),
|
|
773
|
-
step: z3.int().nonnegative().optional(),
|
|
774
|
-
queueWaitMs: z3.number().nonnegative().optional(),
|
|
775
767
|
durationMs: z3.number().nonnegative().optional(),
|
|
768
|
+
emittedAt: AgentTimestampSchema
|
|
769
|
+
});
|
|
770
|
+
var AgentRunStartedEventSchema = AgentRunEventBaseSchema.extend({
|
|
771
|
+
type: z3.literal("run-started"),
|
|
772
|
+
queueWaitMs: z3.number().nonnegative().optional()
|
|
773
|
+
});
|
|
774
|
+
var AgentStepFinishedEventSchema = AgentRunEventBaseSchema.extend({
|
|
775
|
+
type: z3.literal("step-finished"),
|
|
776
|
+
step: z3.int().nonnegative(),
|
|
777
|
+
ttftMs: z3.number().nonnegative().optional(),
|
|
778
|
+
usage: AgentUsageSchema
|
|
779
|
+
});
|
|
780
|
+
var AgentRunTerminalEventSchema = AgentRunEventBaseSchema.extend({
|
|
781
|
+
type: z3.literal("run-terminal"),
|
|
782
|
+
terminalReason: AgentTerminalReasonSchema,
|
|
776
783
|
ttftMs: z3.number().nonnegative().optional(),
|
|
777
|
-
usage: AgentUsageSchema.optional(),
|
|
778
784
|
internalCause: z3.unknown().optional(),
|
|
779
|
-
|
|
785
|
+
usage: AgentUsageSchema
|
|
780
786
|
});
|
|
787
|
+
var AgentRunEventSchema = z3.discriminatedUnion("type", [
|
|
788
|
+
AgentRunStartedEventSchema,
|
|
789
|
+
AgentStepFinishedEventSchema,
|
|
790
|
+
AgentRunTerminalEventSchema
|
|
791
|
+
]);
|
|
781
792
|
function createAgentObservability(config) {
|
|
782
793
|
const manager = createBoundedSinkManager({
|
|
783
794
|
write: config.write,
|
|
@@ -808,7 +819,13 @@ function createAgentObservability(config) {
|
|
|
808
819
|
if ((config.deduplicate ?? true) && emitted.has(parsed.eventId))
|
|
809
820
|
return;
|
|
810
821
|
remember(parsed.eventId);
|
|
811
|
-
manager.submit(() =>
|
|
822
|
+
manager.submit(() => {
|
|
823
|
+
if (config.includeInternalCause)
|
|
824
|
+
return parsed;
|
|
825
|
+
if (parsed.type !== "run-terminal")
|
|
826
|
+
return parsed;
|
|
827
|
+
return AgentRunTerminalEventSchema.omit({ internalCause: true }).parse(parsed);
|
|
828
|
+
});
|
|
812
829
|
},
|
|
813
830
|
flush: () => manager.flush(),
|
|
814
831
|
getStatus: () => manager.getStatus(),
|
|
@@ -861,7 +878,7 @@ async function selectAgentHistory(options) {
|
|
|
861
878
|
if (!Number.isSafeInteger(keepRecentTurns) || keepRecentTurns < 0) {
|
|
862
879
|
throw new TypeError("keepRecentTurns must be a non-negative safe integer");
|
|
863
880
|
}
|
|
864
|
-
const spoken = options.messages.filter((message) => message.
|
|
881
|
+
const spoken = options.messages.filter((message) => message.role !== "assistant" || isSpeakableAssistantStatus(message.status));
|
|
865
882
|
const counts = new Map;
|
|
866
883
|
let total = 0;
|
|
867
884
|
let estimated = false;
|
|
@@ -874,8 +891,8 @@ async function selectAgentHistory(options) {
|
|
|
874
891
|
messages: [...spoken],
|
|
875
892
|
decisions: options.messages.map((candidate) => ({
|
|
876
893
|
messageId: candidate.id,
|
|
877
|
-
action: candidate.
|
|
878
|
-
reason: candidate.
|
|
894
|
+
action: candidate.role === "assistant" && !isSpeakableAssistantStatus(candidate.status) ? "removed" : "kept",
|
|
895
|
+
reason: candidate.role === "assistant" && !isSpeakableAssistantStatus(candidate.status) ? "unspeakable" : "token-count-unavailable",
|
|
879
896
|
tokens: counts.get(candidate.id) ?? { provenance: "unavailable" }
|
|
880
897
|
})),
|
|
881
898
|
totalTokens: { provenance: "unavailable" },
|
|
@@ -901,11 +918,11 @@ async function selectAgentHistory(options) {
|
|
|
901
918
|
}
|
|
902
919
|
const messages = spoken.filter((message) => !removed.has(message.id));
|
|
903
920
|
const decisions = options.messages.map((message) => {
|
|
904
|
-
if (message.
|
|
921
|
+
if (message.role === "assistant" && !isSpeakableAssistantStatus(message.status)) {
|
|
905
922
|
return {
|
|
906
923
|
messageId: message.id,
|
|
907
924
|
action: "removed",
|
|
908
|
-
reason: "
|
|
925
|
+
reason: "unspeakable",
|
|
909
926
|
tokens: { provenance: "unavailable" }
|
|
910
927
|
};
|
|
911
928
|
}
|
|
@@ -1105,6 +1122,7 @@ function interruptedCandidate(candidate, run, now) {
|
|
|
1105
1122
|
AgentMessagePartSchema.parse({ type: "control", reason: "run-interrupted" })
|
|
1106
1123
|
];
|
|
1107
1124
|
return {
|
|
1125
|
+
...candidate.usage && { usage: candidate.usage },
|
|
1108
1126
|
run,
|
|
1109
1127
|
assistant: AgentMessageSchema.parse({
|
|
1110
1128
|
...candidate.assistant,
|
|
@@ -1373,6 +1391,7 @@ function createRunExecutor(dependencies) {
|
|
|
1373
1391
|
let terminalReason = "success";
|
|
1374
1392
|
let usage = input.acceptedRun.usage;
|
|
1375
1393
|
let sawProviderFinish = false;
|
|
1394
|
+
let contextRefusal = false;
|
|
1376
1395
|
let step = 0;
|
|
1377
1396
|
let selectedModel;
|
|
1378
1397
|
let internalCause;
|
|
@@ -1489,56 +1508,38 @@ function createRunExecutor(dependencies) {
|
|
|
1489
1508
|
config.tools(runtimeContext)
|
|
1490
1509
|
]);
|
|
1491
1510
|
if (prompt.contextDecision === "oversized") {
|
|
1511
|
+
contextRefusal = true;
|
|
1492
1512
|
throw new Error("Agent context exceeds the configured model budget");
|
|
1493
1513
|
}
|
|
1494
1514
|
if (prompt.contextDecision === "requires-compaction") {
|
|
1515
|
+
contextRefusal = true;
|
|
1495
1516
|
throw new Error("Agent context still exceeds the model budget after compaction");
|
|
1496
1517
|
}
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
return;
|
|
1510
|
-
const latest = await config.store.loadSnapshot(run.conversationId);
|
|
1511
|
-
const current = latest.runs.find((candidate) => candidate.id === run.id);
|
|
1512
|
-
if (current?.state !== "running" || current.ownerId !== runtimeEpoch) {
|
|
1513
|
-
return;
|
|
1514
|
-
}
|
|
1515
|
-
const pending = latest.runs.find((candidate) => candidate.state === "queued" && input.absorbable?.has(candidate.id));
|
|
1516
|
-
if (!pending)
|
|
1517
|
-
return;
|
|
1518
|
-
const absorbed = await config.store.absorbQueuedRun({
|
|
1519
|
-
conversationId: run.conversationId,
|
|
1520
|
-
runningRunId: current.id,
|
|
1521
|
-
runningExpectedRevision: current.revision,
|
|
1522
|
-
ownerId: runtimeEpoch,
|
|
1523
|
-
...current.fencingToken !== undefined && { fencingToken: current.fencingToken },
|
|
1524
|
-
queuedRunId: pending.id,
|
|
1525
|
-
queuedExpectedRevision: pending.revision
|
|
1526
|
-
});
|
|
1527
|
-
if (absorbed.outcome !== "applied")
|
|
1528
|
-
return;
|
|
1529
|
-
input.onAbsorbed?.(pending.id);
|
|
1530
|
-
snapshot = absorbed.snapshot;
|
|
1531
|
-
run = findRun(snapshot.runs, run.id);
|
|
1532
|
-
await publish({
|
|
1533
|
-
type: "run-state",
|
|
1534
|
-
eventId: agentDurableEventId("run-state", run.id, snapshot.version),
|
|
1535
|
-
conversationId: run.conversationId,
|
|
1536
|
-
runId: run.id,
|
|
1537
|
-
snapshotVersion: snapshot.version,
|
|
1538
|
-
state: run.state,
|
|
1539
|
-
emittedAt: now().toISOString()
|
|
1518
|
+
let carriedSystem = [];
|
|
1519
|
+
const projectHistory = async (source) => {
|
|
1520
|
+
if (config.history?.project)
|
|
1521
|
+
return config.history.project(source.messages);
|
|
1522
|
+
const detailed = await projectAgentHistoryDetailed(source.messages, {
|
|
1523
|
+
...config.history?.resolveFile && { resolveFile: config.history.resolveFile },
|
|
1524
|
+
...config.history?.unresolvedFile && {
|
|
1525
|
+
unresolvedFile: config.history.unresolvedFile
|
|
1526
|
+
},
|
|
1527
|
+
...config.history?.interruptedAssistant && {
|
|
1528
|
+
interruptedAssistant: config.history.interruptedAssistant
|
|
1529
|
+
}
|
|
1540
1530
|
});
|
|
1541
|
-
|
|
1531
|
+
carriedSystem = detailed.system;
|
|
1532
|
+
return [...detailed.messages];
|
|
1533
|
+
};
|
|
1534
|
+
const history = await projectHistory(snapshot);
|
|
1535
|
+
const withCarriedSystem = (instructions) => {
|
|
1536
|
+
if (carriedSystem.length === 0)
|
|
1537
|
+
return instructions;
|
|
1538
|
+
const composed = typeof instructions === "string" ? [{ role: "system", content: instructions }] : Array.isArray(instructions) ? instructions : [instructions];
|
|
1539
|
+
return [
|
|
1540
|
+
...composed,
|
|
1541
|
+
...carriedSystem.map((content) => ({ role: "system", content }))
|
|
1542
|
+
];
|
|
1542
1543
|
};
|
|
1543
1544
|
const maxStepCondition = stepCountIs(maxSteps);
|
|
1544
1545
|
const stopConditions = [
|
|
@@ -1560,15 +1561,13 @@ function createRunExecutor(dependencies) {
|
|
|
1560
1561
|
const result = streamText({
|
|
1561
1562
|
model: selectedModel.model,
|
|
1562
1563
|
tools,
|
|
1563
|
-
instructions: prompt.instructions,
|
|
1564
|
+
instructions: withCarriedSystem(prompt.instructions),
|
|
1564
1565
|
messages: history,
|
|
1565
1566
|
abortSignal: executionSignal,
|
|
1566
1567
|
maxRetries: 0,
|
|
1567
1568
|
stopWhen: stopConditions,
|
|
1568
|
-
prepareStep
|
|
1569
|
-
|
|
1570
|
-
const prepared = await config.loop?.prepareStep?.({ ...options, ...runtimeContext }) ?? {};
|
|
1571
|
-
return absorbed && !prepared.messages ? { ...prepared, messages: absorbed } : prepared;
|
|
1569
|
+
...config.loop?.prepareStep && {
|
|
1570
|
+
prepareStep: (options) => config.loop?.prepareStep?.({ ...options, ...runtimeContext })
|
|
1572
1571
|
}
|
|
1573
1572
|
});
|
|
1574
1573
|
for await (const part of result.stream) {
|
|
@@ -1833,7 +1832,7 @@ function createRunExecutor(dependencies) {
|
|
|
1833
1832
|
reason: isToolExecutionControlError(error) && error.reason === "stale_run" ? "stale-run" : "run-interrupted"
|
|
1834
1833
|
}));
|
|
1835
1834
|
} else {
|
|
1836
|
-
terminalReason = "provider_failure";
|
|
1835
|
+
terminalReason = contextRefusal ? "context_overflow" : "provider_failure";
|
|
1837
1836
|
}
|
|
1838
1837
|
} finally {
|
|
1839
1838
|
idleDeadline.dispose();
|
|
@@ -1942,7 +1941,8 @@ function createAgentRuntime(config) {
|
|
|
1942
1941
|
const waitForAdmissionAcceptances = admissionLanes.waitForAcceptances;
|
|
1943
1942
|
const checkpointEveryEvents = config.loop?.checkpointEveryEvents ?? 20;
|
|
1944
1943
|
const maxSteps = config.loop?.maxSteps ?? 50;
|
|
1945
|
-
const
|
|
1944
|
+
const declaredIdleTimeoutMs = config.loop?.idleTimeoutMs;
|
|
1945
|
+
const idleTimeoutMs = declaredIdleTimeoutMs === null ? undefined : declaredIdleTimeoutMs ?? 60000;
|
|
1946
1946
|
if (!Number.isSafeInteger(checkpointEveryEvents) || checkpointEveryEvents < 1) {
|
|
1947
1947
|
throw new TypeError("checkpointEveryEvents must be a positive safe integer");
|
|
1948
1948
|
}
|
|
@@ -1952,9 +1952,6 @@ function createAgentRuntime(config) {
|
|
|
1952
1952
|
if (idleTimeoutMs !== undefined && (!Number.isSafeInteger(idleTimeoutMs) || idleTimeoutMs < 1)) {
|
|
1953
1953
|
throw new TypeError("idleTimeoutMs must be a positive safe integer");
|
|
1954
1954
|
}
|
|
1955
|
-
const absorbable = new Set;
|
|
1956
|
-
const absorbedInto = new Map;
|
|
1957
|
-
const runResults = new Map;
|
|
1958
1955
|
const policyNames = new Set(["max-steps"]);
|
|
1959
1956
|
for (const policy of config.loop?.stopPolicies ?? []) {
|
|
1960
1957
|
if (!policy.name || policyNames.has(policy.name)) {
|
|
@@ -2087,8 +2084,7 @@ function createAgentRuntime(config) {
|
|
|
2087
2084
|
if (existingTicket)
|
|
2088
2085
|
return existingTicket;
|
|
2089
2086
|
const key = config.runs?.key?.(input) ?? input.conversationId;
|
|
2090
|
-
const
|
|
2091
|
-
const policy = declaredPolicy === "inject" ? "queue" : declaredPolicy;
|
|
2087
|
+
const policy = typeof config.runs?.inputPolicy === "function" ? config.runs.inputPolicy(input) : config.runs?.inputPolicy ?? "queue";
|
|
2092
2088
|
const nowIso = now().toISOString();
|
|
2093
2089
|
const inputMessageId = rawInput.recordIds?.inputMessageId ?? generateId();
|
|
2094
2090
|
const runId = rawInput.recordIds?.runId ?? generateId();
|
|
@@ -2214,8 +2210,6 @@ function createAgentRuntime(config) {
|
|
|
2214
2210
|
state: acceptedRun.state,
|
|
2215
2211
|
emittedAt: now().toISOString()
|
|
2216
2212
|
});
|
|
2217
|
-
if (declaredPolicy === "inject")
|
|
2218
|
-
absorbable.add(acceptedRun.id);
|
|
2219
2213
|
outerAccepted.resolve();
|
|
2220
2214
|
if (acceptance.outcome === "duplicate") {
|
|
2221
2215
|
if (!acceptedRun.terminalReason) {
|
|
@@ -2264,25 +2258,7 @@ function createAgentRuntime(config) {
|
|
|
2264
2258
|
await waitForAdmissionAcceptances(reservation.lane);
|
|
2265
2259
|
return {
|
|
2266
2260
|
runId: acceptedRun.id,
|
|
2267
|
-
execute: () => {
|
|
2268
|
-
const answeredBy = absorbedInto.get(acceptedRun.id);
|
|
2269
|
-
const answer = answeredBy ? runResults.get(answeredBy) : undefined;
|
|
2270
|
-
if (answer)
|
|
2271
|
-
return answer;
|
|
2272
|
-
const running = executeRun({
|
|
2273
|
-
acceptedRun,
|
|
2274
|
-
context,
|
|
2275
|
-
signal,
|
|
2276
|
-
absorbable,
|
|
2277
|
-
onAbsorbed: (absorbedRunId) => {
|
|
2278
|
-
absorbedInto.set(absorbedRunId, acceptedRun.id);
|
|
2279
|
-
}
|
|
2280
|
-
});
|
|
2281
|
-
runResults.set(acceptedRun.id, running);
|
|
2282
|
-
return running.finally(() => {
|
|
2283
|
-
absorbable.delete(acceptedRun.id);
|
|
2284
|
-
});
|
|
2285
|
-
}
|
|
2261
|
+
execute: () => executeRun({ acceptedRun, context, signal })
|
|
2286
2262
|
};
|
|
2287
2263
|
}
|
|
2288
2264
|
});
|
|
@@ -2529,15 +2505,6 @@ var CommitRunTerminalSchema = z6.object({
|
|
|
2529
2505
|
policyName: z6.string().min(1).optional(),
|
|
2530
2506
|
usage: AgentUsageSchema.optional()
|
|
2531
2507
|
});
|
|
2532
|
-
var AbsorbQueuedRunSchema = z6.object({
|
|
2533
|
-
conversationId: AgentRecordIdSchema,
|
|
2534
|
-
runningRunId: AgentRecordIdSchema,
|
|
2535
|
-
runningExpectedRevision: AgentRecordVersionSchema,
|
|
2536
|
-
ownerId: z6.string().min(1),
|
|
2537
|
-
fencingToken: AgentRecordVersionSchema.optional(),
|
|
2538
|
-
queuedRunId: AgentRecordIdSchema,
|
|
2539
|
-
queuedExpectedRevision: AgentRecordVersionSchema
|
|
2540
|
-
});
|
|
2541
2508
|
var RequestRunInterruptSchema = z6.object({
|
|
2542
2509
|
conversationId: AgentRecordIdSchema,
|
|
2543
2510
|
runId: AgentRecordIdSchema,
|
|
@@ -2678,24 +2645,17 @@ function replaceRun(runs, next) {
|
|
|
2678
2645
|
function replaceMessage(messages, next) {
|
|
2679
2646
|
return messages.some((message) => message.id === next.id) ? messages.map((message) => message.id === next.id ? next : message) : [...messages, next];
|
|
2680
2647
|
}
|
|
2648
|
+
var ACTIVE_AGENT_RUN_STATES = [
|
|
2649
|
+
"queued",
|
|
2650
|
+
"running",
|
|
2651
|
+
"interrupt_requested"
|
|
2652
|
+
];
|
|
2653
|
+
function isActiveRunState(state) {
|
|
2654
|
+
return ACTIVE_AGENT_RUN_STATES.includes(state);
|
|
2655
|
+
}
|
|
2681
2656
|
function conflict(actualVersion) {
|
|
2682
2657
|
return { outcome: "conflict", actualVersion };
|
|
2683
2658
|
}
|
|
2684
|
-
function terminalState(reason) {
|
|
2685
|
-
if (reason === "success" || reason === "policy_stop" || reason === "provider_stop") {
|
|
2686
|
-
return "completed";
|
|
2687
|
-
}
|
|
2688
|
-
if (reason === "interrupted")
|
|
2689
|
-
return "interrupted";
|
|
2690
|
-
if (reason === "superseded")
|
|
2691
|
-
return "superseded";
|
|
2692
|
-
if (reason === "cancelled" || reason === "shutdown" || reason === "timeout") {
|
|
2693
|
-
return "cancelled";
|
|
2694
|
-
}
|
|
2695
|
-
if (reason === "abandoned")
|
|
2696
|
-
return "abandoned";
|
|
2697
|
-
return "failed";
|
|
2698
|
-
}
|
|
2699
2659
|
function applied(current, input, effects) {
|
|
2700
2660
|
return {
|
|
2701
2661
|
outcome: "applied",
|
|
@@ -2706,7 +2666,6 @@ function applied(current, input, effects) {
|
|
|
2706
2666
|
messages: input.messages ?? current.messages
|
|
2707
2667
|
}),
|
|
2708
2668
|
...effects?.runRecord && { runRecord: effects.runRecord },
|
|
2709
|
-
...effects?.secondaryRunRecord && { secondaryRunRecord: effects.secondaryRunRecord },
|
|
2710
2669
|
...effects?.admissionReceipt && { admissionReceipt: effects.admissionReceipt },
|
|
2711
2670
|
...effects?.historyMutation && { historyMutation: effects.historyMutation }
|
|
2712
2671
|
};
|
|
@@ -2750,39 +2709,6 @@ function reduceStore(current, operation) {
|
|
|
2750
2709
|
historyMutation: { type: "admit", input: input.input }
|
|
2751
2710
|
});
|
|
2752
2711
|
}
|
|
2753
|
-
if (operation.type === "absorb") {
|
|
2754
|
-
const input = operation.input;
|
|
2755
|
-
if (current.conversationId !== input.conversationId)
|
|
2756
|
-
return { outcome: "not_found" };
|
|
2757
|
-
const running = current.runs.find((candidate) => candidate.id === input.runningRunId);
|
|
2758
|
-
const queued = current.runs.find((candidate) => candidate.id === input.queuedRunId);
|
|
2759
|
-
if (!running || !queued)
|
|
2760
|
-
return { outcome: "not_found" };
|
|
2761
|
-
if (running.revision !== input.runningExpectedRevision || running.state !== "running" || running.ownerId !== input.ownerId || input.fencingToken !== undefined && running.fencingToken !== input.fencingToken) {
|
|
2762
|
-
return conflict(running.revision);
|
|
2763
|
-
}
|
|
2764
|
-
if (queued.revision !== input.queuedExpectedRevision || queued.state !== "queued" || queued.ownerId !== undefined || queued.terminalReason !== undefined || queued.id === running.id) {
|
|
2765
|
-
return conflict(queued.revision);
|
|
2766
|
-
}
|
|
2767
|
-
const stamp = new Date().toISOString();
|
|
2768
|
-
const grown = AgentRunSchema.parse({
|
|
2769
|
-
...running,
|
|
2770
|
-
inputMessageIds: [...running.inputMessageIds, ...queued.inputMessageIds],
|
|
2771
|
-
revision: running.revision + 1,
|
|
2772
|
-
updatedAt: stamp
|
|
2773
|
-
});
|
|
2774
|
-
const emptied = AgentRunSchema.parse({
|
|
2775
|
-
...queued,
|
|
2776
|
-
state: "absorbed",
|
|
2777
|
-
absorbedIntoRunId: running.id,
|
|
2778
|
-
revision: queued.revision + 1,
|
|
2779
|
-
updatedAt: stamp
|
|
2780
|
-
});
|
|
2781
|
-
return applied(current, { runs: replaceRun(replaceRun(current.runs, grown), emptied) }, {
|
|
2782
|
-
runRecord: AgentStoredRunSchema.parse({ schemaVersion: 1, run: grown }),
|
|
2783
|
-
secondaryRunRecord: AgentStoredRunSchema.parse({ schemaVersion: 1, run: emptied })
|
|
2784
|
-
});
|
|
2785
|
-
}
|
|
2786
2712
|
const conversationId = operation.input.conversationId;
|
|
2787
2713
|
const run = operation.type === "compact" ? undefined : current.runs.find((candidate) => candidate.id === operation.input.runId);
|
|
2788
2714
|
if (operation.type !== "compact" && !run)
|
|
@@ -2840,22 +2766,18 @@ function reduceStore(current, operation) {
|
|
|
2840
2766
|
}
|
|
2841
2767
|
if (operation.type === "recover" && run) {
|
|
2842
2768
|
const input = operation.input;
|
|
2843
|
-
if (run.revision !== input.expectedRevision || !
|
|
2769
|
+
if (run.revision !== input.expectedRevision || !isActiveRunState(run.state)) {
|
|
2844
2770
|
return conflict(run.revision);
|
|
2845
2771
|
}
|
|
2846
2772
|
if (input.action === "requeue" && run.state !== "queued" && input.replaySafe !== true) {
|
|
2847
2773
|
throw new TypeError("Recovering an acquired run requires explicit replaySafe evidence");
|
|
2848
2774
|
}
|
|
2775
|
+
const { ownerId: _released, ...carried } = run;
|
|
2849
2776
|
const next = AgentRunSchema.parse({
|
|
2850
|
-
|
|
2851
|
-
id: run.id,
|
|
2852
|
-
conversationId: run.conversationId,
|
|
2853
|
-
inputMessageIds: run.inputMessageIds,
|
|
2854
|
-
assistantMessageId: run.assistantMessageId,
|
|
2777
|
+
...carried,
|
|
2855
2778
|
state: input.action === "requeue" ? "queued" : "abandoned",
|
|
2856
2779
|
revision: run.revision + 1,
|
|
2857
2780
|
...input.action === "abandon" && { terminalReason: "abandoned" },
|
|
2858
|
-
createdAt: run.createdAt,
|
|
2859
2781
|
updatedAt: new Date().toISOString()
|
|
2860
2782
|
});
|
|
2861
2783
|
if (input.action === "abandon") {
|
|
@@ -2896,7 +2818,7 @@ function reduceStore(current, operation) {
|
|
|
2896
2818
|
}
|
|
2897
2819
|
const next = AgentRunSchema.parse({
|
|
2898
2820
|
...run,
|
|
2899
|
-
state:
|
|
2821
|
+
state: runStateForTerminalReason(input.reason),
|
|
2900
2822
|
terminalReason: input.reason,
|
|
2901
2823
|
...input.policyName && { terminalPolicyName: input.policyName },
|
|
2902
2824
|
...input.usage && { usage: input.usage },
|
|
@@ -2925,6 +2847,10 @@ function reduceStore(current, operation) {
|
|
|
2925
2847
|
if (!input.replacedMessageIds.every((id) => current.messages.some((m) => m.id === id))) {
|
|
2926
2848
|
return { outcome: "not_found" };
|
|
2927
2849
|
}
|
|
2850
|
+
const liveAssistant = current.runs.find((candidate) => isActiveRunState(candidate.state) && replaced.has(candidate.assistantMessageId));
|
|
2851
|
+
if (liveAssistant) {
|
|
2852
|
+
throw new TypeError(`Compaction may not replace the assistant message of run ${liveAssistant.id}, which has not finished`);
|
|
2853
|
+
}
|
|
2928
2854
|
const positions = current.messages.map((message, index) => replaced.has(message.id) ? index : undefined).filter((index) => index !== undefined);
|
|
2929
2855
|
const first = positions[0];
|
|
2930
2856
|
if (first === undefined || positions.some((position, offset) => position !== first + offset) || input.summary.conversationId !== input.conversationId || input.summary.runId !== undefined || input.summary.role !== "summary" || input.summary.status !== "committed" || current.messages.some((message) => message.id === input.summary.id) || current.runs.some((candidate) => candidate.assistantMessageId === input.summary.id)) {
|
|
@@ -2988,7 +2914,7 @@ function createAgentRuntimeStore(driver) {
|
|
|
2988
2914
|
});
|
|
2989
2915
|
const mutate = (operation) => driver.transaction(async (transaction) => {
|
|
2990
2916
|
const conversationId = operationConversationId(operation);
|
|
2991
|
-
const operationRunId = operation.type === "accept" ? operation.input.coalesceIntoRunId : operation.type === "compact" ? undefined : operation.
|
|
2917
|
+
const operationRunId = operation.type === "accept" ? operation.input.coalesceIntoRunId : operation.type === "compact" ? undefined : operation.input.runId;
|
|
2992
2918
|
const [stored, messages, activeRecords, operationRecord, duplicateReceipt] = await Promise.all([
|
|
2993
2919
|
driver.head.load(transaction, conversationId),
|
|
2994
2920
|
driver.history.load(transaction, conversationId),
|
|
@@ -3069,9 +2995,6 @@ function createAgentRuntimeStore(driver) {
|
|
|
3069
2995
|
return conflict(outcome.actualVersion);
|
|
3070
2996
|
if (reduced.runRecord)
|
|
3071
2997
|
await driver.runs.save(transaction, reduced.runRecord);
|
|
3072
|
-
if (reduced.secondaryRunRecord) {
|
|
3073
|
-
await driver.runs.save(transaction, reduced.secondaryRunRecord);
|
|
3074
|
-
}
|
|
3075
2998
|
if (reduced.admissionReceipt) {
|
|
3076
2999
|
await driver.admissions.create(transaction, reduced.admissionReceipt);
|
|
3077
3000
|
}
|
|
@@ -3095,7 +3018,6 @@ function createAgentRuntimeStore(driver) {
|
|
|
3095
3018
|
type: "interrupt",
|
|
3096
3019
|
input: RequestRunInterruptSchema.parse(input)
|
|
3097
3020
|
}),
|
|
3098
|
-
absorbQueuedRun: (input) => mutate({ type: "absorb", input: AbsorbQueuedRunSchema.parse(input) }),
|
|
3099
3021
|
recoverRun: (input) => mutate({ type: "recover", input: RecoverAgentRunSchema.parse(input) }),
|
|
3100
3022
|
commitRunTerminal: (input) => mutate({ type: "terminal", input: CommitRunTerminalSchema.parse(input) }),
|
|
3101
3023
|
replaceCompactedRange: (input) => mutate({
|
|
@@ -3191,7 +3113,7 @@ function createMemoryAgentRuntimeStore() {
|
|
|
3191
3113
|
});
|
|
3192
3114
|
},
|
|
3193
3115
|
async listActive(transaction, conversationId) {
|
|
3194
|
-
return [...transaction.runs.get(conversationId)?.values() ?? []].filter((record) =>
|
|
3116
|
+
return [...transaction.runs.get(conversationId)?.values() ?? []].filter((record) => isActiveRunState(record.run.state)).map((record) => AgentStoredRunSchema.parse(structuredClone(record)));
|
|
3195
3117
|
},
|
|
3196
3118
|
async save(transaction, rawRecord) {
|
|
3197
3119
|
const record = AgentStoredRunSchema.parse(structuredClone(rawRecord));
|
|
@@ -3253,9 +3175,12 @@ function createMemoryAgentRuntimeStore() {
|
|
|
3253
3175
|
}
|
|
3254
3176
|
},
|
|
3255
3177
|
async scanRecoverable(input) {
|
|
3256
|
-
const descriptors = [...runs].flatMap(([conversationId, conversationRuns]) => [...conversationRuns.values()].filter((record) =>
|
|
3178
|
+
const descriptors = [...runs].flatMap(([conversationId, conversationRuns]) => [...conversationRuns.values()].filter((record) => isActiveRunState(record.run.state)).map((record) => ({ conversationId, run: record.run }))).sort((left, right) => left.conversationId.localeCompare(right.conversationId) || left.run.id.localeCompare(right.run.id));
|
|
3257
3179
|
const cursorTuple = input.cursor ? parseRecoverableCursor(input.cursor) : undefined;
|
|
3258
|
-
const start = cursorTuple ? descriptors.findIndex((item) => item.conversationId === cursorTuple[0] && item.run.id
|
|
3180
|
+
const start = cursorTuple ? descriptors.findIndex((item) => item.conversationId.localeCompare(cursorTuple[0]) > 0 || item.conversationId === cursorTuple[0] && item.run.id.localeCompare(cursorTuple[1]) > 0) : 0;
|
|
3181
|
+
if (start === -1) {
|
|
3182
|
+
return AgentRecoverablePageSchema.parse({ items: [] });
|
|
3183
|
+
}
|
|
3259
3184
|
const items = descriptors.slice(start, start + input.limit);
|
|
3260
3185
|
const last = items.at(-1);
|
|
3261
3186
|
const hasMore = start + items.length < descriptors.length;
|
|
@@ -3268,7 +3193,6 @@ function createMemoryAgentRuntimeStore() {
|
|
|
3268
3193
|
return createAgentRuntimeStore(driver);
|
|
3269
3194
|
}
|
|
3270
3195
|
export {
|
|
3271
|
-
AbsorbQueuedRunSchema,
|
|
3272
3196
|
AcceptInputAndAssignRunSchema,
|
|
3273
3197
|
AcquireAgentRunSchema,
|
|
3274
3198
|
AgentAdmissionEventSchema,
|
|
@@ -3300,14 +3224,17 @@ export {
|
|
|
3300
3224
|
AgentRunEventSchema,
|
|
3301
3225
|
AgentRunMetricsSchema,
|
|
3302
3226
|
AgentRunSchema,
|
|
3227
|
+
AgentRunStartedEventSchema,
|
|
3303
3228
|
AgentRunStateEventSchema,
|
|
3304
3229
|
AgentRunStateSchema,
|
|
3230
|
+
AgentRunTerminalEventSchema,
|
|
3305
3231
|
AgentRuntimeConflictError,
|
|
3306
3232
|
AgentRuntimeEventCursorSchema,
|
|
3307
3233
|
AgentRuntimeEventSchema,
|
|
3308
3234
|
AgentRuntimeHeadSchema,
|
|
3309
3235
|
AgentSnapshotSchema,
|
|
3310
3236
|
AgentSourcePartSchema,
|
|
3237
|
+
AgentStepFinishedEventSchema,
|
|
3311
3238
|
AgentStoreAppliedSchema,
|
|
3312
3239
|
AgentStoreConflictSchema,
|
|
3313
3240
|
AgentStoreDuplicateSchema,
|
|
@@ -3344,6 +3271,7 @@ export {
|
|
|
3344
3271
|
defineModelRegistry,
|
|
3345
3272
|
projectAgentHistory,
|
|
3346
3273
|
projectAgentHistoryDetailed,
|
|
3274
|
+
runStateForTerminalReason,
|
|
3347
3275
|
selectAgentHistory,
|
|
3348
3276
|
structuredCompaction,
|
|
3349
3277
|
validateAgentModelSnapshot
|