@capybara-hq/kernel 0.1.0-rc.97 → 0.1.0-rc.98

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 (61) hide show
  1. package/dist/catalog/marketplaces.service.d.ts +1 -1
  2. package/dist/channels/channels.schemas.d.ts +10 -0
  3. package/dist/channels/channels.schemas.js +7 -0
  4. package/dist/channels/connections.service.d.ts +7 -0
  5. package/dist/channels/connections.service.js +4 -0
  6. package/dist/channels/features.d.ts +18 -1
  7. package/dist/channels/features.js +22 -0
  8. package/dist/channels/outbound.d.ts +19 -0
  9. package/dist/channels/outbound.js +531 -18
  10. package/dist/channels/phrases.d.ts +10 -0
  11. package/dist/channels/phrases.js +4 -0
  12. package/dist/channels/progress.d.ts +75 -0
  13. package/dist/channels/progress.js +216 -0
  14. package/dist/conversations/event-log.d.ts +8 -2
  15. package/dist/conversations/events.d.ts +5 -0
  16. package/dist/conversations/events.js +5 -1
  17. package/dist/conversations/prompt-suggestions.js +2 -2
  18. package/dist/db/kernel-schema.d.ts +16 -0
  19. package/dist/evals/run-replay.js +2 -2
  20. package/dist/evals/step-replay.js +2 -2
  21. package/dist/evals/worker.js +3 -1
  22. package/dist/extensions/plugin-icons.d.ts +7 -0
  23. package/dist/extensions/plugin-icons.js +8 -0
  24. package/dist/models/purposes.js +2 -2
  25. package/dist/platform/ops/channels.ops.js +24 -5
  26. package/dist/runtime/model-call.d.ts +23 -2
  27. package/dist/runtime/model-call.js +64 -9
  28. package/dist/runtime/run-drafts.d.ts +46 -4
  29. package/dist/runtime/run-drafts.js +110 -9
  30. package/dist/runtime/run-steps.d.ts +2 -1
  31. package/dist/runtime/run-steps.js +6 -2
  32. package/dist/runtime/runtime.module.js +3 -0
  33. package/dist/runtime/stream.controller.d.ts +7 -5
  34. package/dist/runtime/stream.controller.js +10 -6
  35. package/dist/runtime/stream.js +9 -1
  36. package/dist/runtime/write-base.d.ts +95 -0
  37. package/dist/runtime/write-base.js +281 -0
  38. package/dist/runtime/write-base.service.d.ts +68 -0
  39. package/dist/runtime/write-base.service.js +184 -0
  40. package/dist/sandbox/kernel-read.d.ts +39 -9
  41. package/dist/sandbox/kernel-read.js +33 -3
  42. package/dist/sandbox/operation-authority.d.ts +16 -12
  43. package/dist/sandbox/operation-authority.js +33 -20
  44. package/dist/sandbox/operation-intents.d.ts +10 -4
  45. package/dist/sandbox/operation-intents.js +31 -11
  46. package/dist/sandbox/sandbox.service.d.ts +30 -7
  47. package/dist/sandbox/sandbox.service.js +47 -13
  48. package/dist/tools/builtins/agent.js +4 -0
  49. package/dist/tools/builtins/image/generate.js +1 -0
  50. package/dist/tools/builtins/sandbox/bash.js +1 -0
  51. package/dist/tools/builtins/sandbox/edit.js +1 -0
  52. package/dist/tools/builtins/sandbox/write.js +1 -0
  53. package/dist/tools/builtins/send-message.js +1 -0
  54. package/dist/tools/info.d.ts +21 -2
  55. package/dist/tools/info.js +55 -12
  56. package/dist/tools/pipeline.d.ts +3 -1
  57. package/dist/tools/pipeline.js +37 -3
  58. package/dist/tools/registry.d.ts +6 -5
  59. package/dist/tools/registry.js +6 -5
  60. package/package.json +3 -3
  61. package/src/migrations/0185_channel_process_display.sql +13 -0
@@ -16,6 +16,7 @@ import { MediaCache } from "./media-cache.js";
16
16
  import { type PermissionContextFailureKind } from "./permission-context-errors.js";
17
17
  import { type BoundProvider, type ProviderRegistry } from "./providers.js";
18
18
  import type { StepLog } from "./step-log.js";
19
+ import { type WriteBaseReader } from "./write-base.js";
19
20
  /** 单轮收尾的尾部提醒(模型可见,英文;spec 6 轮次额度收尾)。 */
20
21
  export declare const WRAP_UP_REMINDER = "Step limit reached. Do not call tools. Summarize what you found and what remains for the user.";
21
22
  /**
@@ -48,13 +49,19 @@ export declare const contextTooLargeText: (model: ModelInfo, target: number, est
48
49
  * 流式增量的出口(推给前端等订阅方);`step_reset` 表示丢弃本步已推出的增量、重新开始。
49
50
  * `stream_end` (the step's model stream completed) and `step_end` (the step's `assistant_message`
50
51
  * is logged) carry no delta: the run worker's sink writes and then clears the step's live draft on
51
- * them (spec 2026-11-07 §3.2) and publishes neither.
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.
52
56
  */
