@peer-agent/runtime-core 0.1.0-rc.36 → 0.1.0-rc.38

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.
@@ -53,7 +53,9 @@ export type ContextAccountingPipelineOptions<TState, TRequest, TResponse> = Read
53
53
  error?: unknown;
54
54
  }>) => void;
55
55
  getOverflow?: (response: TResponse) => ContextOverflowEvidence | null | undefined;
56
- fingerprintRequest?: (request: TRequest) => string;
56
+ fingerprintRequest?: (request: TRequest, options?: {
57
+ readonly refresh?: boolean;
58
+ }) => string;
57
59
  now?: () => number;
58
60
  }>;
59
61
  export type ContextAccountingExecuteInput<TState> = Readonly<{
@@ -89,7 +91,17 @@ export declare function createRestoredObservedContextAccountingSnapshot(input: R
89
91
  pendingUncountedChanges?: boolean;
90
92
  now?: number;
91
93
  }>): ContextAccountingSnapshot;
92
- export declare function fingerprintCanonicalRequest(request: unknown): string;
94
+ /** Counts real canonical JSON.stringify passes, not cache hits. Test seam. */
95
+ export declare function readCanonicalRequestFingerprintEvaluations(): number;
96
+ export declare function resetCanonicalRequestFingerprintEvaluations(): void;
97
+ /**
98
+ * Fingerprint a canonical provider request once per object.
99
+ * A later call with the same reference reuses the digest. Pass `{ refresh: true }`
100
+ * only after an await that may have mutated the request, such as a transport retry.
101
+ */
102
+ export declare function fingerprintCanonicalRequest(request: unknown, options?: {
103
+ readonly refresh?: boolean;
104
+ }): string;
93
105
  export declare function parseContextOverflowEvidence(error: unknown): ContextOverflowEvidence | null;
