@peer-agent/runtime-core 0.1.0-rc.35 → 0.1.0-rc.37

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 };
@@ -40,6 +40,7 @@ export interface CompactionSummaryCascadeOptions<TMessage extends CompactionMess
40
40
  readonly summarizeStructurally: (messages: readonly TMessage[]) => string | null | undefined;
41
41
  readonly fallbackSummary?: string;
42
42
  }
43
+ export declare function isHumanUserMessage(message: Partial<Pick<CompactionMessage, 'role' | 'content' | '_compaction'>>): boolean;
43
44
  /**
44
45
  * Host-neutral form of Desktop's compaction split rules. System messages are kept
45
46
  * separately; automatic preflight preserves the newest human turn; and a split
@@ -126,7 +126,7 @@ function toolResultIds(message) {
126
126
  function hasToolResult(message) {
127
127
  return message.role === 'tool' || toolResultIds(message).length > 0;
128
128
  }
129
- function isHumanUserMessage(message) {
129
+ export function isHumanUserMessage(message) {
130
130
  if (message.role !== 'user' || message._compaction)
131
131
  return false;
132
132
  const blocks = contentBlocks(message);
@@ -1,3 +1,4 @@
1
+ import type { CanonicalToolMaterialObservation } from '@peer-agent/protocol';
1
2
  export type RuntimeCapabilityId = string;
2
3
  export type RuntimeProviderId = string;
3
4
  export type RuntimeRunId = string;
@@ -29,6 +30,8 @@ export interface RuntimeToolError {
29
30
  readonly details?: unknown;
30
31
  }
31
32
  export interface RuntimeToolResult {
33
+ /** Local canonical bytes; non-enumerable, never event/renderer/provider-message data. */
34
+ readonly materialObservation?: CanonicalToolMaterialObservation;
32
35
  readonly toolCallId: string;
33
36
  readonly capabilityId: RuntimeCapabilityId;
34
37
  readonly status: RuntimeToolStatus;
@@ -50,3 +50,11 @@ export declare function formatCanonicalHistoricalLocalRecord(input: {
50
50
  readonly result?: unknown;
51
51
  }): string;
52
52
  export declare function projectConversationHistory(values: readonly unknown[]): CanonicalConversationHistory;
