@eum-agent/context-management 1.0.0 → 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.
Files changed (3) hide show
  1. package/dist/index.js +2084 -231
  2. package/package.json +5 -5
  3. package/ui/ui.js +295 -226
package/dist/index.js CHANGED
@@ -1,54 +1,901 @@
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
+ import { setImmediate } from "node:timers/promises";
6
+ //#region src/agent-configuration.ts
7
+ /** Discovery entrances are always available while this owner's exposure policy is active. */
8
+ const ESSENTIAL_TOOLS = ["tool_search", "tool_call"];
9
+ /** Sparse explicit overrides; removing a key restores the developer default. */
10
+ const ToolPreloadConfiguration = z.strictObject({ toolPreload: z.record(z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/).refine((name) => !ESSENTIAL_TOOLS.some((essential) => essential === name), "Discovery entrances cannot be overridden"), z.boolean()).default({}) }).default({ toolPreload: {} });
11
+ /** Registers transactional preferences and reads the executing Agent's current overrides. */
12
+ function registerToolPreload(ctx) {
13
+ const store = ctx.services.get("agent-configuration-store");
14
+ const read = (agentId) => ToolPreloadConfiguration.parse(store.read(ctx.pluginName, agentId));
15
+ ctx.agentConfiguration.register({
16
+ schema: ToolPreloadConfiguration,
17
+ read,
18
+ prepare(agentId, value) {
19
+ return {
20
+ apply: () => store.write(ctx.pluginName, agentId, value),
21
+ abort() {},
22
+ settle() {}
23
+ };
24
+ }
25
+ });
26
+ const snapshots = /* @__PURE__ */ new WeakMap();
27
+ ctx.tools.exposure({
28
+ essential: ESSENTIAL_TOOLS,
29
+ preload(tool, view) {
30
+ let value = snapshots.get(view);
31
+ if (!value) {
32
+ value = read(view.agentId);
33
+ snapshots.set(view, value);
34
+ }
35
+ return Object.hasOwn(value.toolPreload, tool.name) ? value.toolPreload[tool.name] : tool.preloadDefault;
36
+ }
37
+ });
38
+ }
39
+ //#endregion
40
+ //#region src/tools/search.ts
41
+ /** Bounded disclosure of full definitions from the authenticated host catalogue. */
42
+ /** Generic discovery input; continuation preserves the query and result count. */
43
+ const ToolSearchInput = z.strictObject({
44
+ query: z.string().trim().min(1).refine((value) => [...value].length <= 512, "Query exceeds 512 Unicode code points").meta({ maxLength: 512 }).describe("Tool name or task keywords, 1–512 Unicode code points after trimming. Prefer the language of tool metadata, usually English; retry synonyms after no matches."),
45
+ limit: z.number().int().min(1).max(10).default(5).describe("Maximum definitions per page; default 5, hard maximum 10."),
46
+ outputTokens: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).default(4096).describe("Desired complete result tokens; default 4096. The host may allocate fewer."),
47
+ cursor: z.string().min(1).refine((value) => Buffer.byteLength(value) <= 4096, "Cursor exceeds 4096 bytes").meta({ maxLength: 4096 }).optional().describe("Opaque continuation, at most 4096 UTF-8 bytes; copy next.arguments unchanged.")
48
+ });
49
+ const definition = z.strictObject({
50
+ name: z.string(),
51
+ description: z.string(),
52
+ inputSchema: z.unknown(),
53
+ guidance: z.array(z.string()).optional()
54
+ });
55
+ /** Complete pages and recoverable discovery refusals, never partial schemas. */
56
+ const ToolSearchOutput = z.union([z.strictObject({
57
+ ok: z.literal(true),
58
+ items: z.array(definition).max(10),
59
+ complete: z.boolean(),
60
+ next: z.strictObject({
61
+ tool: z.literal("tool_search"),
62
+ arguments: ToolSearchInput
63
+ }).nullable()
64
+ }), z.strictObject({
65
+ ok: z.literal(false),
66
+ error: z.strictObject({
67
+ code: z.string(),
68
+ message: z.string(),
69
+ retryable: z.boolean()
70
+ }),
71
+ next: z.strictObject({
72
+ tool: z.literal("tool_search"),
73
+ arguments: ToolSearchInput
74
+ }).nullable(),
75
+ execution: z.strictObject({ state: z.literal("not-started") })
76
+ })]);
77
+ function words(text) {
78
+ return text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
79
+ }
80
+ function metadata(schema) {
81
+ const seen = /* @__PURE__ */ new WeakSet(), pending = [schema], result = [];
82
+ let visited = 0;
83
+ while (pending.length && visited++ < 32768) {
84
+ const node = pending.pop();
85
+ if (!node || typeof node !== "object" || seen.has(node)) continue;
86
+ seen.add(node);
87
+ for (const [key, value] of Object.entries(node)) if ((key === "description" || key === "title") && typeof value === "string") result.push(value);
88
+ else if (key === "properties" && value && typeof value === "object") for (const [name, child] of Object.entries(value)) {
89
+ result.push(name);
90
+ pending.push(child);
91
+ }
92
+ else if (value && typeof value === "object") pending.push(value);
93
+ }
94
+ return result;
95
+ }
96
+ /** Creates owner-bound keyword search with shared accounting and scope-bound exact-page cursors. */
97
+ function toolSearch(ctx) {
98
+ const resources = ctx.services.get("query-resources");
99
+ const pages = /* @__PURE__ */ new Map(), indexes = /* @__PURE__ */ new Map();
100
+ const drop = (cursor) => {
101
+ const page = pages.get(cursor);
102
+ if (!page) return;
103
+ pages.delete(cursor);
104
+ page.root.ids.delete(cursor);
105
+ page.root.bytes -= page.bytes;
106
+ if (page.root.ids.size) page.root.lease.reduce({
107
+ bytes: page.bytes,
108
+ scratchBytes: 0
109
+ });
110
+ else page.root.lease.close("completed");
111
+ };
112
+ const dropRoot = (root) => {
113
+ for (const id of root.ids) pages.delete(id);
114
+ root.ids.clear();
115
+ root.bytes = 0;
116
+ root.lease.close("completed");
117
+ };
118
+ const dropIndex = (key) => {
119
+ const index = indexes.get(key);
120
+ if (index) {
121
+ indexes.delete(key);
122
+ index.lease.close("completed");
123
+ }
124
+ };
125
+ const sweep = () => {
126
+ const now = performance.now();
127
+ for (const [id, page] of pages) if (page.root.lease.signal.aborted || now - page.touched > 6e5 || now - page.created > 36e5) dropRoot(page.root);
128
+ for (const [key, index] of indexes) if (index.lease.signal.aborted || now - index.used > 6e5) dropIndex(key);
129
+ };
130
+ const timer = setInterval(sweep, 6e4);
131
+ timer.unref();
132
+ ctx.onDispose(() => {
133
+ clearInterval(timer);
134
+ for (const id of [...pages.keys()]) drop(id);
135
+ for (const key of [...indexes.keys()]) dropIndex(key);
136
+ });
137
+ const failure = (call, code, message, next = null) => {
138
+ const result = () => ({
139
+ content: JSON.stringify({
140
+ ok: false,
141
+ error: {
142
+ code,
143
+ message,
144
+ retryable: next !== null
145
+ },
146
+ next,
147
+ execution: { state: "not-started" }
148
+ }),
149
+ isError: true
150
+ });
151
+ while (message.length && call.output.measure(result()) > call.output.outputTokens) message = message.slice(0, Math.floor(message.length / 2));
152
+ if (call.output.measure(result()) > call.output.outputTokens) next = null;
153
+ return result();
154
+ };
155
+ const ranked = async (tools, query, fingerprint, call) => {
156
+ const key = JSON.stringify([
157
+ call.sessionId,
158
+ call.historyGeneration,
159
+ fingerprint
160
+ ]);
161
+ let index = indexes.get(key);
162
+ if (!index) {
163
+ while (indexes.size >= 8) dropIndex(indexes.keys().next().value);
164
+ const bytes = 2048 + Buffer.byteLength(JSON.stringify(tools)) * 2;
165
+ const lease = await resources.reserve(call, {
166
+ bytes,
167
+ scratchBytes: 0,
168
+ cleanup: async () => {
169
+ indexes.delete(key);
170
+ return { status: "complete" };
171
+ }
172
+ });
173
+ try {
174
+ index = {
175
+ lease,
176
+ used: performance.now(),
177
+ docs: tools.map((tool) => ({
178
+ name: tool.name,
179
+ names: words(tool.name),
180
+ terms: new Set(words([tool.description, ...metadata(tool.inputSchema)].join(" ")))
181
+ }))
182
+ };
183
+ indexes.set(key, index);
184
+ lease.retain({
185
+ reason: "catalog-index",
186
+ idleMs: 6e5,
187
+ maxAgeMs: 36e5
188
+ });
189
+ } catch (error) {
190
+ lease.close("failed");
191
+ throw error;
192
+ }
193
+ }
194
+ index.used = performance.now();
195
+ const needle = query.toLowerCase(), terms = words(query), byName = new Map(tools.map((tool) => [tool.name, tool]));
196
+ return index.docs.map((doc) => {
197
+ let score = doc.name.toLowerCase() === needle ? 1e6 : doc.name.toLowerCase().startsWith(needle) ? 1e5 : 0;
198
+ for (const term of terms) score += doc.names.includes(term) ? 1e3 : doc.terms.has(term) ? 10 : 0;
199
+ return {
200
+ tool: byName.get(doc.name),
201
+ score
202
+ };
203
+ }).filter((item) => item.score > 0).sort((a, b) => b.score - a.score || Number(a.tool.preload) - Number(b.tool.preload) || (a.tool.name < b.tool.name ? -1 : a.tool.name > b.tool.name ? 1 : 0)).map((item) => item.tool);
204
+ };
205
+ return {
206
+ name: "tool_search",
207
+ preload: true,
208
+ description: "Find available tools by name, task keywords, descriptions and parameter metadata. Returns complete input schemas as data for tool_call. Use English metadata keywords for Chinese tasks; if no matches, retry shorter names or synonyms. Follow next.arguments for more definitions. Search grants no permission and never changes the preloaded tool list.",
209
+ inputSchema: ToolSearchInput,
210
+ outputSchema: ToolSearchOutput,
211
+ deliveryKind: "exact-page",
212
+ async execute(input, call) {
213
+ call.signal.throwIfAborted();
214
+ sweep();
215
+ const snapshot = ctx.tools.catalog.snapshot(call), saved = input.cursor ? pages.get(input.cursor) : void 0;
216
+ const restart = {
217
+ tool: "tool_search",
218
+ arguments: {
219
+ query: input.query,
220
+ limit: input.limit,
221
+ outputTokens: input.outputTokens
222
+ }
223
+ };
224
+ if (input.cursor && (!saved || saved.session !== call.sessionId || saved.address !== JSON.stringify(call.address) || saved.generation !== call.historyGeneration || saved.fingerprint !== snapshot.fingerprint)) return failure(call, "cursor_expired", "Directory or scope changed; restart the search.", restart);
225
+ if (saved && (saved.query !== input.query || saved.limit !== input.limit)) return failure(call, "query_changed", "Preserve query and limit.", {
226
+ tool: "tool_search",
227
+ arguments: {
228
+ query: saved.query,
229
+ limit: saved.limit,
230
+ outputTokens: input.outputTokens
231
+ }
232
+ });
233
+ if (saved?.result) {
234
+ const required = call.output.measure(saved.result);
235
+ if (required > call.output.outputTokens) return failure(call, "definition_too_large", "The saved exact page does not fit.", required <= call.output.maximumTokens ? {
236
+ tool: "tool_search",
237
+ arguments: {
238
+ ...input,
239
+ outputTokens: required
240
+ }
241
+ } : null);
242
+ saved.touched = performance.now();
243
+ call.output.acceptExact(saved.result);
244
+ return saved.result;
245
+ }
246
+ let remaining;
247
+ try {
248
+ remaining = (await ranked(snapshot.tools, input.query, snapshot.fingerprint, call)).slice(saved?.offset ?? 0);
249
+ } catch (error) {
250
+ if (resources.isAdmissionFailure(error)) throw error;
251
+ return failure(call, "query_limit_exceeded", "Shared query capacity unavailable; release older queries.");
252
+ }
253
+ const cursor = randomUUID();
254
+ const build = (count) => ({ content: JSON.stringify({
255
+ ok: true,
256
+ items: remaining.slice(0, count).map((tool) => ({
257
+ name: tool.name,
258
+ description: tool.description,
259
+ inputSchema: tool.inputSchema,
260
+ ...tool.guidance?.length ? { guidance: tool.guidance } : {}
261
+ })),
262
+ complete: count === remaining.length,
263
+ next: count === remaining.length ? null : {
264
+ tool: "tool_search",
265
+ arguments: {
266
+ query: input.query,
267
+ limit: input.limit,
268
+ cursor,
269
+ outputTokens: input.outputTokens
270
+ }
271
+ }
272
+ }) });
273
+ let count = Math.min(input.limit, remaining.length), result = build(count);
274
+ let measured = call.output.measure(result);
275
+ if (count > 0 && measured > call.output.outputTokens) {
276
+ let low = 1;
277
+ let high = count - 1;
278
+ count = 0;
279
+ while (low + 4 <= high) {
280
+ await setImmediate();
281
+ ctx.signal.throwIfAborted();
282
+ call.signal.throwIfAborted();
283
+ const candidateCount = Math.floor((low + high) / 2);
284
+ const candidate = build(candidateCount);
285
+ const cost = call.output.measure(candidate);
286
+ if (cost <= call.output.outputTokens) {
287
+ count = candidateCount;
288
+ result = candidate;
289
+ measured = cost;
290
+ low = candidateCount + 1;
291
+ } else high = candidateCount - 1;
292
+ }
293
+ for (let candidateCount = high; candidateCount >= low; candidateCount -= 1) {
294
+ await setImmediate();
295
+ ctx.signal.throwIfAborted();
296
+ call.signal.throwIfAborted();
297
+ const candidate = build(candidateCount);
298
+ const cost = call.output.measure(candidate);
299
+ if (cost <= call.output.outputTokens) {
300
+ count = candidateCount;
301
+ result = candidate;
302
+ measured = cost;
303
+ break;
304
+ }
305
+ }
306
+ }
307
+ if (count === 0 && remaining.length > 0 || measured > call.output.outputTokens) {
308
+ const required = call.output.measure(build(Math.min(1, remaining.length)));
309
+ return failure(call, "definition_too_large", "A complete definition does not fit.", required <= call.output.maximumTokens ? {
310
+ tool: "tool_search",
311
+ arguments: {
312
+ ...input,
313
+ outputTokens: required
314
+ }
315
+ } : null);
316
+ }
317
+ let added = false;
318
+ try {
319
+ if (count < remaining.length) {
320
+ while (pages.size >= 128) dropRoot(pages.values().next().value.root);
321
+ const bytes = 2048 + JSON.stringify(input).length * 2;
322
+ const root = saved?.root ?? {
323
+ lease: await resources.reserve(call, {
324
+ bytes,
325
+ scratchBytes: 0,
326
+ cleanup: async () => {
327
+ for (const id of root.ids) pages.delete(id);
328
+ root.ids.clear();
329
+ root.bytes = 0;
330
+ return { status: "complete" };
331
+ }
332
+ }),
333
+ ids: /* @__PURE__ */ new Set(),
334
+ bytes: 0
335
+ };
336
+ if (saved) await root.lease.grow(call, {
337
+ bytes,
338
+ scratchBytes: 0
339
+ });
340
+ root.bytes += bytes;
341
+ root.ids.add(cursor);
342
+ pages.set(cursor, {
343
+ query: input.query,
344
+ limit: input.limit,
345
+ session: call.sessionId,
346
+ address: JSON.stringify(call.address),
347
+ generation: call.historyGeneration,
348
+ fingerprint: snapshot.fingerprint,
349
+ offset: (saved?.offset ?? 0) + count,
350
+ root,
351
+ created: saved?.created ?? performance.now(),
352
+ touched: performance.now(),
353
+ bytes
354
+ });
355
+ added = true;
356
+ if (!saved) root.lease.retain({
357
+ reason: "public-cursor",
358
+ idleMs: 6e5,
359
+ maxAgeMs: 36e5
360
+ });
361
+ }
362
+ if (saved) {
363
+ const bytes = Buffer.byteLength(result.content) * 2;
364
+ await saved.root.lease.grow(call, {
365
+ bytes,
366
+ scratchBytes: 0
367
+ });
368
+ saved.root.bytes += bytes;
369
+ saved.bytes += bytes;
370
+ saved.result = result;
371
+ saved.touched = performance.now();
372
+ }
373
+ call.output.acceptExact(result);
374
+ } catch (error) {
375
+ if (resources.isAdmissionFailure(error)) throw error;
376
+ if (added) drop(cursor);
377
+ return failure(call, "query_limit_exceeded", "Shared query capacity unavailable; release older queries.");
378
+ }
379
+ return result;
380
+ }
381
+ };
382
+ }
383
+ //#endregion
384
+ //#region src/tools/call.ts
385
+ /** The target's own parameters, including output budgets, belong inside arguments. */
386
+ const ToolCallInput = z.strictObject({
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.unknown()).pipe(z.record(z.string(), z.json())).describe("Target input object matching its complete schema. Put target outputTokens and continuation fields here.")
389
+ });
390
+ /** Declares the generic route without executing or wrapping a target result. */
391
+ function toolCall() {
392
+ return {
393
+ name: "tool_call",
394
+ preload: true,
395
+ description: "Call an available tool by exact name and arguments matching its schema from tool_search. Search is optional when the name and schema are already known. Target permissions and approvals still apply. Returns the target result directly; never call tool_search or another dispatch route through this tool.",
396
+ inputSchema: ToolCallInput,
397
+ resolveCall: (input) => ({
398
+ name: input.name,
399
+ input: input.arguments
400
+ })
401
+ };
402
+ }
403
+ //#endregion
5
404
  //#region src/context/index.ts