94
106
  export declare function createContextAccountingCompactionPipeline<TState, TRequest, TResponse>(options: ContextAccountingPipelineOptions<TState, TRequest, TResponse>): Readonly<{
95
107
  execute: (input: ContextAccountingExecuteInput<TState>) => Promise<ContextAccountingExecuteResult<TState, TRequest, TResponse>>;
@@ -126,14 +126,39 @@ function stableValue(value, seen) {
126
126
  seen.delete(value);
127
127
  return result;
128
128
  }
129
- export function fingerprintCanonicalRequest(request) {
129
+ const canonicalFingerprintCache = new WeakMap();
130
+ let canonicalFingerprintEvaluations = 0;
131
+ /** Counts real canonical JSON.stringify passes, not cache hits. Test seam. */
132
+ export function readCanonicalRequestFingerprintEvaluations() {
133
+ return canonicalFingerprintEvaluations;
134
+ }
135
+ export function resetCanonicalRequestFingerprintEvaluations() {
136
+ canonicalFingerprintEvaluations = 0;
137
+ }
138
+ /**
139
+ * Fingerprint a canonical provider request once per object.
140
+ * A later call with the same reference reuses the digest. Pass `{ refresh: true }`
141
+ * only after an await that may have mutated the request, such as a transport retry.
142
+ */
143
+ export function fingerprintCanonicalRequest(request, options) {
144
+ const refresh = options?.refresh === true;
145
+ if (!refresh && request !== null && typeof request === 'object') {
146
+ const cached = canonicalFingerprintCache.get(request);
147
+ if (cached)
148
+ return cached;
149
+ }
130
150
  const text = JSON.stringify(stableValue(request, new WeakSet()));
151
+ canonicalFingerprintEvaluations += 1;
131
152
  let hash = 0x811c9dc5;
132
153
  for (let index = 0; index < text.length; index += 1) {
133
154
  hash ^= text.charCodeAt(index);
134
155
  hash = Math.imul(hash, 0x01000193);
135
156
  }
136
- return `ctx_${(hash >>> 0).toString(16).padStart(8, '0')}_${text.length}`;
157
+ const fingerprint = `ctx_${(hash >>> 0).toString(16).padStart(8, '0')}_${text.length}`;
158
+ if (request !== null && typeof request === 'object') {
159
+ canonicalFingerprintCache.set(request, fingerprint);
160
+ }
161
+ return fingerprint;
137
162
  }
138
163
  function errorDetails(error) {
139
164
  if (error instanceof Error) {
@@ -329,14 +354,12 @@ export function createContextAccountingCompactionPipeline(options) {
329
354
  }
330
355
  }
331
356
  };
332
- const count = async (request, requestFingerprint) => {
357
+ // Exact count must not mutate the canonical request. The digest is taken once
358
+ // after the counter returns, so the count path does not stringify again.
359
+ const count = async (request) => {
333
360
  nextCounted = undefined;
334
361
  if (!options.countRequest || counterStatus === 'degraded')
335
- return;
336
- const before = fingerprint(request);
337
- if (before !== requestFingerprint) {
338
- throw new Error('context_request_fingerprint_mismatch: request changed before exact count');
339
- }
362
+ return null;
340
363
  let rawCount;
341
364
  try {
342
365
  rawCount = await options.countRequest(request);
@@ -347,27 +370,23 @@ export function createContextAccountingCompactionPipeline(options) {
347
370
  // explicitly and continue with observed usage instead of blocking chat.
348
371
  counterStatus = 'degraded';
349
372
  nextCounted = undefined;
350
- return;
351
- }
352
- const counted = exactResult(rawCount, capability);
353
- const after = fingerprint(request);
354
- if (after !== requestFingerprint) {
355
- throw new Error('context_request_fingerprint_mismatch: exact counter mutated the canonical request');
373
+ return null;
356
374
  }
357
- if (!counted)
358
- return;
359
- nextCounted = {
360
- inputTokens: counted.inputTokens,
361
- requestFingerprint,
362
- compactionEpoch,
363
- source: counted.source,
364
- countedAt: now(),
365
- };
375
+ return exactResult(rawCount, capability);
366
376
  };
367
377
  const build = async (state) => {
368
378
  const request = await options.buildRequest(state);
379
+ const counted = await count(request);
369
380
  const requestFingerprint = fingerprint(request);
370
- await count(request, requestFingerprint);
381
+ if (counted) {
382
+ nextCounted = {
383
+ inputTokens: counted.inputTokens,
384
+ requestFingerprint,
385
+ compactionEpoch,
386
+ source: counted.source,
387
+ countedAt: now(),
388
+ };
389
+ }
371
390
  latestBuiltFingerprint = requestFingerprint;
372
391
  latestBuiltRequest = request;
373
392
  return { request, requestFingerprint };
@@ -4,6 +4,8 @@
4
4
  * Desktop send, Desktop restore and CLI/TUI restore must all cross this seam.
5
5
  * Provider adapters may lower the camelCase tool fields to their wire format,
6
6
  * but must not reinterpret persisted segments.
7
+ * Oversized tool bodies stay intact here so the host can spill them to a
8
+ * local file before the provider request. This projector does not drop them.
7
9
  */
8
10
  export declare const CANONICAL_HISTORY_PROJECTOR_VERSION = 2;
9
11
  export type CanonicalHistoryContentPart = {
@@ -50,3 +52,11 @@ export declare function formatCanonicalHistoricalLocalRecord(input: {
50
52
  readonly result?: unknown;
51
53
  }): string;
52
54
  export declare function projectConversationHistory(values: readonly unknown[]): CanonicalConversationHistory;
55
+ /**
56
+ * Same projection as projectConversationHistory, but yields during the scan so
57
+ * a long open-session restore does not hold the main thread until it finishes.
58
+ */
59
+ export declare function projectConversationHistoryYielding(values: readonly unknown[], options?: {
60
+ readonly yieldEvery?: number;
61
+ readonly yield?: () => Promise<void>;
62
+ }): Promise<CanonicalConversationHistory>;
@@ -5,6 +5,8 @@ import { formatResourceFeedbackContext, projectResourceFeedbackTransport } from
5
5
  * Desktop send, Desktop restore and CLI/TUI restore must all cross this seam.
6
6
  * Provider adapters may lower the camelCase tool fields to their wire format,
7
7
  * but must not reinterpret persisted segments.
8
+ * Oversized tool bodies stay intact here so the host can spill them to a
9
+ * local file before the provider request. This projector does not drop them.
8
10
  */
9
11
  export const CANONICAL_HISTORY_PROJECTOR_VERSION = 2;
10
12
  function recordOf(value) {
@@ -440,19 +442,7 @@ function projectMessage(value) {
440
442
  }
441
443
  return [];
442
444
  }
443
- export function projectConversationHistory(values) {
444
- const messages = Array.isArray(values) ? values : [];
445
- let compactionBoundaryIndex = -1;
446
- let continuity;
447
- messages.forEach((value, index) => {
448
- const message = recordOf(value);
449
- if (!message || !compactionMarker(message))
450
- return;
451
- compactionBoundaryIndex = index;
452
- continuity = continuityFromBoundary(message, index);
453
- });
454
- const active = foldLegacyToolRows(messages.slice(compactionBoundaryIndex + 1));
455
- const projectedMessages = active.flatMap(projectMessage);
445
+ function finishCanonicalHistory(compactionBoundaryIndex, continuity, projectedMessages) {
456
446
  const fingerprintInput = JSON.stringify({
457
447
  projectorVersion: CANONICAL_HISTORY_PROJECTOR_VERSION,
458
448
  compactionBoundaryIndex,
@@ -475,3 +465,51 @@ export function projectConversationHistory(values) {
475
465
  historyFingerprint: `history-v${CANONICAL_HISTORY_PROJECTOR_VERSION}-${(hash >>> 0).toString(16).padStart(8, '0')}`,
476
466
  };
477
467
  }
468
+ function scanCompactionBoundary(messages) {
469
+ let compactionBoundaryIndex = -1;
470
+ let continuity;
471
+ messages.forEach((value, index) => {
472
+ const message = recordOf(value);
473
+ if (!message || !compactionMarker(message))
474
+ return;
475
+ compactionBoundaryIndex = index;
476
+ continuity = continuityFromBoundary(message, index);
477
+ });
478
+ return { compactionBoundaryIndex, continuity };
479
+ }
480
+ export function projectConversationHistory(values) {
481
+ const messages = Array.isArray(values) ? values : [];
482
+ const scanned = scanCompactionBoundary(messages);
483
+ const active = foldLegacyToolRows(messages.slice(scanned.compactionBoundaryIndex + 1));
484
+ return finishCanonicalHistory(scanned.compactionBoundaryIndex, scanned.continuity, active.flatMap(projectMessage));
485
+ }
486
+ /**
487
+ * Same projection as projectConversationHistory, but yields during the scan so
488
+ * a long open-session restore does not hold the main thread until it finishes.
489
+ */
490
+ export async function projectConversationHistoryYielding(values, options) {
491
+ const messages = Array.isArray(values) ? values : [];
492
+ const yieldEvery = Math.max(1, options?.yieldEvery ?? 200);
493
+ const pause = options?.yield ?? (() => new Promise((resolve) => {
494
+ setTimeout(resolve, 0);
495
+ }));
496
+ let compactionBoundaryIndex = -1;
497
+ let continuity;
498
+ for (let index = 0; index < messages.length; index += 1) {
499
+ if (index > 0 && index % yieldEvery === 0)
500
+ await pause();
501
+ const message = recordOf(messages[index]);
502
+ if (!message || !compactionMarker(message))
503
+ continue;
504
+ compactionBoundaryIndex = index;
505
+ continuity = continuityFromBoundary(message, index);
506
+ }
507
+ const active = foldLegacyToolRows(messages.slice(compactionBoundaryIndex + 1));
508
+ const projectedMessages = [];
509
+ for (let index = 0; index < active.length; index += 1) {
510
+ if (index > 0 && index % yieldEvery === 0)
511
+ await pause();
512
+ projectedMessages.push(...projectMessage(active[index]));
513
+ }
514
+ return finishCanonicalHistory(compactionBoundaryIndex, continuity, projectedMessages);
515
+ }
@@ -2,6 +2,12 @@ export declare const MICROCOMPACTION_CONFIG: Readonly<{
2
2
  keepRecentCount: 8;
3
3
  triggerChars: 6000;
4
4
  previewChars: 800;
5
+ /**
6
+ * Hard cap for one tool-result body in a provider request.
7
+ * The recent window stays more complete than older history, but it cannot
8
+ * carry a multi-megabyte tool body. File reads under this cap stay inline.
9
+ */
10
+ recentToolResultChars: 32000;
5
11
  }>;
6
12
  /** 宽松消息形状:兼容 Desktop apiMessages 与 TUI ModelMessage(无索引签名接口)。 */
7
13
  export type MicrocompactMessage = {
@@ -31,6 +37,12 @@ export declare function extractRecoverableClues(text: unknown, { limit }?: {
31
37
  paths: string[];
32
38
  suggestedRetrieval: string[];
33
39
  };
40
+ /**
41
+ * Bound one tool-result body before it is serialized into a provider request.
42
+ * Small and already-structured results pass through. Oversized text keeps a
43
+ * retrieval skeleton or a short preview, including original size.
44
+ */
45
+ export declare function boundProviderToolResultContent(content: string, maxChars?: number): string;
34
46
  /**
35
47
  * 对「最近 keepRecentCount 条非 system 消息之外」的历史消息做证据引用化/预览化。
36
48
  * system 与 `_compaction` handoff 不参与;已是 local_*_ref 的结果保留骨架不重复截断。
@@ -11,6 +11,12 @@ export const MICROCOMPACTION_CONFIG = Object.freeze({
11
11
  keepRecentCount: 8,
12
12
  triggerChars: 6_000,
13
13
  previewChars: 800,
14
+ /**
15
+ * Hard cap for one tool-result body in a provider request.
16
+ * The recent window stays more complete than older history, but it cannot
17
+ * carry a multi-megabyte tool body. File reads under this cap stay inline.
18
+ */
19
+ recentToolResultChars: 32_000,
14
20
  });
15
21
  export function previewHistoricalText(text, maxChars = MICROCOMPACTION_CONFIG.previewChars) {
16
22
  const value = String(text ?? '');
@@ -282,6 +288,82 @@ function microcompactBlockContent(block, config) {
282
288
  }
283
289
  return { block, compacted: false, beforeChars: 0, afterChars: 0 };
284
290
  }
291
+ /**
292
+ * Bound one tool-result body before it is serialized into a provider request.
293
+ * Small and already-structured results pass through. Oversized text keeps a
294
+ * retrieval skeleton or a short preview, including original size.
295
+ */
296
+ export function boundProviderToolResultContent(content, maxChars = MICROCOMPACTION_CONFIG.recentToolResultChars) {
297
+ if (content.length <= maxChars)
298
+ return content;
299
+ const previewChars = Math.min(MICROCOMPACTION_CONFIG.previewChars, Math.max(200, maxChars));
300
+ const parsed = tryParseJsonObject(content);
301
+ if (parsed) {
302
+ const ref = compactLocalRefPayload(parsed, previewChars);
303
+ const shrunk = ref ?? shrinkOversizedToolRecord(parsed, previewChars, content.length);
304
+ const next = JSON.stringify(ref ? { ...shrunk, originalChars: content.length } : shrunk);
305
+ if (next.length <= maxChars && next.length < content.length)
306
+ return next;
307
+ }
308
+ const preview = compactLongHistoricalString(content, previewChars);
309
+ return preview.length <= maxChars ? preview : preview.slice(0, maxChars);
310
+ }
311
+ function shrinkOversizedToolRecord(value, previewChars, originalChars) {
312
+ const next = {
313
+ contextPreviewTruncated: true,
314
+ originalChars,
315
+ note: 'Tool result omitted from provider history; use artifact, path, or evidence refs for the full output.',
316
+ };
317
+ for (const [key, item] of Object.entries(value)) {
318
+ if (typeof item === 'string') {
319
+ next[key] = item.length > previewChars ? previewHistoricalText(item, previewChars) : item;
320
+ continue;
321
+ }
322
+ if (Array.isArray(item)) {
323
+ next[key] = item.length > 16 ? item.slice(0, 16) : item;
324
+ continue;
325
+ }
326
+ if (item && typeof item === 'object') {
327
+ const nested = shrinkOversizedToolRecord(item, Math.min(previewChars, 400), originalChars);
328
+ delete nested.note;
329
+ delete nested.originalChars;
330
+ next[key] = nested;
331
+ continue;
332
+ }
333
+ next[key] = item;
334
+ }
335
+ return next;
336
+ }
337
+ function boundToolMessageContent(content, maxChars) {
338
+ if (typeof content === 'string') {
339
+ const next = boundProviderToolResultContent(content, maxChars);
340
+ return {
341
+ content: next,
342
+ bounded: next !== content,
343
+ beforeChars: content.length,
344
+ afterChars: next.length,
345
+ };
346
+ }
347
+ if (!Array.isArray(content)) {
348
+ return { content, bounded: false, beforeChars: 0, afterChars: 0 };
349
+ }
350
+ let bounded = false;
351
+ let beforeChars = 0;
352
+ let afterChars = 0;
353
+ const blocks = content.map((block) => {
354
+ const record = block;
355
+ if (record?.type !== 'tool_result' || typeof record.content !== 'string')
356
+ return block;
357
+ const next = boundProviderToolResultContent(record.content, maxChars);
358
+ if (next === record.content)
359
+ return block;
360
+ bounded = true;
361
+ beforeChars += record.content.length;
362
+ afterChars += next.length;
363
+ return { ...record, content: next };
364
+ });
365
+ return { content: blocks, bounded, beforeChars, afterChars };
366
+ }
285
367
  function microcompactMessageContent(content, config) {
286
368
  if (typeof content === 'string') {
287
369
  const result = microcompactStringContent(content, config);
@@ -329,9 +411,27 @@ export function microcompactMessagesForContext(messages, options = {}) {
329
411
  let compactedCount = 0;
330
412
  let beforeChars = 0;
331
413
  let afterChars = 0;
414
+ const recentCap = config.recentToolResultChars;
332
415
  const nextMessages = messages.map((message, index) => {
333
- if (!compactableIndexes.has(index))
334
- return message;
416
+ if (!compactableIndexes.has(index)) {
417
+ if (message?.role !== 'tool' && !Array.isArray(message?.content))
418
+ return message;
419
+ const bounded = boundToolMessageContent(message?.content, recentCap);
420
+ if (!bounded.bounded)
421
+ return message;
422
+ compactedCount++;
423
+ beforeChars += bounded.beforeChars;
424
+ afterChars += bounded.afterChars;
425
+ return {
426
+ ...message,
427
+ content: bounded.content,
428
+ _microCompaction: {
429
+ method: 'provider_tool_result_cap',
430
+ beforeChars: bounded.beforeChars,
431
+ afterChars: bounded.afterChars,
432
+ },
433
+ };
434
+ }
335
435
  const result = microcompactMessageContent(message.content, config);
336
436
  if (!result.compacted)
337
437
  return message;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peer-agent/runtime-core",
3
- "version": "0.1.0-rc.36",
3
+ "version": "0.1.0-rc.38",
4
4
  "description": "Host-neutral capability, permission, projection, and Evidence primitives for Peer Agent runtimes.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -38,7 +38,7 @@
38
38
  "LICENSE"
39
39
  ],
40
40
  "dependencies": {
41
- "@peer-agent/protocol": "0.1.0-rc.36"
41
+ "@peer-agent/protocol": "0.1.0-rc.38"
42
42
  },
43
43
  "devDependencies": {
44
44
  "typescript": "^5.9.3"