@capybara-hq/kernel 0.1.0-rc.29 → 0.1.0-rc.30

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 (62) hide show
  1. package/bootstrap.json +27 -27
  2. package/dist/admin/admin.schemas.d.ts +7 -0
  3. package/dist/config/schema.d.ts +0 -2
  4. package/dist/config/schema.js +0 -16
  5. package/dist/conversations/conversations.controller.d.ts +11 -1
  6. package/dist/conversations/conversations.controller.js +25 -1
  7. package/dist/conversations/conversations.schemas.d.ts +8 -0
  8. package/dist/conversations/conversations.schemas.js +14 -0
  9. package/dist/conversations/conversations.service.d.ts +12 -0
  10. package/dist/conversations/conversations.service.js +10 -0
  11. package/dist/conversations/event-log.d.ts +14 -0
  12. package/dist/conversations/events.d.ts +12 -0
  13. package/dist/conversations/events.js +35 -3
  14. package/dist/db/kernel-schema.d.ts +5 -0
  15. package/dist/errors.d.ts +3 -0
  16. package/dist/errors.js +3 -0
  17. package/dist/evals/plan.d.ts +20 -15
  18. package/dist/evals/plan.js +29 -6
  19. package/dist/evals/reconstruct.d.ts +16 -1
  20. package/dist/evals/reconstruct.js +55 -1
  21. package/dist/evals/sets.service.d.ts +3 -2
  22. package/dist/evals/sets.service.js +16 -2
  23. package/dist/evals/step-replay.d.ts +6 -0
  24. package/dist/evals/step-replay.js +5 -0
  25. package/dist/evals/trajectory.d.ts +5 -1
  26. package/dist/evals/trajectory.js +3 -1
  27. package/dist/evals/worker.js +2 -1
  28. package/dist/identity/settings.d.ts +64 -0
  29. package/dist/identity/settings.js +86 -2
  30. package/dist/orgs/roles.d.ts +1 -1
  31. package/dist/orgs/roles.js +2 -0
  32. package/dist/orgs/settings.service.d.ts +17 -0
  33. package/dist/orgs/settings.service.js +31 -3
  34. package/dist/platform/ops/admin.ops.js +8 -2
  35. package/dist/platform/ops/conversations.ops.js +34 -0
  36. package/dist/platform/ops/evals.ops.js +12 -1
  37. package/dist/platform/ops/orgs.ops.js +1 -0
  38. package/dist/runtime/compaction-progress.d.ts +62 -0
  39. package/dist/runtime/compaction-progress.js +82 -0
  40. package/dist/runtime/compaction-settings.service.d.ts +16 -0
  41. package/dist/runtime/compaction-settings.service.js +42 -0
  42. package/dist/runtime/compaction.service.d.ts +50 -0
  43. package/dist/runtime/compaction.service.js +75 -0
  44. package/dist/runtime/context/compaction.d.ts +90 -12
  45. package/dist/runtime/context/compaction.js +256 -21
  46. package/dist/runtime/context/fit.d.ts +79 -0
  47. package/dist/runtime/context/fit.js +202 -0
  48. package/dist/runtime/model-call.d.ts +134 -5
  49. package/dist/runtime/model-call.js +766 -335
  50. package/dist/runtime/run-control.d.ts +6 -1
  51. package/dist/runtime/run-control.js +7 -0
  52. package/dist/runtime/run-queue.d.ts +14 -0
  53. package/dist/runtime/run-queue.js +75 -0
  54. package/dist/runtime/run-steps.d.ts +3 -1
  55. package/dist/runtime/run-steps.js +9 -2
  56. package/dist/runtime/run-worker.d.ts +14 -2
  57. package/dist/runtime/run-worker.js +160 -33
  58. package/dist/runtime/runtime.module.js +11 -0
  59. package/dist/runtime/stream.js +15 -0
  60. package/dist/tools/pipeline.js +6 -3
  61. package/package.json +1 -1
  62. package/src/migrations/0132_compact_runs.sql +6 -0
@@ -1,11 +1,15 @@
1
- import { type ContentBlock, type ConversationSource, type Logger, type ModelRequest, type ModelStreamEvent, type ModelUsage, type StopReason } from "@capybara-hq/plugin-sdk";
2
- import type { AgentDefinition } from "../agents/definition.js";
1
+ import { type ContentBlock, type ConversationSource, type Logger, type ModelInfo, type ModelRequest, type ModelStreamEvent, type ModelUsage, type StopReason } from "@capybara-hq/plugin-sdk";
2
+ import type { AgentDefinition, ModelRef } from "../agents/definition.js";
3
+ import type { KernelConfig } from "../config/schema.js";
3
4
  import type { AppendEvent, EventLog } from "../conversations/event-log.js";
