@capybara-hq/kernel 0.1.0-rc.100 → 0.1.0-rc.102

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,7 +3,7 @@
3
3
  "schemaVersion": 1,
4
4
  "marketplace": {
5
5
  "url": "https://github.com/capybara-hq/plugins.git",
6
- "commit": "1f142e1cebba0b54d94ba69b97004609d9c03cc4"
6
+ "commit": "ff7f84534f29d9e65a0a1cdca80337d618cfee54"
7
7
  },
8
8
  "plugins": [
9
9
  {
@@ -98,8 +98,8 @@
98
98
  "name": "device-local",
99
99
  "source": "npm",
100
100
  "npm": "@capybara-hq/plugin-device-local",
101
- "version": "0.1.0-rc.12",
102
- "integrity": "sha512-ncQmaRGa48fNjFD5rHQL94yEzBKv0pTS+4vy1uoK9SMWqSJw4/NUfVHs18Li0N2X92yRUystyuGHuJ0/oD4HPA==",
101
+ "version": "0.1.0-rc.13",
102
+ "integrity": "sha512-gZOI8bmP5sfADZkEbB1nuPf+32qVFNJm92RyiFuLhiNNluLWN5ABy4DJehvjFy6bgs+J5Jhu88byfDt0EIrlww==",
103
103
  "required": false,
104
104
  "scope": "all"
105
105
  },
@@ -107,8 +107,8 @@
107
107
  "name": "todo",
108
108
  "source": "npm",
109
109
  "npm": "@capybara-hq/plugin-todo",
110
- "version": "0.1.0-rc.14",
111
- "integrity": "sha512-HtGVlONC/l11Pw0lctdOMQc29ccUaVuU86LYx6cIq/plvfGKUXzSO9K/fAM3ED64eHNPSAUUYGRutloQY6HsfA==",
110
+ "version": "0.1.0-rc.15",
111
+ "integrity": "sha512-mfGmDbr14cPfp8CIqlChgSze/kdQVl2ij4Px5nlf4EOQA74qWhmNnjrJOK0vfXdkJP4J4D97zMBTiwupaHJb9Q==",
112
112
  "required": false
113
113
  },
114
114
  {
@@ -35,8 +35,10 @@ export declare const conversationTopic: (conversationId: string) => string;
35
35
  * tells by it whether it has the step's text from the start (the channel outbound only drafts
36
36
  * complete text) and drops what a live draft already covers (spec 2026-11-07 §3.2). Streamed
37
37
  * tool calls (streaming tool input spec §4, display only): `tool_start` (`callId`, `name`),
38
- * `tool_input` (`callId`, `text`, `offset` counted per call) and `tool_base` (`callId`, `text`,
39
- * `sha256`: the file a streaming `Write` replaces);
38
+ * `tool_input` (`callId`, `text`, `offset` counted per call), `tool_base` (`callId`, `text`,
39
+ * `sha256`: the file a streaming `Write` replaces; `guess` `{ path }` for a guessed candidate)
40
+ * and `tool_base_verdict` (`callId`, `confirmed`: the path closed on a guess, spec 2026-11-27
41
+ * §4.4);
40
42
  * - `ui`:插件经 `ctx.ui.invalidate` 告知这个会话的某个界面贡献变了(不进日志、不是模型可见内容),
41
43
  * SSE 转发为 `event: ui`,网页据此重新取视图。
42
44
  * - `subagent_progress`: after each step of a sub-agent run, on the topic of **every ancestor**
