@peer-agent/runtime-core 0.1.0-rc.5 → 0.1.0-rc.51

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.
@@ -6,10 +6,17 @@
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,
12
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,
13
20
  });
14
21
  export function previewHistoricalText(text, maxChars = MICROCOMPACTION_CONFIG.previewChars) {
15
22
  const value = String(text ?? '');
@@ -281,6 +288,82 @@ function microcompactBlockContent(block, config) {
281
288
  }
282
289
  return { block, compacted: false, beforeChars: 0, afterChars: 0 };
283
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
+ }
284
367
  function microcompactMessageContent(content, config) {
285
368
  if (typeof content === 'string') {
286
369
  const result = microcompactStringContent(content, config);
@@ -309,6 +392,7 @@ function microcompactMessageContent(content, config) {
309
392
  */
310
393
  export function microcompactMessagesForContext(messages, options = {}) {
311
394
  const config = { ...MICROCOMPACTION_CONFIG, ...options };
395
+ let protectLatestUser = options.preserveLatestUserTurn === true;
312
396
  let recentNonSystemSeen = 0;
313
397
  const compactableIndexes = new Set();
314
398
  for (let index = messages.length - 1; index >= 0; index--) {
@@ -316,6 +400,10 @@ export function microcompactMessagesForContext(messages, options = {}) {
316
400
  if (message?.role === 'system' || message?._compaction)
317
401
  continue;
318
402
  recentNonSystemSeen++;
403
+ if (protectLatestUser && message && isHumanUserMessage(message)) {
404
+ protectLatestUser = false;
405
+ continue;
406
+ }
319
407
  if (recentNonSystemSeen > config.keepRecentCount) {
320
408
  compactableIndexes.add(index);
321
409
  }
@@ -323,9 +411,27 @@ export function microcompactMessagesForContext(messages, options = {}) {
323
411
  let compactedCount = 0;
324
412
  let beforeChars = 0;
325
413
  let afterChars = 0;
414
+ const recentCap = config.recentToolResultChars;
326
415
  const nextMessages = messages.map((message, index) => {
327
- if (!compactableIndexes.has(index))
328
- 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
+ }
329
435
  const result = microcompactMessageContent(message.content, config);
330
436
  if (!result.compacted)
331
437
  return message;
@@ -0,0 +1,49 @@
1
+ import { type InputDraftValue, type LocalInputSurface, type ProjectAgentSubmitInputResult, type ProjectInputDraftSnapshot, type ProjectInputMutationResult, type ProjectInputRecoveryPort, type UnconfirmedProjectInput } from '@peer-agent/protocol';
2
+ export interface InputRecoveryView extends ProjectInputDraftSnapshot {
3
+ readonly ready: boolean;
4
+ readonly error: string | null;
5
+ readonly sending: readonly string[];
6
+ readonly received: readonly UnconfirmedProjectInput[];
7
+ readonly rejected: Readonly<Record<string, string>>;
8
+ readonly mutating: readonly string[];
9
+ }
10
+ /** Presentation continuity only; ports own storage and the existing governed input queue. */
11
+ export declare function createProjectInputRecovery({ workspaceId, surface, port, createId, now, receiptTimeoutMs, debounceMs, maxWaitMs }: {
12
+ workspaceId: string;
13
+ surface: LocalInputSurface;
14
+ port: ProjectInputRecoveryPort;
15
+ createId: () => string;
16
+ now?: () => string;
17
+ receiptTimeoutMs?: number;
18
+ debounceMs?: number;
19
+ maxWaitMs?: number;
20
+ }): {
21
+ getSnapshot: () => InputRecoveryView;
22
+ subscribe(fn: () => void): () => void;
23
+ load: () => Promise<boolean>;
24
+ edit: (patch: Partial<InputDraftValue>) => void;
25
+ flush: () => Promise<boolean>;
26
+ acknowledge: (ids: readonly string[]) => void;
27
+ send: (options?: {
28
+ text?: string;
29
+ quoteRefs?: readonly string[];
30
+ taskRefs?: readonly import("@peer-agent/protocol").InputDraftTaskRef[];
31
+ answerTo?: string;
32
+ useDraft?: boolean;
33
+ }) => Promise<ProjectAgentSubmitInputResult>;
34
+ dispose: () => Promise<boolean>;
35
+ hasUnsavedChanges: () => boolean;
36
+ discard: (inputId: string) => Promise<ProjectInputMutationResult>;
37
+ restoreToDraft: (inputId: string, options?: {
38
+ readonly replaceDraft?: boolean;
39
+ }) => Promise<ProjectInputMutationResult>;
40
+ observeReceived(ids: readonly string[], answered?: readonly {
41
+ readonly answerTo: string;
42
+ readonly text: string;
43
+ }[]): void;
44
+ retry(inputId: string): Promise<ProjectAgentSubmitInputResult> | Promise<{
45
+ ok: boolean;
46
+ code: string;
47
+ }>;
48
+ };
49
+ export type ProjectInputRecovery = ReturnType<typeof createProjectInputRecovery>;