@capybara-hq/kernel 0.1.0-rc.103 → 0.1.0-rc.105

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 (55) hide show
  1. package/dist/catalog/marketplaces.service.d.ts +1 -1
  2. package/dist/conversations/conversations.service.d.ts +2 -0
  3. package/dist/conversations/conversations.service.js +6 -1
  4. package/dist/conversations/events.d.ts +12 -0
  5. package/dist/conversations/events.js +23 -0
  6. package/dist/errors.d.ts +13 -0
  7. package/dist/errors.js +13 -0
  8. package/dist/evals/reconstruct.d.ts +9 -1
  9. package/dist/evals/reconstruct.js +7 -0
  10. package/dist/handoff/app-schemes.d.ts +28 -0
  11. package/dist/handoff/app-schemes.js +41 -0
  12. package/dist/handoff/handoff-paths.d.ts +26 -0
  13. package/dist/handoff/handoff-paths.js +25 -0
  14. package/dist/handoff/handoff-tickets.d.ts +28 -0
  15. package/dist/handoff/handoff-tickets.js +111 -0
  16. package/dist/handoff/handoff.controller.d.ts +24 -0
  17. package/dist/handoff/handoff.controller.js +74 -0
  18. package/dist/handoff/handoff.module.d.ts +7 -0
  19. package/dist/handoff/handoff.module.js +26 -0
  20. package/dist/handoff/handoff.schemas.d.ts +13 -0
  21. package/dist/handoff/handoff.schemas.js +3 -0
  22. package/dist/handoff/handoff.service.d.ts +49 -0
  23. package/dist/handoff/handoff.service.js +96 -0
  24. package/dist/http/api.module.js +8 -0
  25. package/dist/http/meta.controller.d.ts +1 -0
  26. package/dist/http/meta.controller.js +7 -0
  27. package/dist/identity/sso.controller.d.ts +30 -6
  28. package/dist/identity/sso.controller.js +51 -17
  29. package/dist/identity/sso.d.ts +10 -2
  30. package/dist/identity/sso.js +15 -3
  31. package/dist/overrides.d.ts +4 -4
  32. package/dist/overrides.js +1 -1
  33. package/dist/platform/exclusions.js +5 -0
  34. package/dist/platform/ops/connectors.ops.js +4 -2
  35. package/dist/runtime/compaction.service.d.ts +6 -3
  36. package/dist/runtime/compaction.service.js +7 -6
  37. package/dist/runtime/context/build.d.ts +13 -3
  38. package/dist/runtime/context/build.js +26 -6
  39. package/dist/runtime/context/compaction.d.ts +29 -1
  40. package/dist/runtime/context/compaction.js +108 -39
  41. package/dist/runtime/context/run-outcome.d.ts +10 -0
  42. package/dist/runtime/context/run-outcome.js +92 -0
  43. package/dist/runtime/model-call.d.ts +9 -0
  44. package/dist/runtime/model-call.js +63 -7
  45. package/dist/runtime/project/knowledge.service.d.ts +16 -7
  46. package/dist/runtime/project/knowledge.service.js +31 -13
  47. package/dist/tools/connectors.service.d.ts +4 -13
  48. package/dist/tools/connectors.service.js +12 -21
  49. package/dist/tools/oauth/flow.d.ts +16 -2
  50. package/dist/tools/oauth/flow.js +23 -4
  51. package/dist/tools/oauth/oauth.controller.d.ts +19 -7
  52. package/dist/tools/oauth/oauth.controller.js +42 -12
  53. package/dist/tools/oauth/oauth.schemas.d.ts +14 -1
  54. package/dist/tools/oauth/oauth.schemas.js +4 -1
  55. package/package.json +3 -3
