@eum-agent/context-management 1.0.0 → 1.0.1

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 +1655 -164
  2. package/package.json +5 -5
  3. package/ui/ui.js +123 -40
package/dist/index.js CHANGED
@@ -2,53 +2,900 @@ import { existsSync } from "node:fs";
2
2
  import { fileURLToPath } from "node:url";
3
3
  import { z } from "zod";
4
4
  import { 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.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.")
423
+ });
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
12
427
  });
13
- /** Reads a Unicode-code-point page from an opaque current-session reference. */
14
- const ContextRestoreInput = z.strictObject({
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")])
467
+ });
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
+ })])
18
479
  });
19
- /** Offers the two independently configurable tools backed by host-owned history. */
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,7 +972,13 @@ 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();
123
984
  const SplitSchema = z.object({
@@ -138,6 +999,8 @@ const SplitSchema = z.object({
138
999
  });
139
1000
  /** Everything the coordinator needs to show a reading again after a restart. */
140
1001
  const ReadingSchema = z.object({
1002
+ /** Model/parameter identity; a mismatching reading is never restored. */
1003
+ measurementIdentity: z.string().optional(),
141
1004
  measurement: ContextMeasurementSchema,
142
1005
  split: SplitSchema.optional(),
143
1006
  displayed: count,
@@ -228,9 +1091,17 @@ const ContextOccupancy = z.object({
228
1091
  });
229
1092
  /** Live request measurements and durable preparation totals for one session. */
230
1093
  const SessionContextStatus = z.object({
1094
+ /** Committed model and parameter identity of this observation, never raw settings. */
1095
+ measurementIdentity: z.string().optional(),
231
1096
  revision: z.number().int().nonnegative(),
232
1097
  measurement: ContextMeasurementSchema.optional(),
233
1098
  occupancy: ContextOccupancy.optional(),
1099
+ /** Display-only observation from this history generation, not validated for current settings. */
1100
+ lastObservation: z.object({
1101
+ measurement: ContextMeasurementSchema,
1102
+ occupancy: ContextOccupancy,
1103
+ actualInputTokens: z.number().int().nonnegative().optional()
1104
+ }).optional(),
234
1105
  actualInputTokens: z.number().int().nonnegative().optional(),
235
1106
  auxiliaryTokens: z.number().int().nonnegative(),
236
1107
  totalTokens: z.number().int().nonnegative(),
@@ -264,14 +1135,19 @@ function createSessionStatusRows(storage) {
264
1135
  ) STRICT`);
265
1136
  const get = storage.db.prepare(`SELECT source_seq, history_generation,
266
1137
  CASE WHEN length(CAST(status AS BLOB)) <= ${MAX_STATUS_BYTES} THEN status ELSE NULL END AS status
1138
+ FROM ${table} WHERE session_id = ?`);
1139
+ const limited = storage.db.prepare(`SELECT source_seq, history_generation,
1140
+ length(CAST(status AS BLOB)) AS bytes,
1141
+ CASE WHEN length(CAST(status AS BLOB)) <= min(?, ${MAX_STATUS_BYTES}) THEN status ELSE NULL END AS status
267
1142
  FROM ${table} WHERE session_id = ?`);
268
1143
  const put = storage.db.prepare(`INSERT INTO ${table}
269
1144
  (session_id, source_seq, history_generation, status) VALUES (?, ?, ?, ?)
270
1145
  ON CONFLICT(session_id) DO UPDATE SET source_seq = excluded.source_seq,
271
1146
  history_generation = excluded.history_generation, status = excluded.status`);
272
1147
  return {
273
- get(sessionId) {
274
- const row = get.get(sessionId);
1148
+ get(sessionId, maxBytes) {
1149
+ const row = maxBytes === void 0 ? get.get(sessionId) : limited.get(maxBytes, sessionId);
1150
+ if (row && maxBytes !== void 0 && row.bytes !== void 0 && row.bytes > maxBytes) throw new Error("read-limit: saved status exceeds member body capacity");
275
1151
  if (!row || row.status === null) return void 0;
276
1152
  try {
277
1153
  const status = SessionContextStatus.safeParse(JSON.parse(row.status));
@@ -294,6 +1170,7 @@ function createSessionStatusRows(storage) {
294
1170
  }
295
1171
  //#endregion
296
1172
  //#region src/runtime/breakdown.ts
1173
+ /** Splits a request's context into the categories a person reads. */
297
1174
  const referencedFiles = (request) => {
298
1175
  const files = /* @__PURE__ */ new Map();
299
1176
  for (const message of request.messages) for (const part of message.content) {
@@ -358,8 +1235,8 @@ function occupancyOf(total, source, raw) {
358
1235
  }))
359
1236
  };
360
1237
  }
361
- /** Splits the final request into category bytes; `inputTokens` is its measured size. */
362
- function rawBreakdown(request, inputTokens, deps) {
1238
+ /** Aggregates category weights after the caller has counted the unchanged messages. */
1239
+ function categoryBreakdown(request, inputTokens, deps, messageBytes) {
363
1240
  const system = request.system ?? [];
364
1241
  const systemBytes = bytesOf(system);
365
1242
  const recorded = deps.systemParts(system);
@@ -382,7 +1259,7 @@ function rawBreakdown(request, inputTokens, deps) {
382
1259
  const volatile = bytesOf([...(request.volatile ?? []).map((note) => note.text), ...request.messages.flatMap((message) => (message.volatile ?? []).map((note) => note.text))]);
383
1260
  const files = referencedFiles(request).reduce((sum, ref) => sum + (deps.measureFile?.(ref) ?? 0), 0);
384
1261
  const content = systemBytes + toolBytes + volatile + files;
385
- const messages = Math.max(Buffer.byteLength(JSON.stringify(request.messages.map(({ volatile: _notes, ...message }) => message))), inputTokens - content);
1262
+ const messages = Math.max(messageBytes, inputTokens - content);
386
1263
  return {
387
1264
  categories: {
388
1265
  system: systemBytes - (parts.rules ?? 0) - (parts.skills ?? 0) - (parts.agents ?? 0),
@@ -403,6 +1280,27 @@ function rawBreakdown(request, inputTokens, deps) {
403
1280
  function bytesOf(texts) {
404
1281
  return texts.reduce((sum, text) => sum + Buffer.byteLength(text), 0);
405
1282
  }
1283
+ /**
1284
+ * Counts exact category bytes without retaining message JSON. Yields after roughly four milliseconds
1285
+ * between messages; serialization of one message is indivisible.
1286
+ */
1287
+ async function rawBreakdown(request, inputTokens, deps, scheduling = {}) {
1288
+ scheduling.signal?.throwIfAborted();
1289
+ const now = scheduling.now ?? (() => performance.now());
1290
+ const yieldWork = scheduling.yield ?? (() => setImmediate());
1291
+ let deadline = now() + 4;
1292
+ let messageBytes = 2;
1293
+ for (const [index, source] of request.messages.entries()) {
1294
+ const { volatile: _notes, ...message } = source;
1295
+ messageBytes += Buffer.byteLength(JSON.stringify(message)) + (index > 0 ? 1 : 0);
1296
+ if (index + 1 < request.messages.length && now() >= deadline) {
1297
+ await yieldWork();
1298
+ scheduling.signal?.throwIfAborted();
1299
+ deadline = now() + 4;
1300
+ }
1301
+ }
1302
+ return categoryBreakdown(request, inputTokens, deps, messageBytes);
1303
+ }
406
1304
  /** Awaits the owner's complete request display count without choosing an encoding. */
407
1305
  async function displayTokensOf(request, signal, measure) {
408
1306
  signal.throwIfAborted();
@@ -410,16 +1308,18 @@ async function displayTokensOf(request, signal, measure) {
410
1308
  signal.throwIfAborted();
411
1309
  return tokens;
412
1310
  }
413
- //#endregion
414
- //#region src/runtime/budget.ts
1311
+ /** Internal output reservation used when the adapter reports no usable reserve. */
1312
+ const ASSUMED_OUTPUT_RESERVE = 8192;
415
1313
  /**
416
- * Returns the safe input budget for a known context window. Capacity is
417
- * unknown when the adapter supplies no context window.
1314
+ * Computes safe input using the declared window or the 128K assumed baseline.
1315
+ * Missing independent input limits impose no additional limit. Known windows,
1316
+ * including small ones, always take precedence over the assumed baseline.
418
1317
  */
419
1318
  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));
1319
+ const window = inspection.contextWindow ?? 128e3;
1320
+ const reserve = inspection.outputReserve > 0 || inspection.contextWindow !== void 0 ? inspection.outputReserve : ASSUMED_OUTPUT_RESERVE;
1321
+ const capacity = Math.min(inspection.inputLimit ?? Number.POSITIVE_INFINITY, window - reserve);
1322
+ const margin = Math.max(256, Math.ceil(window * .05));
423
1323
  return Math.max(0, capacity - margin);
424
1324
  }
425
1325
  /** Capability-owned defaults for first-delivery tool bodies, expressed in model-estimated tokens. */
@@ -434,6 +1334,85 @@ const TOOL_PREVIEW_POLICY = {
434
1334
  stepFraction: .2
435
1335
  };
436
1336
  //#endregion
1337
+ //#region src/runtime/inspection-cache.ts
1338
+ /** Creates one exact-probe result pool shared by every session of the context owner. */
1339
+ function createInspectionCache(options = {}) {
1340
+ let ports = /* @__PURE__ */ new WeakMap();
1341
+ const recent = /* @__PURE__ */ new Map();
1342
+ const maximumEntries = options.entries ?? 512;
1343
+ const maximumBytes = options.bytes ?? 16777216;
1344
+ let retainedBytes = 0;
1345
+ options.signal?.addEventListener("abort", () => {
1346
+ ports = /* @__PURE__ */ new WeakMap();
1347
+ recent.clear();
1348
+ retainedBytes = 0;
1349
+ }, { once: true });
1350
+ return {
1351
+ /** Reuses exact text only within one port and complete measurement scope, with a shared LRU ceiling. */
1352
+ measure(port, scope, text, count, purpose = "text") {
1353
+ options.signal?.throwIfAborted();
1354
+ const started = options.performance?.now();
1355
+ const scopes = ports.get(port) ?? /* @__PURE__ */ new Map();
1356
+ let bucket = scopes.get(scope);
1357
+ const found = bucket?.values.get(text);
1358
+ if (found !== void 0) {
1359
+ recent.delete(found);
1360
+ recent.set(found, true);
1361
+ options.performance?.observe({
1362
+ stage: "model.cache",
1363
+ measurementPurpose: purpose,
1364
+ durationMs: options.performance.now() - started,
1365
+ count: 1,
1366
+ hits: 1,
1367
+ inputBytes: text.length * 2,
1368
+ retainedBytes
1369
+ });
1370
+ return found.value;
1371
+ }
1372
+ const value = count();
1373
+ const bytes = (scope.length + text.length) * 2;
1374
+ let evictions = 0;
1375
+ if (maximumEntries > 0 && bytes <= maximumBytes) {
1376
+ while (recent.size >= maximumEntries || retainedBytes + bytes > maximumBytes) {
1377
+ const oldest = recent.keys().next().value;
1378
+ if (!oldest) break;
1379
+ recent.delete(oldest);
1380
+ oldest.bucket.values.delete(oldest.text);
1381
+ if (!oldest.bucket.values.size) oldest.bucket.scopes.delete(oldest.bucket.scope);
1382
+ retainedBytes -= oldest.bytes;
1383
+ evictions++;
1384
+ }
1385
+ bucket ??= {
1386
+ scope,
1387
+ scopes,
1388
+ values: /* @__PURE__ */ new Map()
1389
+ };
1390
+ scopes.set(scope, bucket);
1391
+ ports.set(port, scopes);
1392
+ const entry = {
1393
+ text,
1394
+ value,
1395
+ bytes,
1396
+ bucket
1397
+ };
1398
+ bucket.values.set(text, entry);
1399
+ recent.set(entry, true);
1400
+ retainedBytes += bytes;
1401
+ }
1402
+ options.performance?.observe({
1403
+ stage: "model.cache",
1404
+ measurementPurpose: purpose,
1405
+ durationMs: options.performance.now() - started,
1406
+ count: 1,
1407
+ misses: 1,
1408
+ evictions,
1409
+ inputBytes: text.length * 2,
1410
+ retainedBytes
1411
+ });
1412
+ return value;
1413
+ } };
1414
+ }
1415
+ //#endregion
437
1416
  //#region src/runtime/preview.ts
438
1417
  const toolUsePartsIn$1 = (message) => message.content.filter((part) => part.type === "tool-use");
439
1418
  const contextSourceRef$1 = (message, part) => `msg:${message}:${part}`;
@@ -441,11 +1420,23 @@ const contextSourceRef$1 = (message, part) => `msg:${message}:${part}`;
441
1420
  * Allocates ordinary result bodies fairly across each complete tool batch.
442
1421
  * `inputBudget` is safe input tokens and `tokens` measures text using the current
443
1422
  * 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.
1423
+ * check; protected pages are excluded from ordinary preview allocation.
1424
+ * Throws when required identifiers alone cannot fit the ordinary step budget.
446
1425
  * Returned replacements reference immutable originals and preserve all metadata.
447
1426
  */
448
- function planToolPreviews(events, inputBudget, tokens, framework) {
1427
+ function planToolPreviews(events, inputBudget, measureTokens, framework, measureResult) {
1428
+ const measured = /* @__PURE__ */ new Map();
1429
+ let cachedCodeUnits = 0;
1430
+ const tokens = (text) => {
1431
+ const found = measured.get(text);
1432
+ if (found !== void 0) return found;
1433
+ const value = measureTokens(text);
1434
+ if (measured.size < 128 && cachedCodeUnits + text.length <= 524288) {
1435
+ measured.set(text, value);
1436
+ cachedCodeUnits += text.length;
1437
+ }
1438
+ return value;
1439
+ };
449
1440
  const projection = framework.project(events);
450
1441
  const replaced = new Set(projection.replacedSourceKeys);
451
1442
  const visible = new Map(projection.entries.map((entry) => [entry.message.id, entry.message]));
@@ -463,25 +1454,79 @@ function planToolPreviews(events, inputBudget, tokens, framework) {
463
1454
  partIndex
464
1455
  }] : []);
465
1456
  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;
1457
+ const answers = /* @__PURE__ */ new Map();
1458
+ for (const { part, partIndex } of parts) {
1459
+ if (!part.delivery?.answerRequestId) continue;
1460
+ const answer = framework.answerSource?.(events, source.message.id, partIndex);
1461
+ if (answer) answers.set(partIndex, answer);
1462
+ }
1463
+ const sourceRef = (partIndex) => answers.get(partIndex)?.ref ?? contextSourceRef$1(source.message.id, partIndex);
466
1464
  const ordered = calls.flatMap((call) => {
467
1465
  const found = parts.find(({ part }) => part.toolUseId === call.id);
468
- return found === void 0 ? [] : [found];
1466
+ return found === void 0 ? [] : [{
1467
+ ...found,
1468
+ part: answers.has(found.partIndex) ? {
1469
+ ...found.part,
1470
+ content: answers.get(found.partIndex).text
1471
+ } : found.part
1472
+ }];
469
1473
  });
470
- const restoreIds = new Set(calls.filter((call) => call.name === "context_restore").map((call) => call.id));
1474
+ const originalCosts = /* @__PURE__ */ new Map();
1475
+ const originalCost = (partIndex, content) => {
1476
+ const found = originalCosts.get(partIndex);
1477
+ if (found !== void 0) return found;
1478
+ const cost = tokens(content);
1479
+ originalCosts.set(partIndex, cost);
1480
+ return cost;
1481
+ };
1482
+ if (measureResult) {
1483
+ for (const { part } of ordered) if (part.files?.length && part.delivery && measureResult({
1484
+ ...part,
1485
+ content: ""
1486
+ }) > part.delivery.outputTokens) throw new Error("media_budget_exceeded: retry original retrieval with a larger outputTokens allowance; committed results remain saved");
1487
+ }
471
1488
  const metadata = ordered.reduce((sum, { part }) => {
472
- const { content: _content, previewTokens: _hint, previewProtected: _protected, ...rest } = part;
473
- return sum + tokens(JSON.stringify(rest));
1489
+ const { content: _content, previewTokens: _hint, delivery: _delivery, requiredContext: _requiredContext, ...rest } = part;
1490
+ return sum + (measureResult && part.files?.length ? measureResult(rest) : tokens(JSON.stringify(rest)));
474
1491
  }, 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;
1492
+ const required = /* @__PURE__ */ new Map();
1493
+ for (const { part } of ordered) for (const block of part.requiredContext ?? []) {
1494
+ const key = JSON.stringify([
1495
+ block.id,
1496
+ block.scope,
1497
+ block.version,
1498
+ block.stampedSource
1499
+ ]);
1500
+ if (!required.has(key)) required.set(key, block);
1501
+ }
1502
+ const requiredCost = [...required.values()].reduce((sum, block) => sum + tokens(JSON.stringify(block)), 0);
1503
+ const exactCost = ordered.reduce((sum, { part }) => sum + (part.delivery?.kind === "exact-page" ? tokens(part.content) : 0), 0);
1504
+ if (metadata + requiredCost + exactCost >= stepLimit) throw new Error("protected_context_exceeds_budget");
1505
+ const available = stepLimit - metadata - requiredCost - exactCost;
1506
+ const encodePreview = (partIndex, preview) => {
1507
+ const ref = sourceRef(partIndex);
1508
+ const part = ordered.find((one) => one.partIndex === partIndex).part;
1509
+ return JSON.stringify({
1510
+ ok: true,
1511
+ complete: false,
1512
+ preview,
1513
+ source: {
1514
+ ref,
1515
+ sourceComplete: answers.has(partIndex) || (part.delivery?.sourceComplete ?? false),
1516
+ recoverable: true
1517
+ },
1518
+ next: {
1519
+ tool: "context_restore",
1520
+ arguments: { pages: [{ ref }] }
1521
+ }
1522
+ });
1523
+ };
1524
+ const desired = ordered.map(({ part, partIndex }) => {
1525
+ if (part.delivery?.kind === "exact-page") return 0;
481
1526
  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);
1527
+ 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
1528
  });
484
- const markerFor = (partIndex) => `\n[tool result preview; context_restore ref "${contextSourceRef$1(source.message.id, partIndex)}"]\n`;
1529
+ const markerFor = (partIndex) => encodePreview(partIndex, "");
485
1530
  const referenceCosts = /* @__PURE__ */ new Map();
486
1531
  let cells = desired.map((wanted, i) => ({
487
1532
  i,
@@ -490,7 +1535,33 @@ function planToolPreviews(events, inputBudget, tokens, framework) {
490
1535
  }));
491
1536
  for (;;) {
492
1537
  let remaining = available - [...referenceCosts.values()].reduce((sum, value) => sum + value, 0);
493
- if (remaining < 0) throw new Error("protected_context_exceeds_budget");
1538
+ if (remaining < 0) {
1539
+ const failure = JSON.stringify({
1540
+ ok: false,
1541
+ error: {
1542
+ code: "step_budget_exhausted",
1543
+ message: "Saved; use context_search.",
1544
+ retryable: true
1545
+ },
1546
+ next: null
1547
+ });
1548
+ const ordinary = ordered.filter(({ part, partIndex }) => part.delivery?.kind !== "exact-page" && !replaced.has(`${source.messageSeq}:${partIndex}`));
1549
+ if (ordinary.length * tokens(failure) > available) throw new Error("protected_context_exceeds_budget");
1550
+ for (const { part, partIndex } of ordinary) replacements.push({
1551
+ messageSeq: source.messageSeq,
1552
+ partIndex,
1553
+ replacement: {
1554
+ ...part,
1555
+ content: failure
1556
+ },
1557
+ sourceRef: contextSourceRef$1(source.message.id, partIndex),
1558
+ originalCodePoints: [...part.content].length,
1559
+ previewTokens: 0,
1560
+ truncated: true
1561
+ });
1562
+ cells = [];
1563
+ break;
1564
+ }
494
1565
  cells = desired.map((wanted, i) => ({
495
1566
  i,
496
1567
  wanted,
@@ -508,20 +1579,21 @@ function planToolPreviews(events, inputBudget, tokens, framework) {
508
1579
  }
509
1580
  let addedReference = false;
510
1581
  ordered.forEach(({ part, partIndex }, i) => {
511
- if (replaced.has(`${source.messageSeq}:${partIndex}`) || restoreIds.has(part.toolUseId) || part.previewProtected === true) return;
1582
+ if (replaced.has(`${source.messageSeq}:${partIndex}`) || part.delivery?.kind === "exact-page") return;
512
1583
  const cell = cells[i];
513
- if (cell !== void 0 && tokens(part.content) > cell.limit && !referenceCosts.has(i)) {
1584
+ if (cell !== void 0 && (answers.has(partIndex) || originalCost(partIndex, part.content) > cell.limit) && !referenceCosts.has(i)) {
514
1585
  referenceCosts.set(i, tokens(markerFor(partIndex)));
515
1586
  addedReference = true;
516
1587
  }
517
1588
  });
518
1589
  if (!addedReference) break;
519
1590
  }
1591
+ if (cells.length === 0) continue;
520
1592
  ordered.forEach(({ part, partIndex }, i) => {
521
- if (replaced.has(`${source.messageSeq}:${partIndex}`) || restoreIds.has(part.toolUseId) || part.previewProtected === true) return;
1593
+ if (replaced.has(`${source.messageSeq}:${partIndex}`) || part.delivery?.kind === "exact-page") return;
522
1594
  const limit = cells[i]?.limit ?? 0;
523
- if (tokens(part.content) <= limit) return;
524
- const ref = contextSourceRef$1(source.message.id, partIndex);
1595
+ if (!answers.has(partIndex) && originalCost(partIndex, part.content) <= limit) return;
1596
+ const ref = sourceRef(partIndex);
525
1597
  const marker = markerFor(partIndex);
526
1598
  const points = [...part.content];
527
1599
  let low = 0;
@@ -532,8 +1604,8 @@ function planToolPreviews(events, inputBudget, tokens, framework) {
532
1604
  const count = Math.floor((low + high) / 2);
533
1605
  const head = Math.ceil(count * 2 / 3);
534
1606
  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("")));
1607
+ const candidate = encodePreview(partIndex, points.slice(0, head).join("") + (tail === 0 ? "" : points.slice(-tail).join("")));
1608
+ const bodyTokens = Math.max(0, tokens(candidate) - tokens(marker));
537
1609
  if (bodyTokens <= limit) {
538
1610
  content = candidate;
539
1611
  previewTokens = bodyTokens;
@@ -583,6 +1655,12 @@ function planContextReduction(input, framework, options = {}) {
583
1655
  }] : []);
584
1656
  const protectedSeqs = /* @__PURE__ */ new Set();
585
1657
  const projection = framework.project(input);
1658
+ const projectedMessages = /* @__PURE__ */ new Map();
1659
+ for (const entry of projection.entries) {
1660
+ const message = entry.message;
1661
+ if (!projectedMessages.has(message.id)) projectedMessages.set(message.id, message);
1662
+ }
1663
+ const originalMessageIds = new Set(projection.sources.map((source) => source.message.id));
586
1664
  const alreadyReplaced = new Set(projection.l1SourceKeys);
587
1665
  const completedSteps = [];
588
1666
  const completedToolResults = /* @__PURE__ */ new Set();
@@ -618,7 +1696,7 @@ function planContextReduction(input, framework, options = {}) {
618
1696
  const part = result.message.content[partIndex];
619
1697
  if (part?.type === "tool-result" && wanted.has(part.toolUseId)) completedToolResults.add(sourceKey(result.messageSeq, partIndex));
620
1698
  }
621
- if (calls.some((call) => call.name === "context_restore")) restoreBatches.push({
1699
+ if (result.message.content.some((part) => part.type === "tool-result" && part.delivery?.kind === "exact-page")) restoreBatches.push({
622
1700
  seqs: [source.messageSeq, result.messageSeq],
623
1701
  resultSeq: result.messageSeq
624
1702
  });
@@ -642,13 +1720,14 @@ function planContextReduction(input, framework, options = {}) {
642
1720
  if (activeTrigger >= 0) {
643
1721
  if (events[activeTrigger + 1]?.kind === "message-appended") protectedSeqs.add(activeTrigger + 1);
644
1722
  }
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);
1723
+ const latestObservedReply = sources.reduce((latest, source) => source.message.role === "assistant" && source.event.usage !== void 0 ? Math.max(latest, source.messageSeq) : latest, -1);
1724
+ for (const batch of restoreBatches) if (!(latestObservedReply > batch.resultSeq)) for (const seq of batch.seqs) protectedSeqs.add(seq);
646
1725
  const l1Candidates = [];
647
1726
  for (const source of sources) {
648
1727
  if (protectedSeqs.has(source.messageSeq)) continue;
649
1728
  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({
1729
+ const part = projectedMessages.get(source.message.id)?.content[partIndex] ?? source.message.content[partIndex];
1730
+ 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
1731
  messageSeq: source.messageSeq,
653
1732
  partIndex,
654
1733
  part,
@@ -673,23 +1752,35 @@ function planContextReduction(input, framework, options = {}) {
673
1752
  }
674
1753
  const candidateKey = l2SourceRanges.map((range) => `${range.messageSeq}:${range.startPart}-${range.endPart}`).join(",");
675
1754
  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
1755
  const eligibleEntries = projection.entries.filter((entry) => entry.sourceRanges.every((range) => eligibleSeqs.has(range.messageSeq)));
1756
+ const l2Messages = eligibleEntries.map((entry) => entry.message);
1757
+ const l2Groups = [];
1758
+ const stepsBySeq = /* @__PURE__ */ new Map();
1759
+ completedSteps.forEach((step, index) => {
1760
+ for (const seq of step) if (!stepsBySeq.has(seq)) stepsBySeq.set(seq, index);
1761
+ });
1762
+ let priorSteps = /* @__PURE__ */ new Set();
679
1763
  for (const entry of eligibleEntries) {
680
1764
  const firstRange = entry.sourceRanges[0];
681
1765
  if (firstRange === void 0) continue;
682
- const step = completedSteps.find((one) => one.includes(firstRange.messageSeq));
1766
+ const step = stepsBySeq.get(firstRange.messageSeq);
683
1767
  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))) {
1768
+ const summarized = !originalMessageIds.has(entry.message.id);
1769
+ if (!summarized && prior && !prior.summarized && step !== void 0 && priorSteps.has(step)) {
686
1770
  prior.messages.push(entry.message);
687
1771
  prior.sourceRanges.push(...entry.sourceRanges);
688
- } else l2Groups.push({
689
- messages: [entry.message],
690
- sourceRanges: [...entry.sourceRanges],
691
- summarized
692
- });
1772
+ } else {
1773
+ priorSteps = /* @__PURE__ */ new Set();
1774
+ l2Groups.push({
1775
+ messages: [entry.message],
1776
+ sourceRanges: [...entry.sourceRanges],
1777
+ summarized
1778
+ });
1779
+ }
1780
+ for (const range of entry.sourceRanges) {
1781
+ const sourceStep = stepsBySeq.get(range.messageSeq);
1782
+ if (sourceStep !== void 0) priorSteps.add(sourceStep);
1783
+ }
693
1784
  }
694
1785
  return {
695
1786
  l1Candidates,
@@ -700,11 +1791,15 @@ function planContextReduction(input, framework, options = {}) {
700
1791
  protectedMessageSeqs: [...protectedSeqs].sort((a, b) => a - b)
701
1792
  };
702
1793
  }
1794
+ function moreThanCodePoints(text, limit) {
1795
+ let count = 0;
1796
+ for (const _ of text) if (++count > limit) return true;
1797
+ return false;
1798
+ }
703
1799
  /** Builds the deterministic replacement for one eligible tool-result body. */
704
1800
  function createL1Replacement(candidate) {
705
- const points = [...candidate.part.content];
706
- const head = points.slice(0, 256).join("");
707
- const tail = points.slice(-128).join("");
1801
+ const head = [...candidate.part.content.slice(0, 512)].slice(0, 256).join("");
1802
+ const tail = [...candidate.part.content.slice(-256)].slice(-128).join("");
708
1803
  return {
709
1804
  messageSeq: candidate.messageSeq,
710
1805
  partIndex: candidate.partIndex,
@@ -899,24 +1994,31 @@ function summaryFallbackPort(primary, fallback, onFallback) {
899
1994
  //#region src/runtime/coordinator.ts
900
1995
  /** Adds the shared safe-input budget to one terminal adapter inspection. */
901
1996
  function contextMeasurement(inspection) {
902
- const inputBudget = safeInputBudget(inspection);
903
- return {
1997
+ const assumed = inspection.contextWindow === void 0 || inspection.capacitySource === "assumed";
1998
+ const outputReserve = assumed && inspection.outputReserve <= 0 ? ASSUMED_OUTPUT_RESERVE : inspection.outputReserve;
1999
+ const measured = {
904
2000
  ...inspection,
905
- outputReserveSource: inspection.outputReserveSource ?? "capacity",
906
- ...inputBudget === void 0 ? {} : { inputBudget }
2001
+ contextWindow: inspection.contextWindow ?? 128e3,
2002
+ capacitySource: assumed ? "assumed" : "declared",
2003
+ outputReserve,
2004
+ outputReserveSource: assumed && inspection.outputReserve <= 0 ? "estimated" : inspection.outputReserveSource ?? "capacity"
2005
+ };
2006
+ return {
2007
+ ...measured,
2008
+ inputBudget: safeInputBudget(measured)
907
2009
  };
908
2010
  }
909
- /** Measures one fully rendered request, reporting an unmeasured request when unsupported. */
2011
+ /** Measures the final request locally; a missing protocol meter uses conservative UTF-8 bytes. */
910
2012
  function inspectContextRequest(port, request) {
911
2013
  const observed = port.inspect?.(request);
912
2014
  if (observed !== void 0) return contextMeasurement(observed);
913
- return {
914
- inputTokens: 0,
915
- unmeasured: true,
2015
+ 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");
2016
+ return contextMeasurement({
2017
+ inputTokens: Buffer.byteLength(JSON.stringify(request)),
916
2018
  estimated: true,
917
2019
  outputReserve: 0,
918
- fingerprint: "unmeasured"
919
- };
2020
+ fingerprint: "estimated:utf8-bytes:assumed-128000"
2021
+ });
920
2022
  }
921
2023
  /** Creates the coordinator bound to one immutable session identity. */
922
2024
  function createContextCoordinator(_deps) {
@@ -924,10 +2026,11 @@ function createContextCoordinator(_deps) {
924
2026
  const projectContext = deps.framework.project;
925
2027
  const effectiveHistory = deps.framework.history;
926
2028
  const planContextReduction$1 = (events) => planContextReduction(events, deps.framework);
927
- const planToolPreviews$1 = (events, budget, tokens) => planToolPreviews(events, budget, tokens, deps.framework);
2029
+ const planToolPreviews$1 = (events, budget, tokens, mediaTokens) => planToolPreviews(events, budget, tokens, deps.framework, mediaTokens);
928
2030
  const now = deps.now ?? (() => Date.now());
929
2031
  const newOperationId = deps.newOperationId ?? randomUUID;
930
2032
  let measurement;
2033
+ let measurementIdentity;
931
2034
  let split;
932
2035
  /** The display estimate of the observed request; the Protocol inspection when none was given. */
933
2036
  let displayed = 0;
@@ -938,14 +2041,47 @@ function createContextCoordinator(_deps) {
938
2041
  * model and the committed context are the same. */
939
2042
  let anchor;
940
2043
  let measurementEventCount = 0;
2044
+ let fixedCatalogTokens = 0;
941
2045
  let diagnostic;
942
2046
  let failedCommit;
943
2047
  let active;
944
- function inspect(port, request) {
945
- return inspectContextRequest(port, {
946
- ...request,
947
- sessionId: deps.sessionId
948
- });
2048
+ function inspect(port, request, purpose = "request") {
2049
+ const started = deps.performance?.now();
2050
+ try {
2051
+ return inspectContextRequest(port, {
2052
+ ...request,
2053
+ sessionId: deps.sessionId
2054
+ });
2055
+ } finally {
2056
+ deps.performance?.observe({
2057
+ stage: "context.inspect",
2058
+ measurementPurpose: purpose,
2059
+ durationMs: deps.performance.now() - started,
2060
+ count: 1
2061
+ });
2062
+ }
2063
+ }
2064
+ const inspections = deps.inspections ?? createInspectionCache({
2065
+ entries: 128,
2066
+ bytes: 1048576,
2067
+ performance: deps.performance
2068
+ });
2069
+ /** Reuses exact fragment text under the same live protocol and session generation. */
2070
+ function fragmentMeter(port, empty, purpose = "text") {
2071
+ const baseline = inspect(port, empty, purpose);
2072
+ const scope = JSON.stringify([
2073
+ deps.sessionId,
2074
+ purpose === "catalogue" ? "catalogue" : "text",
2075
+ baseline.fingerprint,
2076
+ baseline.inputTokens,
2077
+ deps.inspectionScope?.()
2078
+ ]);
2079
+ return {
2080
+ baseline,
2081
+ measure(text, request) {
2082
+ return inspections.measure(port, scope, text, () => inspect(port, request(), purpose).inputTokens, purpose);
2083
+ }
2084
+ };
949
2085
  }
950
2086
  function hasKnownCapacity(value) {
951
2087
  return value.inputBudget !== void 0;
@@ -1006,6 +2142,7 @@ function createContextCoordinator(_deps) {
1006
2142
  if (deps.saved === void 0 || measurement === void 0) return;
1007
2143
  const reading = {
1008
2144
  measurement,
2145
+ measurementIdentity,
1009
2146
  ...split === void 0 ? {} : { split },
1010
2147
  displayed,
1011
2148
  ...reported === void 0 ? {} : { reported },
@@ -1014,7 +2151,11 @@ function createContextCoordinator(_deps) {
1014
2151
  try {
1015
2152
  deps.saved.put(projectContext(deps.read()).revision, JSON.stringify(reading));
1016
2153
  } catch (error) {
1017
- console.error(`context reading not saved: ${error instanceof Error ? error.message : error}`);
2154
+ deps.log?.emit({
2155
+ level: "error",
2156
+ event: "plugin.event",
2157
+ fields: { localCode: "CONTEXT_READING_SAVE_FAILED" }
2158
+ });
1018
2159
  }
1019
2160
  }
1020
2161
  /** Takes the saved reading back when it was written against the context the
@@ -1030,7 +2171,9 @@ function createContextCoordinator(_deps) {
1030
2171
  return;
1031
2172
  }
1032
2173
  if (!parsed.success) return;
2174
+ if (deps.measurementIdentity && parsed.data.measurementIdentity !== deps.measurementIdentity()) return;
1033
2175
  measurement = parsed.data.measurement;
2176
+ measurementIdentity = parsed.data.measurementIdentity;
1034
2177
  split = parsed.data.split;
1035
2178
  displayed = parsed.data.displayed;
1036
2179
  reported = parsed.data.reported;
@@ -1115,9 +2258,31 @@ function createContextCoordinator(_deps) {
1115
2258
  text
1116
2259
  }]
1117
2260
  }] });
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);
2261
+ const textMeter = fragmentMeter(port, textRequest(""));
2262
+ const tokens = (text) => {
2263
+ return Math.max(0, textMeter.measure(text, () => textRequest(text)) - textMeter.baseline.inputTokens);
2264
+ };
2265
+ let replacements;
2266
+ try {
2267
+ replacements = planToolPreviews$1(deps.read(), before.inputBudget, tokens, resultMeter(port));
2268
+ } catch (error) {
2269
+ if (trigger === "auto") {
2270
+ const reason = error instanceof Error ? error.message.slice(0, 256) : "Preview admission failed.";
2271
+ diagnostic = reason.split(":")[0];
2272
+ await recordOperation({
2273
+ operationId,
2274
+ trigger,
2275
+ status: "failed",
2276
+ candidateKey: projection.revision.toString(),
2277
+ fingerprint: before.fingerprint,
2278
+ before,
2279
+ after: before,
2280
+ reason,
2281
+ startedAt: now()
2282
+ });
2283
+ }
2284
+ throw error;
2285
+ }
1121
2286
  if (replacements.length > 0) {
1122
2287
  if (!historyRecoveryAvailable(request)) return {
1123
2288
  request,
@@ -1253,8 +2418,11 @@ function createContextCoordinator(_deps) {
1253
2418
  const replacements = [];
1254
2419
  let prospectiveRequest = request;
1255
2420
  let prospectiveMeasurement = after;
1256
- for (const candidate of candidates) {
1257
- replacements.push(createL1Replacement(candidate));
2421
+ let batchEnd = input.trigger === "auto" ? 1 : candidates.length;
2422
+ while (replacements.length < candidates.length) {
2423
+ await setImmediate();
2424
+ controller.signal.throwIfAborted();
2425
+ for (const candidate of candidates.slice(replacements.length, batchEnd)) replacements.push(createL1Replacement(candidate));
1258
2426
  const prospective = {
1259
2427
  kind: "context-compacted",
1260
2428
  sessionId: deps.sessionId,
@@ -1277,6 +2445,7 @@ function createContextCoordinator(_deps) {
1277
2445
  prospectiveRequest = await input.assembleProjected(prospectiveProjection.messages);
1278
2446
  prospectiveMeasurement = inspect(input.port, prospectiveRequest);
1279
2447
  if (input.trigger === "auto" && belowTrigger(prospectiveMeasurement)) break;
2448
+ batchEnd = Math.min(candidates.length, batchEnd * 2);
1280
2449
  }
1281
2450
  if (replacements.length > 0 && prospectiveMeasurement.inputTokens < after.inputTokens) {
1282
2451
  await commitFact({
@@ -1323,26 +2492,33 @@ function createContextCoordinator(_deps) {
1323
2492
  })
1324
2493
  };
1325
2494
  }
1326
- const branch = [...deps.read()].reverse().find(({ event }) => event.kind === "history-rewound" || event.kind === "history-seeded");
2495
+ const campaignHistory = deps.read();
2496
+ const branch = campaignHistory.findLast(({ event }) => event.kind === "history-rewound" || event.kind === "history-seeded");
1327
2497
  const campaignIdentity = JSON.stringify([
1328
2498
  deps.sessionId,
1329
2499
  branch?.seq ?? -1,
1330
2500
  after.fingerprint,
1331
2501
  deps.model()
1332
2502
  ]);
1333
- const historyOperations = effectiveHistory(deps.read()).flatMap(({ event }) => event.kind === "context-operation" && event.campaignIdentity === campaignIdentity ? [event] : []);
2503
+ const historyOperations = effectiveHistory(campaignHistory).flatMap(({ event }) => event.kind === "context-operation" && event.campaignIdentity === campaignIdentity ? [event] : []);
2504
+ const completedCampaigns = new Set(campaignHistory.flatMap(({ event }) => event.kind === "context-compacted" && event.layer === "l2" ? [event.campaignId] : []));
1334
2505
  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;
2506
+ const priorCampaign = completedCampaigns.has(lastCampaignEvent?.campaignId) ? void 0 : lastCampaignEvent?.campaignId;
1336
2507
  const campaignId = input.trigger === "manual" || priorCampaign === void 0 ? randomUUID() : priorCampaign;
1337
2508
  const campaignEvents = historyOperations.filter((one) => one.campaignId === campaignId);
2509
+ const terminalAttempts = new Map(campaignEvents.filter((one) => one.phase === "completed").map((one) => [one.attempt, one]));
2510
+ const compactedAttempts = /* @__PURE__ */ new Set();
2511
+ let completedChunks = 0;
2512
+ for (const { event } of campaignHistory) if (event.kind === "context-compacted" && event.campaignId === campaignId) {
2513
+ compactedAttempts.add(event.attempt);
2514
+ if (event.layer === "l2") completedChunks++;
2515
+ }
1338
2516
  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);
2517
+ if (compactedAttempts.has(started.attempt)) return false;
2518
+ const terminal = terminalAttempts.get(started.attempt);
2519
+ return terminal === void 0 || terminal.status === "failed";
1343
2520
  }).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;
2521
+ let attempt = campaignEvents.reduce((maximum, one) => Math.max(maximum, one.attempt ?? 0), 0);
1346
2522
  campaign = {
1347
2523
  id: campaignId,
1348
2524
  identity: campaignIdentity,
@@ -1370,20 +2546,34 @@ function createContextCoordinator(_deps) {
1370
2546
  break;
1371
2547
  }
1372
2548
  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),
2549
+ let fitting = 0, oversized = groups.length + 1;
2550
+ let selectedRequest;
2551
+ const fitsPrefix = async (count) => {
2552
+ await setImmediate();
2553
+ controller.signal.throwIfAborted();
2554
+ const candidate = {
2555
+ ...createSummaryRequest(groups.slice(0, count).flatMap((one) => one.messages), maxOutput),
1382
2556
  sessionId: deps.sessionId
1383
- });
1384
- if (!hasKnownCapacity(counted) || counted.inputTokens > counted.inputBudget) break;
1385
- selected.push(group);
2557
+ };
2558
+ const counted = inspectContextRequest(summaryPort, candidate);
2559
+ if (!hasKnownCapacity(counted) || counted.inputTokens > counted.inputBudget) return false;
2560
+ selectedRequest = candidate;
2561
+ return true;
2562
+ };
2563
+ if (groups.length && await fitsPrefix(groups.length)) fitting = groups.length;
2564
+ else {
2565
+ oversized = groups.length;
2566
+ while (oversized - fitting > 8) {
2567
+ const count = Math.floor((fitting + oversized) / 2);
2568
+ if (await fitsPrefix(count)) fitting = count;
2569
+ else oversized = count;
2570
+ }
2571
+ for (let count = oversized - 1; count > fitting; count--) if (await fitsPrefix(count)) {
2572
+ fitting = count;
2573
+ break;
2574
+ }
1386
2575
  }
2576
+ const selected = groups.slice(0, fitting);
1387
2577
  if (selected.length === 0) {
1388
2578
  diagnostic = groups.length > 0 ? "summary_group_too_large" : void 0;
1389
2579
  break;
@@ -1418,7 +2608,7 @@ function createContextCoordinator(_deps) {
1418
2608
  port: summaryPort,
1419
2609
  middleware: deps.middleware(),
1420
2610
  request: {
1421
- ...createSummaryRequest(selected.flatMap((one) => one.messages), maxOutput),
2611
+ ...selectedRequest,
1422
2612
  sessionId: deps.sessionId
1423
2613
  },
1424
2614
  signal: controller.signal
@@ -1621,6 +2811,75 @@ function createContextCoordinator(_deps) {
1621
2811
  summaryModel: () => used
1622
2812
  };
1623
2813
  }
2814
+ const resultMeter = (port) => {
2815
+ const request = (text) => ({ messages: [{
2816
+ id: "00000000-0000-4000-8000-000000000000",
2817
+ role: "user",
2818
+ content: [{
2819
+ type: "text",
2820
+ text
2821
+ }]
2822
+ }] });
2823
+ const meter = fragmentMeter(port, request(""), "tool-result");
2824
+ const base = meter.baseline.inputTokens;
2825
+ return (result) => {
2826
+ const media = typeof result === "object" && result !== null && "files" in result && Array.isArray(result.files) ? result.files.filter((file) => typeof file === "object" && file !== null && typeof file.id === "string" && typeof file.mediaType === "string") : [];
2827
+ const text = typeof result === "string" ? result : JSON.stringify(media.length && typeof result === "object" && result !== null ? {
2828
+ ...result,
2829
+ files: void 0
2830
+ } : result);
2831
+ const withMedia = () => {
2832
+ const candidate = request(text);
2833
+ return {
2834
+ ...candidate,
2835
+ messages: candidate.messages.map((message) => ({
2836
+ ...message,
2837
+ content: [...message.content, ...media.map((file) => ({
2838
+ type: "file",
2839
+ file
2840
+ }))]
2841
+ }))
2842
+ };
2843
+ };
2844
+ const measured = (media.length ? inspect(port, withMedia()).inputTokens : meter.measure(text, () => request(text))) - base;
2845
+ return measured > 0 ? measured : Buffer.byteLength(text);
2846
+ };
2847
+ };
2848
+ const toolOutputPolicy = () => {
2849
+ if (!measurement || measurement.inputBudget === void 0) return void 0;
2850
+ const port = deps.port();
2851
+ const measure = resultMeter(port);
2852
+ const catalogueMeter = fragmentMeter(port, {
2853
+ messages: [],
2854
+ tools: []
2855
+ }, "catalogue");
2856
+ const measureCatalog = (value) => {
2857
+ const definitions = Array.isArray(value) ? value : [value];
2858
+ if (!definitions.length) return 0;
2859
+ const cost = catalogueMeter.measure(JSON.stringify(definitions), () => ({
2860
+ messages: [],
2861
+ tools: definitions
2862
+ })) - catalogueMeter.baseline.inputTokens;
2863
+ return cost > 0 ? cost : Buffer.byteLength(JSON.stringify(definitions));
2864
+ };
2865
+ return {
2866
+ defaultTokens: TOOL_PREVIEW_POLICY.defaultTokens,
2867
+ maximumTokens: TOOL_PREVIEW_POLICY.maximumTokens,
2868
+ stepTokens: Math.max(0, Math.min(TOOL_PREVIEW_POLICY.stepTokens, Math.floor(measurement.inputBudget * TOOL_PREVIEW_POLICY.stepFraction), measurement.inputBudget - measurement.inputTokens)),
2869
+ maximumCalls: 64,
2870
+ requestTokens: measurement.inputBudget,
2871
+ catalog: {
2872
+ tokens: Math.min(2e4, Math.floor(measurement.inputBudget * .2)),
2873
+ dynamicTokens: Math.max(0, Math.min(6e3, Math.floor(measurement.inputBudget * .1), Math.min(2e4, Math.floor(measurement.inputBudget * .2)) - fixedCatalogTokens)),
2874
+ definitionTokens: 4e3,
2875
+ measure: measureCatalog
2876
+ },
2877
+ sourceBytes: 4194304,
2878
+ stepSourceBytes: 16777216,
2879
+ encodedSourceBytes: 8388608,
2880
+ measure
2881
+ };
2882
+ };
1624
2883
  restore();
1625
2884
  return {
1626
2885
  async prepare(ctx, assembleProjected) {
@@ -1631,6 +2890,14 @@ function createContextCoordinator(_deps) {
1631
2890
  if (request.purpose === "summary") return request;
1632
2891
  const before = prepared.after;
1633
2892
  measurement = before;
2893
+ const catalog = toolOutputPolicy()?.catalog;
2894
+ if (catalog && request.tools) {
2895
+ fixedCatalogTokens = catalog.measure(request.tools.filter((tool) => tool.catalogKind !== "dynamic"));
2896
+ if (catalog.measure(request.tools) > catalog.tokens) throw new Error("catalog_too_large");
2897
+ const dynamic = request.tools.filter((tool) => tool.catalogKind === "dynamic");
2898
+ if (dynamic.some((tool) => catalog.measure(tool) > catalog.definitionTokens)) throw new Error("tool_schema_too_large");
2899
+ if (catalog.measure(dynamic) > catalog.dynamicTokens) throw new Error("catalog_too_large");
2900
+ }
1634
2901
  measurementEventCount = deps.read().length;
1635
2902
  diagnostic = hasKnownCapacity(before) ? void 0 : "capacity_unknown";
1636
2903
  notify();
@@ -1646,7 +2913,7 @@ function createContextCoordinator(_deps) {
1646
2913
  });
1647
2914
  if (reduced.result.status === "cancelled") throw new DOMException("context preparation cancelled", "AbortError");
1648
2915
  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");
2916
+ 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
2917
  return reduced.request;
1651
2918
  },
1652
2919
  async compact(assembleProjected, signal) {
@@ -1673,6 +2940,7 @@ function createContextCoordinator(_deps) {
1673
2940
  const projection = projectContext(events);
1674
2941
  const lastResult = latestResult(events);
1675
2942
  return {
2943
+ ...measurementIdentity === void 0 ? {} : { measurementIdentity },
1676
2944
  revision: projection.revision,
1677
2945
  ...measurement === void 0 ? {} : { measurement },
1678
2946
  ...measurement === void 0 ? {} : { occupancy: committedReport ? occupancy(measurement, projection.revision) : occupancyOf(displayed, measurement.unmeasured ? "unmeasured" : "estimated", split) },
@@ -1696,15 +2964,60 @@ function createContextCoordinator(_deps) {
1696
2964
  ...diagnostic === void 0 ? {} : { diagnostic }
1697
2965
  };
1698
2966
  },
2967
+ contributionAllowance() {
2968
+ const port = deps.port();
2969
+ const probe = (text) => ({ messages: [{
2970
+ id: "00000000-0000-4000-8000-000000000000",
2971
+ role: "user",
2972
+ content: [{
2973
+ type: "text",
2974
+ text
2975
+ }]
2976
+ }] });
2977
+ let meter;
2978
+ const current = () => meter ??= fragmentMeter(port, probe(""));
2979
+ const measuredCapacity = measurement?.inputBudget;
2980
+ let capacity;
2981
+ const available = () => capacity ??= measuredCapacity ?? current().baseline.inputBudget ?? 0;
2982
+ return {
2983
+ get tokens() {
2984
+ return Math.max(0, Math.min(2e3, Math.floor(available() * .02)));
2985
+ },
2986
+ get maximumTokens() {
2987
+ return Math.max(0, Math.min(8e3, 12e3, Math.floor(available() * .2)));
2988
+ },
2989
+ get requestTokens() {
2990
+ return available();
2991
+ },
2992
+ measure(text) {
2993
+ const meter = current();
2994
+ const initial = meter.baseline;
2995
+ const delta = meter.measure(text, () => probe(text)) - initial.inputTokens;
2996
+ return delta > 0 ? delta : Buffer.byteLength(text);
2997
+ }
2998
+ };
2999
+ },
3000
+ queryResourcePolicy() {
3001
+ return {
3002
+ queryBytes: 33554432,
3003
+ sessionBytes: 67108864,
3004
+ residentBytes: 268435456,
3005
+ sessionQueries: 64,
3006
+ queryScratchBytes: 33554432,
3007
+ sessionScratchBytes: 67108864,
3008
+ residentScratchBytes: 134217728
3009
+ };
3010
+ },
1699
3011
  restoreAllowance() {
1700
3012
  if (measurement?.inputBudget === void 0) return 0;
1701
3013
  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;
3014
+ const pendingTokens = toolOutputPolicy()?.measure(pendingMessages) ?? Buffer.byteLength(JSON.stringify(pendingMessages));
1704
3015
  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
3016
  },
3017
+ toolOutputPolicy,
1706
3018
  observe(value, shown) {
1707
3019
  measurement = value;
3020
+ measurementIdentity = deps.measurementIdentity?.();
1708
3021
  split = shown?.split;
1709
3022
  displayed = shown?.displayTokens ?? value.inputTokens;
1710
3023
  reported = void 0;
@@ -1739,6 +3052,10 @@ function createContextCoordinator(_deps) {
1739
3052
  function createContextRuntime(ctx, framework) {
1740
3053
  const readings = createSessionContextRowsOn(ctx.storage.open());
1741
3054
  const snapshots = createSessionStatusRows(ctx.storage.open());
3055
+ const inspections = createInspectionCache({
3056
+ signal: ctx.signal,
3057
+ performance: ctx.performance
3058
+ });
1742
3059
  const control = ctx.services.get("agent-context-control");
1743
3060
  const policies = /* @__PURE__ */ new Map();
1744
3061
  const changed = ctx.client.registerFrame({
@@ -1747,6 +3064,19 @@ function createContextRuntime(ctx, framework) {
1747
3064
  payload: z.strictObject({})
1748
3065
  });
1749
3066
  const active = /* @__PURE__ */ new Set();
3067
+ function inspect(port, request) {
3068
+ const started = ctx.performance?.now();
3069
+ try {
3070
+ return inspectContextRequest(port, request);
3071
+ } finally {
3072
+ ctx.performance?.observe({
3073
+ stage: "model.inspect",
3074
+ measurementPurpose: "request",
3075
+ durationMs: ctx.performance.now() - started,
3076
+ count: 1
3077
+ });
3078
+ }
3079
+ }
1750
3080
  ctx.signal.addEventListener("abort", () => {
1751
3081
  for (const policy of active) if (policy.activeOperation) policy.cancel(policy.activeOperation.operationId);
1752
3082
  active.clear();
@@ -1760,35 +3090,64 @@ function createContextRuntime(ctx, framework) {
1760
3090
  const before = control.source(sessionId);
1761
3091
  if (before.historyGeneration !== one.historyGeneration) return;
1762
3092
  const status = one.policy.status();
3093
+ if (status.measurementIdentity !== before.measurementIdentity) return;
1763
3094
  const after = control.source(sessionId);
1764
3095
  if (before.sourceSeq !== after.sourceSeq || before.historyGeneration !== after.historyGeneration) return;
1765
3096
  snapshots.put(sessionId, before.sourceSeq, before.historyGeneration, status);
1766
3097
  one.status = status;
1767
3098
  one.sourceSeq = before.sourceSeq;
1768
3099
  } catch (error) {
1769
- console.error(`context status not saved: ${error instanceof Error ? error.message : error}`);
3100
+ ctx.log.emit({
3101
+ level: "error",
3102
+ event: "plugin.event",
3103
+ fields: { localCode: "CONTEXT_STATUS_SAVE_FAILED" }
3104
+ });
1770
3105
  }
1771
3106
  }
1772
3107
  ctx.events.on((event) => {
1773
3108
  if (event.kind === "message-appended" || event.kind === "turn-ended" || event.kind === "context-compacted" || event.kind === "context-operation") capture(event.sessionId);
1774
3109
  });
1775
3110
  return {
1776
- assertRequest(inspection) {
3111
+ assertRequest(inspection, request) {
3112
+ const catalog = request?.sessionId ? policies.get(request.sessionId)?.policy.toolOutputPolicy()?.catalog : void 0;
3113
+ if (catalog && request?.tools) {
3114
+ if (catalog.measure(request.tools) > catalog.tokens) throw new Error("catalog_too_large");
3115
+ const dynamic = request.tools.filter((tool) => tool.catalogKind === "dynamic");
3116
+ if (dynamic.some((tool) => catalog.measure(tool) > catalog.definitionTokens)) throw new Error("tool_schema_too_large");
3117
+ if (catalog.measure(dynamic) > catalog.dynamicTokens) throw new Error("catalog_too_large");
3118
+ }
1777
3119
  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})`);
3120
+ if (budget !== void 0 && inspection.inputTokens > budget) throw ctx.models.failures.create({
3121
+ code: "context-limit-exceeded",
3122
+ stage: "request",
3123
+ category: "request-too-large",
3124
+ source: "host",
3125
+ retryable: false
3126
+ });
1779
3127
  },
1780
3128
  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");
3129
+ if (hasHistory && inspect(port, request).capacitySource === "assumed") throw new Error("capacity_unknown: configure the target context window before switching");
1782
3130
  },
1783
- status(sessionId) {
3131
+ status(sessionId, maxBytes = 524288) {
1784
3132
  ctx.signal.throwIfAborted();
1785
3133
  const one = policies.get(sessionId);
1786
3134
  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;
3135
+ if (one?.status && one.sourceSeq === source.sourceSeq && one.status.measurementIdentity === source.measurementIdentity && one.historyGeneration === source.historyGeneration) {
3136
+ if (Buffer.byteLength(JSON.stringify(one.status)) > maxBytes) throw new Error("read-limit: status exceeds member body capacity");
3137
+ return one.status;
3138
+ }
3139
+ const saved = snapshots.get(sessionId, maxBytes);
3140
+ if (saved?.sourceSeq === source.sourceSeq && saved.status.measurementIdentity === source.measurementIdentity && saved.historyGeneration === source.historyGeneration) return saved.status;
1790
3141
  const facts = control.reading(sessionId);
3142
+ const compatible = one?.status?.measurementIdentity === source.measurementIdentity && one.historyGeneration === source.historyGeneration ? one.status : saved?.status.measurementIdentity === source.measurementIdentity && saved.historyGeneration === source.historyGeneration ? saved.status : void 0;
3143
+ 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");
1791
3144
  return {
3145
+ ...compatible || !observed?.measurement || !observed.occupancy ? {} : { lastObservation: {
3146
+ measurement: observed.measurement,
3147
+ occupancy: observed.occupancy,
3148
+ ...observed.actualInputTokens === void 0 ? {} : { actualInputTokens: observed.actualInputTokens }
3149
+ } },
3150
+ ...compatible ?? {},
1792
3151
  revision: facts.revision,
1793
3152
  auxiliaryTokens: facts.auxiliaryTokens,
1794
3153
  totalTokens: facts.normalTokens + facts.auxiliaryTokens
@@ -1798,6 +3157,14 @@ function createContextRuntime(ctx, framework) {
1798
3157
  create(session) {
1799
3158
  ctx.signal.throwIfAborted();
1800
3159
  const policy = createContextCoordinator({
3160
+ log: ctx.log,
3161
+ performance: ctx.performance,
3162
+ inspections,
3163
+ inspectionScope: () => {
3164
+ const source = control.source(session.sessionId);
3165
+ return JSON.stringify([source.measurementIdentity, source.historyGeneration]);
3166
+ },
3167
+ measurementIdentity: () => control.source(session.sessionId).measurementIdentity,
1801
3168
  ...session,
1802
3169
  framework,
1803
3170
  onStatusChanged() {
@@ -1825,7 +3192,7 @@ function createContextRuntime(ctx, framework) {
1825
3192
  session,
1826
3193
  policy,
1827
3194
  historyGeneration: source.historyGeneration,
1828
- ...saved?.sourceSeq === source.sourceSeq && saved.historyGeneration === source.historyGeneration ? {
3195
+ ...saved?.sourceSeq === source.sourceSeq && saved.status.measurementIdentity === source.measurementIdentity && saved.historyGeneration === source.historyGeneration ? {
1829
3196
  status: saved.status,
1830
3197
  sourceSeq: source.sourceSeq
1831
3198
  } : {}
@@ -1850,16 +3217,31 @@ function createContextRuntime(ctx, framework) {
1850
3217
  };
1851
3218
  },
1852
3219
  measurement: contextMeasurement,
1853
- inspect: inspectContextRequest,
3220
+ inspect,
1854
3221
  budget: safeInputBudget,
1855
3222
  async shown(request, inputTokens, deps, signal) {
1856
3223
  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
- };
3224
+ const started = ctx.performance?.now();
3225
+ let outcome = "ok";
3226
+ try {
3227
+ const displayTokens = await displayTokensOf(request, AbortSignal.any([signal, ctx.signal]), deps.measureDisplay);
3228
+ ctx.signal.throwIfAborted();
3229
+ return {
3230
+ split: await rawBreakdown(request, inputTokens, deps, { signal: AbortSignal.any([signal, ctx.signal]) }),
3231
+ displayTokens
3232
+ };
3233
+ } catch (error) {
3234
+ outcome = signal.aborted || ctx.signal.aborted ? "cancelled" : "error";
3235
+ throw error;
3236
+ } finally {
3237
+ ctx.performance?.observe({
3238
+ stage: "model.display",
3239
+ measurementPurpose: "display",
3240
+ durationMs: ctx.performance.now() - started,
3241
+ count: 1,
3242
+ outcome
3243
+ });
3244
+ }
1863
3245
  }
1864
3246
  };
1865
3247
  }
@@ -1877,13 +3259,77 @@ const historyPolicy = {
1877
3259
  };
1878
3260
  //#endregion
1879
3261
  //#region src/runtime/methods.ts
3262
+ /** Each session status has an independent declared envelope budget. */
3263
+ const ContextStatusesParams = z.strictObject({
3264
+ sessionIds: z.array(z.string().min(1)).min(1).max(64),
3265
+ maxItemBytes: z.number().int().min(1).max(8388608).default(262144),
3266
+ maxTotalBytes: z.number().int().min(1).max(8388608).default(8388608)
3267
+ }).refine((input) => Buffer.byteLength(JSON.stringify(input)) <= 8388608, "batch-limit: status input exceeds 8 MiB");
3268
+ /** Ordered status members retain their target identity, including missing sessions. */
3269
+ const ContextStatusesResult = z.strictObject({ results: z.array(z.discriminatedUnion("ok", [z.strictObject({
3270
+ index: z.number().int().nonnegative(),
3271
+ target: z.string(),
3272
+ ok: z.literal(true),
3273
+ value: SessionContextStatus.nullable()
3274
+ }), z.strictObject({
3275
+ index: z.number().int().nonnegative(),
3276
+ target: z.string(),
3277
+ ok: z.literal(false),
3278
+ error: z.strictObject({
3279
+ code: z.string(),
3280
+ message: z.string()
3281
+ })
3282
+ })])).max(64) });
1880
3283
  /** Reuses framework exclusivity and cancellation while retaining policy ownership. */
1881
3284
  function registerContextMethods(ctx, runtime) {
1882
3285
  ctx.client.registerMethod({
1883
- name: "status",
1884
- params: z.strictObject({ sessionId: z.string().min(1) }),
1885
- result: SessionContextStatus,
1886
- handle: ({ sessionId }) => runtime.status(sessionId)
3286
+ name: "statuses",
3287
+ params: ContextStatusesParams,
3288
+ result: ContextStatusesResult,
3289
+ handle: (raw) => {
3290
+ const input = ContextStatusesParams.parse(raw);
3291
+ ctx.signal.throwIfAborted();
3292
+ if (input.sessionIds.length * input.maxItemBytes + 8192 > input.maxTotalBytes) throw new Error("batch-limit: declared status budgets exceed collection capacity");
3293
+ const encode = (value) => Buffer.byteLength(JSON.stringify(value));
3294
+ const failures = input.sessionIds.map((target, index) => ({
3295
+ index,
3296
+ target,
3297
+ ok: false,
3298
+ error: {
3299
+ code: "read-limit",
3300
+ message: "Status exceeds its declared member budget"
3301
+ }
3302
+ }));
3303
+ if (failures.some((one) => encode(one) > input.maxItemBytes)) throw new Error("batch-limit: status metadata exceeds member capacity");
3304
+ const known = ctx.services.get("session-context").existsMany(input.sessionIds);
3305
+ if (known.length !== input.sessionIds.length) throw new Error("Invalid session metadata cardinality");
3306
+ return { results: input.sessionIds.map((target, index) => {
3307
+ try {
3308
+ const metadata = encode({
3309
+ index,
3310
+ target,
3311
+ ok: true,
3312
+ value: null
3313
+ });
3314
+ const result = {
3315
+ index,
3316
+ target,
3317
+ ok: true,
3318
+ value: known[index] ? runtime.status(target, input.maxItemBytes - metadata) : null
3319
+ };
3320
+ return encode(result) <= input.maxItemBytes ? result : failures[index];
3321
+ } catch (error) {
3322
+ ctx.signal.throwIfAborted();
3323
+ return {
3324
+ ...failures[index],
3325
+ error: {
3326
+ code: "read-limit",
3327
+ message: error instanceof Error ? error.message.slice(0, 64) : "Status read failed"
3328
+ }
3329
+ };
3330
+ }
3331
+ }) };
3332
+ }
1887
3333
  });
1888
3334
  const control = ctx.services.get("agent-context-control");
1889
3335
  ctx.client.registerMethod({
@@ -1910,16 +3356,50 @@ function registerContextMethods(ctx, runtime) {
1910
3356
  /** The service key, restated here because the host that publishes it
1911
3357
  * cannot import this package. */
1912
3358
  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
- });
3359
+ /** Publishes a code-point bound and rejects it without copying an oversized input. */
3360
+ function boundedText(maximum, description) {
3361
+ return z.string().superRefine((text, ctx) => {
3362
+ let count = 0;
3363
+ for (const _point of text) if (++count > maximum) {
3364
+ ctx.addIssue({
3365
+ code: "too_big",
3366
+ origin: "string",
3367
+ maximum,
3368
+ inclusive: true,
3369
+ message: `At most ${maximum} Unicode code points are allowed.`
3370
+ });
3371
+ break;
3372
+ }
3373
+ }).meta({ maxLength: maximum }).describe(description);
3374
+ }
3375
+ const Title = boundedText(60, "Topic title, at most 60 Unicode code points; the service trims surrounding whitespace.");
3376
+ const Digest = boundedText(2e3, "Complete replacement digest, at most 2000 Unicode code points: goal, decisions, progress and next steps.");
3377
+ const Tokens = z.number().int().positive().optional().describe("Desired output tokens; the host may allocate less without changing which fields are written.");
3378
+ /** At least one business field is required; constraints are present in the model-visible schema. */
3379
+ const SessionNoteInput = z.union([z.strictObject({
3380
+ title: Title,
3381
+ digest: Digest.optional(),
3382
+ outputTokens: Tokens
3383
+ }), z.strictObject({
3384
+ title: Title.optional(),
3385
+ digest: Digest,
3386
+ outputTokens: Tokens
3387
+ })]);
3388
+ /** Short ordinary receipts and their historical retained-preview projection. */
3389
+ const SessionNoteOutput = z.union([z.string().max(2048), z.strictObject({
3390
+ ok: z.literal(true),
3391
+ complete: z.literal(false),
3392
+ preview: z.string(),
3393
+ source: z.strictObject({
3394
+ ref: z.string(),
3395
+ sourceComplete: z.boolean(),
3396
+ recoverable: z.literal(true)
3397
+ }),
3398
+ next: z.strictObject({
3399
+ tool: z.literal("context_restore"),
3400
+ arguments: z.strictObject({ pages: z.array(z.strictObject({ ref: z.string() })) })
3401
+ })
3402
+ })]);
1923
3403
  /** What leads the injected digest. It arrives unasked, so it says what it is. */
1924
3404
  const INJECTED_DIGEST_PREFIX = "Your digest of this session, as you last wrote it:\n";
1925
3405
  /** The `volatile` contributor, id `session-digest`: nothing at all while the
@@ -1941,8 +3421,11 @@ function registerSessionTools(ctx, register) {
1941
3421
  const notes = ctx.services.get(SESSION_NOTES_SERVICE);
1942
3422
  register({
1943
3423
  name: "session_note",
3424
+ preload: false,
1944
3425
  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
3426
  inputSchema: SessionNoteInput,
3427
+ outputSchema: SessionNoteOutput,
3428
+ deliveryKind: "receipt",
1946
3429
  async execute(input, call) {
1947
3430
  const lines = [];
1948
3431
  let failed = false;
@@ -2032,7 +3515,9 @@ const timeContributor = {
2032
3515
  const TOOL_NAMES = [
2033
3516
  "context_search",
2034
3517
  "context_restore",
2035
- "session_note"
3518
+ "session_note",
3519
+ "tool_search",
3520
+ "tool_call"
2036
3521
  ];
2037
3522
  //#endregion
2038
3523
  //#region src/index.ts
@@ -2044,14 +3529,17 @@ const TOOL_NAMES = [
2044
3529
  * enumerated: a misspelled tool name is a load failure naming the field, not
2045
3530
  * a line that quietly does nothing.
2046
3531
  */
2047
- const ContextConfig = z.strictObject({ disabled: z.array(z.enum(TOOL_NAMES)).default([]) }).default({ disabled: [] });
3532
+ const ContextConfig = z.strictObject({ disabled: z.array(z.enum(TOOL_NAMES.filter((name) => name !== "tool_search" && name !== "tool_call"))).default([]) }).default({ disabled: [] });
2048
3533
  const contextPlugin = {
2049
3534
  name: "@eum-agent/context-management",
2050
3535
  requires: [
3536
+ "agent-configuration-store",
2051
3537
  "context-framework",
3538
+ "query-resources",
2052
3539
  "session-context-history",
2053
3540
  "session-notes",
2054
- "agent-context-control"
3541
+ "agent-context-control",
3542
+ "session-context"
2055
3543
  ],
2056
3544
  provides: [
2057
3545
  "context-runtime",
@@ -2073,6 +3561,9 @@ const contextPlugin = {
2073
3561
  ctx.services.provide("context-runtime", runtime);
2074
3562
  const disabled = new Set(config.disabled);
2075
3563
  const register = (tool) => disabled.has(tool.name) ? void 0 : ctx.tools.register(tool);
3564
+ ctx.tools.register(toolSearch(ctx));
3565
+ ctx.tools.register(toolCall());
3566
+ registerToolPreload(ctx);
2076
3567
  registerContextTools(ctx, register);
2077
3568
  registerSessionTools(ctx, register);
2078
3569
  ctx.context.contribute(timeContributor);