omp-antigravity-acp-provider 0.2.2 → 0.2.4
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/README.md +9 -11
- package/THIRD_PARTY_LICENSES.txt +70 -39
- package/extension/acp-compaction.ts +14 -2
- package/extension/acp-errors.ts +11 -3
- package/extension/adapter-config.ts +1 -1
- package/extension/ambient.d.ts +23 -0
- package/extension/assets/zip-archive.mjs +10839 -0
- package/extension/auth-sync.ts +88 -7
- package/extension/commands.ts +12 -15
- package/extension/context-settings.ts +2 -2
- package/extension/index.ts +71 -35
- package/extension/model-catalog.ts +1 -1
- package/extension/omp-context.ts +14 -3
- package/extension/quota-usage.ts +2 -1
- package/extension/runtime/acp/bounded-stream.ts +78 -24
- package/extension/runtime/acp/connection.ts +18 -6
- package/extension/runtime/binding.ts +2 -2
- package/extension/runtime/config.ts +1 -1
- package/extension/runtime/managed.ts +2 -1
- package/extension/runtime/models.ts +15 -8
- package/extension/runtime/prompt.ts +90 -50
- package/extension/runtime/provider.ts +38 -10
- package/extension/runtime/runtime.ts +74 -44
- package/extension/runtime/stream/pi-events.ts +3 -3
- package/extension/runtime/tools/bridge.ts +20 -8
- package/extension/runtime/tools/relay.ts +2 -2
- package/extension/runtime/zip-archive.ts +1 -0
- package/extension/runtime.d.mts +1 -0
- package/extension/runtime.mjs +18311 -35376
- package/extension/secret-service.ts +28 -0
- package/extension/selectors.ts +8 -7
- package/extension/session-store.ts +7 -7
- package/extension/tier-connection.ts +39 -8
- package/extension/tool-policy.ts +2 -2
- package/extension/tool-relay-protocol.d.mts +5 -0
- package/extension/tool-routing.ts +40 -23
- package/extension/transcript-routing.ts +16 -3
- package/extension/turn-cancellation.ts +1 -1
- package/extension/usage-db.ts +42 -22
- package/extension/usage.ts +1 -1
- package/licenses/{pi-ai-1.3.0.txt → pi-mit.txt} +1 -2
- package/package.json +10 -8
|
@@ -27,8 +27,12 @@ export function boundedNdjsonStream(
|
|
|
27
27
|
const encoder = new TextEncoder();
|
|
28
28
|
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
29
29
|
let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
|
|
30
|
-
let
|
|
30
|
+
let chunks: Uint8Array<ArrayBufferLike>[] = [];
|
|
31
|
+
let chunkBytes = 0;
|
|
31
32
|
let closed = false;
|
|
33
|
+
let inputDone = false;
|
|
34
|
+
const queuedFrames: Uint8Array<ArrayBufferLike>[] = [];
|
|
35
|
+
let queuedIndex = 0;
|
|
32
36
|
let released = false;
|
|
33
37
|
const releaseReader = () => {
|
|
34
38
|
if (!reader || released) return;
|
|
@@ -43,41 +47,86 @@ export function boundedNdjsonStream(
|
|
|
43
47
|
if (closed) return;
|
|
44
48
|
try {
|
|
45
49
|
for (;;) {
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
while ((newline = pending.indexOf(0x0a)) >= 0) {
|
|
49
|
-
const frame = pending.subarray(0, newline);
|
|
50
|
-
pending = pending.slice(newline + 1);
|
|
50
|
+
while (queuedIndex < queuedFrames.length) {
|
|
51
|
+
const frame = queuedFrames[queuedIndex++]!;
|
|
51
52
|
if (frame.byteLength > maxFrameBytes) {
|
|
52
53
|
throw new Error(`ACP frame exceeds ${maxFrameBytes} bytes`);
|
|
53
54
|
}
|
|
54
55
|
enqueueFrame(frame, decoder, controller, options.onCompatibilityNoise);
|
|
55
56
|
if (controller.desiredSize !== null && controller.desiredSize <= 0) return;
|
|
56
57
|
}
|
|
58
|
+
queuedFrames.length = 0;
|
|
59
|
+
queuedIndex = 0;
|
|
60
|
+
if (inputDone) {
|
|
61
|
+
closed = true;
|
|
62
|
+
controller.close();
|
|
63
|
+
releaseReader();
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
57
66
|
const { value, done } = await reader!.read();
|
|
58
67
|
if (closed) return;
|
|
59
68
|
if (done) {
|
|
60
|
-
if (
|
|
61
|
-
if (
|
|
69
|
+
if (chunkBytes > 0) {
|
|
70
|
+
if (chunkBytes > maxFrameBytes) {
|
|
62
71
|
throw new Error(`ACP frame exceeds ${maxFrameBytes} bytes`);
|
|
63
72
|
}
|
|
64
|
-
|
|
65
|
-
|
|
73
|
+
const frame = chunks.length === 1 ? chunks[0]! : joinChunks(chunks, chunkBytes);
|
|
74
|
+
chunks = [];
|
|
75
|
+
chunkBytes = 0;
|
|
76
|
+
queuedFrames.push(frame);
|
|
66
77
|
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
releaseReader();
|
|
70
|
-
return;
|
|
78
|
+
inputDone = true;
|
|
79
|
+
continue;
|
|
71
80
|
}
|
|
72
81
|
if (!value || value.byteLength === 0) continue;
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
82
|
+
let offset = 0;
|
|
83
|
+
let newline = value.indexOf(0x0a, offset);
|
|
84
|
+
if (newline < 0) {
|
|
85
|
+
if (chunkBytes + value.byteLength > maxFrameBytes) {
|
|
86
|
+
throw new Error(`ACP frame exceeds ${maxFrameBytes} bytes`);
|
|
87
|
+
}
|
|
88
|
+
chunks.push(value.slice());
|
|
89
|
+
chunkBytes += value.byteLength;
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
while (newline >= 0) {
|
|
93
|
+
const tail = value.subarray(offset, newline);
|
|
94
|
+
const frameLength = chunkBytes + tail.byteLength;
|
|
95
|
+
if (frameLength > maxFrameBytes) {
|
|
96
|
+
throw new Error(`ACP frame exceeds ${maxFrameBytes} bytes`);
|
|
97
|
+
}
|
|
98
|
+
let frame: Uint8Array<ArrayBufferLike>;
|
|
99
|
+
if (chunks.length === 0) {
|
|
100
|
+
frame = tail;
|
|
101
|
+
} else {
|
|
102
|
+
frame = new Uint8Array(frameLength);
|
|
103
|
+
let cursor = 0;
|
|
104
|
+
for (const part of chunks) {
|
|
105
|
+
frame.set(part, cursor);
|
|
106
|
+
cursor += part.byteLength;
|
|
107
|
+
}
|
|
108
|
+
if (tail.byteLength > 0) frame.set(tail, cursor);
|
|
109
|
+
chunks = [];
|
|
110
|
+
chunkBytes = 0;
|
|
111
|
+
}
|
|
112
|
+
queuedFrames.push(frame);
|
|
113
|
+
offset = newline + 1;
|
|
114
|
+
newline = offset < value.byteLength ? value.indexOf(0x0a, offset) : -1;
|
|
115
|
+
}
|
|
116
|
+
if (offset < value.byteLength) {
|
|
117
|
+
const rest = value.subarray(offset);
|
|
118
|
+
if (rest.byteLength > maxFrameBytes) {
|
|
119
|
+
throw new Error(`ACP frame exceeds ${maxFrameBytes} bytes`);
|
|
120
|
+
}
|
|
121
|
+
chunks.push(rest.slice());
|
|
122
|
+
chunkBytes = rest.byteLength;
|
|
76
123
|
}
|
|
77
124
|
}
|
|
78
125
|
} catch (cause) {
|
|
79
126
|
if (closed) return;
|
|
80
127
|
closed = true;
|
|
128
|
+
queuedFrames.length = 0;
|
|
129
|
+
queuedIndex = 0;
|
|
81
130
|
const error = cause instanceof Error ? cause : new Error(String(cause));
|
|
82
131
|
options.onProtocolError?.(error);
|
|
83
132
|
// ACP SDK 0.16.1 starts its receive loop without observing the
|
|
@@ -90,6 +139,8 @@ export function boundedNdjsonStream(
|
|
|
90
139
|
},
|
|
91
140
|
async cancel(reason) {
|
|
92
141
|
closed = true;
|
|
142
|
+
queuedFrames.length = 0;
|
|
143
|
+
queuedIndex = 0;
|
|
93
144
|
try { await reader?.cancel(reason); } catch { /* The input is already gone. */ }
|
|
94
145
|
releaseReader();
|
|
95
146
|
},
|
|
@@ -121,14 +172,17 @@ export function boundedNdjsonStream(
|
|
|
121
172
|
return { readable, writable };
|
|
122
173
|
}
|
|
123
174
|
|
|
124
|
-
function
|
|
125
|
-
|
|
126
|
-
|
|
175
|
+
function joinChunks(
|
|
176
|
+
chunks: Uint8Array<ArrayBufferLike>[],
|
|
177
|
+
totalBytes: number,
|
|
127
178
|
): Uint8Array<ArrayBufferLike> {
|
|
128
|
-
if (
|
|
129
|
-
const joined = new Uint8Array(
|
|
130
|
-
|
|
131
|
-
|
|
179
|
+
if (chunks.length === 1) return chunks[0]!;
|
|
180
|
+
const joined = new Uint8Array(totalBytes);
|
|
181
|
+
let cursor = 0;
|
|
182
|
+
for (const chunk of chunks) {
|
|
183
|
+
joined.set(chunk, cursor);
|
|
184
|
+
cursor += chunk.byteLength;
|
|
185
|
+
}
|
|
132
186
|
return joined;
|
|
133
187
|
}
|
|
134
188
|
|
|
@@ -118,15 +118,16 @@ export class AntigravityAcpConnection {
|
|
|
118
118
|
} else if (notification.update.sessionUpdate === "current_mode_update") {
|
|
119
119
|
const state = this.getSessionState(notification.sessionId);
|
|
120
120
|
const modeSelector = findSessionSelector(state, "mode");
|
|
121
|
+
const currentModeId = notification.update.currentModeId;
|
|
121
122
|
this.sessions.set(notification.sessionId, {
|
|
122
123
|
...state,
|
|
123
124
|
...(state.modes
|
|
124
|
-
? { modes: { ...state.modes, currentModeId
|
|
125
|
+
? { modes: { ...state.modes, currentModeId } }
|
|
125
126
|
: {}),
|
|
126
127
|
...(modeSelector && state.configOptions
|
|
127
128
|
? { configOptions: state.configOptions.map(option =>
|
|
128
129
|
option.type === "select" && option.id === modeSelector.id
|
|
129
|
-
? { ...option, currentValue:
|
|
130
|
+
? { ...option, currentValue: currentModeId }
|
|
130
131
|
: option) }
|
|
131
132
|
: {}),
|
|
132
133
|
});
|
|
@@ -368,6 +369,14 @@ export class AntigravityAcpConnection {
|
|
|
368
369
|
await this.closePromise;
|
|
369
370
|
}
|
|
370
371
|
|
|
372
|
+
async discardSession(_sessionId: string): Promise<void> {}
|
|
373
|
+
|
|
374
|
+
muteSteerChunks(_sessionId: string): void {}
|
|
375
|
+
|
|
376
|
+
async confirmReplacement(_key: string, _sessionId: string): Promise<void> {}
|
|
377
|
+
|
|
378
|
+
async retireForReplacement(_key: string, _sessionId: string): Promise<void> {}
|
|
379
|
+
|
|
371
380
|
private updateSessionState(sessionId: string, response: unknown): SessionState {
|
|
372
381
|
const commands = (response as { availableCommands?: AvailableCommand[] | null }).availableCommands;
|
|
373
382
|
const state = { ...this.sessions.get(sessionId), ...decodeSessionState(response), ...(commands === undefined ? {} : { availableCommands: commands }) };
|
|
@@ -375,13 +384,15 @@ export class AntigravityAcpConnection {
|
|
|
375
384
|
return state;
|
|
376
385
|
}
|
|
377
386
|
|
|
378
|
-
|
|
387
|
+
protected async setSelector(
|
|
379
388
|
sessionId: string,
|
|
380
|
-
category:
|
|
389
|
+
category: string,
|
|
381
390
|
value: string,
|
|
382
391
|
signal?: AbortSignal,
|
|
383
392
|
): Promise<boolean> {
|
|
384
|
-
const selector =
|
|
393
|
+
const selector = this.sessions.get(sessionId)?.configOptions?.find(
|
|
394
|
+
option => option.type === "select" && (option.category === category || option.id === category),
|
|
395
|
+
);
|
|
385
396
|
if (!selector) return false;
|
|
386
397
|
const response = await this.withAbort(
|
|
387
398
|
this.withDeadline(
|
|
@@ -392,7 +403,8 @@ export class AntigravityAcpConnection {
|
|
|
392
403
|
signal,
|
|
393
404
|
);
|
|
394
405
|
const state = this.updateSessionState(sessionId, response);
|
|
395
|
-
|
|
406
|
+
const updated = state.configOptions?.find(option => option.id === selector.id);
|
|
407
|
+
if (!updated || updated.type !== "select" || updated.currentValue !== value) {
|
|
396
408
|
throw new AntigravityAcpError("protocol", `Antigravity did not confirm the requested ${category} selection`);
|
|
397
409
|
}
|
|
398
410
|
return true;
|
|
@@ -120,7 +120,7 @@ function matches(value: unknown, saved: unknown, budget = { nodes: 0 }): boolean
|
|
|
120
120
|
Object.getPrototypeOf(value) !== (array ? Array.prototype : Object.prototype)) return false;
|
|
121
121
|
const keys = Object.keys(value);
|
|
122
122
|
if (keys.length > MAX_MESSAGE_NODES || keys.length !== Object.keys(saved).length ||
|
|
123
|
-
(
|
|
123
|
+
(Array.isArray(value) && Array.isArray(saved) && (value.length !== saved.length || Object.getOwnPropertyNames(value).length !== keys.length + 1))) return false;
|
|
124
124
|
for (const key of keys) {
|
|
125
125
|
const descriptor = Object.getOwnPropertyDescriptor(value, key)!;
|
|
126
126
|
if (!Object.hasOwn(descriptor, "value") || !Object.hasOwn(saved, key) ||
|
|
@@ -136,7 +136,7 @@ export function createHistoryFingerprintMemo() {
|
|
|
136
136
|
if (previous && matches(value, previous.value)) return previous.digest;
|
|
137
137
|
// Drop stale strings even if canonical serialization subsequently throws.
|
|
138
138
|
if (previous) entries.delete(message);
|
|
139
|
-
if (!worthCaching(Reflect.get(value, "content"))) return compute();
|
|
139
|
+
if (!value || typeof value !== "object" || !worthCaching(Reflect.get(value, "content"))) return compute();
|
|
140
140
|
const saved = snapshot(value);
|
|
141
141
|
const digest = compute();
|
|
142
142
|
if (saved !== UNSUPPORTED) entries.set(message, { value: saved, digest });
|
|
@@ -3,7 +3,7 @@ import fs from "node:fs";
|
|
|
3
3
|
import os from "node:os";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
|
|
6
|
-
export type PermissionMode = "default" | "auto_edit" | "yolo";
|
|
6
|
+
export type PermissionMode = "default" | "auto_edit" | "accept-edits" | "yolo";
|
|
7
7
|
export type RuntimeUpdateMode = "automatic" | "notify" | "manual";
|
|
8
8
|
|
|
9
9
|
export interface AntigravityAcpConfig {
|
|
@@ -5,7 +5,7 @@ import os from "node:os";
|
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import { pipeline } from "node:stream/promises";
|
|
7
7
|
import { promisify } from "node:util";
|
|
8
|
-
import {
|
|
8
|
+
import type { File as ZipFile } from "unzipper";
|
|
9
9
|
|
|
10
10
|
import { loadConfig, type RuntimeUpdateMode } from "./config.ts";
|
|
11
11
|
import { resolveAntigravityAcpDirectory, resolveAntigravityAcpLaunch, type AntigravityLaunch } from "./acp/antigravity.ts";
|
|
@@ -447,6 +447,7 @@ async function extractRuntimeArchive(
|
|
|
447
447
|
destination: string,
|
|
448
448
|
release: ResolvedRuntimeRelease,
|
|
449
449
|
): Promise<void> {
|
|
450
|
+
const { Open } = await import("./zip-archive.ts");
|
|
450
451
|
const archive = await Open.file(archivePath);
|
|
451
452
|
validateRuntimeArchiveEntries(archive.files, release);
|
|
452
453
|
const expected = new Map<string, number>([
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { AcpModelInfo } from "./acp/session-state.ts";
|
|
2
|
+
import type { ContextOptions } from "../context-settings.ts";
|
|
2
3
|
import type {
|
|
3
4
|
Model,
|
|
4
5
|
ThinkingLevel,
|
|
@@ -8,11 +9,17 @@ import type {
|
|
|
8
9
|
export const PROVIDER_ID = "antigravity-acp";
|
|
9
10
|
export const API_ID = "antigravity-acp";
|
|
10
11
|
|
|
12
|
+
export interface AntigravityModel extends Omit<Model<typeof API_ID>, "baseUrl" | "input" | "compat"> {
|
|
13
|
+
baseUrl?: string;
|
|
14
|
+
input: readonly string[];
|
|
15
|
+
ompContextPolicy?: ContextOptions;
|
|
16
|
+
}
|
|
17
|
+
|
|
11
18
|
const ZERO_COST = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } as const;
|
|
12
19
|
type Effort = "low" | "medium" | "high";
|
|
13
20
|
type Variants = Partial<Record<Effort, string>>;
|
|
14
21
|
|
|
15
|
-
export const FALLBACK_MODELS: readonly Model<typeof API_ID>[] = [
|
|
22
|
+
export const FALLBACK_MODELS: readonly (Model<typeof API_ID> & { provider: typeof PROVIDER_ID })[] = [
|
|
16
23
|
reasoningModel("gemini-3.8-flash", "Gemini 3.8 Flash", {
|
|
17
24
|
low: "gemini-3.8-flash-low",
|
|
18
25
|
medium: "gemini-3.8-flash-medium",
|
|
@@ -37,7 +44,7 @@ export const FALLBACK_MODELS: readonly Model<typeof API_ID>[] = [
|
|
|
37
44
|
/** Collapse Antigravity's effort-qualified ACP IDs into one Pi model. The
|
|
38
45
|
* exact server IDs live in thinkingLevelMap, allowing Shift+Tab to select the
|
|
39
46
|
* corresponding low/medium/high variant without cluttering /model. */
|
|
40
|
-
export function projectModels(models: readonly AcpModelInfo[]): Model<typeof API_ID>[] {
|
|
47
|
+
export function projectModels(models: readonly AcpModelInfo[]): (Model<typeof API_ID> & { provider: typeof PROVIDER_ID })[] {
|
|
41
48
|
const safe = models.filter((candidate) => validModelId(candidate.modelId.trim()));
|
|
42
49
|
const groups = new Map<
|
|
43
50
|
string,
|
|
@@ -57,7 +64,7 @@ export function projectModels(models: readonly AcpModelInfo[]): Model<typeof API
|
|
|
57
64
|
|
|
58
65
|
const emittedGroups = new Set<string>();
|
|
59
66
|
const emittedIds = new Set<string>();
|
|
60
|
-
const projected: Model<typeof API_ID>[] = [];
|
|
67
|
+
const projected: (Model<typeof API_ID> & { provider: typeof PROVIDER_ID })[] = [];
|
|
61
68
|
for (const candidate of safe) {
|
|
62
69
|
const id = candidate.modelId.trim();
|
|
63
70
|
if (emittedIds.has(id)) continue;
|
|
@@ -88,8 +95,8 @@ export function projectModels(models: readonly AcpModelInfo[]): Model<typeof API
|
|
|
88
95
|
/** Resolve Pi's current reasoning level to the exact model ID advertised by
|
|
89
96
|
* Antigravity. Unsupported programmatic levels clamp to the nearest tier. */
|
|
90
97
|
export function resolveAcpModelId(
|
|
91
|
-
model: Model<typeof API_ID>,
|
|
92
|
-
reasoning: ThinkingLevel | undefined,
|
|
98
|
+
model: Pick<Model<typeof API_ID>, "id" | "reasoning" | "thinkingLevelMap">,
|
|
99
|
+
reasoning: ThinkingLevel | string | undefined,
|
|
93
100
|
): string {
|
|
94
101
|
const map = model.thinkingLevelMap;
|
|
95
102
|
if (!model.reasoning || !map) return model.id;
|
|
@@ -116,7 +123,7 @@ function reasoningModel(
|
|
|
116
123
|
id: string,
|
|
117
124
|
name: string,
|
|
118
125
|
variants: Variants,
|
|
119
|
-
): Model<typeof API_ID> {
|
|
126
|
+
): Model<typeof API_ID> & { provider: typeof PROVIDER_ID } {
|
|
120
127
|
const thinkingLevelMap: ThinkingLevelMap = {
|
|
121
128
|
off: null,
|
|
122
129
|
minimal: null,
|
|
@@ -129,7 +136,7 @@ function reasoningModel(
|
|
|
129
136
|
return baseModel(id, name, true, thinkingLevelMap);
|
|
130
137
|
}
|
|
131
138
|
|
|
132
|
-
function fixedModel(id: string, name: string): Model<typeof API_ID> {
|
|
139
|
+
function fixedModel(id: string, name: string): Model<typeof API_ID> & { provider: typeof PROVIDER_ID } {
|
|
133
140
|
return baseModel(id, name, false);
|
|
134
141
|
}
|
|
135
142
|
|
|
@@ -138,7 +145,7 @@ function baseModel(
|
|
|
138
145
|
name: string,
|
|
139
146
|
reasoning: boolean,
|
|
140
147
|
thinkingLevelMap?: ThinkingLevelMap,
|
|
141
|
-
): Model<typeof API_ID> {
|
|
148
|
+
): Model<typeof API_ID> & { provider: typeof PROVIDER_ID } {
|
|
142
149
|
return {
|
|
143
150
|
id,
|
|
144
151
|
name,
|
|
@@ -358,6 +358,7 @@ function planHistorySteps(
|
|
|
358
358
|
framing: HistoryFraming = MAIN_HISTORY_FRAMING,
|
|
359
359
|
): { prompt: TransferBlock[]; seedSteps: TransferBlock[][] } {
|
|
360
360
|
const metrics = prepareHistoryMetrics(items);
|
|
361
|
+
const verifyPlan = process.env.OMP_ACP_PLAN_VERIFY === "1";
|
|
361
362
|
const instructionBytes = instructionsBlock ? promptTextBytes([instructionsBlock]) : 0;
|
|
362
363
|
const tailBytes = promptTextBytes(tailBlocks);
|
|
363
364
|
const seedTail: TransferBlock[] = [{ type: "text", text: SEED_ACK_TEXT }];
|
|
@@ -387,10 +388,12 @@ function planHistorySteps(
|
|
|
387
388
|
cursor++;
|
|
388
389
|
continue;
|
|
389
390
|
}
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
391
|
+
if (verifyPlan) {
|
|
392
|
+
const rejected = assembleStep(chunkInstructions, items.slice(start, cursor + 1), seedTail, framing);
|
|
393
|
+
const actual = promptTextBytes(rejected);
|
|
394
|
+
if (actual !== predicted || actual <= ACP_STEP_TEXT_BYTES) {
|
|
395
|
+
throw new Error(`History chunk planner predicted ${predicted} bytes for a rejected candidate but rendered ${actual}`);
|
|
396
|
+
}
|
|
394
397
|
}
|
|
395
398
|
break;
|
|
396
399
|
}
|
|
@@ -406,20 +409,28 @@ function planHistorySteps(
|
|
|
406
409
|
const predicted = (stepInstructions ? instructionBytes : 0)
|
|
407
410
|
+ historyRangeTextBytes(metrics, span.start, span.end, framing.envelopeBytes) + seedTailBytes;
|
|
408
411
|
const step = assembleStep(stepInstructions, items.slice(span.start, span.end), seedTail, framing);
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
+
if (verifyPlan) {
|
|
413
|
+
const actual = promptTextBytes(step);
|
|
414
|
+
if (actual !== predicted) throw new Error(`History chunk planner predicted ${predicted} bytes but rendered ${actual}`);
|
|
415
|
+
checkStepTextBytes(actual);
|
|
416
|
+
} else {
|
|
417
|
+
checkStepTextBytes(predicted);
|
|
418
|
+
}
|
|
412
419
|
return step;
|
|
413
420
|
});
|
|
414
421
|
const effectiveFinalInstructions = finalInstructions ?? pendingInstructions;
|
|
415
422
|
const prompt = assembleStep(effectiveFinalInstructions, items.slice(cursor), tailBlocks, framing);
|
|
416
|
-
const actualPromptBytes = promptTextBytes(prompt);
|
|
417
423
|
const predictedPromptBytes = (effectiveFinalInstructions ? instructionBytes : 0)
|
|
418
424
|
+ historyRangeTextBytes(metrics, cursor, items.length, framing.envelopeBytes) + tailBytes;
|
|
419
|
-
if (
|
|
420
|
-
|
|
425
|
+
if (verifyPlan) {
|
|
426
|
+
const actualPromptBytes = promptTextBytes(prompt);
|
|
427
|
+
if (actualPromptBytes !== predictedPromptBytes) {
|
|
428
|
+
throw new Error(`History chunk planner predicted ${predictedPromptBytes} bytes for the final prompt but rendered ${actualPromptBytes}`);
|
|
429
|
+
}
|
|
430
|
+
checkStepTextBytes(actualPromptBytes);
|
|
431
|
+
} else {
|
|
432
|
+
checkStepTextBytes(predictedPromptBytes);
|
|
421
433
|
}
|
|
422
|
-
checkStepTextBytes(actualPromptBytes);
|
|
423
434
|
return { prompt, seedSteps };
|
|
424
435
|
}
|
|
425
436
|
|
|
@@ -444,12 +455,18 @@ function requestFinalHeader(inProgress: boolean, kind: PromptKind = "main"): str
|
|
|
444
455
|
(kind === "ephemeral" ? EPHEMERAL_NO_TOOLS_TEXT + "\n\n" : "");
|
|
445
456
|
}
|
|
446
457
|
|
|
447
|
-
function
|
|
448
|
-
if (maxBytes <= 0) return
|
|
449
|
-
|
|
458
|
+
function takeTextChunkSpan(text: string, maxBytes: number, startOffset = 0): { end: number; bytes: number } {
|
|
459
|
+
if (maxBytes <= 0 || startOffset >= text.length) return { end: startOffset, bytes: 0 };
|
|
460
|
+
const remainingChars = text.length - startOffset;
|
|
461
|
+
if (remainingChars * 3 <= maxBytes) {
|
|
462
|
+
const tail = startOffset === 0 ? text : text.slice(startOffset);
|
|
463
|
+
return { end: text.length, bytes: Buffer.byteLength(tail, "utf8") };
|
|
464
|
+
}
|
|
450
465
|
let bytes = 0;
|
|
451
|
-
let end =
|
|
452
|
-
|
|
466
|
+
let end = startOffset;
|
|
467
|
+
let lastNewlineEnd = -1;
|
|
468
|
+
let lastNewlineBytes = 0;
|
|
469
|
+
for (let index = startOffset; index < text.length;) {
|
|
453
470
|
const codePoint = text.codePointAt(index)!;
|
|
454
471
|
const units = codePoint > 0xffff ? 2 : 1;
|
|
455
472
|
const size = codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4;
|
|
@@ -457,16 +474,26 @@ function takeTextChunk(text: string, maxBytes: number): string {
|
|
|
457
474
|
bytes += size;
|
|
458
475
|
end += units;
|
|
459
476
|
index += units;
|
|
477
|
+
if (codePoint === 0x0a) {
|
|
478
|
+
lastNewlineEnd = end;
|
|
479
|
+
lastNewlineBytes = bytes;
|
|
480
|
+
}
|
|
460
481
|
}
|
|
461
|
-
if (end ===
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
if (newline > 0 && Buffer.byteLength(chunk.slice(0, newline + 1), "utf8") >= maxBytes * 0.5) {
|
|
467
|
-
return chunk.slice(0, newline + 1);
|
|
482
|
+
if (end === startOffset) {
|
|
483
|
+
const codePoint = text.codePointAt(startOffset)!;
|
|
484
|
+
const units = codePoint > 0xffff ? 2 : 1;
|
|
485
|
+
const size = codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4;
|
|
486
|
+
return { end: startOffset + units, bytes: size };
|
|
468
487
|
}
|
|
469
|
-
|
|
488
|
+
if (end < text.length && lastNewlineEnd > startOffset + 1 && lastNewlineBytes >= maxBytes * 0.5) {
|
|
489
|
+
return { end: lastNewlineEnd, bytes: lastNewlineBytes };
|
|
490
|
+
}
|
|
491
|
+
return { end, bytes };
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
function takeTextChunk(text: string, maxBytes: number): string {
|
|
495
|
+
const span = takeTextChunkSpan(text, maxBytes);
|
|
496
|
+
return span.end === text.length ? text : text.slice(0, span.end);
|
|
470
497
|
}
|
|
471
498
|
|
|
472
499
|
function splitOversizedRequest(
|
|
@@ -499,28 +526,29 @@ function splitOversizedRequest(
|
|
|
499
526
|
currentBytes = 0;
|
|
500
527
|
};
|
|
501
528
|
const appendText = (source: TransferBlock, text: string) => {
|
|
502
|
-
let
|
|
529
|
+
let offset = 0;
|
|
503
530
|
const resource = source.type === "resource" && source.resource ? source.resource : undefined;
|
|
504
531
|
const overhead = resource
|
|
505
532
|
? Buffer.byteLength(`Embedded resource (${resource.uri}):\n`, "utf8") + 2
|
|
506
533
|
: 2;
|
|
507
|
-
while (
|
|
534
|
+
while (offset < text.length) {
|
|
508
535
|
const capacity = maxSeedContent - currentBytes - overhead;
|
|
509
536
|
if (capacity <= 0) {
|
|
510
537
|
flush();
|
|
511
538
|
continue;
|
|
512
539
|
}
|
|
513
|
-
const
|
|
514
|
-
if (
|
|
540
|
+
const span = takeTextChunkSpan(text, capacity, offset);
|
|
541
|
+
if (span.end <= offset) {
|
|
515
542
|
flush();
|
|
516
543
|
continue;
|
|
517
544
|
}
|
|
545
|
+
const chunk = offset === 0 && span.end === text.length ? text : text.slice(offset, span.end);
|
|
518
546
|
current.push(resource
|
|
519
547
|
? { ...source, resource: { ...resource, text: chunk } }
|
|
520
548
|
: { ...source, text: chunk });
|
|
521
|
-
currentBytes +=
|
|
522
|
-
|
|
523
|
-
if (
|
|
549
|
+
currentBytes += span.bytes + overhead;
|
|
550
|
+
offset = span.end;
|
|
551
|
+
if (offset < text.length) flush();
|
|
524
552
|
}
|
|
525
553
|
};
|
|
526
554
|
for (const block of blocks) {
|
|
@@ -600,10 +628,11 @@ function historyRecordItems(
|
|
|
600
628
|
// future cold replay fail. Split its text into bounded records; the
|
|
601
629
|
// history envelope still marks every part as reference data.
|
|
602
630
|
const chunks: RecordItem[] = [];
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
let
|
|
631
|
+
const fullText = record.content;
|
|
632
|
+
let offset = 0;
|
|
633
|
+
while (offset < fullText.length) {
|
|
634
|
+
let span = takeTextChunkSpan(fullText, HISTORY_RECORD_CHUNK_BYTES, offset);
|
|
635
|
+
let chunk = offset === 0 && span.end === fullText.length ? fullText : fullText.slice(offset, span.end);
|
|
607
636
|
let candidate: HistoryRecord;
|
|
608
637
|
let json: string;
|
|
609
638
|
for (;;) {
|
|
@@ -613,14 +642,14 @@ function historyRecordItems(
|
|
|
613
642
|
break;
|
|
614
643
|
} catch (splitError) {
|
|
615
644
|
const splitMessage = splitError instanceof Error ? splitError.message : "";
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
chunk =
|
|
645
|
+
if (!splitMessage.includes("Maximum context length exceeded") || span.bytes <= 1) throw splitError;
|
|
646
|
+
const limit = Math.max(1, Math.floor(span.bytes * 0.8));
|
|
647
|
+
span = takeTextChunkSpan(fullText, limit, offset);
|
|
648
|
+
chunk = fullText.slice(offset, span.end);
|
|
620
649
|
}
|
|
621
650
|
}
|
|
622
651
|
chunks.push(make(candidate, [], [], json));
|
|
623
|
-
|
|
652
|
+
offset = span.end;
|
|
624
653
|
}
|
|
625
654
|
return chunks;
|
|
626
655
|
}
|
|
@@ -643,26 +672,28 @@ function historyRecordItems(
|
|
|
643
672
|
};
|
|
644
673
|
for (const block of record.content) {
|
|
645
674
|
if (block.type === "text") {
|
|
646
|
-
|
|
647
|
-
if (!
|
|
675
|
+
const text = block.text ?? "";
|
|
676
|
+
if (!text) {
|
|
648
677
|
current.push(block);
|
|
649
678
|
continue;
|
|
650
679
|
}
|
|
651
|
-
|
|
680
|
+
let offset = 0;
|
|
681
|
+
while (offset < text.length) {
|
|
652
682
|
const capacity = HISTORY_RECORD_CHUNK_BYTES - currentBytes;
|
|
653
683
|
if (capacity <= 0) {
|
|
654
684
|
flush();
|
|
655
685
|
continue;
|
|
656
686
|
}
|
|
657
|
-
const
|
|
658
|
-
if (
|
|
687
|
+
const span = takeTextChunkSpan(text, capacity, offset);
|
|
688
|
+
if (span.end <= offset) {
|
|
659
689
|
flush();
|
|
660
690
|
continue;
|
|
661
691
|
}
|
|
692
|
+
const chunk = offset === 0 && span.end === text.length ? text : text.slice(offset, span.end);
|
|
662
693
|
current.push({ ...block, text: chunk });
|
|
663
|
-
currentBytes +=
|
|
664
|
-
|
|
665
|
-
if (
|
|
694
|
+
currentBytes += span.bytes;
|
|
695
|
+
offset = span.end;
|
|
696
|
+
if (offset < text.length) flush();
|
|
666
697
|
}
|
|
667
698
|
} else {
|
|
668
699
|
current.push(block);
|
|
@@ -694,10 +725,19 @@ export function buildPromptParts(context: TransferContext, fresh: boolean, unsee
|
|
|
694
725
|
// catalog-store attaches ompContextPolicy to discovered models; re-resolution
|
|
695
726
|
// is only needed for partial input in tests and standalone callers.
|
|
696
727
|
const policy = limits.policy;
|
|
728
|
+
const fallbackWindow = policy?.contextWindow ?? limits.contextWindow ?? 32_768;
|
|
729
|
+
const fallbackMaxTokens = policy?.maxTokens ?? limits.maxTokens ?? 8192;
|
|
697
730
|
const options: ResolvedContextOptions = policy &&
|
|
698
731
|
typeof policy.inputTokenBudget === "number" && typeof policy.maxTransferBytes === "number" && typeof policy.maxImageBytes === "number"
|
|
699
|
-
?
|
|
700
|
-
|
|
732
|
+
? {
|
|
733
|
+
contextWindow: fallbackWindow,
|
|
734
|
+
maxTokens: fallbackMaxTokens,
|
|
735
|
+
reserveTokens: policy.reserveTokens ?? Math.min(16_384, Math.floor(fallbackWindow * 0.05)),
|
|
736
|
+
inputTokenBudget: policy.inputTokenBudget,
|
|
737
|
+
maxTransferBytes: policy.maxTransferBytes,
|
|
738
|
+
maxImageBytes: policy.maxImageBytes,
|
|
739
|
+
}
|
|
740
|
+
: resolveContextOptions({ id: "transfer", contextWindow: fallbackWindow, maxTokens: fallbackMaxTokens },
|
|
701
741
|
{ defaults: limits.policy ?? {}, models: {} });
|
|
702
742
|
// Ordinary callers keep the main wording; only a shadow side turn selects
|
|
703
743
|
// the ephemeral variant that prohibits every tool call.
|