@@ -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 what
332
- * follows it. `openers` is the number of covered opening messages re-rendered right after this
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 what
560
- * follows it. `openers` is the number of covered opening messages re-rendered right after this
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,19 @@ 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;
54
+ /**
55
+ * The share of the model's context window a manual compaction keeps verbatim at most (context
56
+ * compaction spec §4.7, maintainer decision 2026-11-28).
57
+ */
58
+ export declare const MANUAL_TAIL_SHARE = 0.2;
59
+ /**
60
+ * The kept tail's budget of a manual compaction (spec §4.7, maintainer decision 2026-11-28): about
61
+ * {@link MANUAL_TAIL_SHARE} of the model's context window, never more than the tail budget every
62
+ * compaction has (`tailBudget`, the planning target minus the system prompt and tool definitions).
63
+ */
64
+ export declare function manualTailBudget(contextWindow: number, tailBudget: number): number;
52
65
  /**
53
66
  * The compaction plan: keep the most recent `settings.keepRecentTurns` turns verbatim (a maximum,
54
67
  * not a rule) and transcribe everything older that the previous summary does not cover yet (that
@@ -63,8 +76,15 @@ export declare function shouldCompact(estimate: number, window: number, settings
63
76
  * right after the summary (build.ts). A latest turn without a tool pair is kept whole (the hard fit
64
77
  * guard handles the rest). `coversUpToSeq` is the largest seq before the first kept event. Returns
65
78
  * null when there is nothing to summarize.
79
+ *
80
+ * `opts.manual` (a manual compact run, spec §4.7, maintainer decision 2026-11-28) ignores
81
+ * `keepRecentTurns`: the kept tail starts at the latest user turn, and inside it the same cut at
82
+ * tool-pair boundaries keeps only what fits `budget` (the caller passes {@link manualTailBudget}),
83
+ * never less than the latest tool pair.
66
84
  */
