@linxiraos/pi-agent-core 1.4.6 → 1.4.9
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 +17 -6
- package/dist/types/agent.d.ts +23 -0
- package/dist/types/compaction/branch-summarization.d.ts +2 -3
- package/dist/types/compaction/compaction-v2-streaming.d.ts +2 -1
- package/dist/types/compaction/compaction.d.ts +4 -2
- package/dist/types/compaction/utils.d.ts +8 -22
- package/dist/types/index.d.ts +0 -1
- package/dist/types/sent-tool-definitions.d.ts +11 -5
- package/dist/types/tokenizer.d.ts +10 -9
- package/dist/types/types.d.ts +8 -2
- package/package.json +10 -10
- package/src/agent-loop.ts +14 -41
- package/src/agent.ts +55 -13
- package/src/compaction/anthropic.ts +9 -4
- package/src/compaction/branch-summarization.ts +8 -10
- package/src/compaction/compaction-v2-streaming.ts +26 -19
- package/src/compaction/compaction.ts +33 -17
- package/src/compaction/openai.ts +7 -1
- package/src/compaction/prompts/anthropic-compaction-instructions.md +1 -2
- package/src/compaction/utils.ts +22 -96
- package/src/index.ts +0 -2
- package/src/sent-tool-definitions.ts +22 -5
- package/src/telemetry.ts +0 -8
- package/src/tokenizer.ts +62 -24
- package/src/types.ts +9 -2
- package/dist/types/utils/yield.d.ts +0 -71
- package/src/compaction/prompts/file-operations.md +0 -5
- package/src/utils/yield.ts +0 -183
package/src/compaction/utils.ts
CHANGED
|
@@ -5,27 +5,32 @@
|
|
|
5
5
|
import type { Message, ToolCall } from "@linxiraos/pi-ai";
|
|
6
6
|
import { type Dialect, getDialectDefinition } from "@linxiraos/pi-ai/dialect";
|
|
7
7
|
import { escapeHarmonyControlTokens } from "@linxiraos/pi-ai/utils/harmony-leak";
|
|
8
|
-
import {
|
|
8
|
+
import { prompt, stringifyJson } from "@linxiraos/pi-utils";
|
|
9
|
+
import * as snapcompact from "@linxiraos/pi-snapcompact";
|
|
9
10
|
import type { AgentMessage } from "../types";
|
|
10
|
-
import fileOperationsTemplate from "./prompts/file-operations.md" with { type: "text" };
|
|
11
11
|
import summarizationSystemPrompt from "./prompts/summarization-system.md" with { type: "text" };
|
|
12
12
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
13
|
+
/** @deprecated Import these from `@linxiraos/pi-snapcompact`. */
|
|
14
|
+
export {
|
|
15
|
+
computeFileLists,
|
|
16
|
+
createFileOps,
|
|
17
|
+
type FileOperations,
|
|
18
|
+
isUrlSchemePath,
|
|
19
|
+
upsertFileOperations,
|
|
20
|
+
} from "@linxiraos/pi-snapcompact";
|
|
16
21
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
22
|
+
/** @deprecated Use `upsertFileOperations("", readFiles, modifiedFiles, readSet)` from `@linxiraos/pi-snapcompact`. */
|
|
23
|
+
export function formatFileOperations(
|
|
24
|
+
readFiles: string[],
|
|
25
|
+
modifiedFiles: string[],
|
|
26
|
+
readSet?: ReadonlySet<string>,
|
|
27
|
+
): string {
|
|
28
|
+
return snapcompact.upsertFileOperations("", readFiles, modifiedFiles, readSet);
|
|
21
29
|
}
|
|
22
30
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
written: new Set(),
|
|
27
|
-
edited: new Set(),
|
|
28
|
-
};
|
|
31
|
+
/** Error text for a summarization call that hit its output limit (`stopReason: "length"`): partial text is never used. */
|
|
32
|
+
export function incompleteOutputError(prefix: string): string {
|
|
33
|
+
return `${prefix}: model output ended incomplete (stopReason: length)`;
|
|
29
34
|
}
|
|
30
35
|
|
|
31
36
|
// Read-tool selector grammar, mirrored from the conservative filesystem splitter in
|
|
@@ -86,27 +91,10 @@ export function isAlternateFormReadSelector(sel: string): boolean {
|
|
|
86
91
|
return sel.split(":").some(part => READ_ALTERNATE_FORM_RE.test(part));
|
|
87
92
|
}
|
|
88
93
|
|
|
89
|
-
/**
|
|
90
|
-
* A real filesystem path never contains a `scheme://` URL. Tool-call paths that
|
|
91
|
-
* do — `conflict://1`, `artifact://3`, `local://ctx.md`, `history://…`,
|
|
92
|
-
* `issue://12`, `https://…`, and the tolerated `file.ts:conflict://1` prefix
|
|
93
|
-
* form — are session-scoped or remote resources, not files the post-compaction
|
|
94
|
-
* agent can re-ground on. Keep them out of the `<files>` summary.
|
|
95
|
-
*/
|
|
96
|
-
const URL_SCHEME_RE = /[a-z][a-z0-9+.-]*:\/\//i;
|
|
97
|
-
|
|
98
|
-
/**
|
|
99
|
-
* Whether `path` references a `scheme://` URL (internal URI or web URL) rather
|
|
100
|
-
* than a filesystem path that belongs in the compaction `<files>` summary.
|
|
101
|
-
*/
|
|
102
|
-
export function isUrlSchemePath(path: string): boolean {
|
|
103
|
-
return URL_SCHEME_RE.test(path);
|
|
104
|
-
}
|
|
105
|
-
|
|
106
94
|
/**
|
|
107
95
|
* Extract file operations from tool calls in an assistant message.
|
|
108
96
|
*/
|
|
109
|
-
export function extractFileOpsFromMessage(message: AgentMessage, fileOps: FileOperations): void {
|
|
97
|
+
export function extractFileOpsFromMessage(message: AgentMessage, fileOps: snapcompact.FileOperations): void {
|
|
110
98
|
if (message.role !== "assistant") return;
|
|
111
99
|
if (!("content" in message) || !Array.isArray(message.content)) return;
|
|
112
100
|
|
|
@@ -123,7 +111,7 @@ export function extractFileOpsFromMessage(message: AgentMessage, fileOps: FileOp
|
|
|
123
111
|
|
|
124
112
|
// Internal URIs (conflict://, artifact://, local://, history://, …) and
|
|
125
113
|
// web URLs are not re-groundable files — keep them out of `<files>`.
|
|
126
|
-
if (isUrlSchemePath(path)) continue;
|
|
114
|
+
if (snapcompact.isUrlSchemePath(path)) continue;
|
|
127
115
|
|
|
128
116
|
switch (block.name) {
|
|
129
117
|
case "read":
|
|
@@ -139,68 +127,6 @@ export function extractFileOpsFromMessage(message: AgentMessage, fileOps: FileOp
|
|
|
139
127
|
}
|
|
140
128
|
}
|
|
141
129
|
|
|
142
|
-
/**
|
|
143
|
-
* Compute final file lists from file operations.
|
|
144
|
-
* Returns readFiles (files only read, not modified) and modifiedFiles.
|
|
145
|
-
*/
|
|
146
|
-
export function computeFileLists(fileOps: FileOperations): { readFiles: string[]; modifiedFiles: string[] } {
|
|
147
|
-
// Drop any `scheme://` URLs (e.g. legacy `conflict://`/`artifact://` entries
|
|
148
|
-
// rehydrated straight into `fileOps` from a pre-fix compaction summary) — only
|
|
149
|
-
// real files belong in `<files>`. New tool-call scans are already filtered.
|
|
150
|
-
const modified = new Set([...fileOps.edited, ...fileOps.written].filter(f => !isUrlSchemePath(f)));
|
|
151
|
-
const readOnly = [...fileOps.read].filter(f => !isUrlSchemePath(f) && !modified.has(f)).sort();
|
|
152
|
-
const modifiedFiles = [...modified].sort();
|
|
153
|
-
return { readFiles: readOnly, modifiedFiles };
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
/**
|
|
157
|
-
* Format file operations as one `<files>` tag: a grouped, prefix-folded
|
|
158
|
-
* directory tree (find-tool shape — `# dir/` headers, bare basenames) with a
|
|
159
|
-
* ` (Read)` / ` (Write)` / ` (RW)` marker per file instead of separate
|
|
160
|
-
* read/modified lists. `readSet` is the cumulative read set (`fileOps.read`),
|
|
161
|
-
* used to tell modified files that were also read (RW) from blind writes.
|
|
162
|
-
*/
|
|
163
|
-
const FILE_OPERATION_SUMMARY_LIMIT = 20;
|
|
164
|
-
|
|
165
|
-
function stripFileOperationTags(summary: string): string {
|
|
166
|
-
// Legacy <read-files>/<modified-files> tags are still stripped so summaries
|
|
167
|
-
// written before the combined <files> tag self-heal on the next compaction.
|
|
168
|
-
return summary
|
|
169
|
-
.replace(/<files>[\s\S]*?<\/files>\s*/g, "")
|
|
170
|
-
.replace(/<read-files>[\s\S]*?<\/read-files>\s*/g, "")
|
|
171
|
-
.replace(/<modified-files>[\s\S]*?<\/modified-files>\s*/g, "")
|
|
172
|
-
.trimEnd();
|
|
173
|
-
}
|
|
174
|
-
export function formatFileOperations(
|
|
175
|
-
readFiles: string[],
|
|
176
|
-
modifiedFiles: string[],
|
|
177
|
-
readSet?: ReadonlySet<string>,
|
|
178
|
-
): string {
|
|
179
|
-
if (readFiles.length === 0 && modifiedFiles.length === 0) return "";
|
|
180
|
-
const mode = new Map<string, "Read" | "Write" | "RW">();
|
|
181
|
-
for (const file of readFiles) mode.set(file, "Read");
|
|
182
|
-
for (const file of modifiedFiles) mode.set(file, readSet?.has(file) ? "RW" : "Write");
|
|
183
|
-
const all = [...mode.keys()].sort();
|
|
184
|
-
let files = formatGroupedPaths(all.slice(0, FILE_OPERATION_SUMMARY_LIMIT), path => ` (${mode.get(path)})`);
|
|
185
|
-
if (all.length > FILE_OPERATION_SUMMARY_LIMIT) {
|
|
186
|
-
files += `\n[…${all.length - FILE_OPERATION_SUMMARY_LIMIT} files elided…]`;
|
|
187
|
-
}
|
|
188
|
-
return prompt.render(fileOperationsTemplate, { files });
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
export function upsertFileOperations(
|
|
192
|
-
summary: string,
|
|
193
|
-
readFiles: string[],
|
|
194
|
-
modifiedFiles: string[],
|
|
195
|
-
readSet?: ReadonlySet<string>,
|
|
196
|
-
): string {
|
|
197
|
-
const baseSummary = stripFileOperationTags(summary);
|
|
198
|
-
const fileOperations = formatFileOperations(readFiles, modifiedFiles, readSet);
|
|
199
|
-
if (!fileOperations) return baseSummary;
|
|
200
|
-
if (!baseSummary) return fileOperations;
|
|
201
|
-
return `${baseSummary}\n\n${fileOperations}`;
|
|
202
|
-
}
|
|
203
|
-
|
|
204
130
|
// ============================================================================
|
|
205
131
|
// Message Serialization
|
|
206
132
|
// ============================================================================
|
package/src/index.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Message, Tool } from "@linxiraos/pi-ai";
|
|
1
|
+
import type { Context, Message, Tool } from "@linxiraos/pi-ai";
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Last wire definition this Agent sent for each tool name, so a provider that keeps
|
|
@@ -14,11 +14,28 @@ export class SentToolDefinitions {
|
|
|
14
14
|
}
|
|
15
15
|
|
|
16
16
|
/**
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
* skipped: the provider drops them from the declaration.
|
|
17
|
+
* A detached copy: an Agent that replays another's request history declares the same withdrawn tools. `keep`
|
|
18
|
+
* leaves out a definition the copy must never declare.
|
|
20
19
|
*/
|
|
21
|
-
|
|
20
|
+
copy(keep: (name: string) => boolean = () => true): SentToolDefinitions {
|
|
21
|
+
const copy = new SentToolDefinitions();
|
|
22
|
+
copy.record([...this.#byName.values()].filter(tool => keep(tool.name)));
|
|
23
|
+
return copy;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* `context` with {@link Context.inactiveTools} set to the definitions for names the latest
|
|
28
|
+
* `requestControls.tools.declared` in its messages holds that are not in its `tools`; cleared when
|
|
29
|
+
* there are none or the request declares no tools. Names never sent by this Agent are skipped: the
|
|
30
|
+
* provider drops them from the declaration.
|
|
31
|
+
*/
|
|
32
|
+
withInactiveTools(context: Context): Context {
|
|
33
|
+
const inactiveTools = context.tools?.length ? this.#inactiveFor(context.messages, context.tools) : undefined;
|
|
34
|
+
if (!inactiveTools && !context.inactiveTools) return context;
|
|
35
|
+
return { ...context, inactiveTools };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
#inactiveFor(messages: readonly Message[], active: readonly Tool[]): Tool[] | undefined {
|
|
22
39
|
let declared: readonly string[] | undefined;
|
|
23
40
|
for (let index = messages.length - 1; index >= 0; index--) {
|
|
24
41
|
const message = messages[index];
|
package/src/telemetry.ts
CHANGED
|
@@ -51,7 +51,6 @@ import {
|
|
|
51
51
|
} from "@opentelemetry/api";
|
|
52
52
|
import { AgentRunCollector, type AgentRunCoverage, type AgentRunSummary, type ToolStatus } from "./run-collector";
|
|
53
53
|
import type { AgentTool } from "./types";
|
|
54
|
-
import { EventLoopKeepalive } from "./utils/yield";
|
|
55
54
|
|
|
56
55
|
/** Default tracer name. Override via {@link AgentTelemetryConfig.tracerName}. */
|
|
57
56
|
export const DEFAULT_TRACER_NAME = "@linxiraos/pi-agent-core";
|
|
@@ -1840,13 +1839,6 @@ export async function instrumentedCompleteSimple<TApi extends Api>(
|
|
|
1840
1839
|
options: SimpleStreamOptions,
|
|
1841
1840
|
span: InstrumentedChatSpanOptions,
|
|
1842
1841
|
): Promise<AssistantMessage> {
|
|
1843
|
-
// Oneshot LLM calls (handoff, compaction/branch summaries) run outside the
|
|
1844
|
-
// agent `#runLoop`, which is where the EventLoopKeepalive normally lives.
|
|
1845
|
-
// Without it, Bun's JSC loop stops servicing timers while parked on the
|
|
1846
|
-
// long-lived completion promise, freezing any host spinner (e.g. the
|
|
1847
|
-
// `/handoff` Loader) until an unrelated I/O event (a terminal resize)
|
|
1848
|
-
// pokes the loop. Keep the loop healthy for the duration of the call.
|
|
1849
|
-
using _keepalive = new EventLoopKeepalive();
|
|
1850
1842
|
const { telemetry, parent, oneshotKind } = span;
|
|
1851
1843
|
const stepNumber = span.stepNumber ?? -1;
|
|
1852
1844
|
const reasoning = options.reasoning;
|
package/src/tokenizer.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import type { AssistantMessage, Model } from "@linxiraos/pi-ai";
|
|
2
2
|
import { renderDemotedThinking } from "@linxiraos/pi-ai/dialect/demotion";
|
|
3
|
+
import { isFactoryDroidGeminiWire, keepsFactoryGeminiReasoning } from "@linxiraos/pi-ai/providers/factory-droid/gemini";
|
|
3
4
|
import { ollamaChatDropsOwnThinking } from "@linxiraos/pi-ai/providers/ollama";
|
|
5
|
+
import { completionsDropsOwnThinking, isLiteLLMThinkingSignature } from "@linxiraos/pi-ai/providers/openai-completions";
|
|
4
6
|
import { isColdReplayableResponsesTurn } from "@linxiraos/pi-ai/providers/openai-shared";
|
|
5
7
|
import {
|
|
8
|
+
dropsForeignReasoningPayload,
|
|
6
9
|
isSameModelTurn,
|
|
7
10
|
shouldDropTruncatedThinkingOnlyAssistant,
|
|
8
11
|
} from "@linxiraos/pi-ai/providers/transform-messages";
|
|
@@ -21,7 +24,6 @@ import { base64ImageSize, estimateImageTokens, type ImageDetail, type ImageSize
|
|
|
21
24
|
import type { AgentMessage } from "./types";
|
|
22
25
|
|
|
23
26
|
const testEnv = Bun.env.NODE_ENV === "test";
|
|
24
|
-
const accurate = process.env.PI_TOKENIZER_ACCURATE === "1" && !testEnv;
|
|
25
27
|
|
|
26
28
|
const NATIVE_ENCODING: Record<ModelTokenizer, natives.Encoding> = {
|
|
27
29
|
"claude-v3": natives.Encoding.ClaudeV3,
|
|
@@ -32,6 +34,7 @@ const NATIVE_ENCODING: Record<ModelTokenizer, natives.Encoding> = {
|
|
|
32
34
|
"deepseek-v3": natives.Encoding.DeepSeekV3,
|
|
33
35
|
"kimi-k2": natives.Encoding.KimiK2,
|
|
34
36
|
glm5: natives.Encoding.Glm5,
|
|
37
|
+
cl100k: natives.Encoding.Cl100kBase,
|
|
35
38
|
o200k: natives.Encoding.O200kBase,
|
|
36
39
|
};
|
|
37
40
|
|
|
@@ -41,7 +44,12 @@ export function tokenizerEncodingForModel(model: Pick<Model, "tokenizer"> | null
|
|
|
41
44
|
}
|
|
42
45
|
|
|
43
46
|
type TokenizerModel = Pick<Model, "tokenizer"> &
|
|
44
|
-
snapcompact.ShapeTarget & {
|
|
47
|
+
snapcompact.ShapeTarget & {
|
|
48
|
+
compat?: Model["compat"];
|
|
49
|
+
thinking?: Model["thinking"];
|
|
50
|
+
reasoning?: boolean;
|
|
51
|
+
requestModelId?: string;
|
|
52
|
+
};
|
|
45
53
|
|
|
46
54
|
/** The model an assistant turn's native reasoning (signed thinking, Responses history) is replayed to. */
|
|
47
55
|
interface ReasoningReplayReader {
|
|
@@ -76,13 +84,12 @@ export interface TokenizerOptions {
|
|
|
76
84
|
}
|
|
77
85
|
|
|
78
86
|
/**
|
|
79
|
-
*
|
|
80
|
-
* when known, o200k_base otherwise
|
|
81
|
-
*
|
|
82
|
-
*
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
* undercounts).
|
|
87
|
+
* Every mode counts with the native tokenizer: the catalog-resolved family
|
|
88
|
+
* when known, o200k_base otherwise. They differ only in the fallback when the
|
|
89
|
+
* loaded addon does not recognize that encoding: `strict` and `upperbound`
|
|
90
|
+
* the raw byte length (never undercounts), `approximate` a bytes/4 guess.
|
|
91
|
+
* Tests (`NODE_ENV=test`) skip the native count outside `strict` and use that
|
|
92
|
+
* fallback.
|
|
86
93
|
*/
|
|
87
94
|
export type TokenCountMode = "strict" | "approximate" | "upperbound";
|
|
88
95
|
|
|
@@ -204,8 +211,8 @@ interface MessageEstimate {
|
|
|
204
211
|
* when the model's encoding, image or thinking-replay pricing, replay
|
|
205
212
|
* identity or native-history replay state changes); one-shot flows construct
|
|
206
213
|
* their own for the model that will be billed. Known tokenizer families use
|
|
207
|
-
* exact native counts;
|
|
208
|
-
*
|
|
214
|
+
* exact native counts; other models are counted in o200k_base, which bills
|
|
215
|
+
* unknown readers closer than a bytes/4 guess.
|
|
209
216
|
*/
|
|
210
217
|
export class Tokenizer {
|
|
211
218
|
readonly #encoding: natives.Encoding | null;
|
|
@@ -213,8 +220,11 @@ export class Tokenizer {
|
|
|
213
220
|
readonly frameBillingKey: string;
|
|
214
221
|
readonly #reasoningReader: ReasoningReplayReader | undefined;
|
|
215
222
|
readonly #dropsOllamaThinking: boolean;
|
|
223
|
+
readonly #dropsCompletionsThinking: boolean;
|
|
216
224
|
/** Claude's own API and prefix-bound hosts keep another model's signature from their deployment. */
|
|
217
225
|
readonly #readsDeploymentSignatures: boolean;
|
|
226
|
+
/** Factory's Gemini generate wire, whose replay pass keeps only Google-origin reasoning. */
|
|
227
|
+
readonly #factoryGeminiWire: boolean;
|
|
218
228
|
readonly reasoningReplayKey: string;
|
|
219
229
|
/** How the reader bills replayed signed thinking (catalog `thinking-replay-tokens`). */
|
|
220
230
|
readonly thinkingReplayTokens: ThinkingReplayTokens;
|
|
@@ -251,11 +261,16 @@ export class Tokenizer {
|
|
|
251
261
|
this.frameBillingKey = snapcompact.frameBillingKey(this.#frameBilling);
|
|
252
262
|
this.#reasoningReader = reasoningReplayReader(model);
|
|
253
263
|
this.#dropsOllamaThinking = ollamaChatDropsOwnThinking(model);
|
|
264
|
+
this.#dropsCompletionsThinking = completionsDropsOwnThinking(model);
|
|
254
265
|
const compat = model?.compat;
|
|
255
266
|
this.#readsDeploymentSignatures =
|
|
256
267
|
model?.api === "anthropic-messages" &&
|
|
257
268
|
((compat !== undefined && "officialEndpoint" in compat && compat.officialEndpoint) ||
|
|
258
269
|
model.thinking?.prefixBinding === true);
|
|
270
|
+
this.#factoryGeminiWire =
|
|
271
|
+
model?.api === "factory-droid-agent" &&
|
|
272
|
+
model.id !== undefined &&
|
|
273
|
+
isFactoryDroidGeminiWire({ id: model.id, requestModelId: model.requestModelId });
|
|
259
274
|
this.reasoningReplayKey = reasoningReplayKey(model);
|
|
260
275
|
this.thinkingReplayTokens = resolveThinkingReplayTokens(model ?? {});
|
|
261
276
|
this.nativeHistoryReplay = options?.nativeHistoryReplay ?? true;
|
|
@@ -266,11 +281,8 @@ export class Tokenizer {
|
|
|
266
281
|
}
|
|
267
282
|
|
|
268
283
|
countTokens(text: string | string[], mode: TokenCountMode = "approximate"): number {
|
|
269
|
-
if (mode
|
|
270
|
-
|
|
271
|
-
return countTokensNat(text, this.#encoding, mode, this.#nativeCounts).tokens;
|
|
272
|
-
if (accurate) return countTokensNat(text, undefined, mode, this.#nativeCounts).tokens;
|
|
273
|
-
return sumFragments(text, mode === "upperbound" ? byteLength : byteEstimate);
|
|
284
|
+
if (testEnv && mode !== "strict") return sumFragments(text, mode === "upperbound" ? byteLength : byteEstimate);
|
|
285
|
+
return countTokensNat(text, this.#encoding, mode, this.#nativeCounts).tokens;
|
|
274
286
|
}
|
|
275
287
|
|
|
276
288
|
/**
|
|
@@ -362,6 +374,21 @@ export class Tokenizer {
|
|
|
362
374
|
);
|
|
363
375
|
}
|
|
364
376
|
|
|
377
|
+
/**
|
|
378
|
+
* Whether `message`'s opaque reasoning payload (thinking signatures, redacted
|
|
379
|
+
* thinking) may reach this reader: everything except what `transformMessages`
|
|
380
|
+
* certainly strips from another model's turn, or what Factory's Gemini wire
|
|
381
|
+
* drops from a turn not of Google origin. Without a replay reader (no
|
|
382
|
+
* model, or a `filterReasoningHistory` target) every payload is charged,
|
|
383
|
+
* which overcounts a filtering reader's foreign turns.
|
|
384
|
+
*/
|
|
385
|
+
#receivesReasoningPayload(message: AssistantMessage): boolean {
|
|
386
|
+
const reader = this.#reasoningReader;
|
|
387
|
+
if (reader === undefined) return true;
|
|
388
|
+
if (this.#factoryGeminiWire) return keepsFactoryGeminiReasoning(message);
|
|
389
|
+
return !dropsForeignReasoningPayload(message, reader);
|
|
390
|
+
}
|
|
391
|
+
|
|
365
392
|
/**
|
|
366
393
|
* The replayed native Responses reasoning {@link countMessage} charges
|
|
367
394
|
* across `messages`: the part of a count that changes with the reading
|
|
@@ -424,6 +451,9 @@ export class Tokenizer {
|
|
|
424
451
|
const replayedReasoning = this.#replayedReasoningTokens(message);
|
|
425
452
|
const ollamaReader = this.#reasoningReader?.api === "ollama-chat" ? this.#reasoningReader : undefined;
|
|
426
453
|
const ownOllamaTurn = ollamaReader !== undefined && isSameModelTurn(message, ollamaReader);
|
|
454
|
+
const completionsReader = this.#dropsCompletionsThinking ? this.#reasoningReader : undefined;
|
|
455
|
+
const ownDroppedCompletionsTurn =
|
|
456
|
+
completionsReader !== undefined && isSameModelTurn(message, completionsReader);
|
|
427
457
|
if (typeof replayedReasoning === "number") extra += replayedReasoning;
|
|
428
458
|
const signaturesPriced = this.thinkingReplayTokens === "signature";
|
|
429
459
|
// The replay's signature rule (`transformMessages`): an aborted or
|
|
@@ -457,18 +487,22 @@ export class Tokenizer {
|
|
|
457
487
|
continue;
|
|
458
488
|
}
|
|
459
489
|
if (this.#dropsOllamaThinking && ownOllamaTurn) continue;
|
|
490
|
+
// Chat-completions drops it unless LiteLLM replays it in `thinking_blocks`.
|
|
491
|
+
if (ownDroppedCompletionsTurn && !isLiteLLMThinkingSignature(block.thinkingSignature)) continue;
|
|
460
492
|
fragments.push(block.thinking);
|
|
461
493
|
// Providers charge for the opaque signature/reasoning payload that
|
|
462
494
|
// rides alongside the thinking text (OpenAI Responses encrypted
|
|
463
|
-
// reasoning items, Gemini thought signatures)
|
|
464
|
-
// `
|
|
465
|
-
//
|
|
466
|
-
//
|
|
495
|
+
// reasoning items, Gemini thought signatures) wherever it survives
|
|
496
|
+
// replay; `transformMessages` strips another model's on most wires.
|
|
497
|
+
// A reader billing at `output` size (Claude) charges the reasoning,
|
|
498
|
+
// priced below, not these bytes. The compaction floor excludes it
|
|
499
|
+
// (its local byte size diverges from provider billing).
|
|
467
500
|
if (
|
|
468
501
|
block.thinkingSignature &&
|
|
469
502
|
!excludeEncryptedReasoning &&
|
|
470
503
|
signaturesPriced &&
|
|
471
|
-
typeof replayedReasoning !== "number"
|
|
504
|
+
typeof replayedReasoning !== "number" &&
|
|
505
|
+
this.#receivesReasoningPayload(message)
|
|
472
506
|
) {
|
|
473
507
|
fragments.push(block.thinkingSignature);
|
|
474
508
|
}
|
|
@@ -477,10 +511,13 @@ export class Tokenizer {
|
|
|
477
511
|
fragments.push(block.name);
|
|
478
512
|
fragments.push(stringifyJson(block.arguments) ?? "null");
|
|
479
513
|
} else if (block.type === "redactedThinking") {
|
|
480
|
-
// Encrypted reasoning blob the provider still bills for
|
|
481
|
-
// excluded from the compaction floor for
|
|
514
|
+
// Encrypted reasoning blob the provider still bills for wherever it
|
|
515
|
+
// survives replay, as above; excluded from the compaction floor for
|
|
516
|
+
// the same reason.
|
|
482
517
|
signedReasoning = true;
|
|
483
|
-
if (!excludeEncryptedReasoning && signaturesPriced
|
|
518
|
+
if (!excludeEncryptedReasoning && signaturesPriced && this.#receivesReasoningPayload(message)) {
|
|
519
|
+
fragments.push(block.data);
|
|
520
|
+
}
|
|
484
521
|
} else if (block.type === "anthropicServerTool") {
|
|
485
522
|
// Native Anthropic server-tool call/result replayed verbatim on the
|
|
486
523
|
// wire (server_tool_use input and opaque result content). The provider
|
|
@@ -578,6 +615,7 @@ export class Tokenizer {
|
|
|
578
615
|
reasoningReplayKey(model) === this.reasoningReplayKey &&
|
|
579
616
|
resolveThinkingReplayTokens(model ?? {}) === this.thinkingReplayTokens &&
|
|
580
617
|
ollamaChatDropsOwnThinking(model) === this.#dropsOllamaThinking &&
|
|
618
|
+
completionsDropsOwnThinking(model) === this.#dropsCompletionsThinking &&
|
|
581
619
|
(options?.nativeHistoryReplay ?? true) === this.nativeHistoryReplay
|
|
582
620
|
);
|
|
583
621
|
}
|
package/src/types.ts
CHANGED
|
@@ -672,7 +672,8 @@ export interface ToolCallContext {
|
|
|
672
672
|
providerMetadata?: ToolCallProviderMetadata;
|
|
673
673
|
/**
|
|
674
674
|
* Cooperative steering signal: aborted when a queued user/steering message
|
|
675
|
-
* (or an interrupting peer IRC) is detected while this tool batch runs.
|
|
675
|
+
* (or an interrupting peer IRC) is detected while this tool batch runs. Its
|
|
676
|
+
* `reason` names the source: a {@link SteeringInterruptSource} or `"irc"`.
|
|
676
677
|
* Unlike the hard abort signal it NEVER kills the tool — long-running
|
|
677
678
|
* tools MAY observe it (via `ctx.toolCall.steeringSignal`) to finish early
|
|
678
679
|
* or background themselves so the message injects promptly; ignoring it is
|
|
@@ -1086,7 +1087,7 @@ export type ToolApprovalDecision =
|
|
|
1086
1087
|
* prompt policies to the tool it dispatches into. */
|
|
1087
1088
|
policyKey?: string;
|
|
1088
1089
|
};
|
|
1089
|
-
export type ToolApproval = ToolApprovalDecision | ((args: unknown) => ToolApprovalDecision);
|
|
1090
|
+
export type ToolApproval = ToolApprovalDecision | ((args: unknown, context?: AgentToolContext) => ToolApprovalDecision);
|
|
1090
1091
|
|
|
1091
1092
|
/**
|
|
1092
1093
|
* Context passed to tool execution.
|
|
@@ -1253,6 +1254,12 @@ export interface AgentTool<
|
|
|
1253
1254
|
*/
|
|
1254
1255
|
approvalCacheTargets?: (args: unknown) => readonly string[] | undefined;
|
|
1255
1256
|
|
|
1257
|
+
/**
|
|
1258
|
+
* Paths a call reads beyond its working directory, matched against restricted folders when it
|
|
1259
|
+
* reports no `approvalCacheTargets`. Unlike cache targets they never key a remembered grant.
|
|
1260
|
+
*/
|
|
1261
|
+
approvalRestrictionPaths?: (args: unknown) => readonly string[] | undefined;
|
|
1262
|
+
|
|
1256
1263
|
/** The main execution callback for this tool. */
|
|
1257
1264
|
execute: AgentToolExecFn<TParameters, TDetails, TTheme>;
|
|
1258
1265
|
|
|
@@ -1,71 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Cooperative yield utility for preventing Bun event-loop busy-wait.
|
|
3
|
-
*
|
|
4
|
-
* ## Root Cause
|
|
5
|
-
*
|
|
6
|
-
* Bun 1.3.x (JavaScriptCore) event loop busy-waits (spins in userspace)
|
|
7
|
-
* when the only pending work is an unresolved Promise — even if there are
|
|
8
|
-
* active I/O watchers (stdin, child process pipes, etc.). The event loop
|
|
9
|
-
* continuously polls for microtask resolution instead of blocking in
|
|
10
|
-
* `epoll_wait`, consuming ~100% of a CPU core.
|
|
11
|
-
*
|
|
12
|
-
* This affects any `await` on a never-resolved Promise, including:
|
|
13
|
-
* - `Promise.withResolvers()` used for user input callbacks
|
|
14
|
-
* - `await proc.exited` for long-running child processes
|
|
15
|
-
* - Agent loop iterations waiting for the next tool call
|
|
16
|
-
*
|
|
17
|
-
* ## Fix
|
|
18
|
-
*
|
|
19
|
-
* A recurring `setInterval` keeps the event loop sleeping in `epoll_wait`.
|
|
20
|
-
* The `EventLoopKeepalive` class and `keepaliveWhile()` wrapper provide a
|
|
21
|
-
* clean way to install and clean up this keepalive timer.
|
|
22
|
-
*
|
|
23
|
-
* The older `yieldIfDue()` and `ExponentialYield` approaches (compensated
|
|
24
|
-
* sleep loops) are retained for the agent-loop hot-path where Promises
|
|
25
|
-
* resolve frequently and the keepalive alone is insufficient.
|
|
26
|
-
*/
|
|
27
|
-
export declare class EventLoopKeepalive {
|
|
28
|
-
#private;
|
|
29
|
-
[Symbol.dispose](): void;
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* Cooperative yield gate. Sleeps for at least {@link YieldGateOptions.sleepMs}
|
|
33
|
-
* but at most once every {@link YieldGateOptions.intervalMs}; hot-path callers
|
|
34
|
-
* invoke it freely and only the slow path actually sleeps.
|
|
35
|
-
*
|
|
36
|
-
* The clock and sleep are injectable so tests drive the gate logic without
|
|
37
|
-
* touching process-global `Date.now`/`scheduler.wait` — globals a concurrent
|
|
38
|
-
* test file can restore mid-run, which previously made the shared gate flake.
|
|
39
|
-
*/
|
|
40
|
-
export interface YieldGateOptions {
|
|
41
|
-
now?: () => number;
|
|
42
|
-
sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
43
|
-
intervalMs?: number;
|
|
44
|
-
sleepMs?: number;
|
|
45
|
-
}
|
|
46
|
-
export declare class YieldGate {
|
|
47
|
-
#private;
|
|
48
|
-
constructor(opts?: YieldGateOptions);
|
|
49
|
-
yieldIfDue(signal?: AbortSignal): Promise<void>;
|
|
50
|
-
}
|
|
51
|
-
/**
|
|
52
|
-
* Yield to the Bun event loop, sleeping for at least 20 ms — but at most once
|
|
53
|
-
* every {@link YIELD_INTERVAL_MS} across all callers.
|
|
54
|
-
*/
|
|
55
|
-
export declare function yieldIfDue(): Promise<void>;
|
|
56
|
-
export declare class ExponentialYield {
|
|
57
|
-
#private;
|
|
58
|
-
constructor(opts?: {
|
|
59
|
-
minMs?: number;
|
|
60
|
-
maxMs?: number;
|
|
61
|
-
multiplier?: number;
|
|
62
|
-
});
|
|
63
|
-
notifyActivity(): void;
|
|
64
|
-
sleep(signal?: AbortSignal): Promise<number>;
|
|
65
|
-
/**
|
|
66
|
-
* Race `racers` against an exponentially-backed-off cooperative yield.
|
|
67
|
-
* The losing sleep is cancelled as soon as a racer settles, so no stray
|
|
68
|
-
* timers keep the event loop alive past the racer's resolution.
|
|
69
|
-
*/
|
|
70
|
-
race<T>(racers: Array<Promise<T>>): Promise<T>;
|
|
71
|
-
}
|