@bastani/atomic 0.9.65 → 0.9.66-alpha.1
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/CHANGELOG.md +28 -0
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +154 -36
- package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +125 -16
- package/dist/builtin/workflows/src/index.js +125 -16
- package/dist/builtin/workflows/src/local-worker-entry.mjs +125 -16
- package/dist/builtin/workflows/src/shared/authoring-contract-ui.d.ts +8 -0
- package/dist/core/agent-session-auto-compaction.js +2 -2
- package/dist/core/agent-session-auto-compaction.js.map +1 -1
- package/dist/core/agent-session-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-compaction.js +9 -1
- package/dist/core/agent-session-compaction.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +5 -2
- package/dist/core/agent-session-methods.d.ts.map +1 -1
- package/dist/core/agent-session-methods.js.map +1 -1
- package/dist/core/agent-session-post-tool-compaction.js +2 -2
- package/dist/core/agent-session-post-tool-compaction.js.map +1 -1
- package/dist/core/compaction/compaction-runner.d.ts +18 -2
- package/dist/core/compaction/compaction-runner.d.ts.map +1 -1
- package/dist/core/compaction/compaction-runner.js +129 -15
- package/dist/core/compaction/compaction-runner.js.map +1 -1
- package/dist/core/compaction/compaction-types.d.ts +4 -0
- package/dist/core/compaction/compaction-types.d.ts.map +1 -1
- package/dist/core/compaction/compaction-types.js.map +1 -1
- package/dist/core/settings-defaults.d.ts +2 -0
- package/dist/core/settings-defaults.d.ts.map +1 -1
- package/dist/core/settings-defaults.js +2 -0
- package/dist/core/settings-defaults.js.map +1 -1
- package/dist/core/settings-manager-basic-accessors.d.ts +2 -0
- package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
- package/dist/core/settings-manager-basic-accessors.js +7 -0
- package/dist/core/settings-manager-basic-accessors.js.map +1 -1
- package/dist/core/settings-schema.d.ts +2 -0
- package/dist/core/settings-schema.d.ts.map +1 -1
- package/dist/core/settings-schema.js +4 -0
- package/dist/core/settings-schema.js.map +1 -1
- package/docs/compaction.md +5 -1
- package/docs/session-format.md +1 -1
- package/docs/settings.md +2 -1
- package/docs/workflows/api-reference.md +3 -1
- package/docs/workflows/operations.md +5 -2
- package/npm-shrinkwrap.json +32 -32
- package/package.json +3 -3
- package/schemas/settings.schema.json +14 -0
|
@@ -17424,12 +17424,19 @@ class SqlResourceAdmission {
|
|
|
17424
17424
|
if (!(await tx.all(`PRAGMA table_info(${admission.owners})`)).some((entry) => entry.name === "boot"))
|
|
17425
17425
|
await tx.exec(`ALTER TABLE ${admission.owners} ADD COLUMN boot TEXT`);
|
|
17426
17426
|
await tx.run(`INSERT INTO ${admission.owners}(id, host, pid, expires_at, boot) VALUES (?, ?, ?, CAST(unixepoch('subsec') * 1000 AS INTEGER) + ?, ?)`, admission.owner, admissionHost, process.pid, OWNER_LEASE_MS, boot);
|
|
17427
|
+
const rootLimits = options.rootLimits ?? "check";
|
|
17427
17428
|
for (const [scope, limits] of [
|
|
17428
17429
|
[`root:${options.root}`, options.limits],
|
|
17429
17430
|
["user", options.userLimits]
|
|
17430
17431
|
]) {
|
|
17431
|
-
|
|
17432
|
+
const ofRoot = scope !== "user";
|
|
17433
|
+
if (ofRoot && rootLimits === "unchanged")
|
|
17432
17434
|
continue;
|
|
17435
|
+
if (!limits && (scope === "user" || !options.host)) {
|
|
17436
|
+
if (ofRoot && rootLimits === "replace")
|
|
17437
|
+
await tx.run(`DELETE FROM ${admission.configuration} WHERE scope = ?`, scope);
|
|
17438
|
+
continue;
|
|
17439
|
+
}
|
|
17433
17440
|
const config = JSON.stringify({
|
|
17434
17441
|
session: limits?.session ?? null,
|
|
17435
17442
|
process: limits?.process ?? null,
|
|
@@ -17440,6 +17447,10 @@ class SqlResourceAdmission {
|
|
|
17440
17447
|
}
|
|
17441
17448
|
}
|
|
17442
17449
|
});
|
|
17450
|
+
if (ofRoot && rootLimits === "replace") {
|
|
17451
|
+
await tx.run(`INSERT OR REPLACE INTO ${admission.configuration} VALUES (?, ?)`, scope, config);
|
|
17452
|
+
continue;
|
|
17453
|
+
}
|
|
17443
17454
|
await tx.run(`INSERT OR IGNORE INTO ${admission.configuration} VALUES (?, ?)`, scope, config);
|
|
17444
17455
|
if ((await tx.get(`SELECT config FROM ${admission.configuration} WHERE scope = ?`, scope))?.config !== config)
|
|
17445
17456
|
throw new Error("Conflicting resource admission configuration");
|
|
@@ -17879,7 +17890,8 @@ async function admitWorkflowSessions(backend, opts, callback) {
|
|
|
17879
17890
|
const admission = await SqlResourceAdmission.open(poolJournalFor(rootBackend.journal), {
|
|
17880
17891
|
...config,
|
|
17881
17892
|
root: opts.parentRun?.rootRunId ?? opts.runId,
|
|
17882
|
-
holder: randomUUID7()
|
|
17893
|
+
holder: randomUUID7(),
|
|
17894
|
+
...opts.parentRun === undefined ? { rootLimits: "replace" } : {}
|
|
17883
17895
|
});
|
|
17884
17896
|
return withResourceAdmission(admission, () => callback({
|
|
17885
17897
|
...opts,
|
|
@@ -60277,6 +60289,12 @@ function expiry(now, duration) {
|
|
|
60277
60289
|
positive(expiresAt);
|
|
60278
60290
|
return expiresAt;
|
|
60279
60291
|
}
|
|
60292
|
+
function short(digest) {
|
|
60293
|
+
return digest.slice(0, 12);
|
|
60294
|
+
}
|
|
60295
|
+
function shownMode(mode) {
|
|
60296
|
+
return mode === undefined ? "unset" : JSON.stringify(mode);
|
|
60297
|
+
}
|
|
60280
60298
|
|
|
60281
60299
|
class SqlPoolQueue {
|
|
60282
60300
|
storage;
|
|
@@ -60457,7 +60475,7 @@ class SqlPoolQueue {
|
|
|
60457
60475
|
throw new Error(STALE_WORK_LEASE);
|
|
60458
60476
|
});
|
|
60459
60477
|
}
|
|
60460
|
-
async enqueue(lease, descriptor, boundary) {
|
|
60478
|
+
async enqueue(lease, descriptor, boundary, options = {}) {
|
|
60461
60479
|
lease = snapshotLease(lease);
|
|
60462
60480
|
const { boundaryId, childRunId, scope } = descriptor;
|
|
60463
60481
|
const topology = boundary.topology;
|
|
@@ -60486,12 +60504,11 @@ class SqlPoolQueue {
|
|
|
60486
60504
|
const { now } = await this.authority(tx, lease);
|
|
60487
60505
|
const previous = await tx.get(`SELECT * FROM ${this.work} WHERE root = ? AND (boundary = ? OR json_extract(descriptor, '$.scope') = ? OR json_extract(descriptor, '$.childRunId') = ?)`, lease.runId, boundaryId, scope, childRunId);
|
|
60488
60506
|
if (previous) {
|
|
60489
|
-
|
|
60490
|
-
|
|
60491
|
-
|
|
60492
|
-
|
|
60493
|
-
|
|
60494
|
-
return fromRow({ ...previous, state: "ready", epoch: lease.epoch });
|
|
60507
|
+
const row = previous.fingerprint === fingerprint ? previous : await this.rebind(tx, lease, previous, json, JSON.parse(payload), fingerprint, options);
|
|
60508
|
+
if (row.state !== "ready" && row.state !== "failed" || row.epoch >= lease.epoch)
|
|
60509
|
+
return fromRow(row);
|
|
60510
|
+
await tx.run(`UPDATE ${this.work} SET state = 'ready', epoch = ? WHERE id = ?`, lease.epoch, row.id);
|
|
60511
|
+
return fromRow({ ...row, state: "ready", epoch: lease.epoch });
|
|
60495
60512
|
}
|
|
60496
60513
|
const siblings = await tx.all(`SELECT json_extract(descriptor, '$.scope') AS scope FROM ${this.work} WHERE root = ?`, lease.runId);
|
|
60497
60514
|
if (siblings.some((item) => scope.startsWith(`${item.scope}:`) || item.scope.startsWith(`${scope}:`)))
|
|
@@ -60522,6 +60539,32 @@ class SqlPoolQueue {
|
|
|
60522
60539
|
if (outcome.status === "exists" && !isSameCheckpointValue(outcome.entry.event.payload, boundary))
|
|
60523
60540
|
throw new Error("Pool boundary identity conflict");
|
|
60524
60541
|
}
|
|
60542
|
+
async rebind(tx, lease, previous, json, boundary, fingerprint, options) {
|
|
60543
|
+
const queued = JSON.parse(previous.descriptor);
|
|
60544
|
+
const requested = JSON.parse(json);
|
|
60545
|
+
const queuedMode = queued.execution.executionMode;
|
|
60546
|
+
const requestedMode = requested.execution.executionMode;
|
|
60547
|
+
const { executionMode: _mode, ...execution } = requested.execution;
|
|
60548
|
+
const asQueued = {
|
|
60549
|
+
...requested,
|
|
60550
|
+
digest: queued.digest,
|
|
60551
|
+
execution: queuedMode === undefined ? execution : { ...execution, executionMode: queuedMode }
|
|
60552
|
+
};
|
|
60553
|
+
if (durableHash({ descriptor: asQueued, boundary }) !== previous.fingerprint)
|
|
60554
|
+
throw new Error("Pool boundary identity conflict");
|
|
60555
|
+
const entryEdited = queued.digest !== requested.digest;
|
|
60556
|
+
if (previous.epoch >= lease.epoch) {
|
|
60557
|
+
const changes = [
|
|
60558
|
+
...entryEdited ? [`entry module (sha256 ${short(queued.digest)} to ${short(requested.digest)})`] : [],
|
|
60559
|
+
...queuedMode !== requestedMode ? [`execution mode (${shownMode(queuedMode)} to ${shownMode(requestedMode)})`] : []
|
|
60560
|
+
];
|
|
60561
|
+
throw new Error(`Pool boundary identity conflict: child ${requested.childRunId} is already queued by this incarnation of root ${lease.runId}, and its worker may be running it, so its ${changes.join(" and ")} cannot change`);
|
|
60562
|
+
}
|
|
60563
|
+
if (entryEdited && options.acceptEntryChanges !== true)
|
|
60564
|
+
throw new Error(`Pool boundary identity conflict: child ${requested.childRunId} was queued by an earlier run of root ${lease.runId} with the entry module of worker definition ${requested.definition} at sha256 ${short(queued.digest)}, and the root now runs that module at sha256 ${short(requested.digest)}. Resume the root with /workflow resume ${lease.runId} --accept-entry-changes, or acceptEntryChanges: true in the SDK, to run the child with the edited module, or restore the module.`);
|
|
60565
|
+
await tx.run(`UPDATE ${this.work} SET descriptor = ?, fingerprint = ? WHERE id = ?`, json, fingerprint, previous.id);
|
|
60566
|
+
return { ...previous, descriptor: json, fingerprint };
|
|
60567
|
+
}
|
|
60525
60568
|
async claim(lease, worker, definitions, durationMs) {
|
|
60526
60569
|
positive(durationMs);
|
|
60527
60570
|
lease = snapshotLease(lease);
|
|
@@ -66203,7 +66246,9 @@ class PoolCoordinator {
|
|
|
66203
66246
|
const queue = this.queue;
|
|
66204
66247
|
const lease = this.lease;
|
|
66205
66248
|
const work = await this.retainedTransition(async () => {
|
|
66206
|
-
let enqueued = await this.whileRootLate(queue, () => queue.enqueue(lease, command.descriptor, command.boundary
|
|
66249
|
+
let enqueued = await this.whileRootLate(queue, () => queue.enqueue(lease, command.descriptor, command.boundary, {
|
|
66250
|
+
acceptEntryChanges: command.acceptEntryChanges === true
|
|
66251
|
+
}));
|
|
66207
66252
|
if (enqueued.state === "completed" && enqueued.epoch < lease.epoch)
|
|
66208
66253
|
enqueued = await this.whileRootLate(queue, () => queue.reopenCompleted(lease, enqueued.id, failedOnInfrastructureFault)) ?? enqueued;
|
|
66209
66254
|
const retained = this.retained.get(enqueued.id);
|
|
@@ -69843,7 +69888,8 @@ class LocalWorkerPool {
|
|
|
69843
69888
|
inputs,
|
|
69844
69889
|
execution
|
|
69845
69890
|
},
|
|
69846
|
-
boundary
|
|
69891
|
+
boundary,
|
|
69892
|
+
...this.options.acceptEntryChanges === true ? { acceptEntryChanges: true } : {}
|
|
69847
69893
|
});
|
|
69848
69894
|
const work = enqueued.work;
|
|
69849
69895
|
this.works.set(work.id, work);
|
|
@@ -70279,14 +70325,66 @@ var DEFAULT_POOLED_STAGE_START_MAX_LOAD_PER_CPU = 3;
|
|
|
70279
70325
|
// dist/builtin/workflows/src/workers/public-pool.ts
|
|
70280
70326
|
import { resolve as resolve15 } from "node:path";
|
|
70281
70327
|
import { isDeepStrictEqual as isDeepStrictEqual2 } from "node:util";
|
|
70328
|
+
function shown(value2) {
|
|
70329
|
+
return value2 === undefined ? "unset" : JSON.stringify(value2);
|
|
70330
|
+
}
|
|
70331
|
+
function isPlainRecord(value2) {
|
|
70332
|
+
return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
|
|
70333
|
+
}
|
|
70334
|
+
function settingChanges(path, saved, current, changes) {
|
|
70335
|
+
if (isDeepStrictEqual2(saved, current))
|
|
70336
|
+
return;
|
|
70337
|
+
if ((saved === undefined || isPlainRecord(saved)) && (current === undefined || isPlainRecord(current))) {
|
|
70338
|
+
for (const key of new Set([...Object.keys(saved ?? {}), ...Object.keys(current ?? {})]))
|
|
70339
|
+
settingChanges(`${path}.${key}`, saved?.[key], current?.[key], changes);
|
|
70340
|
+
return;
|
|
70341
|
+
}
|
|
70342
|
+
changes.push({
|
|
70343
|
+
description: `${path} changed from ${shown(saved)} to ${shown(current)}`,
|
|
70344
|
+
resumable: RESUMABLE_SETTINGS.has(path)
|
|
70345
|
+
});
|
|
70346
|
+
}
|
|
70347
|
+
function resourceChanges(saved, current) {
|
|
70348
|
+
const changes = [];
|
|
70349
|
+
if (saved.localWorkers === undefined !== (current.localWorkers === undefined))
|
|
70350
|
+
changes.push({
|
|
70351
|
+
description: `local workers were turned ${current.localWorkers === undefined ? "off" : "on"}`,
|
|
70352
|
+
resumable: false
|
|
70353
|
+
});
|
|
70354
|
+
else {
|
|
70355
|
+
settingChanges("localWorkers", saved.localWorkers && { ...saved.localWorkers, definitions: undefined }, current.localWorkers && { ...current.localWorkers, definitions: undefined }, changes);
|
|
70356
|
+
}
|
|
70357
|
+
const named = (list) => new Map((list ?? []).map((source) => [`${source.path}#${source.exportName}`, source.digest]));
|
|
70358
|
+
const before = named(saved.definitions);
|
|
70359
|
+
const after = named(current.definitions);
|
|
70360
|
+
for (const [name, digest] of before) {
|
|
70361
|
+
const now = after.get(name);
|
|
70362
|
+
if (now === undefined)
|
|
70363
|
+
changes.push({ description: `worker definition ${name} is no longer listed`, resumable: false });
|
|
70364
|
+
else if (now !== digest)
|
|
70365
|
+
changes.push({
|
|
70366
|
+
description: `the entry module of worker definition ${name} was edited (sha256 ${digest.slice(0, 12)} to ${now.slice(0, 12)})`,
|
|
70367
|
+
resumable: false,
|
|
70368
|
+
entry: true
|
|
70369
|
+
});
|
|
70370
|
+
}
|
|
70371
|
+
for (const name of after.keys())
|
|
70372
|
+
if (!before.has(name))
|
|
70373
|
+
changes.push({ description: `worker definition ${name} was added`, resumable: false });
|
|
70374
|
+
settingChanges("admission", saved.admission, current.admission, changes);
|
|
70375
|
+
settingChanges("coordinator", saved.coordinator, current.coordinator, changes);
|
|
70376
|
+
return changes;
|
|
70377
|
+
}
|
|
70282
70378
|
async function restoreWorkerOptions(backend, options) {
|
|
70283
70379
|
const source = options.continuation?.source.id ?? options.runId;
|
|
70284
70380
|
if (source !== undefined)
|
|
70285
70381
|
await backend.hydrateWorkflow(source);
|
|
70286
70382
|
const original = source === undefined ? undefined : backend.getWorkflow(source);
|
|
70287
70383
|
const saved = original?.resources;
|
|
70288
|
-
if (original && !saved && (options.localWorkers || options.admission))
|
|
70289
|
-
|
|
70384
|
+
if (original && !saved && (options.localWorkers || options.admission)) {
|
|
70385
|
+
const set = [options.localWorkers && "localWorkers", options.admission && "admission"].filter(Boolean).join(" and ");
|
|
70386
|
+
throw new Error(`Root ${source} started without local workers or resource admission, and this resume sets ${set}: immutable resource configuration cannot change on an existing root. Resume it without them, or start a new run.`);
|
|
70387
|
+
}
|
|
70290
70388
|
return {
|
|
70291
70389
|
...options,
|
|
70292
70390
|
localWorkers: options.localWorkers ?? saved?.localWorkers,
|
|
@@ -70349,14 +70447,16 @@ async function activatePublicPool(backend, options) {
|
|
|
70349
70447
|
throw new Error(`This root's local workers ran on another machine (${saved.host}). Their work queue and leases are in that machine's pool database, which this machine cannot see, and its workers may still be running children. Resume the root on that machine.`);
|
|
70350
70448
|
if (saved !== undefined && resources.coordinator !== undefined && saved.host === resources.coordinator.host && saved.database !== resources.coordinator.database)
|
|
70351
70449
|
throw new Error(`This root's local workers keep their work queue and leases in the pool database ${saved.database} on this machine, but the journal is now selected in a way that uses ${resources.coordinator.database}: its adapter, options, prefix or the agent directory changed. Resume the root with the journal selected as it was when the root started.`);
|
|
70352
|
-
|
|
70353
|
-
|
|
70450
|
+
const refused = options.effectiveResources === undefined ? [] : resourceChanges(options.effectiveResources, resources).filter((change) => !change.resumable && !(change.entry && options.acceptEntryChanges === true));
|
|
70451
|
+
if (refused.length > 0)
|
|
70452
|
+
throw new Error(`Since root ${options.runId} started, ${refused.map((change) => change.description).join("; ")}. Its recorded steps and queued children depend on these, so restore them to resume it, or start a new run. The pool size (localWorkers.count) and the root's own limits (admission.limits and admission.host) can change between resumes.${refused.some((change) => change.entry) ? ` An edited entry module can also be accepted: resume with /workflow resume ${options.runId} --accept-entry-changes, or acceptEntryChanges: true in the SDK, to replay the recorded steps and run the rest of each unfinished child with the edited module.` : ""}`);
|
|
70354
70453
|
options.effectiveResources = resources;
|
|
70355
70454
|
if (resources.admission)
|
|
70356
70455
|
await SqlResourceAdmission.open(poolJournal, {
|
|
70357
70456
|
...resources.admission,
|
|
70358
70457
|
root: options.runId,
|
|
70359
|
-
holder: "preflight"
|
|
70458
|
+
holder: "preflight",
|
|
70459
|
+
rootLimits: "unchanged"
|
|
70360
70460
|
});
|
|
70361
70461
|
if (!localWorkers)
|
|
70362
70462
|
return;
|
|
@@ -70371,6 +70471,7 @@ async function activatePublicPool(backend, options) {
|
|
|
70371
70471
|
startupTimeoutMs: options.localWorkers?.startupTimeoutMs,
|
|
70372
70472
|
leaseMs: options.localWorkers?.leaseMs,
|
|
70373
70473
|
maxLoadPerCpu: options.localWorkers?.maxLoadPerCpu ?? DEFAULT_POOLED_STAGE_START_MAX_LOAD_PER_CPU,
|
|
70474
|
+
...options.acceptEntryChanges === true ? { acceptEntryChanges: true } : {},
|
|
70374
70475
|
...options.stageControlRegistry === undefined || options[hostWorkerBindings] ? {} : { stageControlRegistry: options.stageControlRegistry }
|
|
70375
70476
|
});
|
|
70376
70477
|
try {
|
|
@@ -70381,6 +70482,7 @@ async function activatePublicPool(backend, options) {
|
|
|
70381
70482
|
throw error;
|
|
70382
70483
|
}
|
|
70383
70484
|
}
|
|
70485
|
+
var RESUMABLE_SETTINGS;
|
|
70384
70486
|
var init_public_pool = __esm(() => {
|
|
70385
70487
|
init_journal_backend();
|
|
70386
70488
|
init_admission_host();
|
|
@@ -70389,6 +70491,13 @@ var init_public_pool = __esm(() => {
|
|
|
70389
70491
|
init_local_pool();
|
|
70390
70492
|
init_pool_journal();
|
|
70391
70493
|
init_resource_admission();
|
|
70494
|
+
RESUMABLE_SETTINGS = new Set([
|
|
70495
|
+
"localWorkers.count",
|
|
70496
|
+
"admission.limits.session",
|
|
70497
|
+
"admission.limits.process",
|
|
70498
|
+
"admission.host.maxLoadPerCpu",
|
|
70499
|
+
"admission.host.minFreeMemoryBytes"
|
|
70500
|
+
]);
|
|
70392
70501
|
});
|
|
70393
70502
|
|
|
70394
70503
|
// dist/builtin/workflows/src/engine/primitives/chain.ts
|
|
@@ -218,6 +218,14 @@ export interface RunOpts {
|
|
|
218
218
|
readonly journal?: RunJournalOption;
|
|
219
219
|
readonly localWorkers?: import("../workers/public-options.js").LocalWorkerOptions;
|
|
220
220
|
readonly admission?: import("../workers/public-options.js").WorkflowAdmissionOptions;
|
|
221
|
+
/**
|
|
222
|
+
* Resume a root whose local worker definitions' entry modules were edited since it last ran (#4200). Without it that
|
|
223
|
+
* resume is refused, naming each edited module. With it the recorded steps of the root and its children replay from
|
|
224
|
+
* the journal, and its queued children that have not finished run the edited modules. Replay compatibility then
|
|
225
|
+
* rests with the author: a child whose replayed calls no longer match the ones it recorded still fails. Other refused
|
|
226
|
+
* changes, such as an added or removed definition, stay refused.
|
|
227
|
+
*/
|
|
228
|
+
readonly acceptEntryChanges?: boolean;
|
|
221
229
|
readonly models?: WorkflowModelCatalogPort;
|
|
222
230
|
readonly registry?: object;
|
|
223
231
|
readonly depth?: number;
|
|
@@ -493,8 +493,8 @@ export async function _runAutoCompaction(reason, willRetry, urgency = reason ===
|
|
|
493
493
|
// require provider credentials. Missing auth then fails model-driven compaction
|
|
494
494
|
// before persistence or continuation, matching other provider-call failures.
|
|
495
495
|
const result = await this._applyVerbatimCompaction({
|
|
496
|
-
resolvePlannerAuth: async (candidate) => {
|
|
497
|
-
const authResult = await this._getRequiredRequestAuth(candidate, controller.signal);
|
|
496
|
+
resolvePlannerAuth: async (candidate, signal) => {
|
|
497
|
+
const authResult = await this._getRequiredRequestAuth(candidate, signal ?? controller.signal);
|
|
498
498
|
return authResult.apiKey || authResult.headers ? authForStream(this, authResult) : undefined;
|
|
499
499
|
},
|
|
500
500
|
abortController: controller,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-auto-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-auto-compaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAEzE,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAEN,sBAAsB,EACtB,qBAAqB,EACrB,8BAA8B,EAC9B,aAAa,GACb,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,+BAA+B,EAAE,MAAM,yCAAyC,CAAC;AAC1F,OAAO,EAAyB,gCAAgC,EAAE,MAAM,sBAAsB,CAAC;AAE/F;;;;GAIG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAAC,CAAC;AAElD,MAAM,CAAC,MAAM,6CAA6C,GAAG,CAAC,CAAC;AAS/D,6EAA6E;AAC7E,MAAM,UAAU,8BAA8B;IAI7C,IAAI,OAAoB,CAAC;IACzB,MAAM,OAAO,GAAG,IAAI,OAAO,CAAO,CAAC,IAAI,EAAE,EAAE;QAC1C,OAAO,GAAG,IAAI,CAAC;IAChB,CAAC,CAAC,CAAC;IACH,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAC7B,CAAC;AAED,MAAM,+BAA+B,GAAG,uBAAuB,CAAC;AAChE,MAAM,+BAA+B,GAAG,IAAI,MAAM,CACjD,gFAAgF,+BAA+B,uBAAuB,CACtI,CAA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EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACjE,YAAY,EAAE,qBAAqB;SACnC,CAAC,CAAC;QACH,MAAM,wBAAwB,CAAC,IAAI,EAAE;YACpC,MAAM;YACN,YAAY,EAAE,qBAAqB;YACnC,OAAO;YACP,SAAS,EAAE,KAAK;YAChB,aAAa;SACb,CAAC,CAAC;QACH,OAAO,qBAAqB,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,QAAQ,CAAC;IACtD,CAAC;YAAS,CAAC;QACV,IAAI,IAAI,CAAC,8BAA8B,KAAK,UAAU;YAAE,IAAI,CAAC,8BAA8B,GAAG,SAAS,CAAC;QACxG,IAAI,IAAI,CAAC,iBAAiB,KAAK,MAAM;YAAE,IAAI,CAAC,iBAAiB,GAAG,SAAS,CAAC;QAC1E,UAAU,CAAC,OAAO,EAAE,CAAC;QACrB,IAAI,IAAI,CAAC,yBAAyB,KAAK,UAAU,CAAC,OAAO;YAAE,IAAI,CAAC,yBAAyB,GAAG,SAAS,CAAC;IACvG,CAAC;AACF,CAAC;AAED;;GAEG;AAEH,MAAM,CAAC,MAAM,iCAAiC,GAAG;IAChD,uCAAuC;IACvC,gBAAgB;IAChB,kDAAkD;IAClD,4CAA4C;IAC5C,0BAA0B;IAC1B,4BAA4B;IAC5B,kBAAkB;CAClB,CAAC","sourcesContent":["import type { AssistantMessage } from \"@bastani/pi-ai/compat\";\nimport { isContextOverflow, isRecoverableLength } from \"@bastani/pi-ai/compat\";\nimport { emitSessionCompactFailed } from \"./agent-session-compaction.ts\";\nimport type { AgentSessionInternalSurface as AgentSession, AutoCompactionRunOutcome } from \"./agent-session-methods.ts\";\nimport { authForStream } from \"./agent-session-models.ts\";\nimport {\n\ttype CompactionUrgency,\n\tcalculateContextTokens,\n\testimateContextTokens,\n\testimateProjectedContextTokens,\n\tshouldCompact,\n} from \"./compaction/index.ts\";\nimport { MIN_RESPONSES_MAX_OUTPUT_TOKENS } from \"./openai-responses-payload-sanitizer.ts\";\nimport { type ContextEditEntry, getLatestCompactionBoundaryEntry } from \"./session-manager.ts\";\n\n/**\n * Upper bound on direct continuations after a response reaches its requested\n * output cap. Context-limited truncations use one compact-and-retry attempt\n * instead; this bound preserves Atomic's separate output-cap continuation.\n */\nexport const MAX_LENGTH_CONTINUATION_ATTEMPTS = 3;\n\nexport const MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS = 1;\n\ntype JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\ntype ProviderErrorDetails = {\n\tmessage?: string;\n\tcode?: string;\n\tparam?: string;\n};\n\n/** Create the settlement boundary for a regular automatic compaction run. */\nexport function createAutoCompactionCompletion(): {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n} {\n\tlet resolve!: () => void;\n\tconst promise = new Promise<void>((done) => {\n\t\tresolve = done;\n\t});\n\treturn { promise, resolve };\n}\n\nconst OUTPUT_BUDGET_PARAMETER_PATTERN = /\\bmax_output_tokens\\b/;\nconst OUTPUT_BUDGET_UNDERFLOW_PATTERN = new RegExp(\n\t`(?:integer\\\\s+below\\\\s+minimum\\\\s+value|expected\\\\s+(?:a\\\\s+)?value\\\\s*>=\\\\s*${MIN_RESPONSES_MAX_OUTPUT_TOKENS}|got\\\\s+1\\\\s+instead)`,\n);\n\nexport async function _checkCompaction(\n\tthis: AgentSession,\n\tassistantMessage: AssistantMessage,\n\tskipAbortedCheck = true,\n): Promise<void> {\n\tif (this._agentRunAbortRequested) return;\n\tif (this._pendingPostToolCompactionGuard) {\n\t\tconst { result } = this._pendingPostToolCompactionGuard;\n\t\tthis._pendingPostToolCompactionGuard = undefined;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"threshold\",\n\t\t\tresult,\n\t\t\taborted: true,\n\t\t\twillRetry: false,\n\t\t\tmidTurn: true,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t});\n\t}\n\tif (\n\t\tthis._postToolCompactionPreflightError !== undefined &&\n\t\tassistantMessage.errorMessage === this._postToolCompactionPreflightError\n\t) {\n\t\tthis._postToolCompactionPreflightError = undefined;\n\t\treturn;\n\t}\n\t// The agent_end path passes skipAbortedCheck=true; the pre-prompt path passes\n\t// false. Only the live turn-completion path may auto-continue a truncated\n\t// response — before a fresh user prompt we must not resume the old turn.\n\tconst isLiveTurnCompletion = skipAbortedCheck;\n\tconst settings = this.settingsManager.getCompactionSettings(this.model);\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\t// Skip overflow handling if the message came from a different model.\n\t// This handles the case where user switched from a smaller-context model (e.g. opus)\n\t// to a larger-context model (e.g. codex) - the overflow error from the old model\n\t// shouldn't trigger compaction for the new model.\n\tconst sameModel =\n\t\tthis.model !== undefined &&\n\t\tassistantMessage.provider === this.model.provider &&\n\t\tassistantMessage.model === this.model.id;\n\t// Usage and overflow signals belong to the request that produced this assistant.\n\t// A later context edit or compaction changes what the next request contains, so\n\t// only a projected, unedited assistant may drive usage-based decisions; an explicit\n\t// provider overflow error still recovers while its attempt is retained.\n\t// Guarded because fallback suites drive this function on a synthetic session.\n\tconst projectionAware =\n\t\ttypeof this.sessionManager?.buildSessionProjection === \"function\" &&\n\t\ttypeof this._findPersistedMessageEntryId === \"function\";\n\tconst currentProjection = projectionAware ? this.sessionManager.buildSessionProjection() : undefined;\n\tconst branch = projectionAware ? this.sessionManager.getBranch() : [];\n\tconst assistantEntryId = projectionAware ? this._findPersistedMessageEntryId(assistantMessage) : undefined;\n\tconst assistantIsProjected =\n\t\tassistantEntryId === undefined ||\n\t\tcurrentProjection?.entries.some(\n\t\t\t(entry) =>\n\t\t\t\tentry.sourceEntry.id === assistantEntryId && entry.messages.some((message) => message.role === \"assistant\"),\n\t\t) === true;\n\tconst assistantIndex = assistantEntryId ? branch.findIndex((entry) => entry.id === assistantEntryId) : -1;\n\tconst entriesAfterAssistant = assistantIndex >= 0 ? branch.slice(assistantIndex + 1) : [];\n\tconst hasPostAssistantContextEdit = entriesAfterAssistant.some((entry) => entry.type === \"context_edit\");\n\tconst latestAssistantEdit = entriesAfterAssistant\n\t\t.filter(\n\t\t\t(entry): entry is ContextEditEntry => entry.type === \"context_edit\" && entry.targetId === assistantEntryId,\n\t\t)\n\t\t.at(-1);\n\tconst assistantRetainedForExplicitRecovery =\n\t\tassistantEntryId === undefined ||\n\t\t(!entriesAfterAssistant.some((entry) => entry.type === \"compaction\") &&\n\t\t\tlatestAssistantEdit?.replacement !== null);\n\tconst assistantUsageMatchesProjection = assistantIsProjected && !hasPostAssistantContextEdit;\n\tconst explicitOverflow = assistantMessage.stopReason === \"error\" && isContextOverflow(assistantMessage);\n\tconst contextOverflow =\n\t\tsameModel &&\n\t\t((explicitOverflow && assistantRetainedForExplicitRecovery) ||\n\t\t\t(assistantUsageMatchesProjection && isContextOverflow(assistantMessage, contextWindow)));\n\tif (!settings.enabled) {\n\t\t// Compaction cannot recover this turn, so a configured fallback chain may\n\t\t// advance to a larger-context candidate instead of dead-ending.\n\t\tif (contextOverflow) this._contextOverflowUnresolved = true;\n\t\treturn;\n\t}\n\n\t// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false\n\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return;\n\n\t// Skip compaction checks if this assistant message is older than the latest\n\t// compaction boundary. This prevents a stale pre-compaction usage/error\n\t// from retriggering compaction on the first prompt after compaction.\n\tconst compactionBoundaryEntry = getLatestCompactionBoundaryEntry(this.sessionManager.getBranch());\n\tconst assistantIsFromBeforeCompactionBoundary =\n\t\tcompactionBoundaryEntry !== null &&\n\t\tassistantMessage.timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime();\n\tif (assistantIsFromBeforeCompactionBoundary) {\n\t\treturn;\n\t}\n\n\t// Case 1: Recoverable failure. Explicit/silent context overflow still uses\n\t// context metadata. A length stop below the model's original requested output\n\t// cap instead receives one compact-and-retry independent of context metadata.\n\t// This recovers a chat response; `truncated-range-recovery` separately parses\n\t// deletion records from a compaction planner response and is not involved here.\n\tconst desiredMaxOutput = this.model?.maxTokens ?? 0;\n\tconst recoverableLength =\n\t\tisLiveTurnCompletion &&\n\t\tsameModel &&\n\t\tassistantIsProjected &&\n\t\tisRecoverableLength(assistantMessage, desiredMaxOutput);\n\tif (contextOverflow || recoverableLength) {\n\t\tconst willRetry = assistantMessage.stopReason !== \"stop\";\n\t\tif (!willRetry) {\n\t\t\tawait this._runAutoCompaction(\"overflow\", false);\n\t\t\treturn;\n\t\t}\n\n\t\tconst recoveryAttempted = contextOverflow\n\t\t\t? this._overflowRecoveryAttempted\n\t\t\t: this._recoverableLengthRecoveryAttempted;\n\t\tif (recoveryAttempted) {\n\t\t\t// One recovery of this kind has already been spent on this turn. A real\n\t\t\t// context overflow may now advance to a larger-context fallback; a\n\t\t\t// recoverable output truncation stops without claiming overflow.\n\t\t\tif (contextOverflow) this._contextOverflowUnresolved = true;\n\t\t\tconst errorMessage = contextOverflow\n\t\t\t\t? \"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.\"\n\t\t\t\t: \"Response truncation recovery stopped after one retry.\";\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"overflow\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\t...(contextOverflow ? { unresolvedOverflow: true } : {}),\n\t\t\t\terrorMessage,\n\t\t\t});\n\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\treason: \"overflow\",\n\t\t\t\terrorMessage,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tfromExtension: false,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (contextOverflow) this._overflowRecoveryAttempted = true;\n\t\telse this._recoverableLengthRecoveryAttempted = true;\n\t\tlet outcome: AutoCompactionRunOutcome;\n\t\ttry {\n\t\t\toutcome = contextOverflow\n\t\t\t\t? await this._runAutoCompaction(\"overflow\", willRetry)\n\t\t\t\t: await this._runAutoCompaction(\"overflow\", willRetry, \"recoverable\");\n\t\t} catch (error) {\n\t\t\tif (contextOverflow) this._overflowRecoveryAttempted = false;\n\t\t\telse this._recoverableLengthRecoveryAttempted = false;\n\t\t\tthrow error;\n\t\t}\n\t\tif (outcome === \"compacted\" || outcome === \"failed\") return;\n\t\t// No boundary means there is no context to free. Keep this recovery\n\t\t// attempt spent while its one direct continuation is pending, so another\n\t\t// below-cap stop cannot start a new compaction cycle.\n\t\tif (\n\t\t\trecoverableLength &&\n\t\t\toutcome === \"not_compactable\" &&\n\t\t\tthis._compactionAbortController === undefined &&\n\t\t\tthis._manualCompactionPromise === undefined\n\t\t) {\n\t\t\tthis._resumeAfterLengthTruncation();\n\t\t\treturn;\n\t\t}\n\t\tif (contextOverflow) this._overflowRecoveryAttempted = false;\n\t\telse this._recoverableLengthRecoveryAttempted = false;\n\t\treturn;\n\t}\n\n\t// Case 2: Threshold - context is getting large\n\t// For errors or all-zero provider usage, estimate from message content.\n\tlet contextTokens = calculateContextTokens(assistantMessage.usage, assistantMessage.api);\n\tconst hasContextEdits =\n\t\tcurrentProjection?.entries.some((entry) => entry.sourceEntry.type === \"context_edit\") === true;\n\tif (currentProjection && hasContextEdits) {\n\t\t// Edited context invalidates usage captured before the edit; estimate the projection.\n\t\tcontextTokens = estimateProjectedContextTokens(currentProjection, branch).tokens;\n\t} else if (assistantMessage.stopReason === \"error\" || contextTokens === 0) {\n\t\tconst messages = this.agent.state.messages;\n\t\tconst estimate = estimateContextTokens(messages);\n\t\t// Without provider usage, estimate.tokens is the pure message-size estimate.\n\t\t// Only usage-backed estimates need the stale pre-compaction check.\n\t\tif (estimate.lastUsageIndex !== null) {\n\t\t\tconst usageMsg = messages[estimate.lastUsageIndex];\n\t\t\tif (\n\t\t\t\tcompactionBoundaryEntry &&\n\t\t\t\tusageMsg.role === \"assistant\" &&\n\t\t\t\t(usageMsg as AssistantMessage).timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime()\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tcontextTokens = estimate.tokens;\n\t}\n\tif (shouldCompact(contextTokens, contextWindow, settings)) {\n\t\tconst willRetry = shouldRetryAfterThresholdCompaction(assistantMessage, desiredMaxOutput, isLiveTurnCompletion);\n\t\tif (willRetry && isRetryWorthyOutputBudgetError(assistantMessage)) {\n\t\t\tif (this._outputBudgetErrorContinuationAttempts >= MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS) {\n\t\t\t\tconst errorMessage =\n\t\t\t\t\t\"Output-budget recovery stopped after a compact-and-retry attempt. Try reducing context or switching to a larger-context model.\";\n\t\t\t\tthis._emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason: \"threshold\",\n\t\t\t\t\tresult: undefined,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\terrorMessage,\n\t\t\t\t});\n\t\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\t\treason: \"threshold\",\n\t\t\t\t\terrorMessage,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\tfromExtension: false,\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis._outputBudgetErrorContinuationAttempts += 1;\n\t\t}\n\t\tawait this._runAutoCompaction(\"threshold\", willRetry);\n\t\treturn;\n\t}\n\n\t// A length stop that reached its requested output cap is not the\n\t// context-limited truncation recovered above. Preserve Atomic's bounded\n\t// direct-continuation policy for that distinct case.\n\tif (\n\t\tisLiveTurnCompletion &&\n\t\tisOutputCappedLengthStop(assistantMessage, desiredMaxOutput) &&\n\t\tthis._compactionAbortController === undefined &&\n\t\tthis._manualCompactionPromise === undefined\n\t) {\n\t\tthis._resumeAfterLengthTruncation();\n\t}\n}\n\nexport function isRetryWorthyLengthStop(assistantMessage: AssistantMessage): boolean {\n\treturn assistantMessage.stopReason === \"length\" && assistantMessage.usage.output > 0;\n}\n\nexport function isOutputCappedLengthStop(assistantMessage: AssistantMessage, desiredMaxOutput: number): boolean {\n\treturn isRetryWorthyLengthStop(assistantMessage) && !isRecoverableLength(assistantMessage, desiredMaxOutput);\n}\n\nfunction isJsonRecord(value: JsonValue): value is { [key: string]: JsonValue } {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction stringField(record: { [key: string]: JsonValue }, key: string): string | undefined {\n\tconst value = record[key];\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction parseProviderErrorDetails(errorMessage: string): ProviderErrorDetails | undefined {\n\tconst start = errorMessage.indexOf(\"{\");\n\tconst end = errorMessage.lastIndexOf(\"}\");\n\tif (start === -1 || end <= start) return undefined;\n\n\ttry {\n\t\tconst parsed = JSON.parse(errorMessage.slice(start, end + 1)) as JsonValue;\n\t\tif (!isJsonRecord(parsed)) return undefined;\n\n\t\tconst nestedError = parsed.error;\n\t\tif (nestedError !== undefined && isJsonRecord(nestedError)) {\n\t\t\treturn {\n\t\t\t\tmessage: stringField(nestedError, \"message\"),\n\t\t\t\tcode: stringField(nestedError, \"code\") ?? stringField(parsed, \"code\"),\n\t\t\t\tparam: stringField(nestedError, \"param\") ?? stringField(parsed, \"param\"),\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tmessage: stringField(parsed, \"message\"),\n\t\t\tcode: stringField(parsed, \"code\"),\n\t\t\tparam: stringField(parsed, \"param\"),\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isOutputBudgetUnderflowText(text: string): boolean {\n\tconst message = text.toLowerCase();\n\treturn OUTPUT_BUDGET_PARAMETER_PATTERN.test(message) && OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message);\n}\n\nfunction isStructuredOutputBudgetUnderflow(details: ProviderErrorDetails): boolean {\n\tconst message = details.message?.toLowerCase() ?? \"\";\n\tconst param = details.param?.toLowerCase();\n\tif (!OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message)) return false;\n\treturn param !== undefined\n\t\t? OUTPUT_BUDGET_PARAMETER_PATTERN.test(param)\n\t\t: OUTPUT_BUDGET_PARAMETER_PATTERN.test(message);\n}\n\nexport function isRetryWorthyOutputBudgetError(assistantMessage: AssistantMessage): boolean {\n\tif (assistantMessage.stopReason !== \"error\" || !assistantMessage.errorMessage) return false;\n\tif (assistantMessage.api !== \"openai-responses\") return false;\n\n\tconst structuredDetails = parseProviderErrorDetails(assistantMessage.errorMessage);\n\tif (structuredDetails && isStructuredOutputBudgetUnderflow(structuredDetails)) return true;\n\n\treturn isOutputBudgetUnderflowText(assistantMessage.errorMessage);\n}\n\nexport function shouldRetryAfterThresholdCompaction(\n\tassistantMessage: AssistantMessage,\n\tdesiredMaxOutput: number,\n\tisLiveTurnCompletion: boolean,\n): boolean {\n\treturn (\n\t\tisRetryWorthyOutputBudgetError(assistantMessage) ||\n\t\t(isLiveTurnCompletion && isOutputCappedLengthStop(assistantMessage, desiredMaxOutput))\n\t);\n}\n\n/**\n * Internal: remove an incomplete assistant from retry context before auto-continuing after compaction.\n */\n\nexport async function _dropTrailingAutoCompactionRetryAssistantIfPresent(this: AgentSession): Promise<void> {\n\t// The attempt stays in raw session history; a durable context edit omits it from\n\t// the model projection so the continuation resumes from the preceding input.\n\tawait this._omitTrailingAssistantAttempt(\n\t\t(assistant) => assistant.stopReason === \"error\" || assistant.stopReason === \"length\",\n\t);\n}\n\n/**\n * Internal: schedule a live post-event continuation after compaction_end listeners can flush queues.\n * The grace period preserves listener ordering. Queue-only probes wait for transient work to become\n * idle, while retry probes remain tied to the turn that scheduled them and are abandoned if another\n * turn owns the agent when the grace period ends.\n */\n\nexport function _schedulePostAutoCompactionContinuationProbe(\n\tthis: AgentSession,\n\t_reason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): void {\n\tif (this._agentRunAbortRequested) return;\n\tconst token = this._postCompactionContinuationToken + 1;\n\tthis._postCompactionContinuationToken = token;\n\tconst fallbackScopeGeneration = this._fallbackOriginGeneration;\n\tlet pending: Promise<void>;\n\tpending = new Promise<void>((resolve) => {\n\t\tsetTimeout(() => {\n\t\t\tvoid (async () => {\n\t\t\t\tconst settleIfOwned = async (): Promise<void> => {\n\t\t\t\t\tif (\n\t\t\t\t\t\tfallbackScopeGeneration === undefined ||\n\t\t\t\t\t\tthis._fallbackOriginGeneration !== fallbackScopeGeneration ||\n\t\t\t\t\t\ttypeof this._settleFallbackModelScope !== \"function\"\n\t\t\t\t\t)\n\t\t\t\t\t\treturn;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._settleFallbackModelScope();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// A listener must not strand the continuation waiter. The fallback\n\t\t\t\t\t\t// state was already settled before lifecycle notifications ran.\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tif (this._agentRunAbortRequested) return;\n\t\t\t\t\tif (willRetry) {\n\t\t\t\t\t\tif (this._postCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait this.agent.waitForIdle();\n\t\t\t\t\t\tif (this._postCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t\tif (!this.agent.hasQueuedMessages()) {\n\t\t\t\t\t\t\tawait settleIfOwned();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// A queued message starts the next user turn. Settle before Agent\n\t\t\t\t\t\t// snapshots the next request's model.\n\t\t\t\t\t\tawait settleIfOwned();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this._pendingPostCompactionContinuation !== pending) return;\n\t\t\t\t\t// Clear this probe before entering the next run. Its promise is\n\t\t\t\t\t// still awaited by _awaitPendingPostCompactionContinuation, but\n\t\t\t\t\t// the nested agent_end must be free to schedule a new probe.\n\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\tawait this._resumeAfterAutoCompaction();\n\t\t\t\t\tif (willRetry && this._pendingPostCompactionContinuation === undefined) {\n\t\t\t\t\t\tawait settleIfOwned();\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tif (this._pendingPostCompactionContinuation === pending) {\n\t\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\t}\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t})();\n\t\t}, 100);\n\t});\n\tthis._pendingPostCompactionContinuation = pending;\n}\n\nexport async function _awaitPendingPostCompactionContinuation(this: AgentSession): Promise<void> {\n\t// A continuation can schedule another probe (for example a second output-cap\n\t// stop). Keep the owning prompt alive until the whole automatic chain drains.\n\twhile (this._pendingPostCompactionContinuation !== undefined) {\n\t\tawait this._pendingPostCompactionContinuation;\n\t}\n}\n\n/**\n * Internal: resume generation after successful auto-compaction only when active work remains.\n */\n\nexport async function _resumeAfterAutoCompaction(this: AgentSession): Promise<void> {\n\ttry {\n\t\tawait this._runAgentContinue();\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthis._emit({\n\t\t\ttype: \"agent_continue_error\",\n\t\t\tsource: \"post_compaction\",\n\t\t\terrorMessage: `Post-compaction continuation failed: ${message}`,\n\t\t});\n\t}\n}\n\n/**\n * Internal: resume a response that reached its requested output cap when the\n * context does not warrant compaction. Bounded so a model that repeatedly\n * stops at that cap can still terminate.\n */\n\nexport function _resumeAfterLengthTruncation(this: AgentSession): void {\n\tif (this._lengthContinuationAttempts >= MAX_LENGTH_CONTINUATION_ATTEMPTS) return;\n\tthis._lengthContinuationAttempts += 1;\n\t// agent.continue() rejects an assistant tail; drop the incomplete\n\t// length-stopped message so the preceding user/tool-result anchors the\n\t// continuation. It remains persisted in session history.\n\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\tthis._schedulePostAutoCompactionContinuationProbe(\"threshold\", true);\n}\n\n/**\n * Whether an overflow turn is now unrecoverable by compaction, recording it on\n * the session so a configured fallback chain may advance to another candidate.\n */\nfunction overflowUnresolved(this: AgentSession, loadBearing: boolean, aborted = false): boolean | undefined {\n\tif (!loadBearing || aborted) return undefined;\n\tthis._contextOverflowUnresolved = true;\n\treturn true;\n}\n\nexport function hasPendingManualCompactionTakeover(this: AgentSession): boolean {\n\treturn this._compactionReason === \"manual\" && this._compactionAbortController !== undefined;\n}\n\nexport async function _runAutoCompaction(\n\tthis: AgentSession,\n\treason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n\turgency: CompactionUrgency = reason === \"overflow\" ? \"load_bearing\" : \"recoverable\",\n): Promise<AutoCompactionRunOutcome> {\n\tif (\n\t\tthis._compactionAbortController !== undefined ||\n\t\tthis._manualCompactionPromise !== undefined ||\n\t\tthis._autoCompactionAbortController !== undefined\n\t)\n\t\treturn \"deferred\";\n\n\tconst controller = new AbortController();\n\tconst completion = createAutoCompactionCompletion();\n\tthis._autoCompactionAbortController = controller;\n\tthis._autoCompactionCompletion = completion.promise;\n\tthis._compactionReason = reason;\n\tlet fromExtension = false;\n\ttry {\n\t\tthis._emit({ type: \"compaction_start\", reason });\n\t} catch (error) {\n\t\t// A throwing start listener still propagates, matching current behavior,\n\t\t// but must not leave ownership published with no owner running.\n\t\tif (this._autoCompactionAbortController === controller) this._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t\tcompletion.resolve();\n\t\tif (this._autoCompactionCompletion === completion.promise) this._autoCompactionCompletion = undefined;\n\t\tthrow error;\n\t}\n\n\ttry {\n\t\tcontroller.signal.throwIfAborted();\n\t\tif (!this.model) {\n\t\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved.call(this, urgency === \"load_bearing\"),\n\t\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\t});\n\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\treason,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tfromExtension: false,\n\t\t\t});\n\t\t\treturn manualTakeoverPending ? \"deferred\" : \"failed\";\n\t\t}\n\n\t\t// Resolve auth only after extension hooks have had an opportunity to cancel\n\t\t// compaction or provide compacted text, so local extension compaction does not\n\t\t// require provider credentials. Missing auth then fails model-driven compaction\n\t\t// before persistence or continuation, matching other provider-call failures.\n\t\tconst result = await this._applyVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async (candidate) => {\n\t\t\t\tconst authResult = await this._getRequiredRequestAuth(candidate, controller.signal);\n\t\t\t\treturn authResult.apiKey || authResult.headers ? authForStream(this, authResult) : undefined;\n\t\t\t},\n\t\t\tabortController: controller,\n\t\t\tbackupLabel: urgency === \"load_bearing\" ? \"overflow-auto-compact\" : \"auto-compact\",\n\t\t\treason,\n\t\t\turgency,\n\t\t\tonCompactionSource: (value) => {\n\t\t\t\tfromExtension = value;\n\t\t\t},\n\t\t\t// Only an actual context overflow proved the context cannot fit. A\n\t\t\t// recoverable length stop must never reach the fresh-context fallback.\n\t\t\t...(urgency === \"load_bearing\" ? { allowSmallRegion: true } : {}),\n\t\t});\n\t\tif (!result) {\n\t\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved.call(this, urgency === \"load_bearing\"),\n\t\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\t});\n\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\treason,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tfromExtension,\n\t\t\t});\n\t\t\treturn manualTakeoverPending ? \"deferred\" : \"not_compactable\";\n\t\t}\n\n\t\tif (willRetry) {\n\t\t\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\t\t}\n\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult,\n\t\t\taborted: false,\n\t\t\twillRetry,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t});\n\t\tif (!hasPendingManualCompactionTakeover.call(this)) {\n\t\t\tthis._schedulePostAutoCompactionContinuationProbe(reason, willRetry);\n\t\t}\n\t\treturn \"compacted\";\n\t} catch (error) {\n\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\tconst aborted = controller.signal.aborted;\n\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\n\t\tconst formattedErrorMessage = aborted\n\t\t\t? undefined\n\t\t\t: reason === \"overflow\"\n\t\t\t\t? urgency === \"recoverable\"\n\t\t\t\t\t? `Response truncation recovery failed: ${errorMessage}`\n\t\t\t\t\t: `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t: `Auto-compaction failed: ${errorMessage}`;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tunresolvedOverflow: overflowUnresolved.call(this, urgency === \"load_bearing\", aborted),\n\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\terrorMessage: formattedErrorMessage,\n\t\t});\n\t\tawait emitSessionCompactFailed(this, {\n\t\t\treason,\n\t\t\terrorMessage: formattedErrorMessage,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tfromExtension,\n\t\t});\n\t\treturn manualTakeoverPending ? \"deferred\" : \"failed\";\n\t} finally {\n\t\tif (this._autoCompactionAbortController === controller) this._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t\tcompletion.resolve();\n\t\tif (this._autoCompactionCompletion === completion.promise) this._autoCompactionCompletion = undefined;\n\t}\n}\n\n/**\n * Toggle auto-compaction setting.\n */\n\nexport const agentSessionAutoCompactionMethods = {\n\t_awaitPendingPostCompactionContinuation,\n\t_checkCompaction,\n\t_dropTrailingAutoCompactionRetryAssistantIfPresent,\n\t_schedulePostAutoCompactionContinuationProbe,\n\t_resumeAfterAutoCompaction,\n\t_resumeAfterLengthTruncation,\n\t_runAutoCompaction,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-auto-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-auto-compaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAEzE,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAEN,sBAAsB,EACtB,qBAAqB,EACrB,8BAA8B,EAC9B,aAAa,GACb,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,+BAA+B,EAAE,MAAM,yCAAyC,CAAC;AAC1F,OAAO,EAAyB,gCAAgC,EAAE,MAAM,sBAAsB,CAAC;AAE/F;;;;GAIG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAAC,CAAC;AAElD,MAAM,CAAC,MAAM,6CAA6C,GAAG,CAAC,CAAC;AAS/D,6EAA6E;AAC7E,MAAM,UAAU,8BAA8B;IAI7C,IAAI,OAAoB,CAAC;IACzB,MAAM,OAAO,GAAG,IAAI,OAAO,CAAO,CAAC,IAAI,EAAE,EAAE;QAC1C,OAAO,GAAG,IAAI,CAAC;IAChB,CAAC,CAAC,CAAC;IACH,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAC7B,CAAC;AAED,MAAM,+BAA+B,GAAG,uBAAuB,CAAC;AAChE,MAAM,+BAA+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AAK,cAAc,EAAE,OAAO,CAAC;YACtF,GAAG,CAAC,qBAAqB,CAAC,CAAC,CAAC,EAAE,qBAAqB,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACjE,YAAY,EAAE,qBAAqB;SACnC,CAAC,CAAC;QACH,MAAM,wBAAwB,CAAC,IAAI,EAAE;YACpC,MAAM;YACN,YAAY,EAAE,qBAAqB;YACnC,OAAO;YACP,SAAS,EAAE,KAAK;YAChB,aAAa;SACb,CAAC,CAAC;QACH,OAAO,qBAAqB,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,QAAQ,CAAC;IACtD,CAAC;YAAS,CAAC;QACV,IAAI,IAAI,CAAC,8BAA8B,KAAK,UAAU;YAAE,IAAI,CAAC,8BAA8B,GAAG,SAAS,CAAC;QACxG,IAAI,IAAI,CAAC,iBAAiB,KAAK,MAAM;YAAE,IAAI,CAAC,iBAAiB,GAAG,SAAS,CAAC;QAC1E,UAAU,CAAC,OAAO,EAAE,CAAC;QACrB,IAAI,IAAI,CAAC,yBAAyB,KAAK,UAAU,CAAC,OAAO;YAAE,IAAI,CAAC,yBAAyB,GAAG,SAAS,CAAC;IACvG,CAAC;AACF,CAAC;AAED;;GAEG;AAEH,MAAM,CAAC,MAAM,iCAAiC,GAAG;IAChD,uCAAuC;IACvC,gBAAgB;IAChB,kDAAkD;IAClD,4CAA4C;IAC5C,0BAA0B;IAC1B,4BAA4B;IAC5B,kBAAkB;CAClB,CAAC","sourcesContent":["import type { AssistantMessage } from \"@bastani/pi-ai/compat\";\nimport { isContextOverflow, isRecoverableLength } from \"@bastani/pi-ai/compat\";\nimport { emitSessionCompactFailed } from \"./agent-session-compaction.ts\";\nimport type { AgentSessionInternalSurface as AgentSession, AutoCompactionRunOutcome } from \"./agent-session-methods.ts\";\nimport { authForStream } from \"./agent-session-models.ts\";\nimport {\n\ttype CompactionUrgency,\n\tcalculateContextTokens,\n\testimateContextTokens,\n\testimateProjectedContextTokens,\n\tshouldCompact,\n} from \"./compaction/index.ts\";\nimport { MIN_RESPONSES_MAX_OUTPUT_TOKENS } from \"./openai-responses-payload-sanitizer.ts\";\nimport { type ContextEditEntry, getLatestCompactionBoundaryEntry } from \"./session-manager.ts\";\n\n/**\n * Upper bound on direct continuations after a response reaches its requested\n * output cap. Context-limited truncations use one compact-and-retry attempt\n * instead; this bound preserves Atomic's separate output-cap continuation.\n */\nexport const MAX_LENGTH_CONTINUATION_ATTEMPTS = 3;\n\nexport const MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS = 1;\n\ntype JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\ntype ProviderErrorDetails = {\n\tmessage?: string;\n\tcode?: string;\n\tparam?: string;\n};\n\n/** Create the settlement boundary for a regular automatic compaction run. */\nexport function createAutoCompactionCompletion(): {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n} {\n\tlet resolve!: () => void;\n\tconst promise = new Promise<void>((done) => {\n\t\tresolve = done;\n\t});\n\treturn { promise, resolve };\n}\n\nconst OUTPUT_BUDGET_PARAMETER_PATTERN = /\\bmax_output_tokens\\b/;\nconst OUTPUT_BUDGET_UNDERFLOW_PATTERN = new RegExp(\n\t`(?:integer\\\\s+below\\\\s+minimum\\\\s+value|expected\\\\s+(?:a\\\\s+)?value\\\\s*>=\\\\s*${MIN_RESPONSES_MAX_OUTPUT_TOKENS}|got\\\\s+1\\\\s+instead)`,\n);\n\nexport async function _checkCompaction(\n\tthis: AgentSession,\n\tassistantMessage: AssistantMessage,\n\tskipAbortedCheck = true,\n): Promise<void> {\n\tif (this._agentRunAbortRequested) return;\n\tif (this._pendingPostToolCompactionGuard) {\n\t\tconst { result } = this._pendingPostToolCompactionGuard;\n\t\tthis._pendingPostToolCompactionGuard = undefined;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"threshold\",\n\t\t\tresult,\n\t\t\taborted: true,\n\t\t\twillRetry: false,\n\t\t\tmidTurn: true,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t});\n\t}\n\tif (\n\t\tthis._postToolCompactionPreflightError !== undefined &&\n\t\tassistantMessage.errorMessage === this._postToolCompactionPreflightError\n\t) {\n\t\tthis._postToolCompactionPreflightError = undefined;\n\t\treturn;\n\t}\n\t// The agent_end path passes skipAbortedCheck=true; the pre-prompt path passes\n\t// false. Only the live turn-completion path may auto-continue a truncated\n\t// response — before a fresh user prompt we must not resume the old turn.\n\tconst isLiveTurnCompletion = skipAbortedCheck;\n\tconst settings = this.settingsManager.getCompactionSettings(this.model);\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\t// Skip overflow handling if the message came from a different model.\n\t// This handles the case where user switched from a smaller-context model (e.g. opus)\n\t// to a larger-context model (e.g. codex) - the overflow error from the old model\n\t// shouldn't trigger compaction for the new model.\n\tconst sameModel =\n\t\tthis.model !== undefined &&\n\t\tassistantMessage.provider === this.model.provider &&\n\t\tassistantMessage.model === this.model.id;\n\t// Usage and overflow signals belong to the request that produced this assistant.\n\t// A later context edit or compaction changes what the next request contains, so\n\t// only a projected, unedited assistant may drive usage-based decisions; an explicit\n\t// provider overflow error still recovers while its attempt is retained.\n\t// Guarded because fallback suites drive this function on a synthetic session.\n\tconst projectionAware =\n\t\ttypeof this.sessionManager?.buildSessionProjection === \"function\" &&\n\t\ttypeof this._findPersistedMessageEntryId === \"function\";\n\tconst currentProjection = projectionAware ? this.sessionManager.buildSessionProjection() : undefined;\n\tconst branch = projectionAware ? this.sessionManager.getBranch() : [];\n\tconst assistantEntryId = projectionAware ? this._findPersistedMessageEntryId(assistantMessage) : undefined;\n\tconst assistantIsProjected =\n\t\tassistantEntryId === undefined ||\n\t\tcurrentProjection?.entries.some(\n\t\t\t(entry) =>\n\t\t\t\tentry.sourceEntry.id === assistantEntryId && entry.messages.some((message) => message.role === \"assistant\"),\n\t\t) === true;\n\tconst assistantIndex = assistantEntryId ? branch.findIndex((entry) => entry.id === assistantEntryId) : -1;\n\tconst entriesAfterAssistant = assistantIndex >= 0 ? branch.slice(assistantIndex + 1) : [];\n\tconst hasPostAssistantContextEdit = entriesAfterAssistant.some((entry) => entry.type === \"context_edit\");\n\tconst latestAssistantEdit = entriesAfterAssistant\n\t\t.filter(\n\t\t\t(entry): entry is ContextEditEntry => entry.type === \"context_edit\" && entry.targetId === assistantEntryId,\n\t\t)\n\t\t.at(-1);\n\tconst assistantRetainedForExplicitRecovery =\n\t\tassistantEntryId === undefined ||\n\t\t(!entriesAfterAssistant.some((entry) => entry.type === \"compaction\") &&\n\t\t\tlatestAssistantEdit?.replacement !== null);\n\tconst assistantUsageMatchesProjection = assistantIsProjected && !hasPostAssistantContextEdit;\n\tconst explicitOverflow = assistantMessage.stopReason === \"error\" && isContextOverflow(assistantMessage);\n\tconst contextOverflow =\n\t\tsameModel &&\n\t\t((explicitOverflow && assistantRetainedForExplicitRecovery) ||\n\t\t\t(assistantUsageMatchesProjection && isContextOverflow(assistantMessage, contextWindow)));\n\tif (!settings.enabled) {\n\t\t// Compaction cannot recover this turn, so a configured fallback chain may\n\t\t// advance to a larger-context candidate instead of dead-ending.\n\t\tif (contextOverflow) this._contextOverflowUnresolved = true;\n\t\treturn;\n\t}\n\n\t// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false\n\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return;\n\n\t// Skip compaction checks if this assistant message is older than the latest\n\t// compaction boundary. This prevents a stale pre-compaction usage/error\n\t// from retriggering compaction on the first prompt after compaction.\n\tconst compactionBoundaryEntry = getLatestCompactionBoundaryEntry(this.sessionManager.getBranch());\n\tconst assistantIsFromBeforeCompactionBoundary =\n\t\tcompactionBoundaryEntry !== null &&\n\t\tassistantMessage.timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime();\n\tif (assistantIsFromBeforeCompactionBoundary) {\n\t\treturn;\n\t}\n\n\t// Case 1: Recoverable failure. Explicit/silent context overflow still uses\n\t// context metadata. A length stop below the model's original requested output\n\t// cap instead receives one compact-and-retry independent of context metadata.\n\t// This recovers a chat response; `truncated-range-recovery` separately parses\n\t// deletion records from a compaction planner response and is not involved here.\n\tconst desiredMaxOutput = this.model?.maxTokens ?? 0;\n\tconst recoverableLength =\n\t\tisLiveTurnCompletion &&\n\t\tsameModel &&\n\t\tassistantIsProjected &&\n\t\tisRecoverableLength(assistantMessage, desiredMaxOutput);\n\tif (contextOverflow || recoverableLength) {\n\t\tconst willRetry = assistantMessage.stopReason !== \"stop\";\n\t\tif (!willRetry) {\n\t\t\tawait this._runAutoCompaction(\"overflow\", false);\n\t\t\treturn;\n\t\t}\n\n\t\tconst recoveryAttempted = contextOverflow\n\t\t\t? this._overflowRecoveryAttempted\n\t\t\t: this._recoverableLengthRecoveryAttempted;\n\t\tif (recoveryAttempted) {\n\t\t\t// One recovery of this kind has already been spent on this turn. A real\n\t\t\t// context overflow may now advance to a larger-context fallback; a\n\t\t\t// recoverable output truncation stops without claiming overflow.\n\t\t\tif (contextOverflow) this._contextOverflowUnresolved = true;\n\t\t\tconst errorMessage = contextOverflow\n\t\t\t\t? \"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.\"\n\t\t\t\t: \"Response truncation recovery stopped after one retry.\";\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"overflow\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\t...(contextOverflow ? { unresolvedOverflow: true } : {}),\n\t\t\t\terrorMessage,\n\t\t\t});\n\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\treason: \"overflow\",\n\t\t\t\terrorMessage,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tfromExtension: false,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (contextOverflow) this._overflowRecoveryAttempted = true;\n\t\telse this._recoverableLengthRecoveryAttempted = true;\n\t\tlet outcome: AutoCompactionRunOutcome;\n\t\ttry {\n\t\t\toutcome = contextOverflow\n\t\t\t\t? await this._runAutoCompaction(\"overflow\", willRetry)\n\t\t\t\t: await this._runAutoCompaction(\"overflow\", willRetry, \"recoverable\");\n\t\t} catch (error) {\n\t\t\tif (contextOverflow) this._overflowRecoveryAttempted = false;\n\t\t\telse this._recoverableLengthRecoveryAttempted = false;\n\t\t\tthrow error;\n\t\t}\n\t\tif (outcome === \"compacted\" || outcome === \"failed\") return;\n\t\t// No boundary means there is no context to free. Keep this recovery\n\t\t// attempt spent while its one direct continuation is pending, so another\n\t\t// below-cap stop cannot start a new compaction cycle.\n\t\tif (\n\t\t\trecoverableLength &&\n\t\t\toutcome === \"not_compactable\" &&\n\t\t\tthis._compactionAbortController === undefined &&\n\t\t\tthis._manualCompactionPromise === undefined\n\t\t) {\n\t\t\tthis._resumeAfterLengthTruncation();\n\t\t\treturn;\n\t\t}\n\t\tif (contextOverflow) this._overflowRecoveryAttempted = false;\n\t\telse this._recoverableLengthRecoveryAttempted = false;\n\t\treturn;\n\t}\n\n\t// Case 2: Threshold - context is getting large\n\t// For errors or all-zero provider usage, estimate from message content.\n\tlet contextTokens = calculateContextTokens(assistantMessage.usage, assistantMessage.api);\n\tconst hasContextEdits =\n\t\tcurrentProjection?.entries.some((entry) => entry.sourceEntry.type === \"context_edit\") === true;\n\tif (currentProjection && hasContextEdits) {\n\t\t// Edited context invalidates usage captured before the edit; estimate the projection.\n\t\tcontextTokens = estimateProjectedContextTokens(currentProjection, branch).tokens;\n\t} else if (assistantMessage.stopReason === \"error\" || contextTokens === 0) {\n\t\tconst messages = this.agent.state.messages;\n\t\tconst estimate = estimateContextTokens(messages);\n\t\t// Without provider usage, estimate.tokens is the pure message-size estimate.\n\t\t// Only usage-backed estimates need the stale pre-compaction check.\n\t\tif (estimate.lastUsageIndex !== null) {\n\t\t\tconst usageMsg = messages[estimate.lastUsageIndex];\n\t\t\tif (\n\t\t\t\tcompactionBoundaryEntry &&\n\t\t\t\tusageMsg.role === \"assistant\" &&\n\t\t\t\t(usageMsg as AssistantMessage).timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime()\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tcontextTokens = estimate.tokens;\n\t}\n\tif (shouldCompact(contextTokens, contextWindow, settings)) {\n\t\tconst willRetry = shouldRetryAfterThresholdCompaction(assistantMessage, desiredMaxOutput, isLiveTurnCompletion);\n\t\tif (willRetry && isRetryWorthyOutputBudgetError(assistantMessage)) {\n\t\t\tif (this._outputBudgetErrorContinuationAttempts >= MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS) {\n\t\t\t\tconst errorMessage =\n\t\t\t\t\t\"Output-budget recovery stopped after a compact-and-retry attempt. Try reducing context or switching to a larger-context model.\";\n\t\t\t\tthis._emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason: \"threshold\",\n\t\t\t\t\tresult: undefined,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\terrorMessage,\n\t\t\t\t});\n\t\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\t\treason: \"threshold\",\n\t\t\t\t\terrorMessage,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\tfromExtension: false,\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis._outputBudgetErrorContinuationAttempts += 1;\n\t\t}\n\t\tawait this._runAutoCompaction(\"threshold\", willRetry);\n\t\treturn;\n\t}\n\n\t// A length stop that reached its requested output cap is not the\n\t// context-limited truncation recovered above. Preserve Atomic's bounded\n\t// direct-continuation policy for that distinct case.\n\tif (\n\t\tisLiveTurnCompletion &&\n\t\tisOutputCappedLengthStop(assistantMessage, desiredMaxOutput) &&\n\t\tthis._compactionAbortController === undefined &&\n\t\tthis._manualCompactionPromise === undefined\n\t) {\n\t\tthis._resumeAfterLengthTruncation();\n\t}\n}\n\nexport function isRetryWorthyLengthStop(assistantMessage: AssistantMessage): boolean {\n\treturn assistantMessage.stopReason === \"length\" && assistantMessage.usage.output > 0;\n}\n\nexport function isOutputCappedLengthStop(assistantMessage: AssistantMessage, desiredMaxOutput: number): boolean {\n\treturn isRetryWorthyLengthStop(assistantMessage) && !isRecoverableLength(assistantMessage, desiredMaxOutput);\n}\n\nfunction isJsonRecord(value: JsonValue): value is { [key: string]: JsonValue } {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction stringField(record: { [key: string]: JsonValue }, key: string): string | undefined {\n\tconst value = record[key];\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction parseProviderErrorDetails(errorMessage: string): ProviderErrorDetails | undefined {\n\tconst start = errorMessage.indexOf(\"{\");\n\tconst end = errorMessage.lastIndexOf(\"}\");\n\tif (start === -1 || end <= start) return undefined;\n\n\ttry {\n\t\tconst parsed = JSON.parse(errorMessage.slice(start, end + 1)) as JsonValue;\n\t\tif (!isJsonRecord(parsed)) return undefined;\n\n\t\tconst nestedError = parsed.error;\n\t\tif (nestedError !== undefined && isJsonRecord(nestedError)) {\n\t\t\treturn {\n\t\t\t\tmessage: stringField(nestedError, \"message\"),\n\t\t\t\tcode: stringField(nestedError, \"code\") ?? stringField(parsed, \"code\"),\n\t\t\t\tparam: stringField(nestedError, \"param\") ?? stringField(parsed, \"param\"),\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tmessage: stringField(parsed, \"message\"),\n\t\t\tcode: stringField(parsed, \"code\"),\n\t\t\tparam: stringField(parsed, \"param\"),\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isOutputBudgetUnderflowText(text: string): boolean {\n\tconst message = text.toLowerCase();\n\treturn OUTPUT_BUDGET_PARAMETER_PATTERN.test(message) && OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message);\n}\n\nfunction isStructuredOutputBudgetUnderflow(details: ProviderErrorDetails): boolean {\n\tconst message = details.message?.toLowerCase() ?? \"\";\n\tconst param = details.param?.toLowerCase();\n\tif (!OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message)) return false;\n\treturn param !== undefined\n\t\t? OUTPUT_BUDGET_PARAMETER_PATTERN.test(param)\n\t\t: OUTPUT_BUDGET_PARAMETER_PATTERN.test(message);\n}\n\nexport function isRetryWorthyOutputBudgetError(assistantMessage: AssistantMessage): boolean {\n\tif (assistantMessage.stopReason !== \"error\" || !assistantMessage.errorMessage) return false;\n\tif (assistantMessage.api !== \"openai-responses\") return false;\n\n\tconst structuredDetails = parseProviderErrorDetails(assistantMessage.errorMessage);\n\tif (structuredDetails && isStructuredOutputBudgetUnderflow(structuredDetails)) return true;\n\n\treturn isOutputBudgetUnderflowText(assistantMessage.errorMessage);\n}\n\nexport function shouldRetryAfterThresholdCompaction(\n\tassistantMessage: AssistantMessage,\n\tdesiredMaxOutput: number,\n\tisLiveTurnCompletion: boolean,\n): boolean {\n\treturn (\n\t\tisRetryWorthyOutputBudgetError(assistantMessage) ||\n\t\t(isLiveTurnCompletion && isOutputCappedLengthStop(assistantMessage, desiredMaxOutput))\n\t);\n}\n\n/**\n * Internal: remove an incomplete assistant from retry context before auto-continuing after compaction.\n */\n\nexport async function _dropTrailingAutoCompactionRetryAssistantIfPresent(this: AgentSession): Promise<void> {\n\t// The attempt stays in raw session history; a durable context edit omits it from\n\t// the model projection so the continuation resumes from the preceding input.\n\tawait this._omitTrailingAssistantAttempt(\n\t\t(assistant) => assistant.stopReason === \"error\" || assistant.stopReason === \"length\",\n\t);\n}\n\n/**\n * Internal: schedule a live post-event continuation after compaction_end listeners can flush queues.\n * The grace period preserves listener ordering. Queue-only probes wait for transient work to become\n * idle, while retry probes remain tied to the turn that scheduled them and are abandoned if another\n * turn owns the agent when the grace period ends.\n */\n\nexport function _schedulePostAutoCompactionContinuationProbe(\n\tthis: AgentSession,\n\t_reason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): void {\n\tif (this._agentRunAbortRequested) return;\n\tconst token = this._postCompactionContinuationToken + 1;\n\tthis._postCompactionContinuationToken = token;\n\tconst fallbackScopeGeneration = this._fallbackOriginGeneration;\n\tlet pending: Promise<void>;\n\tpending = new Promise<void>((resolve) => {\n\t\tsetTimeout(() => {\n\t\t\tvoid (async () => {\n\t\t\t\tconst settleIfOwned = async (): Promise<void> => {\n\t\t\t\t\tif (\n\t\t\t\t\t\tfallbackScopeGeneration === undefined ||\n\t\t\t\t\t\tthis._fallbackOriginGeneration !== fallbackScopeGeneration ||\n\t\t\t\t\t\ttypeof this._settleFallbackModelScope !== \"function\"\n\t\t\t\t\t)\n\t\t\t\t\t\treturn;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._settleFallbackModelScope();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// A listener must not strand the continuation waiter. The fallback\n\t\t\t\t\t\t// state was already settled before lifecycle notifications ran.\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tif (this._agentRunAbortRequested) return;\n\t\t\t\t\tif (willRetry) {\n\t\t\t\t\t\tif (this._postCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait this.agent.waitForIdle();\n\t\t\t\t\t\tif (this._postCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t\tif (!this.agent.hasQueuedMessages()) {\n\t\t\t\t\t\t\tawait settleIfOwned();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// A queued message starts the next user turn. Settle before Agent\n\t\t\t\t\t\t// snapshots the next request's model.\n\t\t\t\t\t\tawait settleIfOwned();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this._pendingPostCompactionContinuation !== pending) return;\n\t\t\t\t\t// Clear this probe before entering the next run. Its promise is\n\t\t\t\t\t// still awaited by _awaitPendingPostCompactionContinuation, but\n\t\t\t\t\t// the nested agent_end must be free to schedule a new probe.\n\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\tawait this._resumeAfterAutoCompaction();\n\t\t\t\t\tif (willRetry && this._pendingPostCompactionContinuation === undefined) {\n\t\t\t\t\t\tawait settleIfOwned();\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tif (this._pendingPostCompactionContinuation === pending) {\n\t\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\t}\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t})();\n\t\t}, 100);\n\t});\n\tthis._pendingPostCompactionContinuation = pending;\n}\n\nexport async function _awaitPendingPostCompactionContinuation(this: AgentSession): Promise<void> {\n\t// A continuation can schedule another probe (for example a second output-cap\n\t// stop). Keep the owning prompt alive until the whole automatic chain drains.\n\twhile (this._pendingPostCompactionContinuation !== undefined) {\n\t\tawait this._pendingPostCompactionContinuation;\n\t}\n}\n\n/**\n * Internal: resume generation after successful auto-compaction only when active work remains.\n */\n\nexport async function _resumeAfterAutoCompaction(this: AgentSession): Promise<void> {\n\ttry {\n\t\tawait this._runAgentContinue();\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthis._emit({\n\t\t\ttype: \"agent_continue_error\",\n\t\t\tsource: \"post_compaction\",\n\t\t\terrorMessage: `Post-compaction continuation failed: ${message}`,\n\t\t});\n\t}\n}\n\n/**\n * Internal: resume a response that reached its requested output cap when the\n * context does not warrant compaction. Bounded so a model that repeatedly\n * stops at that cap can still terminate.\n */\n\nexport function _resumeAfterLengthTruncation(this: AgentSession): void {\n\tif (this._lengthContinuationAttempts >= MAX_LENGTH_CONTINUATION_ATTEMPTS) return;\n\tthis._lengthContinuationAttempts += 1;\n\t// agent.continue() rejects an assistant tail; drop the incomplete\n\t// length-stopped message so the preceding user/tool-result anchors the\n\t// continuation. It remains persisted in session history.\n\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\tthis._schedulePostAutoCompactionContinuationProbe(\"threshold\", true);\n}\n\n/**\n * Whether an overflow turn is now unrecoverable by compaction, recording it on\n * the session so a configured fallback chain may advance to another candidate.\n */\nfunction overflowUnresolved(this: AgentSession, loadBearing: boolean, aborted = false): boolean | undefined {\n\tif (!loadBearing || aborted) return undefined;\n\tthis._contextOverflowUnresolved = true;\n\treturn true;\n}\n\nexport function hasPendingManualCompactionTakeover(this: AgentSession): boolean {\n\treturn this._compactionReason === \"manual\" && this._compactionAbortController !== undefined;\n}\n\nexport async function _runAutoCompaction(\n\tthis: AgentSession,\n\treason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n\turgency: CompactionUrgency = reason === \"overflow\" ? \"load_bearing\" : \"recoverable\",\n): Promise<AutoCompactionRunOutcome> {\n\tif (\n\t\tthis._compactionAbortController !== undefined ||\n\t\tthis._manualCompactionPromise !== undefined ||\n\t\tthis._autoCompactionAbortController !== undefined\n\t)\n\t\treturn \"deferred\";\n\n\tconst controller = new AbortController();\n\tconst completion = createAutoCompactionCompletion();\n\tthis._autoCompactionAbortController = controller;\n\tthis._autoCompactionCompletion = completion.promise;\n\tthis._compactionReason = reason;\n\tlet fromExtension = false;\n\ttry {\n\t\tthis._emit({ type: \"compaction_start\", reason });\n\t} catch (error) {\n\t\t// A throwing start listener still propagates, matching current behavior,\n\t\t// but must not leave ownership published with no owner running.\n\t\tif (this._autoCompactionAbortController === controller) this._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t\tcompletion.resolve();\n\t\tif (this._autoCompactionCompletion === completion.promise) this._autoCompactionCompletion = undefined;\n\t\tthrow error;\n\t}\n\n\ttry {\n\t\tcontroller.signal.throwIfAborted();\n\t\tif (!this.model) {\n\t\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved.call(this, urgency === \"load_bearing\"),\n\t\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\t});\n\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\treason,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tfromExtension: false,\n\t\t\t});\n\t\t\treturn manualTakeoverPending ? \"deferred\" : \"failed\";\n\t\t}\n\n\t\t// Resolve auth only after extension hooks have had an opportunity to cancel\n\t\t// compaction or provide compacted text, so local extension compaction does not\n\t\t// require provider credentials. Missing auth then fails model-driven compaction\n\t\t// before persistence or continuation, matching other provider-call failures.\n\t\tconst result = await this._applyVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async (candidate, signal) => {\n\t\t\t\tconst authResult = await this._getRequiredRequestAuth(candidate, signal ?? controller.signal);\n\t\t\t\treturn authResult.apiKey || authResult.headers ? authForStream(this, authResult) : undefined;\n\t\t\t},\n\t\t\tabortController: controller,\n\t\t\tbackupLabel: urgency === \"load_bearing\" ? \"overflow-auto-compact\" : \"auto-compact\",\n\t\t\treason,\n\t\t\turgency,\n\t\t\tonCompactionSource: (value) => {\n\t\t\t\tfromExtension = value;\n\t\t\t},\n\t\t\t// Only an actual context overflow proved the context cannot fit. A\n\t\t\t// recoverable length stop must never reach the fresh-context fallback.\n\t\t\t...(urgency === \"load_bearing\" ? { allowSmallRegion: true } : {}),\n\t\t});\n\t\tif (!result) {\n\t\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved.call(this, urgency === \"load_bearing\"),\n\t\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\t});\n\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\treason,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tfromExtension,\n\t\t\t});\n\t\t\treturn manualTakeoverPending ? \"deferred\" : \"not_compactable\";\n\t\t}\n\n\t\tif (willRetry) {\n\t\t\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\t\t}\n\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult,\n\t\t\taborted: false,\n\t\t\twillRetry,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t});\n\t\tif (!hasPendingManualCompactionTakeover.call(this)) {\n\t\t\tthis._schedulePostAutoCompactionContinuationProbe(reason, willRetry);\n\t\t}\n\t\treturn \"compacted\";\n\t} catch (error) {\n\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\tconst aborted = controller.signal.aborted;\n\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\n\t\tconst formattedErrorMessage = aborted\n\t\t\t? undefined\n\t\t\t: reason === \"overflow\"\n\t\t\t\t? urgency === \"recoverable\"\n\t\t\t\t\t? `Response truncation recovery failed: ${errorMessage}`\n\t\t\t\t\t: `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t: `Auto-compaction failed: ${errorMessage}`;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tunresolvedOverflow: overflowUnresolved.call(this, urgency === \"load_bearing\", aborted),\n\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\terrorMessage: formattedErrorMessage,\n\t\t});\n\t\tawait emitSessionCompactFailed(this, {\n\t\t\treason,\n\t\t\terrorMessage: formattedErrorMessage,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tfromExtension,\n\t\t});\n\t\treturn manualTakeoverPending ? \"deferred\" : \"failed\";\n\t} finally {\n\t\tif (this._autoCompactionAbortController === controller) this._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t\tcompletion.resolve();\n\t\tif (this._autoCompactionCompletion === completion.promise) this._autoCompactionCompletion = undefined;\n\t}\n}\n\n/**\n * Toggle auto-compaction setting.\n */\n\nexport const agentSessionAutoCompactionMethods = {\n\t_awaitPendingPostCompactionContinuation,\n\t_checkCompaction,\n\t_dropTrailingAutoCompactionRetryAssistantIfPresent,\n\t_schedulePostAutoCompactionContinuationProbe,\n\t_resumeAfterAutoCompaction,\n\t_resumeAfterLengthTruncation,\n\t_runAutoCompaction,\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-compaction.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-compaction.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACX,2BAA2B,IAAI,YAAY,EAC3C,qBAAqB,EACrB,8BAA8B,EAC9B,MAAM,4BAA4B,CAAC;AAGpC,OAAO,EAYN,KAAK,wBAAwB,EAG7B,MAAM,uBAAuB,CAAC;AAE/B,OAAO,KAAK,EAIX,yBAAyB,EACzB,MAAM,uBAAuB,CAAC;AA4D/B,wBAAsB,wBAAwB,CAC7C,IAAI,EAAE,YAAY,EAClB,OAAO,EAAE,8BAA8B,GACrC,OAAO,CAAC,wBAAwB,GAAG,SAAS,CAAC,
|
|
1
|
+
{"version":3,"file":"agent-session-compaction.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-compaction.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACX,2BAA2B,IAAI,YAAY,EAC3C,qBAAqB,EACrB,8BAA8B,EAC9B,MAAM,4BAA4B,CAAC;AAGpC,OAAO,EAYN,KAAK,wBAAwB,EAG7B,MAAM,uBAAuB,CAAC;AAE/B,OAAO,KAAK,EAIX,yBAAyB,EACzB,MAAM,uBAAuB,CAAC;AA4D/B,wBAAsB,wBAAwB,CAC7C,IAAI,EAAE,YAAY,EAClB,OAAO,EAAE,8BAA8B,GACrC,OAAO,CAAC,wBAAwB,GAAG,SAAS,CAAC,CAkN/C;AAED,wBAAsB,wBAAwB,CAC7C,OAAO,EAAE,YAAY,EACrB,KAAK,EAAE,IAAI,CAAC,yBAAyB,EAAE,MAAM,CAAC,GAC5C,OAAO,CAAC,IAAI,CAAC,CAIf;AA+ED;;;;;;;GAOG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,GAAE,qBAA0B,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAuDlH;AAED,wBAAgB,eAAe,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAGxD;AACD,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAE3D;AACD,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI,CAEnF;AAED,eAAO,MAAM,6BAA6B;;;;;;CAMzC,CAAC"}
|
|
@@ -145,6 +145,11 @@ export async function _applyVerbatimCompaction(options) {
|
|
|
145
145
|
...plan,
|
|
146
146
|
resolveAuth: options.resolvePlannerAuth,
|
|
147
147
|
signal: options.abortController.signal,
|
|
148
|
+
// Automatic compaction runs inside or ahead of an unattended turn, so its planning
|
|
149
|
+
// gets a time limit (#4198). A manual run is watched and cancelled with Escape.
|
|
150
|
+
...(options.reason === "manual"
|
|
151
|
+
? {}
|
|
152
|
+
: { planningTimeoutMs: this.settingsManager.getCompactionPlanningTimeoutMs() }),
|
|
148
153
|
thinkingLevel: this.thinkingLevel,
|
|
149
154
|
urgency: options.urgency,
|
|
150
155
|
fallback,
|
|
@@ -166,6 +171,7 @@ export async function _applyVerbatimCompaction(options) {
|
|
|
166
171
|
...(run.summary ? { summary: run.summary } : {}),
|
|
167
172
|
...(run.summaryFirstKeptEntryId ? { summaryFirstKeptEntryId: run.summaryFirstKeptEntryId } : {}),
|
|
168
173
|
...(run.summaryTokensBefore !== undefined ? { summaryTokensBefore: run.summaryTokensBefore } : {}),
|
|
174
|
+
...(run.freshReason ? { freshReason: run.freshReason } : {}),
|
|
169
175
|
};
|
|
170
176
|
}
|
|
171
177
|
assertCompactionOpen(this);
|
|
@@ -185,6 +191,7 @@ export async function _applyVerbatimCompaction(options) {
|
|
|
185
191
|
...(compacted.backend ? { backend: compacted.backend } : {}),
|
|
186
192
|
...(compacted.model ? { model: compacted.model } : {}),
|
|
187
193
|
...(compacted.summary ? { summary: compacted.summary } : {}),
|
|
194
|
+
...(compacted.freshReason ? { freshReason: compacted.freshReason } : {}),
|
|
188
195
|
...(backupPath ? { backupPath } : {}),
|
|
189
196
|
};
|
|
190
197
|
const entryId = await this.sessionManager.appendCompaction(compacted.text, firstKeptEntryId, tokensBefore, details, compacted.usage);
|
|
@@ -201,6 +208,7 @@ export async function _applyVerbatimCompaction(options) {
|
|
|
201
208
|
...(compacted.backend ? { backend: compacted.backend } : {}),
|
|
202
209
|
...(compacted.model ? { model: compacted.model } : {}),
|
|
203
210
|
...(compacted.summary ? { summary: compacted.summary } : {}),
|
|
211
|
+
...(compacted.freshReason ? { freshReason: compacted.freshReason } : {}),
|
|
204
212
|
...(compacted.usage ? { usage: compacted.usage } : {}),
|
|
205
213
|
...(backupPath ? { backupPath } : {}),
|
|
206
214
|
};
|
|
@@ -277,7 +285,7 @@ async function runOwnedManualCompaction(controller, options) {
|
|
|
277
285
|
...(options.preserve_recent === undefined ? {} : { preserve_recent: options.preserve_recent }),
|
|
278
286
|
...(options.query === undefined ? {} : { query: options.query }),
|
|
279
287
|
...(options.compactionModel === undefined ? {} : { compactionModel: options.compactionModel }),
|
|
280
|
-
resolvePlannerAuth: async (candidate) => authForStream(this, await this._getRequiredRequestAuth(candidate, controller.signal)),
|
|
288
|
+
resolvePlannerAuth: async (candidate, signal) => authForStream(this, await this._getRequiredRequestAuth(candidate, signal ?? controller.signal)),
|
|
281
289
|
abortController: controller,
|
|
282
290
|
backupLabel: "compact",
|
|
283
291
|
reason: "manual",
|