@@ -56,12 +58,16 @@ export type ConversationBusMessage = {
56
58
  kind: "delta";
57
59
  runId: string;
58
60
  step: number;
59
- delta: "text" | "thinking" | "tool_start" | "tool_input" | "tool_base" | "step_reset";
61
+ delta: "text" | "thinking" | "tool_start" | "tool_input" | "tool_base" | "tool_base_verdict" | "step_reset";
60
62
  text?: string;
61
63
  offset?: number;
62
64
  callId?: string;
63
65
  name?: string;
64
66
  sha256?: string;
67
+ guess?: {
68
+ path: string;
69
+ };
70
+ confirmed?: boolean;
65
71
  } | {
66
72
  kind: "ui";
67
73
  plugin: string;
@@ -189,6 +195,12 @@ export declare class EventLog {
189
195
  latestOfType<T extends ConversationEventType>(conversationId: string, type: T): Promise<Extract<ConversationEvent, {
190
196
  type: T;
191
197
  }> | undefined>;
198
+ /**
199
+ * The paths of the conversation's newest recorded file states (`tool_result.view.file`), one per
200
+ * path, newest first, at most `limit`: the candidates of a guessed `Write` base (spec 2026-11-27
201
+ * §4.2). Each path's latest state is what {@link latestFileState} returns for it.
202
+ */
203
+ recentFilePaths(conversationId: string, limit: number): Promise<string[]>;
192
204
  /**
193
205
  * The file state (`tool_result.view.file`) the latest `Read` / `Write` / `Edit` result of this
194
206
  * conversation recorded for `path` (a normalized sandbox path); null when none did. One index
@@ -338,6 +338,27 @@ let EventLog = class EventLog {
338
338
  .executeTakeFirst();
339
339
  return r && toEvent(r);
340
340
  }
341
+ /**
342
+ * The paths of the conversation's newest recorded file states (`tool_result.view.file`), one per
343
+ * path, newest first, at most `limit`: the candidates of a guessed `Write` base (spec 2026-11-27
344
+ * §4.2). Each path's latest state is what {@link latestFileState} returns for it.
345
+ */
346
+ async recentFilePaths(conversationId, limit) {
347
+ const rows = await this.db
348
+ .selectFrom("conversation_events")
349
+ .select([
350
+ sql `payload->'view'->'file'->>'path'`.as("path"),
351
+ sql `max(seq)`.as("last"),
352
+ ])
353
+ .where("conversation_id", "=", conversationId)
354
+ .where("type", "=", "tool_result")
355
+ .where(sql `payload->'view'->'file'->>'path' IS NOT NULL`)
356
+ .groupBy(sql `payload->'view'->'file'->>'path'`)
357
+ .orderBy("last", "desc")
358
+ .limit(limit)
359
+ .execute();
360
+ return rows.map((r) => r.path);
361
+ }
341
362
  /**
342
363
  * The file state (`tool_result.view.file`) the latest `Read` / `Write` / `Edit` result of this
343
364
  * conversation recorded for `path` (a normalized sandbox path); null when none did. One index
@@ -596,6 +596,7 @@ export declare const SubagentFinishStatusSchema: z.ZodEnum<{
596
596
  completed: "completed";
597
597
  failed: "failed";
598
598
  max_duration: "max_duration";
599
+ max_output: "max_output";
599
600
  max_steps: "max_steps";
600
601
  timed_out: "timed_out";
601
602
  }>;
@@ -1957,6 +1958,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1957
1958
  completed: "completed";
1958
1959
  failed: "failed";
1959
1960
  max_duration: "max_duration";
1961
+ max_output: "max_output";
1960
1962
  max_steps: "max_steps";
1961
1963
  timed_out: "timed_out";
1962
1964
  }>;
@@ -1989,6 +1991,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1989
1991
  completed: "completed";
1990
1992
  failed: "failed";
1991
1993
  max_duration: "max_duration";
1994
+ max_output: "max_output";
1992
1995
  max_steps: "max_steps";
1993
1996
  timed_out: "timed_out";
1994
1997
  }>>;
@@ -2055,6 +2058,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
2055
2058
  budget: "budget";
2056
2059
  completed: "completed";
2057
2060
  max_duration: "max_duration";
2061
+ max_output: "max_output";
2058
2062
  max_steps: "max_steps";
2059
2063
  }>;
2060
2064
  consumedUpToSeq: z.ZodNumber;
@@ -660,6 +660,7 @@ export const SubagentFinishStatusSchema = z.enum([
660
660
  "max_steps",
661
661
  "max_duration",
662
662
  "budget",
663
+ "max_output",
663
664
  "aborted",
664
665
  "timed_out",
665
666
  "failed",
@@ -1780,8 +1781,11 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
1780
1781
  step: count,
1781
1782
  })),
1782
1783
  ev("run_finished", z.object({
1783
- /** `budget`: a sub-agent stopped at its parent run's token cap (phase C, spec §8.3). */
1784
- reason: z.enum(["completed", "max_steps", "max_duration", "budget"]),
1784
+ /**
1785
+ * `budget`: a sub-agent stopped at its parent run's token cap (phase C, spec §8.3).
1786
+ * `max_output`: the model's steps kept stopping at the output token limit (issue #951).
1787
+ */
1788
+ reason: z.enum(["completed", "max_steps", "max_duration", "budget", "max_output"]),
1785
1789
  consumedUpToSeq: seqNo,
1786
1790
  })),
1787
1791
  ev("run_failed", z.object({ error: z.object({ code: z.string(), message: z.string() }) })),