6
- /** Discovers original parts only within the executing session. */
7
- const ContextSearchInput = z.strictObject({
8
- query: z.string().min(1).max(512).refine((value) => [...value].length <= 256).optional(),
9
- after: z.string().min(1).max(4096).optional(),
10
- around: z.string().min(1).max(512).optional(),
11
- limit: z.number().int().min(1).max(20).optional()
405
+ /** Current-session original history is delivered through bounded exact pages. */
406
+ const outputTokens = z.number().int().positive().optional().describe("Desired output tokens; the host may allocate less.");
407
+ const cursor = z.string().min(1).max(512).regex(/^[\x21-\x7e]+$/).describe("Opaque cursor copied unchanged from next.arguments.");
408
+ const searchInitial = z.strictObject({
409
+ query: z.string().min(1).max(512).refine((value) => [...value].length <= 256).meta({ maxLength: 256 }).optional().describe("Literal substring, at most 256 Unicode code points; omit to browse."),
410
+ around: z.string().min(1).max(512).optional().describe("Reference from this session whose neighboring parts should be shown."),
411
+ limit: z.number().int().min(1).max(20).default(10).describe("Maximum history entries; default 10, hard maximum 20."),
412
+ outputTokens
413
+ });
414
+ /** Search initialization and continuation are mutually exclusive. */
415
+ const ContextSearchInput = z.union([searchInitial, z.strictObject({
416
+ cursor,
417
+ outputTokens
418
+ })]);
419
+ const sourcePage = z.strictObject({
420
+ ref: z.string().min(1).max(512).describe("Source reference returned by context_search or a retained preview."),
421
+ offset: z.number().int().nonnegative().optional().describe("Zero-based Unicode code-point offset; default zero."),
422
+ limit: z.number().int().min(1).max(4096).default(2048).describe("Desired Unicode code points; default 2048, hard maximum 4096. Delivery may be smaller.")
12
423
  });
13
- /** Reads a Unicode-code-point page from an opaque current-session reference. */
14
- const ContextRestoreInput = z.strictObject({
424
+ const restoreInitial = z.strictObject({
425
+ pages: z.array(sourcePage).min(1).max(64).describe("Original sources in member order; all members share one call allowance."),
426
+ outputTokens
427
+ });
428
+ /** Bounded collection query; physical byte ceilings are host policy rather than model arguments. */
429
+ const ContextRestoreInput = z.union([restoreInitial, z.strictObject({
430
+ cursor,
431
+ outputTokens
432
+ })]);
433
+ const sourceMetadata = {
15
434
  ref: z.string().min(1).max(512),
16
- offset: z.number().int().nonnegative().optional(),
17
- limit: z.number().int().min(1).max(4096).optional()
435
+ seq: z.number().int().nonnegative(),
436
+ part: z.number().int().nonnegative(),
437
+ role: z.enum(["user", "assistant"]),
438
+ kind: z.enum([
439
+ "text",
440
+ "tool-use",
441
+ "tool-result",
442
+ "file"
443
+ ]),
444
+ source: z.unknown().optional(),
445
+ toolCallId: z.string().optional(),
446
+ toolName: z.string().optional()
447
+ };
448
+ const entry = z.strictObject({
449
+ ...sourceMetadata,
450
+ preview: z.string(),
451
+ attachedFiles: z.array(z.strictObject({
452
+ name: z.string(),
453
+ mediaType: z.string()
454
+ })).optional()
455
+ });
456
+ const restored = z.strictObject({
457
+ ...sourceMetadata,
458
+ ok: z.literal(true),
459
+ historical: z.literal(true),
460
+ text: z.string(),
461
+ encoding: z.enum(["text", "json"]),
462
+ offset: z.number().int().nonnegative(),
463
+ end: z.number().int().nonnegative(),
464
+ total: z.number().int().nonnegative(),
465
+ nextOffset: z.number().int().nonnegative().optional(),
466
+ truncatedBeforePersistence: z.union([z.boolean(), z.literal("unknown")])
18
467
  });
19
- /** Offers the two independently configurable tools backed by host-owned history. */
468
+ const failure = z.strictObject({
469
+ ok: z.literal(false),
470
+ error: z.strictObject({
471
+ code: z.string(),
472
+ message: z.string(),
473
+ retryable: z.boolean()
474
+ }),
475
+ next: z.union([z.null(), z.strictObject({
476
+ tool: z.enum(["context_search", "context_restore"]),
477
+ arguments: z.record(z.string(), z.unknown())
478
+ })])
479
+ });
480
+ const retainedPreview = z.strictObject({
481
+ ok: z.literal(true),
482
+ complete: z.literal(false),
483
+ preview: z.string(),
484
+ source: z.strictObject({
485
+ ref: z.string(),
486
+ sourceComplete: z.boolean(),
487
+ recoverable: z.boolean()
488
+ }),
489
+ next: z.strictObject({
490
+ tool: z.literal("context_restore"),
491
+ arguments: z.strictObject({ pages: z.array(z.strictObject({ ref: z.string() })) })
492
+ })
493
+ });
494
+ const restoreMember = z.union([z.strictObject({
495
+ index: z.number().int().nonnegative(),
496
+ ref: z.string(),
497
+ ok: z.literal(true),
498
+ value: restored
499
+ }), z.strictObject({
500
+ index: z.number().int().nonnegative(),
501
+ ref: z.string(),
502
+ ok: z.literal(false),
503
+ error: z.strictObject({
504
+ code: z.string(),
505
+ message: z.string()
506
+ })
507
+ })]);
508
+ const page = (tool, item) => z.strictObject({
509
+ ok: z.literal(true),
510
+ complete: z.boolean(),
511
+ items: z.array(item),
512
+ next: z.strictObject({
513
+ tool: z.literal(tool),
514
+ arguments: z.strictObject({
515
+ cursor,
516
+ outputTokens
517
+ })
518
+ }).nullable(),
519
+ effective: z.strictObject({ outputTokens: z.number().int().nonnegative() })
520
+ });
521
+ /** Original discovery pages, standard refusals, and retained historical projections. */
522
+ const ContextSearchOutput = z.union([
523
+ page("context_search", entry),
524
+ failure,
525
+ retainedPreview
526
+ ]);
527
+ /** Exact source slices, per-member failures, and retained historical projections. */
528
+ const ContextRestoreOutput = z.union([
529
+ page("context_restore", restoreMember),
530
+ failure,
531
+ retainedPreview
532
+ ]);
533
+ /** Offers independently configurable discovery and restoration with owner-local opaque cursors. */
20
534
  function registerContextTools(ctx, register) {
21
535
  const history = ctx.services.get("session-context-history");
536
+ const resources = ctx.services.get("query-resources");
537
+ const states = /* @__PURE__ */ new Map();
538
+ const monotonic = () => performance.now();
539
+ const discard = (id) => {
540
+ const state = states.get(id);
541
+ if (!state) return;
542
+ states.delete(id);
543
+ state.root.ids.delete(id);
544
+ state.root.bytes -= state.bytes;
545
+ state.result = void 0;
546
+ if (state.root.ids.size) state.root.lease.reduce({
547
+ bytes: state.bytes,
548
+ scratchBytes: 0
549
+ });
550
+ else state.root.lease.close("completed");
551
+ };
552
+ const discardRoot = (root) => {
553
+ for (const id of [...root.ids]) discard(id);
554
+ };
555
+ const sweep = () => {
556
+ const now = monotonic();
557
+ for (const [id, state] of states) if (now - state.touched > 6e5 || now - state.created > 36e5) discard(id);
558
+ };
559
+ const timer = setInterval(sweep, 6e4);
560
+ timer.unref();
561
+ ctx.signal.addEventListener("abort", () => {
562
+ clearInterval(timer);
563
+ for (const id of [...states.keys()]) discard(id);
564
+ }, { once: true });
565
+ const refusal = (call, code, message, next = null) => {
566
+ const points = [];
567
+ for (const point of message) {
568
+ if (points.length === 256) break;
569
+ points.push(point);
570
+ }
571
+ let text = points.join("");
572
+ const candidate = () => ({
573
+ content: JSON.stringify({
574
+ ok: false,
575
+ error: {
576
+ code,
577
+ message: text,
578
+ retryable: next !== null
579
+ },
580
+ next
581
+ }),
582
+ isError: true
583
+ });
584
+ if (next !== null && call.output.measure(candidate()) > call.output.outputTokens) next = null;
585
+ while (text && call.output.measure(candidate()) > call.output.outputTokens) {
586
+ points.length = Math.floor(points.length / 2);
587
+ text = points.join("");
588
+ }
589
+ return candidate();
590
+ };
591
+ const nextState = async (call, tool, initial, position, created = monotonic(), parent) => {
592
+ sweep();
593
+ while (states.size >= 512) {
594
+ let oldest, at = Infinity;
595
+ for (const [key, value] of states) if (value.touched < at) {
596
+ oldest = key;
597
+ at = value.touched;
598
+ }
599
+ if (oldest === void 0) break;
600
+ discard(oldest);
601
+ }
602
+ const bytes = 256 + JSON.stringify({
603
+ initial,
604
+ position,
605
+ address: call.address
606
+ }).length * 2;
607
+ const root = parent ?? {
608
+ lease: await resources.reserve(call, {
609
+ bytes,
610
+ scratchBytes: 0,
611
+ cleanup: async () => {
612
+ if (root) {
613
+ for (const key of root.ids) {
614
+ const state = states.get(key);
615
+ if (state) state.result = void 0;
616
+ states.delete(key);
617
+ }
618
+ root.ids.clear();
619
+ root.bytes = 0;
620
+ }
621
+ return { status: "complete" };
622
+ }
623
+ }),
624
+ ids: /* @__PURE__ */ new Set(),
625
+ bytes: 0
626
+ };
627
+ if (root.lease.signal.aborted) {
628
+ if (!parent) root.lease.close("cancelled");
629
+ throw new Error("History query was cancelled.");
630
+ }
631
+ if (parent) await root.lease.grow(call, {
632
+ bytes,
633
+ scratchBytes: 0
634
+ });
635
+ root.bytes += bytes;
636
+ const id = randomUUID();
637
+ root.ids.add(id);
638
+ states.set(id, {
639
+ root,
640
+ bytes,
641
+ session: call.sessionId,
642
+ address: JSON.stringify(call.address),
643
+ generation: call.historyGeneration,
644
+ created,
645
+ touched: monotonic(),
646
+ tool,
647
+ initial,
648
+ position
649
+ });
650
+ if (!parent) root.lease.retain({
651
+ reason: "public-cursor",
652
+ idleMs: 6e5,
653
+ maxAgeMs: 36e5
654
+ });
655
+ return id;
656
+ };
657
+ const select = async (call, tool, input) => {
658
+ if (typeof input.cursor !== "string") return nextState(call, tool, input, {});
659
+ return input.cursor;
660
+ };
661
+ const validated = (call, id, tool) => {
662
+ const state = states.get(id);
663
+ if (state && state.session === call.sessionId && state.address === JSON.stringify(call.address) && state.generation !== call.historyGeneration) discardRoot(state.root);
664
+ if (!state || state.session !== call.sessionId || state.address !== JSON.stringify(call.address) || state.generation !== call.historyGeneration || state.tool !== tool) return refusal(call, "cursor_invalid", "Cursor is unavailable for this session and history.");
665
+ if (monotonic() - state.touched > 6e5 || monotonic() - state.created > 36e5) {
666
+ discardRoot(state.root);
667
+ return refusal(call, "cursor_expired", "Start this expired history query again.", {
668
+ tool,
669
+ arguments: state.initial
670
+ });
671
+ }
672
+ state.touched = monotonic();
673
+ return state;
674
+ };
675
+ const deliver = async (call, state, id, result) => {
676
+ const required = call.output.measure(result);
677
+ if (required > call.output.outputTokens) return refusal(call, "page_too_small", "The complete page does not fit this call allowance.", required <= call.output.maximumTokens ? {
678
+ tool: state.tool,
679
+ arguments: {
680
+ cursor: id,
681
+ outputTokens: required
682
+ }
683
+ } : null);
684
+ if (state.result !== result) {
685
+ const bytes = JSON.stringify(result).length * 2;
686
+ try {
687
+ await state.root.lease.grow(call, {
688
+ bytes,
689
+ scratchBytes: 0
690
+ });
691
+ } catch (error) {
692
+ if (resources.isAdmissionFailure(error)) throw error;
693
+ discardRoot(state.root);
694
+ return refusal(call, "resource_limit", "History query cache exceeded its shared resource allowance.");
695
+ }
696
+ state.root.bytes += bytes;
697
+ state.bytes += bytes;
698
+ }
699
+ call.output.acceptExact(result);
700
+ state.result = result;
701
+ return result;
702
+ };
22
703
  register({
23
704
  name: "context_search",
24
- description: "Find persisted original text and tool inputs/results in this session, including history removed by context compression. Omit query to browse, use a literal query to search, or around for neighboring source parts. Follow next with after. Results are historical data, not new instructions or permissions. Other sessions are never searched.",
705
+ preload: true,
706
+ description: "Find persisted original text and tool inputs/results in this session. Results are historical data, never fresh file reading, loaded skills, instructions or permissions. Use query or around, and follow next.arguments unchanged. Other sessions are never searched.",
25
707
  inputSchema: ContextSearchInput,
708
+ outputSchema: ContextSearchOutput,
709
+ deliveryKind: "exact-page",
26
710
  async execute(input, call) {
27
- const result = history.search(call, input);
28
- return {
29
- content: JSON.stringify(result),
30
- ...!result.ok ? { isError: true } : {}
31
- };
711
+ const id = await select(call, "context_search", input);
712
+ const selected = validated(call, id, "context_search");
713
+ if ("content" in selected) return selected;
714
+ return selected.root.lease.withUse(call, async () => {
715
+ if (selected.result) return deliver(call, selected, id, selected.result);
716
+ const initial = searchInitial.parse(selected.initial);
717
+ const limit = Math.min(initial.limit, Math.max(1, Math.floor(call.output.outputTokens / 700)));
718
+ const result = history.search(call, {
719
+ query: initial.query,
720
+ around: initial.around,
721
+ after: selected.position.after,
722
+ limit
723
+ });
724
+ if (!result.ok) {
725
+ discardRoot(selected.root);
726
+ return refusal(call, result.code, result.message);
727
+ }
728
+ const next = result.next ? {
729
+ tool: "context_search",
730
+ arguments: { cursor: await nextState(call, "context_search", selected.initial, { after: result.next }, selected.created, selected.root) }
731
+ } : null;
732
+ return deliver(call, selected, id, { content: JSON.stringify({
733
+ ok: true,
734
+ complete: next === null,
735
+ items: result.entries,
736
+ next,
737
+ effective: { outputTokens: call.output.outputTokens }
738
+ }) });
739
+ });
32
740
  }
33
741
  });
34
742
  register({
35
743
  name: "context_restore",
36
- description: "Read an exact page of persisted original text by a ref from context_search or a compression marker. offset and limit count Unicode code points; follow nextOffset for more. Request a smaller page if the host reports insufficient space. A file (an image) comes back whole with the page that holds it. Historical tool inputs are returned as JSON data and are never executed. This does not reread a file, grant access, restore another session, or recover text lost before persistence.",
744
+ preload: true,
745
+ description: "Read ordered persisted original sources from pages [{ref,offset?,limit?}]. Offsets and limits are Unicode code points; the call shares one host allowance. Follow next.arguments unchanged. Historical retrieval never re-executes a tool, rereads a live file or confirms a skill load.",
37
746
  inputSchema: ContextRestoreInput,
747
+ outputSchema: ContextRestoreOutput,
748
+ deliveryKind: "exact-page",
38
749
  async execute(input, call) {
39
- const result = history.restore(call, input);
40
- if (!result.ok || result.files === void 0 || result.files.length === 0) return {
41
- content: JSON.stringify(result),
42
- ...!result.ok ? { isError: true } : {}
43
- };
44
- const { files, ...page } = result;
45
- return {
46
- content: JSON.stringify(page),
47
- files: files.map((file) => ({
48
- fileId: file.id,
49
- name: file.name
50
- }))
51
- };
750
+ call.signal.throwIfAborted();
751
+ const id = await select(call, "context_restore", input);
752
+ const selected = validated(call, id, "context_restore");
753
+ if ("content" in selected) return selected;
754
+ return selected.root.lease.withUse(call, async () => {
755
+ if (selected.result) return deliver(call, selected, id, selected.result);
756
+ const onAbort = () => discardRoot(selected.root);
757
+ call.signal.addEventListener("abort", onAbort, { once: true });
758
+ try {
759
+ const initial = restoreInitial.parse(selected.initial);
760
+ const sourceRefs = initial.pages.map((page) => page.ref);
761
+ let member = selected.position.member ?? 0, offset = selected.position.offset ?? initial.pages[member]?.offset ?? 0;
762
+ const items = [], files = [], media = [];
763
+ let continuation;
764
+ while (member < initial.pages.length) {
765
+ await setImmediate();
766
+ call.signal.throwIfAborted();
767
+ const target = initial.pages[member];
768
+ const used = call.output.measure({ content: JSON.stringify({
769
+ ok: true,
770
+ complete: false,
771
+ items,
772
+ next: {
773
+ tool: "context_restore",
774
+ arguments: { cursor: "x".repeat(36) }
775
+ },
776
+ effective: { outputTokens: call.output.outputTokens }
777
+ }) });
778
+ let limit = Math.min(target.limit, Math.max(0, Math.floor((call.output.outputTokens - used - 512) / 24)));
779
+ if (history.previewRestore) {
780
+ let low = 1, high = target.limit;
781
+ limit = 0;
782
+ while (low <= high) {
783
+ await setImmediate();
784
+ call.signal.throwIfAborted();
785
+ const count = Math.floor((low + high) / 2);
786
+ const probe = await history.previewRestore(call, {
787
+ ref: target.ref,
788
+ offset,
789
+ limit: count
790
+ }, sourceRefs);
791
+ if (!probe.ok) {
792
+ limit = 1;
793
+ break;
794
+ }
795
+ const { files: attached, ...value } = probe;
796
+ const candidate = {
797
+ content: JSON.stringify({
798
+ ok: true,
799
+ complete: false,
800
+ items: [...items, {
801
+ index: member,
802
+ ref: target.ref,
803
+ ok: true,
804
+ value
805
+ }],
806
+ next: {
807
+ tool: "context_restore",
808
+ arguments: { cursor: "x".repeat(36) }
809
+ },
810
+ effective: { outputTokens: call.output.outputTokens }
811
+ }),
812
+ ...media.length || attached?.length ? { files: [...media, ...attached ?? []] } : {}
813
+ };
814
+ if (call.output.measure(candidate) <= call.output.outputTokens) {
815
+ limit = count;
816
+ low = count + 1;
817
+ } else high = count - 1;
818
+ }
819
+ }
820
+ if (!limit) {
821
+ continuation = {
822
+ member,
823
+ offset
824
+ };
825
+ break;
826
+ }
827
+ const result = history.restore(call, {
828
+ ref: target.ref,
829
+ offset,
830
+ limit
831
+ });
832
+ if (!result.ok && result.code === "limit_exceeded") {
833
+ continuation = {
834
+ member,
835
+ offset
836
+ };
837
+ break;
838
+ }
839
+ if (!result.ok) items.push({
840
+ index: member,
841
+ ref: target.ref,
842
+ ok: false,
843
+ error: {
844
+ code: result.code,
845
+ message: result.message
846
+ }
847
+ });
848
+ else {
849
+ const { files: attached, ...value } = result;
850
+ items.push({
851
+ index: member,
852
+ ref: target.ref,
853
+ ok: true,
854
+ value
855
+ });
856
+ for (const file of attached ?? []) {
857
+ files.push({
858
+ fileId: file.id,
859
+ name: file.name
860
+ });
861
+ media.push(file);
862
+ }
863
+ if (result.nextOffset !== void 0) {
864
+ continuation = {
865
+ member,
866
+ offset: result.nextOffset
867
+ };
868
+ break;
869
+ }
870
+ }
871
+ member++;
872
+ offset = initial.pages[member]?.offset ?? 0;
873
+ }
874
+ if (!items.length && continuation) return refusal(call, "page_too_small", "No source body fits the current allowance.", call.output.outputTokens < call.output.maximumTokens ? {
875
+ tool: "context_restore",
876
+ arguments: {
877
+ cursor: id,
878
+ outputTokens: call.output.maximumTokens
879
+ }
880
+ } : null);
881
+ const next = continuation ? {
882
+ tool: "context_restore",
883
+ arguments: { cursor: await nextState(call, "context_restore", selected.initial, continuation, selected.created, selected.root) }
884
+ } : null;
885
+ return deliver(call, selected, id, {
886
+ content: JSON.stringify({
887
+ ok: true,
888
+ complete: next === null,
889
+ items,
890
+ next,
891
+ effective: { outputTokens: call.output.outputTokens }
892
+ }),
893
+ ...files.length ? { files } : {}
894
+ });
895
+ } finally {
896
+ call.signal.removeEventListener("abort", onAbort);
897
+ }
898
+ });
52
899
  }
53
900
  });
54
901
  }
@@ -57,6 +904,14 @@ function registerContextTools(ctx, register) {
57
904
  const GUIDANCE = {
58
905
  title: "This session",
59
906
  entries: [
907
+ {
908
+ tools: ["tool_search"],
909
+ text: "`tool_search` finds available tools and their full schemas. Use concise English metadata keywords when the task is Chinese, retry synonyms after no matches, and follow next.arguments for more definitions."
910
+ },
911
+ {
912
+ tools: ["tool_call"],
913
+ text: "`tool_call` calls a discovered or already known ordinary tool with its exact name and schema-compatible arguments. The target retains its normal approvals and result format."
914
+ },
60
915
  {
61
916
  tools: ["context_search"],
62
917
  text: "`context_search` finds where something was said in an earlier, compacted part of this session."
@@ -117,9 +972,24 @@ const ContextMeasurementSchema = z.object({
117
972
  fingerprint: z.string(),
118
973
  inputBudget: z.number().int().nonnegative().optional(),
119
974
  /** Whether the reserve is enforceable upstream or the catalogue capacity. */
120
- outputReserveSource: z.enum(["capacity", "enforced"]).optional()
975
+ outputReserveSource: z.enum([
976
+ "capacity",
977
+ "enforced",
978
+ "estimated"
979
+ ]).optional(),
980
+ /** Whether the capacity comes from a declaration or the owner's assumed baseline. */
981
+ capacitySource: z.enum(["declared", "assumed"]).optional()
121
982
  });
122
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
+ });
123
993
  const SplitSchema = z.object({
124
994
  categories: z.object({
125
995
  system: count,
@@ -138,6 +1008,11 @@ const SplitSchema = z.object({
138
1008
  });
139
1009
  /** Everything the coordinator needs to show a reading again after a restart. */
140
1010
  const ReadingSchema = z.object({
1011
+ /** Durable preparation and compaction identity for the displayed view. */
1012
+ viewIdentity: z.string(),
1013
+ observation: ObservationIdentitySchema.optional(),
1014
+ /** Model/parameter identity; a mismatching reading is never restored. */
1015
+ measurementIdentity: z.string().optional(),
141
1016
  measurement: ContextMeasurementSchema,
142
1017
  split: SplitSchema.optional(),
143
1018
  displayed: count,
@@ -146,7 +1021,8 @@ const ReadingSchema = z.object({
146
1021
  reported: count,
147
1022
  estimate: count,
148
1023
  fingerprint: z.string(),
149
- revision: z.number().int().nonnegative()
1024
+ revision: z.number().int().nonnegative(),
1025
+ viewIdentity: z.string()
150
1026
  }).optional()
151
1027
  });
152
1028
  //#endregion
@@ -160,6 +1036,7 @@ const ContextTrigger = z.enum([
160
1036
  ]);
161
1037
  /** A completed preparation, including failures that preserve the committed view. */
162
1038
  const ContextOperationResult = z.object({
1039
+ modelCallId: z.string().optional(),
163
1040
  campaignId: z.string().optional(),
164
1041
  attempt: z.number().int().positive().optional(),
165
1042
  completedChunks: z.number().int().nonnegative().optional(),
@@ -187,7 +1064,9 @@ const ContextOperationResult = z.object({
187
1064
  }).optional(),
188
1065
  usage: z.object({
189
1066
  inputTokens: z.number().int().nonnegative(),
190
- 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()
191
1070
  }).optional(),
192
1071
  elapsedMs: z.number().int().nonnegative()
193
1072
  });
@@ -228,14 +1107,54 @@ const ContextOccupancy = z.object({
228
1107
  });
229
1108
  /** Live request measurements and durable preparation totals for one session. */
230
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(),
1128
+ /** Committed model and parameter identity of this observation, never raw settings. */
1129
+ measurementIdentity: z.string().optional(),
231
1130
  revision: z.number().int().nonnegative(),
232
1131
  measurement: ContextMeasurementSchema.optional(),
233
1132
  occupancy: ContextOccupancy.optional(),
1133
+ /** Display-only observation from this history generation, not validated for current settings. */
1134
+ lastObservation: z.object({
1135
+ measurement: ContextMeasurementSchema,
1136
+ occupancy: ContextOccupancy,
1137
+ actualInputTokens: z.number().int().nonnegative().optional()
1138
+ }).optional(),
234
1139
  actualInputTokens: z.number().int().nonnegative().optional(),
235
1140
  auxiliaryTokens: z.number().int().nonnegative(),
236
1141
  totalTokens: z.number().int().nonnegative(),
237
1142
  operation: z.object({
238
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(),
239
1158
  trigger: ContextTrigger,
240
1159
  startedAt: z.number().optional(),
241
1160
  completedChunks: z.number().int().nonnegative().optional()
@@ -264,14 +1183,19 @@ function createSessionStatusRows(storage) {
264
1183
  ) STRICT`);
265
1184
  const get = storage.db.prepare(`SELECT source_seq, history_generation,
266
1185
  CASE WHEN length(CAST(status AS BLOB)) <= ${MAX_STATUS_BYTES} THEN status ELSE NULL END AS status
1186
+ FROM ${table} WHERE session_id = ?`);
1187
+ const limited = storage.db.prepare(`SELECT source_seq, history_generation,
1188
+ length(CAST(status AS BLOB)) AS bytes,
1189
+ CASE WHEN length(CAST(status AS BLOB)) <= min(?, ${MAX_STATUS_BYTES}) THEN status ELSE NULL END AS status
267
1190
  FROM ${table} WHERE session_id = ?`);
268
1191
  const put = storage.db.prepare(`INSERT INTO ${table}
269
1192
  (session_id, source_seq, history_generation, status) VALUES (?, ?, ?, ?)
270
1193
  ON CONFLICT(session_id) DO UPDATE SET source_seq = excluded.source_seq,
271
1194
  history_generation = excluded.history_generation, status = excluded.status`);
272
1195
  return {
273
- get(sessionId) {
274
- const row = get.get(sessionId);
1196
+ get(sessionId, maxBytes) {
1197
+ const row = maxBytes === void 0 ? get.get(sessionId) : limited.get(maxBytes, sessionId);
1198
+ if (row && maxBytes !== void 0 && row.bytes !== void 0 && row.bytes > maxBytes) throw new Error("read-limit: saved status exceeds member body capacity");
275
1199
  if (!row || row.status === null) return void 0;
276
1200
  try {
277
1201
  const status = SessionContextStatus.safeParse(JSON.parse(row.status));
@@ -294,6 +1218,7 @@ function createSessionStatusRows(storage) {
294
1218
  }
295
1219
  //#endregion
296
1220
  //#region src/runtime/breakdown.ts
1221
+ /** Splits a request's context into the categories a person reads. */
297
1222
  const referencedFiles = (request) => {
298
1223
  const files = /* @__PURE__ */ new Map();
299
1224
  for (const message of request.messages) for (const part of message.content) {
@@ -358,8 +1283,8 @@ function occupancyOf(total, source, raw) {
358
1283
  }))
359
1284
  };
360
1285
  }
361
- /** Splits the final request into category bytes; `inputTokens` is its measured size. */
362
- function rawBreakdown(request, inputTokens, deps) {
1286
+ /** Aggregates category weights after the caller has counted the unchanged messages. */
1287
+ function categoryBreakdown(request, inputTokens, deps, messageBytes) {
363
1288
  const system = request.system ?? [];
364
1289
  const systemBytes = bytesOf(system);
365
1290
  const recorded = deps.systemParts(system);
@@ -382,7 +1307,7 @@ function rawBreakdown(request, inputTokens, deps) {
382
1307
  const volatile = bytesOf([...(request.volatile ?? []).map((note) => note.text), ...request.messages.flatMap((message) => (message.volatile ?? []).map((note) => note.text))]);
383
1308
  const files = referencedFiles(request).reduce((sum, ref) => sum + (deps.measureFile?.(ref) ?? 0), 0);
384
1309
  const content = systemBytes + toolBytes + volatile + files;
385
- const messages = Math.max(Buffer.byteLength(JSON.stringify(request.messages.map(({ volatile: _notes, ...message }) => message))), inputTokens - content);
1310
+ const messages = Math.max(messageBytes, inputTokens - content);
386
1311
  return {
387
1312
  categories: {
388
1313
  system: systemBytes - (parts.rules ?? 0) - (parts.skills ?? 0) - (parts.agents ?? 0),
@@ -403,23 +1328,39 @@ function rawBreakdown(request, inputTokens, deps) {
403
1328
  function bytesOf(texts) {
404
1329
  return texts.reduce((sum, text) => sum + Buffer.byteLength(text), 0);
405
1330
  }
406
- /** Awaits the owner's complete request display count without choosing an encoding. */
407
- async function displayTokensOf(request, signal, measure) {
408
- signal.throwIfAborted();
409
- const tokens = await measure?.(request, signal);
410
- signal.throwIfAborted();
411
- return tokens;
1331
+ /**
1332
+ * Counts exact category bytes without retaining message JSON. Yields after roughly four milliseconds
1333
+ * between messages; serialization of one message is indivisible.
1334
+ */
1335
+ async function rawBreakdown(request, inputTokens, deps, scheduling = {}) {
1336
+ scheduling.signal?.throwIfAborted();
1337
+ const now = scheduling.now ?? (() => performance.now());
1338
+ const yieldWork = scheduling.yield ?? (() => setImmediate());
1339
+ let deadline = now() + 4;
1340
+ let messageBytes = 2;
1341
+ for (const [index, source] of request.messages.entries()) {
1342
+ const { volatile: _notes, ...message } = source;
1343
+ messageBytes += Buffer.byteLength(JSON.stringify(message)) + (index > 0 ? 1 : 0);
1344
+ if (index + 1 < request.messages.length && now() >= deadline) {
1345
+ await yieldWork();
1346
+ scheduling.signal?.throwIfAborted();
1347
+ deadline = now() + 4;
1348
+ }
1349
+ }
1350
+ return categoryBreakdown(request, inputTokens, deps, messageBytes);
412
1351
  }
413
- //#endregion
414
- //#region src/runtime/budget.ts
1352
+ /** Internal output reservation used when the adapter reports no usable reserve. */
1353
+ const ASSUMED_OUTPUT_RESERVE = 8192;
415
1354
  /**
416
- * Returns the safe input budget for a known context window. Capacity is
417
- * unknown when the adapter supplies no context window.
1355
+ * Computes safe input using the declared window or the 128K assumed baseline.
1356
+ * Missing independent input limits impose no additional limit. Known windows,
1357
+ * including small ones, always take precedence over the assumed baseline.
418
1358
  */
419
1359
  function safeInputBudget(inspection) {
420
- if (inspection.contextWindow === void 0) return void 0;
421
- const capacity = Math.min(inspection.inputLimit ?? Number.POSITIVE_INFINITY, inspection.contextWindow - inspection.outputReserve);
422
- const margin = Math.max(256, Math.ceil(inspection.contextWindow * .05));
1360
+ const window = inspection.contextWindow ?? 128e3;
1361
+ const reserve = inspection.outputReserve > 0 || inspection.contextWindow !== void 0 ? inspection.outputReserve : ASSUMED_OUTPUT_RESERVE;
1362
+ const capacity = Math.min(inspection.inputLimit ?? Number.POSITIVE_INFINITY, window - reserve);
1363
+ const margin = Math.max(256, Math.ceil(window * .05));
423
1364
  return Math.max(0, capacity - margin);
424
1365
  }
425
1366
  /** Capability-owned defaults for first-delivery tool bodies, expressed in model-estimated tokens. */
@@ -434,6 +1375,85 @@ const TOOL_PREVIEW_POLICY = {
434
1375
  stepFraction: .2
435
1376
  };
436
1377
  //#endregion
1378
+ //#region src/runtime/inspection-cache.ts
1379
+ /** Creates one exact-probe result pool shared by every session of the context owner. */
1380
+ function createInspectionCache(options = {}) {
1381
+ let ports = /* @__PURE__ */ new WeakMap();
1382
+ const recent = /* @__PURE__ */ new Map();
1383
+ const maximumEntries = options.entries ?? 512;
1384
+ const maximumBytes = options.bytes ?? 16777216;
1385
+ let retainedBytes = 0;
1386
+ options.signal?.addEventListener("abort", () => {
1387
+ ports = /* @__PURE__ */ new WeakMap();
1388
+ recent.clear();
1389
+ retainedBytes = 0;
1390
+ }, { once: true });
1391
+ return {
1392
+ /** Reuses exact text only within one port and complete measurement scope, with a shared LRU ceiling. */
1393
+ measure(port, scope, text, count, purpose = "text") {
1394
+ options.signal?.throwIfAborted();
1395
+ const started = options.performance?.now();
1396
+ const scopes = ports.get(port) ?? /* @__PURE__ */ new Map();
1397
+ let bucket = scopes.get(scope);
1398
+ const found = bucket?.values.get(text);
1399
+ if (found !== void 0) {
1400
+ recent.delete(found);
1401
+ recent.set(found, true);
1402
+ options.performance?.observe({
1403
+ stage: "model.cache",
1404
+ measurementPurpose: purpose,
1405
+ durationMs: options.performance.now() - started,
1406
+ count: 1,
1407
+ hits: 1,
1408
+ inputBytes: text.length * 2,
1409
+ retainedBytes
1410
+ });
1411
+ return found.value;
1412
+ }
1413
+ const value = count();
1414
+ const bytes = (scope.length + text.length) * 2;
1415
+ let evictions = 0;
1416
+ if (maximumEntries > 0 && bytes <= maximumBytes) {
1417
+ while (recent.size >= maximumEntries || retainedBytes + bytes > maximumBytes) {
1418
+ const oldest = recent.keys().next().value;
1419
+ if (!oldest) break;
1420
+ recent.delete(oldest);
1421
+ oldest.bucket.values.delete(oldest.text);
1422
+ if (!oldest.bucket.values.size) oldest.bucket.scopes.delete(oldest.bucket.scope);
1423
+ retainedBytes -= oldest.bytes;
1424
+ evictions++;
1425
+ }
1426
+ bucket ??= {
1427
+ scope,
1428
+ scopes,
1429
+ values: /* @__PURE__ */ new Map()
1430
+ };
1431
+ scopes.set(scope, bucket);
1432
+ ports.set(port, scopes);
1433
+ const entry = {
1434
+ text,
1435
+ value,
1436
+ bytes,
1437
+ bucket
1438
+ };
1439
+ bucket.values.set(text, entry);
1440
+ recent.set(entry, true);
1441
+ retainedBytes += bytes;
1442
+ }
1443
+ options.performance?.observe({
1444
+ stage: "model.cache",
1445
+ measurementPurpose: purpose,
1446
+ durationMs: options.performance.now() - started,
1447
+ count: 1,
1448
+ misses: 1,
1449
+ evictions,
1450
+ inputBytes: text.length * 2,
1451
+ retainedBytes
1452
+ });
1453
+ return value;
1454
+ } };
1455
+ }
1456
+ //#endregion
437
1457
  //#region src/runtime/preview.ts
438
1458
  const toolUsePartsIn$1 = (message) => message.content.filter((part) => part.type === "tool-use");
439
1459
  const contextSourceRef$1 = (message, part) => `msg:${message}:${part}`;
@@ -441,11 +1461,24 @@ const contextSourceRef$1 = (message, part) => `msg:${message}:${part}`;
441
1461
  * Allocates ordinary result bodies fairly across each complete tool batch.
442
1462
  * `inputBudget` is safe input tokens and `tokens` measures text using the current
443
1463
  * model estimator. Mandatory instructions remain whole for the final request
444
- * check; restoration pages reserve their full cost in the step budget.
445
- * Throws when identifiers or restoration pages alone cannot fit the step.
1464
+ * check; protected pages are excluded from ordinary preview allocation.
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.
446
1467
  * Returned replacements reference immutable originals and preserve all metadata.
447
1468
  */
448
- function planToolPreviews(events, inputBudget, tokens, framework) {
1469
+ function planToolPreviews(events, inputBudget, measureTokens, framework) {
1470
+ const measured = /* @__PURE__ */ new Map();
1471
+ let cachedCodeUnits = 0;
1472
+ const tokens = (text) => {
1473
+ const found = measured.get(text);
1474
+ if (found !== void 0) return found;
1475
+ const value = measureTokens(text);
1476
+ if (measured.size < 128 && cachedCodeUnits + text.length <= 524288) {
1477
+ measured.set(text, value);
1478
+ cachedCodeUnits += text.length;
1479
+ }
1480
+ return value;
1481
+ };
449
1482
  const projection = framework.project(events);
450
1483
  const replaced = new Set(projection.replacedSourceKeys);
451
1484
  const visible = new Map(projection.entries.map((entry) => [entry.message.id, entry.message]));
@@ -463,25 +1496,126 @@ function planToolPreviews(events, inputBudget, tokens, framework) {
463
1496
  partIndex
464
1497
  }] : []);
465
1498
  if (previous.message.role !== "assistant" || source.message.role !== "user" || calls.length === 0 || calls.length !== parts.length || new Set(calls.map((call) => call.id)).size !== calls.length || new Set(parts.map(({ part }) => part.toolUseId)).size !== calls.length || !calls.every((call) => parts.some(({ part }) => part.toolUseId === call.id)) || parts.every(({ partIndex }) => replaced.has(`${source.messageSeq}:${partIndex}`))) continue;
1499
+ const answers = /* @__PURE__ */ new Map();
1500
+ for (const { part, partIndex } of parts) {
1501
+ if (!part.delivery?.answerRequestId) continue;
1502
+ const answer = framework.answerSource?.(events, source.message.id, partIndex);
1503
+ if (answer) answers.set(partIndex, answer);
1504
+ }
1505
+ const sourceRef = (partIndex) => answers.get(partIndex)?.ref ?? contextSourceRef$1(source.message.id, partIndex);
466
1506
  const ordered = calls.flatMap((call) => {
467
1507
  const found = parts.find(({ part }) => part.toolUseId === call.id);
468
- return found === void 0 ? [] : [found];
1508
+ return found === void 0 ? [] : [{
1509
+ ...found,
1510
+ part: answers.has(found.partIndex) ? {
1511
+ ...found.part,
1512
+ content: answers.get(found.partIndex).text
1513
+ } : found.part
1514
+ }];
469
1515
  });
470
- const restoreIds = new Set(calls.filter((call) => call.name === "context_restore").map((call) => call.id));
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
+ }
1569
+ const originalCosts = /* @__PURE__ */ new Map();
1570
+ const originalCost = (partIndex, content) => {
1571
+ const found = originalCosts.get(partIndex);
1572
+ if (found !== void 0) return found;
1573
+ const cost = tokens(content);
1574
+ originalCosts.set(partIndex, cost);
1575
+ return cost;
1576
+ };
471
1577
  const metadata = ordered.reduce((sum, { part }) => {
472
- const { content: _content, previewTokens: _hint, previewProtected: _protected, ...rest } = part;
1578
+ const { content: _content, files: _files, previewTokens: _hint, delivery: _delivery, requiredContext: _requiredContext, ...rest } = part;
473
1579
  return sum + tokens(JSON.stringify(rest));
474
1580
  }, 0);
475
- if (metadata >= stepLimit) throw new Error("protected_context_exceeds_budget");
476
- const protectedTokens = ordered.reduce((sum, { part }) => sum + (restoreIds.has(part.toolUseId) ? tokens(part.content) : 0), 0);
477
- if (protectedTokens + metadata > stepLimit) throw new Error("protected_context_exceeds_budget");
478
- const available = stepLimit - metadata - protectedTokens;
479
- const desired = ordered.map(({ part }) => {
480
- if (restoreIds.has(part.toolUseId) || part.previewProtected === true) return 0;
1581
+ const required = /* @__PURE__ */ new Map();
1582
+ for (const { part } of ordered) for (const block of part.requiredContext ?? []) {
1583
+ const key = JSON.stringify([
1584
+ block.id,
1585
+ block.scope,
1586
+ block.version,
1587
+ block.stampedSource
1588
+ ]);
1589
+ if (!required.has(key)) required.set(key, block);
1590
+ }
1591
+ const requiredCost = [...required.values()].reduce((sum, block) => sum + tokens(JSON.stringify(block)), 0);
1592
+ const exactCost = ordered.reduce((sum, { part }) => sum + (part.delivery?.kind === "exact-page" ? tokens(part.content) : 0), 0);
1593
+ if (metadata + requiredCost + exactCost >= stepLimit) throw new Error("protected_context_exceeds_budget");
1594
+ const available = stepLimit - metadata - requiredCost - exactCost;
1595
+ const encodePreview = (partIndex, preview) => {
1596
+ const ref = sourceRef(partIndex);
1597
+ const part = ordered.find((one) => one.partIndex === partIndex).part;
1598
+ return JSON.stringify({
1599
+ ok: true,
1600
+ complete: false,
1601
+ preview,
1602
+ source: {
1603
+ ref,
1604
+ sourceComplete: answers.has(partIndex) || (part.delivery?.sourceComplete ?? false),
1605
+ recoverable: true
1606
+ },
1607
+ next: {
1608
+ tool: "context_restore",
1609
+ arguments: { pages: [{ ref }] }
1610
+ }
1611
+ });
1612
+ };
1613
+ const desired = ordered.map(({ part, partIndex }) => {
1614
+ if (part.delivery?.kind === "exact-page") return 0;
481
1615
  const hint = part.previewTokens;
482
- return Math.min(tokens(part.content), typeof hint === "number" && Number.isInteger(hint) && hint >= 1 && hint <= TOOL_PREVIEW_POLICY.maximumTokens ? hint : TOOL_PREVIEW_POLICY.defaultTokens);
1616
+ return Math.min(tokens(encodePreview(partIndex, part.content)) - tokens(encodePreview(partIndex, "")), Math.max(0, (part.delivery?.outputTokens ?? TOOL_PREVIEW_POLICY.defaultTokens) - tokens(encodePreview(partIndex, ""))), typeof hint === "number" && Number.isInteger(hint) && hint >= 1 && hint <= TOOL_PREVIEW_POLICY.maximumTokens ? hint : TOOL_PREVIEW_POLICY.defaultTokens);
483
1617
  });
484
- const markerFor = (partIndex) => `\n[tool result preview; context_restore ref "${contextSourceRef$1(source.message.id, partIndex)}"]\n`;
1618
+ const markerFor = (partIndex) => encodePreview(partIndex, "");
485
1619
  const referenceCosts = /* @__PURE__ */ new Map();
486
1620
  let cells = desired.map((wanted, i) => ({
487
1621
  i,
@@ -490,7 +1624,33 @@ function planToolPreviews(events, inputBudget, tokens, framework) {
490
1624
  }));
491
1625
  for (;;) {
492
1626
  let remaining = available - [...referenceCosts.values()].reduce((sum, value) => sum + value, 0);
493
- if (remaining < 0) throw new Error("protected_context_exceeds_budget");
1627
+ if (remaining < 0) {
1628
+ const failure = JSON.stringify({
1629
+ ok: false,
1630
+ error: {
1631
+ code: "step_budget_exhausted",
1632
+ message: "Saved; use context_search.",
1633
+ retryable: true
1634
+ },
1635
+ next: null
1636
+ });
1637
+ const ordinary = ordered.filter(({ part, partIndex }) => part.delivery?.kind !== "exact-page" && !replaced.has(`${source.messageSeq}:${partIndex}`));
1638
+ if (ordinary.length * tokens(failure) > available) throw new Error("protected_context_exceeds_budget");
1639
+ for (const { part, partIndex } of ordinary) replacements.push({
1640
+ messageSeq: source.messageSeq,
1641
+ partIndex,
1642
+ replacement: {
1643
+ ...part,
1644
+ content: failure
1645
+ },
1646
+ sourceRef: contextSourceRef$1(source.message.id, partIndex),
1647
+ originalCodePoints: [...part.content].length,
1648
+ previewTokens: 0,
1649
+ truncated: true
1650
+ });
1651
+ cells = [];
1652
+ break;
1653
+ }
494
1654
  cells = desired.map((wanted, i) => ({
495
1655
  i,
496
1656
  wanted,
@@ -508,20 +1668,21 @@ function planToolPreviews(events, inputBudget, tokens, framework) {
508
1668
  }
509
1669
  let addedReference = false;
510
1670
  ordered.forEach(({ part, partIndex }, i) => {
511
- if (replaced.has(`${source.messageSeq}:${partIndex}`) || restoreIds.has(part.toolUseId) || part.previewProtected === true) return;
1671
+ if (replaced.has(`${source.messageSeq}:${partIndex}`) || part.delivery?.kind === "exact-page") return;
512
1672
  const cell = cells[i];
513
- if (cell !== void 0 && tokens(part.content) > cell.limit && !referenceCosts.has(i)) {
1673
+ if (cell !== void 0 && (answers.has(partIndex) || originalCost(partIndex, part.content) > cell.limit) && !referenceCosts.has(i)) {
514
1674
  referenceCosts.set(i, tokens(markerFor(partIndex)));
515
1675
  addedReference = true;
516
1676
  }
517
1677
  });
518
1678
  if (!addedReference) break;
519
1679
  }
1680
+ if (cells.length === 0) continue;
520
1681
  ordered.forEach(({ part, partIndex }, i) => {
521
- if (replaced.has(`${source.messageSeq}:${partIndex}`) || restoreIds.has(part.toolUseId) || part.previewProtected === true) return;
1682
+ if (replaced.has(`${source.messageSeq}:${partIndex}`) || part.delivery?.kind === "exact-page") return;
522
1683
  const limit = cells[i]?.limit ?? 0;
523
- if (tokens(part.content) <= limit) return;
524
- const ref = contextSourceRef$1(source.message.id, partIndex);
1684
+ if (!answers.has(partIndex) && originalCost(partIndex, part.content) <= limit) return;
1685
+ const ref = sourceRef(partIndex);
525
1686
  const marker = markerFor(partIndex);
526
1687
  const points = [...part.content];
527
1688
  let low = 0;
@@ -532,8 +1693,8 @@ function planToolPreviews(events, inputBudget, tokens, framework) {
532
1693
  const count = Math.floor((low + high) / 2);
533
1694
  const head = Math.ceil(count * 2 / 3);
534
1695
  const tail = count - head;
535
- const candidate = points.slice(0, head).join("") + marker + (tail === 0 ? "" : points.slice(-tail).join(""));
536
- const bodyTokens = tokens(points.slice(0, head).join("") + (tail === 0 ? "" : points.slice(-tail).join("")));
1696
+ const candidate = encodePreview(partIndex, points.slice(0, head).join("") + (tail === 0 ? "" : points.slice(-tail).join("")));
1697
+ const bodyTokens = Math.max(0, tokens(candidate) - tokens(marker));
537
1698
  if (bodyTokens <= limit) {
538
1699
  content = candidate;
539
1700
  previewTokens = bodyTokens;
@@ -583,6 +1744,12 @@ function planContextReduction(input, framework, options = {}) {
583
1744
  }] : []);
584
1745
  const protectedSeqs = /* @__PURE__ */ new Set();
585
1746
  const projection = framework.project(input);
1747
+ const projectedMessages = /* @__PURE__ */ new Map();
1748
+ for (const entry of projection.entries) {
1749
+ const message = entry.message;
1750
+ if (!projectedMessages.has(message.id)) projectedMessages.set(message.id, message);
1751
+ }
1752
+ const originalMessageIds = new Set(projection.sources.map((source) => source.message.id));
586
1753
  const alreadyReplaced = new Set(projection.l1SourceKeys);
587
1754
  const completedSteps = [];
588
1755
  const completedToolResults = /* @__PURE__ */ new Set();
@@ -618,7 +1785,7 @@ function planContextReduction(input, framework, options = {}) {
618
1785
  const part = result.message.content[partIndex];
619
1786
  if (part?.type === "tool-result" && wanted.has(part.toolUseId)) completedToolResults.add(sourceKey(result.messageSeq, partIndex));
620
1787
  }
621
- if (calls.some((call) => call.name === "context_restore")) restoreBatches.push({
1788
+ if (result.message.content.some((part) => part.type === "tool-result" && part.delivery?.kind === "exact-page")) restoreBatches.push({
622
1789
  seqs: [source.messageSeq, result.messageSeq],
623
1790
  resultSeq: result.messageSeq
624
1791
  });
@@ -642,13 +1809,14 @@ function planContextReduction(input, framework, options = {}) {
642
1809
  if (activeTrigger >= 0) {
643
1810
  if (events[activeTrigger + 1]?.kind === "message-appended") protectedSeqs.add(activeTrigger + 1);
644
1811
  }
645
- for (const batch of restoreBatches) if (!sources.some((source) => source.messageSeq > batch.resultSeq && source.message.role === "assistant" && source.event.usage !== void 0)) for (const seq of batch.seqs) protectedSeqs.add(seq);
1812
+ const latestObservedReply = sources.reduce((latest, source) => source.message.role === "assistant" && source.event.usage !== void 0 ? Math.max(latest, source.messageSeq) : latest, -1);
1813
+ for (const batch of restoreBatches) if (!(latestObservedReply > batch.resultSeq)) for (const seq of batch.seqs) protectedSeqs.add(seq);
646
1814
  const l1Candidates = [];
647
1815
  for (const source of sources) {
648
1816
  if (protectedSeqs.has(source.messageSeq)) continue;
649
1817
  for (let partIndex = 0; partIndex < source.message.content.length; partIndex += 1) {
650
- const part = projection.entries.find((one) => one.message.id === source.message.id)?.message.content[partIndex] ?? source.message.content[partIndex];
651
- if (part?.type === "tool-result" && [...part.content].length > 2048 && completedToolResults.has(sourceKey(source.messageSeq, partIndex)) && !alreadyReplaced.has(sourceKey(source.messageSeq, partIndex))) l1Candidates.push({
1818
+ const part = projectedMessages.get(source.message.id)?.content[partIndex] ?? source.message.content[partIndex];
1819
+ if (part?.type === "tool-result" && part.delivery?.kind !== "exact-page" && moreThanCodePoints(part.content, 2048) && completedToolResults.has(sourceKey(source.messageSeq, partIndex)) && !alreadyReplaced.has(sourceKey(source.messageSeq, partIndex))) l1Candidates.push({
652
1820
  messageSeq: source.messageSeq,
653
1821
  partIndex,
654
1822
  part,
@@ -673,23 +1841,35 @@ function planContextReduction(input, framework, options = {}) {
673
1841
  }
674
1842
  const candidateKey = l2SourceRanges.map((range) => `${range.messageSeq}:${range.startPart}-${range.endPart}`).join(",");
675
1843
  const eligibleSeqs = new Set(l2SourceRanges.map((range) => range.messageSeq));
676
- const l2Messages = projection.entries.filter((entry) => entry.sourceRanges.every((range) => eligibleSeqs.has(range.messageSeq))).map((entry) => entry.message);
677
- const l2Groups = [];
678
1844
  const eligibleEntries = projection.entries.filter((entry) => entry.sourceRanges.every((range) => eligibleSeqs.has(range.messageSeq)));
1845
+ const l2Messages = eligibleEntries.map((entry) => entry.message);
1846
+ const l2Groups = [];
1847
+ const stepsBySeq = /* @__PURE__ */ new Map();
1848
+ completedSteps.forEach((step, index) => {
1849
+ for (const seq of step) if (!stepsBySeq.has(seq)) stepsBySeq.set(seq, index);
1850
+ });
1851
+ let priorSteps = /* @__PURE__ */ new Set();
679
1852
  for (const entry of eligibleEntries) {
680
1853
  const firstRange = entry.sourceRanges[0];
681
1854
  if (firstRange === void 0) continue;
682
- const step = completedSteps.find((one) => one.includes(firstRange.messageSeq));
1855
+ const step = stepsBySeq.get(firstRange.messageSeq);
683
1856
  const prior = l2Groups.at(-1);
684
- const summarized = !projection.sources.some((source) => source.message.id === entry.message.id);
685
- if (!summarized && prior && !prior.summarized && step?.some((seq) => prior.sourceRanges.some((range) => range.messageSeq === seq))) {
1857
+ const summarized = !originalMessageIds.has(entry.message.id);
1858
+ if (!summarized && prior && !prior.summarized && step !== void 0 && priorSteps.has(step)) {
686
1859
  prior.messages.push(entry.message);
687
1860
  prior.sourceRanges.push(...entry.sourceRanges);
688
- } else l2Groups.push({
689
- messages: [entry.message],
690
- sourceRanges: [...entry.sourceRanges],
691
- summarized
692
- });
1861
+ } else {
1862
+ priorSteps = /* @__PURE__ */ new Set();
1863
+ l2Groups.push({
1864
+ messages: [entry.message],
1865
+ sourceRanges: [...entry.sourceRanges],
1866
+ summarized
1867
+ });
1868
+ }
1869
+ for (const range of entry.sourceRanges) {
1870
+ const sourceStep = stepsBySeq.get(range.messageSeq);
1871
+ if (sourceStep !== void 0) priorSteps.add(sourceStep);
1872
+ }
693
1873
  }
694
1874
  return {
695
1875
  l1Candidates,
@@ -700,11 +1880,15 @@ function planContextReduction(input, framework, options = {}) {
700
1880
  protectedMessageSeqs: [...protectedSeqs].sort((a, b) => a - b)
701
1881
  };
702
1882
  }
1883
+ function moreThanCodePoints(text, limit) {
1884
+ let count = 0;
1885
+ for (const _ of text) if (++count > limit) return true;
1886
+ return false;
1887
+ }
703
1888
  /** Builds the deterministic replacement for one eligible tool-result body. */
704
1889
  function createL1Replacement(candidate) {
705
- const points = [...candidate.part.content];
706
- const head = points.slice(0, 256).join("");
707
- const tail = points.slice(-128).join("");
1890
+ const head = [...candidate.part.content.slice(0, 512)].slice(0, 256).join("");
1891
+ const tail = [...candidate.part.content.slice(-256)].slice(-128).join("");
708
1892
  return {
709
1893
  messageSeq: candidate.messageSeq,
710
1894
  partIndex: candidate.partIndex,
@@ -896,38 +2080,221 @@ function summaryFallbackPort(primary, fallback, onFallback) {
896
2080
  };
897
2081
  }
898
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
899
2249
  //#region src/runtime/coordinator.ts
900
2250
  /** Adds the shared safe-input budget to one terminal adapter inspection. */
901
2251
  function contextMeasurement(inspection) {
902
- const inputBudget = safeInputBudget(inspection);
903
- return {
2252
+ const assumed = inspection.contextWindow === void 0 || inspection.capacitySource === "assumed";
2253
+ const outputReserve = assumed && inspection.outputReserve <= 0 ? ASSUMED_OUTPUT_RESERVE : inspection.outputReserve;
2254
+ const measured = {
904
2255
  ...inspection,
905
- outputReserveSource: inspection.outputReserveSource ?? "capacity",
906
- ...inputBudget === void 0 ? {} : { inputBudget }
2256
+ contextWindow: inspection.contextWindow ?? 128e3,
2257
+ capacitySource: assumed ? "assumed" : "declared",
2258
+ outputReserve,
2259
+ outputReserveSource: assumed && inspection.outputReserve <= 0 ? "estimated" : inspection.outputReserveSource ?? "capacity"
2260
+ };
2261
+ return {
2262
+ ...measured,
2263
+ inputBudget: safeInputBudget(measured)
907
2264
  };
908
2265
  }
909
- /** Measures one fully rendered request, reporting an unmeasured request when unsupported. */
2266
+ /** Measures the final request locally; a missing protocol meter uses conservative UTF-8 bytes. */
910
2267
  function inspectContextRequest(port, request) {
911
2268
  const observed = port.inspect?.(request);
912
2269
  if (observed !== void 0) return contextMeasurement(observed);
913
- return {
914
- inputTokens: 0,
915
- unmeasured: true,
2270
+ if (request.files?.size || request.messages.some((message) => message.content.some((part) => part.type === "file" || part.type === "tool-result" && part.files?.length))) throw new Error("media_measurement_unavailable");
2271
+ return contextMeasurement({
2272
+ inputTokens: Buffer.byteLength(JSON.stringify(request)),
916
2273
  estimated: true,
917
2274
  outputReserve: 0,
918
- fingerprint: "unmeasured"
919
- };
2275
+ fingerprint: "estimated:utf8-bytes:assumed-128000"
2276
+ });
920
2277
  }
921
2278
  /** Creates the coordinator bound to one immutable session identity. */
922
2279
  function createContextCoordinator(_deps) {
923
2280
  const deps = _deps;
924
- const projectContext = deps.framework.project;
2281
+ const projectContext = (events) => projectDeliveries(events, deps.framework, deps.historyGeneration?.() ?? 0);
925
2282
  const effectiveHistory = deps.framework.history;
926
- const planContextReduction$1 = (events) => planContextReduction(events, deps.framework);
927
- const planToolPreviews$1 = (events, budget, tokens) => planToolPreviews(events, budget, tokens, deps.framework);
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
+ });
928
2291
  const now = deps.now ?? (() => Date.now());
929
2292
  const newOperationId = deps.newOperationId ?? randomUUID;
2293
+ const usageAccumulator = createUsageAccumulator(deps.usageStartSeq ?? -1);
930
2294
  let measurement;
2295
+ let measurementIdentity;
2296
+ let observation;
2297
+ let historical = false;
931
2298
  let split;
932
2299
  /** The display estimate of the observed request; the Protocol inspection when none was given. */
933
2300
  let displayed = 0;
@@ -938,14 +2305,47 @@ function createContextCoordinator(_deps) {
938
2305
  * model and the committed context are the same. */
939
2306
  let anchor;
940
2307
  let measurementEventCount = 0;
2308
+ let fixedCatalogTokens = 0;
941
2309
  let diagnostic;
942
2310
  let failedCommit;
943
2311
  let active;
944
- function inspect(port, request) {
945
- return inspectContextRequest(port, {
946
- ...request,
947
- sessionId: deps.sessionId
948
- });
2312
+ function inspect(port, request, purpose = "request") {
2313
+ const started = deps.performance?.now();
2314
+ try {
2315
+ return inspectContextRequest(port, {
2316
+ ...request,
2317
+ sessionId: deps.sessionId
2318
+ });
2319
+ } finally {
2320
+ deps.performance?.observe({
2321
+ stage: "context.inspect",
2322
+ measurementPurpose: purpose,
2323
+ durationMs: deps.performance.now() - started,
2324
+ count: 1
2325
+ });
2326
+ }
2327
+ }
2328
+ const inspections = deps.inspections ?? createInspectionCache({
2329
+ entries: 128,
2330
+ bytes: 1048576,
2331
+ performance: deps.performance
2332
+ });
2333
+ /** Reuses exact fragment text under the same live protocol and session generation. */
2334
+ function fragmentMeter(port, empty, purpose = "text") {
2335
+ const baseline = inspect(port, empty, purpose);
2336
+ const scope = JSON.stringify([
2337
+ deps.sessionId,
2338
+ purpose === "catalogue" ? "catalogue" : "text",
2339
+ baseline.fingerprint,
2340
+ baseline.inputTokens,
2341
+ deps.inspectionScope?.()
2342
+ ]);
2343
+ return {
2344
+ baseline,
2345
+ measure(text, request) {
2346
+ return inspections.measure(port, scope, text, () => inspect(port, request(), purpose).inputTokens, purpose);
2347
+ }
2348
+ };
949
2349
  }
950
2350
  function hasKnownCapacity(value) {
951
2351
  return value.inputBudget !== void 0;
@@ -959,6 +2359,7 @@ function createContextCoordinator(_deps) {
959
2359
  if (event === void 0 || event.status === void 0) return void 0;
960
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;
961
2361
  return {
2362
+ modelCallId: attemptDetails?.modelCallId,
962
2363
  operationId: event.operationId,
963
2364
  trigger: event.trigger,
964
2365
  status: event.status,
@@ -996,25 +2397,40 @@ function createContextCoordinator(_deps) {
996
2397
  /** What a person is shown: the reported input once the reply arrived, the last
997
2398
  * report plus the estimated growth while a reply is pending, the plain
998
2399
  * estimate when there is no report to build on. */
999
- function occupancy(current, revision) {
2400
+ function occupancy(current, revision, events) {
1000
2401
  if (reported !== void 0) return occupancyOf(reported, "reported", split);
1001
- 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
+ ]);
1002
2411
  }
1003
2412
  /** Writes the reading down so a restart can show it again; a failed write
1004
2413
  * costs the restart its reading, never this one. */
1005
- function save() {
2414
+ function save(events, revision) {
1006
2415
  if (deps.saved === void 0 || measurement === void 0) return;
1007
2416
  const reading = {
2417
+ viewIdentity: viewIdentity(events, revision),
2418
+ observation,
1008
2419
  measurement,
2420
+ measurementIdentity,
1009
2421
  ...split === void 0 ? {} : { split },
1010
2422
  displayed,
1011
2423
  ...reported === void 0 ? {} : { reported },
1012
2424
  ...anchor === void 0 ? {} : { anchor }
1013
2425
  };
1014
2426
  try {
1015
- deps.saved.put(projectContext(deps.read()).revision, JSON.stringify(reading));
2427
+ deps.saved.put(revision, JSON.stringify(reading));
1016
2428
  } catch (error) {
1017
- console.error(`context reading not saved: ${error instanceof Error ? error.message : error}`);
2429
+ deps.log?.emit({
2430
+ level: "error",
2431
+ event: "plugin.event",
2432
+ fields: { localCode: "CONTEXT_READING_SAVE_FAILED" }
2433
+ });
1018
2434
  }
1019
2435
  }
1020
2436
  /** Takes the saved reading back when it was written against the context the
@@ -1022,7 +2438,10 @@ function createContextCoordinator(_deps) {
1022
2438
  * leaves the meter empty until the next request. */
1023
2439
  function restore() {
1024
2440
  const row = deps.saved?.get();
1025
- if (row === void 0 || row.revision !== projectContext(deps.read()).revision) return;
2441
+ if (row === void 0) return;
2442
+ const events = deps.read();
2443
+ const revision = projectContext(events).revision;
2444
+ if (row.revision !== revision) return;
1026
2445
  let parsed;
1027
2446
  try {
1028
2447
  parsed = ReadingSchema.safeParse(JSON.parse(row.reading));
@@ -1030,12 +2449,17 @@ function createContextCoordinator(_deps) {
1030
2449
  return;
1031
2450
  }
1032
2451
  if (!parsed.success) return;
2452
+ if (parsed.data.viewIdentity !== viewIdentity(events, revision)) return;
2453
+ if (deps.measurementIdentity && parsed.data.measurementIdentity !== deps.measurementIdentity()) return;
1033
2454
  measurement = parsed.data.measurement;
2455
+ historical = true;
2456
+ observation = parsed.data.observation;
2457
+ measurementIdentity = parsed.data.measurementIdentity;
1034
2458
  split = parsed.data.split;
1035
2459
  displayed = parsed.data.displayed;
1036
2460
  reported = parsed.data.reported;
1037
2461
  anchor = parsed.data.anchor;
1038
- measurementEventCount = deps.read().length;
2462
+ measurementEventCount = events.length;
1039
2463
  diagnostic = measurement.inputBudget === void 0 ? "capacity_unknown" : void 0;
1040
2464
  }
1041
2465
  function notify() {
@@ -1053,6 +2477,7 @@ function createContextCoordinator(_deps) {
1053
2477
  async function recordOperation(input) {
1054
2478
  await commitFact({
1055
2479
  kind: "context-operation",
2480
+ modelCallId: input.modelCallId,
1056
2481
  sessionId: deps.sessionId,
1057
2482
  address: deps.address,
1058
2483
  operationId: input.operationId,
@@ -1115,42 +2540,61 @@ function createContextCoordinator(_deps) {
1115
2540
  text
1116
2541
  }]
1117
2542
  }] });
1118
- const emptyText = inspect(port, textRequest("")).inputTokens;
1119
- const tokens = (text) => Math.max(0, inspect(port, textRequest(text)).inputTokens - emptyText);
1120
- const replacements = planToolPreviews$1(deps.read(), before.inputBudget, tokens);
1121
- if (replacements.length > 0) {
1122
- if (!historyRecoveryAvailable(request)) return {
1123
- request,
1124
- before,
1125
- after,
1126
- changed,
1127
- recoveryUnavailable: true
1128
- };
1129
- const event = {
1130
- kind: "context-compacted",
2543
+ const textMeter = fragmentMeter(port, textRequest(""));
2544
+ const tokens = (text) => {
2545
+ return Math.max(0, textMeter.measure(text, () => textRequest(text)) - textMeter.baseline.inputTokens);
2546
+ };
2547
+ let replacements;
2548
+ try {
2549
+ replacements = planToolPreviews$1(deps.read(), before.inputBudget, tokens);
2550
+ } catch (error) {
2551
+ if (trigger === "auto") {
2552
+ const reason = error instanceof Error ? error.message.slice(0, 256) : "Preview admission failed.";
2553
+ diagnostic = reason.split(":")[0];
2554
+ await recordOperation({
2555
+ operationId,
2556
+ trigger,
2557
+ status: "failed",
2558
+ candidateKey: projection.revision.toString(),
2559
+ fingerprint: before.fingerprint,
2560
+ before,
2561
+ after: before,
2562
+ reason,
2563
+ startedAt: now()
2564
+ });
2565
+ }
2566
+ throw error;
2567
+ }
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",
1131
2585
  sessionId: deps.sessionId,
1132
2586
  address: deps.address,
1133
- operationId,
1134
- trigger,
1135
- layer: "preview",
1136
- baseRevision: projection.revision,
1137
- revision: projection.revision + 1,
1138
- sourceRanges: replacements.map((one) => ({
1139
- messageSeq: one.messageSeq,
1140
- startPart: one.partIndex,
1141
- endPart: one.partIndex + 1
1142
- })),
1143
- replacements: [...replacements].sort((a, b) => a.messageSeq - b.messageSeq || a.partIndex - b.partIndex),
1144
- before,
1145
- after: before
1146
- };
1147
- event.sourceRanges.sort((a, b) => a.messageSeq - b.messageSeq || a.startPart - b.startPart);
1148
- event.after = inspect(port, await assembleProjected(projectContext(withProjectedEvent(deps.read(), event)).messages));
1149
- 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) {
1150
2594
  projection = projectContext(deps.read());
1151
2595
  request = await assembleProjected(projection.messages);
1152
2596
  after = inspect(port, request);
1153
- changed = true;
2597
+ changed = replacements.length > 0;
1154
2598
  }
1155
2599
  }
1156
2600
  return {
@@ -1170,6 +2614,16 @@ function createContextCoordinator(_deps) {
1170
2614
  active = {
1171
2615
  operationId,
1172
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(),
1173
2627
  controller,
1174
2628
  startedAt: now(),
1175
2629
  completedChunks: 0
@@ -1186,6 +2640,7 @@ function createContextCoordinator(_deps) {
1186
2640
  let previewRecoveryUnavailable = false;
1187
2641
  let summaryDiagnostics = {};
1188
2642
  let summaryUsage;
2643
+ let summaryCallId;
1189
2644
  let plan;
1190
2645
  let campaign;
1191
2646
  try {
@@ -1253,8 +2708,11 @@ function createContextCoordinator(_deps) {
1253
2708
  const replacements = [];
1254
2709
  let prospectiveRequest = request;
1255
2710
  let prospectiveMeasurement = after;
1256
- for (const candidate of candidates) {
1257
- replacements.push(createL1Replacement(candidate));
2711
+ let batchEnd = input.trigger === "auto" ? 1 : candidates.length;
2712
+ while (replacements.length < candidates.length) {
2713
+ await setImmediate();
2714
+ controller.signal.throwIfAborted();
2715
+ for (const candidate of candidates.slice(replacements.length, batchEnd)) replacements.push(createL1Replacement(candidate));
1258
2716
  const prospective = {
1259
2717
  kind: "context-compacted",
1260
2718
  sessionId: deps.sessionId,
@@ -1277,6 +2735,7 @@ function createContextCoordinator(_deps) {
1277
2735
  prospectiveRequest = await input.assembleProjected(prospectiveProjection.messages);
1278
2736
  prospectiveMeasurement = inspect(input.port, prospectiveRequest);
1279
2737
  if (input.trigger === "auto" && belowTrigger(prospectiveMeasurement)) break;
2738
+ batchEnd = Math.min(candidates.length, batchEnd * 2);
1280
2739
  }
1281
2740
  if (replacements.length > 0 && prospectiveMeasurement.inputTokens < after.inputTokens) {
1282
2741
  await commitFact({
@@ -1323,26 +2782,33 @@ function createContextCoordinator(_deps) {
1323
2782
  })
1324
2783
  };
1325
2784
  }
1326
- const branch = [...deps.read()].reverse().find(({ event }) => event.kind === "history-rewound" || event.kind === "history-seeded");
2785
+ const campaignHistory = deps.read();
2786
+ const branch = campaignHistory.findLast(({ event }) => event.kind === "history-rewound" || event.kind === "history-seeded");
1327
2787
  const campaignIdentity = JSON.stringify([
1328
2788
  deps.sessionId,
1329
2789
  branch?.seq ?? -1,
1330
2790
  after.fingerprint,
1331
2791
  deps.model()
1332
2792
  ]);
1333
- const historyOperations = effectiveHistory(deps.read()).flatMap(({ event }) => event.kind === "context-operation" && event.campaignIdentity === campaignIdentity ? [event] : []);
2793
+ const historyOperations = effectiveHistory(campaignHistory).flatMap(({ event }) => event.kind === "context-operation" && event.campaignIdentity === campaignIdentity ? [event] : []);
2794
+ const completedCampaigns = new Set(campaignHistory.flatMap(({ event }) => event.kind === "context-compacted" && event.layer === "l2" ? [event.campaignId] : []));
1334
2795
  const lastCampaignEvent = historyOperations.at(-1);
1335
- const priorCampaign = deps.read().some(({ event }) => event.kind === "context-compacted" && event.layer === "l2" && event.campaignId === lastCampaignEvent?.campaignId) ? void 0 : lastCampaignEvent?.campaignId;
2796
+ const priorCampaign = completedCampaigns.has(lastCampaignEvent?.campaignId) ? void 0 : lastCampaignEvent?.campaignId;
1336
2797
  const campaignId = input.trigger === "manual" || priorCampaign === void 0 ? randomUUID() : priorCampaign;
1337
2798
  const campaignEvents = historyOperations.filter((one) => one.campaignId === campaignId);
2799
+ const terminalAttempts = new Map(campaignEvents.filter((one) => one.phase === "completed").map((one) => [one.attempt, one]));
2800
+ const compactedAttempts = /* @__PURE__ */ new Set();
2801
+ let completedChunks = 0;
2802
+ for (const { event } of campaignHistory) if (event.kind === "context-compacted" && event.campaignId === campaignId) {
2803
+ compactedAttempts.add(event.attempt);
2804
+ if (event.layer === "l2") completedChunks++;
2805
+ }
1338
2806
  let failures = campaignEvents.filter((one) => one.phase === "started").filter((started) => {
1339
- if (deps.read().some(({ event }) => event.kind === "context-compacted" && event.campaignId === campaignId && event.attempt === started.attempt)) return false;
1340
- const terminal = campaignEvents.findLast((one) => one.attempt === started.attempt && one.phase === "completed");
1341
- if (terminal !== void 0) return terminal.status === "failed";
1342
- return !deps.read().some(({ event }) => event.kind === "context-compacted" && event.campaignId === campaignId && event.attempt === started.attempt);
2807
+ if (compactedAttempts.has(started.attempt)) return false;
2808
+ const terminal = terminalAttempts.get(started.attempt);
2809
+ return terminal === void 0 || terminal.status === "failed";
1343
2810
  }).length;
1344
- let attempt = Math.max(0, ...campaignEvents.map((one) => one.attempt ?? 0));
1345
- let completedChunks = deps.read().filter(({ event }) => event.kind === "context-compacted" && event.layer === "l2" && event.campaignId === campaignId).length;
2811
+ let attempt = campaignEvents.reduce((maximum, one) => Math.max(maximum, one.attempt ?? 0), 0);
1346
2812
  campaign = {
1347
2813
  id: campaignId,
1348
2814
  identity: campaignIdentity,
@@ -1370,20 +2836,34 @@ function createContextCoordinator(_deps) {
1370
2836
  break;
1371
2837
  }
1372
2838
  const groups = plan.l2Groups.some((one) => !one.summarized) ? plan.l2Groups : plan.l2Groups.length > 1 ? plan.l2Groups : [];
1373
- const fullMeasurement = inspectContextRequest(summaryPort, {
1374
- ...createSummaryRequest(groups.flatMap((one) => one.messages), maxOutput),
1375
- sessionId: deps.sessionId
1376
- });
1377
- const selected = [];
1378
- if (hasKnownCapacity(fullMeasurement) && fullMeasurement.inputTokens <= fullMeasurement.inputBudget) selected.push(...groups);
1379
- else for (const group of groups) {
1380
- const counted = inspectContextRequest(summaryPort, {
1381
- ...createSummaryRequest([...selected, group].flatMap((one) => one.messages), maxOutput),
2839
+ let fitting = 0, oversized = groups.length + 1;
2840
+ let selectedRequest;
2841
+ const fitsPrefix = async (count) => {
2842
+ await setImmediate();
2843
+ controller.signal.throwIfAborted();
2844
+ const candidate = {
2845
+ ...createSummaryRequest(groups.slice(0, count).flatMap((one) => one.messages), maxOutput),
1382
2846
  sessionId: deps.sessionId
1383
- });
1384
- if (!hasKnownCapacity(counted) || counted.inputTokens > counted.inputBudget) break;
1385
- selected.push(group);
2847
+ };
2848
+ const counted = inspectContextRequest(summaryPort, candidate);
2849
+ if (!hasKnownCapacity(counted) || counted.inputTokens > counted.inputBudget) return false;
2850
+ selectedRequest = candidate;
2851
+ return true;
2852
+ };
2853
+ if (groups.length && await fitsPrefix(groups.length)) fitting = groups.length;
2854
+ else {
2855
+ oversized = groups.length;
2856
+ while (oversized - fitting > 8) {
2857
+ const count = Math.floor((fitting + oversized) / 2);
2858
+ if (await fitsPrefix(count)) fitting = count;
2859
+ else oversized = count;
2860
+ }
2861
+ for (let count = oversized - 1; count > fitting; count--) if (await fitsPrefix(count)) {
2862
+ fitting = count;
2863
+ break;
2864
+ }
1386
2865
  }
2866
+ const selected = groups.slice(0, fitting);
1387
2867
  if (selected.length === 0) {
1388
2868
  diagnostic = groups.length > 0 ? "summary_group_too_large" : void 0;
1389
2869
  break;
@@ -1412,14 +2892,20 @@ function createContextCoordinator(_deps) {
1412
2892
  events = [...deps.read()];
1413
2893
  const baseRevision = projectContext(events).revision;
1414
2894
  let summary;
2895
+ summaryCallId = randomUUID();
2896
+ if (active?.operationId === operationId) {
2897
+ active.phase = "summary";
2898
+ notify();
2899
+ }
1415
2900
  try {
1416
2901
  summary = await runContextSummary({
1417
2902
  framework: deps.framework,
1418
2903
  port: summaryPort,
1419
2904
  middleware: deps.middleware(),
1420
2905
  request: {
1421
- ...createSummaryRequest(selected.flatMap((one) => one.messages), maxOutput),
1422
- sessionId: deps.sessionId
2906
+ ...selectedRequest,
2907
+ sessionId: deps.sessionId,
2908
+ modelCallId: summaryCallId
1423
2909
  },
1424
2910
  signal: controller.signal
1425
2911
  });
@@ -1465,6 +2951,7 @@ function createContextCoordinator(_deps) {
1465
2951
  reason: diagnostic,
1466
2952
  summaryModel: actualSummaryModel() ?? deps.model(),
1467
2953
  usage: summaryUsage,
2954
+ modelCallId: summaryCallId,
1468
2955
  ...error instanceof ContextSummaryError ? error.diagnostics : {},
1469
2956
  startedAt: attemptStartedAt
1470
2957
  });
@@ -1511,6 +2998,7 @@ function createContextCoordinator(_deps) {
1511
2998
  after,
1512
2999
  reason: diagnostic,
1513
3000
  usage: summaryUsage,
3001
+ modelCallId: summaryCallId,
1514
3002
  ...summary.diagnostics,
1515
3003
  startedAt: attemptStartedAt
1516
3004
  });
@@ -1545,6 +3033,7 @@ function createContextCoordinator(_deps) {
1545
3033
  before,
1546
3034
  after,
1547
3035
  usage: summaryUsage,
3036
+ modelCallId: summaryCallId,
1548
3037
  summaryModel: actualSummaryModel() ?? deps.model(),
1549
3038
  ...summary.diagnostics,
1550
3039
  startedAt: attemptStartedAt
@@ -1598,6 +3087,7 @@ function createContextCoordinator(_deps) {
1598
3087
  reason: "cancelled",
1599
3088
  summaryModel: summaryUsage === void 0 ? void 0 : actualSummaryModel() ?? deps.model(),
1600
3089
  usage: summaryUsage,
3090
+ modelCallId: summaryCallId,
1601
3091
  startedAt
1602
3092
  })
1603
3093
  };
@@ -1621,6 +3111,61 @@ function createContextCoordinator(_deps) {
1621
3111
  summaryModel: () => used
1622
3112
  };
1623
3113
  }
3114
+ const resultMeter = (port) => {
3115
+ const request = (text) => ({ messages: [{
3116
+ id: "00000000-0000-4000-8000-000000000000",
3117
+ role: "user",
3118
+ content: [{
3119
+ type: "text",
3120
+ text
3121
+ }]
3122
+ }] });
3123
+ const meter = fragmentMeter(port, request(""), "tool-result");
3124
+ const base = meter.baseline.inputTokens;
3125
+ return (result) => {
3126
+ const text = typeof result === "string" ? result : JSON.stringify(typeof result === "object" && result !== null && "files" in result ? {
3127
+ ...result,
3128
+ files: void 0
3129
+ } : result);
3130
+ const measured = meter.measure(text, () => request(text)) - base;
3131
+ return measured > 0 ? measured : Buffer.byteLength(text);
3132
+ };
3133
+ };
3134
+ const toolOutputPolicy = () => {
3135
+ if (!measurement || measurement.inputBudget === void 0) return void 0;
3136
+ const port = deps.port();
3137
+ const measure = resultMeter(port);
3138
+ const catalogueMeter = fragmentMeter(port, {
3139
+ messages: [],
3140
+ tools: []
3141
+ }, "catalogue");
3142
+ const measureCatalog = (value) => {
3143
+ const definitions = Array.isArray(value) ? value : [value];
3144
+ if (!definitions.length) return 0;
3145
+ const cost = catalogueMeter.measure(JSON.stringify(definitions), () => ({
3146
+ messages: [],
3147
+ tools: definitions
3148
+ })) - catalogueMeter.baseline.inputTokens;
3149
+ return cost > 0 ? cost : Buffer.byteLength(JSON.stringify(definitions));
3150
+ };
3151
+ return {
3152
+ defaultTokens: TOOL_PREVIEW_POLICY.defaultTokens,
3153
+ maximumTokens: TOOL_PREVIEW_POLICY.maximumTokens,
3154
+ stepTokens: Math.max(0, Math.min(TOOL_PREVIEW_POLICY.stepTokens, Math.floor(measurement.inputBudget * TOOL_PREVIEW_POLICY.stepFraction), measurement.inputBudget - measurement.inputTokens)),
3155
+ maximumCalls: 64,
3156
+ requestTokens: measurement.inputBudget,
3157
+ catalog: {
3158
+ tokens: Math.min(2e4, Math.floor(measurement.inputBudget * .2)),
3159
+ dynamicTokens: Math.max(0, Math.min(6e3, Math.floor(measurement.inputBudget * .1), Math.min(2e4, Math.floor(measurement.inputBudget * .2)) - fixedCatalogTokens)),
3160
+ definitionTokens: 4e3,
3161
+ measure: measureCatalog
3162
+ },
3163
+ sourceBytes: 4194304,
3164
+ stepSourceBytes: 16777216,
3165
+ encodedSourceBytes: 8388608,
3166
+ measure
3167
+ };
3168
+ };
1624
3169
  restore();
1625
3170
  return {
1626
3171
  async prepare(ctx, assembleProjected) {
@@ -1631,6 +3176,14 @@ function createContextCoordinator(_deps) {
1631
3176
  if (request.purpose === "summary") return request;
1632
3177
  const before = prepared.after;
1633
3178
  measurement = before;
3179
+ const catalog = toolOutputPolicy()?.catalog;
3180
+ if (catalog && request.tools) {
3181
+ fixedCatalogTokens = catalog.measure(request.tools.filter((tool) => tool.catalogKind !== "dynamic"));
3182
+ if (catalog.measure(request.tools) > catalog.tokens) throw new Error("catalog_too_large");
3183
+ const dynamic = request.tools.filter((tool) => tool.catalogKind === "dynamic");
3184
+ if (dynamic.some((tool) => catalog.measure(tool) > catalog.definitionTokens)) throw new Error("tool_schema_too_large");
3185
+ if (catalog.measure(dynamic) > catalog.dynamicTokens) throw new Error("catalog_too_large");
3186
+ }
1634
3187
  measurementEventCount = deps.read().length;
1635
3188
  diagnostic = hasKnownCapacity(before) ? void 0 : "capacity_unknown";
1636
3189
  notify();
@@ -1646,7 +3199,7 @@ function createContextCoordinator(_deps) {
1646
3199
  });
1647
3200
  if (reduced.result.status === "cancelled") throw new DOMException("context preparation cancelled", "AbortError");
1648
3201
  const finalMeasurement = inspect(port, reduced.request);
1649
- if (finalMeasurement.inputBudget !== void 0 && finalMeasurement.inputTokens > finalMeasurement.inputBudget) throw new Error(reduced.result.reason ?? "context preparation failed");
3202
+ if (finalMeasurement.inputBudget !== void 0 && finalMeasurement.inputTokens > finalMeasurement.inputBudget) throw new Error(reduced.request.requestFailure ? `${reduced.request.requestFailure.code}: ${reduced.request.requestFailure.message.slice(0, 256)}` : reduced.result.reason ?? "context preparation failed");
1650
3203
  return reduced.request;
1651
3204
  },
1652
3205
  async compact(assembleProjected, signal) {
@@ -1664,7 +3217,8 @@ function createContextCoordinator(_deps) {
1664
3217
  },
1665
3218
  status(normalTokens) {
1666
3219
  const raw = deps.read();
1667
- const events = normalTokens === void 0 ? deps.framework.history(raw) : raw;
3220
+ const events = raw;
3221
+ const usage = usageAccumulator.read(raw);
1668
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);
1669
3223
  const latestInput = events.findLast(({ seq, event }) => seq > (deps.usageStartSeq ?? -1) && event.kind === "message-appended" && event.usage)?.event;
1670
3224
  const latestReported = latestInput?.kind === "message-appended" ? latestInput.usage?.inputTokens : void 0;
@@ -1673,14 +3227,24 @@ function createContextCoordinator(_deps) {
1673
3227
  const projection = projectContext(events);
1674
3228
  const lastResult = latestResult(events);
1675
3229
  return {
3230
+ usage,
3231
+ ...observation ? { observation: {
3232
+ identity: observation,
3233
+ source: reported === void 0 ? "estimated" : "reported",
3234
+ freshness: historical ? "historical" : "current"
3235
+ } } : {},
3236
+ ...measurementIdentity === void 0 ? {} : { measurementIdentity },
1676
3237
  revision: projection.revision,
1677
3238
  ...measurement === void 0 ? {} : { measurement },
1678
- ...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) },
1679
3240
  ...anchor === void 0 || normalTokens === void 0 && anchor.reported !== latestReported ? {} : { actualInputTokens: anchor.reported },
1680
3241
  auxiliaryTokens: auxiliary,
1681
3242
  totalTokens: (normalTokens ?? committedTokens) + auxiliary,
1682
3243
  ...active === void 0 ? {} : { operation: {
1683
3244
  operationId: active.operationId,
3245
+ phase: active.phase,
3246
+ target: active.target,
3247
+ elapsedMs: Math.max(0, Math.floor(performance.now() - active.monotonicStart)),
1684
3248
  trigger: active.trigger,
1685
3249
  startedAt: active.startedAt,
1686
3250
  completedChunks: active.completedChunks
@@ -1696,33 +3260,86 @@ function createContextCoordinator(_deps) {
1696
3260
  ...diagnostic === void 0 ? {} : { diagnostic }
1697
3261
  };
1698
3262
  },
3263
+ contributionAllowance() {
3264
+ const port = deps.port();
3265
+ const probe = (text) => ({ messages: [{
3266
+ id: "00000000-0000-4000-8000-000000000000",
3267
+ role: "user",
3268
+ content: [{
3269
+ type: "text",
3270
+ text
3271
+ }]
3272
+ }] });
3273
+ let meter;
3274
+ const current = () => meter ??= fragmentMeter(port, probe(""));
3275
+ const measuredCapacity = measurement?.inputBudget;
3276
+ let capacity;
3277
+ const available = () => capacity ??= measuredCapacity ?? current().baseline.inputBudget ?? 0;
3278
+ return {
3279
+ get tokens() {
3280
+ return Math.max(0, Math.min(2e3, Math.floor(available() * .02)));
3281
+ },
3282
+ get maximumTokens() {
3283
+ return Math.max(0, Math.min(8e3, 12e3, Math.floor(available() * .2)));
3284
+ },
3285
+ get requestTokens() {
3286
+ return available();
3287
+ },
3288
+ measure(text) {
3289
+ const meter = current();
3290
+ const initial = meter.baseline;
3291
+ const delta = meter.measure(text, () => probe(text)) - initial.inputTokens;
3292
+ return delta > 0 ? delta : Buffer.byteLength(text);
3293
+ }
3294
+ };
3295
+ },
3296
+ queryResourcePolicy() {
3297
+ return {
3298
+ queryBytes: 33554432,
3299
+ sessionBytes: 67108864,
3300
+ residentBytes: 268435456,
3301
+ sessionQueries: 64,
3302
+ queryScratchBytes: 33554432,
3303
+ sessionScratchBytes: 67108864,
3304
+ residentScratchBytes: 134217728
3305
+ };
3306
+ },
1699
3307
  restoreAllowance() {
1700
3308
  if (measurement?.inputBudget === void 0) return 0;
1701
3309
  const pendingMessages = deps.read().slice(measurementEventCount).flatMap(({ event }) => event.kind === "message-appended" ? [event.message] : []);
1702
- const pendingTokens = deps.measureText?.(JSON.stringify(JSON.stringify(pendingMessages)));
1703
- if (pendingTokens === void 0) return 0;
3310
+ const pendingTokens = toolOutputPolicy()?.measure(pendingMessages) ?? Buffer.byteLength(JSON.stringify(pendingMessages));
1704
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));
1705
3312
  },
1706
- observe(value, shown) {
3313
+ toolOutputPolicy,
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;
1707
3318
  measurement = value;
3319
+ measurementIdentity = deps.measurementIdentity?.();
1708
3320
  split = shown?.split;
1709
3321
  displayed = shown?.displayTokens ?? value.inputTokens;
1710
3322
  reported = void 0;
1711
- save();
1712
- measurementEventCount = deps.read().length;
3323
+ const events = deps.read();
3324
+ if (deps.saved !== void 0) save(events, projectContext(events).revision);
3325
+ measurementEventCount = events.length;
1713
3326
  diagnostic = value.inputBudget === void 0 ? "capacity_unknown" : void 0;
1714
3327
  notify();
1715
3328
  },
1716
- observeReported(inputTokens) {
1717
- 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;
1718
3334
  reported = inputTokens;
1719
3335
  anchor = {
3336
+ viewIdentity: viewIdentity(events, revision),
1720
3337
  reported: inputTokens,
1721
3338
  estimate: displayed,
1722
3339
  fingerprint: measurement.fingerprint,
1723
- revision: projectContext(deps.read()).revision
3340
+ revision
1724
3341
  };
1725
- save();
3342
+ save(events, revision);
1726
3343
  notify();
1727
3344
  },
1728
3345
  get activeOperation() {
@@ -1735,11 +3352,39 @@ function createContextCoordinator(_deps) {
1735
3352
  }
1736
3353
  //#endregion
1737
3354
  //#region src/runtime/factory.ts
3355
+ /** Activated context maintenance and display policy over generic Agent session inputs. */
1738
3356
  /** Owns persisted readings and stops admitting maintenance after withdrawal. */
1739
3357
  function createContextRuntime(ctx, framework) {
1740
3358
  const readings = createSessionContextRowsOn(ctx.storage.open());
1741
3359
  const snapshots = createSessionStatusRows(ctx.storage.open());
3360
+ const inspections = createInspectionCache({
3361
+ signal: ctx.signal,
3362
+ performance: ctx.performance
3363
+ });
1742
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
+ });
1743
3388
  const policies = /* @__PURE__ */ new Map();
1744
3389
  const changed = ctx.client.registerFrame({
1745
3390
  name: "statusChanged",
@@ -1747,6 +3392,19 @@ function createContextRuntime(ctx, framework) {
1747
3392
  payload: z.strictObject({})
1748
3393
  });
1749
3394
  const active = /* @__PURE__ */ new Set();
3395
+ function inspect(port, request) {
3396
+ const started = ctx.performance?.now();
3397
+ try {
3398
+ return inspectContextRequest(port, request);
3399
+ } finally {
3400
+ ctx.performance?.observe({
3401
+ stage: "model.inspect",
3402
+ measurementPurpose: "request",
3403
+ durationMs: ctx.performance.now() - started,
3404
+ count: 1
3405
+ });
3406
+ }
3407
+ }
1750
3408
  ctx.signal.addEventListener("abort", () => {
1751
3409
  for (const policy of active) if (policy.activeOperation) policy.cancel(policy.activeOperation.operationId);
1752
3410
  active.clear();
@@ -1759,55 +3417,120 @@ function createContextRuntime(ctx, framework) {
1759
3417
  try {
1760
3418
  const before = control.source(sessionId);
1761
3419
  if (before.historyGeneration !== one.historyGeneration) return;
1762
- const status = one.policy.status();
3420
+ const status = ordered(one.policy.status(), before);
3421
+ if (status.measurementIdentity !== before.measurementIdentity) return;
1763
3422
  const after = control.source(sessionId);
1764
3423
  if (before.sourceSeq !== after.sourceSeq || before.historyGeneration !== after.historyGeneration) return;
1765
3424
  snapshots.put(sessionId, before.sourceSeq, before.historyGeneration, status);
1766
3425
  one.status = status;
1767
3426
  one.sourceSeq = before.sourceSeq;
1768
3427
  } catch (error) {
1769
- console.error(`context status not saved: ${error instanceof Error ? error.message : error}`);
3428
+ ctx.log.emit({
3429
+ level: "error",
3430
+ event: "plugin.event",
3431
+ fields: { localCode: "CONTEXT_STATUS_SAVE_FAILED" }
3432
+ });
1770
3433
  }
1771
3434
  }
1772
3435
  ctx.events.on((event) => {
1773
3436
  if (event.kind === "message-appended" || event.kind === "turn-ended" || event.kind === "context-compacted" || event.kind === "context-operation") capture(event.sessionId);
1774
3437
  });
1775
3438
  return {
1776
- assertRequest(inspection) {
3439
+ assertRequest(inspection, request) {
3440
+ const catalog = request?.sessionId ? policies.get(request.sessionId)?.policy.toolOutputPolicy()?.catalog : void 0;
3441
+ if (catalog && request?.tools) {
3442
+ if (catalog.measure(request.tools) > catalog.tokens) throw contextLimitFailure();
3443
+ const dynamic = request.tools.filter((tool) => tool.catalogKind === "dynamic");
3444
+ if (dynamic.some((tool) => catalog.measure(tool) > catalog.definitionTokens)) throw contextLimitFailure();
3445
+ if (catalog.measure(dynamic) > catalog.dynamicTokens) throw contextLimitFailure();
3446
+ }
1777
3447
  const budget = safeInputBudget(inspection);
1778
- if (budget !== void 0 && inspection.inputTokens > budget) throw new Error(`context request exceeds its safe input budget (${inspection.inputTokens} > ${budget})`);
3448
+ if (budget !== void 0 && inspection.inputTokens > budget) throw contextLimitFailure();
1779
3449
  },
1780
3450
  assertSwitch(port, request, hasHistory) {
1781
- if (hasHistory && inspectContextRequest(port, request).inputBudget === void 0) throw new Error("capacity_unknown: configure the target context window before switching");
3451
+ if (hasHistory && inspect(port, request).capacitySource === "assumed") throw new Error("capacity_unknown: configure the target context window before switching");
1782
3452
  },
1783
- status(sessionId) {
3453
+ status(sessionId, maxBytes = 524288) {
1784
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
+ };
1785
3459
  const one = policies.get(sessionId);
1786
3460
  const source = control.source(sessionId);
1787
- if (one?.status && one.sourceSeq === source.sourceSeq && one.historyGeneration === source.historyGeneration) return one.status;
1788
- const saved = snapshots.get(sessionId);
1789
- if (saved?.sourceSeq === source.sourceSeq && saved.historyGeneration === source.historyGeneration) return saved.status;
3461
+ if (one?.status && one.sourceSeq === source.sourceSeq && one.status.measurementIdentity === source.measurementIdentity && one.historyGeneration === source.historyGeneration) {
3462
+ if (Buffer.byteLength(JSON.stringify(one.status)) > maxBytes) throw new Error("read-limit: status exceeds member body capacity");
3463
+ return one.status;
3464
+ }
3465
+ const saved = snapshots.get(sessionId, maxBytes);
3466
+ if (saved?.sourceSeq === source.sourceSeq && saved.status.measurementIdentity === source.measurementIdentity && saved.historyGeneration === source.historyGeneration) return bounded(ordered(saved.status, source, true));
1790
3467
  const facts = control.reading(sessionId);
1791
- return {
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;
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");
3470
+ return bounded(ordered({
3471
+ ...compatible || !observed?.measurement || !observed.occupancy ? {} : { lastObservation: {
3472
+ measurement: observed.measurement,
3473
+ occupancy: observed.occupancy,
3474
+ ...observed.actualInputTokens === void 0 ? {} : { actualInputTokens: observed.actualInputTokens }
3475
+ } },
3476
+ ...compatible ?? {},
1792
3477
  revision: facts.revision,
1793
3478
  auxiliaryTokens: facts.auxiliaryTokens,
1794
- totalTokens: facts.normalTokens + facts.auxiliaryTokens
1795
- };
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));
1796
3488
  },
1797
3489
  acceptsPreviewHint: (tokens) => Number.isInteger(tokens) && tokens >= 1 && tokens <= TOOL_PREVIEW_POLICY.maximumTokens,
1798
3490
  create(session) {
1799
3491
  ctx.signal.throwIfAborted();
1800
3492
  const policy = createContextCoordinator({
3493
+ log: ctx.log,
3494
+ performance: ctx.performance,
3495
+ inspections,
3496
+ inspectionScope: () => {
3497
+ const source = control.source(session.sessionId);
3498
+ return JSON.stringify([source.measurementIdentity, source.historyGeneration]);
3499
+ },
3500
+ measurementIdentity: () => control.source(session.sessionId).measurementIdentity,
3501
+ historyGeneration: () => control.source(session.sessionId).historyGeneration,
1801
3502
  ...session,
1802
3503
  framework,
1803
3504
  onStatusChanged() {
1804
3505
  ctx.signal.throwIfAborted();
1805
3506
  capture(session.sessionId);
1806
- changed.emit(session.sessionId, {});
1807
- session.onStatusChanged?.();
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
+ }
1808
3517
  },
1809
- commit: (event, signal) => {
3518
+ commit: async (event, signal) => {
1810
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
+ }
1811
3534
  return session.commit(event, signal ? AbortSignal.any([signal, ctx.signal]) : ctx.signal);
1812
3535
  },
1813
3536
  saved: {
@@ -1825,20 +3548,25 @@ function createContextRuntime(ctx, framework) {
1825
3548
  session,
1826
3549
  policy,
1827
3550
  historyGeneration: source.historyGeneration,
1828
- ...saved?.sourceSeq === source.sourceSeq && saved.historyGeneration === source.historyGeneration ? {
1829
- status: saved.status,
3551
+ ...saved?.sourceSeq === source.sourceSeq && saved.status.measurementIdentity === source.measurementIdentity && saved.historyGeneration === source.historyGeneration ? {
3552
+ status: ordered(saved.status, source, true),
1830
3553
  sourceSeq: source.sourceSeq
1831
3554
  } : {}
1832
3555
  });
1833
3556
  changed.emit(session.sessionId, {});
1834
3557
  return {
1835
3558
  ...policy,
1836
- prepare(exec, assemble) {
3559
+ async prepare(exec, assemble) {
1837
3560
  ctx.signal.throwIfAborted();
1838
- return policy.prepare({
1839
- ...exec,
1840
- signal: AbortSignal.any([exec.signal, ctx.signal])
1841
- }, assemble);
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
+ }
1842
3570
  },
1843
3571
  compact(assemble, signal) {
1844
3572
  ctx.signal.throwIfAborted();
@@ -1850,16 +3578,31 @@ function createContextRuntime(ctx, framework) {
1850
3578
  };
1851
3579
  },
1852
3580
  measurement: contextMeasurement,
1853
- inspect: inspectContextRequest,
3581
+ inspect,
1854
3582
  budget: safeInputBudget,
1855
3583
  async shown(request, inputTokens, deps, signal) {
1856
3584
  ctx.signal.throwIfAborted();
1857
- const displayTokens = await displayTokensOf(request, AbortSignal.any([signal, ctx.signal]), deps.measureDisplay);
1858
- ctx.signal.throwIfAborted();
1859
- return {
1860
- split: rawBreakdown(request, inputTokens, deps),
1861
- displayTokens
1862
- };
3585
+ const started = ctx.performance?.now();
3586
+ let outcome = "ok";
3587
+ try {
3588
+ const displayTokens = inputTokens;
3589
+ ctx.signal.throwIfAborted();
3590
+ return {
3591
+ split: await rawBreakdown(request, inputTokens, deps, { signal: AbortSignal.any([signal, ctx.signal]) }),
3592
+ displayTokens
3593
+ };
3594
+ } catch (error) {
3595
+ outcome = signal.aborted || ctx.signal.aborted ? "cancelled" : "error";
3596
+ throw error;
3597
+ } finally {
3598
+ ctx.performance?.observe({
3599
+ stage: "model.display",
3600
+ measurementPurpose: "display",
3601
+ durationMs: ctx.performance.now() - started,
3602
+ count: 1,
3603
+ outcome
3604
+ });
3605
+ }
1863
3606
  }
1864
3607
  };
1865
3608
  }
@@ -1877,13 +3620,77 @@ const historyPolicy = {
1877
3620
  };
1878
3621
  //#endregion
1879
3622
  //#region src/runtime/methods.ts
3623
+ /** Each session status has an independent declared envelope budget. */
3624
+ const ContextStatusesParams = z.strictObject({
3625
+ sessionIds: z.array(z.string().min(1)).min(1).max(64),
3626
+ maxItemBytes: z.number().int().min(1).max(8388608).default(262144),
3627
+ maxTotalBytes: z.number().int().min(1).max(8388608).default(8388608)
3628
+ }).refine((input) => Buffer.byteLength(JSON.stringify(input)) <= 8388608, "batch-limit: status input exceeds 8 MiB");
3629
+ /** Ordered status members retain their target identity, including missing sessions. */
3630
+ const ContextStatusesResult = z.strictObject({ results: z.array(z.discriminatedUnion("ok", [z.strictObject({
3631
+ index: z.number().int().nonnegative(),
3632
+ target: z.string(),
3633
+ ok: z.literal(true),
3634
+ value: SessionContextStatus.nullable()
3635
+ }), z.strictObject({
3636
+ index: z.number().int().nonnegative(),
3637
+ target: z.string(),
3638
+ ok: z.literal(false),
3639
+ error: z.strictObject({
3640
+ code: z.string(),
3641
+ message: z.string()
3642
+ })
3643
+ })])).max(64) });
1880
3644
  /** Reuses framework exclusivity and cancellation while retaining policy ownership. */
1881
3645
  function registerContextMethods(ctx, runtime) {
1882
3646
  ctx.client.registerMethod({
1883
- name: "status",
1884
- params: z.strictObject({ sessionId: z.string().min(1) }),
1885
- result: SessionContextStatus,
1886
- handle: ({ sessionId }) => runtime.status(sessionId)
3647
+ name: "statuses",
3648
+ params: ContextStatusesParams,
3649
+ result: ContextStatusesResult,
3650
+ handle: (raw) => {
3651
+ const input = ContextStatusesParams.parse(raw);
3652
+ ctx.signal.throwIfAborted();
3653
+ if (input.sessionIds.length * input.maxItemBytes + 8192 > input.maxTotalBytes) throw new Error("batch-limit: declared status budgets exceed collection capacity");
3654
+ const encode = (value) => Buffer.byteLength(JSON.stringify(value));
3655
+ const failures = input.sessionIds.map((target, index) => ({
3656
+ index,
3657
+ target,
3658
+ ok: false,
3659
+ error: {
3660
+ code: "read-limit",
3661
+ message: "Status exceeds its declared member budget"
3662
+ }
3663
+ }));
3664
+ if (failures.some((one) => encode(one) > input.maxItemBytes)) throw new Error("batch-limit: status metadata exceeds member capacity");
3665
+ const known = ctx.services.get("session-context").existsMany(input.sessionIds);
3666
+ if (known.length !== input.sessionIds.length) throw new Error("Invalid session metadata cardinality");
3667
+ return { results: input.sessionIds.map((target, index) => {
3668
+ try {
3669
+ const metadata = encode({
3670
+ index,
3671
+ target,
3672
+ ok: true,
3673
+ value: null
3674
+ });
3675
+ const result = {
3676
+ index,
3677
+ target,
3678
+ ok: true,
3679
+ value: known[index] ? runtime.status(target, input.maxItemBytes - metadata) : null
3680
+ };
3681
+ return encode(result) <= input.maxItemBytes ? result : failures[index];
3682
+ } catch (error) {
3683
+ ctx.signal.throwIfAborted();
3684
+ return {
3685
+ ...failures[index],
3686
+ error: {
3687
+ code: "read-limit",
3688
+ message: error instanceof Error ? error.message.slice(0, 64) : "Status read failed"
3689
+ }
3690
+ };
3691
+ }
3692
+ }) };
3693
+ }
1887
3694
  });
1888
3695
  const control = ctx.services.get("agent-context-control");
1889
3696
  ctx.client.registerMethod({
@@ -1910,16 +3717,50 @@ function registerContextMethods(ctx, runtime) {
1910
3717
  /** The service key, restated here because the host that publishes it
1911
3718
  * cannot import this package. */
1912
3719
  const SESSION_NOTES_SERVICE = "session-notes";
1913
- const SessionNoteInput = z.strictObject({
1914
- title: z.string().optional().describe("What this session is about, in at most 60 characters."),
1915
- digest: z.string().optional().describe("What this session is doing: the goal, what is settled, what is in progress and what is next. At most 2000 characters; it replaces the previous digest whole.")
1916
- }).superRefine((input, issues) => {
1917
- if (input.title === void 0 && input.digest === void 0) issues.addIssue({
1918
- code: "custom",
1919
- path: ["title"],
1920
- message: "give a title, a digest, or both"
1921
- });
1922
- });
3720
+ /** Publishes a code-point bound and rejects it without copying an oversized input. */
3721
+ function boundedText(maximum, description) {
3722
+ return z.string().superRefine((text, ctx) => {
3723
+ let count = 0;
3724
+ for (const _point of text) if (++count > maximum) {
3725
+ ctx.addIssue({
3726
+ code: "too_big",
3727
+ origin: "string",
3728
+ maximum,
3729
+ inclusive: true,
3730
+ message: `At most ${maximum} Unicode code points are allowed.`
3731
+ });
3732
+ break;
3733
+ }
3734
+ }).meta({ maxLength: maximum }).describe(description);
3735
+ }
3736
+ const Title = boundedText(60, "Topic title, at most 60 Unicode code points; the service trims surrounding whitespace.");
3737
+ const Digest = boundedText(2e3, "Complete replacement digest, at most 2000 Unicode code points: goal, decisions, progress and next steps.");
3738
+ const Tokens = z.number().int().positive().optional().describe("Desired output tokens; the host may allocate less without changing which fields are written.");
3739
+ /** At least one business field is required; constraints are present in the model-visible schema. */
3740
+ const SessionNoteInput = z.union([z.strictObject({
3741
+ title: Title,
3742
+ digest: Digest.optional(),
3743
+ outputTokens: Tokens
3744
+ }), z.strictObject({
3745
+ title: Title.optional(),
3746
+ digest: Digest,
3747
+ outputTokens: Tokens
3748
+ })]);
3749
+ /** Short ordinary receipts and their historical retained-preview projection. */
3750
+ const SessionNoteOutput = z.union([z.string().max(2048), z.strictObject({
3751
+ ok: z.literal(true),
3752
+ complete: z.literal(false),
3753
+ preview: z.string(),
3754
+ source: z.strictObject({
3755
+ ref: z.string(),
3756
+ sourceComplete: z.boolean(),
3757
+ recoverable: z.literal(true)
3758
+ }),
3759
+ next: z.strictObject({
3760
+ tool: z.literal("context_restore"),
3761
+ arguments: z.strictObject({ pages: z.array(z.strictObject({ ref: z.string() })) })
3762
+ })
3763
+ })]);
1923
3764
  /** What leads the injected digest. It arrives unasked, so it says what it is. */
1924
3765
  const INJECTED_DIGEST_PREFIX = "Your digest of this session, as you last wrote it:\n";
1925
3766
  /** The `volatile` contributor, id `session-digest`: nothing at all while the
@@ -1941,8 +3782,11 @@ function registerSessionTools(ctx, register) {
1941
3782
  const notes = ctx.services.get(SESSION_NOTES_SERVICE);
1942
3783
  register({
1943
3784
  name: "session_note",
3785
+ preload: false,
1944
3786
  description: "Write your notes on this session. `title` sets the topic title: a short phrase saying what the conversation is about, shown in the session list; set it once the topic is clear and again when the topic changes. It never replaces the name the person gave the session. `digest` replaces your digest of this session: what it is for, what is settled, what is in progress and what comes next. You are shown it on every step, so keep it current when the work reaches a milestone or changes direction. Give either or both; each is written on its own.",
1945
3787
  inputSchema: SessionNoteInput,
3788
+ outputSchema: SessionNoteOutput,
3789
+ deliveryKind: "receipt",
1946
3790
  async execute(input, call) {
1947
3791
  const lines = [];
1948
3792
  let failed = false;
@@ -2032,7 +3876,9 @@ const timeContributor = {
2032
3876
  const TOOL_NAMES = [
2033
3877
  "context_search",
2034
3878
  "context_restore",
2035
- "session_note"
3879
+ "session_note",
3880
+ "tool_search",
3881
+ "tool_call"
2036
3882
  ];
2037
3883
  //#endregion
2038
3884
  //#region src/index.ts
@@ -2044,14 +3890,18 @@ const TOOL_NAMES = [
2044
3890
  * enumerated: a misspelled tool name is a load failure naming the field, not
2045
3891
  * a line that quietly does nothing.
2046
3892
  */
2047
- const ContextConfig = z.strictObject({ disabled: z.array(z.enum(TOOL_NAMES)).default([]) }).default({ disabled: [] });
3893
+ const ContextConfig = z.strictObject({ disabled: z.array(z.enum(TOOL_NAMES.filter((name) => name !== "tool_search" && name !== "tool_call"))).default([]) }).default({ disabled: [] });
2048
3894
  const contextPlugin = {
2049
3895
  name: "@eum-agent/context-management",
2050
3896
  requires: [
3897
+ "agent-configuration-store",
2051
3898
  "context-framework",
3899
+ "query-resources",
2052
3900
  "session-context-history",
2053
3901
  "session-notes",
2054
- "agent-context-control"
3902
+ "agent-context-control",
3903
+ "owner-session-context",
3904
+ "session-context"
2055
3905
  ],
2056
3906
  provides: [
2057
3907
  "context-runtime",
@@ -2073,6 +3923,9 @@ const contextPlugin = {
2073
3923
  ctx.services.provide("context-runtime", runtime);
2074
3924
  const disabled = new Set(config.disabled);
2075
3925
  const register = (tool) => disabled.has(tool.name) ? void 0 : ctx.tools.register(tool);
3926
+ ctx.tools.register(toolSearch(ctx));
3927
+ ctx.tools.register(toolCall());
3928
+ registerToolPreload(ctx);
2076
3929
  registerContextTools(ctx, register);
2077
3930
  registerSessionTools(ctx, register);
2078
3931
  ctx.context.contribute(timeContributor);