@capybara-hq/kernel 0.1.0-rc.103 → 0.1.0-rc.104
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.
- package/dist/conversations/events.d.ts +11 -0
- package/dist/conversations/events.js +22 -0
- package/dist/evals/reconstruct.d.ts +9 -1
- package/dist/evals/reconstruct.js +7 -0
- package/dist/runtime/compaction.service.d.ts +3 -2
- package/dist/runtime/compaction.service.js +4 -5
- package/dist/runtime/context/build.d.ts +13 -3
- package/dist/runtime/context/build.js +26 -6
- package/dist/runtime/context/compaction.d.ts +2 -0
- package/dist/runtime/context/compaction.js +21 -7
- package/dist/runtime/context/run-outcome.d.ts +10 -0
- package/dist/runtime/context/run-outcome.js +92 -0
- package/dist/runtime/model-call.d.ts +7 -0
- package/dist/runtime/model-call.js +51 -5
- package/package.json +1 -1
|
@@ -1068,6 +1068,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
|
|
|
1068
1068
|
sandbox: z.ZodOptional<z.ZodString>;
|
|
1069
1069
|
}, z.core.$strict>>;
|
|
1070
1070
|
reminderSeqs: z.ZodArray<z.ZodNumber>;
|
|
1071
|
+
runOutcomeSeqs: z.ZodOptional<z.ZodArray<z.ZodNumber>>;
|
|
1071
1072
|
maxOutputTokens: z.ZodNumber;
|
|
1072
1073
|
params: z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
|
|
1073
1074
|
droppedParams: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
@@ -2051,6 +2052,16 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
|
|
|
2051
2052
|
reason: z.ZodString;
|
|
2052
2053
|
step: z.ZodNumber;
|
|
2053
2054
|
}, z.core.$strip>;
|
|
2055
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
2056
|
+
type: z.ZodLiteral<"compaction_skipped">;
|
|
2057
|
+
payload: z.ZodObject<{
|
|
2058
|
+
reason: z.ZodEnum<{
|
|
2059
|
+
too_few_turns: "too_few_turns";
|
|
2060
|
+
}>;
|
|
2061
|
+
keepRecentTurns: z.ZodNumber;
|
|
2062
|
+
turns: z.ZodNumber;
|
|
2063
|
+
step: z.ZodNumber;
|
|
2064
|
+
}, z.core.$strip>;
|
|
2054
2065
|
}, z.core.$strip>, z.ZodObject<{
|
|
2055
2066
|
type: z.ZodLiteral<"run_finished">;
|
|
2056
2067
|
payload: z.ZodObject<{
|
|
@@ -969,6 +969,13 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
|
|
|
969
969
|
systemHash: z.string(),
|
|
970
970
|
permissionContext: PermissionContextMetaV1Schema.optional(),
|
|
971
971
|
reminderSeqs: z.array(seqNo),
|
|
972
|
+
/**
|
|
973
|
+
* The `run_failed` / `run_aborted` events whose run outcome note the request rendered
|
|
974
|
+
* (`runtime/context/run-outcome.ts`, maintainer decision 2026-11-28), in seq order; absent
|
|
975
|
+
* when it rendered none. Reconstruction reports `run_outcome_note` when the rebuild
|
|
976
|
+
* renders another set (a request sent before the note existed).
|
|
977
|
+
*/
|
|
978
|
+
runOutcomeSeqs: z.array(seqNo).optional(),
|
|
972
979
|
/**
|
|
973
980
|
* The request's output cap: `min(model cap, maxOutputTokens knob ??
|
|
974
981
|
* runtime.maxOutputTokens)`, clamped by the hard fit guard.
|
|
@@ -1782,6 +1789,21 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
|
|
|
1782
1789
|
/** The step the compaction ran in, as on `compaction_summary`. */
|
|
1783
1790
|
step: count,
|
|
1784
1791
|
})),
|
|
1792
|
+
/**
|
|
1793
|
+
* A manual compaction (a compact run, context compaction spec §4.7) found nothing to summarize:
|
|
1794
|
+
* the kept tail (the latest `keepRecentTurns` user turns) already holds every user turn since
|
|
1795
|
+
* the last summary (`turns`). Display only, never model-visible; written once per compact run
|
|
1796
|
+
* (maintainer decision 2026-11-28). An automatic compaction's skip writes nothing.
|
|
1797
|
+
*/
|
|
1798
|
+
ev("compaction_skipped", z.object({
|
|
1799
|
+
reason: z.enum(["too_few_turns"]),
|
|
1800
|
+
/** The effective `keepRecentTurns` setting the plan used. */
|
|
1801
|
+
keepRecentTurns: count,
|
|
1802
|
+
/** The user turns since the last summary (all of them without one). */
|
|
1803
|
+
turns: count,
|
|
1804
|
+
/** The step the compaction ran in (0 for a manual compact run). */
|
|
1805
|
+
step: count,
|
|
1806
|
+
})),
|
|
1785
1807
|
ev("run_finished", z.object({
|
|
1786
1808
|
/**
|
|
1787
1809
|
* `budget`: a sub-agent stopped at its parent run's token cap (phase C, spec §8.3).
|
|
@@ -26,7 +26,8 @@ import { type CaseSnapshot } from "./snapshot.js";
|
|
|
26
26
|
* 图片数 / 页数上限、对象被替换后 etag 变了等);
|
|
27
27
|
* - `context_fit` (context compaction spec §4.9, never for a baseline): the candidate model's window
|
|
28
28
|
* makes the hard fit guard plan a different trim than the recorded `model_call.request.fit` (the
|
|
29
|
-
* recorded plan is replayed for a baseline; a candidate applies its recomputed plan)
|
|
29
|
+
* recorded plan is replayed for a baseline; a candidate applies its recomputed plan);
|
|
30
|
+
* - `run_outcome_note`: the rebuilt run outcome notes differ from the recorded `runOutcomeSeqs`.
|
|
30
31
|
*/
|
|
31
32
|
/** 还原结果与原请求不一致的原因。 */
|
|
32
33
|
export type DriftReason = "system_hash" | "tools_changed" | "tool_spec_missing" | "definition_missing"
|
|
@@ -51,6 +52,13 @@ export type DriftReason = "system_hash" | "tools_changed" | "tool_spec_missing"
|
|
|
51
52
|
* goes out against the candidate's window.
|
|
52
53
|
*/
|
|
53
54
|
| "context_fit"
|
|
55
|
+
/**
|
|
56
|
+
* The rebuild renders another set of run outcome notes (`runtime/context/run-outcome.ts`) than
|
|
57
|
+
* the request recorded in `model_call.request.runOutcomeSeqs`: a request sent before the note
|
|
58
|
+
* existed (maintainer decision 2026-11-28). Judged for every reconstruction: the notes come from
|
|
59
|
+
* the log alone, so a candidate cannot change them.
|
|
60
|
+
*/
|
|
61
|
+
| "run_outcome_note"
|
|
54
62
|
/** 整轮回放(T5):有工具调用没有匹配到记录(模型收到 REPLAY_NO_RECORDING)。 */
|
|
55
63
|
| "tool_unmatched";
|
|
56
64
|
export interface ReconstructOptions {
|
|
@@ -46,6 +46,7 @@ const DRIFT_ORDER = [
|
|
|
46
46
|
"media_missing",
|
|
47
47
|
"media_changed",
|
|
48
48
|
"context_fit",
|
|
49
|
+
"run_outcome_note",
|
|
49
50
|
"tool_unmatched",
|
|
50
51
|
];
|
|
51
52
|
function findCall(events, seq) {
|
|
@@ -276,6 +277,12 @@ export function reconstructFromInputs(s, gathered, opts) {
|
|
|
276
277
|
drift.add("tools_changed");
|
|
277
278
|
}
|
|
278
279
|
}
|
|
280
|
+
// run outcome notes: from the log alone, so only a request sent before they existed differs
|
|
281
|
+
const notes = meta.runOutcomeSeqs ?? [];
|
|
282
|
+
const recordedNotes = rec.runOutcomeSeqs ?? [];
|
|
283
|
+
if (notes.length !== recordedNotes.length || notes.some((x, i) => x !== recordedNotes[i])) {
|
|
284
|
+
drift.add("run_outcome_note");
|
|
285
|
+
}
|
|
279
286
|
// 媒体:按附件 id 与记录比较
|
|
280
287
|
const recordedMedia = new Map((rec.media ?? []).map((m) => [m.attachmentId, m]));
|
|
281
288
|
for (const m of meta.media ?? []) {
|
|
@@ -37,8 +37,9 @@ export interface ForcedCompaction {
|
|
|
37
37
|
* settings) and calls the shared {@link runCompaction} with `force: true`: the trigger,
|
|
38
38
|
* `enabled: false` and the failure backoff are bypassed, the compaction plan is still required.
|
|
39
39
|
*
|
|
40
|
-
* The run writes only `compaction_summary` / `compaction_failed` + the
|
|
41
|
-
* `
|
|
40
|
+
* The run writes only its outcome, with `step: 0`: `compaction_summary` / `compaction_failed` + the
|
|
41
|
+
* summary calls' `usage`, or `compaction_skipped` when there is nothing to summarize (maintainer
|
|
42
|
+
* decision 2026-11-28); no user message and no model step.
|
|
42
43
|
*/
|
|
43
44
|
export declare class CompactionService {
|
|
44
45
|
private readonly steps;
|
|
@@ -19,8 +19,9 @@ import { RunSteps } from "./run-steps.js";
|
|
|
19
19
|
* settings) and calls the shared {@link runCompaction} with `force: true`: the trigger,
|
|
20
20
|
* `enabled: false` and the failure backoff are bypassed, the compaction plan is still required.
|
|
21
21
|
*
|
|
22
|
-
* The run writes only `compaction_summary` / `compaction_failed` + the
|
|
23
|
-
* `
|
|
22
|
+
* The run writes only its outcome, with `step: 0`: `compaction_summary` / `compaction_failed` + the
|
|
23
|
+
* summary calls' `usage`, or `compaction_skipped` when there is nothing to summarize (maintainer
|
|
24
|
+
* decision 2026-11-28); no user message and no model step.
|
|
24
25
|
*/
|
|
25
26
|
let CompactionService = class CompactionService {
|
|
26
27
|
steps;
|
|
@@ -59,9 +60,7 @@ let CompactionService = class CompactionService {
|
|
|
59
60
|
// step's request would (spec §4.7)
|
|
60
61
|
const tools = stepToolsOf(await resolveAgentTools(deps, stepInput, events), stepInput, deps);
|
|
61
62
|
const compaction = await this.settings.resolve(input.orgId);
|
|
62
|
-
const out = await runCompaction(deps, stepInput, events, this.config.get().runtime, compaction, tools, {
|
|
63
|
-
force: true,
|
|
64
|
-
});
|
|
63
|
+
const out = await runCompaction(deps, stepInput, events, this.config.get().runtime, compaction, tools, { force: true, manual: true });
|
|
65
64
|
return { summarySeq: out.summarySeq, failed: out.failed };
|
|
66
65
|
}
|
|
67
66
|
};
|
|
@@ -21,6 +21,12 @@ export interface ModelCallMeta {
|
|
|
21
21
|
permissionContext?: PermissionContextMetaV1;
|
|
22
22
|
/** 被放进请求的 `reminder` 事件 seq。 */
|
|
23
23
|
reminderSeqs: number[];
|
|
24
|
+
/**
|
|
25
|
+
* The seqs of the `run_failed` / `run_aborted` events whose run outcome note the request renders
|
|
26
|
+
* (./run-outcome.ts); absent when it renders none. Reconstruction compares it with the rebuild
|
|
27
|
+
* (`run_outcome_note`).
|
|
28
|
+
*/
|
|
29
|
+
runOutcomeSeqs?: number[];
|
|
24
30
|
/** 构建时的 `absorbedUpToSeq`(见 {@link BuildModelRequestInput});未提供则没有该字段。 */
|
|
25
31
|
absorbedUpToSeq?: number;
|
|
26
32
|
/** 请求的模型参数(即 `ModelRequest.params`)。 */
|
|
@@ -328,8 +334,9 @@ export declare function latestSummary(events: ConversationEvent[]): SummaryEvent
|
|
|
328
334
|
*/
|
|
329
335
|
export declare function summaryKeepsTail(events: readonly ConversationEvent[], summary: SummaryEvent): boolean;
|
|
330
336
|
/**
|
|
331
|
-
* The text of the summary's user message (context compaction spec §4.2.2): the summary, then
|
|
332
|
-
*
|
|
337
|
+
* The text of the summary's user message (context compaction spec §4.2.2): the summary, then a
|
|
338
|
+
* plain statement that the earlier conversation was compacted into it (maintainer decision
|
|
339
|
+
* 2026-11-28), then what follows it. `openers` is the number of covered opening messages re-rendered right after this
|
|
333
340
|
* text ({@link summaryOpeners}); `keptTail` says whether newer messages kept verbatim follow
|
|
334
341
|
* ({@link summaryKeepsTail}). Model-facing English, derived from the log alone.
|
|
335
342
|
*/
|
|
@@ -367,7 +374,10 @@ export declare function summaryText(summary: string, framing: {
|
|
|
367
374
|
* 其他事件不进请求。提供 `absorbedUpToSeq` 时,
|
|
368
375
|
* 尚未被吸收的可吸收事件不进请求,运行中途到达的放在吸收它的调用处(见 BuildModelRequestInput)。
|
|
369
376
|
* An `assistant_message` with `stopReason: "max_tokens"` is followed by a `role: "system"`
|
|
370
|
-
* {@link OUTPUT_TRUNCATED_TEXT} (issue #951).
|
|
377
|
+
* {@link OUTPUT_TRUNCATED_TEXT} (issue #951). A `run_failed` / `run_aborted` of a run that is not a
|
|
378
|
+
* compact run is a `role: "system"` run outcome note at its position (`runOutcomeText`, ./run-outcome.ts:
|
|
379
|
+
* that run ended before it finished, and the neutral category of why; maintainer decision
|
|
380
|
+
* 2026-11-28); a summary that covers it drops it.
|
|
371
381
|
* 只追加:新事件只会在 messages 末尾追加;唯一的前缀变化来自新的压缩摘要。
|
|
372
382
|
* `step` 与 `agentVersion` 不进请求内容(保证缓存前缀稳定),由调用方写入 `model_call` 事件。
|
|
373
383
|
*/
|
|
@@ -10,6 +10,7 @@ import { permissionContextHistory } from "./permission-profile.js";
|
|
|
10
10
|
import { pluginContextsAfterSummary, pluginContextText } from "./plugin-context.js";
|
|
11
11
|
import { latestProjectRoot, projectRootText } from "./project-root.js";
|
|
12
12
|
import { currentRunContext, runContextEvents, runContextFullText, runContextText, scheduleHeader, senderLines, } from "./run-context.js";
|
|
13
|
+
import { runOutcomeNotes } from "./run-outcome.js";
|
|
13
14
|
import { invokedSkillNames, invokedSkillsText, skillsCatalogEvents, snapshotChangeText, snapshotCurrentText, snapshotSystemText, systemSkillsCatalog, } from "./skills.js";
|
|
14
15
|
import { toolsChangedText } from "./tool-changes.js";
|
|
15
16
|
/**
|
|
@@ -556,13 +557,16 @@ export function summaryKeepsTail(events, summary) {
|
|
|
556
557
|
(e.type === "assistant_message" && e.payload.content.length > 0)));
|
|
557
558
|
}
|
|
558
559
|
/**
|
|
559
|
-
* The text of the summary's user message (context compaction spec §4.2.2): the summary, then
|
|
560
|
-
*
|
|
560
|
+
* The text of the summary's user message (context compaction spec §4.2.2): the summary, then a
|
|
561
|
+
* plain statement that the earlier conversation was compacted into it (maintainer decision
|
|
562
|
+
* 2026-11-28), then what follows it. `openers` is the number of covered opening messages re-rendered right after this
|
|
561
563
|
* text ({@link summaryOpeners}); `keptTail` says whether newer messages kept verbatim follow
|
|
562
564
|
* ({@link summaryKeepsTail}). Model-facing English, derived from the log alone.
|
|
563
565
|
*/
|
|
564
566
|
export function summaryText(summary, framing) {
|
|
565
|
-
const parts = [
|
|
567
|
+
const parts = [
|
|
568
|
+
"The earlier part of this conversation was compacted into the summary above and is no longer shown verbatim.",
|
|
569
|
+
];
|
|
566
570
|
if (framing.openers > 0) {
|
|
567
571
|
parts.push(framing.openers === 1
|
|
568
572
|
? "The message that opened the current turn follows, shown again verbatim; the summary covers it."
|
|
@@ -605,7 +609,10 @@ export function summaryText(summary, framing) {
|
|
|
605
609
|
* 其他事件不进请求。提供 `absorbedUpToSeq` 时,
|
|
606
610
|
* 尚未被吸收的可吸收事件不进请求,运行中途到达的放在吸收它的调用处(见 BuildModelRequestInput)。
|
|
607
611
|
* An `assistant_message` with `stopReason: "max_tokens"` is followed by a `role: "system"`
|
|
608
|
-
* {@link OUTPUT_TRUNCATED_TEXT} (issue #951).
|
|
612
|
+
* {@link OUTPUT_TRUNCATED_TEXT} (issue #951). A `run_failed` / `run_aborted` of a run that is not a
|
|
613
|
+
* compact run is a `role: "system"` run outcome note at its position (`runOutcomeText`, ./run-outcome.ts:
|
|
614
|
+
* that run ended before it finished, and the neutral category of why; maintainer decision
|
|
615
|
+
* 2026-11-28); a summary that covers it drops it.
|
|
609
616
|
* 只追加:新事件只会在 messages 末尾追加;唯一的前缀变化来自新的压缩摘要。
|
|
610
617
|
* `step` 与 `agentVersion` 不进请求内容(保证缓存前缀稳定),由调用方写入 `model_call` 事件。
|
|
611
618
|
*/
|
|
@@ -640,6 +647,9 @@ export function buildModelRequest(input) {
|
|
|
640
647
|
const permissionHistory = permissionContextHistory(events, summary?.payload.coversUpToSeq);
|
|
641
648
|
const messages = [];
|
|
642
649
|
const reminderSeqs = [];
|
|
650
|
+
/** Run outcome notes by terminal event seq, and the ones this request rendered. */
|
|
651
|
+
const outcomeNotes = runOutcomeNotes(events);
|
|
652
|
+
const runOutcomeSeqs = [];
|
|
643
653
|
const absorbed = input.absorbedUpToSeq;
|
|
644
654
|
/** Where a model_call had taken in absorbable events. */
|
|
645
655
|
const absorbedBy = (e) => e.payload.request.absorbedUpToSeq;
|
|
@@ -1019,6 +1029,16 @@ export function buildModelRequest(input) {
|
|
|
1019
1029
|
messages.push({ role: "user", content: [{ type: "text", text: e.payload.text }] });
|
|
1020
1030
|
}
|
|
1021
1031
|
break;
|
|
1032
|
+
// a run that ended before it finished (a compact run excepted): one note where it ended
|
|
1033
|
+
case "run_aborted":
|
|
1034
|
+
case "run_failed": {
|
|
1035
|
+
const note = outcomeNotes.get(e.seq);
|
|
1036
|
+
if (note !== undefined) {
|
|
1037
|
+
messages.push({ role: "system", content: note });
|
|
1038
|
+
runOutcomeSeqs.push(e.seq);
|
|
1039
|
+
}
|
|
1040
|
+
break;
|
|
1041
|
+
}
|
|
1022
1042
|
case "skills_catalog":
|
|
1023
1043
|
if (e !== systemSkills) {
|
|
1024
1044
|
const text = snapshotChangeText(prevSnapshot.get(e.seq), e.payload);
|
|
@@ -1044,9 +1064,8 @@ export function buildModelRequest(input) {
|
|
|
1044
1064
|
case "artifact_created":
|
|
1045
1065
|
case "compaction_summary":
|
|
1046
1066
|
case "compaction_failed":
|
|
1067
|
+
case "compaction_skipped":
|
|
1047
1068
|
case "run_finished":
|
|
1048
|
-
case "run_aborted":
|
|
1049
|
-
case "run_failed":
|
|
1050
1069
|
// the permission records are not model-visible: the profile reaches the model only through
|
|
1051
1070
|
// its recorded permission_context, the review only through the tool result
|
|
1052
1071
|
case "permission_profile_changed":
|
|
@@ -1115,6 +1134,7 @@ export function buildModelRequest(input) {
|
|
|
1115
1134
|
systemHash: hashSystem(system),
|
|
1116
1135
|
...(permissionHistory.meta !== undefined && { permissionContext: permissionHistory.meta }),
|
|
1117
1136
|
reminderSeqs,
|
|
1137
|
+
...(runOutcomeSeqs.length > 0 && { runOutcomeSeqs }),
|
|
1118
1138
|
...(absorbed !== undefined && { absorbedUpToSeq: absorbed }),
|
|
1119
1139
|
params: { ...request.params },
|
|
1120
1140
|
tools: tools.map((t) => ({ key: t.key, specHash: t.specHash })),
|
|
@@ -49,6 +49,8 @@ export declare const MIN_COMPACTION_CHUNK_TOKENS = 256;
|
|
|
49
49
|
* carries `O`, the request's output cap (§4.1), not the summary cap (§4.8).
|
|
50
50
|
*/
|
|
51
51
|
export declare function shouldCompact(estimate: number, window: number, settings: CompactionSettings): boolean;
|
|
52
|
+
/** The user turns since the latest summary (all of them without one): `events` in any order. */
|
|
53
|
+
export declare function turnsSinceSummary(events: readonly ConversationEvent[]): number;
|
|
52
54
|
/**
|
|
53
55
|
* The compaction plan: keep the most recent `settings.keepRecentTurns` turns verbatim (a maximum,
|
|
54
56
|
* not a rule) and transcribe everything older that the previous summary does not cover yet (that
|
|
@@ -4,6 +4,7 @@ import { latestSummary } from "./build.js";
|
|
|
4
4
|
import { planningBounds } from "./fit.js";
|
|
5
5
|
import { UNKNOWN_RESULT_TEXT } from "./pairing.js";
|
|
6
6
|
import { scheduleHeader, senderTranscriptLabel } from "./run-context.js";
|
|
7
|
+
import { runOutcomeNotes } from "./run-outcome.js";
|
|
7
8
|
import { estimateTokens } from "./tokens.js";
|
|
8
9
|
import { toolsChangedText } from "./tool-changes.js";
|
|
9
10
|
/**
|
|
@@ -123,6 +124,11 @@ export function shouldCompact(estimate, window, settings) {
|
|
|
123
124
|
return false;
|
|
124
125
|
return estimate >= Math.min(settings.threshold * window, target);
|
|
125
126
|
}
|
|
127
|
+
/** The user turns since the latest summary (all of them without one): `events` in any order. */
|
|
128
|
+
export function turnsSinceSummary(events) {
|
|
129
|
+
const floor = latestSummary([...events])?.payload.coversUpToSeq ?? Number.NEGATIVE_INFINITY;
|
|
130
|
+
return events.filter((e) => e.type === "user_message" && e.seq > floor).length;
|
|
131
|
+
}
|
|
126
132
|
/**
|
|
127
133
|
* The compaction plan: keep the most recent `settings.keepRecentTurns` turns verbatim (a maximum,
|
|
128
134
|
* not a rule) and transcribe everything older that the previous summary does not cover yet (that
|
|
@@ -149,7 +155,9 @@ export function compactionPlan(events, settings, budget) {
|
|
|
149
155
|
userIdx.push(i);
|
|
150
156
|
});
|
|
151
157
|
const atPair = pairBoundaries(candidate);
|
|
152
|
-
|
|
158
|
+
// run outcome notes (./run-outcome.ts), read from the whole log: a run's start may be older
|
|
159
|
+
const notes = runOutcomeNotes(sorted);
|
|
160
|
+
const tail = tailTokens(candidate, notes);
|
|
153
161
|
const keep = settings.keepRecentTurns;
|
|
154
162
|
let boundary;
|
|
155
163
|
if (keep <= 0)
|
|
@@ -198,7 +206,7 @@ export function compactionPlan(events, settings, budget) {
|
|
|
198
206
|
}
|
|
199
207
|
const lines = [];
|
|
200
208
|
for (const e of covered) {
|
|
201
|
-
const line = transcriptLine(e);
|
|
209
|
+
const line = transcriptLine(e, notes);
|
|
202
210
|
if (line)
|
|
203
211
|
lines.push(line);
|
|
204
212
|
if (e.type !== "assistant_message")
|
|
@@ -261,10 +269,10 @@ export function openingSeqs(events, runId, coversUpToSeq, absorbedUpToSeq = Numb
|
|
|
261
269
|
* `out[length]` = 0): the events rendered as the transcript renders them, then estimated with the
|
|
262
270
|
* request estimator.
|
|
263
271
|
*/
|
|
264
|
-
function tailTokens(candidate) {
|
|
272
|
+
function tailTokens(candidate, notes) {
|
|
265
273
|
const out = new Array(candidate.length + 1).fill(0);
|
|
266
274
|
for (let i = candidate.length - 1; i >= 0; i--) {
|
|
267
|
-
const line = transcriptLine(candidate[i]);
|
|
275
|
+
const line = transcriptLine(candidate[i], notes);
|
|
268
276
|
const own = line
|
|
269
277
|
? estimateTokens([{ role: "user", content: [{ type: "text", text: line }] }], [])
|
|
270
278
|
: 0;
|
|
@@ -327,7 +335,7 @@ function keepToolPairs(atPair, userIdx, boundary) {
|
|
|
327
335
|
}
|
|
328
336
|
return 0;
|
|
329
337
|
}
|
|
330
|
-
function transcriptLine(e) {
|
|
338
|
+
function transcriptLine(e, notes) {
|
|
331
339
|
switch (e.type) {
|
|
332
340
|
case "user_message": {
|
|
333
341
|
const body = renderBlocks(e.payload.content);
|
|
@@ -364,6 +372,13 @@ function transcriptLine(e) {
|
|
|
364
372
|
// so the summary never carries the project's instructions in a paraphrase
|
|
365
373
|
// run_context is left out: its current values follow the summary anyway (build.ts), and
|
|
366
374
|
// stale names should not be summarised as current
|
|
375
|
+
// a run that ended before it finished is a system message of the request (build.ts); a compact
|
|
376
|
+
// run's end has no note
|
|
377
|
+
case "run_aborted":
|
|
378
|
+
case "run_failed": {
|
|
379
|
+
const note = notes.get(e.seq);
|
|
380
|
+
return note === undefined ? null : `System reminder: ${note}`;
|
|
381
|
+
}
|
|
367
382
|
case "tool_result":
|
|
368
383
|
return `Tool result ${e.payload.toolKey}${e.payload.isError ? " (error)" : ""}: ${e.payload.content}`;
|
|
369
384
|
// Every other event type is left out of the transcript: not model-visible, or re-rendered
|
|
@@ -395,9 +410,8 @@ function transcriptLine(e) {
|
|
|
395
410
|
case "subagent_finished":
|
|
396
411
|
case "compaction_summary":
|
|
397
412
|
case "compaction_failed":
|
|
413
|
+
case "compaction_skipped":
|
|
398
414
|
case "run_finished":
|
|
399
|
-
case "run_aborted":
|
|
400
|
-
case "run_failed":
|
|
401
415
|
// permission_context, like device_paths, follows the summary (the latest covered ones again,
|
|
402
416
|
// build.ts); the profile change and the review record are not model-visible
|
|
403
417
|
case "permission_context":
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { ConversationEvent } from "../../conversations/events.js";
|
|
2
|
+
/** The note for one terminal event (model-facing English). */
|
|
3
|
+
export declare function runOutcomeText(e: Extract<ConversationEvent, {
|
|
4
|
+
type: "run_failed" | "run_aborted";
|
|
5
|
+
}>): string;
|
|
6
|
+
/**
|
|
7
|
+
* The notes a request renders, by the seq of their terminal event: every `run_failed` /
|
|
8
|
+
* `run_aborted` whose run is not a compact run. Read from the log alone (`events` in any order).
|
|
9
|
+
*/
|
|
10
|
+
export declare function runOutcomeNotes(events: readonly ConversationEvent[]): Map<number, string>;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The run outcome note (reliability spec §"Run outcome notes", maintainer decision 2026-11-28): a
|
|
3
|
+
* run that ended `failed` or `aborted` is followed, in every later request, by one system message
|
|
4
|
+
* at its terminal event's position saying that it ended before it finished and why. Without it the
|
|
5
|
+
* model sees only the replayed partial reply and the pairing guard's "Result unknown" results, and
|
|
6
|
+
* cannot tell a stopped run from a finished one.
|
|
7
|
+
*
|
|
8
|
+
* The text is derived from the terminal event's payload alone (the abort reason and detail, the
|
|
9
|
+
* error code), mapped onto a few neutral categories: never the recorded message, which may hold
|
|
10
|
+
* provider text, URLs or other details the model must not see. A compact run (`run_started.trigger:
|
|
11
|
+
* "compact"`) gets no note: the model took no part in it, and its outcome is the summary (or
|
|
12
|
+
* nothing). Every other run gets one, a sub-agent's included (its own log: the next run a
|
|
13
|
+
* `SendMessage` starts sees how the previous one ended). The note sits where the run ended, so it
|
|
14
|
+
* never moves or changes once rendered (append-only); a summary that covers it drops it, and the
|
|
15
|
+
* compaction transcript carries it as a system line.
|
|
16
|
+
*/
|
|
17
|
+
const PREFIX = "The previous run ended before it finished";
|
|
18
|
+
/** Why a stopped run stopped, from `run_aborted` (model-facing English, no trailing period). */
|
|
19
|
+
function abortedReason(p) {
|
|
20
|
+
if (p.detail === "wait_timeout")
|
|
21
|
+
return "it was stopped because the dispatching agent's wait for it timed out";
|
|
22
|
+
if (p.reason === "user" && p.byAccountId !== null)
|
|
23
|
+
return "it was stopped by the user";
|
|
24
|
+
if (p.reason === "shutdown_exhausted")
|
|
25
|
+
return "it was interrupted and could not be resumed";
|
|
26
|
+
return "it was stopped";
|
|
27
|
+
}
|
|
28
|
+
/** The neutral category of a `run_failed` error code (model-facing English, no trailing period). */
|
|
29
|
+
function failedReason(code) {
|
|
30
|
+
switch (code) {
|
|
31
|
+
case "model.rate_limited":
|
|
32
|
+
case "model.overloaded":
|
|
33
|
+
return "the model service was overloaded or rate-limited";
|
|
34
|
+
case "model.server":
|
|
35
|
+
case "run.provider_error":
|
|
36
|
+
return "the model service returned an error";
|
|
37
|
+
case "model.timeout":
|
|
38
|
+
return "the model service did not respond in time";
|
|
39
|
+
case "model.network":
|
|
40
|
+
return "a network error";
|
|
41
|
+
case "model.auth":
|
|
42
|
+
return "the model service rejected the platform's credentials";
|
|
43
|
+
case "model.invalid_request":
|
|
44
|
+
return "the model service rejected the request";
|
|
45
|
+
case "model.context_overflow":
|
|
46
|
+
case "run.context_too_large":
|
|
47
|
+
return "the conversation no longer fit the model's context window";
|
|
48
|
+
case "model.refusal":
|
|
49
|
+
return "the model declined to respond";
|
|
50
|
+
case "model.unconfigured":
|
|
51
|
+
case "run.model_unavailable":
|
|
52
|
+
case "run.provider_unavailable":
|
|
53
|
+
return "the model was unavailable";
|
|
54
|
+
case "run.storage_unavailable":
|
|
55
|
+
return "attachment storage was unavailable";
|
|
56
|
+
case "run.hook_denied":
|
|
57
|
+
return "a platform policy blocked the model request";
|
|
58
|
+
case "run.delivery_failed":
|
|
59
|
+
return "the reply could not be delivered";
|
|
60
|
+
case "run.stalled":
|
|
61
|
+
case "run.orphaned":
|
|
62
|
+
return "it was interrupted and could not be resumed";
|
|
63
|
+
default:
|
|
64
|
+
return "an internal error";
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/** The note for one terminal event (model-facing English). */
|
|
68
|
+
export function runOutcomeText(e) {
|
|
69
|
+
const why = e.type === "run_aborted" ? abortedReason(e.payload) : failedReason(e.payload.error.code);
|
|
70
|
+
return `${PREFIX}: ${why}.`;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* The notes a request renders, by the seq of their terminal event: every `run_failed` /
|
|
74
|
+
* `run_aborted` whose run is not a compact run. Read from the log alone (`events` in any order).
|
|
75
|
+
*/
|
|
76
|
+
export function runOutcomeNotes(events) {
|
|
77
|
+
const compact = new Set();
|
|
78
|
+
for (const e of events) {
|
|
79
|
+
if (e.type === "run_started" && e.payload.trigger === "compact" && e.runId !== null) {
|
|
80
|
+
compact.add(e.runId);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
const out = new Map();
|
|
84
|
+
for (const e of events) {
|
|
85
|
+
if (e.type !== "run_failed" && e.type !== "run_aborted")
|
|
86
|
+
continue;
|
|
87
|
+
if (e.runId !== null && compact.has(e.runId))
|
|
88
|
+
continue;
|
|
89
|
+
out.set(e.seq, runOutcomeText(e));
|
|
90
|
+
}
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
@@ -371,6 +371,13 @@ interface CompactOptions {
|
|
|
371
371
|
ref?: ModelRef;
|
|
372
372
|
/** Whether `ref` is the fallback rung (its saved params are `fallbackParams`). */
|
|
373
373
|
fallback?: boolean;
|
|
374
|
+
/**
|
|
375
|
+
* A manual compact run (spec §4.7, with `force`): an outcome the automatic paths keep silent is
|
|
376
|
+
* recorded, so the person sees what their action did (maintainer decision 2026-11-28): nothing to
|
|
377
|
+
* summarize writes `compaction_skipped`, a model or storage that cannot be reached right now
|
|
378
|
+
* writes `compaction_failed`.
|
|
379
|
+
*/
|
|
380
|
+
manual?: boolean;
|
|
374
381
|
}
|
|
375
382
|
/** What one compaction execution wrote: the events, the summary's seq and whether it failed. */
|
|
376
383
|
export interface CompactionOutcome {
|
|
@@ -5,7 +5,7 @@ import { ApiError } from "../errors.js";
|
|
|
5
5
|
import { ExtensionUnloadedError } from "../extensions/inflight.js";
|
|
6
6
|
import { hasInvocation, skillLoadOffered } from "../skills/catalog.js";
|
|
7
7
|
import { buildModelRequest, latestSummary, mediaRefs, planMedia, } from "./context/build.js";
|
|
8
|
-
import { acceptSummary, buildCompactionRequest, chunkTranscript, compactionBackoff, compactionChunkSize, compactionInputBudget, compactionPlan, compactionRequestOverhead, extractSummary, MIN_COMPACTION_CHUNK_TOKENS, nextTranscriptChunk, openingSeqs, shouldCompact, summarySavedTokens, } from "./context/compaction.js";
|
|
8
|
+
import { acceptSummary, buildCompactionRequest, chunkTranscript, compactionBackoff, compactionChunkSize, compactionInputBudget, compactionPlan, compactionRequestOverhead, extractSummary, MIN_COMPACTION_CHUNK_TOKENS, nextTranscriptChunk, openingSeqs, shouldCompact, summarySavedTokens, turnsSinceSummary, } from "./context/compaction.js";
|
|
9
9
|
import { applyFit, estimateAfterFit, planFit, planningBounds, planReactiveTrim, planSqueezedFit, sentOutputCap, } from "./context/fit.js";
|
|
10
10
|
import { guardToolPairs } from "./context/pairing.js";
|
|
11
11
|
import { hasProjectSkills, overlongProjectSkills } from "./context/project-root.js";
|
|
@@ -232,6 +232,8 @@ const idem = {
|
|
|
232
232
|
*/
|
|
233
233
|
compactionSummary: (runId, step, n) => `compaction_summary:${runId}:${step}:${n}`,
|
|
234
234
|
compactionFailed: (runId, step, n) => `compaction_failed:${runId}:${step}:${n}`,
|
|
235
|
+
/** A manual compact run that found nothing to summarize: one per run (spec §4.7). */
|
|
236
|
+
compactionSkipped: (runId) => `compaction_skipped:${runId}`,
|
|
235
237
|
mediaExcluded: (runId, step, attempt, part) => `media_excluded:${runId}:${step}:${attempt}:${part}`,
|
|
236
238
|
};
|
|
237
239
|
/** The step result of a sub-agent whose budget a compaction call used up: no step request. */
|
|
@@ -745,6 +747,28 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
|
|
|
745
747
|
summarySeq: null,
|
|
746
748
|
failed: false,
|
|
747
749
|
});
|
|
750
|
+
/**
|
|
751
|
+
* A manual compact run's early end that the automatic paths keep silent: recorded as its
|
|
752
|
+
* outcome (`compaction_failed` with a fixed reason), else just skipped.
|
|
753
|
+
*/
|
|
754
|
+
const unavailable = async (reason) => {
|
|
755
|
+
if (opts.manual !== true)
|
|
756
|
+
return skipped(events);
|
|
757
|
+
const written = await appendCounted(deps, input, [
|
|
758
|
+
{
|
|
759
|
+
type: "compaction_failed",
|
|
760
|
+
runId: input.runId,
|
|
761
|
+
idemKey: idem.compactionFailed(input.runId, input.step, compactionOrdinal(events, input.runId, input.step)),
|
|
762
|
+
payload: {
|
|
763
|
+
attempt: consecutiveCompactionFailures(events) + 1,
|
|
764
|
+
step: input.step,
|
|
765
|
+
reason,
|
|
766
|
+
},
|
|
767
|
+
},
|
|
768
|
+
]);
|
|
769
|
+
const merged = await mergeWritten(deps.eventLog, input.conversationId, events, written);
|
|
770
|
+
return { events: merged, summarySeq: null, failed: true };
|
|
771
|
+
};
|
|
748
772
|
const modelRef = opts.ref ?? input.agent.model;
|
|
749
773
|
let provider;
|
|
750
774
|
let info;
|
|
@@ -753,7 +777,7 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
|
|
|
753
777
|
}
|
|
754
778
|
catch (err) {
|
|
755
779
|
deps.log.warn("compaction skipped: model unavailable", { model: modelRef, err });
|
|
756
|
-
return
|
|
780
|
+
return unavailable("the model is unavailable");
|
|
757
781
|
}
|
|
758
782
|
const limits = mediaLimits(deps);
|
|
759
783
|
try {
|
|
@@ -768,7 +792,7 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
|
|
|
768
792
|
conversationId: input.conversationId,
|
|
769
793
|
err,
|
|
770
794
|
});
|
|
771
|
-
return
|
|
795
|
+
return unavailable("attachment storage is unavailable");
|
|
772
796
|
}
|
|
773
797
|
const { request: built, estimate: raw } = buildRequest(limits, events, input, info, attemptParams(input.agent, info, opts.fallback === true).value, runtime, tools, false);
|
|
774
798
|
const estimate = calibrate(raw, lastActual(events));
|
|
@@ -791,8 +815,30 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
|
|
|
791
815
|
// prompt and tool definitions every request carries
|
|
792
816
|
const tailBudget = bounds.target - estimateTokens([], built.system, built.tools);
|
|
793
817
|
const plan = compactionPlan(events, compaction, tailBudget);
|
|
794
|
-
if (!plan)
|
|
795
|
-
|
|
818
|
+
if (!plan) {
|
|
819
|
+
if (opts.manual !== true)
|
|
820
|
+
return skipped(events);
|
|
821
|
+
// a manual compaction that finds nothing to summarize says so (display only, never
|
|
822
|
+
// model-visible): every user turn since the last summary is in the kept tail
|
|
823
|
+
const written = await appendCounted(deps, input, [
|
|
824
|
+
{
|
|
825
|
+
type: "compaction_skipped",
|
|
826
|
+
runId: input.runId,
|
|
827
|
+
idemKey: idem.compactionSkipped(input.runId),
|
|
828
|
+
payload: {
|
|
829
|
+
reason: "too_few_turns",
|
|
830
|
+
keepRecentTurns: compaction.keepRecentTurns,
|
|
831
|
+
turns: turnsSinceSummary(events),
|
|
832
|
+
step: input.step,
|
|
833
|
+
},
|
|
834
|
+
},
|
|
835
|
+
]);
|
|
836
|
+
return {
|
|
837
|
+
events: await mergeWritten(deps.eventLog, input.conversationId, events, written),
|
|
838
|
+
summarySeq: null,
|
|
839
|
+
failed: false,
|
|
840
|
+
};
|
|
841
|
+
}
|
|
796
842
|
// decided now and recorded in the summary (spec §4.2): the request never depends on later events
|
|
797
843
|
const opening = openingSeqs(events, input.runId, plan.coversUpToSeq, input.absorbedUpToSeq);
|
|
798
844
|
const { runId, step, signal, conversationId } = input;
|
package/package.json
CHANGED