@sema-agent/core 7.69.0 → 7.69.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 +583 -0
- package/dist/agents/repair-loop.js +6 -14
- package/dist/agents/subagent.js +2 -1
- package/dist/agents/verify.d.ts +1 -1
- package/dist/agents/verify.js +7 -1
- package/dist/brain/reasoning-request.d.ts +7 -0
- package/dist/brain/reasoning-request.js +6 -0
- package/dist/core/agent-config-dir.d.ts +39 -3
- package/dist/core/agent-config-dir.js +67 -11
- package/dist/core/allow-entry.d.ts +5 -5
- package/dist/core/allow-entry.js +12 -6
- package/dist/core/ask-headline.d.ts +2 -2
- package/dist/core/ask-origin.d.ts +31 -31
- package/dist/core/ask-origin.js +20 -13
- package/dist/core/attachment-source.d.ts +1 -1
- package/dist/core/attachment-source.js +1 -0
- package/dist/core/auto-compaction.d.ts +44 -62
- package/dist/core/auto-compaction.js +44 -103
- package/dist/core/cache-break-detector.d.ts +23 -11
- package/dist/core/cache-break-detector.js +11 -5
- package/dist/core/checkpoint-features.d.ts +1 -1
- package/dist/core/checkpoint-features.js +1 -1
- package/dist/core/checkpoint-requirements.d.ts +19 -1
- package/dist/core/checkpoint-requirements.js +6 -0
- package/dist/core/checkpoint-row-verdict.js +3 -0
- package/dist/core/checkpoint-store.d.ts +13 -2
- package/dist/core/child-clamp-seats.d.ts +30 -3
- package/dist/core/child-clamp-seats.js +24 -0
- package/dist/core/compaction-retired-members.d.ts +12 -0
- package/dist/core/compaction-retired-members.js +22 -0
- package/dist/core/config-refusal-codes.d.ts +1 -1
- package/dist/core/config-refusal-codes.js +2 -0
- package/dist/core/context-edit.d.ts +32 -17
- package/dist/core/context-edit.js +28 -0
- package/dist/core/cron.d.ts +68 -0
- package/dist/core/cron.js +259 -0
- package/dist/core/engine-attestation.d.ts +16 -0
- package/dist/core/engine-attestation.js +2 -0
- package/dist/core/engine-capabilities.d.ts +14 -1
- package/dist/core/engine-capabilities.js +1 -1
- package/dist/core/engine-notice.d.ts +18 -7
- package/dist/core/engine-version.js +1 -1
- package/dist/core/gate-outcome.d.ts +29 -2
- package/dist/core/gate-outcome.js +6 -0
- package/dist/core/git-read-only.d.ts +10 -0
- package/dist/core/git-read-only.js +1 -0
- package/dist/core/git-worktree-env.js +9 -8
- package/dist/core/governance-codes.d.ts +9 -2
- package/dist/core/governance-codes.js +9 -0
- package/dist/core/locked-config.js +7 -3
- package/dist/core/lsp.d.ts +3 -0
- package/dist/core/lsp.js +3 -2
- package/dist/core/memory-engine/engine.d.ts +48 -12
- package/dist/core/memory-engine/engine.js +108 -46
- package/dist/core/memory-engine/file-backend.d.ts +2 -1
- package/dist/core/memory-engine/index-copies.d.ts +47 -0
- package/dist/core/memory-engine/index-copies.js +88 -0
- package/dist/core/memory-engine/layout.d.ts +20 -3
- package/dist/core/memory-engine/layout.js +39 -3
- package/dist/core/memory-engine/origin-clearance.d.ts +9 -7
- package/dist/core/memory-engine/origin-clearance.js +2 -4
- package/dist/core/memory-engine/types.d.ts +16 -3
- package/dist/core/mode-policy.d.ts +7 -1
- package/dist/core/mode-policy.js +9 -0
- package/dist/core/mods/session-compact.js +3 -3
- package/dist/core/mods/stations.d.ts +2 -0
- package/dist/core/mods/stations.js +2 -1
- package/dist/core/path-guard-rows.d.ts +8 -3
- package/dist/core/path-guard-rows.js +18 -5
- package/dist/core/peer-seat.d.ts +3 -0
- package/dist/core/peer-seat.js +3 -0
- package/dist/core/permission-rule-model.js +3 -2
- package/dist/core/process-identity.d.ts +11 -3
- package/dist/core/process-identity.js +26 -16
- package/dist/core/runner/assemble-result.d.ts +5 -0
- package/dist/core/runner/assemble-result.js +1 -1
- package/dist/core/runner/cleared-results-record.d.ts +33 -0
- package/dist/core/runner/cleared-results-record.js +56 -0
- package/dist/core/runner/compact-session.js +14 -9
- package/dist/core/runner/compaction-knobs.d.ts +1 -1
- package/dist/core/runner/continuation-gate.js +2 -1
- package/dist/core/runner/continues-from.d.ts +1 -1
- package/dist/core/runner/continues-from.js +1 -1
- package/dist/core/runner/contracts.d.ts +83 -31
- package/dist/core/runner/conversation-segment.d.ts +19 -12
- package/dist/core/runner/conversation-segment.js +27 -7
- package/dist/core/runner/derived-route-fallback.d.ts +2 -12
- package/dist/core/runner/derived-route-fallback.js +0 -6
- package/dist/core/runner/gate-exit.d.ts +2 -1
- package/dist/core/runner/gate-exit.js +4 -2
- package/dist/core/runner/git-status-frame.d.ts +2 -2
- package/dist/core/runner/git-status-frame.js +2 -1
- package/dist/core/runner/initial-run-state.js +1 -1
- package/dist/core/runner/leg-caller-places.d.ts +39 -0
- package/dist/core/runner/leg-caller-places.js +23 -0
- package/dist/core/runner/leg-frame.d.ts +8 -2
- package/dist/core/runner/leg-receipt.d.ts +29 -2
- package/dist/core/runner/leg-receipt.js +37 -6
- package/dist/core/runner/media-removed-seat.d.ts +10 -6
- package/dist/core/runner/media-removed-seat.js +6 -3
- package/dist/core/runner/messages-omitted-seat.d.ts +2 -1
- package/dist/core/runner/messages-omitted-seat.js +15 -5
- package/dist/core/runner/person-path-rows.d.ts +25 -7
- package/dist/core/runner/person-path-rows.js +16 -2
- package/dist/core/runner/prefix-ledger.d.ts +120 -0
- package/dist/core/runner/prefix-ledger.js +176 -0
- package/dist/core/runner/prepare-advisor.d.ts +2 -0
- package/dist/core/runner/prepare-advisor.js +2 -1
- package/dist/core/runner/prepare-artifact.d.ts +3 -0
- package/dist/core/runner/prepare-artifact.js +2 -2
- package/dist/core/runner/prepare-caps-and-workflow.d.ts +2 -0
- package/dist/core/runner/prepare-caps-and-workflow.js +4 -3
- package/dist/core/runner/prepare-config-doors.d.ts +9 -8
- package/dist/core/runner/prepare-config-doors.js +15 -12
- package/dist/core/runner/prepare-context-lane.d.ts +25 -6
- package/dist/core/runner/prepare-context-lane.js +82 -27
- package/dist/core/runner/prepare-gate-stations.d.ts +1 -2
- package/dist/core/runner/prepare-gate-stations.js +2 -4
- package/dist/core/runner/prepare-hands-readface.d.ts +18 -5
- package/dist/core/runner/prepare-hands-readface.js +41 -22
- package/dist/core/runner/prepare-inherited-gate.d.ts +5 -0
- package/dist/core/runner/prepare-inherited-gate.js +2 -0
- package/dist/core/runner/prepare-memory.d.ts +10 -2
- package/dist/core/runner/prepare-memory.js +51 -5
- package/dist/core/runner/prepare-policy-chain.d.ts +3 -0
- package/dist/core/runner/prepare-policy-chain.js +13 -2
- package/dist/core/runner/prepare-prompt-assembly.d.ts +12 -4
- package/dist/core/runner/prepare-prompt-assembly.js +10 -4
- package/dist/core/runner/prepare-prompt-inputs.d.ts +3 -7
- package/dist/core/runner/prepare-prompt-inputs.js +6 -7
- package/dist/core/runner/prepare-safety-scan.js +7 -0
- package/dist/core/runner/prepare-suspend-saga.d.ts +4 -0
- package/dist/core/runner/prepare-suspend-saga.js +3 -2
- package/dist/core/runner/prepare-task.js +59 -53
- package/dist/core/runner/prepare-tool-disclosure-mount.d.ts +5 -11
- package/dist/core/runner/prepare-tool-disclosure-mount.js +7 -8
- package/dist/core/runner/prepare-turn-wiring.d.ts +16 -25
- package/dist/core/runner/prepare-turn-wiring.js +8 -18
- package/dist/core/runner/prepare-wiring-manifest.d.ts +1 -0
- package/dist/core/runner/prepare-wiring-manifest.js +3 -2
- package/dist/core/runner/prompt-suggestions.d.ts +3 -1
- package/dist/core/runner/prompt-suggestions.js +1 -1
- package/dist/core/runner/read-block-judge.d.ts +47 -0
- package/dist/core/runner/read-block-judge.js +33 -0
- package/dist/core/runner/role-resolution-table.d.ts +15 -10
- package/dist/core/runner/role-resolution-table.js +4 -5
- package/dist/core/runner/rule-store-unreadable-notice.d.ts +7 -4
- package/dist/core/runner/rule-store-unreadable-notice.js +4 -3
- package/dist/core/runner/run-compaction-machinery.d.ts +0 -10
- package/dist/core/runner/run-compaction-machinery.js +3 -39
- package/dist/core/runner/run-harness-handlers.js +4 -17
- package/dist/core/runner/run-identity-wiring.js +4 -1
- package/dist/core/runner/run-leg.js +11 -1
- package/dist/core/runner/run-recovery-lanes.d.ts +0 -4
- package/dist/core/runner/run-recovery-lanes.js +34 -18
- package/dist/core/runner/run-settle-and-teardown.d.ts +1 -3
- package/dist/core/runner/run-settle-and-teardown.js +14 -22
- package/dist/core/runner/run-telemetry-and-budget-seats.js +0 -1
- package/dist/core/runner/run-terminal-adoption.d.ts +11 -30
- package/dist/core/runner/run-terminal-adoption.js +5 -88
- package/dist/core/runner/run-tool-mount-facts.js +1 -5
- package/dist/core/runner/run-turn-boundary.js +56 -26
- package/dist/core/runner/runtask.js +7 -7
- package/dist/core/runner/session-hash-salt.d.ts +18 -0
- package/dist/core/runner/session-hash-salt.js +36 -0
- package/dist/core/runner/shell-env-withheld.d.ts +8 -5
- package/dist/core/runner/shell-env-withheld.js +3 -3
- package/dist/core/runner/side-call-account.d.ts +9 -1
- package/dist/core/runner/side-call-account.js +15 -4
- package/dist/core/runner/skill-mention.d.ts +12 -0
- package/dist/core/runner/skill-mention.js +50 -0
- package/dist/core/runner/stream-settle-backstop.js +1 -0
- package/dist/core/runner/synthetic-tools.js +2 -2
- package/dist/core/runner/tool-table-view.d.ts +5 -9
- package/dist/core/runner/tool-table-view.js +23 -21
- package/dist/core/runner/write-protection-station.d.ts +5 -2
- package/dist/core/runner/write-protection-station.js +1 -1
- package/dist/core/runner-deps.d.ts +25 -27
- package/dist/core/scheduler.d.ts +13 -3
- package/dist/core/scheduler.js +0 -12
- package/dist/core/secret-env.d.ts +47 -11
- package/dist/core/secret-env.js +65 -4
- package/dist/core/sensitive-path-policy.js +4 -0
- package/dist/core/session-checkout.js +10 -9
- package/dist/core/shell-read-silence.d.ts +2 -1
- package/dist/core/shell-run-candidates.d.ts +1 -1
- package/dist/core/shell-run-candidates.js +11 -3
- package/dist/core/task-event.d.ts +32 -10
- package/dist/core/task-intake.d.ts +5 -3
- package/dist/core/task-intake.js +6 -2
- package/dist/core/task-result.d.ts +39 -0
- package/dist/core/task-spec-members.d.ts +3 -0
- package/dist/core/task-spec-members.js +2 -2
- package/dist/core/task-spec.d.ts +37 -20
- package/dist/core/tool-policy.d.ts +30 -18
- package/dist/core/tool-policy.js +44 -32
- package/dist/core/tool-roster.d.ts +21 -7
- package/dist/core/tool-roster.js +34 -6
- package/dist/core/tool-spec-members.js +1 -1
- package/dist/core/tool-spec.d.ts +27 -0
- package/dist/core/tools.js +1 -0
- package/dist/core/trace.d.ts +42 -19
- package/dist/core/unc-spelling.d.ts +31 -0
- package/dist/core/unc-spelling.js +51 -0
- package/dist/core/wiring-manifest.d.ts +30 -3
- package/dist/core/wiring-manifest.js +10 -0
- package/dist/core/workflow-run-store-contract.js +22 -0
- package/dist/core/workflow-run-store.d.ts +17 -13
- package/dist/core/workflow-run-store.js +1 -1
- package/dist/core/write-protect.d.ts +4 -0
- package/dist/core/write-protect.js +17 -15
- package/dist/engine/compaction/compaction.d.ts +48 -98
- package/dist/engine/compaction/compaction.js +136 -216
- package/dist/engine/compaction/utils.d.ts +2 -11
- package/dist/engine/compaction/utils.js +4 -13
- package/dist/engine/execution-env/node-execution-env.js +17 -6
- package/dist/engine/harness/agent-harness.d.ts +19 -5
- package/dist/engine/harness/agent-harness.js +18 -7
- package/dist/engine/harness/types.d.ts +5 -7
- package/dist/engine/loop/agent-loop.d.ts +14 -1
- package/dist/engine/loop/agent-loop.js +31 -11
- package/dist/engine/loop/types.d.ts +8 -2
- package/dist/index.d.ts +9 -6
- package/dist/index.js +8 -6
- package/dist/internal/harness-types.d.ts +1 -1
- package/dist/internal/harness.d.ts +1 -1
- package/dist/internal/harness.js +1 -1
- package/dist/orchestration/run-spec.js +7 -2
- package/dist/orchestration/run-workflow-tool.js +5 -3
- package/dist/orchestration/workflow-park-adoption.d.ts +66 -8
- package/dist/orchestration/workflow-park-adoption.js +195 -45
- package/dist/orchestration/workflow-types.d.ts +20 -0
- package/dist/orchestration/workflow-types.js +1 -0
- package/dist/orchestration/workflow.d.ts +3 -2
- package/dist/orchestration/workflow.js +10 -4
- package/dist/prompt-assembly/catalog/core-behavior.js +6 -0
- package/dist/prompt-assembly/catalog/events.d.ts +8 -0
- package/dist/prompt-assembly/catalog/locales/zh-Hans/core-behavior.js +6 -0
- package/dist/prompt-assembly/catalog/locales/zh-Hans/mechanism.js +1 -0
- package/dist/prompt-assembly/catalog/mechanism.d.ts +8 -0
- package/dist/prompt-assembly/catalog/mechanism.js +1 -0
- package/dist/prompt-assembly/catalog/schema.d.ts +1 -1
- package/dist/prompt-assembly/catalog/schema.js +1 -0
- package/dist/prompt-assembly/catalog/sections.js +8 -0
- package/dist/prompt-assembly/event-registry.js +1 -0
- package/dist/prompt-assembly/select.js +1 -0
- package/dist/prompt-assembly/turn-snapshot.d.ts +14 -27
- package/dist/prompt-assembly/turn-snapshot.js +6 -18
- package/dist/prompt-assembly/types.d.ts +3 -0
- package/dist/prompts/default.d.ts +9 -0
- package/dist/prompts/default.js +4 -0
- package/dist/shell/lex.d.ts +75 -11
- package/dist/shell/lex.js +340 -76
- package/dist/tools/fs/bash-program-position.js +2 -6
- package/dist/tools/fs/bash-readonly-classifier.d.ts +18 -3
- package/dist/tools/fs/bash-readonly-classifier.js +19 -9
- package/dist/tools/fs/containment-face.d.ts +12 -3
- package/dist/tools/fs/containment-face.js +16 -7
- package/dist/tools/fs/file-read-check.d.ts +26 -1
- package/dist/tools/fs/file-read-check.js +20 -2
- package/dist/tools/fs/fs-bash.js +4 -4
- package/dist/tools/fs/fs-read.d.ts +3 -0
- package/dist/tools/fs/fs-read.js +2 -2
- package/dist/tools/fs/fs-search-tools.d.ts +2 -2
- package/dist/tools/fs/fs-search-tools.js +4 -4
- package/dist/tools/fs/index.js +5 -3
- package/dist/tools/fs/pdf.js +12 -4
- package/dist/tools/fs/read-deny-home.d.ts +13 -2
- package/dist/tools/fs/read-deny-home.js +26 -22
- package/dist/tools/fs/read-deny.js +15 -6
- package/dist/tools/fs/removal-targets.d.ts +33 -17
- package/dist/tools/fs/removal-targets.js +160 -61
- package/dist/tools/fs/repo-map.d.ts +1 -1
- package/dist/tools/fs/repo-map.js +2 -2
- package/dist/tools/fs/safety.d.ts +28 -5
- package/dist/tools/fs/safety.js +72 -8
- package/dist/tools/fs/shell-read-bindings.d.ts +8 -2
- package/dist/tools/fs/shell-read-bindings.js +25 -6
- package/dist/tools/fs/shell-read-check.d.ts +3 -0
- package/dist/tools/fs/shell-read-check.js +22 -4
- package/dist/tools/fs/shell-read-establish.js +73 -43
- package/dist/tools/fs/shell-read-judge.d.ts +32 -14
- package/dist/tools/fs/shell-read-judge.js +13 -5
- package/dist/tools/fs/shell-read-object-path.d.ts +5 -1
- package/dist/tools/fs/shell-read-object-path.js +17 -4
- package/dist/tools/fs/shell-read-plan.d.ts +8 -2
- package/dist/tools/fs/shell-read-plan.js +36 -22
- package/dist/tools/fs/shell-read-sourced.js +12 -4
- package/dist/tools/fs/shell-read-start.d.ts +4 -2
- package/dist/tools/fs/shell-read-start.js +3 -3
- package/dist/tools/fs/shell-read-workdir.d.ts +14 -6
- package/dist/tools/fs/shell-read-workdir.js +35 -17
- package/dist/tools/scheduler-tools.d.ts +7 -17
- package/dist/tools/scheduler-tools.js +9 -85
- package/dist/tools/worktree.js +5 -4
- package/package.json +3 -2
- package/test/export-surface.snapshot.json +47 -1
- package/wire-changes/core-stores-sql@7.68.6.json +39 -0
- package/wire-changes/core-stores-sql@7.69.1.json +39 -0
- package/wire-changes/core@7.68.6.json +125 -0
- package/wire-changes/core@7.69.1.json +2561 -0
- package/wire-changes/mods-kernel@7.68.6.json +39 -0
- package/wire-changes/mods-kernel@7.69.1.json +39 -0
- package/wire-changes/primitives@7.68.6.json +39 -0
- package/wire-changes/primitives@7.69.1.json +39 -0
- package/wire-changes/wiki-gate@7.68.6.json +39 -0
- package/wire-changes/wiki-gate@7.69.1.json +39 -0
- package/dist/core/runner/prompt-hash-salt.d.ts +0 -1
- package/dist/core/runner/prompt-hash-salt.js +0 -2
|
@@ -3,11 +3,12 @@ import { resolveAgentCoreCompleteFn, } from "../loop/runtime-deps.js";
|
|
|
3
3
|
import { asAgentMessage, convertToLlm, createCompactionSummaryMessage, createCustomMessage, } from "../harness/messages.js";
|
|
4
4
|
import { buildSessionContext } from "../session/session.js";
|
|
5
5
|
import { CompactionError, err, isSyntheticApiErrorMessage, ok, } from "../harness/types.js";
|
|
6
|
-
import { budgetInvokedSkillsRetention, computeFileLists, createFileOps, extractFileOpsFromMessage, extractInvokedSkills, extractPersistedOutputRefs, formatFileOperations, formatPersistedOutputRefs, PERSISTED_OUTPUT_REFS_MAX_ENTRIES, readElidedMessages, readPersistedOutputRefs, readRetainedInvokedSkills, readUnsummarizedMessages, replaceInvokedSkillBodiesForSummary, serializeConversation,
|
|
6
|
+
import { budgetInvokedSkillsRetention, computeFileLists, createFileOps, extractFileOpsFromMessage, extractInvokedSkills, extractPersistedOutputRefs, formatFileOperations, formatPersistedOutputRefs, PERSISTED_OUTPUT_REFS_MAX_ENTRIES, readElidedMessages, readPersistedOutputRefs, readRetainedInvokedSkills, readUnsummarizedMessages, replaceInvokedSkillBodiesForSummary, serializeConversation, } from "./utils.js";
|
|
7
7
|
import { ENGINE_AUTHORITY_ENVELOPE_TAGS, sanitizeUntrustedText } from "../../core/untrusted-text.js";
|
|
8
8
|
import { sliceHeadSafe } from "../../core/surrogate-safe-slice.js";
|
|
9
9
|
import { thrownText } from "../../core/thrown-value.js";
|
|
10
10
|
import { capabilityHeld } from "../../brain/model-capability.js";
|
|
11
|
+
import { thinkingBudgetFollowsCap } from "../../brain/reasoning-request.js";
|
|
11
12
|
function safeJsonStringify(value) {
|
|
12
13
|
try {
|
|
13
14
|
return JSON.stringify(value) ?? "undefined";
|
|
@@ -63,12 +64,10 @@ function getMessageFromEntryForCompaction(entry) {
|
|
|
63
64
|
}
|
|
64
65
|
return getMessageFromEntry(entry);
|
|
65
66
|
}
|
|
66
|
-
export const DEFAULT_CLAMP_TOLERANCE = 0.1;
|
|
67
67
|
export const DEFAULT_COMPACTION_SETTINGS = {
|
|
68
68
|
enabled: true,
|
|
69
69
|
reserveTokens: 16384,
|
|
70
70
|
keepRecentTokens: 0,
|
|
71
|
-
clampTolerance: DEFAULT_CLAMP_TOLERANCE,
|
|
72
71
|
};
|
|
73
72
|
export const DEFAULT_CHARS_PER_TOKEN = 3;
|
|
74
73
|
const IMAGE_TOKEN_ESTIMATE = 2000;
|
|
@@ -256,21 +255,6 @@ function findValidCutPoints(entries, startIndex, endIndex) {
|
|
|
256
255
|
}
|
|
257
256
|
return cutPoints;
|
|
258
257
|
}
|
|
259
|
-
export function findTurnStartIndex(entries, entryIndex, startIndex) {
|
|
260
|
-
for (let i = entryIndex; i >= startIndex; i--) {
|
|
261
|
-
const entry = entries[i];
|
|
262
|
-
if (entry.type === "custom_message") {
|
|
263
|
-
return i;
|
|
264
|
-
}
|
|
265
|
-
if (entry.type === "message") {
|
|
266
|
-
const role = entry.message.role;
|
|
267
|
-
if ((role === "user" && opensTurn(entry.message)) || role === "bashExecution") {
|
|
268
|
-
return i;
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
}
|
|
272
|
-
return -1;
|
|
273
|
-
}
|
|
274
258
|
function opensTurn(message) {
|
|
275
259
|
return userAttachmentOf(message) === undefined;
|
|
276
260
|
}
|
|
@@ -337,7 +321,7 @@ function foldToolPairsForward(entries, callSites, cutPoints, endIndex, cutIndex)
|
|
|
337
321
|
const site = emittingCallSite(callSites, msg.toolCallId, i);
|
|
338
322
|
if (site === -1 || site >= cutIndex)
|
|
339
323
|
continue;
|
|
340
|
-
const next = cutPoints.find((c) => c > i);
|
|
324
|
+
const next = cutPoints.find((c) => c > i && opensGroup(entries, c));
|
|
341
325
|
if (next === undefined)
|
|
342
326
|
return -1;
|
|
343
327
|
cutIndex = next;
|
|
@@ -345,34 +329,31 @@ function foldToolPairsForward(entries, callSites, cutPoints, endIndex, cutIndex)
|
|
|
345
329
|
}
|
|
346
330
|
return cutIndex;
|
|
347
331
|
}
|
|
348
|
-
function
|
|
349
|
-
|
|
350
|
-
const isUserMessage = cutEntry.type === "message" && cutEntry.message.role === "user" && opensTurn(cutEntry.message);
|
|
351
|
-
const turnStartIndex = isUserMessage ? -1 : findTurnStartIndex(entries, cutIndex, startIndex);
|
|
352
|
-
return {
|
|
353
|
-
firstKeptEntryIndex: cutIndex,
|
|
354
|
-
turnStartIndex,
|
|
355
|
-
isSplitTurn: !isUserMessage && turnStartIndex !== -1,
|
|
356
|
-
};
|
|
357
|
-
}
|
|
358
|
-
function leavesSummarizableHistory(entries, startIndex, cut) {
|
|
359
|
-
const historyEnd = cut.isSplitTurn ? cut.turnStartIndex : cut.firstKeptEntryIndex;
|
|
360
|
-
for (let i = startIndex; i < historyEnd; i++) {
|
|
361
|
-
if (getMessageFromEntryForCompaction(entries[i]) !== undefined)
|
|
362
|
-
return true;
|
|
363
|
-
}
|
|
364
|
-
if (!cut.isSplitTurn)
|
|
365
|
-
return false;
|
|
366
|
-
for (let i = cut.turnStartIndex; i < cut.firstKeptEntryIndex; i++) {
|
|
332
|
+
function leavesSummarizableHistory(entries, startIndex, floor) {
|
|
333
|
+
for (let i = startIndex; i < floor; i++) {
|
|
367
334
|
if (getMessageFromEntryForCompaction(entries[i]) !== undefined)
|
|
368
335
|
return true;
|
|
369
336
|
}
|
|
370
337
|
return false;
|
|
371
338
|
}
|
|
339
|
+
function opensGroup(entries, index) {
|
|
340
|
+
const entry = entries[index];
|
|
341
|
+
return entry?.type === "message" && entry.message.role === "assistant";
|
|
342
|
+
}
|
|
343
|
+
function groupFloor(entries, cutIndex, cutPoints) {
|
|
344
|
+
let floor = cutPoints[0];
|
|
345
|
+
for (const c of cutPoints) {
|
|
346
|
+
if (c > cutIndex)
|
|
347
|
+
break;
|
|
348
|
+
if (opensGroup(entries, c))
|
|
349
|
+
floor = c;
|
|
350
|
+
}
|
|
351
|
+
return floor;
|
|
352
|
+
}
|
|
372
353
|
export function findCutPoint(entries, startIndex, endIndex, keepRecentTokens, charsPerToken = DEFAULT_CHARS_PER_TOKEN) {
|
|
373
354
|
const cutPoints = findValidCutPoints(entries, startIndex, endIndex);
|
|
374
355
|
if (cutPoints.length === 0) {
|
|
375
|
-
return { firstKeptEntryIndex: startIndex
|
|
356
|
+
return { firstKeptEntryIndex: startIndex };
|
|
376
357
|
}
|
|
377
358
|
let accumulatedTokens = 0;
|
|
378
359
|
let cutIndex = cutPoints[0];
|
|
@@ -403,16 +384,16 @@ export function findCutPoint(entries, startIndex, endIndex, keepRecentTokens, ch
|
|
|
403
384
|
break;
|
|
404
385
|
}
|
|
405
386
|
}
|
|
387
|
+
cutIndex = groupFloor(entries, cutIndex, cutPoints);
|
|
406
388
|
const callSites = collectToolCallSites(entries, startIndex, endIndex);
|
|
407
389
|
const budgetCutIndex = cutIndex;
|
|
408
390
|
cutIndex = enforceToolPairContainment(entries, callSites, endIndex, cutIndex);
|
|
409
|
-
|
|
410
|
-
if (cutIndex !== budgetCutIndex && !leavesSummarizableHistory(entries, startIndex, kept)) {
|
|
391
|
+
if (cutIndex !== budgetCutIndex && !leavesSummarizableHistory(entries, startIndex, cutIndex)) {
|
|
411
392
|
const folded = foldToolPairsForward(entries, callSites, cutPoints, endIndex, budgetCutIndex);
|
|
412
393
|
if (folded !== -1)
|
|
413
|
-
return
|
|
394
|
+
return { firstKeptEntryIndex: folded };
|
|
414
395
|
}
|
|
415
|
-
return
|
|
396
|
+
return { firstKeptEntryIndex: cutIndex };
|
|
416
397
|
}
|
|
417
398
|
export const SUMMARIZATION_SYSTEM_PROMPT = `You are a context summarization assistant. Your task is to read a conversation between a user and an AI coding assistant, then produce a structured summary following the exact format specified.
|
|
418
399
|
|
|
@@ -582,6 +563,15 @@ function createSummarizationOptions(model, maxTokens, auth, signal, thinkingLeve
|
|
|
582
563
|
}
|
|
583
564
|
return options;
|
|
584
565
|
}
|
|
566
|
+
function carriedSummarizationOptions(maxTokens, auth, signal, controls) {
|
|
567
|
+
return {
|
|
568
|
+
...(maxTokens !== undefined ? { maxTokens } : {}),
|
|
569
|
+
signal,
|
|
570
|
+
...auth,
|
|
571
|
+
...(controls.reasoning !== undefined ? { reasoning: controls.reasoning } : {}),
|
|
572
|
+
...(controls.tryUndeclared === true ? { tryUndeclared: true } : {}),
|
|
573
|
+
};
|
|
574
|
+
}
|
|
585
575
|
async function completeSummarization(model, context, options, streamFn, runtime) {
|
|
586
576
|
const call = async () => streamFn ? (await streamFn(model, context, options)).result() : await resolveAgentCoreCompleteFn(runtime)(model, context, options);
|
|
587
577
|
const signal = options.signal;
|
|
@@ -602,8 +592,9 @@ async function completeSummarization(model, context, options, streamFn, runtime)
|
|
|
602
592
|
release();
|
|
603
593
|
}
|
|
604
594
|
}
|
|
595
|
+
const PASS_CUT_REPLIES = new WeakSet();
|
|
605
596
|
function summaryCallAborted(model) {
|
|
606
|
-
|
|
597
|
+
const reply = {
|
|
607
598
|
role: "assistant",
|
|
608
599
|
content: [],
|
|
609
600
|
api: model.api,
|
|
@@ -613,6 +604,8 @@ function summaryCallAborted(model) {
|
|
|
613
604
|
stopReason: "aborted",
|
|
614
605
|
timestamp: Date.now(),
|
|
615
606
|
};
|
|
607
|
+
PASS_CUT_REPLIES.add(reply);
|
|
608
|
+
return reply;
|
|
616
609
|
}
|
|
617
610
|
const SUMMARY_REASONING_FLOOR = 2048;
|
|
618
611
|
const SUMMARY_MAX_ESCALATIONS = 2;
|
|
@@ -686,48 +679,6 @@ function clampSummarizationConversation(conversationText, model, charsPerToken,
|
|
|
686
679
|
conversationText.slice(conversationText.length - tailChars);
|
|
687
680
|
return { text, droppedChars: elided, keptChars: headChars + tailChars };
|
|
688
681
|
}
|
|
689
|
-
export function dryRunSummarizationClamp(preparation, model, customInstructions, charsPerToken) {
|
|
690
|
-
const cpt = charsPerToken ?? model.charsPerToken ?? DEFAULT_CHARS_PER_TOKEN;
|
|
691
|
-
const { messagesToSummarize, turnPrefixMessages, isSplitTurn, previousSummary, settings, contextInstructionFiles } = preparation;
|
|
692
|
-
const summaryBudget = summaryOutputBudgetTokens(model, settings);
|
|
693
|
-
let dropped = 0;
|
|
694
|
-
let kept = 0;
|
|
695
|
-
let conversationChars = 0;
|
|
696
|
-
let instructionFilesChars = 0;
|
|
697
|
-
if (messagesToSummarize.length > 0) {
|
|
698
|
-
let basePrompt = previousSummary ? UPDATE_SUMMARIZATION_PROMPT : SUMMARIZATION_PROMPT;
|
|
699
|
-
if (customInstructions) {
|
|
700
|
-
basePrompt = `${basePrompt}\n\nAdditional Instructions:\n${customInstructions}`;
|
|
701
|
-
}
|
|
702
|
-
const text = serializeConversation(convertToLlm(messagesToSummarize));
|
|
703
|
-
conversationChars += text.length;
|
|
704
|
-
const baseFixed = SUMMARIZATION_SYSTEM_PROMPT.length + basePrompt.length + (previousSummary?.length ?? 0) + 128;
|
|
705
|
-
const baseMaxTokens = Math.floor(0.8 * summaryBudget);
|
|
706
|
-
const section = fitContextInstructionFilesSection(contextInstructionFiles, model, cpt, baseFixed, baseMaxTokens);
|
|
707
|
-
instructionFilesChars += section.length;
|
|
708
|
-
const clamped = clampSummarizationConversation(text, model, cpt, baseFixed + section.length, baseMaxTokens);
|
|
709
|
-
dropped += Math.max(0, clamped.droppedChars);
|
|
710
|
-
kept += clamped.keptChars;
|
|
711
|
-
}
|
|
712
|
-
if (isSplitTurn && turnPrefixMessages.length > 0) {
|
|
713
|
-
const text = serializeConversation(convertToLlm(turnPrefixMessages));
|
|
714
|
-
conversationChars += text.length;
|
|
715
|
-
const baseFixed = SUMMARIZATION_SYSTEM_PROMPT.length + turnPrefixSummarizationPrompt(customInstructions).length + 128;
|
|
716
|
-
const baseMaxTokens = Math.floor(0.5 * summaryBudget);
|
|
717
|
-
const section = fitContextInstructionFilesSection(contextInstructionFiles, model, cpt, baseFixed, baseMaxTokens);
|
|
718
|
-
instructionFilesChars += section.length;
|
|
719
|
-
const clamped = clampSummarizationConversation(text, model, cpt, baseFixed + section.length, baseMaxTokens);
|
|
720
|
-
dropped += Math.max(0, clamped.droppedChars);
|
|
721
|
-
kept += clamped.keptChars;
|
|
722
|
-
}
|
|
723
|
-
return {
|
|
724
|
-
droppedChars: dropped,
|
|
725
|
-
keptChars: kept,
|
|
726
|
-
truncationRatio: dropped / Math.max(1, dropped + kept),
|
|
727
|
-
conversationChars,
|
|
728
|
-
instructionFilesChars,
|
|
729
|
-
};
|
|
730
|
-
}
|
|
731
682
|
const COMPACTION_PTL_MAX_RETRIES = 3;
|
|
732
683
|
export const COMPACTION_PTL_RETRY_MARKER = "[earlier conversation truncated for compaction retry]";
|
|
733
684
|
const PTL_NO_GAP_DROP_FRACTION = 0.2;
|
|
@@ -754,6 +705,10 @@ function parsePromptTooLong(message) {
|
|
|
754
705
|
}
|
|
755
706
|
return { isPtl: PTL_CLASS_RE.test(message) && !PTL_DENY_RE.test(message) };
|
|
756
707
|
}
|
|
708
|
+
export function refusalShortfall(sent, failureMessage, unitsPerToken) {
|
|
709
|
+
const { gapTokens } = parsePromptTooLong(failureMessage);
|
|
710
|
+
return Math.max(gapTokens !== undefined ? Math.ceil(gapTokens * unitsPerToken * PTL_GAP_SAFETY) : Math.ceil(sent * PTL_NO_GAP_DROP_FRACTION), 1);
|
|
711
|
+
}
|
|
757
712
|
function splitMessageGroups(messages) {
|
|
758
713
|
const groups = [];
|
|
759
714
|
let current = [];
|
|
@@ -791,7 +746,7 @@ async function summarizeWithPtlRetry(req) {
|
|
|
791
746
|
}
|
|
792
747
|
try {
|
|
793
748
|
req.onInputTruncated?.({
|
|
794
|
-
label:
|
|
749
|
+
label: "history",
|
|
795
750
|
droppedChars,
|
|
796
751
|
keptChars,
|
|
797
752
|
...(droppedMessages !== undefined && droppedMessages > 0 ? { droppedMessages } : {}),
|
|
@@ -824,7 +779,7 @@ async function summarizeWithPtlRetry(req) {
|
|
|
824
779
|
let thrown;
|
|
825
780
|
let didThrow = false;
|
|
826
781
|
try {
|
|
827
|
-
result = await summarizeWithLengthRecovery(req.
|
|
782
|
+
result = await summarizeWithLengthRecovery(req.model, context, req.baseMaxTokens, req.auth, req.signal, req.thinkingLevel, req.streamFn, req.runtime, req.charsPerToken);
|
|
828
783
|
}
|
|
829
784
|
catch (e) {
|
|
830
785
|
didThrow = true;
|
|
@@ -833,7 +788,7 @@ async function summarizeWithPtlRetry(req) {
|
|
|
833
788
|
if (!didThrow && result && result.ok) {
|
|
834
789
|
const unwrapped = stripSummaryEnvelope(result.value);
|
|
835
790
|
if (unwrapped.trim() === "") {
|
|
836
|
-
return err(markEmptySummaryClass(new CompactionError("summarization_failed",
|
|
791
|
+
return err(markEmptySummaryClass(new CompactionError("summarization_failed", "Summarization produced an empty summary (the response was an empty <summary> envelope)")));
|
|
837
792
|
}
|
|
838
793
|
return ok(unwrapped);
|
|
839
794
|
}
|
|
@@ -855,12 +810,10 @@ async function summarizeWithPtlRetry(req) {
|
|
|
855
810
|
catch {
|
|
856
811
|
}
|
|
857
812
|
const sentChars = clamped.text.length;
|
|
858
|
-
const gapChars =
|
|
859
|
-
|
|
860
|
-
: Math.ceil(sentChars * PTL_NO_GAP_DROP_FRACTION);
|
|
861
|
-
budgetCapChars = Math.max(SUMMARY_INPUT_MIN_KEEP_CHARS, sentChars - Math.max(gapChars, 1));
|
|
813
|
+
const gapChars = refusalShortfall(sentChars, failureMessage, req.cpt);
|
|
814
|
+
budgetCapChars = Math.max(SUMMARY_INPUT_MIN_KEEP_CHARS, sentChars - gapChars);
|
|
862
815
|
const beforeChars = serialized.length;
|
|
863
|
-
const rollbackTargetChars = Math.max(SUMMARY_INPUT_MIN_KEEP_CHARS, beforeChars -
|
|
816
|
+
const rollbackTargetChars = Math.max(SUMMARY_INPUT_MIN_KEEP_CHARS, beforeChars - gapChars);
|
|
864
817
|
let remainingChars = beforeChars;
|
|
865
818
|
let droppedMessages = 0;
|
|
866
819
|
while (groups.length > 1 && remainingChars > rollbackTargetChars) {
|
|
@@ -888,30 +841,38 @@ function stripAnalysisScratch(text, lengthTruncated) {
|
|
|
888
841
|
}
|
|
889
842
|
return out;
|
|
890
843
|
}
|
|
891
|
-
async function summarizeWithLengthRecovery(
|
|
844
|
+
async function summarizeWithLengthRecovery(model, context, baseMaxTokens, auth, signal, thinkingLevel, streamFn, runtime, charsPerToken, controls) {
|
|
892
845
|
const cpt = charsPerToken ?? model.charsPerToken ?? DEFAULT_CHARS_PER_TOKEN;
|
|
893
846
|
const modelCap = model.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY;
|
|
894
847
|
const windowCap = model.contextWindow > 0
|
|
895
848
|
? Math.max(baseMaxTokens, model.contextWindow - estimateSummarizationInputTokens(context, cpt) - SUMMARY_WINDOW_MARGIN)
|
|
896
849
|
: Number.POSITIVE_INFINITY;
|
|
897
|
-
const
|
|
898
|
-
|
|
850
|
+
const ownCap = Math.min(modelCap, windowCap);
|
|
851
|
+
const capFollowsMain = controls !== undefined && thinkingBudgetFollowsCap(model, controls.reasoning, controls.tryUndeclared === true);
|
|
852
|
+
const cap = capFollowsMain ? modelCap : ownCap;
|
|
853
|
+
let maxTokens = Math.min(ownCap, capabilityHeld(model, "reasoning") ? Math.max(baseMaxTokens, SUMMARY_REASONING_FLOOR) : baseMaxTokens);
|
|
854
|
+
let firstCap = maxTokens;
|
|
855
|
+
if (capFollowsMain) {
|
|
856
|
+
firstCap = controls?.maxTokens;
|
|
857
|
+
maxTokens = controls?.maxTokens ?? (model.maxTokens > 0 ? model.maxTokens : maxTokens);
|
|
858
|
+
}
|
|
899
859
|
for (let attempt = 0;; attempt++) {
|
|
900
860
|
const canEscalate = attempt < SUMMARY_MAX_ESCALATIONS && maxTokens < cap;
|
|
901
|
-
const
|
|
902
|
-
|
|
903
|
-
|
|
861
|
+
const sentCap = attempt === 0 ? firstCap : maxTokens;
|
|
862
|
+
const response = await completeSummarization(model, context, controls !== undefined ? carriedSummarizationOptions(sentCap, auth, signal, controls) : createSummarizationOptions(model, maxTokens, auth, signal, thinkingLevel), streamFn, runtime);
|
|
863
|
+
if (PASS_CUT_REPLIES.has(response)) {
|
|
864
|
+
return err(new CompactionError("aborted", response.errorMessage || "Summarization aborted"));
|
|
904
865
|
}
|
|
905
|
-
if (response.stopReason === "error") {
|
|
866
|
+
if (response.stopReason === "error" || response.stopReason === "aborted") {
|
|
906
867
|
if (response.errorKind === "length_empty") {
|
|
907
868
|
if (canEscalate) {
|
|
908
869
|
maxTokens = Math.min(cap, Math.max(maxTokens * 2, SUMMARY_REASONING_FLOOR));
|
|
909
870
|
continue;
|
|
910
871
|
}
|
|
911
|
-
return err(markEmptySummaryClass(new CompactionError("summarization_failed",
|
|
872
|
+
return err(markEmptySummaryClass(new CompactionError("summarization_failed", `Summarization produced an empty summary (stopReason=error, max_tokens exhausted by reasoning ` +
|
|
912
873
|
`after ${attempt + 1} attempt(s): ${response.errorMessage || "no detail"})`)));
|
|
913
874
|
}
|
|
914
|
-
return err(new CompactionError("summarization_failed",
|
|
875
|
+
return err(new CompactionError("summarization_failed", `Summarization failed: ${response.errorMessage || "Unknown error"}`));
|
|
915
876
|
}
|
|
916
877
|
const lengthTruncated = response.stopReason === "length";
|
|
917
878
|
const raw = response.content
|
|
@@ -926,31 +887,68 @@ async function summarizeWithLengthRecovery(label, model, context, baseMaxTokens,
|
|
|
926
887
|
maxTokens = Math.min(cap, Math.max(maxTokens * 2, SUMMARY_REASONING_FLOOR));
|
|
927
888
|
continue;
|
|
928
889
|
}
|
|
929
|
-
return err(markEmptySummaryClass(new CompactionError("summarization_failed",
|
|
890
|
+
return err(markEmptySummaryClass(new CompactionError("summarization_failed", `Summarization produced an empty summary (stopReason=${response.stopReason}` +
|
|
930
891
|
`${lengthTruncated ? ", the output was analysis scratch cut at max_tokens" : ""})`)));
|
|
931
892
|
}
|
|
932
893
|
}
|
|
933
|
-
async function forkSummarize(fork, model, baseMaxTokens, auth, customInstructions, signal, thinkingLevel, streamFn, runtime, charsPerToken, contextInstructionFiles) {
|
|
894
|
+
async function forkSummarize(fork, model, baseMaxTokens, auth, customInstructions, signal, thinkingLevel, streamFn, runtime, charsPerToken, contextInstructionFiles, onInputTruncated, onPtlRetry) {
|
|
934
895
|
const instruction = forkSummarizationInstruction(customInstructions, contextInstructionFiles);
|
|
935
|
-
const
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
...(fork.tools !== undefined && fork.tools.length > 0 ? { tools: fork.tools } : {}),
|
|
939
|
-
...(fork.promptLocale !== undefined ? { promptLocale: fork.promptLocale } : {}),
|
|
940
|
-
messages: [
|
|
941
|
-
...fork.messages,
|
|
942
|
-
{ role: "user", content: [{ type: "text", text: instruction }], timestamp: Date.now() },
|
|
943
|
-
],
|
|
944
|
-
};
|
|
896
|
+
const cpt = charsPerToken ?? model.charsPerToken ?? DEFAULT_CHARS_PER_TOKEN;
|
|
897
|
+
let groups = splitMessageGroups(fork.messages);
|
|
898
|
+
let dropped = false;
|
|
945
899
|
let result;
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
900
|
+
for (let retry = 0;; retry++) {
|
|
901
|
+
const kept = groups.flat();
|
|
902
|
+
const context = {
|
|
903
|
+
...(fork.systemPrompt !== undefined ? { systemPrompt: fork.systemPrompt } : {}),
|
|
904
|
+
...(fork.systemBlocks !== undefined ? { systemBlocks: fork.systemBlocks } : {}),
|
|
905
|
+
...(fork.tools !== undefined && fork.tools.length > 0 ? { tools: fork.tools } : {}),
|
|
906
|
+
...(fork.promptLocale !== undefined ? { promptLocale: fork.promptLocale } : {}),
|
|
907
|
+
messages: [
|
|
908
|
+
...(dropped ? [{ role: "user", content: [{ type: "text", text: COMPACTION_PTL_RETRY_MARKER }], timestamp: Date.now() }] : []),
|
|
909
|
+
...kept,
|
|
910
|
+
{ role: "user", content: [{ type: "text", text: instruction }], timestamp: Date.now() },
|
|
911
|
+
],
|
|
912
|
+
};
|
|
913
|
+
let failure;
|
|
914
|
+
try {
|
|
915
|
+
result = await summarizeWithLengthRecovery(model, context, baseMaxTokens, auth, signal, thinkingLevel, streamFn, runtime, charsPerToken, fork.request);
|
|
916
|
+
if (result.ok || !parsePromptTooLong(result.error.message).isPtl)
|
|
917
|
+
break;
|
|
918
|
+
failure = result.error.message;
|
|
919
|
+
}
|
|
920
|
+
catch (e) {
|
|
921
|
+
failure = thrownText(e);
|
|
922
|
+
if (!parsePromptTooLong(failure).isPtl)
|
|
923
|
+
throw e;
|
|
924
|
+
}
|
|
925
|
+
const ptl = parsePromptTooLong(failure);
|
|
926
|
+
if (retry >= COMPACTION_PTL_MAX_RETRIES || groups.length <= 1 || signal?.aborted === true)
|
|
927
|
+
return { kind: "fallback", detail: failure };
|
|
928
|
+
try {
|
|
929
|
+
onPtlRetry?.();
|
|
930
|
+
}
|
|
931
|
+
catch {
|
|
932
|
+
}
|
|
933
|
+
const beforeChars = serializeConversation(kept).length;
|
|
934
|
+
const gapChars = ptl.gapTokens !== undefined ? Math.ceil(ptl.gapTokens * cpt * PTL_GAP_SAFETY) : Math.ceil(beforeChars * PTL_NO_GAP_DROP_FRACTION);
|
|
935
|
+
const targetChars = Math.max(SUMMARY_INPUT_MIN_KEEP_CHARS, beforeChars - Math.max(gapChars, 1));
|
|
936
|
+
let remainingChars = beforeChars;
|
|
937
|
+
let droppedMessages = 0;
|
|
938
|
+
while (groups.length > 1 && remainingChars > targetChars) {
|
|
939
|
+
const gone = groups.shift();
|
|
940
|
+
droppedMessages += gone.length;
|
|
941
|
+
remainingChars -= serializeConversation(gone).length + 2;
|
|
942
|
+
}
|
|
943
|
+
if (droppedMessages === 0)
|
|
944
|
+
return { kind: "fallback", detail: failure };
|
|
945
|
+
groups = [...groups];
|
|
946
|
+
dropped = true;
|
|
947
|
+
try {
|
|
948
|
+
onInputTruncated?.({ label: "history", droppedChars: beforeChars - Math.max(remainingChars, 0), keptChars: Math.max(remainingChars, 0), ...(droppedMessages > 0 ? { droppedMessages } : {}) });
|
|
949
|
+
}
|
|
950
|
+
catch {
|
|
951
|
+
}
|
|
954
952
|
}
|
|
955
953
|
if (!result.ok) {
|
|
956
954
|
if (result.error.code === "summarization_failed" && (isEmptySummaryClass(result.error) || parsePromptTooLong(result.error.message).isPtl)) {
|
|
@@ -974,8 +972,6 @@ export async function generateSummary(currentMessages, model, summaryBudgetToken
|
|
|
974
972
|
const instructionFilesSection = fitContextInstructionFilesSection(contextInstructionFiles, model, cpt, SUMMARIZATION_SYSTEM_PROMPT.length + basePrompt.length + (previousSummary?.length ?? 0) + 128, baseMaxTokens);
|
|
975
973
|
const llmMessages = convertToLlm(currentMessages);
|
|
976
974
|
return summarizeWithPtlRetry({
|
|
977
|
-
label: "Summarization",
|
|
978
|
-
truncationLabel: "history",
|
|
979
975
|
llmMessages,
|
|
980
976
|
buildPromptText: (conversationText) => {
|
|
981
977
|
let promptText = `${instructionFilesSection}<conversation>\n${conversationText}\n</conversation>\n\n`;
|
|
@@ -1030,32 +1026,17 @@ export function prepareCompaction(pathEntries, settings, charsPerToken = DEFAULT
|
|
|
1030
1026
|
return err(new CompactionError("invalid_session", "First kept entry has no UUID - session may need migration"));
|
|
1031
1027
|
}
|
|
1032
1028
|
const firstKeptEntryId = firstKeptEntry.id;
|
|
1033
|
-
const historyEnd = cutPoint.isSplitTurn ? cutPoint.turnStartIndex : cutPoint.firstKeptEntryIndex;
|
|
1034
1029
|
const messagesToSummarize = [];
|
|
1035
|
-
for (let i = boundaryStart; i <
|
|
1030
|
+
for (let i = boundaryStart; i < cutPoint.firstKeptEntryIndex; i++) {
|
|
1036
1031
|
const msg = getMessageFromEntryForCompaction(pathEntries[i]);
|
|
1037
1032
|
if (msg) {
|
|
1038
1033
|
messagesToSummarize.push(msg);
|
|
1039
1034
|
}
|
|
1040
1035
|
}
|
|
1041
|
-
|
|
1042
|
-
if (cutPoint.isSplitTurn) {
|
|
1043
|
-
for (let i = cutPoint.turnStartIndex; i < cutPoint.firstKeptEntryIndex; i++) {
|
|
1044
|
-
const msg = getMessageFromEntryForCompaction(pathEntries[i]);
|
|
1045
|
-
if (msg) {
|
|
1046
|
-
turnPrefixMessages.push(msg);
|
|
1047
|
-
}
|
|
1048
|
-
}
|
|
1049
|
-
}
|
|
1050
|
-
if (messagesToSummarize.length === 0 && (!cutPoint.isSplitTurn || turnPrefixMessages.length === 0)) {
|
|
1036
|
+
if (messagesToSummarize.length === 0) {
|
|
1051
1037
|
return ok(undefined);
|
|
1052
1038
|
}
|
|
1053
1039
|
const fileOps = extractFileOperations(messagesToSummarize, pathEntries, prevCompactionIndex);
|
|
1054
|
-
if (cutPoint.isSplitTurn) {
|
|
1055
|
-
for (const msg of turnPrefixMessages) {
|
|
1056
|
-
extractFileOpsFromMessage(msg, fileOps);
|
|
1057
|
-
}
|
|
1058
|
-
}
|
|
1059
1040
|
const prevRetainedSkills = prevCompactionIndex >= 0 &&
|
|
1060
1041
|
!pathEntries[prevCompactionIndex].fromHook
|
|
1061
1042
|
? readRetainedInvokedSkills(pathEntries[prevCompactionIndex].details)
|
|
@@ -1063,7 +1044,7 @@ export function prepareCompaction(pathEntries, settings, charsPerToken = DEFAULT
|
|
|
1063
1044
|
const retentionBudgetChars = windowTokens !== undefined && windowTokens > 0
|
|
1064
1045
|
? Math.max(0, windowTokens - settings.reserveTokens - settings.keepRecentTokens) * charsPerToken
|
|
1065
1046
|
: undefined;
|
|
1066
|
-
const invokedSkills = budgetInvokedSkillsRetention(extractInvokedSkills(
|
|
1047
|
+
const invokedSkills = budgetInvokedSkillsRetention(extractInvokedSkills(messagesToSummarize, prevRetainedSkills), retentionBudgetChars);
|
|
1067
1048
|
const refSet = new Set();
|
|
1068
1049
|
if (prevCompactionIndex >= 0 && !pathEntries[prevCompactionIndex].fromHook) {
|
|
1069
1050
|
for (const r of readPersistedOutputRefs(pathEntries[prevCompactionIndex].details)) {
|
|
@@ -1071,23 +1052,18 @@ export function prepareCompaction(pathEntries, settings, charsPerToken = DEFAULT
|
|
|
1071
1052
|
}
|
|
1072
1053
|
}
|
|
1073
1054
|
extractPersistedOutputRefs(messagesToSummarize, refSet);
|
|
1074
|
-
if (cutPoint.isSplitTurn) {
|
|
1075
|
-
extractPersistedOutputRefs(turnPrefixMessages, refSet);
|
|
1076
|
-
}
|
|
1077
1055
|
const persistedOutputRefs = [...refSet].slice(-PERSISTED_OUTPUT_REFS_MAX_ENTRIES);
|
|
1078
1056
|
const prevElided = prevCompactionIndex >= 0 && !pathEntries[prevCompactionIndex].fromHook
|
|
1079
1057
|
? readElidedMessages(pathEntries[prevCompactionIndex].details)
|
|
1080
1058
|
: undefined;
|
|
1081
|
-
const elidedMessages = (prevElided ?? 0) + messagesToSummarize.length
|
|
1059
|
+
const elidedMessages = (prevElided ?? 0) + messagesToSummarize.length;
|
|
1082
1060
|
const carriedUnsummarizedMessages = prevCompactionIndex >= 0 && !pathEntries[prevCompactionIndex].fromHook
|
|
1083
1061
|
? readUnsummarizedMessages(pathEntries[prevCompactionIndex].details)
|
|
1084
1062
|
: undefined;
|
|
1085
|
-
const
|
|
1063
|
+
const summarizeReady = replaceInvokedSkillBodiesForSummary(messagesToSummarize, new Set(invokedSkills.map((s) => s.name)));
|
|
1086
1064
|
return ok({
|
|
1087
1065
|
firstKeptEntryId,
|
|
1088
1066
|
messagesToSummarize: summarizeReady,
|
|
1089
|
-
turnPrefixMessages: prefixReady,
|
|
1090
|
-
isSplitTurn: cutPoint.isSplitTurn,
|
|
1091
1067
|
tokensBefore,
|
|
1092
1068
|
previousSummary,
|
|
1093
1069
|
fileOps,
|
|
@@ -1103,23 +1079,9 @@ export function prepareCompaction(pathEntries, settings, charsPerToken = DEFAULT
|
|
|
1103
1079
|
settings,
|
|
1104
1080
|
});
|
|
1105
1081
|
}
|
|
1106
|
-
const TURN_PREFIX_SUMMARIZATION_PROMPT = `This is the PREFIX of a turn that was too large to keep. The SUFFIX (recent work) is retained.
|
|
1107
|
-
|
|
1108
|
-
Summarize the prefix to provide context for the retained suffix:
|
|
1109
|
-
|
|
1110
|
-
## Original Request
|
|
1111
|
-
[What did the user ask for in this turn?]
|
|
1112
|
-
|
|
1113
|
-
## Early Progress
|
|
1114
|
-
- [Key decisions and work done in the prefix]
|
|
1115
|
-
|
|
1116
|
-
## Context for Suffix
|
|
1117
|
-
- [Information needed to understand the retained recent work]
|
|
1118
|
-
|
|
1119
|
-
Be concise. Focus on what's needed to understand the kept suffix.`;
|
|
1120
1082
|
export { computeFileLists, serializeConversation } from "./utils.js";
|
|
1121
1083
|
export async function compact(preparation, model, auth, customInstructions, signal, thinkingLevel, streamFn, runtime, charsPerToken, onInputTruncated, onPtlRetry, forkContext) {
|
|
1122
|
-
const { firstKeptEntryId, messagesToSummarize,
|
|
1084
|
+
const { firstKeptEntryId, messagesToSummarize, tokensBefore, previousSummary, fileOps, invokedSkills, persistedOutputRefs, elidedMessages, carriedUnsummarizedMessages, contextInstructionFiles, settings, } = preparation;
|
|
1123
1085
|
let uncoveredThisPass = 0;
|
|
1124
1086
|
const observeInputTruncated = (info) => {
|
|
1125
1087
|
if (info.droppedMessages !== undefined && info.droppedMessages > 0) {
|
|
@@ -1130,15 +1092,21 @@ export async function compact(preparation, model, auth, customInstructions, sign
|
|
|
1130
1092
|
if (!firstKeptEntryId) {
|
|
1131
1093
|
return err(new CompactionError("invalid_session", "First kept entry has no UUID - session may need migration"));
|
|
1132
1094
|
}
|
|
1133
|
-
if (messagesToSummarize.length === 0
|
|
1095
|
+
if (messagesToSummarize.length === 0) {
|
|
1134
1096
|
return err(new CompactionError("summarization_failed", "Nothing to summarize (empty preparation)"));
|
|
1135
1097
|
}
|
|
1136
1098
|
let summary;
|
|
1137
1099
|
const summaryBudget = summaryOutputBudgetTokens(model, settings);
|
|
1138
1100
|
if (forkContext !== undefined && forkContext.messages.length > 0) {
|
|
1139
|
-
|
|
1101
|
+
let forkUncovered = 0;
|
|
1102
|
+
const forked = await forkSummarize(forkContext, model, Math.floor(0.8 * summaryBudget), auth, customInstructions, signal, thinkingLevel, streamFn, runtime, charsPerToken, contextInstructionFiles, (info) => {
|
|
1103
|
+
if (info.droppedMessages !== undefined && info.droppedMessages > 0)
|
|
1104
|
+
forkUncovered += info.droppedMessages;
|
|
1105
|
+
onInputTruncated?.(info);
|
|
1106
|
+
}, onPtlRetry);
|
|
1140
1107
|
if (forked.kind === "ok") {
|
|
1141
1108
|
summary = forked.summary;
|
|
1109
|
+
uncoveredThisPass += forkUncovered;
|
|
1142
1110
|
}
|
|
1143
1111
|
else if (forked.kind === "err") {
|
|
1144
1112
|
return err(forked.error);
|
|
@@ -1151,25 +1119,7 @@ export async function compact(preparation, model, auth, customInstructions, sign
|
|
|
1151
1119
|
}
|
|
1152
1120
|
}
|
|
1153
1121
|
}
|
|
1154
|
-
if (summary
|
|
1155
|
-
}
|
|
1156
|
-
else if (isSplitTurn && turnPrefixMessages.length > 0) {
|
|
1157
|
-
const [historyResult, turnPrefixResult] = await Promise.all([
|
|
1158
|
-
messagesToSummarize.length > 0
|
|
1159
|
-
? generateSummary(messagesToSummarize, model, summaryBudget, auth, signal, customInstructions, previousSummary, thinkingLevel, streamFn, runtime, charsPerToken, observeInputTruncated, onPtlRetry, contextInstructionFiles)
|
|
1160
|
-
:
|
|
1161
|
-
Promise.resolve(ok(previousSummary ? stripFileOperationsFooter(previousSummary) : "No prior history.")),
|
|
1162
|
-
generateTurnPrefixSummary(turnPrefixMessages, model, summaryBudget, auth, signal, customInstructions, thinkingLevel, streamFn, runtime, charsPerToken, observeInputTruncated, onPtlRetry, contextInstructionFiles),
|
|
1163
|
-
]);
|
|
1164
|
-
if (!historyResult.ok) {
|
|
1165
|
-
return err(historyResult.error);
|
|
1166
|
-
}
|
|
1167
|
-
if (!turnPrefixResult.ok) {
|
|
1168
|
-
return err(turnPrefixResult.error);
|
|
1169
|
-
}
|
|
1170
|
-
summary = `${historyResult.value}\n\n---\n\n**Turn Context (split turn):**\n\n${turnPrefixResult.value}`;
|
|
1171
|
-
}
|
|
1172
|
-
else {
|
|
1122
|
+
if (summary === undefined) {
|
|
1173
1123
|
const summaryResult = await generateSummary(messagesToSummarize, model, summaryBudget, auth, signal, customInstructions, previousSummary, thinkingLevel, streamFn, runtime, charsPerToken, observeInputTruncated, onPtlRetry, contextInstructionFiles);
|
|
1174
1124
|
if (!summaryResult.ok) {
|
|
1175
1125
|
return err(summaryResult.error);
|
|
@@ -1196,33 +1146,3 @@ export async function compact(preparation, model, auth, customInstructions, sign
|
|
|
1196
1146
|
},
|
|
1197
1147
|
});
|
|
1198
1148
|
}
|
|
1199
|
-
export function turnPrefixSummarizationPrompt(customInstructions) {
|
|
1200
|
-
return customInstructions
|
|
1201
|
-
? `${TURN_PREFIX_SUMMARIZATION_PROMPT}\n\nAdditional Instructions:\n${customInstructions}`
|
|
1202
|
-
: TURN_PREFIX_SUMMARIZATION_PROMPT;
|
|
1203
|
-
}
|
|
1204
|
-
async function generateTurnPrefixSummary(messages, model, summaryBudgetTokens, auth, signal, customInstructions, thinkingLevel, streamFn, runtime, charsPerToken, onInputTruncated, onPtlRetry, contextInstructionFiles) {
|
|
1205
|
-
const llmMessages = convertToLlm(messages);
|
|
1206
|
-
const basePrompt = turnPrefixSummarizationPrompt(customInstructions);
|
|
1207
|
-
const cpt = charsPerToken ?? model.charsPerToken ?? DEFAULT_CHARS_PER_TOKEN;
|
|
1208
|
-
const baseMaxTokens = Math.floor(0.5 * summaryBudgetTokens);
|
|
1209
|
-
const instructionFilesSection = fitContextInstructionFilesSection(contextInstructionFiles, model, cpt, SUMMARIZATION_SYSTEM_PROMPT.length + basePrompt.length + 128, baseMaxTokens);
|
|
1210
|
-
return summarizeWithPtlRetry({
|
|
1211
|
-
label: "Turn prefix summarization",
|
|
1212
|
-
truncationLabel: "turn_prefix",
|
|
1213
|
-
llmMessages,
|
|
1214
|
-
buildPromptText: (conversationText) => `${instructionFilesSection}<conversation>\n${conversationText}\n</conversation>\n\n${basePrompt}`,
|
|
1215
|
-
model,
|
|
1216
|
-
cpt,
|
|
1217
|
-
fixedPromptChars: SUMMARIZATION_SYSTEM_PROMPT.length + basePrompt.length + instructionFilesSection.length + 128,
|
|
1218
|
-
baseMaxTokens,
|
|
1219
|
-
auth,
|
|
1220
|
-
signal,
|
|
1221
|
-
thinkingLevel,
|
|
1222
|
-
streamFn,
|
|
1223
|
-
runtime,
|
|
1224
|
-
charsPerToken,
|
|
1225
|
-
onInputTruncated,
|
|
1226
|
-
onPtlRetry,
|
|
1227
|
-
});
|
|
1228
|
-
}
|
|
@@ -76,12 +76,11 @@ export declare function budgetInvokedSkillsRetention(newestFirst: InvokedSkillRe
|
|
|
76
76
|
* leaving the originals in the summarization input would (a) double-charge the window budget and
|
|
77
77
|
* (b) let multi-thousand-char skill texts crowd real conversation out of the summary input clamp.
|
|
78
78
|
* The toolResult MESSAGE stays (shallow-copied, same toolCallId/toolName) so the call/result
|
|
79
|
-
* pairing stays legal for serialization; only its content is swapped for a short note.
|
|
80
|
-
* lets a split-turn boundary pass both legs at once so the call→name pairing map spans them.
|
|
79
|
+
* pairing stays legal for serialization; only its content is swapped for a short note.
|
|
81
80
|
* `retainedNames` keeps the placeholder honest: a skill the retention budget skipped is disclosed
|
|
82
81
|
* as omitted, not claimed preserved. Non-matching messages pass through by reference.
|
|
83
82
|
*/
|
|
84
|
-
export declare function replaceInvokedSkillBodiesForSummary(
|
|
83
|
+
export declare function replaceInvokedSkillBodiesForSummary(messages: AgentMessage[], retainedNames: ReadonlySet<string>): AgentMessage[];
|
|
85
84
|
/** Defensive reader for persisted `CompactionDetails.invokedSkills` (details is `unknown` on the
|
|
86
85
|
* wire; sessions persisted before this field existed simply yield an empty list). */
|
|
87
86
|
export declare function readRetainedInvokedSkills(details: unknown): InvokedSkillRetention[];
|
|
@@ -129,13 +128,5 @@ export declare function computeFileLists(fileOps: FileOperations): {
|
|
|
129
128
|
};
|
|
130
129
|
/** Format file lists as summary metadata tags (each list capped at {@link FILE_LIST_MAX_ENTRIES}). */
|
|
131
130
|
export declare function formatFileOperations(readFiles: string[], modifiedFiles: string[]): string;
|
|
132
|
-
/**
|
|
133
|
-
* Inverse of {@link formatFileOperations}: strip a TRAILING file-ops footer block from a stored summary.
|
|
134
|
-
* Every summary persisted by `compact()` ends with this footer; when a prior summary is threaded verbatim
|
|
135
|
-
* as the history of a later split-turn compaction (bug-hunt #1), the canonical superset footer is
|
|
136
|
-
* re-appended — so the stale embedded one must be removed first to avoid a duplicate. Anchored at end-of-
|
|
137
|
-
* string, so a `<read-files>`/`<modified-files>` string that legitimately appears mid-body is untouched.
|
|
138
|
-
*/
|
|
139
|
-
export declare function stripFileOperationsFooter(summary: string): string;
|
|
140
131
|
/** Serialize LLM messages to plain text for summarization prompts. */
|
|
141
132
|
export declare function serializeConversation(messages: Message[]): string;
|