@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
|
@@ -5,8 +5,8 @@ import { ApiError } from "../errors.js";
|
|
|
5
5
|
import { ExtensionUnloadedError } from "../extensions/inflight.js";
|
|
6
6
|
import { hasInvocation, skillLoadOffered } from "../skills/catalog.js";
|
|
7
7
|
import { buildModelRequest, latestSummary, mediaRefs, planMedia, } from "./context/build.js";
|
|
8
|
-
import { acceptSummary, buildCompactionRequest, chunkTranscript, compactionBackoff, compactionChunkSize, compactionInputBudget, compactionPlan, compactionRequestOverhead, extractSummary, MIN_COMPACTION_CHUNK_TOKENS, nextTranscriptChunk, shouldCompact, summarySavedTokens, } from "./context/compaction.js";
|
|
9
|
-
import { applyFit,
|
|
8
|
+
import { acceptSummary, buildCompactionRequest, chunkTranscript, compactionBackoff, compactionChunkSize, compactionInputBudget, compactionPlan, compactionRequestOverhead, extractSummary, MIN_COMPACTION_CHUNK_TOKENS, nextTranscriptChunk, openingSeqs, shouldCompact, summarySavedTokens, } from "./context/compaction.js";
|
|
9
|
+
import { applyFit, estimateAfterFit, planFit, planningBounds, planReactiveTrim, planSqueezedFit, sentOutputCap, } from "./context/fit.js";
|
|
10
10
|
import { guardToolPairs } from "./context/pairing.js";
|
|
11
11
|
import { TOOLS_UNSUPPORTED_REMINDER, turnLimitReminder } from "./context/reminders.js";
|
|
12
12
|
import { calibrate, estimateTokens } from "./context/tokens.js";
|
|
@@ -95,14 +95,6 @@ export const MAX_MODEL_ATTEMPTS = 3;
|
|
|
95
95
|
* so a persistent `model.context_overflow` cannot loop.
|
|
96
96
|
*/
|
|
97
97
|
export const MAX_STEP_MODEL_CALLS = MAX_MODEL_ATTEMPTS + 2;
|
|
98
|
-
/**
|
|
99
|
-
* The progressively smaller fit targets of a reactive trim, as fractions of the model's window
|
|
100
|
-
* (context compaction spec §4.3 point 5 / §4.4 point 3). The trim fix-up tries them most
|
|
101
|
-
* aggressive first (70%, then 80%, then 90% of the window) and uses the first target a fit plan
|
|
102
|
-
* actually reaches, so the retry really shrinks a request the provider rejected. `null` when the
|
|
103
|
-
* request already fits every target (nothing to trim).
|
|
104
|
-
*/
|
|
105
|
-
export const REACTIVE_TRIM_FACTORS = [0.9, 0.8, 0.7];
|
|
106
98
|
/**
|
|
107
99
|
* The agent's tools for one request, resolved now (connectors and extensions can change between
|
|
108
100
|
* steps): disabled tools and disabled sub-agent tools, a sub-agent's narrower roster, sandbox
|
|
@@ -154,23 +146,57 @@ const idem = {
|
|
|
154
146
|
modelCall: modelCallIdemKey,
|
|
155
147
|
hookDenied: (runId, step, attempt) => `hook_denied:${runId}:${step}:${attempt}`,
|
|
156
148
|
/**
|
|
157
|
-
* Usage of a compaction call: `n` is the compaction
|
|
158
|
-
* chunked compaction sends one call per chunk, so the chunk index
|
|
159
|
-
* (context compaction spec §4.5).
|
|
149
|
+
* Usage of a compaction call: `n` is the compaction's ordinal in the step
|
|
150
|
+
* ({@link compactionOrdinal}). A chunked compaction sends one call per chunk, so the chunk index
|
|
151
|
+
* (1-based) is part of the key (context compaction spec §4.5).
|
|
160
152
|
*/
|
|
161
153
|
compactionUsage: (runId, step, n, chunk) => chunk === undefined
|
|
162
154
|
? `usage_compaction:${runId}:${step}:${n}`
|
|
163
155
|
: `usage_compaction:${runId}:${step}:${n}:${chunk}`,
|
|
164
156
|
/**
|
|
165
|
-
* The outcome of one compaction
|
|
166
|
-
*
|
|
167
|
-
*
|
|
157
|
+
* The outcome of one compaction: `n` is its ordinal in the step ({@link compactionOrdinal}), so a
|
|
158
|
+
* proactive summary and a forced one in the same step are two events (spec §4.4, revision
|
|
159
|
+
* 2026-11-15). Retrying the same compaction after a crash writes nothing new; a manual compact run
|
|
160
|
+
* is keyed by its run id and step 0 (context compaction spec §4.7).
|
|
168
161
|
*/
|
|
169
162
|
compactionSummary: (runId, step, n) => `compaction_summary:${runId}:${step}:${n}`,
|
|
170
163
|
compactionFailed: (runId, step, n) => `compaction_failed:${runId}:${step}:${n}`,
|
|
171
164
|
mediaExcluded: (runId, step, attempt, part) => `media_excluded:${runId}:${step}:${attempt}:${part}`,
|
|
172
165
|
};
|
|
173
|
-
/**
|
|
166
|
+
/** The step result of a sub-agent whose budget a compaction call used up: no step request. */
|
|
167
|
+
const BUDGET_STOP = {
|
|
168
|
+
content: [],
|
|
169
|
+
stopReason: "end_turn",
|
|
170
|
+
reused: false,
|
|
171
|
+
aborted: false,
|
|
172
|
+
usage: null,
|
|
173
|
+
budget: true,
|
|
174
|
+
};
|
|
175
|
+
/** A forced compaction in the ladder used up the sub-agent's budget (see {@link BUDGET_STOP}). */
|
|
176
|
+
class BudgetUsedUp extends Error {
|
|
177
|
+
constructor() {
|
|
178
|
+
super("sub-agent budget used up by a compaction call");
|
|
179
|
+
this.name = "BudgetUsedUp";
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* A sub-agent checks its budget again after a compaction call, so the step's own request is not a
|
|
184
|
+
* second call over the cap (review M5; the loop checks before each step); the budget wrap-up is the
|
|
185
|
+
* one call allowed over it.
|
|
186
|
+
*/
|
|
187
|
+
async function budgetUsedUpAfterCompaction(deps, input, wrapUpReason) {
|
|
188
|
+
if (wrapUpReason === "budget" || input.parentRunId === undefined)
|
|
189
|
+
return false;
|
|
190
|
+
return subagentBudgetUsedUp(deps.db, deps.config, input.orgId, input.parent?.budgetRunId ?? (await budgetRunOf(deps.db, input.parentRunId)));
|
|
191
|
+
}
|
|
192
|
+
/** The reactive trim cannot reach any of its targets: no trim retry (spec §4.3 point 6). */
|
|
193
|
+
class NoReactiveTrim extends Error {
|
|
194
|
+
constructor() {
|
|
195
|
+
super("no reachable reactive trim");
|
|
196
|
+
this.name = "NoReactiveTrim";
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
/** The external signal fired: the step ends as aborted. */
|
|
174
200
|
class StepAborted extends Error {
|
|
175
201
|
constructor() {
|
|
176
202
|
super("model step aborted");
|
|
@@ -239,18 +265,9 @@ wrapUpReason) {
|
|
|
239
265
|
// a sub-agent checks its budget again after a compaction call, so the step's own request is
|
|
240
266
|
// not a second call over the cap (review M5; the loop checks before each step); the budget
|
|
241
267
|
// wrap-up is the one call allowed over it
|
|
242
|
-
if (
|
|
243
|
-
input
|
|
244
|
-
|
|
245
|
-
(await subagentBudgetUsedUp(deps.db, deps.config, input.orgId, input.parent?.budgetRunId ?? (await budgetRunOf(deps.db, input.parentRunId))))) {
|
|
246
|
-
return {
|
|
247
|
-
content: [],
|
|
248
|
-
stopReason: "end_turn",
|
|
249
|
-
reused: false,
|
|
250
|
-
aborted: false,
|
|
251
|
-
usage: null,
|
|
252
|
-
budget: true,
|
|
253
|
-
};
|
|
268
|
+
if (events.length !== beforeCompaction &&
|
|
269
|
+
(await budgetUsedUpAfterCompaction(deps, input, wrapUpReason))) {
|
|
270
|
+
return BUDGET_STOP;
|
|
254
271
|
}
|
|
255
272
|
// the tool set changed since the previous request (an extension switched on, a sub-agent
|
|
256
273
|
// roster added): tell the model before this request (tool naming spec §9.1). Keyed by the new
|
|
@@ -286,7 +303,18 @@ wrapUpReason) {
|
|
|
286
303
|
});
|
|
287
304
|
}
|
|
288
305
|
}
|
|
289
|
-
|
|
306
|
+
let laddered;
|
|
307
|
+
try {
|
|
308
|
+
laddered = await ladder(deps, input, events, runtime, compaction, tools, wrapUpReason, streamed);
|
|
309
|
+
}
|
|
310
|
+
catch (e) {
|
|
311
|
+
// a forced compaction inside the ladder used up a sub-agent's budget (the same check as
|
|
312
|
+
// after the proactive compaction above)
|
|
313
|
+
if (e instanceof BudgetUsedUp)
|
|
314
|
+
return BUDGET_STOP;
|
|
315
|
+
throw e;
|
|
316
|
+
}
|
|
317
|
+
const { outcome, ref } = laddered;
|
|
290
318
|
// assistant_message and usage in one append = one transaction, which also owes the usage's
|
|
291
319
|
// usage.report delivery (transactional outbox spec §8.1)
|
|
292
320
|
await appendCounted(deps, input, [
|
|
@@ -569,6 +597,40 @@ function consecutiveCompactionFailures(events) {
|
|
|
569
597
|
}
|
|
570
598
|
return n;
|
|
571
599
|
}
|
|
600
|
+
/** The step an event of a run belongs to, when its payload names one. */
|
|
601
|
+
function stepOf(e) {
|
|
602
|
+
const step = e.payload.step;
|
|
603
|
+
return typeof step === "number" ? step : undefined;
|
|
604
|
+
}
|
|
605
|
+
/**
|
|
606
|
+
* The ordinal of the next compaction of this run's `step`: 1 + the `compaction_summary` /
|
|
607
|
+
* `compaction_failed` events the step already wrote (context compaction spec §4.4, revision
|
|
608
|
+
* 2026-11-15). It keys the compaction's events (summary, failure, usage, hook denial), so every
|
|
609
|
+
* compaction of a step writes its own, while a crash-retried compaction (nothing written yet) gets
|
|
610
|
+
* the same keys again. Outcome events record their step, so they are counted by it. Older ones
|
|
611
|
+
* have none: a run's step N compacts after every event of its earlier steps, so those are counted
|
|
612
|
+
* from the run's last event of an earlier step on. The backoff keeps counting consecutive failures
|
|
613
|
+
* ({@link consecutiveCompactionFailures}).
|
|
614
|
+
*/
|
|
615
|
+
function compactionOrdinal(events, runId, step) {
|
|
616
|
+
let recorded = 0;
|
|
617
|
+
let legacy = 0;
|
|
618
|
+
for (const e of events) {
|
|
619
|
+
if (e.runId !== runId)
|
|
620
|
+
continue;
|
|
621
|
+
const of = stepOf(e);
|
|
622
|
+
if (e.type === "compaction_summary" || e.type === "compaction_failed") {
|
|
623
|
+
if (of === undefined)
|
|
624
|
+
legacy++;
|
|
625
|
+
else if (of === step)
|
|
626
|
+
recorded++;
|
|
627
|
+
continue;
|
|
628
|
+
}
|
|
629
|
+
if (of !== undefined && of < step)
|
|
630
|
+
legacy = 0;
|
|
631
|
+
}
|
|
632
|
+
return recorded + legacy + 1;
|
|
633
|
+
}
|
|
572
634
|
/** Estimated input tokens of a plain text (a user message's only content). */
|
|
573
635
|
function textTokens(text) {
|
|
574
636
|
return estimateTokens([{ role: "user", content: [{ type: "text", text }] }], []);
|
|
@@ -625,23 +687,26 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
|
|
|
625
687
|
// The trigger's output cap is the step's own cap, min(agent max, model max) (spec §4.1), not the
|
|
626
688
|
// settings' maxOutputTokens — that one caps the summary call (spec §4.8).
|
|
627
689
|
const output = built.maxOutputTokens;
|
|
690
|
+
// planned with the bounds every step request uses (spec §4.1): O_p and R_p
|
|
691
|
+
const bounds = planningBounds(info.contextWindow, output, compaction.reserveTokens);
|
|
628
692
|
// The hard line ignores both gates: enabled: false turns proactive early compaction off only,
|
|
629
693
|
// and backoff only delays proactive attempts (context compaction spec §4.1). The reactive path
|
|
630
694
|
// (`force`) ignores the trigger entirely (spec §4.4).
|
|
631
695
|
if (!opts.force) {
|
|
632
|
-
if (estimate + output <= info.contextWindow && compactionBackoff(events))
|
|
696
|
+
if (estimate + bounds.output <= info.contextWindow && compactionBackoff(events))
|
|
633
697
|
return skipped(events);
|
|
634
698
|
if (!shouldCompact(estimate, info.contextWindow, { ...compaction, maxOutputTokens: output })) {
|
|
635
699
|
return skipped(events);
|
|
636
700
|
}
|
|
637
701
|
}
|
|
638
|
-
// the input room left for the kept tail: the
|
|
639
|
-
//
|
|
640
|
-
const tailBudget =
|
|
641
|
-
estimateTokens([], built.system, built.tools);
|
|
702
|
+
// the input room left for the kept tail: the planning target `W - O_p - R_p`, minus the system
|
|
703
|
+
// prompt and tool definitions every request carries
|
|
704
|
+
const tailBudget = bounds.target - estimateTokens([], built.system, built.tools);
|
|
642
705
|
const plan = compactionPlan(events, compaction, tailBudget);
|
|
643
706
|
if (!plan)
|
|
644
707
|
return skipped(events);
|
|
708
|
+
// decided now and recorded in the summary (spec §4.2): the request never depends on later events
|
|
709
|
+
const opening = openingSeqs(events, input.runId, plan.coversUpToSeq, input.absorbedUpToSeq);
|
|
645
710
|
const { runId, step, signal, conversationId } = input;
|
|
646
711
|
const ref = modelRef;
|
|
647
712
|
// §4.6 progress: from here the compaction is certain, so the conversation may show a row. It is
|
|
@@ -659,7 +724,9 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
|
|
|
659
724
|
// the summary call's output cap: the org's effective setting, never above the model's own cap
|
|
660
725
|
// (context compaction spec §4.8)
|
|
661
726
|
const summaryCap = Math.min(compaction.maxOutputTokens, info.maxOutputTokens);
|
|
727
|
+
// the payload's attempt drives the backoff; the keys use the compaction's ordinal in the step
|
|
662
728
|
const attemptNo = consecutiveCompactionFailures(events) + 1;
|
|
729
|
+
const ordinal = compactionOrdinal(events, runId, step);
|
|
663
730
|
// hooks see compaction calls like step attempts (I-1): same scope, chat runs only
|
|
664
731
|
const scope = hookScope(deps.hooks, input);
|
|
665
732
|
const hookBase = scope && {
|
|
@@ -848,7 +915,7 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
|
|
|
848
915
|
const usageEvents = () => usages.map(({ chunk, usage }) => ({
|
|
849
916
|
type: "usage",
|
|
850
917
|
runId,
|
|
851
|
-
idemKey: idem.compactionUsage(runId, step,
|
|
918
|
+
idemKey: idem.compactionUsage(runId, step, ordinal, chunk),
|
|
852
919
|
payload: {
|
|
853
920
|
step,
|
|
854
921
|
provider: ref.provider,
|
|
@@ -868,7 +935,7 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
|
|
|
868
935
|
runId,
|
|
869
936
|
...(input.accountId !== undefined && { accountId: input.accountId }),
|
|
870
937
|
...(input.agentId !== undefined && { agentId: input.agentId }),
|
|
871
|
-
idemKey: `hook_denied_compaction:${runId}:${step}:${
|
|
938
|
+
idemKey: `hook_denied_compaction:${runId}:${step}:${ordinal}`,
|
|
872
939
|
};
|
|
873
940
|
const denied = hookDeniedEvent(site, "model.request", verdict, { step, attempt: 1 });
|
|
874
941
|
const entry = hookDeniedAudit(site, denied.payload, verdict);
|
|
@@ -876,9 +943,10 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
|
|
|
876
943
|
const failed = {
|
|
877
944
|
type: "compaction_failed",
|
|
878
945
|
runId,
|
|
879
|
-
idemKey: idem.compactionFailed(runId, step,
|
|
946
|
+
idemKey: idem.compactionFailed(runId, step, ordinal),
|
|
880
947
|
payload: {
|
|
881
948
|
attempt: attemptNo,
|
|
949
|
+
step,
|
|
882
950
|
reason: `compaction request blocked by the "${verdict.plugin}" policy hook (${verdict.cause})${chunkNote(multiChunk ? denial.chunk : null)}`,
|
|
883
951
|
},
|
|
884
952
|
};
|
|
@@ -908,20 +976,23 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
|
|
|
908
976
|
type: "compaction_summary",
|
|
909
977
|
runId,
|
|
910
978
|
// the manual compact run's run id is in it; a crash-retried attempt writes nothing twice
|
|
911
|
-
idemKey: idem.compactionSummary(runId, step,
|
|
979
|
+
idemKey: idem.compactionSummary(runId, step, ordinal),
|
|
912
980
|
payload: {
|
|
913
981
|
coversUpToSeq: plan.coversUpToSeq,
|
|
914
982
|
text: summary,
|
|
983
|
+
// the run's opening messages the summary covers: request building re-renders them
|
|
984
|
+
...(opening.length > 0 && { openingSeqs: opening }),
|
|
915
985
|
// what compaction saved: the estimated transcript input minus the stored summary
|
|
916
986
|
// output (context compaction spec §4.9)
|
|
917
987
|
savedTokens: summarySavedTokens(plan.transcript, summary),
|
|
988
|
+
step,
|
|
918
989
|
},
|
|
919
990
|
}
|
|
920
991
|
: {
|
|
921
992
|
type: "compaction_failed",
|
|
922
993
|
runId,
|
|
923
|
-
idemKey: idem.compactionFailed(runId, step,
|
|
924
|
-
payload: { attempt: attemptNo, reason: `${failure}${chunkNote(failedChunk)}` },
|
|
994
|
+
idemKey: idem.compactionFailed(runId, step, ordinal),
|
|
995
|
+
payload: { attempt: attemptNo, step, reason: `${failure}${chunkNote(failedChunk)}` },
|
|
925
996
|
};
|
|
926
997
|
// the compaction calls' usage (I-1): logged with the outcome in one append (one transaction),
|
|
927
998
|
// marked `purpose: "compaction"` so step consumers (calibration, trajectory steps, replay plans)
|
|
@@ -1061,11 +1132,15 @@ async function ladder(deps, input, events, runtime, compaction, tools, wrapUpRea
|
|
|
1061
1132
|
if (forceCompact) {
|
|
1062
1133
|
forceCompact = false;
|
|
1063
1134
|
// the rung's model, not the agent's: a fallback may have a smaller window (spec §4.4)
|
|
1135
|
+
const before = evs;
|
|
1064
1136
|
evs = await maybeCompact(deps, input, evs, runtime, compaction, tools, {
|
|
1065
1137
|
force: true,
|
|
1066
1138
|
ref: rung.ref,
|
|
1067
1139
|
fallback: rung.fallback,
|
|
1068
1140
|
});
|
|
1141
|
+
if (evs !== before && (await budgetUsedUpAfterCompaction(deps, input, wrapUpReason))) {
|
|
1142
|
+
throw new BudgetUsedUp();
|
|
1143
|
+
}
|
|
1069
1144
|
}
|
|
1070
1145
|
if (tools.list.length > 0 && !info.capabilities.tools) {
|
|
1071
1146
|
evs = await appendLocal(deps.eventLog, conversationId, evs, {
|
|
@@ -1084,38 +1159,76 @@ async function ladder(deps, input, events, runtime, compaction, tools, wrapUpRea
|
|
|
1084
1159
|
});
|
|
1085
1160
|
}
|
|
1086
1161
|
const params = attemptParams(agent, info, rung.fallback);
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
// the
|
|
1090
|
-
//
|
|
1091
|
-
//
|
|
1092
|
-
//
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
? reactiveTrimPlan(evs, request, info, request.maxOutputTokens, reserve, estimate)
|
|
1099
|
-
: planFit({
|
|
1162
|
+
// the hard fit guard (context compaction spec §4.3): the target is `W - O_p - R_p` (the
|
|
1163
|
+
// planning bounds, §4.1), a request over it is trimmed deterministically, and only then is
|
|
1164
|
+
// the cap clamped from the input actually sent, keeping the reserve (`clamp(O, 1, W - input
|
|
1165
|
+
// - R_p)`). The plan is recorded and replayed byte-for-byte. The last resorts, in order
|
|
1166
|
+
// (§4.3 point 5): one forced compaction with this rung's model, the squeezed fit, then
|
|
1167
|
+
// `run.context_too_large` before any call.
|
|
1168
|
+
const fit = async () => {
|
|
1169
|
+
await loadMedia(deps, input, evs, info, tools);
|
|
1170
|
+
const built = buildRequest(deps, evs, input, info, params.value, runtime, tools, wrapUp);
|
|
1171
|
+
const { request, estimate } = built;
|
|
1172
|
+
const fitInput = {
|
|
1100
1173
|
events: evs,
|
|
1101
1174
|
request,
|
|
1102
1175
|
model: info,
|
|
1103
1176
|
maxOutputTokens: request.maxOutputTokens,
|
|
1104
|
-
reserveTokens:
|
|
1177
|
+
reserveTokens: compaction.reserveTokens,
|
|
1105
1178
|
estimate,
|
|
1179
|
+
};
|
|
1180
|
+
const { target } = planningBounds(info.contextWindow, request.maxOutputTokens, compaction.reserveTokens);
|
|
1181
|
+
const planned = trimForAttempt ? planReactiveTrim(fitInput) : planFit(fitInput);
|
|
1182
|
+
const reached = planned === null || estimateAfterFit(request, estimate, planned) <= target;
|
|
1183
|
+
return { ...built, fitInput, target, planned, reached };
|
|
1184
|
+
};
|
|
1185
|
+
let fitted = await fit();
|
|
1186
|
+
// the reactive trim reaches none of its targets (or there is nothing to trim): no retry,
|
|
1187
|
+
// the overflow surfaces (spec §4.3 point 6)
|
|
1188
|
+
if (trimForAttempt && fitted.planned === null)
|
|
1189
|
+
throw new NoReactiveTrim();
|
|
1190
|
+
if (!trimForAttempt && !fitted.reached && !compactFixup) {
|
|
1191
|
+
// the strict plan cannot reach the target (a fallback rung with a smaller window, a huge
|
|
1192
|
+
// latest turn): compact once with this rung's model (a fallback's window may be smaller,
|
|
1193
|
+
// spec §4.4), rebuild and plan again within this attempt. It is the rung's compaction
|
|
1194
|
+
// fix-up, so a later context_overflow on this rung goes to the trim.
|
|
1195
|
+
compactFixup = true;
|
|
1196
|
+
const before = evs;
|
|
1197
|
+
evs = await maybeCompact(deps, input, evs, runtime, compaction, tools, {
|
|
1198
|
+
force: true,
|
|
1199
|
+
ref: rung.ref,
|
|
1200
|
+
fallback: rung.fallback,
|
|
1106
1201
|
});
|
|
1107
|
-
|
|
1202
|
+
if (evs !== before) {
|
|
1203
|
+
if (await budgetUsedUpAfterCompaction(deps, input, wrapUpReason)) {
|
|
1204
|
+
throw new BudgetUsedUp();
|
|
1205
|
+
}
|
|
1206
|
+
fitted = await fit();
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
const { request, meta, estimate, fitInput } = fitted;
|
|
1210
|
+
/** `O`: the configured cap (min of the agent's and the model's), before the clamp. */
|
|
1211
|
+
const output = request.maxOutputTokens;
|
|
1212
|
+
let target = fitted.target;
|
|
1213
|
+
let planned = fitted.planned;
|
|
1214
|
+
if (!trimForAttempt && !fitted.reached) {
|
|
1215
|
+
// still out of reach: plan against `W - 1 - R_p` (the output takes what is left, the
|
|
1216
|
+
// reserve stays); the cap sent is clamped after it like any other
|
|
1217
|
+
({ plan: planned, target } = planSqueezedFit(fitInput));
|
|
1218
|
+
}
|
|
1108
1219
|
let sentEstimate = estimate;
|
|
1109
1220
|
if (planned !== null) {
|
|
1110
1221
|
const after = estimateAfterFit(request, estimate, planned);
|
|
1111
|
-
// a reactive trim
|
|
1112
|
-
//
|
|
1222
|
+
// a reactive trim plan reached its target; the ordinary guard stays strict and fails
|
|
1223
|
+
// before any provider call
|
|
1113
1224
|
if (!trimForAttempt && after > target) {
|
|
1114
1225
|
throw new RunError("run.context_too_large", contextTooLargeText(info, target, after));
|
|
1115
1226
|
}
|
|
1116
|
-
sentRequest = applyFit(request, planned);
|
|
1117
1227
|
sentEstimate = after;
|
|
1118
1228
|
}
|
|
1229
|
+
// O' = clamp(O, 1, W - inputAfterFit - R_p): recorded as the request's maxOutputTokens
|
|
1230
|
+
request.maxOutputTokens = sentOutputCap(info.contextWindow, output, sentEstimate, compaction.reserveTokens);
|
|
1231
|
+
const sentRequest = planned === null ? request : applyFit(request, planned);
|
|
1119
1232
|
sentMedia = (meta.media ?? []).flatMap((m) => m.outcome === "bytes" ? [m.attachmentId] : []);
|
|
1120
1233
|
// model.request before model_call: a denied request is never logged as sent nor sent (a denial
|
|
1121
1234
|
// logged before a crash is sticky: runStep checks it before compaction)
|
|
@@ -1213,6 +1326,19 @@ async function ladder(deps, input, events, runtime, compaction, tools, wrapUpRea
|
|
|
1213
1326
|
// a hook denial is final (not retried, not reclassified)
|
|
1214
1327
|
if (err instanceof RunError)
|
|
1215
1328
|
throw err;
|
|
1329
|
+
if (err instanceof BudgetUsedUp)
|
|
1330
|
+
throw err;
|
|
1331
|
+
if (err instanceof NoReactiveTrim) {
|
|
1332
|
+
// nothing was sent for this attempt: it takes no number, and the overflow that asked for
|
|
1333
|
+
// the trim is what the rung ends with (a fallback model, a different window, may remain)
|
|
1334
|
+
attempt--;
|
|
1335
|
+
if (!rung.fallback && agent.fallback) {
|
|
1336
|
+
skipToFallback = true;
|
|
1337
|
+
break;
|
|
1338
|
+
}
|
|
1339
|
+
const f = last;
|
|
1340
|
+
throw new RunError(f.code, f.message);
|
|
1341
|
+
}
|
|
1216
1342
|
const f = classify(err);
|
|
1217
1343
|
if (scope && deps.hooks && sentAt !== undefined) {
|
|
1218
1344
|
fireObserve(deps.hooks, "model.response", {
|
|
@@ -1325,30 +1451,6 @@ async function ladder(deps, input, events, runtime, compaction, tools, wrapUpRea
|
|
|
1325
1451
|
const f = last;
|
|
1326
1452
|
throw new RunError(f.code, f.message);
|
|
1327
1453
|
}
|
|
1328
|
-
/**
|
|
1329
|
-
* The deterministic fit plan for a reactive trim (context compaction spec §4.3 point 5 / §4.4): the
|
|
1330
|
-
* request is trimmed to fit 70%, then 80%, then 90% of the model's window, applying the first target
|
|
1331
|
-
* a plan actually reaches. Most aggressive first: the provider rejected a request the estimate
|
|
1332
|
-
* thought fit, so the retry must really shrink it, not leave the optimistic request unchanged.
|
|
1333
|
-
* Returns null only when the request already fits every target (nothing to trim). The plan is
|
|
1334
|
-
* ordinary and replays byte-for-byte like any other.
|
|
1335
|
-
*/
|
|
1336
|
-
function reactiveTrimPlan(events, request, model, maxOutputTokens, reserveTokens, estimate) {
|
|
1337
|
-
for (let i = REACTIVE_TRIM_FACTORS.length - 1; i >= 0; i--) {
|
|
1338
|
-
const window = Math.max(1, Math.floor(REACTIVE_TRIM_FACTORS[i] * model.contextWindow));
|
|
1339
|
-
const plan = planFit({
|
|
1340
|
-
events,
|
|
1341
|
-
request,
|
|
1342
|
-
model: { ...model, contextWindow: window },
|
|
1343
|
-
maxOutputTokens,
|
|
1344
|
-
reserveTokens,
|
|
1345
|
-
estimate,
|
|
1346
|
-
});
|
|
1347
|
-
if (plan !== null)
|
|
1348
|
-
return plan;
|
|
1349
|
-
}
|
|
1350
|
-
return null;
|
|
1351
|
-
}
|
|
1352
1454
|
/** 不可重试、且可能由请求里的媒体引起的失败:带了媒体字节时写 `media_excluded`(Ruling M8)。 */
|
|
1353
1455
|
const REJECTS_MEDIA = new Set(["model.invalid_request"]);
|
|
1354
1456
|
/**
|
|
@@ -30,6 +30,8 @@ export declare const REVIEW_SYSTEM_PROMPT: string;
|
|
|
30
30
|
export declare const REVIEW_MAX_OUTPUT_TOKENS = 300;
|
|
31
31
|
/** The marker a command (or path) cut to fit the review model's context ends with. */
|
|
32
32
|
export declare const REVIEW_TRUNCATED_MARKER = " [command truncated to fit the review model's context]";
|
|
33
|
+
/** The reason of a classifier allow turned into an ask because the command did not fit. */
|
|
34
|
+
export declare const REVIEW_TRUNCATED_ASK_REASON = "The command is too long for the review to read in full; it needs the person's approval.";
|
|
33
35
|
/** The reason of an `ask` the classifier could not decide (timeout, error, unparseable answer). */
|
|
34
36
|
export declare const REVIEW_ASK_REASON = "The command review could not decide; this command needs the person's approval.";
|
|
35
37
|
/** The reason prefix when a `model.request` policy hook denies the classifier call. */
|
|
@@ -35,6 +35,8 @@ export const REVIEW_SYSTEM_PROMPT = "You decide whether one shell command (or on
|
|
|
35
35
|
export const REVIEW_MAX_OUTPUT_TOKENS = 300;
|
|
36
36
|
/** The marker a command (or path) cut to fit the review model's context ends with. */
|
|
37
37
|
export const REVIEW_TRUNCATED_MARKER = " [command truncated to fit the review model's context]";
|
|
38
|
+
/** The reason of a classifier allow turned into an ask because the command did not fit. */
|
|
39
|
+
export const REVIEW_TRUNCATED_ASK_REASON = "The command is too long for the review to read in full; it needs the person's approval.";
|
|
38
40
|
/** The reason of an `ask` the classifier could not decide (timeout, error, unparseable answer). */
|
|
39
41
|
export const REVIEW_ASK_REASON = "The command review could not decide; this command needs the person's approval.";
|
|
40
42
|
/** The reason prefix when a `model.request` policy hook denies the classifier call. */
|
|
@@ -329,7 +331,16 @@ export async function runClassifier(deps, args) {
|
|
|
329
331
|
}
|
|
330
332
|
observe(deps, hookBase, sent, out, null, args.signal);
|
|
331
333
|
await logUsage(deps, args, out);
|
|
332
|
-
|
|
334
|
+
const answer = parseReviewAnswer(textOf(out.content)) ?? {
|
|
335
|
+
decision: "ask",
|
|
336
|
+
reason: REVIEW_ASK_REASON,
|
|
337
|
+
};
|
|
338
|
+
// the model saw only the beginning of the command: its allow cannot cover the part it never read
|
|
339
|
+
// (hardening spec R8); its deny or ask stands
|
|
340
|
+
if (answer.decision === "allow" && fitted.text !== input.text) {
|
|
341
|
+
return { decision: "ask", reason: REVIEW_TRUNCATED_ASK_REASON };
|
|
342
|
+
}
|
|
343
|
+
return answer;
|
|
333
344
|
}
|
|
334
345
|
/**
|
|
335
346
|
* Appends the call's `usage` event (purpose `review`, the call's run, step and `callId`; idempotent
|
|
@@ -5,9 +5,9 @@
|
|
|
5
5
|
* a model or a lock; the parser and the table are pure.
|
|
6
6
|
*/
|
|
7
7
|
export type { ClassifierAnswer, ReviewClassifierDeps, ReviewClassifierInput, ReviewHookFacts, RunClassifierArgs, } from "./classifier.js";
|
|
8
|
-
export { boundMessages, classifierMessage, fitReviewInput, newReviewTag, parseReviewAnswer, REVIEW_ASK_REASON, REVIEW_MAX_OUTPUT_TOKENS, REVIEW_PURPOSE, REVIEW_SYSTEM_PROMPT, REVIEW_TRUNCATED_MARKER, REVIEW_UNAVAILABLE_PREFIX, reviewSystemPrompt, runClassifier, } from "./classifier.js";
|
|
8
|
+
export { boundMessages, classifierMessage, fitReviewInput, newReviewTag, parseReviewAnswer, REVIEW_ASK_REASON, REVIEW_MAX_OUTPUT_TOKENS, REVIEW_PURPOSE, REVIEW_SYSTEM_PROMPT, REVIEW_TRUNCATED_ASK_REASON, REVIEW_TRUNCATED_MARKER, REVIEW_UNAVAILABLE_PREFIX, reviewSystemPrompt, runClassifier, } from "./classifier.js";
|
|
9
9
|
export type { CommandReview, ReviewCall, ReviewInput, ReviewVerdict } from "./review.service.js";
|
|
10
10
|
export { CommandReviewService, REVIEW_REASONS, } from "./review.service.js";
|
|
11
|
-
export { parseCommand, reviewRules, reviewWrite, } from "./rules.js";
|
|
11
|
+
export { parseCommand, reviewRules, reviewWrite, writtenPaths, } from "./rules.js";
|
|
12
12
|
export type { ParsedCommand, Redirect, ReviewFacts, ReviewResult, RuleHit, RuleOutcome, SimpleCommand, } from "./types.js";
|
|
13
|
-
export { isSessionGrantableRule } from "./types.js";
|
|
13
|
+
export { applySessionGrants, isSessionGrantableRule } from "./types.js";
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* auto mode (and for the file writes outside the workspace). Only the service touches the database,
|
|
5
5
|
* a model or a lock; the parser and the table are pure.
|
|
6
6
|
*/
|
|
7
|
-
export { boundMessages, classifierMessage, fitReviewInput, newReviewTag, parseReviewAnswer, REVIEW_ASK_REASON, REVIEW_MAX_OUTPUT_TOKENS, REVIEW_PURPOSE, REVIEW_SYSTEM_PROMPT, REVIEW_TRUNCATED_MARKER, REVIEW_UNAVAILABLE_PREFIX, reviewSystemPrompt, runClassifier, } from "./classifier.js";
|
|
7
|
+
export { boundMessages, classifierMessage, fitReviewInput, newReviewTag, parseReviewAnswer, REVIEW_ASK_REASON, REVIEW_MAX_OUTPUT_TOKENS, REVIEW_PURPOSE, REVIEW_SYSTEM_PROMPT, REVIEW_TRUNCATED_ASK_REASON, REVIEW_TRUNCATED_MARKER, REVIEW_UNAVAILABLE_PREFIX, reviewSystemPrompt, runClassifier, } from "./classifier.js";
|
|
8
8
|
export { CommandReviewService, REVIEW_REASONS, } from "./review.service.js";
|
|
9
|
-
export { parseCommand, reviewRules, reviewWrite, } from "./rules.js";
|
|
10
|
-
export { isSessionGrantableRule } from "./types.js";
|
|
9
|
+
export { parseCommand, reviewRules, reviewWrite, writtenPaths, } from "./rules.js";
|
|
10
|
+
export { applySessionGrants, isSessionGrantableRule } from "./types.js";
|
|
@@ -111,12 +111,20 @@ export declare class CommandReviewService implements CommandReview {
|
|
|
111
111
|
*/
|
|
112
112
|
private rootConversationOf;
|
|
113
113
|
/**
|
|
114
|
-
*
|
|
114
|
+
* The rule classes the root conversation holds session grants for (`command:<ruleId>` rows).
|
|
115
115
|
* Command grants carry no tool-spec fingerprint: the approval records the rule, not the command.
|
|
116
|
-
* Only a concrete
|
|
117
|
-
*
|
|
116
|
+
* Only a concrete grantable class counts: a stored catch-all or never-session class (old data)
|
|
117
|
+
* covers nothing.
|
|
118
118
|
*/
|
|
119
|
-
private
|
|
119
|
+
private grantedRules;
|
|
120
|
+
/**
|
|
121
|
+
* The absolute paths the conversation tree's own tool calls wrote — the root's and every
|
|
122
|
+
* sub-agent's: `Write` / `Edit` targets and the write targets (downloads and copies included) of
|
|
123
|
+
* their `Bash` lines, from the latest {@link WRITTEN_EVENTS_READ} assistant messages of the tree.
|
|
124
|
+
* All agents of a tree share the device, so a file one of them wrote is code the run produced,
|
|
125
|
+
* whoever runs it (hardening spec R1).
|
|
126
|
+
*/
|
|
127
|
+
private writtenInTree;
|
|
120
128
|
/**
|
|
121
129
|
* The bounded text of the root conversation's last person messages: the `user_message` text blocks
|
|
122
130
|
* only, never an assistant message or a tool result. `sandbox.review.messageTokens` caps it.
|