@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.
- package/bootstrap.json +27 -27
- package/dist/admin/admin.schemas.d.ts +7 -0
- package/dist/config/schema.d.ts +0 -2
- package/dist/config/schema.js +0 -16
- package/dist/conversations/conversations.controller.d.ts +11 -1
- package/dist/conversations/conversations.controller.js +25 -1
- package/dist/conversations/conversations.schemas.d.ts +8 -0
- package/dist/conversations/conversations.schemas.js +14 -0
- package/dist/conversations/conversations.service.d.ts +12 -0
- package/dist/conversations/conversations.service.js +10 -0
- package/dist/conversations/event-log.d.ts +14 -0
- package/dist/conversations/events.d.ts +12 -0
- package/dist/conversations/events.js +35 -3
- package/dist/db/kernel-schema.d.ts +5 -0
- package/dist/errors.d.ts +3 -0
- package/dist/errors.js +3 -0
- package/dist/evals/plan.d.ts +20 -15
- package/dist/evals/plan.js +29 -6
- package/dist/evals/reconstruct.d.ts +16 -1
- package/dist/evals/reconstruct.js +55 -1
- package/dist/evals/sets.service.d.ts +3 -2
- package/dist/evals/sets.service.js +16 -2
- package/dist/evals/step-replay.d.ts +6 -0
- package/dist/evals/step-replay.js +5 -0
- package/dist/evals/trajectory.d.ts +5 -1
- package/dist/evals/trajectory.js +3 -1
- package/dist/evals/worker.js +2 -1
- package/dist/identity/settings.d.ts +64 -0
- package/dist/identity/settings.js +86 -2
- package/dist/orgs/roles.d.ts +1 -1
- package/dist/orgs/roles.js +2 -0
- package/dist/orgs/settings.service.d.ts +17 -0
- package/dist/orgs/settings.service.js +31 -3
- package/dist/platform/ops/admin.ops.js +8 -2
- package/dist/platform/ops/conversations.ops.js +34 -0
- package/dist/platform/ops/evals.ops.js +12 -1
- package/dist/platform/ops/orgs.ops.js +1 -0
- package/dist/runtime/compaction-progress.d.ts +62 -0
- package/dist/runtime/compaction-progress.js +82 -0
- package/dist/runtime/compaction-settings.service.d.ts +16 -0
- package/dist/runtime/compaction-settings.service.js +42 -0
- package/dist/runtime/compaction.service.d.ts +50 -0
- package/dist/runtime/compaction.service.js +75 -0
- package/dist/runtime/context/compaction.d.ts +90 -12
- package/dist/runtime/context/compaction.js +256 -21
- package/dist/runtime/context/fit.d.ts +79 -0
- package/dist/runtime/context/fit.js +202 -0
- package/dist/runtime/model-call.d.ts +134 -5
- package/dist/runtime/model-call.js +766 -335
- package/dist/runtime/run-control.d.ts +6 -1
- package/dist/runtime/run-control.js +7 -0
- package/dist/runtime/run-queue.d.ts +14 -0
- package/dist/runtime/run-queue.js +75 -0
- package/dist/runtime/run-steps.d.ts +3 -1
- package/dist/runtime/run-steps.js +9 -2
- package/dist/runtime/run-worker.d.ts +14 -2
- package/dist/runtime/run-worker.js +160 -33
- package/dist/runtime/runtime.module.js +11 -0
- package/dist/runtime/stream.js +15 -0
- package/dist/tools/pipeline.js +6 -3
- package/package.json +1 -1
- package/src/migrations/0132_compact_runs.sql +6 -0
|
@@ -13,7 +13,7 @@ import { z } from "zod";
|
|
|
13
13
|
import { readPlatformAttribution, } from "../attribution/platform-attribution.js";
|
|
14
14
|
import { ApiError } from "../errors.js";
|
|
15
15
|
import { audit } from "../identity/audit.js";
|
|
16
|
-
import { readSandboxLimitOverride } from "../identity/settings.js";
|
|
16
|
+
import { COMPACTION_SETTINGS_PARTIAL, COMPACTION_SETTINGS_PATCH, readPlatformCompactionSettings, readSandboxLimitOverride, } from "../identity/settings.js";
|
|
17
17
|
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
18
18
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
19
19
|
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
@@ -176,6 +176,11 @@ export const OrgSettingsSchema = z.object({
|
|
|
176
176
|
gitGateway: GitGatewaySettingSchema.optional().catch({ ...GIT_GATEWAY_INVALID }),
|
|
177
177
|
/** Scheduled tasks (spec §9); the platform bounds clamp it, see `effectiveScheduleSettings`. */
|
|
178
178
|
scheduledTasks: ScheduledTasksSettingsSchema.prefault({}).catch(ScheduledTasksSettingsSchema.parse({})),
|
|
179
|
+
/**
|
|
180
|
+
* Conversation compaction overrides (context compaction spec §4.8): every field given wins, the
|
|
181
|
+
* rest follow the platform; absent (or an invalid stored value) follows the platform entirely.
|
|
182
|
+
*/
|
|
183
|
+
compaction: COMPACTION_SETTINGS_PARTIAL.optional().catch(undefined),
|
|
179
184
|
});
|
|
180
185
|
/** PATCH 体:只改给出的字段;未知字段 → 400。 */
|
|
181
186
|
export const OrgSettingsPatchSchema = z
|
|
@@ -210,6 +215,12 @@ export const OrgSettingsPatchSchema = z
|
|
|
210
215
|
uiArrangement: OrgUiArrangementPatchSchema.optional(),
|
|
211
216
|
/** Fields to change in the scheduled-tasks group; the rest keep their value. */
|
|
212
217
|
scheduledTasks: ScheduledTasksPatchSchema.optional(),
|
|
218
|
+
/**
|
|
219
|
+
* Conversation compaction overrides (context compaction spec §4.8): a partial object merges
|
|
220
|
+
* into the stored fields (absent fields keep their value); null clears the whole override
|
|
221
|
+
* (follow the platform again). Strict: a misspelled field is a 400, not a silent no-op.
|
|
222
|
+
*/
|
|
223
|
+
compaction: COMPACTION_SETTINGS_PATCH.nullable().optional(),
|
|
213
224
|
})
|
|
214
225
|
.strict();
|
|
215
226
|
/** Whether a finished background task wakes an idle conversation: the org's setting, else the deployment's. */
|
|
@@ -292,9 +303,10 @@ let OrgSettingsService = class OrgSettingsService {
|
|
|
292
303
|
/** 部署默认值(设置页展示「跟随部署」时的实际取值)。 */
|
|
293
304
|
async deployment() {
|
|
294
305
|
const lim = this.config.get().sandbox.limits;
|
|
295
|
-
const [autoMode, attribution] = await Promise.all([
|
|
306
|
+
const [autoMode, attribution, compaction] = await Promise.all([
|
|
296
307
|
readDevicesAutoMode(this.db.db, this.config, this.log),
|
|
297
308
|
readPlatformAttribution(this.db.db, this.config, this.log),
|
|
309
|
+
readPlatformCompactionSettings(this.db.db),
|
|
298
310
|
]);
|
|
299
311
|
return {
|
|
300
312
|
autoMode,
|
|
@@ -303,6 +315,7 @@ let OrgSettingsService = class OrgSettingsService {
|
|
|
303
315
|
: { mode: "open", allowHosts: [...lim.allowHosts] },
|
|
304
316
|
attribution,
|
|
305
317
|
publicUrl: this.config.get().http.publicUrl !== undefined,
|
|
318
|
+
compaction,
|
|
306
319
|
};
|
|
307
320
|
}
|
|
308
321
|
/** 组织实际生效的沙箱 cpu / 内存(只读;由超级管理员在部署设置里覆盖)。 */
|
|
@@ -405,8 +418,10 @@ let OrgSettingsService = class OrgSettingsService {
|
|
|
405
418
|
// null clears autoMode / cloudNetwork / wakeOnBackgroundTask: follow the deployment again
|
|
406
419
|
.map(([k, v]) => [k, v === null ? undefined : v]));
|
|
407
420
|
const arrangementPatch = patch.uiArrangement;
|
|
421
|
+
const compactionPatch = patch.compaction;
|
|
408
422
|
delete changes.uiArrangement;
|
|
409
423
|
delete changes.scheduledTasks;
|
|
424
|
+
delete changes.compaction;
|
|
410
425
|
const after = { ...before, ...changes };
|
|
411
426
|
if (patch.scheduledTasks !== undefined) {
|
|
412
427
|
after.scheduledTasks = ScheduledTasksSettingsSchema.parse({
|
|
@@ -414,6 +429,13 @@ let OrgSettingsService = class OrgSettingsService {
|
|
|
414
429
|
...Object.fromEntries(Object.entries(patch.scheduledTasks).filter(([, v]) => v !== undefined)),
|
|
415
430
|
});
|
|
416
431
|
}
|
|
432
|
+
if (compactionPatch !== undefined) {
|
|
433
|
+
// a partial object merges into the stored fields; null clears the whole override
|
|
434
|
+
if (compactionPatch === null)
|
|
435
|
+
delete after.compaction;
|
|
436
|
+
else
|
|
437
|
+
after.compaction = { ...before.compaction, ...compactionPatch };
|
|
438
|
+
}
|
|
417
439
|
if (arrangementPatch !== undefined) {
|
|
418
440
|
after.uiArrangement = mergeArrangement(before.uiArrangement, arrangementPatch);
|
|
419
441
|
if (Object.keys(after.uiArrangement).length === 0)
|
|
@@ -433,6 +455,12 @@ let OrgSettingsService = class OrgSettingsService {
|
|
|
433
455
|
delete after.uiArrangement;
|
|
434
456
|
if (after.gitGateway === undefined)
|
|
435
457
|
delete after.gitGateway;
|
|
458
|
+
// an empty compaction override is the same as none: follow the platform
|
|
459
|
+
if (after.compaction !== undefined && Object.keys(after.compaction).length === 0) {
|
|
460
|
+
delete after.compaction;
|
|
461
|
+
}
|
|
462
|
+
if (after.compaction === undefined)
|
|
463
|
+
delete after.compaction;
|
|
436
464
|
if (sameSettings(before, after))
|
|
437
465
|
return before;
|
|
438
466
|
// Lock order: the org row (orgLock above), then the theme's catalog item and its row FOR
|
|
@@ -442,7 +470,7 @@ let OrgSettingsService = class OrgSettingsService {
|
|
|
442
470
|
}
|
|
443
471
|
// Merge with the stored value: keep the keys this version does not know (a cleared autoMode /
|
|
444
472
|
// cloudNetwork is not kept)
|
|
445
|
-
const { autoMode: _oldAutoMode, cloudNetwork: _oldNetwork, wakeOnBackgroundTask: _oldWake, timeZone: _oldZone, theme: _oldTheme, uiArrangement: _oldArrangement, scheduledTasks: _oldScheduled, ...rest } = stored;
|
|
473
|
+
const { autoMode: _oldAutoMode, cloudNetwork: _oldNetwork, wakeOnBackgroundTask: _oldWake, timeZone: _oldZone, theme: _oldTheme, uiArrangement: _oldArrangement, scheduledTasks: _oldScheduled, compaction: _oldCompaction, ...rest } = stored;
|
|
446
474
|
await this.db
|
|
447
475
|
.updateTable("orgs")
|
|
448
476
|
.set({ settings: JSON.stringify({ ...rest, ...after }) })
|
|
@@ -217,8 +217,14 @@ let AdminOperations = class AdminOperations {
|
|
|
217
217
|
example: { orgCreation: "super_admin" },
|
|
218
218
|
authz: { superAdmin: true },
|
|
219
219
|
mirrors: ["PUT /api/v1/admin/settings"],
|
|
220
|
-
// the per-org override records are orgs.set-limits (one org at a time)
|
|
221
|
-
|
|
220
|
+
// the per-org override records are orgs.set-limits (one org at a time); compaction is
|
|
221
|
+
// changed in the admin console's settings page
|
|
222
|
+
omits: [
|
|
223
|
+
"runConcurrencyOverrides",
|
|
224
|
+
"sandboxLimitOverrides",
|
|
225
|
+
"subagentLimitOverrides",
|
|
226
|
+
"compaction",
|
|
227
|
+
],
|
|
222
228
|
confirm: "platform",
|
|
223
229
|
errors: [
|
|
224
230
|
{
|
|
@@ -412,6 +412,40 @@ let ConversationsOperations = class ConversationsOperations {
|
|
|
412
412
|
runId: await this.conversations.abort(ctx.orgId, input.conversationId, ctx.actorAccountId),
|
|
413
413
|
}),
|
|
414
414
|
}),
|
|
415
|
+
defineOperation({
|
|
416
|
+
id: "conversations.compact",
|
|
417
|
+
description: "Compact one of your conversations now: an earlier part of its history is replaced by a summary, saving context for the next runs (it does not delete the conversation or stop it). A run already compacting the conversation is reused; a conversation with a run in progress cannot be compacted. The person may remember this permission.",
|
|
418
|
+
input: Id,
|
|
419
|
+
example: { conversationId: "3f2b8a40-6c1d-4e0b-9a77-5d1e2c8b9f10" },
|
|
420
|
+
authz: { orgAction: "conversations.compact" },
|
|
421
|
+
mirrors: ["POST /api/v1/orgs/:orgId/conversations/:id/compact"],
|
|
422
|
+
// the tool call itself is the request: a retry id has no meaning here
|
|
423
|
+
omits: ["clientRequestId"],
|
|
424
|
+
renames: { conversationId: "id" },
|
|
425
|
+
errors: [
|
|
426
|
+
{
|
|
427
|
+
code: "conversation.not_found",
|
|
428
|
+
next: "Check the id with conversations.list: only your own conversations can be read or changed.",
|
|
429
|
+
},
|
|
430
|
+
{
|
|
431
|
+
code: "conversation.busy",
|
|
432
|
+
next: "A run is active in that conversation: check conversations.list for its state and compact once it is idle.",
|
|
433
|
+
},
|
|
434
|
+
{
|
|
435
|
+
code: "conversation.read_only",
|
|
436
|
+
next: "That is a sub-agent's conversation and is compacted by its own runs; compact the conversation it belongs to.",
|
|
437
|
+
},
|
|
438
|
+
],
|
|
439
|
+
confirm: "personal",
|
|
440
|
+
precheck: (i, ctx) => this.precheckWritable(i.conversationId, ctx),
|
|
441
|
+
summary: async (i, ctx) => {
|
|
442
|
+
const t = await this.titleOf(ctx, i.conversationId);
|
|
443
|
+
return { zh: `压缩对话「${t}」的早期历史`, en: `Compact the earlier history of "${t}"` };
|
|
444
|
+
},
|
|
445
|
+
run: async (input, ctx) => ({
|
|
446
|
+
runId: await this.conversations.compact(ctx.orgId, input.conversationId, ctx.actorAccountId),
|
|
447
|
+
}),
|
|
448
|
+
}),
|
|
415
449
|
defineOperation({
|
|
416
450
|
id: "conversations.delete",
|
|
417
451
|
description: "Delete one of your conversations: a running run in it is stopped and the conversation disappears from every list. This cannot be undone from the tool. The person confirms every delete; it is never remembered. The conversation you are working in cannot be deleted.",
|
|
@@ -295,6 +295,10 @@ let EvalsOperations = class EvalsOperations {
|
|
|
295
295
|
next: "The run belongs to another agent than the set's; add runs of the set's agent.",
|
|
296
296
|
},
|
|
297
297
|
{ code: "eval.case_exists", next: "That run is already a case of the set." },
|
|
298
|
+
{
|
|
299
|
+
code: "eval.compact_not_replayable",
|
|
300
|
+
next: "A manual compaction run has no step to replay; pick an ordinary run of the conversation.",
|
|
301
|
+
},
|
|
298
302
|
{
|
|
299
303
|
code: "eval.too_many_cases",
|
|
300
304
|
next: "The set is full; remove a case with evals.remove-case or use another set.",
|
|
@@ -347,7 +351,7 @@ let EvalsOperations = class EvalsOperations {
|
|
|
347
351
|
}
|
|
348
352
|
const run = await this.kdb.db
|
|
349
353
|
.selectFrom("runs")
|
|
350
|
-
.select("status")
|
|
354
|
+
.select(["status", "compact"])
|
|
351
355
|
.where("id", "=", i.runId)
|
|
352
356
|
.where("conversation_id", "=", i.conversationId)
|
|
353
357
|
.executeTakeFirst();
|
|
@@ -358,6 +362,13 @@ let EvalsOperations = class EvalsOperations {
|
|
|
358
362
|
message: "Conversation or run not found",
|
|
359
363
|
};
|
|
360
364
|
}
|
|
365
|
+
if (run.compact) {
|
|
366
|
+
return {
|
|
367
|
+
ok: false,
|
|
368
|
+
code: "eval.compact_not_replayable",
|
|
369
|
+
message: "A manual compaction run has no model step to replay",
|
|
370
|
+
};
|
|
371
|
+
}
|
|
361
372
|
if (run.status === "running" || run.status === "queued") {
|
|
362
373
|
return {
|
|
363
374
|
ok: false,
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { ExtensionContext, Logger } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import type { Redis } from "ioredis";
|
|
3
|
+
/** The three phases of a compaction (context compaction spec §4.6). */
|
|
4
|
+
export type CompactionPhase = "preparing" | "summarizing" | "writing";
|
|
5
|
+
/**
|
|
6
|
+
* A compaction's progress (context compaction spec §4.6): ephemeral, Redis-kept and display-only.
|
|
7
|
+
* `chunk` / `chunks` are set only in the chunked path (a real `i/N`, never a percentage); `chars`
|
|
8
|
+
* is how much of the running summary has streamed in the current call.
|
|
9
|
+
*/
|
|
10
|
+
export interface CompactionProgress {
|
|
11
|
+
phase: CompactionPhase;
|
|
12
|
+
step: number;
|
|
13
|
+
chunk?: number;
|
|
14
|
+
chunks?: number;
|
|
15
|
+
chars?: number;
|
|
16
|
+
/** When this compaction started (the web row's elapsed time). */
|
|
17
|
+
startedAt: number;
|
|
18
|
+
}
|
|
19
|
+
/** One snapshot to publish: the run and conversation it belongs to and the progress itself. */
|
|
20
|
+
export interface CompactionProgressUpdate {
|
|
21
|
+
runId: string;
|
|
22
|
+
conversationId: string;
|
|
23
|
+
agentId?: string;
|
|
24
|
+
progress: CompactionProgress;
|
|
25
|
+
}
|
|
26
|
+
/** How long a progress key lives without a write (a backstop; each write refreshes it). */
|
|
27
|
+
export declare const COMPACTION_PROGRESS_TTL_SECONDS = 600;
|
|
28
|
+
/** At most one write per run per window while the summary streams (a phase change always writes). */
|
|
29
|
+
export declare const COMPACTION_PROGRESS_FLUSH_MS = 200;
|
|
30
|
+
/** The run's progress key. */
|
|
31
|
+
export declare const compactionProgressKey: (runId: string) => string;
|
|
32
|
+
/** What the run publishes inside `maybeCompact` (the injected service implements it). */
|
|
33
|
+
export interface CompactionProgressSink {
|
|
34
|
+
update(u: CompactionProgressUpdate): void;
|
|
35
|
+
clear(runId: string): void;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Compaction progress for the conversation SSE (context compaction spec §4.6). The process running
|
|
39
|
+
* the compaction writes the run's Redis key (`capk:run-compaction:<runId>`, TTL
|
|
40
|
+
* {@link COMPACTION_PROGRESS_TTL_SECONDS}) and publishes a `compaction_progress` message on the
|
|
41
|
+
* conversation's topic, which the SSE forwards as `event: compaction`.
|
|
42
|
+
*
|
|
43
|
+
* Multi-replica safe: the durable state is the Redis key (a viewer may read it on any replica); the
|
|
44
|
+
* in-memory map only throttles this writer's own writes and a phase change always writes. Progress
|
|
45
|
+
* is display-only, never in the event log: a lost write or publish costs nothing, and failures are
|
|
46
|
+
* logged, never thrown to the run.
|
|
47
|
+
*/
|
|
48
|
+
export declare class CompactionProgressService implements CompactionProgressSink {
|
|
49
|
+
private readonly redis;
|
|
50
|
+
private readonly bus;
|
|
51
|
+
private readonly log;
|
|
52
|
+
/** Writer-local: when each run was last written, and its phase then. */
|
|
53
|
+
private readonly last;
|
|
54
|
+
constructor(redis: Redis, bus: Pick<ExtensionContext["bus"], "publish">, log: Pick<Logger, "warn">);
|
|
55
|
+
/**
|
|
56
|
+
* Publishes one snapshot: a phase change writes at once; while the summary streams (`chars`
|
|
57
|
+
* moving) a write happens at most every {@link COMPACTION_PROGRESS_FLUSH_MS}. Fire-and-forget.
|
|
58
|
+
*/
|
|
59
|
+
update(u: CompactionProgressUpdate): void;
|
|
60
|
+
/** Deletes the run's progress key (the compaction ended); the TTL is the backstop. */
|
|
61
|
+
clear(runId: string): void;
|
|
62
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
8
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
|
+
};
|
|
10
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
11
|
+
import { conversationTopic } from "../conversations/event-log.js";
|
|
12
|
+
import { KERNEL_BUS, KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
|
|
13
|
+
/** How long a progress key lives without a write (a backstop; each write refreshes it). */
|
|
14
|
+
export const COMPACTION_PROGRESS_TTL_SECONDS = 600;
|
|
15
|
+
/** At most one write per run per window while the summary streams (a phase change always writes). */
|
|
16
|
+
export const COMPACTION_PROGRESS_FLUSH_MS = 200;
|
|
17
|
+
/** The run's progress key. */
|
|
18
|
+
export const compactionProgressKey = (runId) => `capk:run-compaction:${runId}`;
|
|
19
|
+
/**
|
|
20
|
+
* Compaction progress for the conversation SSE (context compaction spec §4.6). The process running
|
|
21
|
+
* the compaction writes the run's Redis key (`capk:run-compaction:<runId>`, TTL
|
|
22
|
+
* {@link COMPACTION_PROGRESS_TTL_SECONDS}) and publishes a `compaction_progress` message on the
|
|
23
|
+
* conversation's topic, which the SSE forwards as `event: compaction`.
|
|
24
|
+
*
|
|
25
|
+
* Multi-replica safe: the durable state is the Redis key (a viewer may read it on any replica); the
|
|
26
|
+
* in-memory map only throttles this writer's own writes and a phase change always writes. Progress
|
|
27
|
+
* is display-only, never in the event log: a lost write or publish costs nothing, and failures are
|
|
28
|
+
* logged, never thrown to the run.
|
|
29
|
+
*/
|
|
30
|
+
let CompactionProgressService = class CompactionProgressService {
|
|
31
|
+
redis;
|
|
32
|
+
bus;
|
|
33
|
+
log;
|
|
34
|
+
/** Writer-local: when each run was last written, and its phase then. */
|
|
35
|
+
last = new Map();
|
|
36
|
+
constructor(redis, bus, log) {
|
|
37
|
+
this.redis = redis;
|
|
38
|
+
this.bus = bus;
|
|
39
|
+
this.log = log;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Publishes one snapshot: a phase change writes at once; while the summary streams (`chars`
|
|
43
|
+
* moving) a write happens at most every {@link COMPACTION_PROGRESS_FLUSH_MS}. Fire-and-forget.
|
|
44
|
+
*/
|
|
45
|
+
update(u) {
|
|
46
|
+
const { runId, progress } = u;
|
|
47
|
+
const now = Date.now();
|
|
48
|
+
const prev = this.last.get(runId);
|
|
49
|
+
if (prev !== undefined &&
|
|
50
|
+
prev.phase === progress.phase &&
|
|
51
|
+
now - prev.writtenAt < COMPACTION_PROGRESS_FLUSH_MS) {
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
this.last.set(runId, { writtenAt: now, phase: progress.phase });
|
|
55
|
+
this.redis
|
|
56
|
+
.set(compactionProgressKey(runId), JSON.stringify(progress), "EX", COMPACTION_PROGRESS_TTL_SECONDS)
|
|
57
|
+
.catch((err) => this.log.warn("compaction progress write failed", { runId, err }));
|
|
58
|
+
this.bus
|
|
59
|
+
.publish(conversationTopic(u.conversationId), {
|
|
60
|
+
kind: "compaction_progress",
|
|
61
|
+
runId,
|
|
62
|
+
conversationId: u.conversationId,
|
|
63
|
+
...(u.agentId !== undefined && { agentId: u.agentId }),
|
|
64
|
+
...progress,
|
|
65
|
+
})
|
|
66
|
+
.catch((err) => this.log.warn("compaction progress publish failed", { runId, err }));
|
|
67
|
+
}
|
|
68
|
+
/** Deletes the run's progress key (the compaction ended); the TTL is the backstop. */
|
|
69
|
+
clear(runId) {
|
|
70
|
+
this.last.delete(runId);
|
|
71
|
+
this.redis
|
|
72
|
+
.del(compactionProgressKey(runId))
|
|
73
|
+
.catch((err) => this.log.warn("compaction progress clear failed", { runId, err }));
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
CompactionProgressService = __decorate([
|
|
77
|
+
Injectable(),
|
|
78
|
+
__param(0, Inject(REDIS)),
|
|
79
|
+
__param(1, Inject(KERNEL_BUS)),
|
|
80
|
+
__param(2, Inject(KERNEL_LOGGER))
|
|
81
|
+
], CompactionProgressService);
|
|
82
|
+
export { CompactionProgressService };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type CompactionSettings, SettingsService } from "../identity/settings.js";
|
|
2
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
3
|
+
export { COMPACTION_SETTINGS, type CompactionSettings, effectiveCompactionSettings, } from "../identity/settings.js";
|
|
4
|
+
/**
|
|
5
|
+
* The compaction settings in effect for one organization (context compaction spec §4.8):
|
|
6
|
+
* the organization's override over the platform's stored settings, which carry the built-in
|
|
7
|
+
* defaults. Read live on every model step, so a change in the admin console or the org settings
|
|
8
|
+
* applies on the next step on every replica.
|
|
9
|
+
*/
|
|
10
|
+
export declare class CompactionSettingsService {
|
|
11
|
+
private readonly settings;
|
|
12
|
+
private readonly db;
|
|
13
|
+
constructor(settings: Pick<SettingsService, "get">, db: KernelDb);
|
|
14
|
+
/** The effective settings for `orgId`: org override > platform setting > built-in default. */
|
|
15
|
+
resolve(orgId: string): Promise<CompactionSettings>;
|
|
16
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
8
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
|
+
};
|
|
10
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
11
|
+
import { effectiveCompactionSettings, SettingsService, } from "../identity/settings.js";
|
|
12
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
13
|
+
import { readOrgSettings } from "../orgs/settings.service.js";
|
|
14
|
+
export { COMPACTION_SETTINGS, effectiveCompactionSettings, } from "../identity/settings.js";
|
|
15
|
+
/**
|
|
16
|
+
* The compaction settings in effect for one organization (context compaction spec §4.8):
|
|
17
|
+
* the organization's override over the platform's stored settings, which carry the built-in
|
|
18
|
+
* defaults. Read live on every model step, so a change in the admin console or the org settings
|
|
19
|
+
* applies on the next step on every replica.
|
|
20
|
+
*/
|
|
21
|
+
let CompactionSettingsService = class CompactionSettingsService {
|
|
22
|
+
settings;
|
|
23
|
+
db;
|
|
24
|
+
constructor(settings, db) {
|
|
25
|
+
this.settings = settings;
|
|
26
|
+
this.db = db;
|
|
27
|
+
}
|
|
28
|
+
/** The effective settings for `orgId`: org override > platform setting > built-in default. */
|
|
29
|
+
async resolve(orgId) {
|
|
30
|
+
const [platform, org] = await Promise.all([
|
|
31
|
+
this.settings.get(),
|
|
32
|
+
readOrgSettings(this.db.db, orgId),
|
|
33
|
+
]);
|
|
34
|
+
return effectiveCompactionSettings(platform.compaction, org.compaction);
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
CompactionSettingsService = __decorate([
|
|
38
|
+
Injectable(),
|
|
39
|
+
__param(0, Inject(SettingsService)),
|
|
40
|
+
__param(1, Inject(KernelDb))
|
|
41
|
+
], CompactionSettingsService);
|
|
42
|
+
export { CompactionSettingsService };
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { ConversationSource } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import type { AgentDefinition } from "../agents/definition.js";
|
|
3
|
+
import { EventLog } from "../conversations/event-log.js";
|
|
4
|
+
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
5
|
+
import { CompactionSettingsService } from "./compaction-settings.service.js";
|
|
6
|
+
import { RunSteps } from "./run-steps.js";
|
|
7
|
+
/** What a manual compact run gives the shared compaction execution (context compaction spec §4.7). */
|
|
8
|
+
export interface ForceCompactionInput {
|
|
9
|
+
orgId: string;
|
|
10
|
+
conversationId: string;
|
|
11
|
+
/** The compact run's id: its events (and their idempotency keys) carry it. */
|
|
12
|
+
runId: string;
|
|
13
|
+
/** The run's trigger account (the person who asked): hook payloads attribute the calls to it. */
|
|
14
|
+
accountId: string;
|
|
15
|
+
agentId: string;
|
|
16
|
+
/**
|
|
17
|
+
* The conversation's effective definition: the agent version the next run would use with the
|
|
18
|
+
* conversation's model selection (including `model_switched`) applied.
|
|
19
|
+
*/
|
|
20
|
+
agent: AgentDefinition;
|
|
21
|
+
agentVersion: number;
|
|
22
|
+
source: ConversationSource;
|
|
23
|
+
/** A compact run is a chat conversation's (sub-agent and eval conversations take no compaction). */
|
|
24
|
+
conversationKind: "chat";
|
|
25
|
+
/** The conversation's `consumed_seq`: nothing new is absorbed by the compaction. */
|
|
26
|
+
absorbedUpToSeq: number;
|
|
27
|
+
signal: AbortSignal;
|
|
28
|
+
}
|
|
29
|
+
/** What the compact run recorded: the `compaction_summary` it wrote, and whether it failed. */
|
|
30
|
+
export interface ForcedCompaction {
|
|
31
|
+
summarySeq: number | null;
|
|
32
|
+
failed: boolean;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* The manual compaction a compact run executes (context compaction spec §4.7). It prepares the same
|
|
36
|
+
* environment a model step has (the events, the effective definition's tools, the org's compaction
|
|
37
|
+
* settings) and calls the shared {@link runCompaction} with `force: true`: the trigger,
|
|
38
|
+
* `enabled: false` and the failure backoff are bypassed, the compaction plan is still required.
|
|
39
|
+
*
|
|
40
|
+
* The run writes only `compaction_summary` / `compaction_failed` + the summary calls' `usage`, with
|
|
41
|
+
* `step: 0`; no user message and no model step.
|
|
42
|
+
*/
|
|
43
|
+
export declare class CompactionService {
|
|
44
|
+
private readonly steps;
|
|
45
|
+
private readonly eventLog;
|
|
46
|
+
private readonly config;
|
|
47
|
+
private readonly settings;
|
|
48
|
+
constructor(steps: RunSteps, eventLog: EventLog, config: KernelConfigService, settings: CompactionSettingsService);
|
|
49
|
+
force(input: ForceCompactionInput): Promise<ForcedCompaction>;
|
|
50
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
8
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
|
+
};
|
|
10
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
11
|
+
import { EventLog } from "../conversations/event-log.js";
|
|
12
|
+
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
13
|
+
import { CompactionSettingsService } from "./compaction-settings.service.js";
|
|
14
|
+
import { readAllEvents, resolveAgentTools, runCompaction, stepToolsOf, } from "./model-call.js";
|
|
15
|
+
import { RunSteps } from "./run-steps.js";
|
|
16
|
+
/**
|
|
17
|
+
* The manual compaction a compact run executes (context compaction spec §4.7). It prepares the same
|
|
18
|
+
* environment a model step has (the events, the effective definition's tools, the org's compaction
|
|
19
|
+
* settings) and calls the shared {@link runCompaction} with `force: true`: the trigger,
|
|
20
|
+
* `enabled: false` and the failure backoff are bypassed, the compaction plan is still required.
|
|
21
|
+
*
|
|
22
|
+
* The run writes only `compaction_summary` / `compaction_failed` + the summary calls' `usage`, with
|
|
23
|
+
* `step: 0`; no user message and no model step.
|
|
24
|
+
*/
|
|
25
|
+
let CompactionService = class CompactionService {
|
|
26
|
+
steps;
|
|
27
|
+
eventLog;
|
|
28
|
+
config;
|
|
29
|
+
settings;
|
|
30
|
+
constructor(steps, eventLog, config, settings) {
|
|
31
|
+
this.steps = steps;
|
|
32
|
+
this.eventLog = eventLog;
|
|
33
|
+
this.config = config;
|
|
34
|
+
this.settings = settings;
|
|
35
|
+
}
|
|
36
|
+
async force(input) {
|
|
37
|
+
// the run's steps environment (the model registry, the tool registry, media, hooks, progress);
|
|
38
|
+
// no step state is kept on it, so a compact run may share it with the steps of other runs
|
|
39
|
+
const deps = this.steps.deps;
|
|
40
|
+
const events = await readAllEvents(this.eventLog, input.conversationId);
|
|
41
|
+
const stepInput = {
|
|
42
|
+
orgId: input.orgId,
|
|
43
|
+
conversationId: input.conversationId,
|
|
44
|
+
runId: input.runId,
|
|
45
|
+
step: 0,
|
|
46
|
+
agent: input.agent,
|
|
47
|
+
agentVersion: input.agentVersion,
|
|
48
|
+
signal: input.signal,
|
|
49
|
+
// a compact run streams nothing to the conversation: the summary call's deltas only move the
|
|
50
|
+
// progress counters, which the compaction reports itself
|
|
51
|
+
sink: () => { },
|
|
52
|
+
absorbedUpToSeq: input.absorbedUpToSeq,
|
|
53
|
+
agentId: input.agentId,
|
|
54
|
+
accountId: input.accountId,
|
|
55
|
+
source: input.source,
|
|
56
|
+
conversationKind: input.conversationKind,
|
|
57
|
+
};
|
|
58
|
+
// tools and media resolve as for a step: the summary request estimates the same history a
|
|
59
|
+
// step's request would (spec §4.7)
|
|
60
|
+
const tools = stepToolsOf(await resolveAgentTools(deps, stepInput, events), stepInput, deps);
|
|
61
|
+
const compaction = await this.settings.resolve(input.orgId);
|
|
62
|
+
const out = await runCompaction(deps, stepInput, events, this.config.get().runtime, compaction, tools, {
|
|
63
|
+
force: true,
|
|
64
|
+
});
|
|
65
|
+
return { summarySeq: out.summarySeq, failed: out.failed };
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
CompactionService = __decorate([
|
|
69
|
+
Injectable(),
|
|
70
|
+
__param(0, Inject(RunSteps)),
|
|
71
|
+
__param(1, Inject(EventLog)),
|
|
72
|
+
__param(2, Inject(KernelConfigService)),
|
|
73
|
+
__param(3, Inject(CompactionSettingsService))
|
|
74
|
+
], CompactionService);
|
|
75
|
+
export { CompactionService };
|
|
@@ -1,23 +1,101 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { ModelRequest } from "@capybara-hq/plugin-sdk";
|
|
2
2
|
import type { ConversationEvent } from "../../conversations/events.js";
|
|
3
|
+
import type { CompactionSettings } from "../../identity/settings.js";
|
|
3
4
|
/** 压缩请求的标记:放在 system 中,便于识别(model-fake 据此返回摘要)。 */
|
|
4
5
|
export declare const COMPACTION_MARKER = "CAPYBARA_COMPACTION";
|
|
5
|
-
/** 压缩请求的输出上限。 */
|
|
6
|
-
export declare const COMPACTION_MAX_OUTPUT_TOKENS = 4096;
|
|
7
|
-
/** 估算 token 数达到上下文窗口的 `threshold`(如 0.8)时压缩。 */
|
|
8
|
-
export declare function shouldCompact(estimatedTokens: number, model: ModelInfo, threshold: number): boolean;
|
|
9
6
|
/**
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
7
|
+
* The summary request's output cap when the caller gives none: the built-in default of the
|
|
8
|
+
* `compaction.maxOutputTokens` setting (context compaction spec §4.8). The effective setting is
|
|
9
|
+
* what the request uses, capped by the model's own max output.
|
|
13
10
|
*/
|
|
14
|
-
export declare
|
|
11
|
+
export declare const COMPACTION_MAX_OUTPUT_TOKENS = 20000;
|
|
12
|
+
/**
|
|
13
|
+
* The input room a request leaves below the window: the output cap and the safety reserve are never
|
|
14
|
+
* spent on input (context compaction spec §4.1).
|
|
15
|
+
*/
|
|
16
|
+
export declare function compactionInputBudget(window: number, maxOutput: number, reserve: number): number;
|
|
17
|
+
/**
|
|
18
|
+
* The input tokens every summary request carries regardless of its chunk: the instruction, the
|
|
19
|
+
* transcript wrapper and a small margin. A chunked compaction subtracts it from the chunk size
|
|
20
|
+
* (context compaction spec §4.5), so chunk + overhead stays inside the request budget.
|
|
21
|
+
*/
|
|
22
|
+
export declare function compactionRequestOverhead(): number;
|
|
23
|
+
/**
|
|
24
|
+
* The chunk size of a chunked compaction (context compaction spec §4.5): one summary call's input
|
|
25
|
+
* budget `B` minus the room the running summary may take in the next call (half the output cap) and
|
|
26
|
+
* the request's fixed overhead.
|
|
27
|
+
*/
|
|
28
|
+
export declare function compactionChunkSize(budget: number, maxOutputTokens: number): number;
|
|
29
|
+
/**
|
|
30
|
+
* The floor of one summary chunk (context compaction spec §4.5): the running summary can shrink a
|
|
31
|
+
* later chunk below it, and such a chunk fails with a clear reason instead of letting
|
|
32
|
+
* {@link nextTranscriptChunk} clamp to one token and make a call per token. A base chunk below it
|
|
33
|
+
* (a window that leaves no room for a chunked compaction) falls back to one call over the whole
|
|
34
|
+
* transcript.
|
|
35
|
+
*/
|
|
36
|
+
export declare const MIN_COMPACTION_CHUNK_TOKENS = 256;
|
|
37
|
+
/**
|
|
38
|
+
* Compaction trigger (context compaction spec §4.1): the calibrated estimate reaches the lower of
|
|
39
|
+
* `threshold × window` and the input budget, or it reaches the hard line `estimate + output >
|
|
40
|
+
* window`, which fires even when proactive early compaction is turned off (`enabled: false`).
|
|
41
|
+
* `settings.maxOutputTokens` here carries `O`, the request's output cap (§4.1), not the summary cap (§4.8).
|
|
42
|
+
*/
|
|
43
|
+
export declare function shouldCompact(estimate: number, window: number, settings: CompactionSettings): boolean;
|
|
44
|
+
/**
|
|
45
|
+
* The compaction plan: keep the most recent `settings.keepRecentTurns` turns verbatim (a maximum,
|
|
46
|
+
* not a rule) and transcribe everything older that the previous summary does not cover yet (that
|
|
47
|
+
* summary goes first, for the new summary to merge).
|
|
48
|
+
*
|
|
49
|
+
* The kept tail shrinks turn by turn, down to the latest user turn, until its estimated tokens fit
|
|
50
|
+
* `budget` — the input room left after the output cap, the reserve, the system prompt and the tool
|
|
51
|
+
* definitions. A single turn over the budget is still kept (the hard fit guard handles the rest).
|
|
52
|
+
* `coversUpToSeq` is the largest seq before the first kept user_message. Returns null when there is
|
|
53
|
+
* nothing to summarize.
|
|
54
|
+
*/
|
|
55
|
+
export declare function compactionPlan(events: ConversationEvent[], settings: CompactionSettings, budget: number): {
|
|
15
56
|
coversUpToSeq: number;
|
|
16
57
|
transcript: string;
|
|
17
58
|
} | null;
|
|
18
|
-
/**
|
|
19
|
-
|
|
20
|
-
|
|
59
|
+
/**
|
|
60
|
+
* The text to store as the compaction summary (context compaction spec §4.2.1): the `<summary>`
|
|
61
|
+
* block when the model returned one, since the `<analysis>` scratchpad must never be sent in a
|
|
62
|
+
* later request; otherwise the answer with any `<analysis>` block and any dangling `<summary>` tag
|
|
63
|
+
* removed (a truncated response may have been cut off after the opening tag). Trimmed; an empty
|
|
64
|
+
* result fails the attempt.
|
|
65
|
+
*/
|
|
66
|
+
export declare function extractSummary(text: string): string;
|
|
67
|
+
/**
|
|
68
|
+
* The next chunk of a transcript and what is left to summarise (context compaction spec §4.5):
|
|
69
|
+
* whole lines up to `chunkSize` estimated tokens, counting the line separators; a single line over
|
|
70
|
+
* the chunk size (usually a tool result) is hard-split at a character boundary with the split
|
|
71
|
+
* marker, never inside a UTF-16 surrogate pair, and the rest of the line stays for the next call.
|
|
72
|
+
* Null for empty input.
|
|
73
|
+
*/
|
|
74
|
+
export declare function nextTranscriptChunk(transcript: string, chunkSize: number): {
|
|
75
|
+
chunk: string;
|
|
76
|
+
rest: string;
|
|
77
|
+
} | null;
|
|
78
|
+
/**
|
|
79
|
+
* Splits a transcript into chunks of at most `chunkSize` estimated tokens at line boundaries
|
|
80
|
+
* (context compaction spec §4.5). A single line over the chunk size is hard-split at a character
|
|
81
|
+
* boundary rather than failing, its pieces marked with {@link CHUNK_SPLIT_MARKER}. Empty input
|
|
82
|
+
* returns no chunks; input that fits returns itself as the only chunk.
|
|
83
|
+
*/
|
|
84
|
+
export declare function chunkTranscript(transcript: string, chunkSize: number): string[];
|
|
85
|
+
/**
|
|
86
|
+
* The summary request: the marked English instruction as the system prompt and the transcript as
|
|
87
|
+
* the only user message. `maxOutputTokens` is the effective `compaction.maxOutputTokens` setting,
|
|
88
|
+
* which the caller narrows to the model's own cap (context compaction spec §4.8); omitted, it is
|
|
89
|
+
* the built-in default.
|
|
90
|
+
*/
|
|
91
|
+
export declare function buildCompactionRequest(transcript: string, model: string, maxOutputTokens?: number): ModelRequest;
|
|
92
|
+
/**
|
|
93
|
+
* What a compaction saved (context compaction spec §4.9): the estimated transcript input minus the
|
|
94
|
+
* stored summary output. Floored at zero — a summary at least as long as the transcript saved no
|
|
95
|
+
* tokens, and `savedTokens` is a non-negative count — so the UI can render it as "saved N".
|
|
96
|
+
*/
|
|
97
|
+
export declare function summarySavedTokens(transcript: string, summary: string): number;
|
|
98
|
+
/** A summary of at least min(200, 5% of the transcript) characters is accepted; shorter fails. */
|
|
21
99
|
export declare function acceptSummary(text: string, transcript: string): boolean;
|
|
22
100
|
/**
|
|
23
101
|
* 压缩失败后的退避:最近一次 `compaction_failed`(attempt = n)之后新增的 user 轮次少于 2^n 时
|