@peer-agent/runtime-core 0.0.1-beta.43

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 (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +26 -0
  3. package/dist/capability-registry.d.ts +15 -0
  4. package/dist/capability-registry.js +88 -0
  5. package/dist/compaction-progress.d.ts +51 -0
  6. package/dist/compaction-progress.js +83 -0
  7. package/dist/context-accounting-lifecycle.d.ts +41 -0
  8. package/dist/context-accounting-lifecycle.js +90 -0
  9. package/dist/context-accounting-pipeline.d.ts +98 -0
  10. package/dist/context-accounting-pipeline.js +561 -0
  11. package/dist/context-compaction.d.ts +70 -0
  12. package/dist/context-compaction.js +192 -0
  13. package/dist/context-projection-lifecycle.d.ts +32 -0
  14. package/dist/context-projection-lifecycle.js +65 -0
  15. package/dist/context-projection.d.ts +74 -0
  16. package/dist/context-projection.js +183 -0
  17. package/dist/contracts.d.ts +218 -0
  18. package/dist/contracts.js +1 -0
  19. package/dist/conversation-history-projector.d.ts +52 -0
  20. package/dist/conversation-history-projector.js +472 -0
  21. package/dist/decision.d.ts +4 -0
  22. package/dist/decision.js +23 -0
  23. package/dist/evidence.d.ts +64 -0
  24. package/dist/evidence.js +127 -0
  25. package/dist/hooks.d.ts +5 -0
  26. package/dist/hooks.js +4 -0
  27. package/dist/index.d.ts +18 -0
  28. package/dist/index.js +18 -0
  29. package/dist/local-tool-contracts.d.ts +60 -0
  30. package/dist/local-tool-contracts.js +64 -0
  31. package/dist/microcompact.d.ts +38 -0
  32. package/dist/microcompact.js +354 -0
  33. package/dist/permission.d.ts +18 -0
  34. package/dist/permission.js +50 -0
  35. package/dist/projection-materializers.d.ts +18 -0
  36. package/dist/projection-materializers.js +34 -0
  37. package/dist/projection.d.ts +15 -0
  38. package/dist/projection.js +78 -0
  39. package/dist/runtime-usage-accounting.d.ts +19 -0
  40. package/dist/runtime-usage-accounting.js +79 -0
  41. package/package.json +47 -0
@@ -0,0 +1,561 @@
1
+ import { CONTEXT_PROJECTION_CONFIG, decideContextCompaction, isPromptTooLongError, } from "./context-projection.js";
2
+ function finiteTokenCount(value) {
3
+ return typeof value === 'number' && Number.isFinite(value) && value > 0
4
+ ? Math.floor(value)
5
+ : 0;
6
+ }
7
+ function finiteWindow(value) {
8
+ const count = finiteTokenCount(value);
9
+ return count > 0 ? count : null;
10
+ }
11
+ function finiteRevision(value) {
12
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0
13
+ ? value
14
+ : 0;
15
+ }
16
+ export function normalizeObservedInputTokens(usage) {
17
+ if (!usage)
18
+ return null;
19
+ const input = finiteTokenCount(usage.inputTokens);
20
+ const cacheRead = finiteTokenCount(usage.cacheReadTokens);
21
+ const total = usage.inputIncludesCache ? input : input + cacheRead;
22
+ return total > 0 ? total : null;
23
+ }
24
+ /**
25
+ * Restores the last provider-backed baseline for observed-only channels.
26
+ *
27
+ * The restored number describes the last request actually measured by the
28
+ * provider. It remains marked pending because the assistant response and any
29
+ * later durable changes have not yet been measured as the next request.
30
+ */
31
+ export function createRestoredObservedContextAccountingSnapshot(input) {
32
+ const contextWindow = finiteWindow(input.contextWindow);
33
+ const inputTokens = normalizeObservedInputTokens(input.usage);
34
+ const revision = finiteRevision(input.revision);
35
+ const compactionEpoch = finiteRevision(input.compactionEpoch ?? input.usage?.compactionEpoch);
36
+ if (inputTokens == null) {
37
+ return {
38
+ version: 1,
39
+ conversationId: input.identity.conversationId,
40
+ contentRevision: finiteRevision(input.identity.contentRevision),
41
+ modelKey: input.identity.modelKey,
42
+ revision,
43
+ phase: 'restored',
44
+ compactionEpoch,
45
+ contextWindow,
46
+ inputBudget: contextWindow,
47
+ compactionThresholdTokens: contextWindow == null
48
+ ? null
49
+ : Math.floor(contextWindow * CONTEXT_PROJECTION_CONFIG.triggerRatio),
50
+ authoritativeInputTokens: null,
51
+ percent: null,
52
+ pressureSource: 'unknown',
53
+ pendingUncountedChanges: input.pendingUncountedChanges ?? true,
54
+ pendingContentChars: 0,
55
+ countCapability: input.countCapability,
56
+ counterStatus: 'active',
57
+ updatedAt: input.now ?? Date.now(),
58
+ };
59
+ }
60
+ const restoredObservedAt = Number(input.usage?.observedAt);
61
+ const observedAt = Number.isFinite(restoredObservedAt) && restoredObservedAt >= 0
62
+ ? restoredObservedAt
63
+ : input.now ?? Date.now();
64
+ const restoredFingerprint = typeof input.usage?.requestFingerprint === 'string'
65
+ ? input.usage.requestFingerprint.trim()
66
+ : '';
67
+ const requestFingerprint = restoredFingerprint
68
+ || `restored_observation_${input.identity.conversationId}_${compactionEpoch}`;
69
+ return {
70
+ version: 1,
71
+ conversationId: input.identity.conversationId,
72
+ contentRevision: finiteRevision(input.identity.contentRevision),
73
+ modelKey: input.identity.modelKey,
74
+ revision,
75
+ phase: 'restored',
76
+ compactionEpoch,
77
+ contextWindow,
78
+ inputBudget: contextWindow,
79
+ compactionThresholdTokens: contextWindow == null
80
+ ? null
81
+ : Math.floor(contextWindow * CONTEXT_PROJECTION_CONFIG.triggerRatio),
82
+ authoritativeInputTokens: inputTokens,
83
+ percent: contextWindow == null
84
+ ? null
85
+ : Math.min(100, Math.round((inputTokens / contextWindow) * 100)),
86
+ pressureSource: 'provider_usage',
87
+ pendingUncountedChanges: input.pendingUncountedChanges ?? true,
88
+ pendingContentChars: 0,
89
+ countCapability: input.countCapability,
90
+ counterStatus: 'active',
91
+ updatedAt: observedAt,
92
+ lastObserved: {
93
+ inputTokens,
94
+ requestFingerprint,
95
+ compactionEpoch,
96
+ source: 'provider_usage',
97
+ observedAt,
98
+ },
99
+ };
100
+ }
101
+ function stableValue(value, seen) {
102
+ if (value == null || typeof value === 'string' || typeof value === 'boolean')
103
+ return value;
104
+ if (typeof value === 'number')
105
+ return Number.isFinite(value) ? value : String(value);
106
+ if (typeof value === 'bigint')
107
+ return value.toString();
108
+ if (typeof value === 'undefined' || typeof value === 'function' || typeof value === 'symbol')
109
+ return null;
110
+ if (Array.isArray(value))
111
+ return value.map((item) => stableValue(item, seen));
112
+ if (typeof value !== 'object')
113
+ return String(value);
114
+ if (seen.has(value))
115
+ throw new TypeError('Canonical provider request must not contain cycles.');
116
+ seen.add(value);
117
+ const record = value;
118
+ const result = {};
119
+ for (const key of Object.keys(record).sort()) {
120
+ const item = record[key];
121
+ if (typeof item === 'undefined' || typeof item === 'function' || typeof item === 'symbol')
122
+ continue;
123
+ result[key] = stableValue(item, seen);
124
+ }
125
+ seen.delete(value);
126
+ return result;
127
+ }
128
+ export function fingerprintCanonicalRequest(request) {
129
+ const text = JSON.stringify(stableValue(request, new WeakSet()));
130
+ let hash = 0x811c9dc5;
131
+ for (let index = 0; index < text.length; index += 1) {
132
+ hash ^= text.charCodeAt(index);
133
+ hash = Math.imul(hash, 0x01000193);
134
+ }
135
+ return `ctx_${(hash >>> 0).toString(16).padStart(8, '0')}_${text.length}`;
136
+ }
137
+ function errorDetails(error) {
138
+ if (error instanceof Error) {
139
+ const status = finiteTokenCount(error.status) || undefined;
140
+ return { ...(status ? { status } : {}), message: error.message };
141
+ }
142
+ if (typeof error === 'string')
143
+ return { message: error };
144
+ if (error && typeof error === 'object') {
145
+ const record = error;
146
+ const status = finiteTokenCount(record.status) || undefined;
147
+ const message = String(record.errorText ?? record.message ?? record.error ?? JSON.stringify(record));
148
+ return { ...(status ? { status } : {}), message };
149
+ }
150
+ return { message: String(error ?? '') };
151
+ }
152
+ function tokenFromMatch(match) {
153
+ if (!match?.[1])
154
+ return undefined;
155
+ const value = Number(match[1].replaceAll(',', ''));
156
+ return Number.isFinite(value) && value > 0 ? Math.floor(value) : undefined;
157
+ }
158
+ export function parseContextOverflowEvidence(error) {
159
+ const details = errorDetails(error);
160
+ if (!isPromptTooLongError(details.status, details.message))
161
+ return null;
162
+ const text = details.message;
163
+ const requestedTokens = tokenFromMatch(text.match(/request\s+(?:contains|has)\s+([\d,]+)\s+tokens?/i)
164
+ ?? text.match(/requested\s+([\d,]+)\s+tokens?/i)
165
+ ?? text.match(/([\d,]+)\s+tokens?\s*(?:>|over|exceeds)/i));
166
+ const maximumTokens = tokenFromMatch(text.match(/maximum\s+(?:prompt|context)(?:\s+length)?\s+(?:is|of)\s+([\d,]+)/i)
167
+ ?? text.match(/([\d,]+)\s+(?:token\s+)?(?:maximum|limit)/i));
168
+ return {
169
+ ...(requestedTokens ? { requestedTokens } : {}),
170
+ ...(maximumTokens ? { maximumTokens } : {}),
171
+ ...(details.status ? { status: details.status } : {}),
172
+ message: text,
173
+ };
174
+ }
175
+ function resolveCapability(configured, hasCounter) {
176
+ if (configured)
177
+ return configured;
178
+ return hasCounter ? { kind: 'provider_tokenizer', tokenizerVersion: 'adapter' } : { kind: 'observed_usage_only' };
179
+ }
180
+ function exactResult(value, capability) {
181
+ if (typeof value === 'number') {
182
+ const count = finiteTokenCount(value);
183
+ if (!count)
184
+ return null;
185
+ return {
186
+ inputTokens: count,
187
+ source: capability.kind === 'provider_count_api' ? 'provider_count_api' : 'provider_tokenizer',
188
+ };
189
+ }
190
+ if (!value)
191
+ return null;
192
+ const count = finiteTokenCount(value.inputTokens);
193
+ return count ? { inputTokens: count, source: value.source } : null;
194
+ }
195
+ export function createContextAccountingCompactionPipeline(options) {
196
+ const now = options.now ?? Date.now;
197
+ const fingerprint = options.fingerprintRequest ?? fingerprintCanonicalRequest;
198
+ const capability = resolveCapability(options.countCapability, typeof options.countRequest === 'function');
199
+ const identity = () => (typeof options.identity === 'function' ? options.identity() : options.identity);
200
+ const initialIdentity = identity();
201
+ const initial = options.initialSnapshot
202
+ && options.initialSnapshot.version === 1
203
+ && options.initialSnapshot.conversationId === initialIdentity.conversationId
204
+ && options.initialSnapshot.modelKey === initialIdentity.modelKey
205
+ ? options.initialSnapshot
206
+ : null;
207
+ let compactionEpoch = initial?.compactionEpoch ?? 0;
208
+ let lastObserved = initial?.lastObserved;
209
+ let nextCounted = initial?.nextCounted;
210
+ let lastOverflow = initial?.lastOverflow;
211
+ let lastOverflowEpoch = initial?.pressureSource === 'provider_error_evidence'
212
+ ? initial.compactionEpoch
213
+ : undefined;
214
+ let compactionRevision = initial?.lastObserved?.supersededByCompactionRevision ?? 0;
215
+ let verification = initial?.verification;
216
+ let counterStatus = initial?.counterStatus ?? 'active';
217
+ let revision = initial?.revision ?? 0;
218
+ let phase = initial?.phase ?? 'restored';
219
+ let latestBuiltFingerprint = null;
220
+ const contextWindow = () => finiteWindow(typeof options.contextWindow === 'function' ? options.contextWindow() : options.contextWindow);
221
+ const buildSnapshot = () => {
222
+ const currentIdentity = identity();
223
+ const window = contextWindow();
224
+ const reserve = Math.max(0, finiteTokenCount(options.requiredOutputReserveTokens));
225
+ const inputBudget = window == null ? null : Math.max(1, window - reserve);
226
+ const thresholdRatio = options.compactionThresholdRatio ?? CONTEXT_PROJECTION_CONFIG.triggerRatio;
227
+ const compactionThresholdTokens = inputBudget == null
228
+ ? null
229
+ : Math.floor(inputBudget * thresholdRatio);
230
+ const activeObserved = lastObserved?.compactionEpoch === compactionEpoch
231
+ && lastObserved.supersededByCompactionRevision == null
232
+ ? lastObserved
233
+ : undefined;
234
+ const activeCounted = nextCounted?.compactionEpoch === compactionEpoch ? nextCounted : undefined;
235
+ const activeOverflowTokens = lastOverflowEpoch === compactionEpoch
236
+ ? finiteTokenCount(lastOverflow?.requestedTokens) || null
237
+ : null;
238
+ const observedMatchesCurrent = activeObserved?.requestFingerprint === latestBuiltFingerprint;
239
+ const countedMatchesCurrent = activeCounted?.requestFingerprint === latestBuiltFingerprint;
240
+ const observedSupersedesCount = Boolean(activeObserved
241
+ && activeCounted
242
+ && activeObserved.requestFingerprint === activeCounted.requestFingerprint);
243
+ const authority = observedMatchesCurrent
244
+ ? activeObserved
245
+ : countedMatchesCurrent
246
+ ? activeCounted
247
+ : observedSupersedesCount
248
+ ? activeObserved
249
+ : activeCounted ?? activeObserved;
250
+ const authoritativeInputTokens = authority?.inputTokens ?? activeOverflowTokens;
251
+ const pressureSource = authority?.source
252
+ ?? (activeOverflowTokens ? 'provider_error_evidence' : 'unknown');
253
+ return {
254
+ version: 1,
255
+ conversationId: currentIdentity.conversationId,
256
+ contentRevision: finiteRevision(currentIdentity.contentRevision),
257
+ modelKey: currentIdentity.modelKey,
258
+ revision,
259
+ phase,
260
+ compactionEpoch,
261
+ contextWindow: window,
262
+ inputBudget,
263
+ compactionThresholdTokens,
264
+ authoritativeInputTokens,
265
+ percent: window == null || authoritativeInputTokens == null
266
+ ? null
267
+ : Math.min(100, Math.round((authoritativeInputTokens / window) * 100)),
268
+ pressureSource,
269
+ pendingUncountedChanges: authoritativeInputTokens == null
270
+ || (!observedMatchesCurrent && !countedMatchesCurrent),
271
+ pendingContentChars: 0,
272
+ countCapability: capability,
273
+ counterStatus,
274
+ updatedAt: now(),
275
+ ...(lastObserved ? { lastObserved } : {}),
276
+ ...(activeCounted ? { nextCounted: activeCounted } : {}),
277
+ ...(lastOverflow ? { lastOverflow } : {}),
278
+ ...(verification ? { verification } : {}),
279
+ };
280
+ };
281
+ const publish = (nextPhase) => {
282
+ phase = nextPhase;
283
+ revision += 1;
284
+ const snapshot = buildSnapshot();
285
+ options.onSnapshot?.(snapshot, nextPhase);
286
+ return snapshot;
287
+ };
288
+ const observe = (usage, requestFingerprint, verifyCount = true) => {
289
+ const inputTokens = normalizeObservedInputTokens(usage);
290
+ if (inputTokens == null)
291
+ return;
292
+ lastObserved = {
293
+ inputTokens,
294
+ requestFingerprint,
295
+ compactionEpoch,
296
+ source: 'provider_usage',
297
+ observedAt: now(),
298
+ };
299
+ if (verifyCount
300
+ && nextCounted
301
+ && nextCounted.requestFingerprint === requestFingerprint) {
302
+ const absoluteDelta = Math.abs(nextCounted.inputTokens - inputTokens);
303
+ const relativeDelta = absoluteDelta / Math.max(1, inputTokens);
304
+ const tolerance = Number.isFinite(options.driftToleranceRatio)
305
+ ? Math.max(0, Number(options.driftToleranceRatio))
306
+ : 0.02;
307
+ verification = {
308
+ requestFingerprint,
309
+ countedInputTokens: nextCounted.inputTokens,
310
+ observedInputTokens: inputTokens,
311
+ absoluteDelta,
312
+ relativeDelta,
313
+ tolerance,
314
+ status: relativeDelta <= tolerance ? 'verified' : 'drift',
315
+ verifiedAt: now(),
316
+ };
317
+ if (verification.status === 'drift') {
318
+ counterStatus = 'degraded';
319
+ nextCounted = undefined;
320
+ }
321
+ }
322
+ };
323
+ const count = async (request, requestFingerprint) => {
324
+ nextCounted = undefined;
325
+ if (!options.countRequest || counterStatus === 'degraded')
326
+ return;
327
+ const before = fingerprint(request);
328
+ if (before !== requestFingerprint) {
329
+ throw new Error('context_request_fingerprint_mismatch: request changed before exact count');
330
+ }
331
+ let rawCount;
332
+ try {
333
+ rawCount = await options.countRequest(request);
334
+ }
335
+ catch {
336
+ // Counting is advisory to the send path. A provider count endpoint may
337
+ // be unavailable even when message generation is healthy; degrade
338
+ // explicitly and continue with observed usage instead of blocking chat.
339
+ counterStatus = 'degraded';
340
+ nextCounted = undefined;
341
+ return;
342
+ }
343
+ const counted = exactResult(rawCount, capability);
344
+ const after = fingerprint(request);
345
+ if (after !== requestFingerprint) {
346
+ throw new Error('context_request_fingerprint_mismatch: exact counter mutated the canonical request');
347
+ }
348
+ if (!counted)
349
+ return;
350
+ nextCounted = {
351
+ inputTokens: counted.inputTokens,
352
+ requestFingerprint,
353
+ compactionEpoch,
354
+ source: counted.source,
355
+ countedAt: now(),
356
+ };
357
+ };
358
+ const build = async (state) => {
359
+ const request = await options.buildRequest(state);
360
+ const requestFingerprint = fingerprint(request);
361
+ await count(request, requestFingerprint);
362
+ latestBuiltFingerprint = requestFingerprint;
363
+ return { request, requestFingerprint };
364
+ };
365
+ const decide = () => {
366
+ const snapshot = buildSnapshot();
367
+ if (snapshot.authoritativeInputTokens == null || snapshot.inputBudget == null)
368
+ return null;
369
+ return decideContextCompaction({
370
+ pressureTokens: snapshot.authoritativeInputTokens,
371
+ contextWindow: snapshot.inputBudget,
372
+ triggerRatio: options.compactionThresholdRatio,
373
+ });
374
+ };
375
+ const advanceEpoch = () => {
376
+ compactionEpoch += 1;
377
+ compactionRevision += 1;
378
+ if (lastObserved && lastObserved.supersededByCompactionRevision == null) {
379
+ lastObserved = {
380
+ ...lastObserved,
381
+ supersededByCompactionRevision: compactionRevision,
382
+ };
383
+ }
384
+ nextCounted = undefined;
385
+ };
386
+ const runCompaction = async (state, reason, emergency) => {
387
+ const result = await options.compact({
388
+ state,
389
+ reason,
390
+ emergency,
391
+ compactionEpoch,
392
+ });
393
+ if (result.compacted)
394
+ advanceEpoch();
395
+ return result;
396
+ };
397
+ const overflowFromResponse = (response) => {
398
+ return options.getOverflow?.(response) ?? null;
399
+ };
400
+ const execute = async (input) => {
401
+ let state = input.state;
402
+ let built = await build(state);
403
+ let decision = decide();
404
+ let compacted = false;
405
+ if (input.command === 'count_only') {
406
+ const snapshot = publish('restored');
407
+ return {
408
+ state,
409
+ request: built.request,
410
+ response: null,
411
+ snapshot,
412
+ decision,
413
+ compactionEpoch,
414
+ compacted,
415
+ retriedAfterOverflow: false,
416
+ };
417
+ }
418
+ const forceReason = input.command === 'manual_compact'
419
+ ? 'manual'
420
+ : input.forceCompact
421
+ ? 'forced'
422
+ : null;
423
+ const thresholdReason = decision?.shouldCompact
424
+ ? nextCounted
425
+ ? 'exact_count_threshold'
426
+ : 'observed_threshold'
427
+ : null;
428
+ const initialReason = forceReason ?? thresholdReason;
429
+ if (initialReason) {
430
+ const compactResult = await runCompaction(state, initialReason, false);
431
+ if (compactResult.compacted) {
432
+ compacted = true;
433
+ state = compactResult.state;
434
+ built = await build(state);
435
+ decision = decide();
436
+ }
437
+ }
438
+ if (input.command === 'manual_compact') {
439
+ const snapshot = publish(compacted ? 'post_compaction' : 'request_preflight');
440
+ return {
441
+ state,
442
+ request: built.request,
443
+ response: null,
444
+ snapshot,
445
+ decision,
446
+ compactionEpoch,
447
+ compacted,
448
+ retriedAfterOverflow: false,
449
+ };
450
+ }
451
+ if (compacted)
452
+ publish('post_compaction');
453
+ publish('request_preflight');
454
+ const assertFingerprint = () => {
455
+ if (fingerprint(built.request) !== built.requestFingerprint) {
456
+ throw new Error('context_request_fingerprint_mismatch: canonical request changed before send');
457
+ }
458
+ };
459
+ let retriedAfterOverflow = false;
460
+ let response;
461
+ let responseUsage = null;
462
+ const sendRequest = async () => {
463
+ try {
464
+ const nextResponse = await options.send(built.request);
465
+ responseUsage = options.getUsage?.(nextResponse) ?? null;
466
+ try {
467
+ options.onProviderRequest?.({
468
+ requestFingerprint: built.requestFingerprint,
469
+ usage: responseUsage,
470
+ response: nextResponse,
471
+ });
472
+ }
473
+ catch {
474
+ // Usage telemetry must not change provider semantics.
475
+ }
476
+ return nextResponse;
477
+ }
478
+ catch (error) {
479
+ responseUsage = null;
480
+ try {
481
+ options.onProviderRequest?.({
482
+ requestFingerprint: built.requestFingerprint,
483
+ usage: null,
484
+ error,
485
+ });
486
+ }
487
+ catch {
488
+ // Usage telemetry must not change provider semantics.
489
+ }
490
+ throw error;
491
+ }
492
+ };
493
+ try {
494
+ assertFingerprint();
495
+ response = await sendRequest();
496
+ }
497
+ catch (error) {
498
+ const evidence = parseContextOverflowEvidence(error);
499
+ if (!evidence)
500
+ throw error;
501
+ lastOverflow = evidence;
502
+ lastOverflowEpoch = compactionEpoch;
503
+ const recovered = await runCompaction(state, 'provider_overflow', true);
504
+ if (!recovered.compacted)
505
+ throw error;
506
+ compacted = true;
507
+ retriedAfterOverflow = true;
508
+ state = recovered.state;
509
+ built = await build(state);
510
+ publish('post_compaction');
511
+ publish('request_preflight');
512
+ assertFingerprint();
513
+ response = await sendRequest();
514
+ }
515
+ const responseOverflow = overflowFromResponse(response);
516
+ if (responseOverflow) {
517
+ lastOverflow = responseOverflow;
518
+ lastOverflowEpoch = compactionEpoch;
519
+ const recovered = await runCompaction(state, 'provider_overflow', true);
520
+ if (recovered.compacted) {
521
+ compacted = true;
522
+ retriedAfterOverflow = true;
523
+ state = recovered.state;
524
+ built = await build(state);
525
+ publish('post_compaction');
526
+ publish('request_preflight');
527
+ assertFingerprint();
528
+ response = await sendRequest();
529
+ }
530
+ }
531
+ // A retry is terminal for this execute call. If the retried response is
532
+ // still over the limit, retain its exact requested-token evidence for UI
533
+ // and diagnostics without entering a second retry loop.
534
+ const finalOverflow = overflowFromResponse(response);
535
+ if (finalOverflow) {
536
+ lastOverflow = finalOverflow;
537
+ lastOverflowEpoch = compactionEpoch;
538
+ }
539
+ observe(responseUsage, built.requestFingerprint);
540
+ // The response may add assistant/tool-call content to the next request.
541
+ // Preserve the observed request as authority but mark the next request as
542
+ // pending until it is rebuilt and counted.
543
+ latestBuiltFingerprint = null;
544
+ const snapshot = publish('turn_complete');
545
+ return {
546
+ state,
547
+ request: built.request,
548
+ response,
549
+ snapshot,
550
+ decision,
551
+ compactionEpoch,
552
+ compacted,
553
+ retriedAfterOverflow,
554
+ };
555
+ };
556
+ return Object.freeze({
557
+ execute,
558
+ snapshot: buildSnapshot,
559
+ observe,
560
+ });
561
+ }
@@ -0,0 +1,70 @@
1
+ export type CompactionMessage = Readonly<{
2
+ role: string;
3
+ content?: unknown;
4
+ toolCallId?: string;
5
+ tool_call_id?: string;
6
+ toolCalls?: readonly Readonly<{
7
+ id?: string;
8
+ }>[];
9
+ tool_calls?: readonly Readonly<{
10
+ id?: string;
11
+ }>[];
12
+ _compaction?: unknown;
13
+ }>;
14
+ export type CompactionMethod = 'llm' | 'structured' | 'fallback_drop';
15
+ export declare const COMPACTION_SUMMARY_SYSTEM_PROMPT = "\u4F60\u662F\u5BF9\u8BDD\u6458\u8981\u4E13\u5BB6\u3002\u8BF7\u5C06\u4EE5\u4E0B\u5BF9\u8BDD\u5386\u53F2\u538B\u7F29\u4E3A\u8BE6\u7EC6\u6458\u8981\uFF0C\u4FDD\u7559\u5173\u952E\u4FE1\u606F\uFF1A\u7528\u6237\u610F\u56FE\u3001\u91CD\u8981\u51B3\u7B56\u3001\u6280\u672F\u6982\u5FF5\u3001\u6587\u4EF6\u53D8\u66F4\u3001\u9519\u8BEF\u4FEE\u590D\u3001\u5F85\u529E\u4E8B\u9879\u3002\u7279\u522B\u8981\u8BE6\u7EC6\u8BB0\u5F55\u7528\u6237\u7684\u5177\u4F53\u6267\u884C\u52A8\u4F5C\u4E0E\u64CD\u4F5C\u6B65\u9AA4\u2014\u2014\u7528\u6237\u8981\u6C42\u505A\u4E86\u4EC0\u4E48\u3001\u5B9E\u9645\u6539\u52A8\u4E86\u54EA\u4E9B\u6587\u4EF6\u3001\u547D\u4EE4/\u64CD\u4F5C\u6267\u884C\u5230\u54EA\u4E00\u6B65\u3001\u5F53\u524D\u505C\u5728\u4F55\u5904\u2014\u2014\u56E0\u4E3A\u539F\u6587\u5DF2\u5168\u91CF\u538B\u7F29\u3001\u4E0D\u518D\u4FDD\u7559\uFF0C\u8FDE\u7EED\u6027\u5B8C\u5168\u4F9D\u8D56\u672C\u6458\u8981\u627F\u8F7D\u3002\u8F93\u51FA\u7EAF\u6587\u672C\uFF0C\u4E0D\u8981\u7528 markdown\u3002";
16
+ export declare const COMPACTION_SUMMARY_PROMPT = "Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.\nThis summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.\n\nBefore providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:\n\n1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:\n - The user's explicit requests and intents\n - Your approach to addressing the user's requests\n - Key decisions, technical concepts and code patterns\n - Specific details like file names, full code snippets, function signatures, file edits, etc\n - Errors that you ran into and how you fixed them\n - Pay special attention to specific user feedback that may have led to a change in your approach.\n2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.\n\nYour summary should include the following sections:\n\n1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail\n2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.\n3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Include a summary of why this file read or edit is important.\n4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback.\n5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.\n6. All user messages: List ALL user messages that are not tool results. These are critical for understanding user feedback and changing intent.\n7. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.\n8. Current Work: Describe in detail precisely what was being worked on immediately before this summary request. CRITICAL \u2014 record the user's concrete execution actions and operation steps in detail: what the user asked to do, which files were actually changed, what commands/operations were run and to which step they progressed, and exactly where things currently stand. The original conversation is fully compacted and NOT retained, so continuity depends entirely on this summary capturing those execution details.\n9. Optional Next Step: List the next step related to the most recent work. Include direct quotes from the most recent conversation.\n\nCRITICAL: Respond with TEXT ONLY. Do NOT call any tools.\n\nPlease provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.";
17
+ export declare function formatCompactionMessagesForSummary(messages: readonly CompactionMessage[]): string;
18
+ export interface CompactionSplit<TMessage extends CompactionMessage> {
19
+ readonly systemMessages: readonly TMessage[];
20
+ readonly oldMessages: readonly TMessage[];
21
+ readonly keepMessages: readonly TMessage[];
22
+ }
23
+ export interface CompactionSummaryResult {
24
+ readonly method: CompactionMethod;
25
+ readonly summary: string;
26
+ readonly fallbackReason?: 'llm_unavailable' | 'llm_failed' | 'structured_empty';
27
+ readonly fallbackDetail?: string;
28
+ }
29
+ export interface CompactionSummaryCascadeOptions<TMessage extends CompactionMessage> {
30
+ readonly oldMessages: readonly TMessage[];
31
+ readonly summarizeWithLlm?: (messages: readonly TMessage[]) => Promise<string | null | undefined>;
32
+ readonly summarizeStructurally: (messages: readonly TMessage[]) => string | null | undefined;
33
+ readonly fallbackSummary?: string;
34
+ }
35
+ /**
36
+ * Host-neutral form of Desktop's compaction split rules. System messages are kept
37
+ * separately; automatic preflight preserves the newest human turn; and a split
38
+ * never leaves an orphan tool result or an unfinished tool call in summarized history.
39
+ */
40
+ export declare function splitMessagesForCompaction<TMessage extends CompactionMessage>(messages: readonly TMessage[], options?: {
41
+ readonly preserveLatestUserTurn?: boolean;
42
+ readonly keepRecentCount?: number;
43
+ }): CompactionSplit<TMessage>;
44
+ /** Desktop's summary preference order, expressed behind a host-provided model port. */
45
+ export declare function runCompactionSummaryCascade<TMessage extends CompactionMessage>(options: CompactionSummaryCascadeOptions<TMessage>): Promise<CompactionSummaryResult>;
46
+ export type CompactionStrategyResult<TMessage extends CompactionMessage> = Readonly<{
47
+ compacted: boolean;
48
+ systemMessages: readonly TMessage[];
49
+ keepMessages: readonly TMessage[];
50
+ oldMessages: readonly TMessage[];
51
+ summary?: string;
52
+ handoffContent?: string;
53
+ method?: CompactionSummaryResult['method'];
54
+ fallbackReason?: CompactionSummaryResult['fallbackReason'];
55
+ fallbackDetail?: string;
56
+ }>;
57
+ /**
58
+ * Shared strategy boundary used by both Desktop and CLI/TUI. Hosts provide the
59
+ * LLM/structural summarizers and handoff formatting, while split safety and
60
+ * fallback ordering remain owned by runtime-core.
61
+ */
62
+ export declare function compactMessagesWithSummaryStrategy<TMessage extends CompactionMessage>(options: Readonly<{
63
+ messages: readonly TMessage[];
64
+ preserveLatestUserTurn?: boolean;
65
+ keepRecentCount?: number;
66
+ summarizeWithLlm?: (oldMessages: readonly TMessage[]) => Promise<string | null | undefined>;
67
+ summarizeStructurally: (oldMessages: readonly TMessage[]) => string | null | undefined;
68
+ buildHandoffContent: (summary: string, oldCount: number) => string;
69
+ fallbackSummary?: string;
70
+ }>): Promise<CompactionStrategyResult<TMessage>>;