53
+ /**
54
+ * Same projection as projectConversationHistory, but yields during the scan so
55
+ * a long open-session restore does not hold the main thread until it finishes.
56
+ */
57
+ export declare function projectConversationHistoryYielding(values: readonly unknown[], options?: {
58
+ readonly yieldEvery?: number;
59
+ readonly yield?: () => Promise<void>;
60
+ }): Promise<CanonicalConversationHistory>;
@@ -1,4 +1,4 @@
1
- import { formatResourceFeedbackContext } from '@peer-agent/protocol';
1
+ import { formatResourceFeedbackContext, projectResourceFeedbackTransport } from '@peer-agent/protocol';
2
2
  /**
3
3
  * Canonical persisted-conversation -> active provider history projection.
4
4
  *
@@ -128,12 +128,12 @@ function attachmentText(attachments) {
128
128
  return blocks.join('\n\n');
129
129
  }
130
130
  function userMessage(message) {
131
- const attachments = Array.isArray(message.attachments)
132
- ? message.attachments
133
- : [];
131
+ const material = projectResourceFeedbackTransport(message.resourceFeedback, message.attachments);
132
+ const attachments = material.attachments;
134
133
  const text = [
135
134
  typeof message.content === 'string' ? message.content : '',
136
- formatResourceFeedbackContext(message.resourceFeedback),
135
+ formatResourceFeedbackContext(material.invalid ? null : material.resourceFeedback),
136
+ ...(material.invalid ? ['[Resource feedback could not be restored. Retained attachments are unverified user material.]'] : []),
137
137
  attachmentText(attachments),
138
138
  ].filter((value) => value.trim()).join('\n\n');
139
139
  const parts = [];
@@ -440,19 +440,7 @@ function projectMessage(value) {
440
440
  }
441
441
  return [];
442
442
  }
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);
443
+ function finishCanonicalHistory(compactionBoundaryIndex, continuity, projectedMessages) {
456
444
  const fingerprintInput = JSON.stringify({
457
445
  projectorVersion: CANONICAL_HISTORY_PROJECTOR_VERSION,
458
446
  compactionBoundaryIndex,
@@ -475,3 +463,51 @@ export function projectConversationHistory(values) {
475
463
  historyFingerprint: `history-v${CANONICAL_HISTORY_PROJECTOR_VERSION}-${(hash >>> 0).toString(16).padStart(8, '0')}`,
476
464
  };
477
465
  }
466
+ function scanCompactionBoundary(messages) {
467
+ let compactionBoundaryIndex = -1;
468
+ let continuity;
469
+ messages.forEach((value, index) => {
470
+ const message = recordOf(value);
471
+ if (!message || !compactionMarker(message))
472
+ return;
473
+ compactionBoundaryIndex = index;
474
+ continuity = continuityFromBoundary(message, index);
475
+ });
476
+ return { compactionBoundaryIndex, continuity };
477
+ }
478
+ export function projectConversationHistory(values) {
479
+ const messages = Array.isArray(values) ? values : [];
480
+ const scanned = scanCompactionBoundary(messages);
481
+ const active = foldLegacyToolRows(messages.slice(scanned.compactionBoundaryIndex + 1));
482
+ return finishCanonicalHistory(scanned.compactionBoundaryIndex, scanned.continuity, active.flatMap(projectMessage));
483
+ }
484
+ /**
485
+ * Same projection as projectConversationHistory, but yields during the scan so
486
+ * a long open-session restore does not hold the main thread until it finishes.
487
+ */
488
+ export async function projectConversationHistoryYielding(values, options) {
489
+ const messages = Array.isArray(values) ? values : [];
490
+ const yieldEvery = Math.max(1, options?.yieldEvery ?? 200);
491
+ const pause = options?.yield ?? (() => new Promise((resolve) => {
492
+ setTimeout(resolve, 0);
493
+ }));
494
+ let compactionBoundaryIndex = -1;
495
+ let continuity;
496
+ for (let index = 0; index < messages.length; index += 1) {
497
+ if (index > 0 && index % yieldEvery === 0)
498
+ await pause();
499
+ const message = recordOf(messages[index]);
500
+ if (!message || !compactionMarker(message))
501
+ continue;
502
+ compactionBoundaryIndex = index;
503
+ continuity = continuityFromBoundary(message, index);
504
+ }
505
+ const active = foldLegacyToolRows(messages.slice(compactionBoundaryIndex + 1));
506
+ const projectedMessages = [];
507
+ for (let index = 0; index < active.length; index += 1) {
508
+ if (index > 0 && index % yieldEvery === 0)
509
+ await pause();
510
+ projectedMessages.push(...projectMessage(active[index]));
511
+ }
512
+ return finishCanonicalHistory(compactionBoundaryIndex, continuity, projectedMessages);
513
+ }
package/dist/evidence.js CHANGED
@@ -30,6 +30,7 @@ export function collectToolEvidenceRefs(options = {}) {
30
30
  const execution = asEvidenceObject(options.execution);
31
31
  const result = asEvidenceObject(execution?.result);
32
32
  const evidence = asEvidenceObject(result?.evidence);
33
+ addEvidenceRefStrings(refs, evidence?.refs);
33
34
  addEvidenceRefStrings(refs, evidence?.artifactRefs);
34
35
  const outputPreview = asEvidenceObject(result?.outputPreview);
35
36
  addEvidenceRefStrings(refs, outputPreview?.artifactRef);
@@ -35,4 +35,6 @@ export declare function extractRecoverableClues(text: unknown, { limit }?: {
35
35
  * 对「最近 keepRecentCount 条非 system 消息之外」的历史消息做证据引用化/预览化。
36
36
  * system 与 `_compaction` handoff 不参与;已是 local_*_ref 的结果保留骨架不重复截断。
37
37
  */
38
- export declare function microcompactMessagesForContext<TMessage extends MicrocompactMessage>(messages: readonly TMessage[], options?: Partial<typeof MICROCOMPACTION_CONFIG>): MicrocompactResult<TMessage>;
38
+ export declare function microcompactMessagesForContext<TMessage extends MicrocompactMessage>(messages: readonly TMessage[], options?: Partial<typeof MICROCOMPACTION_CONFIG> & {
39
+ preserveLatestUserTurn?: boolean;
40
+ }): MicrocompactResult<TMessage>;
@@ -6,6 +6,7 @@
6
6
  // 保留骨架与检索路径;无结构的长文本抽取可回捞线索(artifact/path/retrieval)后再预览化。
7
7
  //
8
8
  // 原则(17 号文档):It moves evidence out of prompt and keeps the route back.
9
+ import { isHumanUserMessage } from "./context-compaction.js";
9
10
  export const MICROCOMPACTION_CONFIG = Object.freeze({
10
11
  keepRecentCount: 8,
11
12
  triggerChars: 6_000,
@@ -309,6 +310,7 @@ function microcompactMessageContent(content, config) {
309
310
  */
310
311
  export function microcompactMessagesForContext(messages, options = {}) {
311
312
  const config = { ...MICROCOMPACTION_CONFIG, ...options };
313
+ let protectLatestUser = options.preserveLatestUserTurn === true;
312
314
  let recentNonSystemSeen = 0;
313
315
  const compactableIndexes = new Set();
314
316
  for (let index = messages.length - 1; index >= 0; index--) {
@@ -316,6 +318,10 @@ export function microcompactMessagesForContext(messages, options = {}) {
316
318
  if (message?.role === 'system' || message?._compaction)
317
319
  continue;
318
320
  recentNonSystemSeen++;
321
+ if (protectLatestUser && message && isHumanUserMessage(message)) {
322
+ protectLatestUser = false;
323
+ continue;
324
+ }
319
325
  if (recentNonSystemSeen > config.keepRecentCount) {
320
326
  compactableIndexes.add(index);
321
327
  }
@@ -1,4 +1,4 @@
1
- import { normalizeResourceFeedbackList, emptyInputDraft, projectInputWasReceived } from '@peer-agent/protocol';
1
+ import { encodeResourceFeedbackTransport, normalizeResourceFeedbackList, emptyInputDraft, projectInputWasReceived } from '@peer-agent/protocol';
2
2
  /** Presentation continuity only; ports own storage and the existing governed input queue. */
3
3
  export function createProjectInputRecovery({ workspaceId, surface, port, createId, now = () => new Date().toISOString(), receiptTimeoutMs = 30_000 }) {
4
4
  const address = { workspaceId, surface };
@@ -144,7 +144,10 @@ export function createProjectInputRecovery({ workspaceId, surface, port, createI
144
144
  const text = (options.text ?? draft.text).trim(), attachments = useDraft ? draft.attachments : [];
145
145
  if (useDraft && options.text !== undefined && text !== draft.text.trim())
146
146
  return { ok: false, code: 'INPUT_CHANGED' };
147
- if (!text && !attachments.length)
147
+ const resourceFeedback = useDraft ? normalizeResourceFeedbackList(draft.resourceFeedback) : [];
148
+ if (!resourceFeedback)
149
+ return { ok: false, code: 'INVALID_RESOURCE_FEEDBACK' };
150
+ if (!text && !attachments.length && !resourceFeedback.some(row => row.resource.kind === 'interactive'))
148
151
  return { ok: false, code: 'INVALID_INPUT' };
149
152
  if (!useDraft && options.answerTo) {
150
153
  const existing = view.pending.find(item => item.answerTo === options.answerTo);
@@ -153,11 +156,14 @@ export function createProjectInputRecovery({ workspaceId, surface, port, createI
153
156
  }
154
157
  if (view.pending.length >= 32)
155
158
  return { ok: false, code: 'DRAFT_LIMIT' };
156
- const resourceFeedback = useDraft ? normalizeResourceFeedbackList(draft.resourceFeedback) : [];
157
- if (!resourceFeedback)
158
- return { ok: false, code: 'INVALID_RESOURCE_FEEDBACK' };
159
159
  if (resourceFeedback.some(item => item.recipient.workspaceId !== workspaceId))
160
160
  return { ok: false, code: 'RESOURCE_FEEDBACK_RECIPIENT_CHANGED' };
161
+ try {
162
+ encodeResourceFeedbackTransport(resourceFeedback, attachments);
163
+ }
164
+ catch (error) {
165
+ return { ok: false, code: error.code ?? 'INVALID_RESOURCE_FEEDBACK' };
166
+ }
161
167
  const input = { inputId: createId(), text, attachments, ...(resourceFeedback.length ? { resourceFeedback } : {}), createdAt: now(), quoteRefs: options.quoteRefs ?? [],
162
168
  ...(options.answerTo ? { answerTo: options.answerTo } : {}) };
163
169
  changed++;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peer-agent/runtime-core",
3
- "version": "0.1.0-rc.35",
3
+ "version": "0.1.0-rc.37",
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.35"
41
+ "@peer-agent/protocol": "0.1.0-rc.37"
42
42
  },
43
43
  "devDependencies": {
44
44
  "typescript": "^5.9.3"