53
57
  export type StreamSink = (delta: {
54
- kind: "text" | "thinking" | "step_reset" | "stream_end" | "step_end";
58
+ kind: "text" | "thinking" | "tool_start" | "tool_input" | "tool_base" | "step_reset" | "stream_end" | "step_end";
55
59
  runId: string;
56
60
  step: number;
57
61
  text?: string;
62
+ callId?: string;
63
+ name?: string;
64
+ sha256?: string;
58
65
  }) => void;
59
66
  export interface ModelStepDeps {
60
67
  db: KernelSchemaDb;
@@ -101,6 +108,16 @@ export interface ModelStepDeps {
101
108
  * install only the recorded feeder (`evals/recorded-permission-context.ts`).
102
109
  */
103
110
  permissionContext?: PermissionContextPort;
111
+ /**
112
+ * Reads the display-only base of a streaming `Write` (streaming tool input spec §4.1), published
113
+ * as `tool_base`. Only chat and sub-agent runs use it (never an eval replay); absent, no base.
114
+ */
115
+ writeBase?: WriteBaseReader;
116
+ /**
117
+ * How long an attempt waits for its aborted base reads (default `WRITE_BASE_SETTLE_MS`); tests
118
+ * shorten it.
119
+ */
120
+ writeBaseSettleMs?: number;
104
121
  }
105
122
  /** What the request boundary passes to {@link PermissionContextPort.beforeRequest}. */
106
123
  export type PermissionContextRequestInput = Pick<ModelStepInput, "orgId" | "conversationId" | "runId" | "step" | "signal"> & {
@@ -373,6 +390,10 @@ export interface CompactionOutcome {
373
390
  * manual compact run through `CompactionService.force`.
374
391
  */
375
392
  export declare function runCompaction(deps: ModelStepDeps, input: ModelStepInput, events: ConversationEvent[], runtime: Runtime, compaction: CompactionSettings, tools: StepTools, opts?: CompactOptions): Promise<CompactionOutcome>;
393
+ /** Characters one streamed delta carries, for the idle and size accounting of a stream. */
394
+ export declare function deltaChars(ev: Exclude<ModelStreamEvent, {
395
+ type: "message_complete";
396
+ }>): number;
376
397
  /**
377
398
  * 消费一次模型流,带空闲看门狗:两次事件之间超过 `idleMs` → 本地中止并按 `ModelError("timeout")` 抛出。
378
399
  * 外部 `signal` 触发 → `StepAborted`。每次 `next()` 都与停止信号竞速,供应商不响应 signal 也不会卡住。
@@ -18,6 +18,7 @@ import { PERMISSION_CONTEXT_RUN_ERRORS, permissionContextFailureKind, permission
18
18
  import { ProviderListError } from "./providers.js";
19
19
  import { ExecutionRevoked } from "./run-execution.js";
20
20
  import { budgetRunOf, subagentBudgetUsedUp } from "./subagents/limits.js";
21
+ import { writeBaseViewOf, writeBaseWatcher } from "./write-base.js";
21
22
  /** 单轮收尾的尾部提醒(模型可见,英文;spec 6 轮次额度收尾)。 */
22
23
  export const WRAP_UP_REMINDER = "Step limit reached. Do not call tools. Summarize what you found and what remains for the user.";
23
24
  /**
@@ -1392,15 +1393,35 @@ async function ladder(deps, input, events, runtime, compaction, tools, wrapUpRea
1392
1393
  ]);
1393
1394
  await deps.eventLog.notify(conversationId, Math.max(...written.map((e) => e.seq)));
1394
1395
  sentAt = Date.now();
1395
- const outcome = await consumeModelStream(provider, sentRequest, info.streamIdleTimeoutMs ?? runtime.streamIdleMs, signal, (ev) => {
1396
- if (ev.type === "text_delta") {
1397
- streamed.text += ev.text;
1398
- sink({ kind: "text", runId, step, text: ev.text });
1399
- }
1400
- else {
1401
- sink({ kind: "thinking", runId, step, text: ev.text });
1402
- }
1403
- });
1396
+ // this attempt's pending base reads end with its stream (a reset, the end, an abort)
1397
+ const baseStop = new AbortController();
1398
+ const bases = baseWatcher(deps, input, tools, baseStop.signal);
1399
+ let outcome;
1400
+ try {
1401
+ outcome = await consumeModelStream(provider, sentRequest, info.streamIdleTimeoutMs ?? runtime.streamIdleMs, signal, (ev) => {
1402
+ if (ev.type === "text_delta") {
1403
+ streamed.text += ev.text;
1404
+ sink({ kind: "text", runId, step, text: ev.text });
1405
+ }
1406
+ else if (ev.type === "thinking_delta") {
1407
+ sink({ kind: "thinking", runId, step, text: ev.text });
1408
+ }
1409
+ else if (ev.type === "tool_call_start") {
1410
+ sink({ kind: "tool_start", runId, step, callId: ev.id, name: ev.name });
1411
+ bases?.onStart(ev.id, ev.name);
1412
+ }
1413
+ else {
1414
+ sink({ kind: "tool_input", runId, step, callId: ev.id, text: ev.input });
1415
+ bases?.onInput(ev.id, ev.input);
1416
+ }
1417
+ });
1418
+ }
1419
+ finally {
1420
+ // the attempt's base reads end with it: aborted, then waited for (the abort reaches
1421
+ // the lease and provider waits, so this is short), at most WRITE_BASE_SETTLE_MS
1422
+ baseStop.abort();
1423
+ await bases?.settle();
1424
+ }
1404
1425
  // the draft's last write, before the assistant_message is logged
1405
1426
  sink({ kind: "stream_end", runId, step });
1406
1427
  if (scope && deps.hooks) {
@@ -1642,6 +1663,28 @@ function classify(err) {
1642
1663
  retryAfterMs: undefined,
1643
1664
  };
1644
1665
  }
1666
+ /**
1667
+ * The `Write` base watcher of one stream attempt (streaming tool input spec §4.1), or none: only a
1668
+ * chat or sub-agent run with a reader gets one (an eval replay never reads a device). Its reads
1669
+ * stop when `stop` fires or the run aborts; a base found in time goes out as `tool_base`.
1670
+ */
1671
+ function baseWatcher(deps, input, tools, stop) {
1672
+ const reader = deps.writeBase;
1673
+ const kind = input.conversationKind;
1674
+ if (reader === undefined || (kind !== "chat" && kind !== "subagent"))
1675
+ return undefined;
1676
+ const { conversationId, runId, step, sink } = input;
1677
+ return writeBaseWatcher({
1678
+ reader,
1679
+ // the resolved tools carry their source (`ResolvedTool`): only the builtin Write reads
1680
+ inputViewOf: (name) => writeBaseViewOf(tools.list, name),
1681
+ emit: (callId, base) => sink({ kind: "tool_base", runId, step, callId, text: base.text, sha256: base.sha256 }),
1682
+ conversationId,
1683
+ signal: AbortSignal.any([input.signal, stop]),
1684
+ log: deps.log,
1685
+ ...(deps.writeBaseSettleMs !== undefined && { settleMs: deps.writeBaseSettleMs }),
1686
+ });
1687
+ }
1645
1688
  /** 可被中止的等待(本进程发起的模型调用自己的计时器,结束即清除);中止 → StepAborted。 */
1646
1689
  function abortableSleep(ms, signal) {
1647
1690
  return new Promise((resolve, reject) => {
@@ -1658,6 +1701,18 @@ function abortableSleep(ms, signal) {
1658
1701
  signal.addEventListener("abort", onAbort, { once: true });
1659
1702
  });
1660
1703
  }
1704
+ /** Characters one streamed delta carries, for the idle and size accounting of a stream. */
1705
+ export function deltaChars(ev) {
1706
+ switch (ev.type) {
1707
+ case "text_delta":
1708
+ case "thinking_delta":
1709
+ return ev.text.length;
1710
+ case "tool_call_delta":
1711
+ return ev.input.length;
1712
+ case "tool_call_start":
1713
+ return 0;
1714
+ }
1715
+ }
1661
1716
  /**
1662
1717
  * 消费一次模型流,带空闲看门狗:两次事件之间超过 `idleMs` → 本地中止并按 `ModelError("timeout")` 抛出。
1663
1718
  * 外部 `signal` 触发 → `StepAborted`。每次 `next()` 都与停止信号竞速,供应商不响应 signal 也不会卡住。
@@ -7,13 +7,33 @@ import { type StreamSink } from "./model-call.js";
7
7
  export declare const DRAFT_TTL_SECONDS = 600;
8
8
  /** At most one write per step per window, plus the one at the end of the model stream. */
9
9
  export declare const DRAFT_FLUSH_MS = 200;
10
- /** One step's draft: `{ text, thinking }` as JSON (spec 2026-11-07 §3.2). */
10
+ /**
11
+ * UTF-8 bytes of tool input plus bases one step's draft keeps (streaming tool input spec §4); past
12
+ * it a call is marked `inputTruncated` and its later fragments are only published.
13
+ */
14
+ export declare const DRAFT_TOOL_INPUT_MAX: number;
15
+ /** One step's draft: `{ text, thinking, tools }` as JSON (spec 2026-11-07 §3.2). */
11
16
  export declare const draftKey: (runId: string, step: number) => string;
17
+ /** A tool call a step streams (display only: the logged `assistant_message` is what runs). */
18
+ export interface DraftTool {
19
+ id: string;
20
+ name: string;
21
+ /** The head of the call's JSON input as streamed (not parseable until it is complete). */
22
+ input: string;
23
+ /** The step's {@link DRAFT_TOOL_INPUT_MAX} was reached: later fragments are not in the draft. */
24
+ inputTruncated?: true;
25
+ /** The file a streaming `Write` replaces (streaming tool input spec §4.1). */
26
+ base?: {
27
+ text: string;
28
+ sha256: string;
29
+ };
30
+ }
12
31
  /** What one step of a run has streamed so far. */
13
32
  export interface RunDraft {
14
33
  step: number;
15
34
  text: string;
16
35
  thinking: string;
36
+ tools: DraftTool[];
17
37
  }
18
38
  /** A draft of a conversation's active run (the `event: draft` frame's data). */
19
39
  export interface LiveDraft extends RunDraft {
@@ -45,6 +65,26 @@ export declare class RunDrafts {
45
65
  private get db();
46
66
  /** Adds a delta to the step's draft; writes it when the last write is a window old. */
47
67
  append(runId: string, step: number, channel: "text" | "thinking", text: string): void;
68
+ /** A tool call the step starts streaming (a call id seen again keeps what it has). */
69
+ startTool(runId: string, step: number, callId: string, name: string): void;
70
+ /**
71
+ * Adds a fragment of a call's input. Past {@link DRAFT_TOOL_INPUT_MAX} for the step the call is
72
+ * marked `inputTruncated` and keeps its head: later fragments are only published.
73
+ */
74
+ appendToolInput(runId: string, step: number, callId: string, text: string): void;
75
+ /**
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.
79
+ */
80
+ setToolBase(runId: string, step: number, callId: string, base: {
81
+ text: string;
82
+ sha256: string;
83
+ }): void;
84
+ /** The step's held draft, a fresh one when the run moved to another step. */
85
+ private heldFor;
86
+ /** The held draft changed: written now when the last write is a window old, else held. */
87
+ private changed;
48
88
  /** The end of the step's model stream: writes what the window still holds. */
49
89
  flush(runId: string, step: number): void;
50
90
  /** Deletes the step's draft (its `assistant_message` is logged, or the step starts over). */
@@ -71,15 +111,17 @@ export declare class RunDrafts {
71
111
  /** What {@link streamSink} uses. */
72
112
  export interface StreamSinkDeps {
73
113
  bus: Pick<ExtensionContext["bus"], "publish">;
74
- drafts: Pick<RunDrafts, "append" | "flush" | "clear">;
114
+ drafts: Pick<RunDrafts, "append" | "flush" | "clear" | "startTool" | "appendToolInput" | "setToolBase">;
75
115
  log: Pick<Logger, "warn">;
76
116
  }
77
117
  /**
78
118
  * The run's stream sink (one per execution of a run): publishes deltas on the conversation's topic
79
119
  * (`conv.<id>`, shared with `{ kind: "events" }`, so a subscriber on any replica gets them) with
80
120
  * `offset`, the characters of that channel (text or thinking) this attempt of the step streamed
81
- * before the delta, and keeps the step's live draft. `step_reset` clears the draft and both
82
- * offsets; `stream_end` / `step_end` only flush / clear the draft and are not published. A failed
121
+ * 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
123
+ * call's input this attempt streamed before the delta. `step_reset` clears the draft and every
124
+ * offset; `stream_end` / `step_end` only flush / clear the draft and are not published. A failed
83
125
  * publish is only logged: deltas are drafts, the `assistant_message` in the log is the truth.
84
126
  */
85
127
  export declare function streamSink(conversationId: string, deps: StreamSinkDeps): StreamSink;
@@ -16,10 +16,32 @@ import { assistantIdemKey } from "./model-call.js";
16
16
  export const DRAFT_TTL_SECONDS = 600;
17
17
  /** At most one write per step per window, plus the one at the end of the model stream. */
18
18
  export const DRAFT_FLUSH_MS = 200;
19
- /** One step's draft: `{ text, thinking }` as JSON (spec 2026-11-07 §3.2). */
19
+ /**
20
+ * UTF-8 bytes of tool input plus bases one step's draft keeps (streaming tool input spec §4); past
21
+ * it a call is marked `inputTruncated` and its later fragments are only published.
22
+ */
23
+ export const DRAFT_TOOL_INPUT_MAX = 512 * 1024;
24
+ /** One step's draft: `{ text, thinking, tools }` as JSON (spec 2026-11-07 §3.2). */
20
25
  export const draftKey = (runId, step) => `capk:run-draft:${runId}:${step}`;
21
26
  /** The steps of a run that have a draft (a set, so a reader finds them without a key scan). */
22
27
  const stepsKey = (runId) => `capk:run-draft-steps:${runId}`;
28
+ const isRecord = (x) => typeof x === "object" && x !== null && !Array.isArray(x);
29
+ const parseTool = (x) => {
30
+ if (!isRecord(x) || typeof x.id !== "string" || typeof x.name !== "string")
31
+ return [];
32
+ const t = {
33
+ id: x.id,
34
+ name: x.name,
35
+ input: typeof x.input === "string" ? x.input : "",
36
+ };
37
+ if (x.inputTruncated === true)
38
+ t.inputTruncated = true;
39
+ const b = x.base;
40
+ if (isRecord(b) && typeof b.text === "string" && typeof b.sha256 === "string") {
41
+ t.base = { text: b.text, sha256: b.sha256 };
42
+ }
43
+ return [t];
44
+ };
23
45
  const parse = (step, v) => {
24
46
  if (v === null)
25
47
  return null;
@@ -29,6 +51,7 @@ const parse = (step, v) => {
29
51
  step,
30
52
  text: typeof d.text === "string" ? d.text : "",
31
53
  thinking: typeof d.thinking === "string" ? d.thinking : "",
54
+ tools: Array.isArray(d.tools) ? d.tools.flatMap(parseTool) : [],
32
55
  };
33
56
  }
34
57
  catch {
@@ -68,6 +91,55 @@ let RunDrafts = class RunDrafts {
68
91
  }
69
92
  /** Adds a delta to the step's draft; writes it when the last write is a window old. */
70
93
  append(runId, step, channel, text) {
94
+ const h = this.heldFor(runId, step);
95
+ h[channel] += text;
96
+ this.changed(runId, h);
97
+ }
98
+ /** A tool call the step starts streaming (a call id seen again keeps what it has). */
99
+ startTool(runId, step, callId, name) {
100
+ const h = this.heldFor(runId, step);
101
+ if (h.tools.some((t) => t.id === callId))
102
+ return;
103
+ h.tools.push({ id: callId, name, input: "" });
104
+ this.changed(runId, h);
105
+ }
106
+ /**
107
+ * Adds a fragment of a call's input. Past {@link DRAFT_TOOL_INPUT_MAX} for the step the call is
108
+ * marked `inputTruncated` and keeps its head: later fragments are only published.
109
+ */
110
+ appendToolInput(runId, step, callId, text) {
111
+ const h = this.heldFor(runId, step);
112
+ const t = h.tools.find((x) => x.id === callId);
113
+ if (t === undefined || t.inputTruncated)
114
+ return;
115
+ const bytes = Buffer.byteLength(text);
116
+ if (h.toolBytes + bytes > DRAFT_TOOL_INPUT_MAX)
117
+ t.inputTruncated = true;
118
+ else {
119
+ t.input += text;
120
+ h.toolBytes += bytes;
121
+ }
122
+ this.changed(runId, h);
123
+ }
124
+ /**
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.
128
+ */
129
+ setToolBase(runId, step, callId, base) {
130
+ const h = this.heldFor(runId, step);
131
+ const t = h.tools.find((x) => x.id === callId);
132
+ if (t === undefined || t.base !== undefined)
133
+ return;
134
+ const bytes = Buffer.byteLength(base.text);
135
+ if (h.toolBytes + bytes > DRAFT_TOOL_INPUT_MAX)
136
+ return;
137
+ t.base = { text: base.text, sha256: base.sha256 };
138
+ h.toolBytes += bytes;
139
+ this.changed(runId, h);
140
+ }
141
+ /** The step's held draft, a fresh one when the run moved to another step. */
142
+ heldFor(runId, step) {
71
143
  let h = this.held.get(runId);
72
144
  if (h?.step !== step) {
73
145
  if (h)
@@ -76,13 +148,19 @@ let RunDrafts = class RunDrafts {
76
148
  step,
77
149
  text: "",
78
150
  thinking: "",
151
+ tools: [],
152
+ toolBytes: 0,
79
153
  writtenAt: Number.NEGATIVE_INFINITY,
80
154
  dirty: false,
81
155
  timer: undefined,
82
156
  };
83
157
  this.held.set(runId, h);
84
158
  }
85
- h[channel] += text;
159
+ return h;
160
+ }
161
+ /** The held draft changed: written now when the last write is a window old, else held. */
162
+ changed(runId, h) {
163
+ const { step } = h;
86
164
  h.dirty = true;
87
165
  const elapsed = Date.now() - h.writtenAt;
88
166
  if (elapsed >= DRAFT_FLUSH_MS)
@@ -180,7 +258,7 @@ let RunDrafts = class RunDrafts {
180
258
  const { step } = h;
181
259
  this.redis
182
260
  .multi()
183
- .set(draftKey(runId, step), JSON.stringify({ text: h.text, thinking: h.thinking }), "EX", DRAFT_TTL_SECONDS)
261
+ .set(draftKey(runId, step), JSON.stringify({ text: h.text, thinking: h.thinking, tools: h.tools }), "EX", DRAFT_TTL_SECONDS)
184
262
  .sadd(stepsKey(runId), String(step))
185
263
  .expire(stepsKey(runId), DRAFT_TTL_SECONDS)
186
264
  .exec()
@@ -199,12 +277,14 @@ export { RunDrafts };
199
277
  * The run's stream sink (one per execution of a run): publishes deltas on the conversation's topic
200
278
  * (`conv.<id>`, shared with `{ kind: "events" }`, so a subscriber on any replica gets them) with
201
279
  * `offset`, the characters of that channel (text or thinking) this attempt of the step streamed
202
- * before the delta, and keeps the step's live draft. `step_reset` clears the draft and both
203
- * offsets; `stream_end` / `step_end` only flush / clear the draft and are not published. A failed
280
+ * 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
282
+ * call's input this attempt streamed before the delta. `step_reset` clears the draft and every
283
+ * offset; `stream_end` / `step_end` only flush / clear the draft and are not published. A failed
204
284
  * publish is only logged: deltas are drafts, the `assistant_message` in the log is the truth.
205
285
  */
206
286
  export function streamSink(conversationId, deps) {
207
- let at = { runId: "", step: -1, text: 0, thinking: 0 };
287
+ let at = { runId: "", step: -1, text: 0, thinking: 0, tools: new Map() };
208
288
  const publish = (msg) => deps.bus
209
289
  .publish(conversationTopic(conversationId), msg)
210
290
  .catch((err) => deps.log.warn("stream delta publish failed", { conversationId, err }));
@@ -214,17 +294,38 @@ export function streamSink(conversationId, deps) {
214
294
  if (d.kind === "step_end")
215
295
  return deps.drafts.clear(d.runId, d.step);
216
296
  if (at.runId !== d.runId || at.step !== d.step || d.kind === "step_reset") {
217
- at = { runId: d.runId, step: d.step, text: 0, thinking: 0 };
297
+ at = { runId: d.runId, step: d.step, text: 0, thinking: 0, tools: new Map() };
218
298
  }
219
299
  if (d.kind === "step_reset") {
220
300
  deps.drafts.clear(d.runId, d.step);
221
301
  void publish({ kind: "delta", runId: d.runId, step: d.step, delta: "step_reset" });
222
302
  return;
223
303
  }
304
+ const { runId, step } = d;
224
305
  const text = d.text ?? "";
306
+ if (d.kind === "tool_start" || d.kind === "tool_input" || d.kind === "tool_base") {
307
+ const callId = d.callId ?? "";
308
+ if (d.kind === "tool_start") {
309
+ const name = d.name ?? "";
310
+ deps.drafts.startTool(runId, step, callId, name);
311
+ void publish({ kind: "delta", runId, step, delta: "tool_start", callId, name });
312
+ }
313
+ else if (d.kind === "tool_input") {
314
+ const offset = at.tools.get(callId) ?? 0;
315
+ at.tools.set(callId, offset + text.length);
316
+ deps.drafts.appendToolInput(runId, step, callId, text);
317
+ void publish({ kind: "delta", runId, step, delta: "tool_input", callId, text, offset });
318
+ }
319
+ else {
320
+ 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 });
323
+ }
324
+ return;
325
+ }
225
326
  const offset = at[d.kind];
226
327
  at[d.kind] += text.length;
227
- deps.drafts.append(d.runId, d.step, d.kind, text);
228
- void publish({ kind: "delta", runId: d.runId, step: d.step, delta: d.kind, text, offset });
328
+ deps.drafts.append(runId, step, d.kind, text);
329
+ void publish({ kind: "delta", runId, step, delta: d.kind, text, offset });
229
330
  };
230
331
  }
@@ -15,6 +15,7 @@ import { PermissionContextRecorder } from "./permission-context.service.js";
15
15
  import { ProviderRegistry } from "./providers.js";
16
16
  import { StepLog } from "./step-log.js";
17
17
  import { SubagentsService } from "./subagents/subagents.service.js";
18
+ import { WriteBaseService } from "./write-base.service.js";
18
19
  /**
19
20
  * Builds the agent loop a run executes (default {@link LangGraphLoop}: its checkpoints live in the
20
21
  * kernel's {@link KyselyCheckpointSaver}, so another replica resumes a crashed worker's run).
@@ -37,7 +38,7 @@ export declare class AgentLoops {
37
38
  */
38
39
  export declare class RunSteps {
39
40
  readonly deps: LoopDeps;
40
- constructor(kdb: KernelDb, eventLog: EventLog, stepLog: StepLog, registry: ProviderRegistry, tools: ToolRegistry, config: KernelConfigService, log: KernelLogger, toolPipeline: ToolPipeline, host: ExtensionHost, subagents: SubagentsService, attachments: AttachmentsService, compactionSettings: CompactionSettingsService, compactionProgress: CompactionProgressService, permissionContext: PermissionContextRecorder);
41
+ constructor(kdb: KernelDb, eventLog: EventLog, stepLog: StepLog, registry: ProviderRegistry, tools: ToolRegistry, config: KernelConfigService, log: KernelLogger, toolPipeline: ToolPipeline, host: ExtensionHost, subagents: SubagentsService, attachments: AttachmentsService, compactionSettings: CompactionSettingsService, compactionProgress: CompactionProgressService, permissionContext: PermissionContextRecorder, writeBase: WriteBaseService);
41
42
  }
42
43
  /**
43
44
  * The live request boundary of a run's steps (spec B2): every agent-history request construction
@@ -24,6 +24,7 @@ import { PermissionContextRecorder } from "./permission-context.service.js";
24
24
  import { ProviderRegistry } from "./providers.js";
25
25
  import { StepLog } from "./step-log.js";
26
26
  import { SubagentsService } from "./subagents/subagents.service.js";
27
+ import { WriteBaseService } from "./write-base.service.js";
27
28
  /** Optional provider: the {@link AgentLoopFactory} runs use instead of the default (tests). */
28
29
  export const AGENT_LOOP_FACTORY = Symbol("AGENT_LOOP_FACTORY");
29
30
  /** The agent loops of chat runs and of eval full-run replays (one factory, one checkpoint store). */
@@ -54,7 +55,7 @@ export { AgentLoops };
54
55
  */
55
56
  let RunSteps = class RunSteps {
56
57
  deps;
57
- constructor(kdb, eventLog, stepLog, registry, tools, config, log, toolPipeline, host, subagents, attachments, compactionSettings, compactionProgress, permissionContext) {
58
+ constructor(kdb, eventLog, stepLog, registry, tools, config, log, toolPipeline, host, subagents, attachments, compactionSettings, compactionProgress, permissionContext, writeBase) {
58
59
  this.deps = {
59
60
  get db() {
60
61
  return kdb.db;
@@ -81,6 +82,8 @@ let RunSteps = class RunSteps {
81
82
  },
82
83
  // the request boundary of the recorded permission context (spec B2)
83
84
  ...livePermissionContext(permissionContext),
85
+ // the display-only base of a streaming Write (streaming tool input spec §4.1)
86
+ writeBase,
84
87
  };
85
88
  }
86
89
  };
@@ -99,7 +102,8 @@ RunSteps = __decorate([
99
102
  __param(10, Inject(AttachmentsService)),
100
103
  __param(11, Inject(CompactionSettingsService)),
101
104
  __param(12, Inject(CompactionProgressService)),
102
- __param(13, Inject(PermissionContextRecorder))
105
+ __param(13, Inject(PermissionContextRecorder)),
106
+ __param(14, Inject(WriteBaseService))
103
107
  ], RunSteps);
104
108
  export { RunSteps };
105
109
  /**
@@ -54,6 +54,7 @@ import { ConversationStreams } from "./stream.js";
54
54
  import { SubagentsModule } from "./subagents/subagents.service.js";
55
55
  import { UsageReportModule } from "./usage-report.js";
56
56
  import { Waits } from "./waits.js";
57
+ import { WriteBaseService } from "./write-base.service.js";
57
58
  /**
58
59
  * The run runtime: the conversation run lock, this process's event streams, the run queue and its
59
60
  * worker (consumed through `RuntimeWorkersModule`'s processors), the waits (a run nobody runs is
@@ -116,6 +117,8 @@ RuntimeModule = __decorate([
116
117
  PermissionContextRecorder,
117
118
  PluginContextService,
118
119
  ProjectKnowledgeService,
120
+ // the display-only base of a streaming Write (streaming tool input spec §4.1)
121
+ WriteBaseService,
119
122
  RunWorker,
120
123
  // the org's effective compaction settings, one read per model step
121
124
  CompactionSettingsService,
@@ -19,8 +19,9 @@ declare const DraftParams: z.ZodObject<{
19
19
  * 会话事件流(SSE):`GET /api/v1/orgs/:orgId/conversations/:id/stream?after=<seq>`,`agents.use`,只有会话所有者可用。
20
20
  * - opening it never changes run state (a read; transactional outbox spec §6);
21
21
  * - 先订阅会话频道、再回放 `after`(或优先的 `Last-Event-ID`)之后的事件:`id: <seq>` / `event: event`;
22
- * - after that catch-up, one `event: draft` (`data: {"runId","step","text","thinking"}`) per step of
23
- * the running run whose `assistant_message` is not logged (live drafts, spec 2026-11-07 §3.2);
22
+ * - after that catch-up, one `event: draft` (`data: {"runId","step","text","thinking","tools"}`)
23
+ * per step of the running run whose `assistant_message` is not logged (live drafts, spec
24
+ * 2026-11-07 §3.2);
24
25
  * 之后收到 `events` 通知就补读新事件(按 seq 去重),收到增量就发 `event: delta`,收到界面刷新
25
26
  * (插件 `ctx.ui.invalidate`)就发 `event: ui`(`data: {"plugin","contribution"}`);
26
27
  * - 每 `runtime.sseHeartbeatMs` 发 `: ping` 注释;每 `runtime.sseRecheckMs` 复核凭据(会话未吊销 / 令牌仍有效,
@@ -37,9 +38,10 @@ export declare class ConversationStreamController {
37
38
  private readonly log;
38
39
  constructor(streams: ConversationStreams, sessions: SessionService, tokens: ApiTokenService, access: ConversationAccess, drafts: RunDrafts, log: Pick<Logger, "warn">);
39
40
  /**
40
- * The live drafts of one run (spec 2026-11-07 §3.2): `{ drafts: { step, text, thinking }[] }`,
41
- * the steps still streaming whose `assistant_message` is not logged (none once the run is no
42
- * longer running). What a stream client asks for when a delta's `offset` is past its draft.
41
+ * The live drafts of one run (spec 2026-11-07 §3.2):
42
+ * `{ drafts: { step, text, thinking, tools }[] }`, the steps still streaming whose
43
+ * `assistant_message` is not logged (none once the run is no longer running). What a stream
44
+ * client asks for when a delta's `offset` is past its draft.
43
45
  * The stream's access rule (the conversation is visible to the viewer, else 404
44
46
  * `conversation.not_found`); a run not of this conversation → 404 `run.not_found`.
45
47
  */
@@ -46,8 +46,9 @@ class RunDraftParamsDto extends createZodDto(DraftParams, "RunDraftParams") {
46
46
  * 会话事件流(SSE):`GET /api/v1/orgs/:orgId/conversations/:id/stream?after=<seq>`,`agents.use`,只有会话所有者可用。
47
47
  * - opening it never changes run state (a read; transactional outbox spec §6);
48
48
  * - 先订阅会话频道、再回放 `after`(或优先的 `Last-Event-ID`)之后的事件:`id: <seq>` / `event: event`;
49
- * - after that catch-up, one `event: draft` (`data: {"runId","step","text","thinking"}`) per step of
50
- * the running run whose `assistant_message` is not logged (live drafts, spec 2026-11-07 §3.2);
49
+ * - after that catch-up, one `event: draft` (`data: {"runId","step","text","thinking","tools"}`)
50
+ * per step of the running run whose `assistant_message` is not logged (live drafts, spec
51
+ * 2026-11-07 §3.2);
51
52
  * 之后收到 `events` 通知就补读新事件(按 seq 去重),收到增量就发 `event: delta`,收到界面刷新
52
53
  * (插件 `ctx.ui.invalidate`)就发 `event: ui`(`data: {"plugin","contribution"}`);
53
54
  * - 每 `runtime.sseHeartbeatMs` 发 `: ping` 注释;每 `runtime.sseRecheckMs` 复核凭据(会话未吊销 / 令牌仍有效,
@@ -71,9 +72,10 @@ let ConversationStreamController = class ConversationStreamController {
71
72
  this.log = log;
72
73
  }
73
74
  /**
74
- * The live drafts of one run (spec 2026-11-07 §3.2): `{ drafts: { step, text, thinking }[] }`,
75
- * the steps still streaming whose `assistant_message` is not logged (none once the run is no
76
- * longer running). What a stream client asks for when a delta's `offset` is past its draft.
75
+ * The live drafts of one run (spec 2026-11-07 §3.2):
76
+ * `{ drafts: { step, text, thinking, tools }[] }`, the steps still streaming whose
77
+ * `assistant_message` is not logged (none once the run is no longer running). What a stream
78
+ * client asks for when a delta's `offset` is past its draft.
77
79
  * The stream's access rule (the conversation is visible to the viewer, else 404
78
80
  * `conversation.not_found`); a run not of this conversation → 404 `run.not_found`.
79
81
  */
@@ -98,7 +100,9 @@ let ConversationStreamController = class ConversationStreamController {
98
100
  });
99
101
  live = [];
100
102
  }
101
- return { drafts: live.map(({ step, text, thinking }) => ({ step, text, thinking })) };
103
+ return {
104
+ drafts: live.map(({ step, text, thinking, tools }) => ({ step, text, thinking, tools })),
105
+ };
102
106
  }
103
107
  async stream(principal, org, id, q, lastEventId, req, reply) {
104
108
  const p = requireUser(principal);
@@ -74,7 +74,15 @@ function isBusMessage(m) {
74
74
  return k === "delta" && typeof m.runId === "string";
75
75
  }
76
76
  const eventFrame = (e) => `id: ${e.seq}\nevent: event\ndata: ${JSON.stringify(e)}\n\n`;
77
- const draftFrame = (d) => `event: draft\ndata: ${JSON.stringify({ runId: d.runId, step: d.step, text: d.text, thinking: d.thinking })}\n\n`;
77
+ /** The `event: draft` frame's data: the live draft as the client reads it. */
78
+ const draftData = (d) => ({
79
+ runId: d.runId,
80
+ step: d.step,
81
+ text: d.text,
82
+ thinking: d.thinking,
83
+ tools: d.tools,
84
+ });
85
+ const draftFrame = (d) => `event: draft\ndata: ${JSON.stringify(draftData(d))}\n\n`;
78
86
  const suggestionFrame = (s) => `event: suggestion\ndata: ${JSON.stringify({ runId: s.runId, afterSeq: s.afterSeq, text: s.text })}\n\n`;
79
87
  /**
80
88
  * 会话事件流(SSE):本进程持有的连接集合,停机时一并关闭。