@myagentroam/agent 0.9.62 → 0.9.64
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/LICENSE +202 -0
- package/NOTICE +4 -0
- package/dist/cli/codex-auth-file.js +268 -3
- package/dist/cli/main.js +427 -2
- package/dist/error.js +66 -2
- package/dist/host/contracts.js +20 -2
- package/dist/host/local-agent-host.js +146 -2
- package/dist/host/local-process-executor.js +39 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.js +12 -2
- package/dist/model/anthropic-messages.js +474 -2
- package/dist/model/anthropic-thinking.js +33 -2
- package/dist/model/catalog-file.js +88 -2
- package/dist/model/configuration.js +137 -2
- package/dist/model/contracts.d.ts +2 -0
- package/dist/model/contracts.js +1 -2
- package/dist/model/http.js +529 -2
- package/dist/model/openai-responses.d.ts +2 -0
- package/dist/model/openai-responses.js +1602 -2
- package/dist/model/runtime-credential.js +35 -2
- package/dist/model/sse.js +199 -2
- package/dist/prompts/compact.js +25 -2
- package/dist/prompts/core.js +37 -2
- package/dist/prompts/execution-budget.js +10 -2
- package/dist/prompts/index.d.ts +3 -2
- package/dist/prompts/index.js +47 -2
- package/dist/prompts/modes.js +25 -2
- package/dist/prompts/output.js +1 -2
- package/dist/prompts/resources.d.ts +1 -1
- package/dist/prompts/resources.js +31 -2
- package/dist/prompts/subagent.d.ts +6 -0
- package/dist/prompts/subagent.js +29 -2
- package/dist/prompts/title.js +9 -2
- package/dist/prompts/workflow.js +32 -2
- package/dist/runtime/async-queue.js +62 -2
- package/dist/runtime/builtin-skills.js +19 -2
- package/dist/runtime/byted-ark-imagegen-skill.js +18 -2
- package/dist/runtime/codex-imagegen-skill.js +35 -2
- package/dist/runtime/compact.js +225 -2
- package/dist/runtime/context-gc-runtime.d.ts +35 -0
- package/dist/runtime/context-gc-runtime.js +163 -0
- package/dist/runtime/context-gc-tokens.d.ts +24 -0
- package/dist/runtime/context-gc-tokens.js +83 -0
- package/dist/runtime/context-gc.d.ts +66 -0
- package/dist/runtime/context-gc.js +909 -0
- package/dist/runtime/context-projection.d.ts +23 -0
- package/dist/runtime/context-projection.js +203 -0
- package/dist/runtime/environment-context.js +41 -2
- package/dist/runtime/execution-policy.js +13 -2
- package/dist/runtime/instructions.js +298 -2
- package/dist/runtime/normalize.js +40 -2
- package/dist/runtime/plan-output.js +95 -2
- package/dist/runtime/rollout-budget.d.ts +2 -0
- package/dist/runtime/rollout-budget.js +92 -2
- package/dist/runtime/token-budget.d.ts +2 -0
- package/dist/runtime/token-budget.js +44 -2
- package/dist/sdk/agent.js +1804 -2
- package/dist/sdk/types.d.ts +15 -5
- package/dist/sdk/types.js +1 -2
- package/dist/session/catalog.d.ts +5 -4
- package/dist/session/catalog.js +133 -2
- package/dist/session/context-gc-checkpoint.d.ts +148 -0
- package/dist/session/context-gc-checkpoint.js +665 -0
- package/dist/session/context-gc-replacements.d.ts +52 -0
- package/dist/session/context-gc-replacements.js +226 -0
- package/dist/session/context-gc-subagent.d.ts +43 -0
- package/dist/session/context-gc-subagent.js +267 -0
- package/dist/session/jsonl-store.d.ts +42 -4
- package/dist/session/jsonl-store.js +1657 -2
- package/dist/subagent/scheduler.d.ts +35 -2
- package/dist/subagent/scheduler.js +249 -2
- package/dist/subagent/session-controller.d.ts +94 -0
- package/dist/subagent/session-controller.js +675 -0
- package/dist/tools/agent-cancel.js +28 -2
- package/dist/tools/{task.d.ts → agent-message.d.ts} +2 -2
- package/dist/tools/agent-message.js +51 -0
- package/dist/tools/agent-start.js +84 -2
- package/dist/tools/agent-wait.js +53 -2
- package/dist/tools/apply-patch.js +478 -2
- package/dist/tools/code-mode.js +370 -2
- package/dist/tools/codex-image-gen.js +312 -2
- package/dist/tools/exec.js +455 -2
- package/dist/tools/execution-limits.d.ts +1 -0
- package/dist/tools/execution-limits.js +44 -2
- package/dist/tools/local-registry.js +233 -2
- package/dist/tools/local-workspace-tools.js +28 -2
- package/dist/tools/question.js +124 -2
- package/dist/tools/read-context.d.ts +16 -0
- package/dist/tools/read-context.js +85 -0
- package/dist/tools/read.d.ts +13 -0
- package/dist/tools/read.js +294 -2
- package/dist/tools/registry.js +76 -2
- package/dist/tools/runtime-context.d.ts +9 -2
- package/dist/tools/runtime-context.js +1 -2
- package/dist/tools/runtime.js +21 -2
- package/dist/tools/scheduler.js +41 -2
- package/dist/tools/shared/path-resolver.js +133 -2
- package/dist/tools/skill.js +37 -2
- package/dist/tools/todo-read.js +10 -2
- package/dist/tools/todo-write.js +65 -2
- package/dist/tools/todo.js +67 -2
- package/dist/tools/view-image.js +81 -2
- package/dist/tools/web-fetch.js +11 -2
- package/dist/tools/web-search.js +14 -2
- package/package.json +9 -7
- package/README.md +0 -3
- package/dist/runtime/prompt.d.ts +0 -9
- package/dist/runtime/prompt.js +0 -2
- package/dist/tools/shared/secret-redaction.d.ts +0 -4
- package/dist/tools/shared/secret-redaction.js +0 -2
- package/dist/tools/task-cancel.d.ts +0 -7
- package/dist/tools/task-cancel.js +0 -2
- package/dist/tools/task-output.d.ts +0 -7
- package/dist/tools/task-output.js +0 -2
- package/dist/tools/task-tools.d.ts +0 -36
- package/dist/tools/task-tools.js +0 -2
- package/dist/tools/task.js +0 -2
- package/dist/tools/todo-tools.d.ts +0 -25
- package/dist/tools/todo-tools.js +0 -2
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { ClientToolDefinition, ModelUsage } from '../model/contracts.js';
|
|
2
|
+
import { type ContextGcPlatform } from '../session/context-gc-checkpoint.js';
|
|
3
|
+
import { JsonlSessionStore, type SessionRecord } from '../session/jsonl-store.js';
|
|
4
|
+
import { type ContextProjection } from './context-projection.js';
|
|
5
|
+
export interface ContextGcRuntimeInput {
|
|
6
|
+
readonly store: JsonlSessionStore;
|
|
7
|
+
readonly sessionId: string;
|
|
8
|
+
readonly records?: readonly SessionRecord[];
|
|
9
|
+
readonly system: string;
|
|
10
|
+
readonly tools: readonly ClientToolDefinition[];
|
|
11
|
+
readonly modelId: string;
|
|
12
|
+
readonly modelProtocol?: string;
|
|
13
|
+
readonly contextWindowTokens: number;
|
|
14
|
+
readonly usage: ModelUsage;
|
|
15
|
+
readonly workspace: string;
|
|
16
|
+
readonly platform: ContextGcPlatform;
|
|
17
|
+
readonly activeProcessIds?: ReadonlySet<string>;
|
|
18
|
+
readonly getActiveProcessIds?: () => Promise<ReadonlySet<string>>;
|
|
19
|
+
}
|
|
20
|
+
export interface ContextGcCommitResult {
|
|
21
|
+
readonly records: readonly SessionRecord[];
|
|
22
|
+
readonly projection: ContextProjection;
|
|
23
|
+
}
|
|
24
|
+
/** Only scheduling metadata survives a call; records and validation caches do not. */
|
|
25
|
+
export declare class ContextGcRuntime {
|
|
26
|
+
#private;
|
|
27
|
+
reset(): void;
|
|
28
|
+
run(input: ContextGcRuntimeInput): Promise<ContextGcCommitResult | false>;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Runs the deterministic planner and commits its checkpoint. Planning and
|
|
32
|
+
* commit failures are opportunistic no-ops unless the checkpoint is confirmed
|
|
33
|
+
* durable after an ambiguous append result.
|
|
34
|
+
*/
|
|
35
|
+
export declare function tryCommitContextGc(input: ContextGcRuntimeInput): Promise<ContextGcCommitResult | false>;
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
2
|
+
import { ContextGcCheckpointCache, contextGcMinimumUsageGrowth, contextGcReplacementKey, contextGcSourceProjectionHash } from '../session/context-gc-checkpoint.js';
|
|
3
|
+
import { contextGcEligibleUsage, inspectContextGc } from './context-gc.js';
|
|
4
|
+
import { buildContextProjection } from './context-projection.js';
|
|
5
|
+
/** Only scheduling metadata survives a call; records and validation caches do not. */
|
|
6
|
+
export class ContextGcRuntime {
|
|
7
|
+
#scope = '';
|
|
8
|
+
#lastUsage;
|
|
9
|
+
#checkpoint;
|
|
10
|
+
#failures = 0;
|
|
11
|
+
#remaining = 0;
|
|
12
|
+
reset() {
|
|
13
|
+
this.#scope = '';
|
|
14
|
+
this.#lastUsage = undefined;
|
|
15
|
+
this.#checkpoint = undefined;
|
|
16
|
+
this.#failures = 0;
|
|
17
|
+
this.#remaining = 0;
|
|
18
|
+
}
|
|
19
|
+
async run(input) {
|
|
20
|
+
const scope = JSON.stringify([
|
|
21
|
+
input.sessionId,
|
|
22
|
+
input.modelId,
|
|
23
|
+
input.modelProtocol,
|
|
24
|
+
input.contextWindowTokens
|
|
25
|
+
]);
|
|
26
|
+
if (scope !== this.#scope) {
|
|
27
|
+
this.reset();
|
|
28
|
+
this.#scope = scope;
|
|
29
|
+
}
|
|
30
|
+
const usage = contextGcEligibleUsage(input.usage, input.contextWindowTokens);
|
|
31
|
+
if (usage === undefined) {
|
|
32
|
+
this.#lastUsage = undefined;
|
|
33
|
+
this.#failures = 0;
|
|
34
|
+
this.#remaining = 0;
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
if (this.#lastUsage !== undefined && usage < this.#lastUsage) {
|
|
38
|
+
this.#failures = 0;
|
|
39
|
+
this.#remaining = 0;
|
|
40
|
+
}
|
|
41
|
+
this.#lastUsage = usage;
|
|
42
|
+
const maximumInterval = usage / input.contextWindowTokens >= 0.8 ? 2 : 8;
|
|
43
|
+
this.#remaining = Math.min(this.#remaining, maximumInterval - 1);
|
|
44
|
+
if (this.#remaining > 0) {
|
|
45
|
+
this.#remaining--;
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
if (this.#checkpoint?.modelId === input.modelId &&
|
|
49
|
+
this.#checkpoint.contextWindowTokens === input.contextWindowTokens &&
|
|
50
|
+
usage - this.#checkpoint.contextInputTokens <
|
|
51
|
+
contextGcMinimumUsageGrowth(input.contextWindowTokens))
|
|
52
|
+
return false;
|
|
53
|
+
const attempt = await attemptContextGc(input);
|
|
54
|
+
if (attempt.result) {
|
|
55
|
+
this.#checkpoint = { ...attempt.result.projection.checkpoint.trigger };
|
|
56
|
+
this.#failures = 0;
|
|
57
|
+
this.#remaining = 1;
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
if (attempt.checkpointTrigger)
|
|
61
|
+
this.#checkpoint = { ...attempt.checkpointTrigger };
|
|
62
|
+
this.#failures = Math.min(3, this.#failures + 1);
|
|
63
|
+
this.#remaining =
|
|
64
|
+
Math.min(2 ** this.#failures, maximumInterval, attempt.retryAfterRollouts ?? Infinity) - 1;
|
|
65
|
+
}
|
|
66
|
+
return attempt.result;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Runs the deterministic planner and commits its checkpoint. Planning and
|
|
71
|
+
* commit failures are opportunistic no-ops unless the checkpoint is confirmed
|
|
72
|
+
* durable after an ambiguous append result.
|
|
73
|
+
*/
|
|
74
|
+
export async function tryCommitContextGc(input) {
|
|
75
|
+
return (await attemptContextGc(input)).result;
|
|
76
|
+
}
|
|
77
|
+
async function attemptContextGc(input) {
|
|
78
|
+
const contextUsage = contextGcEligibleUsage(input.usage, input.contextWindowTokens);
|
|
79
|
+
if (contextUsage === undefined)
|
|
80
|
+
return { result: false };
|
|
81
|
+
let deferred = { result: false };
|
|
82
|
+
let draft;
|
|
83
|
+
try {
|
|
84
|
+
const records = input.records ?? (await input.store.readExecutionState(input.sessionId)).contextRecords;
|
|
85
|
+
const checkpointCache = new ContextGcCheckpointCache();
|
|
86
|
+
const previous = checkpointCache.read(records, undefined, input.workspace);
|
|
87
|
+
if (previous) {
|
|
88
|
+
deferred = { ...deferred, checkpointTrigger: previous.payload.trigger };
|
|
89
|
+
if (contextUsage - previous.payload.trigger.contextInputTokens <
|
|
90
|
+
contextGcMinimumUsageGrowth(input.contextWindowTokens))
|
|
91
|
+
return deferred;
|
|
92
|
+
}
|
|
93
|
+
const projection = buildContextProjection(records, input.workspace, checkpointCache);
|
|
94
|
+
const inspection = inspectContextGc({
|
|
95
|
+
records,
|
|
96
|
+
checkpointCache,
|
|
97
|
+
messages: projection.entries.map((entry) => entry.message),
|
|
98
|
+
messageSources: projection.entries.map((entry) => entry.record),
|
|
99
|
+
system: input.system,
|
|
100
|
+
tools: input.tools,
|
|
101
|
+
modelId: input.modelId,
|
|
102
|
+
...(input.modelProtocol === undefined ? {} : { modelProtocol: input.modelProtocol }),
|
|
103
|
+
contextWindowTokens: input.contextWindowTokens,
|
|
104
|
+
usage: input.usage,
|
|
105
|
+
workspace: input.workspace,
|
|
106
|
+
platform: input.platform,
|
|
107
|
+
activeProcessIds: input.activeProcessIds ?? (await input.getActiveProcessIds?.()) ?? new Set()
|
|
108
|
+
});
|
|
109
|
+
if (inspection.retryAfterRollouts !== undefined)
|
|
110
|
+
deferred = { ...deferred, retryAfterRollouts: inspection.retryAfterRollouts };
|
|
111
|
+
const plan = inspection.plan;
|
|
112
|
+
if (!plan)
|
|
113
|
+
return deferred;
|
|
114
|
+
const hash = contextGcSourceProjectionHash(records, plan.draft.boundarySequence, plan.draft.base);
|
|
115
|
+
if (!hash)
|
|
116
|
+
return deferred;
|
|
117
|
+
plan.draft.sourceProjectionHash = hash;
|
|
118
|
+
draft = plan.draft;
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
return deferred;
|
|
122
|
+
}
|
|
123
|
+
try {
|
|
124
|
+
await input.store.commitContextGc(input.sessionId, draft);
|
|
125
|
+
return {
|
|
126
|
+
...deferred,
|
|
127
|
+
result: await matchingCheckpointWasPersisted(input.store, input.sessionId, draft, input.workspace)
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
catch (commitError) {
|
|
131
|
+
try {
|
|
132
|
+
return {
|
|
133
|
+
...deferred,
|
|
134
|
+
result: await matchingCheckpointWasPersisted(input.store, input.sessionId, draft, input.workspace)
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
catch { }
|
|
138
|
+
void commitError;
|
|
139
|
+
return deferred;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
async function matchingCheckpointWasPersisted(store, sessionId, draft, workspace) {
|
|
143
|
+
const state = await store.readExecutionState(sessionId);
|
|
144
|
+
const projection = buildContextProjection(state.contextRecords, workspace);
|
|
145
|
+
const payload = projection.checkpoint;
|
|
146
|
+
const latest = payload ? { payload } : undefined;
|
|
147
|
+
if (latest?.payload.boundarySequence !== draft.boundarySequence ||
|
|
148
|
+
latest.payload.sourceProjectionHash !== draft.sourceProjectionHash ||
|
|
149
|
+
!isDeepStrictEqual(latest.payload.base, draft.base) ||
|
|
150
|
+
!isDeepStrictEqual(latest.payload.trigger, draft.trigger) ||
|
|
151
|
+
!isDeepStrictEqual(latest.payload.economics, draft.economics) ||
|
|
152
|
+
!isDeepStrictEqual(latest.payload.metrics, draft.metrics))
|
|
153
|
+
return false;
|
|
154
|
+
const persisted = new Map(latest.payload.replacements.map((replacement) => [
|
|
155
|
+
contextGcReplacementKey(replacement),
|
|
156
|
+
replacement
|
|
157
|
+
]));
|
|
158
|
+
const matches = draft.replacements.every((replacement) => {
|
|
159
|
+
const value = persisted.get(contextGcReplacementKey(replacement));
|
|
160
|
+
return value !== undefined && isDeepStrictEqual(value, replacement);
|
|
161
|
+
});
|
|
162
|
+
return matches ? { records: state.contextRecords, projection } : false;
|
|
163
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { ClientToolDefinition, ModelMessage } from '../model/contracts.js';
|
|
2
|
+
export { MODEL_TOKEN_ESTIMATOR as CONTEXT_GC_TOKEN_ESTIMATOR } from './token-budget.js';
|
|
3
|
+
interface TokenContext {
|
|
4
|
+
readonly modelId: string;
|
|
5
|
+
readonly modelProtocol?: string;
|
|
6
|
+
readonly system: string;
|
|
7
|
+
readonly tools: readonly ClientToolDefinition[];
|
|
8
|
+
readonly messages?: readonly ModelMessage[];
|
|
9
|
+
readonly tokenCache?: Map<string, number>;
|
|
10
|
+
}
|
|
11
|
+
/** Uses Responses lowering, including native alias and cross-model filtering. */
|
|
12
|
+
export declare function contextGcTokenEntries(input: TokenContext, messages: readonly ModelMessage[]): {
|
|
13
|
+
tokens: number;
|
|
14
|
+
key: string;
|
|
15
|
+
text: string;
|
|
16
|
+
}[];
|
|
17
|
+
/** Cancel identical entries, including multiplicity, before estimating the difference. */
|
|
18
|
+
export declare function contextGcReclaimedTokens(input: TokenContext, before: readonly ModelMessage[], after: readonly ModelMessage[]): number;
|
|
19
|
+
export declare function contextGcPrefixTokens(input: TokenContext): number;
|
|
20
|
+
export declare function contextGcMessageTokens(input: TokenContext, messages: readonly ModelMessage[]): number;
|
|
21
|
+
export declare function contextGcCacheImpact(input: TokenContext, before: readonly ModelMessage[], after: readonly ModelMessage[], cacheRead: number, reclaimedTokens: number): {
|
|
22
|
+
preservedCachedPrefixTokens: number;
|
|
23
|
+
reclaimedCachedTokens: number;
|
|
24
|
+
};
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { openAiInput } from '../model/openai-responses.js';
|
|
2
|
+
import { countModelTokens } from './token-budget.js';
|
|
3
|
+
export { MODEL_TOKEN_ESTIMATOR as CONTEXT_GC_TOKEN_ESTIMATOR } from './token-budget.js';
|
|
4
|
+
/** Uses Responses lowering, including native alias and cross-model filtering. */
|
|
5
|
+
export function contextGcTokenEntries(input, messages) {
|
|
6
|
+
return serializedEntries(input, messages).map((entry) => ({
|
|
7
|
+
...entry,
|
|
8
|
+
tokens: tokensFor(input, entry.text)
|
|
9
|
+
}));
|
|
10
|
+
}
|
|
11
|
+
function serializedEntries(input, messages) {
|
|
12
|
+
const responses = input.modelProtocol === 'OPENAI_RESPONSES' ||
|
|
13
|
+
(input.modelProtocol === undefined &&
|
|
14
|
+
(input.messages ?? messages).some((message) => message.provider === 'OPENAI_RESPONSES'));
|
|
15
|
+
const values = responses
|
|
16
|
+
? openAiInput(messages, undefined, input.modelId, true)
|
|
17
|
+
: messages.filter((message) => message.role !== 'provider' ||
|
|
18
|
+
(message.provider === 'ANTHROPIC_MESSAGES' && message.providerModelId === input.modelId));
|
|
19
|
+
return values.map((value, index) => {
|
|
20
|
+
const item = value;
|
|
21
|
+
const callId = item.call_id ?? item.callId;
|
|
22
|
+
const output = item.role === 'tool' ||
|
|
23
|
+
item.type === 'function_call_output' ||
|
|
24
|
+
item.type === 'custom_tool_call_output';
|
|
25
|
+
const key = typeof callId === 'string'
|
|
26
|
+
? `${output ? 'output' : 'input'}:${callId}`
|
|
27
|
+
: typeof item.id === 'string'
|
|
28
|
+
? `id:${item.id}`
|
|
29
|
+
: `index:${index}`;
|
|
30
|
+
const text = stableJson(value);
|
|
31
|
+
return { key, text };
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
/** Cancel identical entries, including multiplicity, before estimating the difference. */
|
|
35
|
+
export function contextGcReclaimedTokens(input, before, after) {
|
|
36
|
+
const counts = new Map();
|
|
37
|
+
for (const entry of serializedEntries(input, before))
|
|
38
|
+
counts.set(entry.text, (counts.get(entry.text) ?? 0) + 1);
|
|
39
|
+
for (const entry of serializedEntries(input, after))
|
|
40
|
+
counts.set(entry.text, (counts.get(entry.text) ?? 0) - 1);
|
|
41
|
+
let reclaimed = 0;
|
|
42
|
+
for (const [text, count] of counts)
|
|
43
|
+
if (count !== 0)
|
|
44
|
+
reclaimed += count * tokensFor(input, text);
|
|
45
|
+
return Math.max(0, reclaimed);
|
|
46
|
+
}
|
|
47
|
+
export function contextGcPrefixTokens(input) {
|
|
48
|
+
return tokensFor(input, stableJson({ system: input.system, tools: input.tools }));
|
|
49
|
+
}
|
|
50
|
+
export function contextGcMessageTokens(input, messages) {
|
|
51
|
+
return contextGcTokenEntries(input, messages).reduce((sum, entry) => sum + entry.tokens, 0);
|
|
52
|
+
}
|
|
53
|
+
export function contextGcCacheImpact(input, before, after, cacheRead, reclaimedTokens) {
|
|
54
|
+
const afterByKey = new Map(contextGcTokenEntries(input, after).map((entry) => [entry.key, entry]));
|
|
55
|
+
let offset = contextGcPrefixTokens(input);
|
|
56
|
+
let earliest = cacheRead;
|
|
57
|
+
let reclaimedCachedTokens = 0;
|
|
58
|
+
for (const entry of contextGcTokenEntries(input, before)) {
|
|
59
|
+
const replacement = afterByKey.get(entry.key);
|
|
60
|
+
if (entry.text !== replacement?.text) {
|
|
61
|
+
earliest = Math.min(earliest, offset);
|
|
62
|
+
reclaimedCachedTokens += Math.min(Math.max(0, entry.tokens - (replacement?.tokens ?? 0)), Math.max(0, cacheRead - offset));
|
|
63
|
+
}
|
|
64
|
+
offset += entry.tokens;
|
|
65
|
+
}
|
|
66
|
+
return {
|
|
67
|
+
preservedCachedPrefixTokens: Math.max(0, Math.min(cacheRead, earliest)),
|
|
68
|
+
reclaimedCachedTokens: Math.min(reclaimedTokens, reclaimedCachedTokens)
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
function tokensFor(input, text) {
|
|
72
|
+
const cached = input.tokenCache?.get(text);
|
|
73
|
+
if (cached !== undefined)
|
|
74
|
+
return cached;
|
|
75
|
+
const tokens = countModelTokens(text);
|
|
76
|
+
input.tokenCache?.set(text, tokens);
|
|
77
|
+
return tokens;
|
|
78
|
+
}
|
|
79
|
+
function stableJson(value) {
|
|
80
|
+
return JSON.stringify(value, (_key, item) => item && typeof item === 'object' && !Array.isArray(item)
|
|
81
|
+
? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b)))
|
|
82
|
+
: item);
|
|
83
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { ClientToolDefinition, ModelMessage, ModelUsage } from '../model/contracts.js';
|
|
2
|
+
import { ContextGcCheckpointCache, type ContextGcCheckpointDraft, type ContextGcEconomicsPolicy, type ContextGcMetrics, type ContextGcPlatform } from '../session/context-gc-checkpoint.js';
|
|
3
|
+
import type { SessionRecord } from '../session/jsonl-store.js';
|
|
4
|
+
export declare const CONTEXT_GC_POLICY: ContextGcEconomicsPolicy;
|
|
5
|
+
interface ContextGcEconomicsInput {
|
|
6
|
+
readonly contextUsageTokens: number;
|
|
7
|
+
readonly reclaimedTokens: number;
|
|
8
|
+
readonly reclaimedCachedTokens: number;
|
|
9
|
+
readonly cacheReadTokens: number;
|
|
10
|
+
readonly preservedCachedPrefixTokens: number;
|
|
11
|
+
readonly compactDeferralCreditCostUnits: number;
|
|
12
|
+
readonly projectedRolloutsUntilCompactAfterGc: number;
|
|
13
|
+
readonly contextGrowthSampleCount: number;
|
|
14
|
+
readonly minimumGrossReductionRate?: number;
|
|
15
|
+
readonly minimumReclaimedTokens?: number;
|
|
16
|
+
}
|
|
17
|
+
export interface ContextGcEconomicsResult {
|
|
18
|
+
readonly cacheRebuildPenaltyCostUnits: number;
|
|
19
|
+
readonly requiredPositiveNetRollouts: number;
|
|
20
|
+
readonly requiredTargetRoiRollouts: number;
|
|
21
|
+
readonly expectedNetSavedCostUnits: number;
|
|
22
|
+
readonly cacheInvestmentRoi: number;
|
|
23
|
+
readonly grossReductionRate: number;
|
|
24
|
+
readonly passes: boolean;
|
|
25
|
+
}
|
|
26
|
+
export interface ContextGcPlan {
|
|
27
|
+
readonly stage: 'STAGE_A' | 'STAGE_A_AND_EXEC';
|
|
28
|
+
readonly draft: ContextGcCheckpointDraft;
|
|
29
|
+
readonly metrics: ContextGcMetrics;
|
|
30
|
+
}
|
|
31
|
+
export interface ContextGcInspection {
|
|
32
|
+
readonly plan?: ContextGcPlan;
|
|
33
|
+
readonly retryAfterRollouts?: number;
|
|
34
|
+
}
|
|
35
|
+
export interface ContextGcPlannerInput {
|
|
36
|
+
readonly records: readonly SessionRecord[];
|
|
37
|
+
readonly messages: readonly ModelMessage[];
|
|
38
|
+
readonly messageSources: readonly SessionRecord[];
|
|
39
|
+
readonly system: string;
|
|
40
|
+
readonly tools: readonly ClientToolDefinition[];
|
|
41
|
+
readonly modelId: string;
|
|
42
|
+
readonly modelProtocol?: string;
|
|
43
|
+
readonly contextWindowTokens: number;
|
|
44
|
+
readonly usage: ModelUsage;
|
|
45
|
+
readonly workspace: string;
|
|
46
|
+
readonly platform: ContextGcPlatform;
|
|
47
|
+
readonly activeProcessIds: ReadonlySet<string>;
|
|
48
|
+
readonly tokenCache?: Map<string, number>;
|
|
49
|
+
readonly checkpointCache?: ContextGcCheckpointCache;
|
|
50
|
+
}
|
|
51
|
+
export declare function evaluateContextGcEconomics(input: ContextGcEconomicsInput): ContextGcEconomicsResult;
|
|
52
|
+
export declare function contextGcMinimumGrossReductionRate(usageRatio: number): number;
|
|
53
|
+
export declare function contextGcMinimumReclaimedTokens(contextUsageTokens: number, contextWindowTokens: number): number;
|
|
54
|
+
export declare function contextGcEligibleUsage(usage: ModelUsage, contextWindowTokens: number): number | undefined;
|
|
55
|
+
export declare function planContextGc(input: ContextGcPlannerInput): ContextGcPlan | undefined;
|
|
56
|
+
export declare function inspectContextGc(input: ContextGcPlannerInput): ContextGcInspection;
|
|
57
|
+
export declare function contextGcImminentCompactAvoidanceCredit(input: {
|
|
58
|
+
readonly contextUsageTokens: number;
|
|
59
|
+
readonly contextWindowTokens: number;
|
|
60
|
+
readonly compactThresholdTokens: number;
|
|
61
|
+
readonly projectedTokensBeforeGc: number;
|
|
62
|
+
readonly projectedTokensAfterGc: number;
|
|
63
|
+
readonly contextGrowthP75Tokens: number;
|
|
64
|
+
}): number;
|
|
65
|
+
export declare function contextGcAppliedCompactCreditCostUnits(compactDeferralCreditCostUnits: number, imminentCompactAvoidanceCreditCostUnits: number): number;
|
|
66
|
+
export {};
|