4
5
  import { type ConversationEvent } from "../conversations/events.js";
5
6
  import type { KernelSchemaDb } from "../db/kernel-schema.js";
6
7
  import type { KernelConfigService } from "../infra/config/kernel-config.service.js";
7
8
  import type { ToolRegistry, UnavailableTool } from "../tools/registry.js";
9
+ import type { CompactionProgressSink } from "./compaction-progress.js";
10
+ import type { CompactionSettings, CompactionSettingsService } from "./compaction-settings.service.js";
8
11
  import { type BuildModelRequestInput, type MediaBytes, type MediaInfo, type ModelCallMeta, type RequestTool } from "./context/build.js";
12
+ import { type FitPlan } from "./context/fit.js";
9
13
  import { type ConversationKindForHooks, type HookRunner } from "./hook-calls.js";
10
14
  import type { SubagentParent } from "./loop.js";
11
15
  import { MediaCache } from "./media-cache.js";
@@ -32,6 +36,13 @@ export declare function toolsUnavailableReminder(unavailable: readonly Unavailab
32
36
  * also the message of the `model.hook_denied` error a denied `ctx.models.embed` call rejects with.
33
37
  */
34
38
  export declare const modelDeniedText: (plugin: string, reason: string) => string;
39
+ /**
40
+ * The `run.context_too_large` message (user-facing, not model-visible): the hard fit guard could
41
+ * not bring the request under `W - O - R` even after dropping all older history and truncating the
42
+ * latest turn, so the system prompt, tools and the latest message are themselves too large
43
+ * (context compaction spec §4.3 point 4).
44
+ */
45
+ export declare const contextTooLargeText: (model: ModelInfo, target: number, estimate: number) => string;
35
46
  /**
36
47
  * 流式增量的出口(推给前端等订阅方);`step_reset` 表示丢弃本步已推出的增量、重新开始。
37
48
  * `stream_end` (the step's model stream completed) and `step_end` (the step's `assistant_message`
@@ -56,6 +67,16 @@ export interface ModelStepDeps {
56
67
  /** 工具注册表:每步开始时解析 agent 引用的工具(状态可能在步骤之间变化)。 */
57
68
  tools: Pick<ToolRegistry, "forAgent">;
58
69
  config: Pick<KernelConfigService, "get">;
70
+ /**
71
+ * The compaction settings in effect for the run's organization (context compaction spec §4.8):
72
+ * resolved once per model step.
73
+ */
74
+ compactionSettings: Pick<CompactionSettingsService, "resolve">;
75
+ /**
76
+ * Ephemeral compaction progress (context compaction spec §4.6): display-only, never in the log.
77
+ * Absent in eval replays and single-step replays, which have no live conversation to show it on.
78
+ */
79
+ compactionProgress?: CompactionProgressSink;
59
80
  log: Logger;
60
81
  /**
61
82
  * 会话附件(构建请求时解析日志里的媒体引用;见 AttachmentsService)。未提供时媒体引用一律按「不再可用」处理。
@@ -155,14 +176,66 @@ export declare class RunError extends Error {
155
176
  export declare const assistantIdemKey: (runId: string, step: number) => string;
156
177
  /** 某步第 attempt 次模型调用的 model_call 幂等键(管线据此找到模型实际收到的工具)。 */
157
178
  export declare const modelCallIdemKey: (runId: string, step: number, attempt: number) => string;
158
- /** 一步最多的模型调用尝试次数(主模型、同模型重试、兜底,见 `ladder`)。 */
179
+ /**
180
+ * The ladder's three rungs: the main model, one same-model retry and the fallback (see `ladder`).
181
+ * A step may make more calls than this: reactive `model.context_overflow` fix-ups retry on the same
182
+ * rung, all within {@link MAX_STEP_MODEL_CALLS}.
183
+ */
159
184
  export declare const MAX_MODEL_ATTEMPTS = 3;
185
+ /**
186
+ * The most `model_call` rows one step may write (context compaction spec §4.4): the ladder's three
187
+ * rungs plus up to two reactive-overflow fix-up retries. The ladder stops before a further attempt,
188
+ * so a persistent `model.context_overflow` cannot loop.
189
+ */
190
+ export declare const MAX_STEP_MODEL_CALLS: number;
191
+ /**
192
+ * The progressively smaller fit targets of a reactive trim, as fractions of the model's window
193
+ * (context compaction spec §4.3 point 5 / §4.4 point 3). The trim fix-up tries them most
194
+ * aggressive first (70%, then 80%, then 90% of the window) and uses the first target a fit plan
195
+ * actually reaches, so the retry really shrinks a request the provider rejected. `null` when the
196
+ * request already fits every target (nothing to trim).
197
+ */
198
+ export declare const REACTIVE_TRIM_FACTORS: readonly [0.9, 0.8, 0.7];
199
+ /** 本步解析出的工具与是否启用 ToolSearch(见 `ToolRegistry.forAgent`),以及本步已取的附件字节。 */
200
+ export interface StepTools {
201
+ list: RequestTool[];
202
+ toolSearch: boolean;
203
+ /** 本步已取到的附件信息与字节;同一步的多次构建(压缩估算、各次尝试)共用。只缓存成功的结果。 */
204
+ media: StepMedia;
205
+ }
206
+ /** What `ToolRegistry.forAgent` resolved for one request: the tools, ToolSearch and unavailable ones. */
207
+ export interface ResolvedAgentTools {
208
+ tools: RequestTool[];
209
+ toolSearch: boolean;
210
+ unavailable: UnavailableTool[];
211
+ }
212
+ /**
213
+ * The agent's tools for one request, resolved now (connectors and extensions can change between
214
+ * steps): disabled tools and disabled sub-agent tools, a sub-agent's narrower roster, sandbox
215
+ * scoping and replay mode, with `Skill` offered when the log has a catalog snapshot or an
216
+ * invocation. The automatic step path and a manual compact run resolve them the same way, so the
217
+ * compaction sees the same history a step would.
218
+ */
219
+ export declare function resolveAgentTools(deps: Pick<ModelStepDeps, "tools">, input: Pick<ModelStepInput, "orgId" | "conversationId" | "agent" | "parent" | "parentRunId" | "subagent" | "source" | "conversationKind">, events: readonly ConversationEvent[]): Promise<ResolvedAgentTools>;
220
+ /** The step's {@link StepTools} from resolved tools: a fresh attachment cache unless one is shared. */
221
+ export declare function stepToolsOf(resolved: ResolvedAgentTools, input: Pick<ModelStepInput, "mediaCache">, deps: Pick<ModelStepDeps, "config">): StepTools;
222
+ /**
223
+ * 本步的附件缓存:`looked` 是已查过行的 id(没有行的不在 `info` 里);`run` 是本次运行的字节缓存
224
+ * (跨步复用,键含 etag)。
225
+ */
226
+ interface StepMedia {
227
+ looked: Set<string>;
228
+ info: Map<string, MediaInfo>;
229
+ bytes: Map<string, MediaBytes | null>;
230
+ run: MediaCache;
231
+ }
160
232
  /** 一次模型流的结果({@link consumeModelStream})。 */
161
233
  export interface StreamOutcome {
162
234
  content: ContentBlock[];
163
235
  stopReason: StopReason;
164
236
  usage: ModelUsage;
165
237
  }
238
+ type Runtime = KernelConfig["runtime"];
166
239
  /**
167
240
  * 一步模型调用:幂等 → 读日志 → 压缩 → 尾部提醒 → 构建请求 → 流式(看门狗)→ 降级梯子 → 写事件。
168
241
  * 模型看到的一切先写进日志(`model_call` / `reminder` / `compaction_summary`),请求可由日志还原。
@@ -197,17 +270,32 @@ export declare function appendCounted(deps: {
197
270
  budgetRunId?: string | undefined;
198
271
  } | undefined;
199
272
  }, events: AppendEvent[]): Promise<ConversationEvent[]>;
273
+ /** 读会话的全部事件(读到当前 last_seq),按 seq 升序。A manual compact run reads it the same way. */
274
+ export declare function readAllEvents(eventLog: Pick<EventLog, "readAfter">, conversationId: string): Promise<ConversationEvent[]>;
200
275
  /** {@link assembleModelRequest} 的输入。 */
201
276
  export interface AssembleModelRequestInput extends Omit<BuildModelRequestInput, "tools"> {
202
277
  /** 本步解析出的工具;模型不支持工具(`capabilities.tools` 为 false)时不带。 */
203
278
  tools: readonly RequestTool[];
204
279
  /** 参数里没有 `maxOutputTokens` 旋钮时的输出上限(运行时为 `runtime.maxOutputTokens`)。 */
205
280
  defaultMaxOutputTokens: number;
281
+ /**
282
+ * The cap recorded in `model_call.request.maxOutputTokens` (a baseline replay only): the runtime
283
+ * may have clamped it below the knob (context compaction spec §4.3), so a replay that recomputed
284
+ * it from the knob would send a larger cap than the recorded one. Given, it wins over the knob.
285
+ */
286
+ recordedMaxOutputTokens?: number;
287
+ /**
288
+ * A recorded hard-fit plan (context compaction spec §4.3/§4.9): applied after the pairing guard,
289
+ * so a replayed request equals the one that was sent. The plan's message indexes refer to the
290
+ * assembled (post-guard) request; the runtime computes it on the same list.
291
+ */
292
+ fit?: FitPlan;
206
293
  }
207
294
  /**
208
295
  * 发给模型的请求(纯函数):`buildModelRequest`(注入 `params` 与本步工具:模型不支持工具时不带;收尾调用带
209
- * `toolChoice: "none"`)→ `guardToolPairs`。输出上限:参数里有 `maxOutputTokens` 旋钮时取
210
- * `min(模型上限, 旋钮)`,否则 `min(模型上限, defaultMaxOutputTokens)`。
296
+ * `toolChoice: "none"`)→ `guardToolPairs` → the recorded `fit` plan (when given). 输出上限:参数里有
297
+ * `maxOutputTokens` 旋钮时取 `min(模型上限, 旋钮)`,否则 `min(模型上限, defaultMaxOutputTokens)`;记录了输出
298
+ * 上限的基线回放(`recordedMaxOutputTokens`)原样取记录值,旋钮不再覆盖。
211
299
  * 运行时({@link runModelStep})与由日志还原请求(`evals/reconstruct.ts`)共用这一份,二者不会漂移。
212
300
  */
213
301
  export declare function assembleModelRequest(input: AssembleModelRequestInput): {
@@ -215,6 +303,47 @@ export declare function assembleModelRequest(input: AssembleModelRequestInput):
215
303
  meta: ModelCallMeta;
216
304
  mediaTokens: number;
217
305
  };
306
+ /** Options of {@link maybeCompact}. */
307
+ interface CompactOptions {
308
+ /**
309
+ * The reactive path (context compaction spec §4.4): summarise regardless of the trigger,
310
+ * `enabled: false` and the failure backoff. A proactive call leaves all of them in force.
311
+ */
312
+ force?: boolean;
313
+ /**
314
+ * The model to summarise with (default the agent's main model). The reactive path passes the rung
315
+ * that overflowed: a fallback rung may have a smaller window and the summary must fit it.
316
+ */
317
+ ref?: ModelRef;
318
+ /** Whether `ref` is the fallback rung (its saved params are `fallbackParams`). */
319
+ fallback?: boolean;
320
+ }
321
+ /** What one compaction execution wrote: the events, the summary's seq and whether it failed. */
322
+ export interface CompactionOutcome {
323
+ /** The step's event list with what the compaction wrote merged in (unchanged when it wrote none). */
324
+ events: ConversationEvent[];
325
+ /** The seq of the `compaction_summary` written; null when none was (skipped or failed). */
326
+ summarySeq: number | null;
327
+ /** Whether a `compaction_failed` was written (a failed call, a denial or a failed acceptance). */
328
+ failed: boolean;
329
+ }
330
+ /**
331
+ * Compaction: summarize the earlier conversation with the main model (consumed non-streaming) when
332
+ * the calibrated estimate crosses the trigger (context compaction spec §4.1). The hard line
333
+ * (`estimate + output > window`) ignores `enabled: false` and the failure backoff; the proactive
334
+ * trigger respects both. Accepted → `compaction_summary`; too short or an error →
335
+ * `compaction_failed` (attempt from 1, consecutive failures increment), and the step continues
336
+ * unchanged. When the main model cannot be resolved right now, compaction is skipped and the
337
+ * fallback ladder handles the step.
338
+ *
339
+ * `opts.force` (the reactive path, spec §4.4, and a manual compact run, spec §4.7) bypasses the
340
+ * trigger, `enabled` and the backoff, and `opts.ref` makes it summarise with the rung's model rather
341
+ * than the agent's main model.
342
+ *
343
+ * The one execution both paths run: the automatic step path through {@link maybeCompact} and a
344
+ * manual compact run through `CompactionService.force`.
345
+ */
346
+ export declare function runCompaction(deps: ModelStepDeps, input: ModelStepInput, events: ConversationEvent[], runtime: Runtime, compaction: CompactionSettings, tools: StepTools, opts?: CompactOptions): Promise<CompactionOutcome>;
218
347
  /**
219
348
  * 消费一次模型流,带空闲看门狗:两次事件之间超过 `idleMs` → 本地中止并按 `ModelError("timeout")` 抛出。
220
349
  * 外部 `signal` 触发 → `StepAborted`。每次 `next()` 都与停止信号竞速,供应商不响应 signal 也不会卡住。