@eum-agent/context-management 1.0.1 → 1.1.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/index.js +471 -109
- package/package.json +5 -5
- package/ui/ui.js +183 -197
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { existsSync } from "node:fs";
|
|
2
2
|
import { fileURLToPath } from "node:url";
|
|
3
3
|
import { z } from "zod";
|
|
4
|
-
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
5
5
|
import { setImmediate } from "node:timers/promises";
|
|
6
6
|
//#region src/agent-configuration.ts
|
|
7
7
|
/** Discovery entrances are always available while this owner's exposure policy is active. */
|
|
@@ -385,7 +385,7 @@ function toolSearch(ctx) {
|
|
|
385
385
|
/** The target's own parameters, including output budgets, belong inside arguments. */
|
|
386
386
|
const ToolCallInput = z.strictObject({
|
|
387
387
|
name: z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/).describe("Exact available tool name, usually returned by tool_search."),
|
|
388
|
-
arguments: z.record(z.string(), z.json()).describe("Target input object matching its complete schema. Put target outputTokens and continuation fields here.")
|
|
388
|
+
arguments: z.record(z.string(), z.unknown()).pipe(z.record(z.string(), z.json())).describe("Target input object matching its complete schema. Put target outputTokens and continuation fields here.")
|
|
389
389
|
});
|
|
390
390
|
/** Declares the generic route without executing or wrapping a target result. */
|
|
391
391
|
function toolCall() {
|
|
@@ -981,6 +981,15 @@ const ContextMeasurementSchema = z.object({
|
|
|
981
981
|
capacitySource: z.enum(["declared", "assumed"]).optional()
|
|
982
982
|
});
|
|
983
983
|
const count = z.number().int().nonnegative();
|
|
984
|
+
/** Request identity persisted with the last display reading. */
|
|
985
|
+
const ObservationIdentitySchema = z.object({
|
|
986
|
+
sessionId: z.string(),
|
|
987
|
+
historyGeneration: count,
|
|
988
|
+
modelCallId: z.string(),
|
|
989
|
+
modelFingerprint: z.string(),
|
|
990
|
+
projectionRevision: count,
|
|
991
|
+
sourceSeq: z.number().int().min(-1)
|
|
992
|
+
});
|
|
984
993
|
const SplitSchema = z.object({
|
|
985
994
|
categories: z.object({
|
|
986
995
|
system: count,
|
|
@@ -999,6 +1008,9 @@ const SplitSchema = z.object({
|
|
|
999
1008
|
});
|
|
1000
1009
|
/** Everything the coordinator needs to show a reading again after a restart. */
|
|
1001
1010
|
const ReadingSchema = z.object({
|
|
1011
|
+
/** Durable preparation and compaction identity for the displayed view. */
|
|
1012
|
+
viewIdentity: z.string(),
|
|
1013
|
+
observation: ObservationIdentitySchema.optional(),
|
|
1002
1014
|
/** Model/parameter identity; a mismatching reading is never restored. */
|
|
1003
1015
|
measurementIdentity: z.string().optional(),
|
|
1004
1016
|
measurement: ContextMeasurementSchema,
|
|
@@ -1009,7 +1021,8 @@ const ReadingSchema = z.object({
|
|
|
1009
1021
|
reported: count,
|
|
1010
1022
|
estimate: count,
|
|
1011
1023
|
fingerprint: z.string(),
|
|
1012
|
-
revision: z.number().int().nonnegative()
|
|
1024
|
+
revision: z.number().int().nonnegative(),
|
|
1025
|
+
viewIdentity: z.string()
|
|
1013
1026
|
}).optional()
|
|
1014
1027
|
});
|
|
1015
1028
|
//#endregion
|
|
@@ -1023,6 +1036,7 @@ const ContextTrigger = z.enum([
|
|
|
1023
1036
|
]);
|
|
1024
1037
|
/** A completed preparation, including failures that preserve the committed view. */
|
|
1025
1038
|
const ContextOperationResult = z.object({
|
|
1039
|
+
modelCallId: z.string().optional(),
|
|
1026
1040
|
campaignId: z.string().optional(),
|
|
1027
1041
|
attempt: z.number().int().positive().optional(),
|
|
1028
1042
|
completedChunks: z.number().int().nonnegative().optional(),
|
|
@@ -1050,7 +1064,9 @@ const ContextOperationResult = z.object({
|
|
|
1050
1064
|
}).optional(),
|
|
1051
1065
|
usage: z.object({
|
|
1052
1066
|
inputTokens: z.number().int().nonnegative(),
|
|
1053
|
-
outputTokens: z.number().int().nonnegative()
|
|
1067
|
+
outputTokens: z.number().int().nonnegative(),
|
|
1068
|
+
cacheReadTokens: z.number().int().nonnegative().optional(),
|
|
1069
|
+
cacheWriteTokens: z.number().int().nonnegative().optional()
|
|
1054
1070
|
}).optional(),
|
|
1055
1071
|
elapsedMs: z.number().int().nonnegative()
|
|
1056
1072
|
});
|
|
@@ -1091,6 +1107,24 @@ const ContextOccupancy = z.object({
|
|
|
1091
1107
|
});
|
|
1092
1108
|
/** Live request measurements and durable preparation totals for one session. */
|
|
1093
1109
|
const SessionContextStatus = z.object({
|
|
1110
|
+
statusOrder: z.object({
|
|
1111
|
+
epoch: z.string(),
|
|
1112
|
+
sequence: z.number().int().nonnegative(),
|
|
1113
|
+
sourceSeq: z.number().int().min(-1),
|
|
1114
|
+
historyGeneration: z.number().int().nonnegative()
|
|
1115
|
+
}).optional(),
|
|
1116
|
+
observation: z.object({
|
|
1117
|
+
identity: ObservationIdentitySchema,
|
|
1118
|
+
source: z.enum(["estimated", "reported"]),
|
|
1119
|
+
freshness: z.enum(["current", "historical"])
|
|
1120
|
+
}).optional(),
|
|
1121
|
+
usage: z.object({
|
|
1122
|
+
inputTokens: z.number().int().nonnegative(),
|
|
1123
|
+
outputTokens: z.number().int().nonnegative(),
|
|
1124
|
+
totalTokens: z.number().int().nonnegative(),
|
|
1125
|
+
cacheReadTokens: z.number().int().nonnegative().optional(),
|
|
1126
|
+
cacheWriteTokens: z.number().int().nonnegative().optional()
|
|
1127
|
+
}).optional(),
|
|
1094
1128
|
/** Committed model and parameter identity of this observation, never raw settings. */
|
|
1095
1129
|
measurementIdentity: z.string().optional(),
|
|
1096
1130
|
revision: z.number().int().nonnegative(),
|
|
@@ -1107,6 +1141,20 @@ const SessionContextStatus = z.object({
|
|
|
1107
1141
|
totalTokens: z.number().int().nonnegative(),
|
|
1108
1142
|
operation: z.object({
|
|
1109
1143
|
operationId: z.string(),
|
|
1144
|
+
phase: z.enum([
|
|
1145
|
+
"preview",
|
|
1146
|
+
"reduction",
|
|
1147
|
+
"summary"
|
|
1148
|
+
]).optional(),
|
|
1149
|
+
target: z.discriminatedUnion("kind", [z.object({
|
|
1150
|
+
kind: z.literal("run"),
|
|
1151
|
+
historyGeneration: z.number().int().nonnegative(),
|
|
1152
|
+
turn: z.string()
|
|
1153
|
+
}), z.object({
|
|
1154
|
+
kind: z.literal("maintenance"),
|
|
1155
|
+
operationId: z.string()
|
|
1156
|
+
})]).optional(),
|
|
1157
|
+
elapsedMs: z.number().int().nonnegative().optional(),
|
|
1110
1158
|
trigger: ContextTrigger,
|
|
1111
1159
|
startedAt: z.number().optional(),
|
|
1112
1160
|
completedChunks: z.number().int().nonnegative().optional()
|
|
@@ -1301,13 +1349,6 @@ async function rawBreakdown(request, inputTokens, deps, scheduling = {}) {
|
|
|
1301
1349
|
}
|
|
1302
1350
|
return categoryBreakdown(request, inputTokens, deps, messageBytes);
|
|
1303
1351
|
}
|
|
1304
|
-
/** Awaits the owner's complete request display count without choosing an encoding. */
|
|
1305
|
-
async function displayTokensOf(request, signal, measure) {
|
|
1306
|
-
signal.throwIfAborted();
|
|
1307
|
-
const tokens = await measure?.(request, signal);
|
|
1308
|
-
signal.throwIfAborted();
|
|
1309
|
-
return tokens;
|
|
1310
|
-
}
|
|
1311
1352
|
/** Internal output reservation used when the adapter reports no usable reserve. */
|
|
1312
1353
|
const ASSUMED_OUTPUT_RESERVE = 8192;
|
|
1313
1354
|
/**
|
|
@@ -1422,9 +1463,10 @@ const contextSourceRef$1 = (message, part) => `msg:${message}:${part}`;
|
|
|
1422
1463
|
* model estimator. Mandatory instructions remain whole for the final request
|
|
1423
1464
|
* check; protected pages are excluded from ordinary preview allocation.
|
|
1424
1465
|
* Throws when required identifiers alone cannot fit the ordinary step budget.
|
|
1466
|
+
* Media is preserved outside this text budget and measured by the final request check.
|
|
1425
1467
|
* Returned replacements reference immutable originals and preserve all metadata.
|
|
1426
1468
|
*/
|
|
1427
|
-
function planToolPreviews(events, inputBudget, measureTokens, framework
|
|
1469
|
+
function planToolPreviews(events, inputBudget, measureTokens, framework) {
|
|
1428
1470
|
const measured = /* @__PURE__ */ new Map();
|
|
1429
1471
|
let cachedCodeUnits = 0;
|
|
1430
1472
|
const tokens = (text) => {
|
|
@@ -1471,6 +1513,59 @@ function planToolPreviews(events, inputBudget, measureTokens, framework, measure
|
|
|
1471
1513
|
} : found.part
|
|
1472
1514
|
}];
|
|
1473
1515
|
});
|
|
1516
|
+
if (ordered.every(({ part }) => Number.isSafeInteger(part.delivery?.outputTokens))) {
|
|
1517
|
+
for (const { part, partIndex } of ordered) {
|
|
1518
|
+
if (replaced.has(`${source.messageSeq}:${partIndex}`) || part.delivery?.kind === "exact-page") continue;
|
|
1519
|
+
const allowance = part.delivery?.outputTokens ?? 0;
|
|
1520
|
+
const { files: _media, ownerContext: _provenance, delivery: _delivery, previewTokens: _hint, widgets: _widgets, widgetIssues: _widgetIssues, ...textPart } = part;
|
|
1521
|
+
const cost = (content) => tokens(JSON.stringify({
|
|
1522
|
+
...textPart,
|
|
1523
|
+
content
|
|
1524
|
+
}));
|
|
1525
|
+
if (!answers.has(partIndex) && cost(part.content) <= allowance) continue;
|
|
1526
|
+
const ref = sourceRef(partIndex);
|
|
1527
|
+
const encode = (preview) => JSON.stringify({
|
|
1528
|
+
ok: true,
|
|
1529
|
+
complete: false,
|
|
1530
|
+
preview,
|
|
1531
|
+
source: {
|
|
1532
|
+
ref,
|
|
1533
|
+
sourceComplete: answers.has(partIndex) || (part.delivery?.sourceComplete ?? false),
|
|
1534
|
+
recoverable: true
|
|
1535
|
+
},
|
|
1536
|
+
next: {
|
|
1537
|
+
tool: "context_restore",
|
|
1538
|
+
arguments: { pages: [{ ref }] }
|
|
1539
|
+
}
|
|
1540
|
+
});
|
|
1541
|
+
let content = encode("");
|
|
1542
|
+
if (cost(content) > allowance) throw new Error("protected_context_exceeds_budget");
|
|
1543
|
+
const points = [...part.content];
|
|
1544
|
+
let low = 0, high = points.length;
|
|
1545
|
+
while (low <= high) {
|
|
1546
|
+
const count = Math.floor((low + high) / 2);
|
|
1547
|
+
const head = Math.ceil(count * 2 / 3), tail = count - head;
|
|
1548
|
+
const candidate = encode(points.slice(0, head).join("") + (tail ? points.slice(-tail).join("") : ""));
|
|
1549
|
+
if (cost(candidate) <= allowance) {
|
|
1550
|
+
content = candidate;
|
|
1551
|
+
low = count + 1;
|
|
1552
|
+
} else high = count - 1;
|
|
1553
|
+
}
|
|
1554
|
+
replacements.push({
|
|
1555
|
+
messageSeq: source.messageSeq,
|
|
1556
|
+
partIndex,
|
|
1557
|
+
replacement: {
|
|
1558
|
+
...part,
|
|
1559
|
+
content
|
|
1560
|
+
},
|
|
1561
|
+
sourceRef: ref,
|
|
1562
|
+
originalCodePoints: points.length,
|
|
1563
|
+
previewTokens: Math.max(0, tokens(content) - tokens(encode(""))),
|
|
1564
|
+
truncated: true
|
|
1565
|
+
});
|
|
1566
|
+
}
|
|
1567
|
+
continue;
|
|
1568
|
+
}
|
|
1474
1569
|
const originalCosts = /* @__PURE__ */ new Map();
|
|
1475
1570
|
const originalCost = (partIndex, content) => {
|
|
1476
1571
|
const found = originalCosts.get(partIndex);
|
|
@@ -1479,15 +1574,9 @@ function planToolPreviews(events, inputBudget, measureTokens, framework, measure
|
|
|
1479
1574
|
originalCosts.set(partIndex, cost);
|
|
1480
1575
|
return cost;
|
|
1481
1576
|
};
|
|
1482
|
-
if (measureResult) {
|
|
1483
|
-
for (const { part } of ordered) if (part.files?.length && part.delivery && measureResult({
|
|
1484
|
-
...part,
|
|
1485
|
-
content: ""
|
|
1486
|
-
}) > part.delivery.outputTokens) throw new Error("media_budget_exceeded: retry original retrieval with a larger outputTokens allowance; committed results remain saved");
|
|
1487
|
-
}
|
|
1488
1577
|
const metadata = ordered.reduce((sum, { part }) => {
|
|
1489
|
-
const { content: _content, previewTokens: _hint, delivery: _delivery, requiredContext: _requiredContext, ...rest } = part;
|
|
1490
|
-
return sum +
|
|
1578
|
+
const { content: _content, files: _files, previewTokens: _hint, delivery: _delivery, requiredContext: _requiredContext, ...rest } = part;
|
|
1579
|
+
return sum + tokens(JSON.stringify(rest));
|
|
1491
1580
|
}, 0);
|
|
1492
1581
|
const required = /* @__PURE__ */ new Map();
|
|
1493
1582
|
for (const { part } of ordered) for (const block of part.requiredContext ?? []) {
|
|
@@ -1991,6 +2080,172 @@ function summaryFallbackPort(primary, fallback, onFallback) {
|
|
|
1991
2080
|
};
|
|
1992
2081
|
}
|
|
1993
2082
|
//#endregion
|
|
2083
|
+
//#region src/runtime/first-delivery.ts
|
|
2084
|
+
const OWNER = "@eum-agent/context-management";
|
|
2085
|
+
const fingerprints = /* @__PURE__ */ new WeakMap();
|
|
2086
|
+
/** Immutable event values retain their digest without rereading result bodies. */
|
|
2087
|
+
function fingerprint(value) {
|
|
2088
|
+
const cached = fingerprints.get(value);
|
|
2089
|
+
if (cached !== void 0) return cached;
|
|
2090
|
+
const canonical = JSON.stringify(value, (_key, entry) => {
|
|
2091
|
+
if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return entry;
|
|
2092
|
+
return Object.fromEntries(Object.entries(entry).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0));
|
|
2093
|
+
});
|
|
2094
|
+
const digest = createHash("sha256").update(canonical).digest("hex");
|
|
2095
|
+
fingerprints.set(value, digest);
|
|
2096
|
+
return digest;
|
|
2097
|
+
}
|
|
2098
|
+
/** Owner payload for one immutable first-delivery decision. */
|
|
2099
|
+
const FirstDeliverySchema = z.strictObject({
|
|
2100
|
+
type: z.literal("first-delivery"),
|
|
2101
|
+
historyGeneration: z.number().int().nonnegative(),
|
|
2102
|
+
sourceMessageSeq: z.number().int().nonnegative(),
|
|
2103
|
+
sourceMessageId: z.string(),
|
|
2104
|
+
partIndex: z.number().int().nonnegative(),
|
|
2105
|
+
toolUseId: z.string(),
|
|
2106
|
+
originalFingerprint: z.string(),
|
|
2107
|
+
allowanceTokens: z.number().int().nonnegative(),
|
|
2108
|
+
kind: z.enum([
|
|
2109
|
+
"passthrough",
|
|
2110
|
+
"exact",
|
|
2111
|
+
"preview"
|
|
2112
|
+
]),
|
|
2113
|
+
replacement: z.string().optional(),
|
|
2114
|
+
sourceRef: z.string().optional(),
|
|
2115
|
+
modelFingerprint: z.string(),
|
|
2116
|
+
originalCodePoints: z.number().int().nonnegative().optional(),
|
|
2117
|
+
previewTokens: z.number().int().nonnegative().optional()
|
|
2118
|
+
}).refine((value) => value.kind !== "preview" || value.replacement !== void 0 && value.sourceRef !== void 0, "Preview delivery requires its replacement and source reference");
|
|
2119
|
+
/** Plans immutable owner records for previously unprepared tool results. */
|
|
2120
|
+
function deliveryPlans(projection, replacements, generation, modelFingerprint) {
|
|
2121
|
+
const prepared = new Set(projection.replacedSourceKeys);
|
|
2122
|
+
const visible = new Set(projection.messages.map((message) => message.id));
|
|
2123
|
+
return projection.sources.flatMap(({ messageSeq, message }) => {
|
|
2124
|
+
if (!visible.has(message.id)) return [];
|
|
2125
|
+
return message.content.flatMap((part, partIndex) => {
|
|
2126
|
+
if (part.type !== "tool-result" || prepared.has(`${messageSeq}:${partIndex}`)) return [];
|
|
2127
|
+
const replacement = replacements.find((one) => one.messageSeq === messageSeq && one.partIndex === partIndex);
|
|
2128
|
+
return [{
|
|
2129
|
+
type: "first-delivery",
|
|
2130
|
+
historyGeneration: generation,
|
|
2131
|
+
sourceMessageSeq: messageSeq,
|
|
2132
|
+
sourceMessageId: message.id,
|
|
2133
|
+
partIndex,
|
|
2134
|
+
toolUseId: part.toolUseId,
|
|
2135
|
+
originalFingerprint: fingerprint(part),
|
|
2136
|
+
allowanceTokens: part.delivery?.outputTokens ?? 2e3,
|
|
2137
|
+
kind: replacement ? "preview" : part.delivery?.kind === "exact-page" ? "exact" : "passthrough",
|
|
2138
|
+
...replacement ? {
|
|
2139
|
+
replacement: replacement.replacement.content,
|
|
2140
|
+
sourceRef: replacement.sourceRef,
|
|
2141
|
+
originalCodePoints: replacement.originalCodePoints,
|
|
2142
|
+
previewTokens: replacement.previewTokens
|
|
2143
|
+
} : {},
|
|
2144
|
+
modelFingerprint
|
|
2145
|
+
}];
|
|
2146
|
+
});
|
|
2147
|
+
});
|
|
2148
|
+
}
|
|
2149
|
+
/** Applies recorded owner views without changing the authoritative source messages. */
|
|
2150
|
+
function projectDeliveries(input, framework, generation) {
|
|
2151
|
+
const events = input.map((one, seq) => "event" in one ? one : {
|
|
2152
|
+
seq,
|
|
2153
|
+
at: 0,
|
|
2154
|
+
event: one
|
|
2155
|
+
});
|
|
2156
|
+
const projection = framework.project(events);
|
|
2157
|
+
const prepared = /* @__PURE__ */ new Map();
|
|
2158
|
+
const sources = new Map(projection.sources.map((source) => [source.message.id, source]));
|
|
2159
|
+
const replaced = new Set(projection.replacedSourceKeys);
|
|
2160
|
+
for (const { event } of framework.history(events)) {
|
|
2161
|
+
if (event.kind !== "owner-state" || event.owner !== OWNER || event.key !== "first-delivery") continue;
|
|
2162
|
+
const parsed = FirstDeliverySchema.safeParse(event.data);
|
|
2163
|
+
if (!parsed.success) throw new Error("invalid_first_delivery");
|
|
2164
|
+
const receipt = parsed.data;
|
|
2165
|
+
if (receipt.historyGeneration !== generation) continue;
|
|
2166
|
+
const source = sources.get(receipt.sourceMessageId);
|
|
2167
|
+
if (!source) continue;
|
|
2168
|
+
const key = `${source.messageSeq}:${receipt.partIndex}`;
|
|
2169
|
+
if (replaced.has(key)) continue;
|
|
2170
|
+
const part = source.message.content[receipt.partIndex];
|
|
2171
|
+
if (!part || part.type !== "tool-result" || part.toolUseId !== receipt.toolUseId || fingerprint(part) !== receipt.originalFingerprint) throw new Error("first_delivery_source_changed");
|
|
2172
|
+
const previous = prepared.get(key);
|
|
2173
|
+
if (previous && fingerprint(previous) !== fingerprint(receipt)) throw new Error("first_delivery_conflict");
|
|
2174
|
+
prepared.set(key, receipt);
|
|
2175
|
+
}
|
|
2176
|
+
const sourceSeq = new Map(projection.sources.map((one) => [one.message.id, one.messageSeq]));
|
|
2177
|
+
const entries = projection.entries.map((entry) => ({
|
|
2178
|
+
...entry,
|
|
2179
|
+
message: {
|
|
2180
|
+
...entry.message,
|
|
2181
|
+
content: entry.message.content.map((part, index) => {
|
|
2182
|
+
const receipt = prepared.get(`${sourceSeq.get(entry.message.id)}:${index}`);
|
|
2183
|
+
return part.type === "tool-result" && receipt?.kind === "preview" ? {
|
|
2184
|
+
...part,
|
|
2185
|
+
content: receipt.replacement ?? ""
|
|
2186
|
+
} : part;
|
|
2187
|
+
})
|
|
2188
|
+
}
|
|
2189
|
+
}));
|
|
2190
|
+
const previews = [...projection.previews];
|
|
2191
|
+
for (const receipt of prepared.values()) {
|
|
2192
|
+
if (receipt.kind !== "preview") continue;
|
|
2193
|
+
const source = sources.get(receipt.sourceMessageId);
|
|
2194
|
+
const original = source.message.content[receipt.partIndex];
|
|
2195
|
+
if (original?.type !== "tool-result") continue;
|
|
2196
|
+
previews.push({
|
|
2197
|
+
messageSeq: source.messageSeq,
|
|
2198
|
+
partIndex: receipt.partIndex,
|
|
2199
|
+
replacement: {
|
|
2200
|
+
...original,
|
|
2201
|
+
content: receipt.replacement
|
|
2202
|
+
},
|
|
2203
|
+
sourceRef: receipt.sourceRef,
|
|
2204
|
+
originalCodePoints: receipt.originalCodePoints,
|
|
2205
|
+
previewTokens: receipt.previewTokens,
|
|
2206
|
+
truncated: true
|
|
2207
|
+
});
|
|
2208
|
+
}
|
|
2209
|
+
return {
|
|
2210
|
+
...projection,
|
|
2211
|
+
previews,
|
|
2212
|
+
entries,
|
|
2213
|
+
messages: entries.map((entry) => entry.message),
|
|
2214
|
+
replacedSourceKeys: [...projection.replacedSourceKeys, ...prepared.keys()]
|
|
2215
|
+
};
|
|
2216
|
+
}
|
|
2217
|
+
//#endregion
|
|
2218
|
+
//#region src/runtime/usage.ts
|
|
2219
|
+
/** Folds committed physical usage incrementally, independent of visible history. */
|
|
2220
|
+
function createUsageAccumulator(startSeq) {
|
|
2221
|
+
let offset = 0;
|
|
2222
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2223
|
+
let inputTokens = 0, outputTokens = 0;
|
|
2224
|
+
let cacheReadTokens, cacheWriteTokens;
|
|
2225
|
+
return { read(events) {
|
|
2226
|
+
for (; offset < events.length; offset++) {
|
|
2227
|
+
const row = events[offset];
|
|
2228
|
+
if (row.seq <= startSeq) continue;
|
|
2229
|
+
const event = row.event;
|
|
2230
|
+
if (event.kind !== "message-appended" && event.kind !== "context-operation" || !event.usage) continue;
|
|
2231
|
+
const key = event.kind === "message-appended" ? `normal:${event.message.modelCallId ?? event.message.id}` : `auxiliary:${event.modelCallId ?? (event.campaignId && event.attempt ? `${event.campaignId}:${event.attempt}` : row.seq)}`;
|
|
2232
|
+
if (seen.has(key)) continue;
|
|
2233
|
+
seen.add(key);
|
|
2234
|
+
inputTokens += event.usage.inputTokens;
|
|
2235
|
+
outputTokens += event.usage.outputTokens;
|
|
2236
|
+
if (event.usage.cacheReadTokens !== void 0) cacheReadTokens = (cacheReadTokens ?? 0) + event.usage.cacheReadTokens;
|
|
2237
|
+
if (event.usage.cacheWriteTokens !== void 0) cacheWriteTokens = (cacheWriteTokens ?? 0) + event.usage.cacheWriteTokens;
|
|
2238
|
+
}
|
|
2239
|
+
return {
|
|
2240
|
+
inputTokens,
|
|
2241
|
+
outputTokens,
|
|
2242
|
+
totalTokens: inputTokens + outputTokens,
|
|
2243
|
+
...cacheReadTokens === void 0 ? {} : { cacheReadTokens },
|
|
2244
|
+
...cacheWriteTokens === void 0 ? {} : { cacheWriteTokens }
|
|
2245
|
+
};
|
|
2246
|
+
} };
|
|
2247
|
+
}
|
|
2248
|
+
//#endregion
|
|
1994
2249
|
//#region src/runtime/coordinator.ts
|
|
1995
2250
|
/** Adds the shared safe-input budget to one terminal adapter inspection. */
|
|
1996
2251
|
function contextMeasurement(inspection) {
|
|
@@ -2023,14 +2278,23 @@ function inspectContextRequest(port, request) {
|
|
|
2023
2278
|
/** Creates the coordinator bound to one immutable session identity. */
|
|
2024
2279
|
function createContextCoordinator(_deps) {
|
|
2025
2280
|
const deps = _deps;
|
|
2026
|
-
const projectContext = deps.framework.
|
|
2281
|
+
const projectContext = (events) => projectDeliveries(events, deps.framework, deps.historyGeneration?.() ?? 0);
|
|
2027
2282
|
const effectiveHistory = deps.framework.history;
|
|
2028
|
-
const planContextReduction$1 = (events) => planContextReduction(events,
|
|
2029
|
-
|
|
2283
|
+
const planContextReduction$1 = (events) => planContextReduction(events, {
|
|
2284
|
+
...deps.framework,
|
|
2285
|
+
project: projectContext
|
|
2286
|
+
});
|
|
2287
|
+
const planToolPreviews$1 = (events, budget, tokens) => planToolPreviews(events, budget, tokens, {
|
|
2288
|
+
...deps.framework,
|
|
2289
|
+
project: projectContext
|
|
2290
|
+
});
|
|
2030
2291
|
const now = deps.now ?? (() => Date.now());
|
|
2031
2292
|
const newOperationId = deps.newOperationId ?? randomUUID;
|
|
2293
|
+
const usageAccumulator = createUsageAccumulator(deps.usageStartSeq ?? -1);
|
|
2032
2294
|
let measurement;
|
|
2033
2295
|
let measurementIdentity;
|
|
2296
|
+
let observation;
|
|
2297
|
+
let historical = false;
|
|
2034
2298
|
let split;
|
|
2035
2299
|
/** The display estimate of the observed request; the Protocol inspection when none was given. */
|
|
2036
2300
|
let displayed = 0;
|
|
@@ -2095,6 +2359,7 @@ function createContextCoordinator(_deps) {
|
|
|
2095
2359
|
if (event === void 0 || event.status === void 0) return void 0;
|
|
2096
2360
|
const attemptDetails = event.campaignId === void 0 ? event : events.findLast(({ event: one }) => one.kind === "context-operation" && one.campaignId === event.campaignId && one.attempt === event.attempt && one.usage !== void 0)?.event;
|
|
2097
2361
|
return {
|
|
2362
|
+
modelCallId: attemptDetails?.modelCallId,
|
|
2098
2363
|
operationId: event.operationId,
|
|
2099
2364
|
trigger: event.trigger,
|
|
2100
2365
|
status: event.status,
|
|
@@ -2132,15 +2397,25 @@ function createContextCoordinator(_deps) {
|
|
|
2132
2397
|
/** What a person is shown: the reported input once the reply arrived, the last
|
|
2133
2398
|
* report plus the estimated growth while a reply is pending, the plain
|
|
2134
2399
|
* estimate when there is no report to build on. */
|
|
2135
|
-
function occupancy(current, revision) {
|
|
2400
|
+
function occupancy(current, revision, events) {
|
|
2136
2401
|
if (reported !== void 0) return occupancyOf(reported, "reported", split);
|
|
2137
|
-
return occupancyOf(anchor !== void 0 && anchor.fingerprint === current.fingerprint && anchor.revision === revision ? Math.max(0, anchor.reported + displayed - anchor.estimate) : displayed, current.unmeasured ? "unmeasured" : "estimated", split);
|
|
2402
|
+
return occupancyOf(anchor !== void 0 && anchor.fingerprint === current.fingerprint && anchor.viewIdentity === viewIdentity(events, revision) && anchor.revision === revision ? Math.max(0, anchor.reported + displayed - anchor.estimate) : displayed, current.unmeasured ? "unmeasured" : "estimated", split);
|
|
2403
|
+
}
|
|
2404
|
+
function viewIdentity(events, revision) {
|
|
2405
|
+
const last = events.findLast(({ event }) => event.kind === "owner-state" && event.owner === "@eum-agent/context-management" && event.key === "first-delivery");
|
|
2406
|
+
return JSON.stringify([
|
|
2407
|
+
revision,
|
|
2408
|
+
last?.seq ?? -1,
|
|
2409
|
+
deps.historyGeneration?.() ?? 0
|
|
2410
|
+
]);
|
|
2138
2411
|
}
|
|
2139
2412
|
/** Writes the reading down so a restart can show it again; a failed write
|
|
2140
2413
|
* costs the restart its reading, never this one. */
|
|
2141
|
-
function save() {
|
|
2414
|
+
function save(events, revision) {
|
|
2142
2415
|
if (deps.saved === void 0 || measurement === void 0) return;
|
|
2143
2416
|
const reading = {
|
|
2417
|
+
viewIdentity: viewIdentity(events, revision),
|
|
2418
|
+
observation,
|
|
2144
2419
|
measurement,
|
|
2145
2420
|
measurementIdentity,
|
|
2146
2421
|
...split === void 0 ? {} : { split },
|
|
@@ -2149,7 +2424,7 @@ function createContextCoordinator(_deps) {
|
|
|
2149
2424
|
...anchor === void 0 ? {} : { anchor }
|
|
2150
2425
|
};
|
|
2151
2426
|
try {
|
|
2152
|
-
deps.saved.put(
|
|
2427
|
+
deps.saved.put(revision, JSON.stringify(reading));
|
|
2153
2428
|
} catch (error) {
|
|
2154
2429
|
deps.log?.emit({
|
|
2155
2430
|
level: "error",
|
|
@@ -2163,7 +2438,10 @@ function createContextCoordinator(_deps) {
|
|
|
2163
2438
|
* leaves the meter empty until the next request. */
|
|
2164
2439
|
function restore() {
|
|
2165
2440
|
const row = deps.saved?.get();
|
|
2166
|
-
if (row === void 0
|
|
2441
|
+
if (row === void 0) return;
|
|
2442
|
+
const events = deps.read();
|
|
2443
|
+
const revision = projectContext(events).revision;
|
|
2444
|
+
if (row.revision !== revision) return;
|
|
2167
2445
|
let parsed;
|
|
2168
2446
|
try {
|
|
2169
2447
|
parsed = ReadingSchema.safeParse(JSON.parse(row.reading));
|
|
@@ -2171,14 +2449,17 @@ function createContextCoordinator(_deps) {
|
|
|
2171
2449
|
return;
|
|
2172
2450
|
}
|
|
2173
2451
|
if (!parsed.success) return;
|
|
2452
|
+
if (parsed.data.viewIdentity !== viewIdentity(events, revision)) return;
|
|
2174
2453
|
if (deps.measurementIdentity && parsed.data.measurementIdentity !== deps.measurementIdentity()) return;
|
|
2175
2454
|
measurement = parsed.data.measurement;
|
|
2455
|
+
historical = true;
|
|
2456
|
+
observation = parsed.data.observation;
|
|
2176
2457
|
measurementIdentity = parsed.data.measurementIdentity;
|
|
2177
2458
|
split = parsed.data.split;
|
|
2178
2459
|
displayed = parsed.data.displayed;
|
|
2179
2460
|
reported = parsed.data.reported;
|
|
2180
2461
|
anchor = parsed.data.anchor;
|
|
2181
|
-
measurementEventCount =
|
|
2462
|
+
measurementEventCount = events.length;
|
|
2182
2463
|
diagnostic = measurement.inputBudget === void 0 ? "capacity_unknown" : void 0;
|
|
2183
2464
|
}
|
|
2184
2465
|
function notify() {
|
|
@@ -2196,6 +2477,7 @@ function createContextCoordinator(_deps) {
|
|
|
2196
2477
|
async function recordOperation(input) {
|
|
2197
2478
|
await commitFact({
|
|
2198
2479
|
kind: "context-operation",
|
|
2480
|
+
modelCallId: input.modelCallId,
|
|
2199
2481
|
sessionId: deps.sessionId,
|
|
2200
2482
|
address: deps.address,
|
|
2201
2483
|
operationId: input.operationId,
|
|
@@ -2264,7 +2546,7 @@ function createContextCoordinator(_deps) {
|
|
|
2264
2546
|
};
|
|
2265
2547
|
let replacements;
|
|
2266
2548
|
try {
|
|
2267
|
-
replacements = planToolPreviews$1(deps.read(), before.inputBudget, tokens
|
|
2549
|
+
replacements = planToolPreviews$1(deps.read(), before.inputBudget, tokens);
|
|
2268
2550
|
} catch (error) {
|
|
2269
2551
|
if (trigger === "auto") {
|
|
2270
2552
|
const reason = error instanceof Error ? error.message.slice(0, 256) : "Preview admission failed.";
|
|
@@ -2283,39 +2565,36 @@ function createContextCoordinator(_deps) {
|
|
|
2283
2565
|
}
|
|
2284
2566
|
throw error;
|
|
2285
2567
|
}
|
|
2286
|
-
if (replacements.length > 0) {
|
|
2287
|
-
|
|
2288
|
-
|
|
2289
|
-
|
|
2290
|
-
|
|
2291
|
-
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
|
|
2295
|
-
|
|
2568
|
+
if (replacements.length > 0 && !historyRecoveryAvailable(request)) return {
|
|
2569
|
+
request,
|
|
2570
|
+
before,
|
|
2571
|
+
after,
|
|
2572
|
+
changed,
|
|
2573
|
+
recoveryUnavailable: true
|
|
2574
|
+
};
|
|
2575
|
+
const generation = deps.historyGeneration?.() ?? 0;
|
|
2576
|
+
const plans = deliveryPlans(projection, replacements, generation, before.fingerprint);
|
|
2577
|
+
for (const data of plans) {
|
|
2578
|
+
signal?.throwIfAborted();
|
|
2579
|
+
if ((deps.historyGeneration?.() ?? 0) !== generation) throw new Error("stale-origin");
|
|
2580
|
+
const hash = createHash("sha256").update(JSON.stringify(data)).digest("hex");
|
|
2581
|
+
await commitFact({
|
|
2582
|
+
kind: "owner-state",
|
|
2583
|
+
owner: "@eum-agent/context-management",
|
|
2584
|
+
key: "first-delivery",
|
|
2296
2585
|
sessionId: deps.sessionId,
|
|
2297
2586
|
address: deps.address,
|
|
2298
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
startPart: one.partIndex,
|
|
2306
|
-
endPart: one.partIndex + 1
|
|
2307
|
-
})),
|
|
2308
|
-
replacements: [...replacements].sort((a, b) => a.messageSeq - b.messageSeq || a.partIndex - b.partIndex),
|
|
2309
|
-
before,
|
|
2310
|
-
after: before
|
|
2311
|
-
};
|
|
2312
|
-
event.sourceRanges.sort((a, b) => a.messageSeq - b.messageSeq || a.startPart - b.startPart);
|
|
2313
|
-
event.after = inspect(port, await assembleProjected(projectContext(withProjectedEvent(deps.read(), event)).messages));
|
|
2314
|
-
await commitFact(event, signal);
|
|
2587
|
+
revision: (deps.read().at(-1)?.seq ?? -1) + 1,
|
|
2588
|
+
operationId: `first-delivery:${hash}`,
|
|
2589
|
+
requestHash: hash,
|
|
2590
|
+
data
|
|
2591
|
+
}, signal);
|
|
2592
|
+
}
|
|
2593
|
+
if (plans.length) {
|
|
2315
2594
|
projection = projectContext(deps.read());
|
|
2316
2595
|
request = await assembleProjected(projection.messages);
|
|
2317
2596
|
after = inspect(port, request);
|
|
2318
|
-
changed =
|
|
2597
|
+
changed = replacements.length > 0;
|
|
2319
2598
|
}
|
|
2320
2599
|
}
|
|
2321
2600
|
return {
|
|
@@ -2335,6 +2614,16 @@ function createContextCoordinator(_deps) {
|
|
|
2335
2614
|
active = {
|
|
2336
2615
|
operationId,
|
|
2337
2616
|
trigger: input.trigger,
|
|
2617
|
+
phase: "reduction",
|
|
2618
|
+
target: input.trigger === "manual" ? {
|
|
2619
|
+
kind: "maintenance",
|
|
2620
|
+
operationId
|
|
2621
|
+
} : {
|
|
2622
|
+
kind: "run",
|
|
2623
|
+
historyGeneration: deps.historyGeneration?.() ?? 0,
|
|
2624
|
+
turn: `turn:${deps.sessionId}:${deps.framework.history(deps.read()).findLast(({ event }) => event.kind === "trigger")?.seq ?? -1}`
|
|
2625
|
+
},
|
|
2626
|
+
monotonicStart: performance.now(),
|
|
2338
2627
|
controller,
|
|
2339
2628
|
startedAt: now(),
|
|
2340
2629
|
completedChunks: 0
|
|
@@ -2351,6 +2640,7 @@ function createContextCoordinator(_deps) {
|
|
|
2351
2640
|
let previewRecoveryUnavailable = false;
|
|
2352
2641
|
let summaryDiagnostics = {};
|
|
2353
2642
|
let summaryUsage;
|
|
2643
|
+
let summaryCallId;
|
|
2354
2644
|
let plan;
|
|
2355
2645
|
let campaign;
|
|
2356
2646
|
try {
|
|
@@ -2602,6 +2892,11 @@ function createContextCoordinator(_deps) {
|
|
|
2602
2892
|
events = [...deps.read()];
|
|
2603
2893
|
const baseRevision = projectContext(events).revision;
|
|
2604
2894
|
let summary;
|
|
2895
|
+
summaryCallId = randomUUID();
|
|
2896
|
+
if (active?.operationId === operationId) {
|
|
2897
|
+
active.phase = "summary";
|
|
2898
|
+
notify();
|
|
2899
|
+
}
|
|
2605
2900
|
try {
|
|
2606
2901
|
summary = await runContextSummary({
|
|
2607
2902
|
framework: deps.framework,
|
|
@@ -2609,7 +2904,8 @@ function createContextCoordinator(_deps) {
|
|
|
2609
2904
|
middleware: deps.middleware(),
|
|
2610
2905
|
request: {
|
|
2611
2906
|
...selectedRequest,
|
|
2612
|
-
sessionId: deps.sessionId
|
|
2907
|
+
sessionId: deps.sessionId,
|
|
2908
|
+
modelCallId: summaryCallId
|
|
2613
2909
|
},
|
|
2614
2910
|
signal: controller.signal
|
|
2615
2911
|
});
|
|
@@ -2655,6 +2951,7 @@ function createContextCoordinator(_deps) {
|
|
|
2655
2951
|
reason: diagnostic,
|
|
2656
2952
|
summaryModel: actualSummaryModel() ?? deps.model(),
|
|
2657
2953
|
usage: summaryUsage,
|
|
2954
|
+
modelCallId: summaryCallId,
|
|
2658
2955
|
...error instanceof ContextSummaryError ? error.diagnostics : {},
|
|
2659
2956
|
startedAt: attemptStartedAt
|
|
2660
2957
|
});
|
|
@@ -2701,6 +2998,7 @@ function createContextCoordinator(_deps) {
|
|
|
2701
2998
|
after,
|
|
2702
2999
|
reason: diagnostic,
|
|
2703
3000
|
usage: summaryUsage,
|
|
3001
|
+
modelCallId: summaryCallId,
|
|
2704
3002
|
...summary.diagnostics,
|
|
2705
3003
|
startedAt: attemptStartedAt
|
|
2706
3004
|
});
|
|
@@ -2735,6 +3033,7 @@ function createContextCoordinator(_deps) {
|
|
|
2735
3033
|
before,
|
|
2736
3034
|
after,
|
|
2737
3035
|
usage: summaryUsage,
|
|
3036
|
+
modelCallId: summaryCallId,
|
|
2738
3037
|
summaryModel: actualSummaryModel() ?? deps.model(),
|
|
2739
3038
|
...summary.diagnostics,
|
|
2740
3039
|
startedAt: attemptStartedAt
|
|
@@ -2788,6 +3087,7 @@ function createContextCoordinator(_deps) {
|
|
|
2788
3087
|
reason: "cancelled",
|
|
2789
3088
|
summaryModel: summaryUsage === void 0 ? void 0 : actualSummaryModel() ?? deps.model(),
|
|
2790
3089
|
usage: summaryUsage,
|
|
3090
|
+
modelCallId: summaryCallId,
|
|
2791
3091
|
startedAt
|
|
2792
3092
|
})
|
|
2793
3093
|
};
|
|
@@ -2823,25 +3123,11 @@ function createContextCoordinator(_deps) {
|
|
|
2823
3123
|
const meter = fragmentMeter(port, request(""), "tool-result");
|
|
2824
3124
|
const base = meter.baseline.inputTokens;
|
|
2825
3125
|
return (result) => {
|
|
2826
|
-
const
|
|
2827
|
-
const text = typeof result === "string" ? result : JSON.stringify(media.length && typeof result === "object" && result !== null ? {
|
|
3126
|
+
const text = typeof result === "string" ? result : JSON.stringify(typeof result === "object" && result !== null && "files" in result ? {
|
|
2828
3127
|
...result,
|
|
2829
3128
|
files: void 0
|
|
2830
3129
|
} : result);
|
|
2831
|
-
const
|
|
2832
|
-
const candidate = request(text);
|
|
2833
|
-
return {
|
|
2834
|
-
...candidate,
|
|
2835
|
-
messages: candidate.messages.map((message) => ({
|
|
2836
|
-
...message,
|
|
2837
|
-
content: [...message.content, ...media.map((file) => ({
|
|
2838
|
-
type: "file",
|
|
2839
|
-
file
|
|
2840
|
-
}))]
|
|
2841
|
-
}))
|
|
2842
|
-
};
|
|
2843
|
-
};
|
|
2844
|
-
const measured = (media.length ? inspect(port, withMedia()).inputTokens : meter.measure(text, () => request(text))) - base;
|
|
3130
|
+
const measured = meter.measure(text, () => request(text)) - base;
|
|
2845
3131
|
return measured > 0 ? measured : Buffer.byteLength(text);
|
|
2846
3132
|
};
|
|
2847
3133
|
};
|
|
@@ -2931,7 +3217,8 @@ function createContextCoordinator(_deps) {
|
|
|
2931
3217
|
},
|
|
2932
3218
|
status(normalTokens) {
|
|
2933
3219
|
const raw = deps.read();
|
|
2934
|
-
const events =
|
|
3220
|
+
const events = raw;
|
|
3221
|
+
const usage = usageAccumulator.read(raw);
|
|
2935
3222
|
const committedTokens = events.reduce((total, { seq, event }) => seq > (deps.usageStartSeq ?? -1) && event.kind === "message-appended" && event.usage ? total + event.usage.inputTokens + event.usage.outputTokens : total, 0);
|
|
2936
3223
|
const latestInput = events.findLast(({ seq, event }) => seq > (deps.usageStartSeq ?? -1) && event.kind === "message-appended" && event.usage)?.event;
|
|
2937
3224
|
const latestReported = latestInput?.kind === "message-appended" ? latestInput.usage?.inputTokens : void 0;
|
|
@@ -2940,15 +3227,24 @@ function createContextCoordinator(_deps) {
|
|
|
2940
3227
|
const projection = projectContext(events);
|
|
2941
3228
|
const lastResult = latestResult(events);
|
|
2942
3229
|
return {
|
|
3230
|
+
usage,
|
|
3231
|
+
...observation ? { observation: {
|
|
3232
|
+
identity: observation,
|
|
3233
|
+
source: reported === void 0 ? "estimated" : "reported",
|
|
3234
|
+
freshness: historical ? "historical" : "current"
|
|
3235
|
+
} } : {},
|
|
2943
3236
|
...measurementIdentity === void 0 ? {} : { measurementIdentity },
|
|
2944
3237
|
revision: projection.revision,
|
|
2945
3238
|
...measurement === void 0 ? {} : { measurement },
|
|
2946
|
-
...measurement === void 0 ? {} : { occupancy: committedReport ? occupancy(measurement, projection.revision) : occupancyOf(displayed, measurement.unmeasured ? "unmeasured" : "estimated", split) },
|
|
3239
|
+
...measurement === void 0 ? {} : { occupancy: committedReport ? occupancy(measurement, projection.revision, events) : occupancyOf(displayed, measurement.unmeasured ? "unmeasured" : "estimated", split) },
|
|
2947
3240
|
...anchor === void 0 || normalTokens === void 0 && anchor.reported !== latestReported ? {} : { actualInputTokens: anchor.reported },
|
|
2948
3241
|
auxiliaryTokens: auxiliary,
|
|
2949
3242
|
totalTokens: (normalTokens ?? committedTokens) + auxiliary,
|
|
2950
3243
|
...active === void 0 ? {} : { operation: {
|
|
2951
3244
|
operationId: active.operationId,
|
|
3245
|
+
phase: active.phase,
|
|
3246
|
+
target: active.target,
|
|
3247
|
+
elapsedMs: Math.max(0, Math.floor(performance.now() - active.monotonicStart)),
|
|
2952
3248
|
trigger: active.trigger,
|
|
2953
3249
|
startedAt: active.startedAt,
|
|
2954
3250
|
completedChunks: active.completedChunks
|
|
@@ -3015,27 +3311,35 @@ function createContextCoordinator(_deps) {
|
|
|
3015
3311
|
return Math.min(Math.min(8192, Math.max(0, Math.floor(measurement.inputBudget * TOOL_PREVIEW_POLICY.stepFraction) - 256)), Math.max(0, measurement.inputBudget - measurement.inputTokens - pendingTokens - 256));
|
|
3016
3312
|
},
|
|
3017
3313
|
toolOutputPolicy,
|
|
3018
|
-
observe(value, shown) {
|
|
3314
|
+
observe(identity, value, shown) {
|
|
3315
|
+
if (identity.sessionId !== deps.sessionId || identity.historyGeneration !== (deps.historyGeneration?.() ?? 0) || deps.measurementIdentity && identity.modelFingerprint !== deps.measurementIdentity() || observation && (identity.sourceSeq < observation.sourceSeq || identity.sourceSeq === observation.sourceSeq && (identity.modelCallId !== observation.modelCallId || reported !== void 0))) return;
|
|
3316
|
+
observation = { ...identity };
|
|
3317
|
+
historical = false;
|
|
3019
3318
|
measurement = value;
|
|
3020
3319
|
measurementIdentity = deps.measurementIdentity?.();
|
|
3021
3320
|
split = shown?.split;
|
|
3022
3321
|
displayed = shown?.displayTokens ?? value.inputTokens;
|
|
3023
3322
|
reported = void 0;
|
|
3024
|
-
|
|
3025
|
-
|
|
3323
|
+
const events = deps.read();
|
|
3324
|
+
if (deps.saved !== void 0) save(events, projectContext(events).revision);
|
|
3325
|
+
measurementEventCount = events.length;
|
|
3026
3326
|
diagnostic = value.inputBudget === void 0 ? "capacity_unknown" : void 0;
|
|
3027
3327
|
notify();
|
|
3028
3328
|
},
|
|
3029
|
-
observeReported(
|
|
3030
|
-
if (measurement === void 0) return;
|
|
3329
|
+
observeReported(identity, usage) {
|
|
3330
|
+
if (measurement === void 0 || usage.inputTokens <= 0 || !observation || identity.sessionId !== observation.sessionId || identity.historyGeneration !== observation.historyGeneration || identity.modelCallId !== observation.modelCallId || identity.modelFingerprint !== observation.modelFingerprint || identity.projectionRevision !== observation.projectionRevision || identity.sourceSeq !== observation.sourceSeq || identity.historyGeneration !== (deps.historyGeneration?.() ?? 0) || deps.measurementIdentity && identity.modelFingerprint !== deps.measurementIdentity()) return;
|
|
3331
|
+
const events = deps.read();
|
|
3332
|
+
const revision = projectContext(events).revision;
|
|
3333
|
+
const inputTokens = usage.inputTokens;
|
|
3031
3334
|
reported = inputTokens;
|
|
3032
3335
|
anchor = {
|
|
3336
|
+
viewIdentity: viewIdentity(events, revision),
|
|
3033
3337
|
reported: inputTokens,
|
|
3034
3338
|
estimate: displayed,
|
|
3035
3339
|
fingerprint: measurement.fingerprint,
|
|
3036
|
-
revision
|
|
3340
|
+
revision
|
|
3037
3341
|
};
|
|
3038
|
-
save();
|
|
3342
|
+
save(events, revision);
|
|
3039
3343
|
notify();
|
|
3040
3344
|
},
|
|
3041
3345
|
get activeOperation() {
|
|
@@ -3048,6 +3352,7 @@ function createContextCoordinator(_deps) {
|
|
|
3048
3352
|
}
|
|
3049
3353
|
//#endregion
|
|
3050
3354
|
//#region src/runtime/factory.ts
|
|
3355
|
+
/** Activated context maintenance and display policy over generic Agent session inputs. */
|
|
3051
3356
|
/** Owns persisted readings and stops admitting maintenance after withdrawal. */
|
|
3052
3357
|
function createContextRuntime(ctx, framework) {
|
|
3053
3358
|
const readings = createSessionContextRowsOn(ctx.storage.open());
|
|
@@ -3057,6 +3362,29 @@ function createContextRuntime(ctx, framework) {
|
|
|
3057
3362
|
performance: ctx.performance
|
|
3058
3363
|
});
|
|
3059
3364
|
const control = ctx.services.get("agent-context-control");
|
|
3365
|
+
const contextLimitFailure = () => ctx.models.failures.create({
|
|
3366
|
+
code: "context-limit-exceeded",
|
|
3367
|
+
stage: "request",
|
|
3368
|
+
category: "request-too-large",
|
|
3369
|
+
source: "host",
|
|
3370
|
+
retryable: false
|
|
3371
|
+
});
|
|
3372
|
+
const epoch = randomUUID();
|
|
3373
|
+
let sequence = 0;
|
|
3374
|
+
const ordered = (status, source, historical = false) => ({
|
|
3375
|
+
...status,
|
|
3376
|
+
...historical ? { operation: void 0 } : {},
|
|
3377
|
+
...historical && status.observation ? { observation: {
|
|
3378
|
+
...status.observation,
|
|
3379
|
+
freshness: "historical"
|
|
3380
|
+
} } : {},
|
|
3381
|
+
statusOrder: {
|
|
3382
|
+
epoch,
|
|
3383
|
+
sequence: ++sequence,
|
|
3384
|
+
sourceSeq: source.sourceSeq,
|
|
3385
|
+
historyGeneration: source.historyGeneration
|
|
3386
|
+
}
|
|
3387
|
+
});
|
|
3060
3388
|
const policies = /* @__PURE__ */ new Map();
|
|
3061
3389
|
const changed = ctx.client.registerFrame({
|
|
3062
3390
|
name: "statusChanged",
|
|
@@ -3089,7 +3417,7 @@ function createContextRuntime(ctx, framework) {
|
|
|
3089
3417
|
try {
|
|
3090
3418
|
const before = control.source(sessionId);
|
|
3091
3419
|
if (before.historyGeneration !== one.historyGeneration) return;
|
|
3092
|
-
const status = one.policy.status();
|
|
3420
|
+
const status = ordered(one.policy.status(), before);
|
|
3093
3421
|
if (status.measurementIdentity !== before.measurementIdentity) return;
|
|
3094
3422
|
const after = control.source(sessionId);
|
|
3095
3423
|
if (before.sourceSeq !== after.sourceSeq || before.historyGeneration !== after.historyGeneration) return;
|
|
@@ -3111,25 +3439,23 @@ function createContextRuntime(ctx, framework) {
|
|
|
3111
3439
|
assertRequest(inspection, request) {
|
|
3112
3440
|
const catalog = request?.sessionId ? policies.get(request.sessionId)?.policy.toolOutputPolicy()?.catalog : void 0;
|
|
3113
3441
|
if (catalog && request?.tools) {
|
|
3114
|
-
if (catalog.measure(request.tools) > catalog.tokens) throw
|
|
3442
|
+
if (catalog.measure(request.tools) > catalog.tokens) throw contextLimitFailure();
|
|
3115
3443
|
const dynamic = request.tools.filter((tool) => tool.catalogKind === "dynamic");
|
|
3116
|
-
if (dynamic.some((tool) => catalog.measure(tool) > catalog.definitionTokens)) throw
|
|
3117
|
-
if (catalog.measure(dynamic) > catalog.dynamicTokens) throw
|
|
3444
|
+
if (dynamic.some((tool) => catalog.measure(tool) > catalog.definitionTokens)) throw contextLimitFailure();
|
|
3445
|
+
if (catalog.measure(dynamic) > catalog.dynamicTokens) throw contextLimitFailure();
|
|
3118
3446
|
}
|
|
3119
3447
|
const budget = safeInputBudget(inspection);
|
|
3120
|
-
if (budget !== void 0 && inspection.inputTokens > budget) throw
|
|
3121
|
-
code: "context-limit-exceeded",
|
|
3122
|
-
stage: "request",
|
|
3123
|
-
category: "request-too-large",
|
|
3124
|
-
source: "host",
|
|
3125
|
-
retryable: false
|
|
3126
|
-
});
|
|
3448
|
+
if (budget !== void 0 && inspection.inputTokens > budget) throw contextLimitFailure();
|
|
3127
3449
|
},
|
|
3128
3450
|
assertSwitch(port, request, hasHistory) {
|
|
3129
3451
|
if (hasHistory && inspect(port, request).capacitySource === "assumed") throw new Error("capacity_unknown: configure the target context window before switching");
|
|
3130
3452
|
},
|
|
3131
3453
|
status(sessionId, maxBytes = 524288) {
|
|
3132
3454
|
ctx.signal.throwIfAborted();
|
|
3455
|
+
const bounded = (status) => {
|
|
3456
|
+
if (Buffer.byteLength(JSON.stringify(status)) > maxBytes) throw new Error("read-limit: status exceeds member body capacity");
|
|
3457
|
+
return status;
|
|
3458
|
+
};
|
|
3133
3459
|
const one = policies.get(sessionId);
|
|
3134
3460
|
const source = control.source(sessionId);
|
|
3135
3461
|
if (one?.status && one.sourceSeq === source.sourceSeq && one.status.measurementIdentity === source.measurementIdentity && one.historyGeneration === source.historyGeneration) {
|
|
@@ -3137,11 +3463,11 @@ function createContextRuntime(ctx, framework) {
|
|
|
3137
3463
|
return one.status;
|
|
3138
3464
|
}
|
|
3139
3465
|
const saved = snapshots.get(sessionId, maxBytes);
|
|
3140
|
-
if (saved?.sourceSeq === source.sourceSeq && saved.status.measurementIdentity === source.measurementIdentity && saved.historyGeneration === source.historyGeneration) return saved.status;
|
|
3466
|
+
if (saved?.sourceSeq === source.sourceSeq && saved.status.measurementIdentity === source.measurementIdentity && saved.historyGeneration === source.historyGeneration) return bounded(ordered(saved.status, source, true));
|
|
3141
3467
|
const facts = control.reading(sessionId);
|
|
3142
3468
|
const compatible = one?.status?.measurementIdentity === source.measurementIdentity && one.historyGeneration === source.historyGeneration ? one.status : saved?.status.measurementIdentity === source.measurementIdentity && saved.historyGeneration === source.historyGeneration ? saved.status : void 0;
|
|
3143
3469
|
const observed = [one?.historyGeneration === source.historyGeneration ? one.status : void 0, saved?.historyGeneration === source.historyGeneration ? saved.status : void 0].find((status) => status?.measurement && status.occupancy && status.occupancy.source !== "unmeasured");
|
|
3144
|
-
return {
|
|
3470
|
+
return bounded(ordered({
|
|
3145
3471
|
...compatible || !observed?.measurement || !observed.occupancy ? {} : { lastObservation: {
|
|
3146
3472
|
measurement: observed.measurement,
|
|
3147
3473
|
occupancy: observed.occupancy,
|
|
@@ -3150,8 +3476,15 @@ function createContextRuntime(ctx, framework) {
|
|
|
3150
3476
|
...compatible ?? {},
|
|
3151
3477
|
revision: facts.revision,
|
|
3152
3478
|
auxiliaryTokens: facts.auxiliaryTokens,
|
|
3153
|
-
totalTokens: facts.normalTokens + facts.auxiliaryTokens
|
|
3154
|
-
|
|
3479
|
+
totalTokens: facts.normalTokens + facts.auxiliaryTokens,
|
|
3480
|
+
usage: {
|
|
3481
|
+
...facts.usage ?? {
|
|
3482
|
+
inputTokens: 0,
|
|
3483
|
+
outputTokens: 0
|
|
3484
|
+
},
|
|
3485
|
+
totalTokens: (facts.usage?.inputTokens ?? 0) + (facts.usage?.outputTokens ?? 0)
|
|
3486
|
+
}
|
|
3487
|
+
}, source, true));
|
|
3155
3488
|
},
|
|
3156
3489
|
acceptsPreviewHint: (tokens) => Number.isInteger(tokens) && tokens >= 1 && tokens <= TOOL_PREVIEW_POLICY.maximumTokens,
|
|
3157
3490
|
create(session) {
|
|
@@ -3165,16 +3498,39 @@ function createContextRuntime(ctx, framework) {
|
|
|
3165
3498
|
return JSON.stringify([source.measurementIdentity, source.historyGeneration]);
|
|
3166
3499
|
},
|
|
3167
3500
|
measurementIdentity: () => control.source(session.sessionId).measurementIdentity,
|
|
3501
|
+
historyGeneration: () => control.source(session.sessionId).historyGeneration,
|
|
3168
3502
|
...session,
|
|
3169
3503
|
framework,
|
|
3170
3504
|
onStatusChanged() {
|
|
3171
3505
|
ctx.signal.throwIfAborted();
|
|
3172
3506
|
capture(session.sessionId);
|
|
3173
|
-
|
|
3174
|
-
|
|
3507
|
+
try {
|
|
3508
|
+
changed.emit(session.sessionId, {});
|
|
3509
|
+
session.onStatusChanged?.();
|
|
3510
|
+
} catch {
|
|
3511
|
+
ctx.log.emit({
|
|
3512
|
+
level: "error",
|
|
3513
|
+
event: "plugin.event",
|
|
3514
|
+
fields: { localCode: "CONTEXT_STATUS_PUBLISH_FAILED" }
|
|
3515
|
+
});
|
|
3516
|
+
}
|
|
3175
3517
|
},
|
|
3176
|
-
commit: (event, signal) => {
|
|
3518
|
+
commit: async (event, signal) => {
|
|
3177
3519
|
ctx.signal.throwIfAborted();
|
|
3520
|
+
if (event.kind === "owner-state") {
|
|
3521
|
+
const ownerState = ctx.services.get("owner-session-context");
|
|
3522
|
+
const source = control.source(session.sessionId);
|
|
3523
|
+
const previous = [...framework.history(session.read())].reverse().find(({ event: one }) => one.kind === "owner-state" && one.owner === event.owner && one.key === event.key);
|
|
3524
|
+
return {
|
|
3525
|
+
seq: (await ownerState.recordPrepared(session.sessionId, {
|
|
3526
|
+
key: event.key,
|
|
3527
|
+
expectedRevision: previous?.event.kind === "owner-state" ? previous.event.revision : null,
|
|
3528
|
+
operationId: event.operationId,
|
|
3529
|
+
data: event.data
|
|
3530
|
+
}, source.historyGeneration, signal ? AbortSignal.any([signal, ctx.signal]) : ctx.signal)).revision,
|
|
3531
|
+
revision: framework.project(session.read()).revision
|
|
3532
|
+
};
|
|
3533
|
+
}
|
|
3178
3534
|
return session.commit(event, signal ? AbortSignal.any([signal, ctx.signal]) : ctx.signal);
|
|
3179
3535
|
},
|
|
3180
3536
|
saved: {
|
|
@@ -3193,19 +3549,24 @@ function createContextRuntime(ctx, framework) {
|
|
|
3193
3549
|
policy,
|
|
3194
3550
|
historyGeneration: source.historyGeneration,
|
|
3195
3551
|
...saved?.sourceSeq === source.sourceSeq && saved.status.measurementIdentity === source.measurementIdentity && saved.historyGeneration === source.historyGeneration ? {
|
|
3196
|
-
status: saved.status,
|
|
3552
|
+
status: ordered(saved.status, source, true),
|
|
3197
3553
|
sourceSeq: source.sourceSeq
|
|
3198
3554
|
} : {}
|
|
3199
3555
|
});
|
|
3200
3556
|
changed.emit(session.sessionId, {});
|
|
3201
3557
|
return {
|
|
3202
3558
|
...policy,
|
|
3203
|
-
prepare(exec, assemble) {
|
|
3559
|
+
async prepare(exec, assemble) {
|
|
3204
3560
|
ctx.signal.throwIfAborted();
|
|
3205
|
-
|
|
3206
|
-
|
|
3207
|
-
|
|
3208
|
-
|
|
3561
|
+
try {
|
|
3562
|
+
return await policy.prepare({
|
|
3563
|
+
...exec,
|
|
3564
|
+
signal: AbortSignal.any([exec.signal, ctx.signal])
|
|
3565
|
+
}, assemble);
|
|
3566
|
+
} catch (error) {
|
|
3567
|
+
if (!exec.signal.aborted && error instanceof Error && /^(protected_context_exceeds_budget|fixed_context_too_large|context_still_exceeds_budget|catalog_too_large|tool_schema_too_large|summary_)/.test(error.message)) throw contextLimitFailure();
|
|
3568
|
+
throw error;
|
|
3569
|
+
}
|
|
3209
3570
|
},
|
|
3210
3571
|
compact(assemble, signal) {
|
|
3211
3572
|
ctx.signal.throwIfAborted();
|
|
@@ -3224,7 +3585,7 @@ function createContextRuntime(ctx, framework) {
|
|
|
3224
3585
|
const started = ctx.performance?.now();
|
|
3225
3586
|
let outcome = "ok";
|
|
3226
3587
|
try {
|
|
3227
|
-
const displayTokens =
|
|
3588
|
+
const displayTokens = inputTokens;
|
|
3228
3589
|
ctx.signal.throwIfAborted();
|
|
3229
3590
|
return {
|
|
3230
3591
|
split: await rawBreakdown(request, inputTokens, deps, { signal: AbortSignal.any([signal, ctx.signal]) }),
|
|
@@ -3539,6 +3900,7 @@ const contextPlugin = {
|
|
|
3539
3900
|
"session-context-history",
|
|
3540
3901
|
"session-notes",
|
|
3541
3902
|
"agent-context-control",
|
|
3903
|
+
"owner-session-context",
|
|
3542
3904
|
"session-context"
|
|
3543
3905
|
],
|
|
3544
3906
|
provides: [
|