@capybara-hq/kernel 0.1.0-rc.102 → 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/bootstrap.json CHANGED
@@ -3,15 +3,15 @@
3
3
  "schemaVersion": 1,
4
4
  "marketplace": {
5
5
  "url": "https://github.com/capybara-hq/plugins.git",
6
- "commit": "ff7f84534f29d9e65a0a1cdca80337d618cfee54"
6
+ "commit": "87ca221485218c947d592a6642e441620f1f27cc"
7
7
  },
8
8
  "plugins": [
9
9
  {
10
10
  "name": "openai-compatible",
11
11
  "source": "npm",
12
12
  "npm": "@capybara-hq/plugin-openai-compatible",
13
- "version": "0.1.0-rc.13",
14
- "integrity": "sha512-IXdGfR9nhUXFWcF+3Bpmemn6M2e/EgC7x1jhKg84H23vKANviVcGvyTugyAjyd7K3vd0DD8aYAW1CMnTksUpJg==",
13
+ "version": "0.1.0-rc.14",
14
+ "integrity": "sha512-BbB4lSBy4kEZA2kLOBDz00oOOjmQ4IaPPthmho00M15ZGcvDRMTuilw+244lbYPALZ3Kxzo1zNPWFI8STqUyDw==",
15
15
  "required": false
16
16
  },
17
17
  {
@@ -34,8 +34,8 @@
34
34
  "name": "openai",
35
35
  "source": "npm",
36
36
  "npm": "@capybara-hq/plugin-openai",
37
- "version": "0.1.0-rc.13",
38
- "integrity": "sha512-96cLlSSDPNlAjeFjHYYVfupqUDYYmePMThmB1nhwDoNO15F3OXEUECRGUR8PbUSjjthZTQ7gmb+HfCx9CqBweg==",
37
+ "version": "0.1.0-rc.14",
38
+ "integrity": "sha512-Ybde3qfkz0PruixbxzgxrlVYTahz2eplRj4ioeTP20yFQcoPTLbm5hoBuj64nZTKlvTtmYQ+gvK6ofYUWY2NTw==",
39
39
  "required": false
40
40
  },
41
41
  {
@@ -50,16 +50,16 @@
50
50
  "name": "bailian",
51
51
  "source": "npm",
52
52
  "npm": "@capybara-hq/plugin-bailian",
53
- "version": "0.1.0-rc.12",
54
- "integrity": "sha512-bEO6UTSlFJq5F+4ht/FQtgM2pOhRzaVY2+URWegR7lZ7utd9AhkTEoRAFnECUq3e7kI7/pJMoNyNX6KTMd9Xpw==",
53
+ "version": "0.1.0-rc.13",
54
+ "integrity": "sha512-TglGdOPeJTUVSxm+KQOdWDrxRnjhFVEatvfQFVkSwOElxocNyEFBm7K3GSQmmuY2ISgxJQceA7Yvjlb0JNpKiA==",
55
55
  "required": false
56
56
  },
57
57
  {
58
58
  "name": "ark",
59
59
  "source": "npm",
60
60
  "npm": "@capybara-hq/plugin-ark",
61
- "version": "0.1.0-rc.13",
62
- "integrity": "sha512-dmS7jJcPGTsWBzRC8rIe5T/GUrqfNNzlQeS5iIfoZdXGNPJqNrylHLp12eRZspaTPkZzpGgowV0MOhiQvwDzMA==",
61
+ "version": "0.1.0-rc.14",
62
+ "integrity": "sha512-sMyvv8eTeOHnR5WzxRxdYCXMnIn3uiS1kQokSFvojWy8Jk70t/kqMshUgisL+Tl8g3C0SFGwJYqvonWK+NI2jQ==",
63
63
  "required": false
64
64
  },
65
65
  {
@@ -90,8 +90,8 @@
90
90
  "name": "device-docker",
91
91
  "source": "npm",
92
92
  "npm": "@capybara-hq/plugin-device-docker",
93
- "version": "0.1.0-rc.34",
94
- "integrity": "sha512-FOYFio9VPBzGic0RqpFDN6qMmyuWEA2PHl2ZsIknHfvHYqMQsv6NCoESbWo2SAVGzmt6c3YRC1u8C02m3SDAEg==",
93
+ "version": "0.1.0-rc.35",
94
+ "integrity": "sha512-9Aegf1i/JFzEURfO6L7DbPkVlYgrmQ3TkHSx4OS8fHr9C53MM5kSRHOyv1UfDTNbXlyKn6NOHn/oy1kiwQSkDQ==",
95
95
  "required": false
96
96
  },
97
97
  {
@@ -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.
@@ -1109,9 +1116,11 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
1109
1116
  .enum(["compaction", "title", "web_fetch", "review", "image", "vision", "suggestion"])
1110
1117
  .optional(),
1111
1118
  /**
1112
- * The chunk a chunked compaction call summarised (1-based), with the number of calls the
1119
+ * The chunk a chunked compaction call summarised (1-based), with the number of chunks the
1113
1120
  * compaction attempted (the full chunk count on a completed one; on a failed or hook-denied
1114
- * run only the calls that were made). Absent on a single-call compaction.
1121
+ * run only the chunks that were sent). A chunk asked again after a summary cut off at the
1122
+ * output token limit counts once; both its calls carry its index. Absent on a single-call
1123
+ * compaction.
1115
1124
  */
1116
1125
  chunk: count.optional(),
1117
1126
  chunks: count.optional(),
@@ -1780,6 +1789,21 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
1780
1789
  /** The step the compaction ran in, as on `compaction_summary`. */
1781
1790
  step: count,
1782
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
+ })),
1783
1807
  ev("run_finished", z.object({
1784
1808
  /**
1785
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 ?? []) {
@@ -3,9 +3,12 @@ import { type ExtensionPackageLimits } from "./package.js";
3
3
  * 把内容寻址的插件包同步到本副本的本地目录(C13):`<dir>/<name>/<sha256 前 16 位>/`。
4
4
  *
5
5
  * - 目录里有校验文件 {@link MARKER} 且其中每个文件的 sha256 都对得上 → 直接复用(同一 sha 重启不再下载);
6
- * - 否则取包(`blobs.get` 按记录的存放位置读取并校验 sha256),先解到同级的临时目录、写好宿主包链接与校验文件,
7
- * 再改名换入;目标位置的残缺目录先原子地改名移开再删(不原地删除,见 {@link clearBrokenRoot})。并发的同机进程
8
- * 各自解到自己的临时目录,改名失败时以已就位且完整的为准。
6
+ * - Otherwise fetch the package (`blobs.get` reads it from the recorded location and checks the
7
+ * sha256), unpack it into a sibling temporary directory, write the host package links and the
8
+ * marker, then rename it in. Concurrent processes on the same machine each unpack into their own
9
+ * temporary directory; when the rename finds a root in place, a complete one is used as is and
10
+ * never moved (a peer may be reading it), and only an incomplete one is moved aside atomically
11
+ * and deleted (never removed in place, see {@link clearBrokenRoot}) before one more rename.
9
12
  * - `node_modules/` 下为 {@link HOST_PROVIDED_PACKAGES} 建指向宿主副本的符号链接:插件 import 的 SDK 与 zod
10
13
  * 就是内核用的那一份(同一模块实例)。插件目录不在宿主 `node_modules` 的上游,别的包一概解析不到。
11
14
  */
@@ -29,8 +32,9 @@ export declare function syncPackage(dir: string, name: string, sha: string, blob
29
32
  get(sha256: string): Promise<Uint8Array>;
30
33
  }, limits?: ExtensionPackageLimits): Promise<string>;
31
34
  /**
32
- * Gets a broken package root out of the way before the rename. Never `rm` in place: another process
33
- * on the same volume may have renamed its complete directory in after our `intact` check. The root is
35
+ * Gets a broken package root out of the way before the rename; called only on a root just found
36
+ * incomplete. Never `rm` in place: another process on the same volume may have renamed its complete
37
+ * directory in after our `intact` check. The root is
34
38
  * renamed aside atomically and checked again there: if it turns out complete, it is put back (or,
35
39
  * when yet another process filled the root meanwhile, that one is used) and returned; otherwise the
36
40
  * moved-aside copy is deleted. Exported for tests.
@@ -10,9 +10,12 @@ import { extractExtensionPackage } from "./package.js";
10
10
  * 把内容寻址的插件包同步到本副本的本地目录(C13):`<dir>/<name>/<sha256 前 16 位>/`。
11
11
  *
12
12
  * - 目录里有校验文件 {@link MARKER} 且其中每个文件的 sha256 都对得上 → 直接复用(同一 sha 重启不再下载);
13
- * - 否则取包(`blobs.get` 按记录的存放位置读取并校验 sha256),先解到同级的临时目录、写好宿主包链接与校验文件,
14
- * 再改名换入;目标位置的残缺目录先原子地改名移开再删(不原地删除,见 {@link clearBrokenRoot})。并发的同机进程
15
- * 各自解到自己的临时目录,改名失败时以已就位且完整的为准。
13
+ * - Otherwise fetch the package (`blobs.get` reads it from the recorded location and checks the
14
+ * sha256), unpack it into a sibling temporary directory, write the host package links and the
15
+ * marker, then rename it in. Concurrent processes on the same machine each unpack into their own
16
+ * temporary directory; when the rename finds a root in place, a complete one is used as is and
17
+ * never moved (a peer may be reading it), and only an incomplete one is moved aside atomically
18
+ * and deleted (never removed in place, see {@link clearBrokenRoot}) before one more rename.
16
19
  * - `node_modules/` 下为 {@link HOST_PROVIDED_PACKAGES} 建指向宿主副本的符号链接:插件 import 的 SDK 与 zod
17
20
  * 就是内核用的那一份(同一模块实例)。插件目录不在宿主 `node_modules` 的上游,别的包一概解析不到。
18
21
  */
@@ -140,24 +143,26 @@ export async function syncPackage(dir, name, sha, blobs, limits) {
140
143
  }
141
144
  const marker = { sha256: sha, entry, files };
142
145
  await writeFile(join(tmp, MARKER), JSON.stringify(marker), { flag: "wx", mode: 0o644 });
143
- // 换入:解包期间同机另一个进程可能已换入完整的目录——以它为准,不删;否则先移走残缺目录
144
- const done = await intact(root, sha);
145
- if (done)
146
- return urlOf(done);
147
- const restored = await clearBrokenRoot(root, sha);
148
- if (restored)
149
- return urlOf(restored);
150
- try {
151
- await rename(tmp, root);
152
- }
153
- catch (e) {
154
- // 同机另一个进程刚换入:以它为准(必须完整),否则抛原错误
155
- const other = await intact(root, sha);
156
- if (!other)
157
- throw e;
158
- return urlOf(other);
146
+ // Swap in: rename first. A root already in place (another process on this volume swapped in
147
+ // the same sha, maybe while we unpacked) is used as is when complete and never leaves its
148
+ // place: that process may be reading it right now (listing migrations, importing). Only a
149
+ // root found incomplete is moved aside, then the rename is tried once more.
150
+ for (let attempt = 0;; attempt++) {
151
+ try {
152
+ await rename(tmp, root);
153
+ return urlOf(marker);
154
+ }
155
+ catch (e) {
156
+ const other = await intact(root, sha);
157
+ if (other)
158
+ return urlOf(other);
159
+ if (attempt > 0)
160
+ throw e;
161
+ const restored = await clearBrokenRoot(root, sha);
162
+ if (restored)
163
+ return urlOf(restored);
164
+ }
159
165
  }
160
- return urlOf(marker);
161
166
  }
162
167
  finally {
163
168
  await rm(tmp, { recursive: true, force: true }).catch(() => { });
@@ -190,8 +195,9 @@ async function extensionEntryOf(root, name) {
190
195
  return packagePath(entry);
191
196
  }
192
197
  /**
193
- * Gets a broken package root out of the way before the rename. Never `rm` in place: another process
194
- * on the same volume may have renamed its complete directory in after our `intact` check. The root is
198
+ * Gets a broken package root out of the way before the rename; called only on a root just found
199
+ * incomplete. Never `rm` in place: another process on the same volume may have renamed its complete
200
+ * directory in after our `intact` check. The root is
195
201
  * renamed aside atomically and checked again there: if it turns out complete, it is put back (or,
196
202
  * when yet another process filled the root meanwhile, that one is used) and returned; otherwise the
197
203
  * moved-aside copy is deleted. Exported for tests.
@@ -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 summary calls' `usage`, with
41
- * `step: 0`; no user message and no model step.
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 summary calls' `usage`, with
23
- * `step: 0`; no user message and no model step.
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`)。 */
@@ -319,8 +325,25 @@ export declare function summaryOpeners(events: readonly ConversationEvent[], sum
319
325
  })[];
320
326
  /** 最近一条 `compaction_summary` 事件(按 seq);没有则 null。 */
321
327
  export declare function latestSummary(events: ConversationEvent[]): SummaryEvent | null;
322
- /** 摘要作为首条 user 消息时的文本。 */
323
- export declare function summaryText(summary: string): string;
328
+ /**
329
+ * Whether messages from before the summary was written stay verbatim after it (context compaction
330
+ * spec §4.2.2): a user, assistant or absorbed message logged after the summary's boundary and
331
+ * before the summary itself (the kept tail, or a message logged while the summary call ran). Read
332
+ * only from events older than the summary, so the answer never changes once it is written and the
333
+ * summary's message stays the same from one request to the next. `events` sorted by seq.
334
+ */
335
+ export declare function summaryKeepsTail(events: readonly ConversationEvent[], summary: SummaryEvent): boolean;
336
+ /**
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
340
+ * text ({@link summaryOpeners}); `keptTail` says whether newer messages kept verbatim follow
341
+ * ({@link summaryKeepsTail}). Model-facing English, derived from the log alone.
342
+ */
343
+ export declare function summaryText(summary: string, framing: {
344
+ openers: number;
345
+ keptTail: boolean;
346
+ }): string;
324
347
  /**
325
348
  * 由会话事件日志 + agent 定义构建模型请求(纯函数,不做 I/O)。
326
349
  * - system:`BEHAVIOR_RULES + "\n\n" + agent.instructions` 一个块,打缓存断点(a sub-agent's log:
@@ -351,7 +374,10 @@ export declare function summaryText(summary: string): string;
351
374
  * 其他事件不进请求。提供 `absorbedUpToSeq` 时,
352
375
  * 尚未被吸收的可吸收事件不进请求,运行中途到达的放在吸收它的调用处(见 BuildModelRequestInput)。
353
376
  * An `assistant_message` with `stopReason: "max_tokens"` is followed by a `role: "system"`
354
- * {@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.
355
381
  * 只追加:新事件只会在 messages 末尾追加;唯一的前缀变化来自新的压缩摘要。
356
382
  * `step` 与 `agentVersion` 不进请求内容(保证缓存前缀稳定),由调用方写入 `model_call` 事件。
357
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
  /**
@@ -539,9 +540,44 @@ export function latestSummary(events) {
539
540
  }
540
541
  return found;
541
542
  }
542
- /** 摘要作为首条 user 消息时的文本。 */
543
- export function summaryText(summary) {
544
- return `<conversation_summary>\n${summary}\n</conversation_summary>`;
543
+ /**
544
+ * Whether messages from before the summary was written stay verbatim after it (context compaction
545
+ * spec §4.2.2): a user, assistant or absorbed message logged after the summary's boundary and
546
+ * before the summary itself (the kept tail, or a message logged while the summary call ran). Read
547
+ * only from events older than the summary, so the answer never changes once it is written and the
548
+ * summary's message stays the same from one request to the next. `events` sorted by seq.
549
+ */
550
+ export function summaryKeepsTail(events, summary) {
551
+ const after = summary.payload.coversUpToSeq;
552
+ return events.some((e) => e.seq > after &&
553
+ e.seq < summary.seq &&
554
+ (isAbsorbable(e) ||
555
+ e.type === "reminder" ||
556
+ e.type === "skill_fork_result" ||
557
+ (e.type === "assistant_message" && e.payload.content.length > 0)));
558
+ }
559
+ /**
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
563
+ * text ({@link summaryOpeners}); `keptTail` says whether newer messages kept verbatim follow
564
+ * ({@link summaryKeepsTail}). Model-facing English, derived from the log alone.
565
+ */
566
+ export function summaryText(summary, framing) {
567
+ const parts = [
568
+ "The earlier part of this conversation was compacted into the summary above and is no longer shown verbatim.",
569
+ ];
570
+ if (framing.openers > 0) {
571
+ parts.push(framing.openers === 1
572
+ ? "The message that opened the current turn follows, shown again verbatim; the summary covers it."
573
+ : "The messages that opened the current turn follow, shown again verbatim; the summary covers them.");
574
+ }
575
+ if (framing.keptTail) {
576
+ const anchor = framing.openers === 0 ? "this summary" : "those";
577
+ parts.push(`The messages after ${anchor} are the most recent ones in the conversation, kept verbatim. The summary was written without seeing them, so something it says is still pending may already have happened in them.`);
578
+ }
579
+ parts.push("Continue the work from where it left off.");
580
+ return `<conversation_summary>\n${summary}\n</conversation_summary>\n\n${parts.join(" ")}`;
545
581
  }
546
582
  /**
547
583
  * 由会话事件日志 + agent 定义构建模型请求(纯函数,不做 I/O)。
@@ -573,7 +609,10 @@ export function summaryText(summary) {
573
609
  * 其他事件不进请求。提供 `absorbedUpToSeq` 时,
574
610
  * 尚未被吸收的可吸收事件不进请求,运行中途到达的放在吸收它的调用处(见 BuildModelRequestInput)。
575
611
  * An `assistant_message` with `stopReason: "max_tokens"` is followed by a `role: "system"`
576
- * {@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.
577
616
  * 只追加:新事件只会在 messages 末尾追加;唯一的前缀变化来自新的压缩摘要。
578
617
  * `step` 与 `agentVersion` 不进请求内容(保证缓存前缀稳定),由调用方写入 `model_call` 事件。
579
618
  */
@@ -608,6 +647,9 @@ export function buildModelRequest(input) {
608
647
  const permissionHistory = permissionContextHistory(events, summary?.payload.coversUpToSeq);
609
648
  const messages = [];
610
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 = [];
611
653
  const absorbed = input.absorbedUpToSeq;
612
654
  /** Where a model_call had taken in absorbable events. */
613
655
  const absorbedBy = (e) => e.payload.request.absorbedUpToSeq;
@@ -811,7 +853,13 @@ export function buildModelRequest(input) {
811
853
  messages.push({
812
854
  role: "user",
813
855
  content: [
814
- { type: "text", text: summaryText(summary.payload.text) },
856
+ {
857
+ type: "text",
858
+ text: summaryText(summary.payload.text, {
859
+ openers: openers.length,
860
+ keptTail: summaryKeepsTail(events, summary),
861
+ }),
862
+ },
815
863
  ...openers.flatMap((o) => userBlocks(o, false)),
816
864
  ],
817
865
  });
@@ -981,6 +1029,16 @@ export function buildModelRequest(input) {
981
1029
  messages.push({ role: "user", content: [{ type: "text", text: e.payload.text }] });
982
1030
  }
983
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
+ }
984
1042
  case "skills_catalog":
985
1043
  if (e !== systemSkills) {
986
1044
  const text = snapshotChangeText(prevSnapshot.get(e.seq), e.payload);
@@ -1006,9 +1064,8 @@ export function buildModelRequest(input) {
1006
1064
  case "artifact_created":
1007
1065
  case "compaction_summary":
1008
1066
  case "compaction_failed":
1067
+ case "compaction_skipped":
1009
1068
  case "run_finished":
1010
- case "run_aborted":
1011
- case "run_failed":
1012
1069
  // the permission records are not model-visible: the profile reaches the model only through
1013
1070
  // its recorded permission_context, the review only through the tool result
1014
1071
  case "permission_profile_changed":
@@ -1077,6 +1134,7 @@ export function buildModelRequest(input) {
1077
1134
  systemHash: hashSystem(system),
1078
1135
  ...(permissionHistory.meta !== undefined && { permissionContext: permissionHistory.meta }),
1079
1136
  reminderSeqs,
1137
+ ...(runOutcomeSeqs.length > 0 && { runOutcomeSeqs }),
1080
1138
  ...(absorbed !== undefined && { absorbedUpToSeq: absorbed }),
1081
1139
  params: { ...request.params },
1082
1140
  tools: tools.map((t) => ({ key: t.key, specHash: t.specHash })),
@@ -13,10 +13,18 @@ export declare const COMPACTION_MAX_OUTPUT_TOKENS = 20000;
13
13
  * spent on its input. A step's request plans with {@link planningBounds} instead.
14
14
  */
15
15
  export declare function compactionInputBudget(window: number, maxOutput: number, reserve: number): number;
16
+ /**
17
+ * The note the retry of a summary call cut off at the output token limit carries after the
18
+ * transcript (model-facing English; context compaction spec §4.2.1, issue #959). The word target is
19
+ * about three eighths of the cap (well under the cap at about 0.75 words per token, with the
20
+ * `<analysis>` block dropped), in steps of 50, between 50 and {@link RETRY_MAX_WORDS}.
21
+ */
22
+ export declare function compactionRetryNote(maxOutputTokens: number): string;
16
23
  /**
17
24
  * The input tokens every summary request carries regardless of its chunk: the instruction, the
18
- * transcript wrapper and a small margin. A chunked compaction subtracts it from the chunk size
19
- * (context compaction spec §4.5), so chunk + overhead stays inside the request budget.
25
+ * transcript wrapper, the retry note at its longest (a retried call resends its chunk with it) and a
26
+ * small margin. A chunked compaction subtracts it from the chunk size (context compaction spec
27
+ * §4.5), so chunk + overhead stays inside the request budget on a retry too.
20
28
  */
21
29
  export declare function compactionRequestOverhead(): number;
22
30
  /**
@@ -41,6 +49,8 @@ export declare const MIN_COMPACTION_CHUNK_TOKENS = 256;
41
49
  * carries `O`, the request's output cap (§4.1), not the summary cap (§4.8).
42
50
  */
43
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;
44
54
  /**
45
55
  * The compaction plan: keep the most recent `settings.keepRecentTurns` turns verbatim (a maximum,
46
56
  * not a rule) and transcribe everything older that the previous summary does not cover yet (that
@@ -103,9 +113,13 @@ export declare function chunkTranscript(transcript: string, chunkSize: number):
103
113
  * The summary request: the English instruction (request `purpose: "compaction"`) as the system prompt and the transcript as
104
114
  * the only user message. `maxOutputTokens` is the effective `compaction.maxOutputTokens` setting,
105
115
  * which the caller narrows to the model's own cap (context compaction spec §4.8); omitted, it is
106
- * the built-in default.
116
+ * the built-in default. `retry` is the one retry after a call stopped at the output token limit:
117
+ * the same request with {@link compactionRetryNote} after the transcript (the cut-off answer is not
118
+ * sent back, so the request stays inside the same input budget).
107
119
  */
108
- export declare function buildCompactionRequest(transcript: string, model: string, maxOutputTokens?: number): ModelRequest;
120
+ export declare function buildCompactionRequest(transcript: string, model: string, maxOutputTokens?: number, opts?: {
121
+ retry?: boolean;
122
+ }): ModelRequest;
109
123
  /**
110
124
  * What a compaction saved (context compaction spec §4.9): the estimated transcript input minus the
111
125
  * stored summary output. Floored at zero — a summary at least as long as the transcript saved no