@@ -667,7 +667,9 @@ export async function replayRun(d, s, candidate, evalRunId, signal) {
667
667
  : {
668
668
  type: "run_finished",
669
669
  payload: {
670
- reason: outcome.kind === "max_steps" || outcome.kind === "max_duration"
670
+ reason: outcome.kind === "max_steps" ||
671
+ outcome.kind === "max_duration" ||
672
+ outcome.kind === "max_output"
671
673
  ? outcome.kind
672
674
  : "completed",
673
675
  consumedUpToSeq: "consumedUpToSeq" in outcome ? Math.max(outcome.consumedUpToSeq, trigger) : trigger,
@@ -350,6 +350,8 @@ export declare function summaryText(summary: string): string;
350
350
  * (同一步的多个结果合并,按该 assistant 消息里 tool_call 的顺序;找不到对应调用的结果不进请求)。
351
351
  * 其他事件不进请求。提供 `absorbedUpToSeq` 时,
352
352
  * 尚未被吸收的可吸收事件不进请求,运行中途到达的放在吸收它的调用处(见 BuildModelRequestInput)。
353
+ * An `assistant_message` with `stopReason: "max_tokens"` is followed by a `role: "system"`
354
+ * {@link OUTPUT_TRUNCATED_TEXT} (issue #951).
353
355
  * 只追加:新事件只会在 messages 末尾追加;唯一的前缀变化来自新的压缩摘要。
354
356
  * `step` 与 `agentVersion` 不进请求内容(保证缓存前缀稳定),由调用方写入 `model_call` 事件。
355
357
  */
@@ -5,6 +5,7 @@ import { isAbsorbable, } from "../../conversations/events.js";
5
5
  import { catalogText, isAlwaysLoaded } from "../../tools/builtins/tool-search.js";
6
6
  import { renderSubagentDelivery } from "../subagents/render.js";
7
7
  import { devicePathsAt, devicePathsText } from "./device-paths.js";
8
+ import { OUTPUT_TRUNCATED_TEXT } from "./output-truncated.js";
8
9
  import { permissionContextHistory } from "./permission-profile.js";
9
10
  import { pluginContextsAfterSummary, pluginContextText } from "./plugin-context.js";
10
11
  import { latestProjectRoot, projectRootText } from "./project-root.js";
@@ -571,6 +572,8 @@ export function summaryText(summary) {
571
572
  * (同一步的多个结果合并,按该 assistant 消息里 tool_call 的顺序;找不到对应调用的结果不进请求)。
572
573
  * 其他事件不进请求。提供 `absorbedUpToSeq` 时,
573
574
  * 尚未被吸收的可吸收事件不进请求,运行中途到达的放在吸收它的调用处(见 BuildModelRequestInput)。
575
+ * An `assistant_message` with `stopReason: "max_tokens"` is followed by a `role: "system"`
576
+ * {@link OUTPUT_TRUNCATED_TEXT} (issue #951).
574
577
  * 只追加:新事件只会在 messages 末尾追加;唯一的前缀变化来自新的压缩摘要。
575
578
  * `step` 与 `agentVersion` 不进请求内容(保证缓存前缀稳定),由调用方写入 `model_call` 事件。
576
579
  */
@@ -904,6 +907,11 @@ export function buildModelRequest(input) {
904
907
  if (blocks.length > 0)
905
908
  messages.push({ role: "user", content: [...blocks, ...images] });
906
909
  }
910
+ // cut off at the output token limit (issue #951): said right after it, from the logged
911
+ // stop reason alone (also when nothing of the reply was kept)
912
+ if (e.payload.stopReason === "max_tokens") {
913
+ messages.push({ role: "system", content: OUTPUT_TRUNCATED_TEXT });
914
+ }
907
915
  break;
908
916
  case "reminder":
909
917
  messages.push({ role: "system", content: e.payload.text });
@@ -0,0 +1,16 @@
1
+ /**
2
+ * A model step cut off at the output token limit (issue #951). The step's `assistant_message`
3
+ * records `stopReason: "max_tokens"`; providers drop a tool call whose arguments were cut off, so
4
+ * nothing of it runs. Request building renders {@link OUTPUT_TRUNCATED_TEXT} as a system message
5
+ * right after such a message: derived from the logged stop reason alone, so a reconstruction
6
+ * renders the same text and no `DriftReason` is needed. The loop then gives the model another
7
+ * step, up to {@link MAX_TRUNCATED_STEPS} truncated steps in a row, after which the run ends with
8
+ * `max_output`.
9
+ */
10
+ /** The model-visible text after a step cut off at the output token limit (English). */
11
+ export declare const OUTPUT_TRUNCATED_TEXT: string;
12
+ /**
13
+ * Truncated model steps in a row after which the run ends with `max_output` instead of giving the
14
+ * model another step.
15
+ */
16
+ export declare const MAX_TRUNCATED_STEPS = 3;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * A model step cut off at the output token limit (issue #951). The step's `assistant_message`
3
+ * records `stopReason: "max_tokens"`; providers drop a tool call whose arguments were cut off, so
4
+ * nothing of it runs. Request building renders {@link OUTPUT_TRUNCATED_TEXT} as a system message
5
+ * right after such a message: derived from the logged stop reason alone, so a reconstruction
6
+ * renders the same text and no `DriftReason` is needed. The loop then gives the model another
7
+ * step, up to {@link MAX_TRUNCATED_STEPS} truncated steps in a row, after which the run ends with
8
+ * `max_output`.
9
+ */
10
+ /** The model-visible text after a step cut off at the output token limit (English). */
11
+ export const OUTPUT_TRUNCATED_TEXT = "Your previous response was cut off because it reached the output token limit. " +
12
+ "A tool call that was still being written when it was cut off was incomplete and was not run. " +
13
+ "Continue from where the response stopped. Keep each response, including the input of each " +
14
+ "tool call, well under the limit: split long content across several smaller tool calls.";
15
+ /**
16
+ * Truncated model steps in a row after which the run ends with `max_output` instead of giving the
17
+ * model another step.
18
+ */
19
+ export const MAX_TRUNCATED_STEPS = 3;
@@ -1,4 +1,5 @@
1
1
  import { Annotation, END, START, StateGraph } from "@langchain/langgraph";
2
+ import { MAX_TRUNCATED_STEPS } from "./context/output-truncated.js";
2
3
  import { MediaCache } from "./media-cache.js";
3
4
  import { runFinalWrapUp, runModelStep, } from "./model-call.js";
4
5
  import { withExclusiveAdmission } from "./run-execution.js";
@@ -26,6 +27,7 @@ const LoopState = Annotation.Root({
26
27
  lastStopReason: Annotation(),
27
28
  outcome: Annotation(),
28
29
  budgetWrapUp: Annotation(),
30
+ truncatedSteps: Annotation(),
29
31
  });
30
32
  const INITIAL = {
31
33
  step: 0,
@@ -33,6 +35,7 @@ const INITIAL = {
33
35
  lastStopReason: null,
34
36
  outcome: null,
35
37
  budgetWrapUp: null,
38
+ truncatedSteps: null,
36
39
  };
37
40
  /**
38
41
  * prepare 节点在停机信号下抛出:本次 invoke 以它结束,checkpoint 停在 prepare 之前
@@ -209,8 +212,19 @@ export class LangGraphLoop {
209
212
  if (r.aborted) {
210
213
  return { lastStopReason: "aborted", outcome: timedOut() ? "max_duration" : "aborted" };
211
214
  }
215
+ // cut off at the output token limit (issue #951): request building tells the model, and it
216
+ // gets another step, up to MAX_TRUNCATED_STEPS in a row
217
+ if (r.stopReason === "max_tokens") {
218
+ const truncatedSteps = (s.truncatedSteps ?? 0) + 1;
219
+ return {
220
+ lastStopReason: r.stopReason,
221
+ truncatedSteps,
222
+ outcome: truncatedSteps >= MAX_TRUNCATED_STEPS ? "max_output" : null,
223
+ };
224
+ }
212
225
  return {
213
226
  lastStopReason: r.stopReason,
227
+ truncatedSteps: null,
214
228
  outcome: r.stopReason === "tool_use" ? null : "completed",
215
229
  };
216
230
  };
@@ -276,7 +290,14 @@ export class LangGraphLoop {
276
290
  ? "wrapUp"
277
291
  : "model";
278
292
  }, ["model", "wrapUp", END])
279
- .addConditionalEdges("model", (s) => (s.budgetWrapUp === true ? "wrapUp" : s.outcome === null ? "tools" : END), ["tools", "wrapUp", END])
293
+ .addConditionalEdges("model", (s) => {
294
+ if (s.budgetWrapUp === true)
295
+ return "wrapUp";
296
+ if (s.outcome !== null)
297
+ return END;
298
+ // a truncated step has no tool calls to run (providers drop a cut-off one)
299
+ return s.lastStopReason === "max_tokens" ? "prepare" : "tools";
300
+ }, ["tools", "prepare", "wrapUp", END])
280
301
  .addEdge("tools", "prepare")
281
302
  .addEdge("wrapUp", END)
282
303
  .compile({ checkpointer: this.saver });
@@ -114,9 +114,12 @@ export declare const subagentWaitingIdemKey: (childRunId: string, waitId: string
114
114
  /** The id of a run's `subagents` wait in `step` (part of BullMQ job ids, so no `:`). */
115
115
  export declare const subagentsWaitId: (runId: string, step: number) => string;
116
116
  export type LoopOutcome =
117
- /** `budget`: a sub-agent run stopped at its parent run's token cap (phase C). */
117
+ /**
118
+ * `budget`: a sub-agent run stopped at its parent run's token cap (phase C). `max_output`: the
119
+ * model's steps kept stopping at the output token limit (issue #951).
120
+ */
118
121
  {
119
- kind: "completed" | "max_steps" | "max_duration" | "budget";
122
+ kind: "completed" | "max_steps" | "max_duration" | "budget" | "max_output";
120
123
  consumedUpToSeq: number;
121
124
  } | {
122
125
  kind: "aborted";
@@ -50,18 +50,26 @@ export declare const contextTooLargeText: (model: ModelInfo, target: number, est
50
50
  * `stream_end` (the step's model stream completed) and `step_end` (the step's `assistant_message`
51
51
  * is logged) carry no delta: the run worker's sink writes and then clears the step's live draft on
52
52
  * them (spec 2026-11-07 §3.2) and publishes neither. `tool_start` (`callId`, `name`), `tool_input`
53
- * (`callId`, `text`: a fragment of the call's JSON input) and `tool_base` (`callId`, `text`,
54
- * `sha256`: the file a streaming `Write` replaces) are display only (streaming tool input spec §4):
55
- * nothing streamed reaches the log, the model or a hook.
53
+ * (`callId`, `text`: a fragment of the call's JSON input), `tool_base` (`callId`, `text`,
54
+ * `sha256`: the file a streaming `Write` replaces; `guess` when it is a guessed candidate, spec
55
+ * 2026-11-27 §4.4) and `tool_base_verdict` (`callId`, `confirmed`: the path closed on a guess) are
56
+ * display only (streaming tool input spec §4): nothing streamed reaches the log, the model or a
57
+ * hook.
56
58
  */
57
59
  export type StreamSink = (delta: {
58
- kind: "text" | "thinking" | "tool_start" | "tool_input" | "tool_base" | "step_reset" | "stream_end" | "step_end";
60
+ kind: "text" | "thinking" | "tool_start" | "tool_input" | "tool_base" | "tool_base_verdict" | "step_reset" | "stream_end" | "step_end";
59
61
  runId: string;
60
62
  step: number;
61
63
  text?: string;
62
64
  callId?: string;
63
65
  name?: string;
64
66
  sha256?: string;
67
+ /** `tool_base`: the base is a guess, the candidate file at `path`. */
68
+ guess?: {
69
+ path: string;
70
+ };
71
+ /** `tool_base_verdict`: whether the path confirmed the guess. */
72
+ confirmed?: boolean;
65
73
  }) => void;
66
74
  export interface ModelStepDeps {
67
75
  db: KernelSchemaDb;
@@ -1395,7 +1395,7 @@ async function ladder(deps, input, events, runtime, compaction, tools, wrapUpRea
1395
1395
  sentAt = Date.now();
1396
1396
  // this attempt's pending base reads end with its stream (a reset, the end, an abort)
1397
1397
  const baseStop = new AbortController();
1398
- const bases = baseWatcher(deps, input, tools, baseStop.signal);
1398
+ const bases = baseWatcher(deps, input, tools, baseStop.signal, rung.ref);
1399
1399
  let outcome;
1400
1400
  try {
1401
1401
  outcome = await consumeModelStream(provider, sentRequest, info.streamIdleTimeoutMs ?? runtime.streamIdleMs, signal, (ev) => {
@@ -1668,7 +1668,7 @@ function classify(err) {
1668
1668
  * chat or sub-agent run with a reader gets one (an eval replay never reads a device). Its reads
1669
1669
  * stop when `stop` fires or the run aborts; a base found in time goes out as `tool_base`.
1670
1670
  */
1671
- function baseWatcher(deps, input, tools, stop) {
1671
+ function baseWatcher(deps, input, tools, stop, model) {
1672
1672
  const reader = deps.writeBase;
1673
1673
  const kind = input.conversationKind;
1674
1674
  if (reader === undefined || (kind !== "chat" && kind !== "subagent"))
@@ -1678,8 +1678,18 @@ function baseWatcher(deps, input, tools, stop) {
1678
1678
  reader,
1679
1679
  // the resolved tools carry their source (`ResolvedTool`): only the builtin Write reads
1680
1680
  inputViewOf: (name) => writeBaseViewOf(tools.list, name),
1681
- emit: (callId, base) => sink({ kind: "tool_base", runId, step, callId, text: base.text, sha256: base.sha256 }),
1681
+ emit: (callId, base) => sink({
1682
+ kind: "tool_base",
1683
+ runId,
1684
+ step,
1685
+ callId,
1686
+ text: base.text,
1687
+ sha256: base.sha256,
1688
+ ...(base.guess !== undefined && { guess: base.guess }),
1689
+ }),
1690
+ verdict: (callId, confirmed) => sink({ kind: "tool_base_verdict", runId, step, callId, confirmed }),
1682
1691
  conversationId,
1692
+ model: { provider: model.provider, model: model.model },
1683
1693
  signal: AbortSignal.any([input.signal, stop]),
1684
1694
  log: deps.log,
1685
1695
  ...(deps.writeBaseSettleMs !== undefined && { settleMs: deps.writeBaseSettleMs }),
@@ -23,11 +23,25 @@ export interface DraftTool {
23
23
  /** The step's {@link DRAFT_TOOL_INPUT_MAX} was reached: later fragments are not in the draft. */
24
24
  inputTruncated?: true;
25
25
  /** The file a streaming `Write` replaces (streaming tool input spec §4.1). */
26
- base?: {
27
- text: string;
28
- sha256: string;
26
+ base?: DraftBase;
27
+ }
28
+ /**
29
+ * A streaming `Write`'s base: exact, or a guess (spec 2026-11-27 §4.4) naming the candidate's path
30
+ * until the path's verdict. A rejected guess stays, marked, so a lagging draft never brings it back.
31
+ */
32
+ export interface DraftBase {
33
+ text: string;
34
+ sha256: string;
35
+ guess?: {
36
+ path: string;
29
37
  };
38
+ verdict?: "confirmed" | "rejected";
30
39
  }
40
+ /**
41
+ * The base a call keeps when `got` arrives (spec 2026-11-27 §4.4): the first one; an exact base
42
+ * replaces a guess not confirmed; the same guess takes a verdict it lacks.
43
+ */
44
+ export declare function mergeDraftBase(prev: DraftBase | undefined, got: DraftBase | undefined): DraftBase | undefined;
31
45
  /** What one step of a run has streamed so far. */
32
46
  export interface RunDraft {
33
47
  step: number;
@@ -73,14 +87,22 @@ export declare class RunDrafts {
73
87
  */
74
88
  appendToolInput(runId: string, step: number, callId: string, text: string): void;
75
89
  /**
76
- * The file a streaming `Write` replaces; kept only within {@link DRAFT_TOOL_INPUT_MAX}, which the
77
- * base shares with the input (spec: "input plus base"). Like {@link appendToolInput}, it ignores
78
- * a call never started.
90
+ * The file a streaming `Write` replaces (exact, or a guess); kept by {@link mergeDraftBase} and
91
+ * only within {@link DRAFT_TOOL_INPUT_MAX}, which bases share with the input (spec: "input plus
92
+ * base"). Like {@link appendToolInput}, it ignores a call never started.
79
93
  */
80
94
  setToolBase(runId: string, step: number, callId: string, base: {
81
95
  text: string;
82
96
  sha256: string;
97
+ guess?: {
98
+ path: string;
99
+ };
83
100
  }): void;
101
+ /**
102
+ * The verdict on a call's guessed base (spec 2026-11-27 §4.4): kept on a guess without one; a
103
+ * call without a guessed base ignores it.
104
+ */
105
+ setToolBaseVerdict(runId: string, step: number, callId: string, confirmed: boolean): void;
84
106
  /** The step's held draft, a fresh one when the run moved to another step. */
85
107
  private heldFor;
86
108
  /** The held draft changed: written now when the last write is a window old, else held. */
@@ -111,7 +133,7 @@ export declare class RunDrafts {
111
133
  /** What {@link streamSink} uses. */
112
134
  export interface StreamSinkDeps {
113
135
  bus: Pick<ExtensionContext["bus"], "publish">;
114
- drafts: Pick<RunDrafts, "append" | "flush" | "clear" | "startTool" | "appendToolInput" | "setToolBase">;
136
+ drafts: Pick<RunDrafts, "append" | "flush" | "clear" | "startTool" | "appendToolInput" | "setToolBase" | "setToolBaseVerdict">;
115
137
  log: Pick<Logger, "warn">;
116
138
  }
117
139
  /**
@@ -119,7 +141,7 @@ export interface StreamSinkDeps {
119
141
  * (`conv.<id>`, shared with `{ kind: "events" }`, so a subscriber on any replica gets them) with
120
142
  * `offset`, the characters of that channel (text or thinking) this attempt of the step streamed
121
143
  * before the delta, and keeps the step's live draft. Tool calls (streaming tool input spec §4):
122
- * `tool_start` and `tool_base` carry no offset, `tool_input`'s `offset` is the characters of that
144
+ * `tool_start`, `tool_base` and `tool_base_verdict` carry no offset, `tool_input`'s `offset` is the characters of that
123
145
  * call's input this attempt streamed before the delta. `step_reset` clears the draft and every
124
146
  * offset; `stream_end` / `step_end` only flush / clear the draft and are not published. A failed
125
147
  * publish is only logged: deltas are drafts, the `assistant_message` in the log is the truth.
@@ -25,6 +25,26 @@ export const DRAFT_TOOL_INPUT_MAX = 512 * 1024;
25
25
  export const draftKey = (runId, step) => `capk:run-draft:${runId}:${step}`;
26
26
  /** The steps of a run that have a draft (a set, so a reader finds them without a key scan). */
27
27
  const stepsKey = (runId) => `capk:run-draft-steps:${runId}`;
28
+ /**
29
+ * The base a call keeps when `got` arrives (spec 2026-11-27 §4.4): the first one; an exact base
30
+ * replaces a guess not confirmed; the same guess takes a verdict it lacks.
31
+ */
32
+ export function mergeDraftBase(prev, got) {
33
+ if (got === undefined)
34
+ return prev;
35
+ if (prev === undefined)
36
+ return got;
37
+ // an exact base replaces a guess not confirmed: it is only read after a rejection, so a copy
38
+ // that still shows the guess missed the verdict
39
+ if (prev.guess !== undefined && prev.verdict !== "confirmed" && got.guess === undefined)
40
+ return got;
41
+ if (prev.verdict === undefined &&
42
+ got.verdict !== undefined &&
43
+ prev.sha256 === got.sha256 &&
44
+ prev.guess?.path === got.guess?.path)
45
+ return { ...prev, verdict: got.verdict };
46
+ return prev;
47
+ }
28
48
  const isRecord = (x) => typeof x === "object" && x !== null && !Array.isArray(x);
29
49
  const parseTool = (x) => {
30
50
  if (!isRecord(x) || typeof x.id !== "string" || typeof x.name !== "string")
@@ -38,7 +58,12 @@ const parseTool = (x) => {
38
58
  t.inputTruncated = true;
39
59
  const b = x.base;
40
60
  if (isRecord(b) && typeof b.text === "string" && typeof b.sha256 === "string") {
41
- t.base = { text: b.text, sha256: b.sha256 };
61
+ const base = { text: b.text, sha256: b.sha256 };
62
+ if (isRecord(b.guess) && typeof b.guess.path === "string")
63
+ base.guess = { path: b.guess.path };
64
+ if (base.guess !== undefined && (b.verdict === "confirmed" || b.verdict === "rejected"))
65
+ base.verdict = b.verdict;
66
+ t.base = base;
42
67
  }
43
68
  return [t];
44
69
  };
@@ -122,22 +147,39 @@ let RunDrafts = class RunDrafts {
122
147
  this.changed(runId, h);
123
148
  }
124
149
  /**
125
- * The file a streaming `Write` replaces; kept only within {@link DRAFT_TOOL_INPUT_MAX}, which the
126
- * base shares with the input (spec: "input plus base"). Like {@link appendToolInput}, it ignores
127
- * a call never started.
150
+ * The file a streaming `Write` replaces (exact, or a guess); kept by {@link mergeDraftBase} and
151
+ * only within {@link DRAFT_TOOL_INPUT_MAX}, which bases share with the input (spec: "input plus
152
+ * base"). Like {@link appendToolInput}, it ignores a call never started.
128
153
  */
129
154
  setToolBase(runId, step, callId, base) {
130
155
  const h = this.heldFor(runId, step);
131
156
  const t = h.tools.find((x) => x.id === callId);
132
- if (t === undefined || t.base !== undefined)
157
+ if (t === undefined)
158
+ return;
159
+ const got = { text: base.text, sha256: base.sha256 };
160
+ if (base.guess !== undefined)
161
+ got.guess = { path: base.guess.path };
162
+ if (mergeDraftBase(t.base, got) !== got)
133
163
  return;
134
164
  const bytes = Buffer.byteLength(base.text);
135
165
  if (h.toolBytes + bytes > DRAFT_TOOL_INPUT_MAX)
136
166
  return;
137
- t.base = { text: base.text, sha256: base.sha256 };
167
+ t.base = got;
138
168
  h.toolBytes += bytes;
139
169
  this.changed(runId, h);
140
170
  }
171
+ /**
172
+ * The verdict on a call's guessed base (spec 2026-11-27 §4.4): kept on a guess without one; a
173
+ * call without a guessed base ignores it.
174
+ */
175
+ setToolBaseVerdict(runId, step, callId, confirmed) {
176
+ const h = this.heldFor(runId, step);
177
+ const t = h.tools.find((x) => x.id === callId);
178
+ if (t?.base?.guess === undefined || t.base.verdict !== undefined)
179
+ return;
180
+ t.base = { ...t.base, verdict: confirmed ? "confirmed" : "rejected" };
181
+ this.changed(runId, h);
182
+ }
141
183
  /** The step's held draft, a fresh one when the run moved to another step. */
142
184
  heldFor(runId, step) {
143
185
  let h = this.held.get(runId);
@@ -278,7 +320,7 @@ export { RunDrafts };
278
320
  * (`conv.<id>`, shared with `{ kind: "events" }`, so a subscriber on any replica gets them) with
279
321
  * `offset`, the characters of that channel (text or thinking) this attempt of the step streamed
280
322
  * before the delta, and keeps the step's live draft. Tool calls (streaming tool input spec §4):
281
- * `tool_start` and `tool_base` carry no offset, `tool_input`'s `offset` is the characters of that
323
+ * `tool_start`, `tool_base` and `tool_base_verdict` carry no offset, `tool_input`'s `offset` is the characters of that
282
324
  * call's input this attempt streamed before the delta. `step_reset` clears the draft and every
283
325
  * offset; `stream_end` / `step_end` only flush / clear the draft and are not published. A failed
284
326
  * publish is only logged: deltas are drafts, the `assistant_message` in the log is the truth.
@@ -303,7 +345,10 @@ export function streamSink(conversationId, deps) {
303
345
  }
304
346
  const { runId, step } = d;
305
347
  const text = d.text ?? "";
306
- if (d.kind === "tool_start" || d.kind === "tool_input" || d.kind === "tool_base") {
348
+ if (d.kind === "tool_start" ||
349
+ d.kind === "tool_input" ||
350
+ d.kind === "tool_base" ||
351
+ d.kind === "tool_base_verdict") {
307
352
  const callId = d.callId ?? "";
308
353
  if (d.kind === "tool_start") {
309
354
  const name = d.name ?? "";
@@ -316,10 +361,29 @@ export function streamSink(conversationId, deps) {
316
361
  deps.drafts.appendToolInput(runId, step, callId, text);
317
362
  void publish({ kind: "delta", runId, step, delta: "tool_input", callId, text, offset });
318
363
  }
364
+ else if (d.kind === "tool_base_verdict") {
365
+ const confirmed = d.confirmed === true;
366
+ deps.drafts.setToolBaseVerdict(runId, step, callId, confirmed);
367
+ void publish({ kind: "delta", runId, step, delta: "tool_base_verdict", callId, confirmed });
368
+ }
319
369
  else {
320
370
  const sha256 = d.sha256 ?? "";
321
- deps.drafts.setToolBase(runId, step, callId, { text, sha256 });
322
- void publish({ kind: "delta", runId, step, delta: "tool_base", callId, text, sha256 });
371
+ const guess = d.guess;
372
+ deps.drafts.setToolBase(runId, step, callId, {
373
+ text,
374
+ sha256,
375
+ ...(guess !== undefined && { guess }),
376
+ });
377
+ void publish({
378
+ kind: "delta",
379
+ runId,
380
+ step,
381
+ delta: "tool_base",
382
+ callId,
383
+ text,
384
+ sha256,
385
+ ...(guess !== undefined && { guess }),
386
+ });
323
387
  }
324
388
  return;
325
389
  }
@@ -13,6 +13,8 @@ export function subagentStatusText(status, opts = {}) {
13
13
  return "stopped at the time limit; the reply may be partial";
14
14
  case "budget":
15
15
  return "stopped: token budget used up";
16
+ case "max_output":
17
+ return "stopped: its replies kept reaching the output token limit; the reply may be partial";
16
18
  case "aborted":
17
19
  return opts.abortedBy === "parent" ? "stopped with this run" : "stopped by the user";
18
20
  case "timed_out":