67
- export declare function compactionPlan(events: ConversationEvent[], settings: CompactionSettings, budget: number): {
85
+ export declare function compactionPlan(events: ConversationEvent[], settings: CompactionSettings, budget: number, opts?: {
86
+ manual?: boolean;
87
+ }): {
68
88
  coversUpToSeq: number;
69
89
  transcript: string;
70
90
  } | null;
@@ -81,6 +101,14 @@ export declare function compactionPlan(events: ConversationEvent[], settings: Co
81
101
  * and a covered interjection (after the first call) is never one. Sorted by seq.
82
102
  */
83
103
  export declare function openingSeqs(events: readonly ConversationEvent[], runId: string, coversUpToSeq: number, absorbedUpToSeq?: number): number[];
104
+ /**
105
+ * The opening messages a manual compaction's summary re-renders (context compaction spec §4.7,
106
+ * maintainer decision 2026-11-28): a compact run is started by no message, so its own run has none;
107
+ * the turn it cuts into is the one the latest run a message started (trigger `message` or
108
+ * `schedule`) opened, and {@link openingSeqs} of that run decides which of its opening messages the
109
+ * summary covers. None when no such run is in the log.
110
+ */
111
+ export declare function manualOpeningSeqs(events: readonly ConversationEvent[], coversUpToSeq: number, absorbedUpToSeq: number): number[];
84
112
  /**
85
113
  * The text to store as the compaction summary (context compaction spec §4.2.1): the `<summary>`
86
114
  * block when the model returned one, since the `<analysis>` scratchpad must never be sent in a
@@ -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,24 @@ 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
+ }
132
+ /**
133
+ * The share of the model's context window a manual compaction keeps verbatim at most (context
134
+ * compaction spec §4.7, maintainer decision 2026-11-28).
135
+ */
136
+ export const MANUAL_TAIL_SHARE = 0.2;
137
+ /**
138
+ * The kept tail's budget of a manual compaction (spec §4.7, maintainer decision 2026-11-28): about
139
+ * {@link MANUAL_TAIL_SHARE} of the model's context window, never more than the tail budget every
140
+ * compaction has (`tailBudget`, the planning target minus the system prompt and tool definitions).
141
+ */
142
+ export function manualTailBudget(contextWindow, tailBudget) {
143
+ return Math.min(tailBudget, Math.floor(contextWindow * MANUAL_TAIL_SHARE));
144
+ }
126
145
  /**
127
146
  * The compaction plan: keep the most recent `settings.keepRecentTurns` turns verbatim (a maximum,
128
147
  * not a rule) and transcribe everything older that the previous summary does not cover yet (that
@@ -137,8 +156,13 @@ export function shouldCompact(estimate, window, settings) {
137
156
  * right after the summary (build.ts). A latest turn without a tool pair is kept whole (the hard fit
138
157
  * guard handles the rest). `coversUpToSeq` is the largest seq before the first kept event. Returns
139
158
  * null when there is nothing to summarize.
159
+ *
160
+ * `opts.manual` (a manual compact run, spec §4.7, maintainer decision 2026-11-28) ignores
161
+ * `keepRecentTurns`: the kept tail starts at the latest user turn, and inside it the same cut at
162
+ * tool-pair boundaries keeps only what fits `budget` (the caller passes {@link manualTailBudget}),
163
+ * never less than the latest tool pair.
140
164
  */
141
- export function compactionPlan(events, settings, budget) {
165
+ export function compactionPlan(events, settings, budget, opts = {}) {
142
166
  const sorted = [...events].sort((a, b) => a.seq - b.seq);
143
167
  const prev = latestSummary(sorted);
144
168
  const floor = prev ? prev.payload.coversUpToSeq : Number.NEGATIVE_INFINITY;
@@ -149,43 +173,41 @@ export function compactionPlan(events, settings, budget) {
149
173
  userIdx.push(i);
150
174
  });
151
175
  const atPair = pairBoundaries(candidate);
152
- const tail = tailTokens(candidate);
153
- const keep = settings.keepRecentTurns;
176
+ // run outcome notes (./run-outcome.ts), read from the whole log: a run's start may be older
177
+ const notes = runOutcomeNotes(sorted);
178
+ const tail = tailTokens(candidate, notes);
154
179
  let boundary;
155
- if (keep <= 0)
156
- boundary = candidate.length;
157
- else if (userIdx.length < keep)
158
- boundary = 0;
159
- else
160
- boundary = userIdx[userIdx.length - keep];
161
- boundary = keepToolPairs(atPair, userIdx, boundary);
162
- if (boundary < candidate.length && tail[boundary] > budget) {
163
- // size-aware tail: drop earlier kept turns until the rest fits the budget
164
- for (const start of userIdx) {
165
- if (start <= boundary)
166
- continue;
167
- boundary = keepToolPairs(atPair, userIdx, start);
168
- if (tail[boundary] <= budget)
169
- break;
180
+ if (opts.manual === true) {
181
+ // every turn before the latest user turn is summarized; without a user message since the
182
+ // last summary the whole range is the (continuing) latest turn
183
+ boundary = keepToolPairs(atPair, userIdx, userIdx.at(-1) ?? 0);
184
+ if (boundary < candidate.length && tail[boundary] > budget) {
185
+ boundary = cutInsideTurn(candidate, atPair, tail, boundary, budget);
170
186
  }
171
- // the latest user turn alone is over the budget: cut inside it at a tool-pair boundary,
172
- // oldest first, never past the latest tool pair (spec §4.2, revision 2026-11-15)
173
- if (tail[boundary] > budget) {
174
- let limit = -1;
175
- for (let i = candidate.length - 1; i > boundary && limit < 0; i--) {
176
- const e = candidate[i];
177
- if (e.type === "assistant_message" && e.payload.content.some((b) => b.type === "tool_call"))
178
- limit = i;
179
- }
180
- let chosen = boundary;
181
- for (let j = boundary + 1; j <= limit; j++) {
182
- if (!atPair[j])
187
+ }
188
+ else {
189
+ const keep = settings.keepRecentTurns;
190
+ if (keep <= 0)
191
+ boundary = candidate.length;
192
+ else if (userIdx.length < keep)
193
+ boundary = 0;
194
+ else
195
+ boundary = userIdx[userIdx.length - keep];
196
+ boundary = keepToolPairs(atPair, userIdx, boundary);
197
+ if (boundary < candidate.length && tail[boundary] > budget) {
198
+ // size-aware tail: drop earlier kept turns until the rest fits the budget
199
+ for (const start of userIdx) {
200
+ if (start <= boundary)
183
201
  continue;
184
- chosen = j;
185
- if (tail[j] <= budget)
202
+ boundary = keepToolPairs(atPair, userIdx, start);
203
+ if (tail[boundary] <= budget)
186
204
  break;
187
205
  }
188
- boundary = chosen;
206
+ // the latest user turn alone is over the budget: cut inside it (spec §4.2, revision
207
+ // 2026-11-15)
208
+ if (tail[boundary] > budget) {
209
+ boundary = cutInsideTurn(candidate, atPair, tail, boundary, budget);
210
+ }
189
211
  }
190
212
  }
191
213
  const covered = candidate.slice(0, boundary);
@@ -198,7 +220,7 @@ export function compactionPlan(events, settings, budget) {
198
220
  }
199
221
  const lines = [];
200
222
  for (const e of covered) {
201
- const line = transcriptLine(e);
223
+ const line = transcriptLine(e, notes);
202
224
  if (line)
203
225
  lines.push(line);
204
226
  if (e.type !== "assistant_message")
@@ -256,15 +278,33 @@ export function openingSeqs(events, runId, coversUpToSeq, absorbedUpToSeq = Numb
256
278
  .filter((e) => e.type === "user_message" && e.seq > floor && e.seq <= upTo && e.seq <= coversUpToSeq)
257
279
  .map((e) => e.seq);
258
280
  }
281
+ /**
282
+ * The opening messages a manual compaction's summary re-renders (context compaction spec §4.7,
283
+ * maintainer decision 2026-11-28): a compact run is started by no message, so its own run has none;
284
+ * the turn it cuts into is the one the latest run a message started (trigger `message` or
285
+ * `schedule`) opened, and {@link openingSeqs} of that run decides which of its opening messages the
286
+ * summary covers. None when no such run is in the log.
287
+ */
288
+ export function manualOpeningSeqs(events, coversUpToSeq, absorbedUpToSeq) {
289
+ const start = events
290
+ .filter((e) => e.type === "run_started" &&
291
+ (e.payload.trigger === undefined ||
292
+ e.payload.trigger === "message" ||
293
+ e.payload.trigger === "schedule"))
294
+ .reduce((a, e) => (a === null || e.seq > a.seq ? e : a), null);
295
+ if (start?.runId == null)
296
+ return [];
297
+ return openingSeqs(events, start.runId, coversUpToSeq, absorbedUpToSeq);
298
+ }
259
299
  /**
260
300
  * Estimated input tokens of the kept tail from each index (`out[i]` for the events from `i` on,
261
301
  * `out[length]` = 0): the events rendered as the transcript renders them, then estimated with the
262
302
  * request estimator.
263
303
  */
264
- function tailTokens(candidate) {
304
+ function tailTokens(candidate, notes) {
265
305
  const out = new Array(candidate.length + 1).fill(0);
266
306
  for (let i = candidate.length - 1; i >= 0; i--) {
267
- const line = transcriptLine(candidate[i]);
307
+ const line = transcriptLine(candidate[i], notes);
268
308
  const own = line
269
309
  ? estimateTokens([{ role: "user", content: [{ type: "text", text: line }] }], [])
270
310
  : 0;
@@ -327,7 +367,30 @@ function keepToolPairs(atPair, userIdx, boundary) {
327
367
  }
328
368
  return 0;
329
369
  }
330
- function transcriptLine(e) {
370
+ /**
371
+ * The cut inside the latest user turn (context compaction spec §4.2, revision 2026-11-15): from
372
+ * `boundary`, the first tool-pair boundary, oldest first, whose tail fits `budget`, never past the
373
+ * latest tool pair (the latest assistant message with tool calls). A turn without a tool pair after
374
+ * `boundary` keeps `boundary`.
375
+ */
376
+ function cutInsideTurn(candidate, atPair, tail, boundary, budget) {
377
+ let limit = -1;
378
+ for (let i = candidate.length - 1; i > boundary && limit < 0; i--) {
379
+ const e = candidate[i];
380
+ if (e.type === "assistant_message" && e.payload.content.some((b) => b.type === "tool_call"))
381
+ limit = i;
382
+ }
383
+ let chosen = boundary;
384
+ for (let j = boundary + 1; j <= limit; j++) {
385
+ if (!atPair[j])
386
+ continue;
387
+ chosen = j;
388
+ if (tail[j] <= budget)
389
+ break;
390
+ }
391
+ return chosen;
392
+ }
393
+ function transcriptLine(e, notes) {
331
394
  switch (e.type) {
332
395
  case "user_message": {
333
396
  const body = renderBlocks(e.payload.content);
@@ -364,6 +427,13 @@ function transcriptLine(e) {
364
427
  // so the summary never carries the project's instructions in a paraphrase
365
428
  // run_context is left out: its current values follow the summary anyway (build.ts), and
366
429
  // stale names should not be summarised as current
430
+ // a run that ended before it finished is a system message of the request (build.ts); a compact
431
+ // run's end has no note
432
+ case "run_aborted":
433
+ case "run_failed": {
434
+ const note = notes.get(e.seq);
435
+ return note === undefined ? null : `System reminder: ${note}`;
436
+ }
367
437
  case "tool_result":
368
438
  return `Tool result ${e.payload.toolKey}${e.payload.isError ? " (error)" : ""}: ${e.payload.content}`;
369
439
  // Every other event type is left out of the transcript: not model-visible, or re-rendered
@@ -395,9 +465,8 @@ function transcriptLine(e) {
395
465
  case "subagent_finished":
396
466
  case "compaction_summary":
397
467
  case "compaction_failed":
468
+ case "compaction_skipped":
398
469
  case "run_finished":
399
- case "run_aborted":
400
- case "run_failed":
401
470
  // permission_context, like device_paths, follows the summary (the latest covered ones again,
402
471
  // build.ts); the profile change and the review record are not model-visible
403
472
  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,15 @@ 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`): it plans with the manual rule (every turn before
376
+ * the latest summarized, at most {@link manualTailBudget} of the latest turn kept; maintainer
377
+ * decision 2026-11-28), which the reactive path (`force` alone) does not. An outcome the automatic
378
+ * paths keep silent is recorded, so the person sees what their action did: nothing to summarize
379
+ * writes `compaction_skipped`, a model or storage that cannot be reached right now writes
380
+ * `compaction_failed`.
381
+ */
382
+ manual?: boolean;
374
383
  }
375
384
  /** What one compaction execution wrote: the events, the summary's seq and whether it failed. */
376
385
  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, manualOpeningSeqs, manualTailBudget, 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 skipped(events);
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 skipped(events);
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));
@@ -790,11 +814,43 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
790
814
  // the input room left for the kept tail: the planning target `W - O_p - R_p`, minus the system
791
815
  // prompt and tool definitions every request carries
792
816
  const tailBudget = bounds.target - estimateTokens([], built.system, built.tools);
793
- const plan = compactionPlan(events, compaction, tailBudget);
794
- if (!plan)
795
- return skipped(events);
817
+ // a manual compaction ignores keepRecentTurns and keeps at most about a fifth of the window of
818
+ // the latest turn (spec §4.7, maintainer decision 2026-11-28); the reactive path (`force`
819
+ // without `manual`) plans like the proactive one
820
+ const manual = opts.manual === true;
821
+ const plan = manual
822
+ ? compactionPlan(events, compaction, manualTailBudget(info.contextWindow, tailBudget), {
823
+ manual: true,
824
+ })
825
+ : compactionPlan(events, compaction, tailBudget);
826
+ if (!plan) {
827
+ if (!manual)
828
+ return skipped(events);
829
+ // a manual compaction that finds nothing to summarize says so (display only, never
830
+ // model-visible): nothing precedes the kept tail
831
+ const written = await appendCounted(deps, input, [
832
+ {
833
+ type: "compaction_skipped",
834
+ runId: input.runId,
835
+ idemKey: idem.compactionSkipped(input.runId),
836
+ payload: {
837
+ reason: "nothing_to_summarize",
838
+ turns: turnsSinceSummary(events),
839
+ step: input.step,
840
+ },
841
+ },
842
+ ]);
843
+ return {
844
+ events: await mergeWritten(deps.eventLog, input.conversationId, events, written),
845
+ summarySeq: null,
846
+ failed: false,
847
+ };
848
+ }
796
849
  // decided now and recorded in the summary (spec §4.2): the request never depends on later events
797
- const opening = openingSeqs(events, input.runId, plan.coversUpToSeq, input.absorbedUpToSeq);
850
+ // a manual compact run is started by no message: the turn it cuts into is the latest message run's
851
+ const opening = manual
852
+ ? manualOpeningSeqs(events, plan.coversUpToSeq, input.absorbedUpToSeq)
853
+ : openingSeqs(events, input.runId, plan.coversUpToSeq, input.absorbedUpToSeq);
798
854
  const { runId, step, signal, conversationId } = input;
799
855
  const ref = modelRef;
800
856
  // §4.6 progress: from here the compaction is certain, so the conversation may show a row. It is