@capybara-hq/kernel 0.1.0-rc.30 → 0.1.0-rc.32
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 +3 -3
- package/dist/catalog/marketplace-fetch.d.ts +5 -2
- package/dist/catalog/marketplace-fetch.js +4 -1
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/catalog/requests.service.d.ts +6 -5
- package/dist/catalog/requests.service.js +7 -6
- package/dist/config/load.d.ts +6 -0
- package/dist/config/load.js +26 -0
- package/dist/config/schema.js +5 -5
- package/dist/conversations/events.d.ts +10 -0
- package/dist/conversations/events.js +23 -1
- package/dist/ctx/create-ctx.d.ts +26 -4
- package/dist/ctx/create-ctx.js +54 -34
- package/dist/devices/devices.controller.js +3 -2
- package/dist/devices/devices.service.d.ts +17 -5
- package/dist/devices/devices.service.js +24 -13
- package/dist/devices/dto.d.ts +7 -6
- package/dist/devices/dto.js +6 -5
- package/dist/errors.d.ts +6 -1
- package/dist/errors.js +6 -1
- package/dist/evals/reconstruct.js +18 -8
- package/dist/extensions/bootstrap.d.ts +1 -1
- package/dist/extensions/bootstrap.js +7 -1
- package/dist/extensions/installs.js +4 -1
- package/dist/extensions/permission-set.d.ts +7 -6
- package/dist/extensions/permission-set.js +9 -6
- package/dist/extensions/permission-view.d.ts +4 -4
- package/dist/extensions/permission-view.js +10 -5
- package/dist/http/app.d.ts +8 -2
- package/dist/http/app.js +12 -2
- package/dist/http/plugin-dispatch.d.ts +55 -18
- package/dist/http/plugin-dispatch.js +124 -29
- package/dist/http/plugin-route-access.d.ts +56 -0
- package/dist/http/plugin-route-access.js +192 -0
- package/dist/identity/auth.guard.d.ts +26 -12
- package/dist/identity/auth.guard.js +62 -33
- package/dist/infra/throttler/named-throttlers.d.ts +3 -0
- package/dist/infra/throttler/named-throttlers.js +16 -0
- package/dist/infra/throttler/throttler.guard.d.ts +2 -1
- package/dist/infra/throttler/throttler.guard.js +2 -1
- package/dist/kernel.module.js +3 -0
- package/dist/lifecycle/kernel-lifecycle.js +1 -3
- package/dist/net/public-address.d.ts +14 -4
- package/dist/net/public-address.js +22 -12
- package/dist/net/safe-fetch.d.ts +2 -1
- package/dist/net/safe-fetch.js +16 -4
- package/dist/overrides.d.ts +3 -0
- package/dist/overrides.js +2 -0
- package/dist/packages/npm.d.ts +28 -9
- package/dist/packages/npm.js +30 -19
- package/dist/packages/provenance.d.ts +3 -1
- package/dist/packages/provenance.js +7 -3
- package/dist/platform/ops/devices.ops.js +1 -1
- package/dist/platform/ops/platform.ops.d.ts +3 -1
- package/dist/platform/ops/platform.ops.js +11 -13
- package/dist/runtime/context/build.d.ts +10 -1
- package/dist/runtime/context/build.js +44 -10
- package/dist/runtime/context/compaction.d.ts +27 -8
- package/dist/runtime/context/compaction.js +133 -58
- package/dist/runtime/context/fit.d.ts +54 -22
- package/dist/runtime/context/fit.js +116 -40
- package/dist/runtime/model-call.d.ts +0 -8
- package/dist/runtime/model-call.js +185 -83
- package/dist/sandbox/review/classifier.d.ts +2 -0
- package/dist/sandbox/review/classifier.js +12 -1
- package/dist/sandbox/review/index.d.ts +3 -3
- package/dist/sandbox/review/index.js +3 -3
- package/dist/sandbox/review/review.service.d.ts +12 -4
- package/dist/sandbox/review/review.service.js +88 -19
- package/dist/sandbox/review/rules.d.ts +6 -0
- package/dist/sandbox/review/rules.js +1013 -95
- package/dist/sandbox/review/types.d.ts +21 -4
- package/dist/sandbox/review/types.js +41 -5
- package/dist/sandbox/sandbox.service.d.ts +8 -7
- package/dist/sandbox/sandbox.service.js +16 -16
- package/dist/setup/kernel-checks.js +3 -2
- package/dist/setup/oauth-token-probe.d.ts +1 -8
- package/dist/setup/oauth-token-probe.js +0 -16
- package/dist/tools/builtins/sandbox/common.d.ts +1 -1
- package/dist/tools/builtins/sandbox/common.js +1 -1
- package/dist/tools/builtins/tool-search.js +4 -3
- package/dist/tools/oauth/discovery.d.ts +38 -16
- package/dist/tools/oauth/discovery.js +59 -33
- package/dist/tools/pipeline.js +17 -13
- package/package.json +3 -3
package/dist/packages/npm.js
CHANGED
|
@@ -1,14 +1,24 @@
|
|
|
1
1
|
import { createHash, timingSafeEqual } from "node:crypto";
|
|
2
2
|
import { isIP } from "node:net";
|
|
3
3
|
import semver from "semver";
|
|
4
|
+
import { NetDeniedError } from "../net/public-address.js";
|
|
5
|
+
import { safeFetch } from "../net/safe-fetch.js";
|
|
4
6
|
/**
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* -
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
7
|
+
* Downloads plugin packages from an npm registry (D14 / C21 / C26). The registry URL comes from
|
|
8
|
+
* the config (trusted), but whatever it returns is external input:
|
|
9
|
+
* - every request goes through `packages/kernel/src/net` ({@link safeFetch}) under `cfg.net`
|
|
10
|
+
* (the kernel passes `marketplaceNetPolicy`: the registry's origin is trusted, any other host
|
|
11
|
+
* must resolve to public addresses unless `marketplaces.allowPrivateHosts` exempts it, https
|
|
12
|
+
* tunnels through `net.httpsProxy`, and the connection is pinned to the checked address);
|
|
13
|
+
* - redirects are never followed (a 3xx fails): one registry redirect could otherwise send the
|
|
14
|
+
* download (and the token) anywhere;
|
|
15
|
+
* - metadata and tarball are counted while read and aborted past their caps;
|
|
16
|
+
* - without `opts` the tarball must be on the registry's origin (the only origin the token goes
|
|
17
|
+
* to) and is verified against the packument's `dist.integrity` (sha512 SRI); with
|
|
18
|
+
* `opts.expectedIntegrity` (marketplace imports, T24) only that integrity counts;
|
|
19
|
+
* - `opts.tarballUrl` (a download URL the marketplace gives) must be https (loopback http in tests
|
|
20
|
+
* under `net.allowInsecureLoopback`), needs `expectedIntegrity`, and never gets the registry
|
|
21
|
+
* token unless it is on the registry's origin.
|
|
12
22
|
*/
|
|
13
23
|
/** 下载或校验失败(HTTP 层映射为 `packages.npm_failed`,502)。消息为英文,不含令牌。 */
|
|
14
24
|
export class NpmFetchError extends Error {
|
|
@@ -77,18 +87,21 @@ export async function readCapped(res, max, onTooLarge) {
|
|
|
77
87
|
}
|
|
78
88
|
return Buffer.concat(chunks);
|
|
79
89
|
}
|
|
80
|
-
|
|
90
|
+
/**
|
|
91
|
+
* One GET through {@link safeFetch} under `cfg.net` (no redirects, the network rules); a refusal,
|
|
92
|
+
* a network error or a non-2xx answer is an {@link NpmFetchError} with an English message.
|
|
93
|
+
*/
|
|
94
|
+
export async function npmGet(cfg, url, headers, signal, what) {
|
|
81
95
|
let res;
|
|
82
96
|
try {
|
|
83
|
-
res = await
|
|
97
|
+
res = await safeFetch(url.toString(), { headers, signal }, cfg.net, cfg.lookup !== undefined ? { lookup: cfg.lookup } : {});
|
|
84
98
|
}
|
|
85
99
|
catch (e) {
|
|
100
|
+
if (e instanceof NetDeniedError && e.code === "net.redirect") {
|
|
101
|
+
throw new NpmFetchError(`the ${what} responded with a redirect (${e.status}); redirects are not followed`, { cause: e });
|
|
102
|
+
}
|
|
86
103
|
throw new NpmFetchError(`cannot fetch the ${what}: ${errMsg(e)}`, { cause: e });
|
|
87
104
|
}
|
|
88
|
-
if (res.status >= 300 && res.status < 400) {
|
|
89
|
-
await res.body?.cancel().catch(() => { });
|
|
90
|
-
throw new NpmFetchError(`the ${what} responded with a redirect (${res.status}); redirects are not followed`);
|
|
91
|
-
}
|
|
92
105
|
if (!res.ok) {
|
|
93
106
|
await res.body?.cancel().catch(() => { });
|
|
94
107
|
throw new NpmFetchError(`the ${what} responded with HTTP ${res.status}`);
|
|
@@ -145,13 +158,11 @@ export async function fetchNpmPackage(cfg, name, version, signal, opts = {}) {
|
|
|
145
158
|
catch {
|
|
146
159
|
throw new NpmFetchError("the tarball URL is not a valid URL");
|
|
147
160
|
}
|
|
148
|
-
const insecureOk = cfg.allowInsecureLoopback ===
|
|
149
|
-
tarball.protocol === "http:" &&
|
|
150
|
-
isLoopback(tarball.hostname);
|
|
161
|
+
const insecureOk = cfg.net.allowInsecureLoopback && tarball.protocol === "http:" && isLoopback(tarball.hostname);
|
|
151
162
|
if (tarball.protocol !== "https:" && !insecureOk) {
|
|
152
163
|
throw new NpmFetchError("the tarball URL must use https");
|
|
153
164
|
}
|
|
154
|
-
//
|
|
165
|
+
// the token goes only to the registry origin
|
|
155
166
|
if (tarball.origin !== registry.origin)
|
|
156
167
|
tarballHeaders = {};
|
|
157
168
|
resolved = version;
|
|
@@ -160,7 +171,7 @@ export async function fetchNpmPackage(cfg, name, version, signal, opts = {}) {
|
|
|
160
171
|
else {
|
|
161
172
|
// scope 包名里的 `/` 按 npm 客户端的写法编码为 %2f
|
|
162
173
|
const docUrl = new URL(name.replace("/", "%2f"), registry);
|
|
163
|
-
const res = await
|
|
174
|
+
const res = await npmGet(cfg, docUrl, { ...authHeaders, accept: "application/json" }, signal, "npm registry");
|
|
164
175
|
const raw = await readCapped(res, MAX_METADATA_BYTES, () => new NpmFetchError("the npm package metadata is too large"));
|
|
165
176
|
let doc;
|
|
166
177
|
try {
|
|
@@ -207,7 +218,7 @@ export async function fetchNpmPackage(cfg, name, version, signal, opts = {}) {
|
|
|
207
218
|
throw new NpmFetchError(`npm package ${name}@${picked} has no integrity to verify`);
|
|
208
219
|
resolved = picked;
|
|
209
220
|
}
|
|
210
|
-
const res = await
|
|
221
|
+
const res = await npmGet(cfg, tarball, tarballHeaders, signal, "package tarball");
|
|
211
222
|
const bytes = await readCapped(res, cfg.maxBytes, tooLarge);
|
|
212
223
|
verify(bytes, integrity, opts.expectedIntegrity !== undefined ? "the expected integrity" : "the npm dist.integrity");
|
|
213
224
|
return {
|
|
@@ -6,7 +6,9 @@ import { type NpmFetchConfig } from "./npm.js";
|
|
|
6
6
|
* workflow it was built from. This is display only: the sigstore signatures are not verified, and
|
|
7
7
|
* nothing here ever fails an import. A registry without provenance, a network error, a timeout, an
|
|
8
8
|
* oversized or malformed answer all give `{ checked: false, reason }` ("provenance not checked").
|
|
9
|
-
* The registry token goes only to the registry (the attestation URL is always on its origin).
|
|
9
|
+
* The registry token goes only to the registry (the attestation URL is always on its origin). The
|
|
10
|
+
* request goes through `packages/kernel/src/net` under `cfg.net` like every npm download (no
|
|
11
|
+
* redirects, the network rules, `net.httpsProxy`); a refused address is "not checked" too.
|
|
10
12
|
*/
|
|
11
13
|
/** What the SLSA provenance of an npm package says about its build. */
|
|
12
14
|
export interface Provenance {
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { NetDeniedError } from "../net/public-address.js";
|
|
2
|
+
import { safeFetch } from "../net/safe-fetch.js";
|
|
1
3
|
import { readCapped } from "./npm.js";
|
|
2
4
|
/** The predicate type of an SLSA v1 provenance statement. */
|
|
3
5
|
export const SLSA_PROVENANCE_V1 = "https://slsa.dev/provenance/v1";
|
|
@@ -38,14 +40,13 @@ export async function fetchProvenance(cfg, name, version, signal, opts = {}) {
|
|
|
38
40
|
const registry = new URL(cfg.registry.endsWith("/") ? cfg.registry : `${cfg.registry}/`);
|
|
39
41
|
// the npm client's escaping: a scoped name's `/` is %2f
|
|
40
42
|
const url = new URL(`-/npm/v1/attestations/${name.replace("/", "%2f")}@${encodeURIComponent(version)}`, registry);
|
|
41
|
-
const res = await
|
|
43
|
+
const res = await safeFetch(url.toString(), {
|
|
42
44
|
headers: {
|
|
43
45
|
accept: "application/json",
|
|
44
46
|
...(cfg.token !== undefined && { authorization: `Bearer ${cfg.token}` }),
|
|
45
47
|
},
|
|
46
|
-
redirect: "manual",
|
|
47
48
|
signal,
|
|
48
|
-
});
|
|
49
|
+
}, cfg.net, cfg.lookup !== undefined ? { lookup: cfg.lookup } : {});
|
|
49
50
|
if (res.status === 404) {
|
|
50
51
|
await res.body?.cancel().catch(() => { });
|
|
51
52
|
return notChecked("the registry has no provenance for this version");
|
|
@@ -60,6 +61,9 @@ export async function fetchProvenance(cfg, name, version, signal, opts = {}) {
|
|
|
60
61
|
catch (e) {
|
|
61
62
|
if (signal.aborted)
|
|
62
63
|
return notChecked("the registry did not answer in time");
|
|
64
|
+
if (e instanceof NetDeniedError) {
|
|
65
|
+
return notChecked(`the network rules refused the attestations: ${e.message}`);
|
|
66
|
+
}
|
|
63
67
|
return notChecked(`cannot read the attestations: ${errMsg(e)}`);
|
|
64
68
|
}
|
|
65
69
|
try {
|
|
@@ -131,7 +131,7 @@ let DevicesOperations = class DevicesOperations {
|
|
|
131
131
|
}),
|
|
132
132
|
defineOperation({
|
|
133
133
|
id: "devices.get",
|
|
134
|
-
description: "Read one of your devices with its source (cloud or local), provider, state, instance, the machine of a local one and whether it is online, limits, its mode (the one its commands run at and the one this org allows, and which layer allows auto mode), its network and where that comes from, a pending change that applies on its next use, its recent mode and policy changes, and creation time. Takes the id from devices.list. Only the person changes a device's mode: a local device's on the machine, a cloud device's on
|
|
134
|
+
description: "Read one of your devices with its source (cloud or local), provider, state, instance, the machine of a local one and whether it is online, limits, its mode (the one its commands run at and the one this org allows, and which layer allows auto mode), its network and where that comes from, a pending change that applies on its next use, its recent mode and policy changes, and creation time. Takes the id from devices.list. Only the person changes a device's mode: a local device's on the machine (auto mode is enabled only there), a cloud device's on its device page (to sandbox, or back to following the org's mode).",
|
|
135
135
|
input: DeviceId,
|
|
136
136
|
example: { deviceId: "4e8a0c1d-6b2f-4a37-8d19-3c5e7f9a1b20" },
|
|
137
137
|
authz: { orgAction: "agents.use" },
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type OnModuleInit } from "@nestjs/common";
|
|
2
2
|
import { AgentsService } from "../../agents/agents.service.js";
|
|
3
3
|
import { AccountsService } from "../../identity/accounts.js";
|
|
4
|
+
import { KernelConfigService } from "../../infra/config/kernel-config.service.js";
|
|
4
5
|
import { KernelDb } from "../../infra/database/kernel-db.js";
|
|
5
6
|
import { OrgSettingsService } from "../../orgs/settings.service.js";
|
|
6
7
|
import { ThemesService } from "../../themes/themes.service.js";
|
|
@@ -20,7 +21,8 @@ export declare class PlatformOperationsProvider implements OnModuleInit {
|
|
|
20
21
|
private readonly accounts;
|
|
21
22
|
private readonly themes;
|
|
22
23
|
private readonly db;
|
|
23
|
-
|
|
24
|
+
private readonly config;
|
|
25
|
+
constructor(registry: PlatformOperations, actor: PlatformActor, agents: AgentsService, settings: OrgSettingsService, tools: ToolRegistry, accounts: AccountsService, themes: ThemesService, db: KernelDb, config: KernelConfigService);
|
|
24
26
|
/**
|
|
25
27
|
* The skills in the agent's catalog now, by the names a run's catalog lists them, each with its
|
|
26
28
|
* plugin (skills default-on spec §11): the resolver's result for this conversation, as the next
|
|
@@ -13,9 +13,11 @@ import { AgentsService } from "../../agents/agents.service.js";
|
|
|
13
13
|
import { conversationSourceOf } from "../../conversations/source.js";
|
|
14
14
|
import { AccountsService } from "../../identity/accounts.js";
|
|
15
15
|
import { PreferencesSchema } from "../../identity/me.schemas.js";
|
|
16
|
+
import { KernelConfigService } from "../../infra/config/kernel-config.service.js";
|
|
16
17
|
import { KernelDb } from "../../infra/database/kernel-db.js";
|
|
17
18
|
import { can } from "../../orgs/roles.js";
|
|
18
19
|
import { OrgSettingsService } from "../../orgs/settings.service.js";
|
|
20
|
+
import { effectiveDevicePolicy, readDeploymentDevicePolicy } from "../../sandbox/modes.js";
|
|
19
21
|
import { resolveEffectiveSkills } from "../../skills/catalog.js";
|
|
20
22
|
import { ThemesService } from "../../themes/themes.service.js";
|
|
21
23
|
import { SANDBOX_TOOL_NAMES } from "../../tools/builtin-names.js";
|
|
@@ -53,7 +55,8 @@ let PlatformOperationsProvider = class PlatformOperationsProvider {
|
|
|
53
55
|
accounts;
|
|
54
56
|
themes;
|
|
55
57
|
db;
|
|
56
|
-
|
|
58
|
+
config;
|
|
59
|
+
constructor(registry, actor, agents, settings, tools, accounts, themes, db, config) {
|
|
57
60
|
this.registry = registry;
|
|
58
61
|
this.actor = actor;
|
|
59
62
|
this.agents = agents;
|
|
@@ -62,6 +65,7 @@ let PlatformOperationsProvider = class PlatformOperationsProvider {
|
|
|
62
65
|
this.accounts = accounts;
|
|
63
66
|
this.themes = themes;
|
|
64
67
|
this.db = db;
|
|
68
|
+
this.config = config;
|
|
65
69
|
}
|
|
66
70
|
/**
|
|
67
71
|
* The skills in the agent's catalog now, by the names a run's catalog lists them, each with its
|
|
@@ -149,10 +153,9 @@ let PlatformOperationsProvider = class PlatformOperationsProvider {
|
|
|
149
153
|
this.skillNames(ctx, d),
|
|
150
154
|
]);
|
|
151
155
|
const sandbox = toolKeys.some((k) => SANDBOX_TOOL_NAMES.includes(k));
|
|
152
|
-
|
|
153
|
-
// a
|
|
154
|
-
const
|
|
155
|
-
const mode = deployment.autoMode.mode === "allowed" && org.autoMode !== "off" ? "auto" : "sandbox";
|
|
156
|
+
// a new device's mode and network (auto mode spec §4.3): the one derivation the
|
|
157
|
+
// devices use, so a sandbox-mode device on the open network reads as open
|
|
158
|
+
const policy = effectiveDevicePolicy(await readDeploymentDevicePolicy(this.db.db, this.config), await this.settings.get(ctx.orgId), null);
|
|
156
159
|
return {
|
|
157
160
|
id: agent.id,
|
|
158
161
|
name: d.name,
|
|
@@ -168,13 +171,7 @@ let PlatformOperationsProvider = class PlatformOperationsProvider {
|
|
|
168
171
|
disabledSkills: d.disabledSkills ?? [],
|
|
169
172
|
subagents: d.subagents ?? null,
|
|
170
173
|
sandbox: sandbox
|
|
171
|
-
? {
|
|
172
|
-
enabled: true,
|
|
173
|
-
mode,
|
|
174
|
-
network: mode === "auto" && deployment.cloudNetwork.mode === "open"
|
|
175
|
-
? "open-public"
|
|
176
|
-
: "allowlist",
|
|
177
|
-
}
|
|
174
|
+
? { enabled: true, mode: policy.mode, network: policy.network.kind }
|
|
178
175
|
: { enabled: false },
|
|
179
176
|
profile: {
|
|
180
177
|
avatar: agent.profile.avatar,
|
|
@@ -258,6 +255,7 @@ PlatformOperationsProvider = __decorate([
|
|
|
258
255
|
__param(4, Inject(ToolRegistry)),
|
|
259
256
|
__param(5, Inject(AccountsService)),
|
|
260
257
|
__param(6, Inject(ThemesService)),
|
|
261
|
-
__param(7, Inject(KernelDb))
|
|
258
|
+
__param(7, Inject(KernelDb)),
|
|
259
|
+
__param(8, Inject(KernelConfigService))
|
|
262
260
|
], PlatformOperationsProvider);
|
|
263
261
|
export { PlatformOperationsProvider };
|
|
@@ -217,6 +217,14 @@ type SummaryEvent = ConversationEvent & {
|
|
|
217
217
|
type: "compaction_summary";
|
|
218
218
|
payload: EventPayload<"compaction_summary">;
|
|
219
219
|
};
|
|
220
|
+
/**
|
|
221
|
+
* The user messages a summary re-renders after its text (context compaction spec §4.2, revision
|
|
222
|
+
* 2026-11-15): exactly the ones its `openingSeqs` names, in seq order, decided when the summary was
|
|
223
|
+
* written. A summary without the field (every older log) re-renders nothing. `events` sorted by seq.
|
|
224
|
+
*/
|
|
225
|
+
export declare function summaryOpeners(events: readonly ConversationEvent[], summary: SummaryEvent | null): (ConversationEvent & {
|
|
226
|
+
type: "user_message";
|
|
227
|
+
})[];
|
|
220
228
|
/** 最近一条 `compaction_summary` 事件(按 seq);没有则 null。 */
|
|
221
229
|
export declare function latestSummary(events: ConversationEvent[]): SummaryEvent | null;
|
|
222
230
|
/** 摘要作为首条 user 消息时的文本。 */
|
|
@@ -229,7 +237,8 @@ export declare function summaryText(summary: string): string;
|
|
|
229
237
|
* 第二个块是工具目录(见 {@link BuildModelRequestInput.toolSearch});
|
|
230
238
|
* - 之后的 `skills_catalog` 在所在位置渲染为 system 变更提醒;被压缩摘要覆盖的,若摘要时生效的目录与 system 里的
|
|
231
239
|
* 不同,紧随摘要补一条完整的当前目录;
|
|
232
|
-
* - messages:最近一条摘要(若有)作为首条 user
|
|
240
|
+
* - messages:最近一条摘要(若有)作为首条 user 消息(摘要切在用户轮次内部时,该轮的开头消息按普通
|
|
241
|
+
* user_message 的渲染接在摘要文本之后、同一条消息里:摘要的 `openingSeqs`,{@link summaryOpeners}),其后按 seq 回放 `coversUpToSeq` 之后的
|
|
233
242
|
* `user_message` / `assistant_message`(content 原样,含 opaque;aborted 的也回放;媒体引用按
|
|
234
243
|
* {@link resolveMedia} 换成 base64 或文字占位)/ `reminder`
|
|
235
244
|
* (`role: "system"`,放在它所在的位置)/ `tools_changed` (`role: "system"`, the text of {@link toolsChangedText}, at its position) /
|
|
@@ -54,13 +54,18 @@ function mediaMode(b, model) {
|
|
|
54
54
|
return "bytes";
|
|
55
55
|
return isText(b.mediaType) ? "inline" : "placeholder";
|
|
56
56
|
}
|
|
57
|
-
/**
|
|
57
|
+
/**
|
|
58
|
+
* 最近摘要之后、会进请求的消息里,该模型需要字节的媒体块(按 seq 与块顺序);也包括随摘要再次发送的
|
|
59
|
+
* 用户消息(摘要的 `openingSeqs`,{@link summaryOpeners})。
|
|
60
|
+
*/
|
|
58
61
|
function mediaBlocks(events, model) {
|
|
59
62
|
const sorted = [...events].sort((a, b) => a.seq - b.seq);
|
|
60
|
-
const
|
|
63
|
+
const summary = latestSummary(sorted);
|
|
64
|
+
const after = summary?.payload.coversUpToSeq ?? Number.NEGATIVE_INFINITY;
|
|
65
|
+
const openers = new Set(summaryOpeners(sorted, summary));
|
|
61
66
|
const out = [];
|
|
62
67
|
for (const e of sorted) {
|
|
63
|
-
if (e.seq <= after)
|
|
68
|
+
if (e.seq <= after && !openers.has(e))
|
|
64
69
|
continue;
|
|
65
70
|
if (e.type !== "user_message" && e.type !== "assistant_message")
|
|
66
71
|
continue;
|
|
@@ -313,6 +318,17 @@ export function resolveMedia(content, model, ctx) {
|
|
|
313
318
|
}
|
|
314
319
|
return { blocks: out, tokens, outcomes };
|
|
315
320
|
}
|
|
321
|
+
/**
|
|
322
|
+
* The user messages a summary re-renders after its text (context compaction spec §4.2, revision
|
|
323
|
+
* 2026-11-15): exactly the ones its `openingSeqs` names, in seq order, decided when the summary was
|
|
324
|
+
* written. A summary without the field (every older log) re-renders nothing. `events` sorted by seq.
|
|
325
|
+
*/
|
|
326
|
+
export function summaryOpeners(events, summary) {
|
|
327
|
+
const seqs = new Set(summary?.payload.openingSeqs ?? []);
|
|
328
|
+
if (seqs.size === 0)
|
|
329
|
+
return [];
|
|
330
|
+
return events.filter((e) => e.type === "user_message" && seqs.has(e.seq));
|
|
331
|
+
}
|
|
316
332
|
/** 最近一条 `compaction_summary` 事件(按 seq);没有则 null。 */
|
|
317
333
|
export function latestSummary(events) {
|
|
318
334
|
let found = null;
|
|
@@ -334,7 +350,8 @@ export function summaryText(summary) {
|
|
|
334
350
|
* 第二个块是工具目录(见 {@link BuildModelRequestInput.toolSearch});
|
|
335
351
|
* - 之后的 `skills_catalog` 在所在位置渲染为 system 变更提醒;被压缩摘要覆盖的,若摘要时生效的目录与 system 里的
|
|
336
352
|
* 不同,紧随摘要补一条完整的当前目录;
|
|
337
|
-
* - messages:最近一条摘要(若有)作为首条 user
|
|
353
|
+
* - messages:最近一条摘要(若有)作为首条 user 消息(摘要切在用户轮次内部时,该轮的开头消息按普通
|
|
354
|
+
* user_message 的渲染接在摘要文本之后、同一条消息里:摘要的 `openingSeqs`,{@link summaryOpeners}),其后按 seq 回放 `coversUpToSeq` 之后的
|
|
338
355
|
* `user_message` / `assistant_message`(content 原样,含 opaque;aborted 的也回放;媒体引用按
|
|
339
356
|
* {@link resolveMedia} 换成 base64 或文字占位)/ `reminder`
|
|
340
357
|
* (`role: "system"`,放在它所在的位置)/ `tools_changed` (`role: "system"`, the text of {@link toolsChangedText}, at its position) /
|
|
@@ -473,15 +490,29 @@ export function buildModelRequest(input) {
|
|
|
473
490
|
}
|
|
474
491
|
racedPending = racedPending.filter((x) => x.seq > toSeq);
|
|
475
492
|
};
|
|
476
|
-
/**
|
|
477
|
-
|
|
493
|
+
/**
|
|
494
|
+
* Context compaction spec §4.2 (revision 2026-11-15): the user messages that started the run the
|
|
495
|
+
* summary cuts into, covered by it, are sent again right after the summary text (exactly the
|
|
496
|
+
* summary's `openingSeqs`).
|
|
497
|
+
*/
|
|
498
|
+
const openers = summaryOpeners(events, summary);
|
|
499
|
+
const openerSet = new Set(openers);
|
|
500
|
+
/**
|
|
501
|
+
* Run context spec §4: the sender lines, by the messages after the summary boundary (and the
|
|
502
|
+
* re-sent opening messages first, which then count as the messages before them).
|
|
503
|
+
*/
|
|
504
|
+
const firstOpener = openers[0];
|
|
505
|
+
const senders = firstOpener !== undefined
|
|
506
|
+
? senderLines(events.filter((e) => e.seq > after || openerSet.has(e)), firstOpener.seq - 1)
|
|
507
|
+
: senderLines(events, after);
|
|
478
508
|
/**
|
|
479
509
|
* A user message's blocks: its sender line first when the sender changed (a separate block, so
|
|
480
510
|
* `content[0]` stays the typed text), then a scheduled task's header (scheduled tasks spec §12,
|
|
481
|
-
* from the marker in the log), then its own blocks, then its fork report when it has one
|
|
511
|
+
* from the marker in the log), then its own blocks, then its fork report when it has one (never
|
|
512
|
+
* for the re-sent opening message: its report follows the rules of a covered invocation).
|
|
482
513
|
*/
|
|
483
|
-
const userBlocks = (u) => {
|
|
484
|
-
const report = forkReports.get(u.seq);
|
|
514
|
+
const userBlocks = (u, withReport = true) => {
|
|
515
|
+
const report = withReport ? forkReports.get(u.seq) : undefined;
|
|
485
516
|
const line = senders.get(u.seq);
|
|
486
517
|
const schedule = u.payload.schedule;
|
|
487
518
|
const blocks = blocksOf(u.payload.content);
|
|
@@ -549,7 +580,10 @@ export function buildModelRequest(input) {
|
|
|
549
580
|
if (summary) {
|
|
550
581
|
messages.push({
|
|
551
582
|
role: "user",
|
|
552
|
-
content: [
|
|
583
|
+
content: [
|
|
584
|
+
{ type: "text", text: summaryText(summary.payload.text) },
|
|
585
|
+
...openers.flatMap((o) => userBlocks(o, false)),
|
|
586
|
+
],
|
|
553
587
|
});
|
|
554
588
|
// run context spec §5: snapshots covered by the summary are not rendered; the context in
|
|
555
589
|
// effect at the summary's boundary follows it whole
|
|
@@ -10,8 +10,9 @@ export declare const COMPACTION_MARKER = "CAPYBARA_COMPACTION";
|
|
|
10
10
|
*/
|
|
11
11
|
export declare const COMPACTION_MAX_OUTPUT_TOKENS = 20000;
|
|
12
12
|
/**
|
|
13
|
-
* The input room
|
|
14
|
-
*
|
|
13
|
+
* The input room one summary call leaves below the compaction model's window (context compaction
|
|
14
|
+
* spec §4.5, `B = Wc - Cmax - R`): the summary call's own output cap and the safety reserve are never
|
|
15
|
+
* spent on its input. A step's request plans with {@link planningBounds} instead.
|
|
15
16
|
*/
|
|
16
17
|
export declare function compactionInputBudget(window: number, maxOutput: number, reserve: number): number;
|
|
17
18
|
/**
|
|
@@ -36,9 +37,10 @@ export declare function compactionChunkSize(budget: number, maxOutputTokens: num
|
|
|
36
37
|
export declare const MIN_COMPACTION_CHUNK_TOKENS = 256;
|
|
37
38
|
/**
|
|
38
39
|
* Compaction trigger (context compaction spec §4.1): the calibrated estimate reaches the lower of
|
|
39
|
-
* `threshold × window` and the input
|
|
40
|
-
*
|
|
41
|
-
*
|
|
40
|
+
* `threshold × window` and the input target `W - O_p - R_p` (the planning bounds,
|
|
41
|
+
* {@link planningBounds}), or it reaches the hard line `estimate + O_p > window`, which fires even
|
|
42
|
+
* when proactive early compaction is turned off (`enabled: false`). `settings.maxOutputTokens` here
|
|
43
|
+
* carries `O`, the request's output cap (§4.1), not the summary cap (§4.8).
|
|
42
44
|
*/
|
|
43
45
|
export declare function shouldCompact(estimate: number, window: number, settings: CompactionSettings): boolean;
|
|
44
46
|
/**
|
|
@@ -48,14 +50,31 @@ export declare function shouldCompact(estimate: number, window: number, settings
|
|
|
48
50
|
*
|
|
49
51
|
* The kept tail shrinks turn by turn, down to the latest user turn, until its estimated tokens fit
|
|
50
52
|
* `budget` — the input room left after the output cap, the reserve, the system prompt and the tool
|
|
51
|
-
* definitions.
|
|
52
|
-
*
|
|
53
|
-
*
|
|
53
|
+
* definitions. When the latest user turn alone does not fit (context compaction spec §4.2, revision
|
|
54
|
+
* 2026-11-15), the boundary moves inside it, to tool-pair boundaries oldest first, until the tail
|
|
55
|
+
* fits or only the latest tool pair (the latest assistant message with tool calls, and what follows
|
|
56
|
+
* it) is left; the summary then covers the turn's user message, which request building shows again
|
|
57
|
+
* right after the summary (build.ts). A latest turn without a tool pair is kept whole (the hard fit
|
|
58
|
+
* guard handles the rest). `coversUpToSeq` is the largest seq before the first kept event. Returns
|
|
59
|
+
* null when there is nothing to summarize.
|
|
54
60
|
*/
|
|
55
61
|
export declare function compactionPlan(events: ConversationEvent[], settings: CompactionSettings, budget: number): {
|
|
56
62
|
coversUpToSeq: number;
|
|
57
63
|
transcript: string;
|
|
58
64
|
} | null;
|
|
65
|
+
/**
|
|
66
|
+
* The user messages that started run `runId`, among those a summary covering up to
|
|
67
|
+
* `coversUpToSeq` covers (context compaction spec §4.2, revision 2026-11-15): recorded in the
|
|
68
|
+
* summary as `openingSeqs` when it is written, so request building re-renders exactly these after
|
|
69
|
+
* the summary text and a request never depends on later events. The opening messages are the user
|
|
70
|
+
* messages the run's first model call absorbed (`absorbedUpToSeq` of that call, or of the request
|
|
71
|
+
* about to be built when the run has made none yet) that no earlier turn answered or absorbed:
|
|
72
|
+
* after the latest assistant message and model call before the run's `run_started`.
|
|
73
|
+
* Several when the person sent several before the first call. None for a run that no message
|
|
74
|
+
* started (a finished background task or a sub-agent's delivery woke it, a manual compact run),
|
|
75
|
+
* and a covered interjection (after the first call) is never one. Sorted by seq.
|
|
76
|
+
*/
|
|
77
|
+
export declare function openingSeqs(events: readonly ConversationEvent[], runId: string, coversUpToSeq: number, absorbedUpToSeq?: number): number[];
|
|
59
78
|
/**
|
|
60
79
|
* The text to store as the compaction summary (context compaction spec §4.2.1): the `<summary>`
|
|
61
80
|
* block when the model returned one, since the `<analysis>` scratchpad must never be sent in a
|