@linxiraos/pi-agent-core 1.4.7 → 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 +6 -6
- package/dist/types/agent.d.ts +11 -0
- package/dist/types/compaction/branch-summarization.d.ts +2 -3
- package/dist/types/compaction/compaction-v2-streaming.d.ts +1 -0
- package/dist/types/compaction/compaction.d.ts +4 -2
- package/dist/types/compaction/utils.d.ts +8 -22
- package/dist/types/sent-tool-definitions.d.ts +11 -5
- package/dist/types/tokenizer.d.ts +9 -9
- package/dist/types/types.d.ts +3 -2
- package/package.json +8 -8
- package/src/agent-loop.ts +10 -19
- package/src/agent.ts +18 -5
- package/src/compaction/branch-summarization.ts +8 -10
- package/src/compaction/compaction-v2-streaming.ts +6 -2
- package/src/compaction/compaction.ts +23 -11
- package/src/compaction/openai.ts +4 -0
- package/src/compaction/utils.ts +22 -96
- package/src/sent-tool-definitions.ts +22 -5
- package/src/tokenizer.ts +53 -24
- package/src/types.ts +3 -2
- package/src/compaction/prompts/file-operations.md +0 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
## [Unreleased]
|
|
2
2
|
|
|
3
|
-
## [1.4.
|
|
3
|
+
## [1.4.9] - 2026-11-03
|
|
4
4
|
|
|
5
|
-
- Synced with upstream OMP v18.
|
|
5
|
+
- Synced with upstream OMP v18.16.0; user-visible changes ride the coding-agent package.
|
|
6
|
+
|
|
7
|
+
### Changed
|
|
8
|
+
|
|
9
|
+
- Switched from local `@linxiraos/pi-ai` to upstream `@mariozechner/pi-ai` package
|
|
6
10
|
|
|
7
11
|
## [9.2.2] - 2026-01-31
|
|
8
12
|
|
|
@@ -79,10 +83,6 @@
|
|
|
79
83
|
|
|
80
84
|
## [3.21.0] - 2026-01-06
|
|
81
85
|
|
|
82
|
-
### Changed
|
|
83
|
-
|
|
84
|
-
- Switched from local `@linxiraos/pi-ai` to upstream `@mariozechner/pi-ai` package
|
|
85
|
-
|
|
86
86
|
### Added
|
|
87
87
|
|
|
88
88
|
- Added `sessionId` option for provider caching (e.g., OpenAI Codex session-based prompt caching)
|
package/dist/types/agent.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { type ApiKey, type AssistantMessage, type AssistantMessageEvent, type Co
|
|
|
2
2
|
import type { Dialect } from "@linxiraos/pi-ai/dialect";
|
|
3
3
|
import type { HarmonyAuditEvent } from "@linxiraos/pi-ai/utils/harmony-leak";
|
|
4
4
|
import type { AppendOnlyContextManager } from "./append-only-context.js";
|
|
5
|
+
import { SentToolDefinitions } from "./sent-tool-definitions.js";
|
|
5
6
|
import { Tokenizer } from "./tokenizer.js";
|
|
6
7
|
import type { AgentBeforeModelCall, AgentContext, AgentEvent, AgentLoopConfig, AgentMessage, AgentState, AgentTool, AgentToolContext, AgentTurnEndContext, AsideBoundary, AsideMessage, PrepareQueuedMessages, SpeculativeToolExecutionConfig, StreamFn, ToolCallContext, ToolChoiceDirective } from "./types.js";
|
|
7
8
|
export declare class AgentBusyError extends Error {
|
|
@@ -64,6 +65,11 @@ export interface AgentOptions {
|
|
|
64
65
|
* Shared provider state map for session-scoped transport/session caches.
|
|
65
66
|
*/
|
|
66
67
|
providerSessionState?: Map<string, ProviderSessionState>;
|
|
68
|
+
/**
|
|
69
|
+
* Tool definitions already sent, for an Agent that replays another Agent's request history
|
|
70
|
+
* (see {@link Agent.copySentToolDefinitions}). Defaults to an empty store.
|
|
71
|
+
*/
|
|
72
|
+
sentToolDefinitions?: SentToolDefinitions;
|
|
67
73
|
/**
|
|
68
74
|
* Resolves an API key or resolver dynamically for each LLM call.
|
|
69
75
|
* Useful for expiring tokens and model-scoped credential routing.
|
|
@@ -295,6 +301,11 @@ export declare class Agent {
|
|
|
295
301
|
* Set the prompt cache key forwarded to providers.
|
|
296
302
|
*/
|
|
297
303
|
set promptCacheKey(value: string | undefined);
|
|
304
|
+
/**
|
|
305
|
+
* A detached copy of the tool definitions this agent has sent (`AgentOptions.sentToolDefinitions`), without the
|
|
306
|
+
* names `keep` rejects.
|
|
307
|
+
*/
|
|
308
|
+
copySentToolDefinitions(keep?: (name: string) => boolean): SentToolDefinitions;
|
|
298
309
|
/**
|
|
299
310
|
* Fields added to every log record written while this agent runs (the
|
|
300
311
|
* owning session's `sessionId`), so in-process agents' records stay apart.
|
|
@@ -5,12 +5,12 @@
|
|
|
5
5
|
* a summary of the branch being left so context isn't lost.
|
|
6
6
|
*/
|
|
7
7
|
import type { Api, ApiKey, AssistantMessage, Context, Model, SimpleStreamOptions } from "@linxiraos/pi-ai";
|
|
8
|
+
import * as snapcompact from "@linxiraos/pi-snapcompact";
|
|
8
9
|
import { type AgentTelemetry } from "../telemetry.js";
|
|
9
10
|
import { Tokenizer } from "../tokenizer.js";
|
|
10
11
|
import type { AgentMessage } from "../types.js";
|
|
11
12
|
import type { ReadonlySessionManager, SessionEntry } from "./entries.js";
|
|
12
13
|
import { type ConvertToLlm } from "./messages.js";
|
|
13
|
-
import { type FileOperations } from "./utils.js";
|
|
14
14
|
export interface BranchSummaryResult {
|
|
15
15
|
summary?: string;
|
|
16
16
|
readFiles?: string[];
|
|
@@ -23,12 +23,11 @@ export interface BranchSummaryDetails {
|
|
|
23
23
|
readFiles: string[];
|
|
24
24
|
modifiedFiles: string[];
|
|
25
25
|
}
|
|
26
|
-
export type { FileOperations } from "./utils.js";
|
|
27
26
|
export interface BranchPreparation {
|
|
28
27
|
/** Messages extracted for summarization, in chronological order */
|
|
29
28
|
messages: AgentMessage[];
|
|
30
29
|
/** File operations extracted from tool calls */
|
|
31
|
-
fileOps: FileOperations;
|
|
30
|
+
fileOps: snapcompact.FileOperations;
|
|
32
31
|
/** Total estimated tokens in messages */
|
|
33
32
|
totalTokens: number;
|
|
34
33
|
}
|
|
@@ -85,6 +85,7 @@ export declare function requestCompactionV2Streaming(model: Model, apiKey: strin
|
|
|
85
85
|
providerSessionState?: Map<string, ProviderSessionState>;
|
|
86
86
|
codexCompaction?: CodexCompactionContext;
|
|
87
87
|
preferWebsockets?: boolean;
|
|
88
|
+
codexAccessPrograms?: boolean;
|
|
88
89
|
}): Promise<CompactionV2Response>;
|
|
89
90
|
/** Build Codex-style V2 replacement history from retention candidates plus compaction output. */
|
|
90
91
|
export declare function buildCompactionV2ReplacementHistory(input: unknown[], compactionItem: Record<string, unknown>, retainedMessageBudget?: number): {
|
|
@@ -5,13 +5,13 @@
|
|
|
5
5
|
* and after compaction the session is reloaded.
|
|
6
6
|
*/
|
|
7
7
|
import { type Api, type ApiKey, type AssistantMessage, type CodexCompactionContext, type Context, type FetchImpl, type MessageAttribution, type Model, type OneshotRetryOptions, type ProviderSessionState, type SimpleStreamOptions, type Tool, type Usage } from "@linxiraos/pi-ai";
|
|
8
|
+
import * as snapcompact from "@linxiraos/pi-snapcompact";
|
|
8
9
|
import { type AgentTelemetry } from "../telemetry.js";
|
|
9
10
|
import { ThinkingLevel } from "../thinking.js";
|
|
10
11
|
import { Tokenizer } from "../tokenizer.js";
|
|
11
12
|
import type { AgentMessage } from "../types.js";
|
|
12
13
|
import type { SessionEntry } from "./entries.js";
|
|
13
14
|
import { type ConvertToLlm } from "./messages.js";
|
|
14
|
-
import { type FileOperations } from "./utils.js";
|
|
15
15
|
/** Details stored in CompactionEntry.details for file tracking */
|
|
16
16
|
export interface CompactionDetails {
|
|
17
17
|
readFiles: string[];
|
|
@@ -256,6 +256,8 @@ export interface SummaryOptions {
|
|
|
256
256
|
providerSessionState?: Map<string, ProviderSessionState>;
|
|
257
257
|
/** Whether Codex remote compaction should prefer the provider WebSocket transport. */
|
|
258
258
|
preferWebsockets?: boolean;
|
|
259
|
+
/** Daybreak Blue request on Codex remote compaction; see `StreamOptions.codexAccessPrograms`. */
|
|
260
|
+
codexAccessPrograms?: boolean;
|
|
259
261
|
/** Classification shared by every provider request in this logical compaction. */
|
|
260
262
|
codexCompaction?: CodexCompactionContext;
|
|
261
263
|
/** Provider-visible tools for remote compaction transports that replay native tool history. */
|
|
@@ -366,7 +368,7 @@ export interface CompactionPreparation {
|
|
|
366
368
|
/** Preserved opaque compaction payload from the previous compaction, if any. */
|
|
367
369
|
previousPreserveData?: Record<string, unknown>;
|
|
368
370
|
/** File operations extracted from messagesToSummarize */
|
|
369
|
-
fileOps: FileOperations;
|
|
371
|
+
fileOps: snapcompact.FileOperations;
|
|
370
372
|
/** Compaction settions from settings.jsonl */
|
|
371
373
|
settings: CompactionSettings;
|
|
372
374
|
}
|
|
@@ -3,13 +3,14 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import type { Message } from "@linxiraos/pi-ai";
|
|
5
5
|
import { type Dialect } from "@linxiraos/pi-ai/dialect";
|
|
6
|
+
import * as snapcompact from "@linxiraos/pi-snapcompact";
|
|
6
7
|
import type { AgentMessage } from "../types.js";
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
export declare function
|
|
8
|
+
/** @deprecated Import these from `@linxiraos/pi-snapcompact`. */
|
|
9
|
+
export { computeFileLists, createFileOps, type FileOperations, isUrlSchemePath, upsertFileOperations, } from "@linxiraos/pi-snapcompact";
|
|
10
|
+
/** @deprecated Use `upsertFileOperations("", readFiles, modifiedFiles, readSet)` from `@linxiraos/pi-snapcompact`. */
|
|
11
|
+
export declare function formatFileOperations(readFiles: string[], modifiedFiles: string[], readSet?: ReadonlySet<string>): string;
|
|
12
|
+
/** Error text for a summarization call that hit its output limit (`stopReason: "length"`): partial text is never used. */
|
|
13
|
+
export declare function incompleteOutputError(prefix: string): string;
|
|
13
14
|
/**
|
|
14
15
|
* Split a read-tool path into its base path and trailing selector, mirroring the
|
|
15
16
|
* read tool's own splitter. Single source of the grammar in this package: the
|
|
@@ -31,25 +32,10 @@ export declare function stripReadSelector(path: string): string;
|
|
|
31
32
|
* than its plain lines: verbatim `raw` bytes or the merge `conflicts` view.
|
|
32
33
|
*/
|
|
33
34
|
export declare function isAlternateFormReadSelector(sel: string): boolean;
|
|
34
|
-
/**
|
|
35
|
-
* Whether `path` references a `scheme://` URL (internal URI or web URL) rather
|
|
36
|
-
* than a filesystem path that belongs in the compaction `<files>` summary.
|
|
37
|
-
*/
|
|
38
|
-
export declare function isUrlSchemePath(path: string): boolean;
|
|
39
35
|
/**
|
|
40
36
|
* Extract file operations from tool calls in an assistant message.
|
|
41
37
|
*/
|
|
42
|
-
export declare function extractFileOpsFromMessage(message: AgentMessage, fileOps: FileOperations): void;
|
|
43
|
-
/**
|
|
44
|
-
* Compute final file lists from file operations.
|
|
45
|
-
* Returns readFiles (files only read, not modified) and modifiedFiles.
|
|
46
|
-
*/
|
|
47
|
-
export declare function computeFileLists(fileOps: FileOperations): {
|
|
48
|
-
readFiles: string[];
|
|
49
|
-
modifiedFiles: string[];
|
|
50
|
-
};
|
|
51
|
-
export declare function formatFileOperations(readFiles: string[], modifiedFiles: string[], readSet?: ReadonlySet<string>): string;
|
|
52
|
-
export declare function upsertFileOperations(summary: string, readFiles: string[], modifiedFiles: string[], readSet?: ReadonlySet<string>): string;
|
|
38
|
+
export declare function extractFileOpsFromMessage(message: AgentMessage, fileOps: snapcompact.FileOperations): void;
|
|
53
39
|
/**
|
|
54
40
|
* Truncate tool results to the same representation used in summarization prompts.
|
|
55
41
|
*/
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { Context, Tool } from "@linxiraos/pi-ai";
|
|
2
2
|
/**
|
|
3
3
|
* Last wire definition this Agent sent for each tool name, so a provider that keeps
|
|
4
4
|
* withdrawn tools declared (Anthropic `tool_removal`) can re-declare them byte-identically.
|
|
@@ -9,9 +9,15 @@ export declare class SentToolDefinitions {
|
|
|
9
9
|
/** Remember the definitions a request is about to send. */
|
|
10
10
|
record(tools: readonly Tool[]): void;
|
|
11
11
|
/**
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
* skipped: the provider drops them from the declaration.
|
|
12
|
+
* A detached copy: an Agent that replays another's request history declares the same withdrawn tools. `keep`
|
|
13
|
+
* leaves out a definition the copy must never declare.
|
|
15
14
|
*/
|
|
16
|
-
|
|
15
|
+
copy(keep?: (name: string) => boolean): SentToolDefinitions;
|
|
16
|
+
/**
|
|
17
|
+
* `context` with {@link Context.inactiveTools} set to the definitions for names the latest
|
|
18
|
+
* `requestControls.tools.declared` in its messages holds that are not in its `tools`; cleared when
|
|
19
|
+
* there are none or the request declares no tools. Names never sent by this Agent are skipped: the
|
|
20
|
+
* provider drops them from the declaration.
|
|
21
|
+
*/
|
|
22
|
+
withInactiveTools(context: Context): Context;
|
|
17
23
|
}
|
|
@@ -10,6 +10,7 @@ type TokenizerModel = Pick<Model, "tokenizer"> & snapcompact.ShapeTarget & {
|
|
|
10
10
|
compat?: Model["compat"];
|
|
11
11
|
thinking?: Model["thinking"];
|
|
12
12
|
reasoning?: boolean;
|
|
13
|
+
requestModelId?: string;
|
|
13
14
|
};
|
|
14
15
|
/** Identity of the reader whose replayed reasoning a {@link Tokenizer} counts; equal keys count it alike. */
|
|
15
16
|
export declare function reasoningReplayKey(model: TokenizerModel | null | undefined): string;
|
|
@@ -24,13 +25,12 @@ export interface TokenizerOptions {
|
|
|
24
25
|
nativeHistoryReplay?: boolean;
|
|
25
26
|
}
|
|
26
27
|
/**
|
|
27
|
-
*
|
|
28
|
-
* when known, o200k_base otherwise
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
* undercounts).
|
|
28
|
+
* Every mode counts with the native tokenizer: the catalog-resolved family
|
|
29
|
+
* when known, o200k_base otherwise. They differ only in the fallback when the
|
|
30
|
+
* loaded addon does not recognize that encoding: `strict` and `upperbound`
|
|
31
|
+
* the raw byte length (never undercounts), `approximate` a bytes/4 guess.
|
|
32
|
+
* Tests (`NODE_ENV=test`) skip the native count outside `strict` and use that
|
|
33
|
+
* fallback.
|
|
34
34
|
*/
|
|
35
35
|
export type TokenCountMode = "strict" | "approximate" | "upperbound";
|
|
36
36
|
/** Options for {@link Tokenizer.countMessage} / {@link Tokenizer.countMessages}. */
|
|
@@ -69,8 +69,8 @@ export interface TokenBudgetCheck {
|
|
|
69
69
|
* when the model's encoding, image or thinking-replay pricing, replay
|
|
70
70
|
* identity or native-history replay state changes); one-shot flows construct
|
|
71
71
|
* their own for the model that will be billed. Known tokenizer families use
|
|
72
|
-
* exact native counts;
|
|
73
|
-
*
|
|
72
|
+
* exact native counts; other models are counted in o200k_base, which bills
|
|
73
|
+
* unknown readers closer than a bytes/4 guess.
|
|
74
74
|
*/
|
|
75
75
|
export declare class Tokenizer {
|
|
76
76
|
#private;
|
package/dist/types/types.d.ts
CHANGED
|
@@ -588,7 +588,8 @@ export interface ToolCallContext {
|
|
|
588
588
|
providerMetadata?: ToolCallProviderMetadata;
|
|
589
589
|
/**
|
|
590
590
|
* Cooperative steering signal: aborted when a queued user/steering message
|
|
591
|
-
* (or an interrupting peer IRC) is detected while this tool batch runs.
|
|
591
|
+
* (or an interrupting peer IRC) is detected while this tool batch runs. Its
|
|
592
|
+
* `reason` names the source: a {@link SteeringInterruptSource} or `"irc"`.
|
|
592
593
|
* Unlike the hard abort signal it NEVER kills the tool — long-running
|
|
593
594
|
* tools MAY observe it (via `ctx.toolCall.steeringSignal`) to finish early
|
|
594
595
|
* or background themselves so the message injects promptly; ignoring it is
|
|
@@ -967,7 +968,7 @@ export type ToolApprovalDecision = ToolTier | {
|
|
|
967
968
|
* prompt policies to the tool it dispatches into. */
|
|
968
969
|
policyKey?: string;
|
|
969
970
|
};
|
|
970
|
-
export type ToolApproval = ToolApprovalDecision | ((args: unknown) => ToolApprovalDecision);
|
|
971
|
+
export type ToolApproval = ToolApprovalDecision | ((args: unknown, context?: AgentToolContext) => ToolApprovalDecision);
|
|
971
972
|
/**
|
|
972
973
|
* Context passed to tool execution.
|
|
973
974
|
* Apps can extend via declaration merging.
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"type": "module",
|
|
3
3
|
"name": "@linxiraos/pi-agent-core",
|
|
4
|
-
"version": "1.4.
|
|
4
|
+
"version": "1.4.9",
|
|
5
5
|
"description": "General-purpose agent with transport abstraction, state management, and attachment support",
|
|
6
6
|
"homepage": "https://linxira-os.github.io/zeta/",
|
|
7
7
|
"author": "Linxira-OS",
|
|
@@ -35,16 +35,16 @@
|
|
|
35
35
|
"fmt": "oxfmt --no-error-on-unmatched-pattern 'src/**/*.{ts,tsx}' '{test,bench,examples,scripts}/**/*.ts' '*.ts'"
|
|
36
36
|
},
|
|
37
37
|
"dependencies": {
|
|
38
|
-
"@linxiraos/pi-ai": "1.4.
|
|
39
|
-
"@linxiraos/pi-catalog": "1.4.
|
|
40
|
-
"@linxiraos/pi-natives": "1.4.
|
|
41
|
-
"@linxiraos/pi-utils": "1.4.
|
|
42
|
-
"@linxiraos/pi-wire": "1.4.
|
|
43
|
-
"@linxiraos/pi-snapcompact": "1.4.
|
|
38
|
+
"@linxiraos/pi-ai": "1.4.9",
|
|
39
|
+
"@linxiraos/pi-catalog": "1.4.9",
|
|
40
|
+
"@linxiraos/pi-natives": "1.4.9",
|
|
41
|
+
"@linxiraos/pi-utils": "1.4.9",
|
|
42
|
+
"@linxiraos/pi-wire": "1.4.9",
|
|
43
|
+
"@linxiraos/pi-snapcompact": "1.4.9",
|
|
44
44
|
"@opentelemetry/api": "^1.9.1"
|
|
45
45
|
},
|
|
46
46
|
"devDependencies": {
|
|
47
|
-
"@linxiraos/pi-omptype": "1.4.
|
|
47
|
+
"@linxiraos/pi-omptype": "1.4.9",
|
|
48
48
|
"@opentelemetry/context-async-hooks": "^2.9.0",
|
|
49
49
|
"@opentelemetry/sdk-trace-base": "^2.9.0",
|
|
50
50
|
"@types/bun": "1.4.4"
|
package/src/agent-loop.ts
CHANGED
|
@@ -53,7 +53,7 @@ import {
|
|
|
53
53
|
signalListLabel,
|
|
54
54
|
} from "@linxiraos/pi-ai/utils/harmony-leak";
|
|
55
55
|
import { isDsmlLeakRecoveryTarget, removeDsmlToolMarkupLeak } from "@linxiraos/pi-ai/utils/dsml-leak";
|
|
56
|
-
import { cloneJsonTree, logger, sanitizeText, structuredCloneJSON } from "@linxiraos/pi-utils";
|
|
56
|
+
import { cloneJsonTree, logger, sanitizeText, structuredCloneJSON, toError } from "@linxiraos/pi-utils";
|
|
57
57
|
import { INTENT_FIELD } from "@linxiraos/pi-wire";
|
|
58
58
|
import { LiveSteeringChannel } from "./live-steering";
|
|
59
59
|
import { agentPauseGate } from "./pause";
|
|
@@ -1071,12 +1071,6 @@ function resolveIntentMode(intent: AgentTool["intent"]): "require" | "optional"
|
|
|
1071
1071
|
return "require";
|
|
1072
1072
|
}
|
|
1073
1073
|
|
|
1074
|
-
/**
|
|
1075
|
-
* Longest `i` value accepted as an intent; anything past this is a tool
|
|
1076
|
-
* payload the model put in the wrong field, not an intent.
|
|
1077
|
-
*/
|
|
1078
|
-
const MAX_INTENT_LENGTH = 200;
|
|
1079
|
-
|
|
1080
1074
|
function extractIntent(args: Record<string, unknown>): { intent?: string; strippedArgs: Record<string, unknown> } {
|
|
1081
1075
|
const { [INTENT_FIELD]: intent, ...strippedArgs } = args;
|
|
1082
1076
|
if (typeof intent !== "string") {
|
|
@@ -1194,7 +1188,7 @@ function resolveAsides(entries: AsideMessage[] | undefined): AgentMessage[] {
|
|
|
1194
1188
|
if (message) out.push(message);
|
|
1195
1189
|
}
|
|
1196
1190
|
} catch (error) {
|
|
1197
|
-
discardAsides(out,
|
|
1191
|
+
discardAsides(out, toError(error));
|
|
1198
1192
|
throw error;
|
|
1199
1193
|
}
|
|
1200
1194
|
return out;
|
|
@@ -1976,6 +1970,9 @@ async function prepareProviderCall(
|
|
|
1976
1970
|
}),
|
|
1977
1971
|
};
|
|
1978
1972
|
}
|
|
1973
|
+
// Before the transform too, so a request-size clamp in it measures the withdrawn definitions the provider
|
|
1974
|
+
// re-declares; recomputed below against what the transform returns.
|
|
1975
|
+
if (config.sentToolDefinitions) llmContext = config.sentToolDefinitions.withInactiveTools(llmContext);
|
|
1979
1976
|
if (config.transformProviderContext) {
|
|
1980
1977
|
llmContext = await config.transformProviderContext(llmContext, model);
|
|
1981
1978
|
}
|
|
@@ -1991,10 +1988,9 @@ async function prepareProviderCall(
|
|
|
1991
1988
|
};
|
|
1992
1989
|
}
|
|
1993
1990
|
// After `transformProviderContext`, so the recorded definitions are exactly what the provider receives.
|
|
1994
|
-
if (config.sentToolDefinitions
|
|
1995
|
-
config.sentToolDefinitions.record(llmContext.tools);
|
|
1996
|
-
|
|
1997
|
-
if (inactiveTools) llmContext = { ...llmContext, inactiveTools };
|
|
1991
|
+
if (config.sentToolDefinitions) {
|
|
1992
|
+
if (llmContext.tools) config.sentToolDefinitions.record(llmContext.tools);
|
|
1993
|
+
llmContext = config.sentToolDefinitions.withInactiveTools(llmContext);
|
|
1998
1994
|
}
|
|
1999
1995
|
return { model, context: llmContext, promptToolWireTools, ownedDialect };
|
|
2000
1996
|
}
|
|
@@ -3105,11 +3101,6 @@ async function prepareToolCallDispatch(
|
|
|
3105
3101
|
? { intent: undefined, strippedArgs: argsForExecution }
|
|
3106
3102
|
: extractIntent(toolCall.arguments);
|
|
3107
3103
|
argsForExecution = strippedArgs;
|
|
3108
|
-
if (intent !== undefined && intent.length > MAX_INTENT_LENGTH && tool) {
|
|
3109
|
-
entry.args = strippedArgs;
|
|
3110
|
-
entry.validationErrorMessage = `\`${INTENT_FIELD}\` is a short intent label (at most ${MAX_INTENT_LENGTH} chars); the value you sent is ${intent.length} chars. The tool was not run. Put that content in the tool's own parameters and retry with a brief \`${INTENT_FIELD}\`.`;
|
|
3111
|
-
continue;
|
|
3112
|
-
}
|
|
3113
3104
|
if (intent) {
|
|
3114
3105
|
toolCall.intent = intent;
|
|
3115
3106
|
} else if (typeof tool?.intent === "function") {
|
|
@@ -3411,7 +3402,7 @@ async function executeToolCalls(
|
|
|
3411
3402
|
// also cascades: the freshly detached job's own completion re-triggers
|
|
3412
3403
|
// this check for the next command, so millisecond-long commands chain
|
|
3413
3404
|
// into separate background deliveries (#12869).
|
|
3414
|
-
if (source === "irc" && softInterrupts) steeringSoftController.abort();
|
|
3405
|
+
if (source === "irc" && softInterrupts) steeringSoftController.abort("irc");
|
|
3415
3406
|
};
|
|
3416
3407
|
|
|
3417
3408
|
const checkSteering = async (): Promise<void> => {
|
|
@@ -3450,7 +3441,7 @@ async function executeToolCalls(
|
|
|
3450
3441
|
interruptState.triggered = true;
|
|
3451
3442
|
interruptState.source = steeringSource ?? "unknown";
|
|
3452
3443
|
steeringAbortController.abort(TOOL_INTERRUPT_ABORT_REASON);
|
|
3453
|
-
if (softInterrupts) steeringSoftController.abort();
|
|
3444
|
+
if (softInterrupts) steeringSoftController.abort(interruptState.source);
|
|
3454
3445
|
}
|
|
3455
3446
|
return;
|
|
3456
3447
|
}
|
package/src/agent.ts
CHANGED
|
@@ -176,6 +176,11 @@ export interface AgentOptions {
|
|
|
176
176
|
* Shared provider state map for session-scoped transport/session caches.
|
|
177
177
|
*/
|
|
178
178
|
providerSessionState?: Map<string, ProviderSessionState>;
|
|
179
|
+
/**
|
|
180
|
+
* Tool definitions already sent, for an Agent that replays another Agent's request history
|
|
181
|
+
* (see {@link Agent.copySentToolDefinitions}). Defaults to an empty store.
|
|
182
|
+
*/
|
|
183
|
+
sentToolDefinitions?: SentToolDefinitions;
|
|
179
184
|
|
|
180
185
|
/**
|
|
181
186
|
* Resolves an API key or resolver dynamically for each LLM call.
|
|
@@ -568,6 +573,7 @@ export class Agent {
|
|
|
568
573
|
this.#deadline = opts.deadline;
|
|
569
574
|
this.#promptCacheKey = opts.promptCacheKey;
|
|
570
575
|
this.#providerSessionState = opts.providerSessionState;
|
|
576
|
+
if (opts.sentToolDefinitions) this.#sentToolDefinitions = opts.sentToolDefinitions;
|
|
571
577
|
this.#thinkingBudgets = opts.thinkingBudgets;
|
|
572
578
|
this.#temperature = opts.temperature;
|
|
573
579
|
this.#topP = opts.topP;
|
|
@@ -642,6 +648,14 @@ export class Agent {
|
|
|
642
648
|
this.#promptCacheKey = value;
|
|
643
649
|
}
|
|
644
650
|
|
|
651
|
+
/**
|
|
652
|
+
* A detached copy of the tool definitions this agent has sent (`AgentOptions.sentToolDefinitions`), without the
|
|
653
|
+
* names `keep` rejects.
|
|
654
|
+
*/
|
|
655
|
+
copySentToolDefinitions(keep?: (name: string) => boolean): SentToolDefinitions {
|
|
656
|
+
return this.#sentToolDefinitions.copy(keep);
|
|
657
|
+
}
|
|
658
|
+
|
|
645
659
|
/**
|
|
646
660
|
* Fields added to every log record written while this agent runs (the
|
|
647
661
|
* owning session's `sessionId`), so in-process agents' records stay apart.
|
|
@@ -959,12 +973,11 @@ export class Agent {
|
|
|
959
973
|
pruneDescriptions: this.#pruneToolDescriptions,
|
|
960
974
|
}) ?? []);
|
|
961
975
|
let context: Context = { systemPrompt, messages, tools };
|
|
976
|
+
// Side requests reuse the main loop's sent definitions without recording their own; attached before the
|
|
977
|
+
// transform too, so a request-size clamp in it measures them.
|
|
978
|
+
context = this.#sentToolDefinitions.withInactiveTools(context);
|
|
962
979
|
if (this.#transformProviderContext) context = await this.#transformProviderContext(context, model);
|
|
963
|
-
|
|
964
|
-
if (context.tools?.length) {
|
|
965
|
-
const inactiveTools = this.#sentToolDefinitions.inactiveFor(context.messages, context.tools);
|
|
966
|
-
if (inactiveTools) context = { ...context, inactiveTools };
|
|
967
|
-
}
|
|
980
|
+
context = this.#sentToolDefinitions.withInactiveTools(context);
|
|
968
981
|
return context;
|
|
969
982
|
}
|
|
970
983
|
|
|
@@ -24,15 +24,12 @@ import {
|
|
|
24
24
|
import branchSummaryPrompt from "./prompts/branch-summary.md" with { type: "text" };
|
|
25
25
|
import branchSummaryPreamble from "./prompts/branch-summary-preamble.md" with { type: "text" };
|
|
26
26
|
import {
|
|
27
|
-
computeFileLists,
|
|
28
|
-
createFileOps,
|
|
29
27
|
extractFileOpsFromMessage,
|
|
30
|
-
|
|
28
|
+
incompleteOutputError,
|
|
31
29
|
SUMMARIZATION_SYSTEM_PROMPT,
|
|
32
30
|
serializeConversationForSummary,
|
|
33
31
|
stripReadSelector,
|
|
34
32
|
truncateToolResultForSummary,
|
|
35
|
-
upsertFileOperations,
|
|
36
33
|
} from "./utils";
|
|
37
34
|
|
|
38
35
|
// ============================================================================
|
|
@@ -53,13 +50,11 @@ export interface BranchSummaryDetails {
|
|
|
53
50
|
modifiedFiles: string[];
|
|
54
51
|
}
|
|
55
52
|
|
|
56
|
-
export type { FileOperations } from "./utils";
|
|
57
|
-
|
|
58
53
|
export interface BranchPreparation {
|
|
59
54
|
/** Messages extracted for summarization, in chronological order */
|
|
60
55
|
messages: AgentMessage[];
|
|
61
56
|
/** File operations extracted from tool calls */
|
|
62
|
-
fileOps: FileOperations;
|
|
57
|
+
fileOps: snapcompact.FileOperations;
|
|
63
58
|
/** Total estimated tokens in messages */
|
|
64
59
|
totalTokens: number;
|
|
65
60
|
}
|
|
@@ -251,7 +246,7 @@ export function prepareBranchEntries(
|
|
|
251
246
|
tokenBudget: number = 0,
|
|
252
247
|
): BranchPreparation {
|
|
253
248
|
const messages: AgentMessage[] = [];
|
|
254
|
-
const fileOps = createFileOps();
|
|
249
|
+
const fileOps = snapcompact.createFileOps();
|
|
255
250
|
let totalTokens = 0;
|
|
256
251
|
|
|
257
252
|
// First pass: collect file ops from ALL entries (even if they don't fit in token budget)
|
|
@@ -386,6 +381,9 @@ export async function generateBranchSummary(
|
|
|
386
381
|
if (response.stopReason === "error") {
|
|
387
382
|
return { error: response.errorMessage || "Summarization failed" };
|
|
388
383
|
}
|
|
384
|
+
if (response.stopReason === "length") {
|
|
385
|
+
return { error: incompleteOutputError("Summarization failed") };
|
|
386
|
+
}
|
|
389
387
|
|
|
390
388
|
let summary = response.content
|
|
391
389
|
.filter((c): c is { type: "text"; text: string } => c.type === "text")
|
|
@@ -396,8 +394,8 @@ export async function generateBranchSummary(
|
|
|
396
394
|
summary = BRANCH_SUMMARY_PREAMBLE + summary;
|
|
397
395
|
|
|
398
396
|
// Compute file lists and append to summary
|
|
399
|
-
const { readFiles, modifiedFiles } = computeFileLists(fileOps);
|
|
400
|
-
summary = upsertFileOperations(summary, readFiles, modifiedFiles, fileOps.read);
|
|
397
|
+
const { readFiles, modifiedFiles } = snapcompact.computeFileLists(fileOps);
|
|
398
|
+
summary = snapcompact.upsertFileOperations(summary, readFiles, modifiedFiles, fileOps.read);
|
|
401
399
|
|
|
402
400
|
return {
|
|
403
401
|
summary: summary || "No summary generated",
|
|
@@ -32,7 +32,7 @@ import {
|
|
|
32
32
|
OPENAI_HEADER_VALUES,
|
|
33
33
|
OPENAI_HEADERS,
|
|
34
34
|
} from "@linxiraos/pi-catalog/wire/codex";
|
|
35
|
-
import { $env, isUnexpectedSocketCloseMessage, logger, ptree, stringifyJson } from "@linxiraos/pi-utils";
|
|
35
|
+
import { $env, isUnexpectedSocketCloseMessage, logger, ptree, stringifyJson, toError } from "@linxiraos/pi-utils";
|
|
36
36
|
import { appendAzureApiVersion, resolveAzureOpenAiBaseUrl } from "./azure-openai-endpoint";
|
|
37
37
|
import { prepareBedrockCompactionRequest } from "./bedrock";
|
|
38
38
|
|
|
@@ -274,6 +274,7 @@ export async function requestCompactionV2Streaming(
|
|
|
274
274
|
providerSessionState?: Map<string, ProviderSessionState>;
|
|
275
275
|
codexCompaction?: CodexCompactionContext;
|
|
276
276
|
preferWebsockets?: boolean;
|
|
277
|
+
codexAccessPrograms?: boolean;
|
|
277
278
|
},
|
|
278
279
|
): Promise<CompactionV2Response> {
|
|
279
280
|
let fetchImpl: FetchImpl = options?.fetch ?? globalThis.fetch;
|
|
@@ -316,9 +317,10 @@ export async function requestCompactionV2Streaming(
|
|
|
316
317
|
providerSessionState: options?.providerSessionState,
|
|
317
318
|
codexCompaction: options?.codexCompaction,
|
|
318
319
|
preferWebsockets: options?.preferWebsockets,
|
|
320
|
+
codexAccessPrograms: options?.codexAccessPrograms,
|
|
319
321
|
});
|
|
320
322
|
} catch (err) {
|
|
321
|
-
const error =
|
|
323
|
+
const error = toError(err);
|
|
322
324
|
if (signal?.aborted) throw error;
|
|
323
325
|
|
|
324
326
|
if (isRetryableCompactionError(error) && attempt < V2_COMPACTION_MAX_RETRIES) {
|
|
@@ -352,6 +354,7 @@ async function attemptCompactionV2Streaming(
|
|
|
352
354
|
providerSessionState?: Map<string, ProviderSessionState>;
|
|
353
355
|
codexCompaction?: CodexCompactionContext;
|
|
354
356
|
preferWebsockets?: boolean;
|
|
357
|
+
codexAccessPrograms?: boolean;
|
|
355
358
|
},
|
|
356
359
|
): Promise<CompactionV2Response> {
|
|
357
360
|
// Faithful to Codex: append the compaction trigger as the final input item
|
|
@@ -377,6 +380,7 @@ async function attemptCompactionV2Streaming(
|
|
|
377
380
|
sessionId: request.sessionId,
|
|
378
381
|
providerSessionState: options.providerSessionState,
|
|
379
382
|
preferWebsockets: options.preferWebsockets,
|
|
383
|
+
codexAccessPrograms: options.codexAccessPrograms,
|
|
380
384
|
responsesLite: model.useResponsesLite,
|
|
381
385
|
codexCompaction: createOpenAICodexCompactionRequestContext({
|
|
382
386
|
context: options.codexCompaction,
|
|
@@ -86,15 +86,12 @@ import handoffDocumentPrompt from "./prompts/handoff-document.md" with { type: "
|
|
|
86
86
|
import snapcompactArchiveContextPrompt from "./prompts/snapcompact-archive-context.md" with { type: "text" };
|
|
87
87
|
|
|
88
88
|
import {
|
|
89
|
-
computeFileLists,
|
|
90
|
-
createFileOps,
|
|
91
89
|
escapeSummaryBoundaryTags,
|
|
92
90
|
extractFileOpsFromMessage,
|
|
93
|
-
|
|
91
|
+
incompleteOutputError,
|
|
94
92
|
SUMMARIZATION_SYSTEM_PROMPT,
|
|
95
93
|
serializeConversationForSummary,
|
|
96
94
|
stripReadSelector,
|
|
97
|
-
upsertFileOperations,
|
|
98
95
|
} from "./utils";
|
|
99
96
|
|
|
100
97
|
// ============================================================================
|
|
@@ -114,8 +111,8 @@ function extractFileOperations(
|
|
|
114
111
|
messages: AgentMessage[],
|
|
115
112
|
entries: SessionEntry[],
|
|
116
113
|
prevCompactionIndex: number,
|
|
117
|
-
): FileOperations {
|
|
118
|
-
const fileOps = createFileOps();
|
|
114
|
+
): snapcompact.FileOperations {
|
|
115
|
+
const fileOps = snapcompact.createFileOps();
|
|
119
116
|
|
|
120
117
|
// Collect from previous compaction's details (if pi-generated)
|
|
121
118
|
if (prevCompactionIndex >= 0) {
|
|
@@ -750,6 +747,8 @@ export interface SummaryOptions {
|
|
|
750
747
|
providerSessionState?: Map<string, ProviderSessionState>;
|
|
751
748
|
/** Whether Codex remote compaction should prefer the provider WebSocket transport. */
|
|
752
749
|
preferWebsockets?: boolean;
|
|
750
|
+
/** Daybreak Blue request on Codex remote compaction; see `StreamOptions.codexAccessPrograms`. */
|
|
751
|
+
codexAccessPrograms?: boolean;
|
|
753
752
|
/** Classification shared by every provider request in this logical compaction. */
|
|
754
753
|
codexCompaction?: CodexCompactionContext;
|
|
755
754
|
/** Provider-visible tools for remote compaction transports that replay native tool history. */
|
|
@@ -1073,6 +1072,9 @@ async function summarizeConversationWindow(
|
|
|
1073
1072
|
if (response.stopReason === "error") {
|
|
1074
1073
|
throw createSummarizationError("Summarization failed", response);
|
|
1075
1074
|
}
|
|
1075
|
+
if (response.stopReason === "length") {
|
|
1076
|
+
throw new Error(incompleteOutputError("Summarization failed"));
|
|
1077
|
+
}
|
|
1076
1078
|
|
|
1077
1079
|
const textContent = response.content
|
|
1078
1080
|
.filter((c): c is { type: "text"; text: string } => c.type === "text")
|
|
@@ -1180,6 +1182,9 @@ export async function generateHandoffFromContext(
|
|
|
1180
1182
|
if (response.stopReason === "error") {
|
|
1181
1183
|
throw createSummarizationError("Handoff generation failed", response);
|
|
1182
1184
|
}
|
|
1185
|
+
if (response.stopReason === "length") {
|
|
1186
|
+
throw new Error(incompleteOutputError("Handoff generation failed"));
|
|
1187
|
+
}
|
|
1183
1188
|
|
|
1184
1189
|
return response.content
|
|
1185
1190
|
.filter((c): c is { type: "text"; text: string } => c.type === "text")
|
|
@@ -1303,8 +1308,10 @@ async function generateShortSummary(
|
|
|
1303
1308
|
case "error":
|
|
1304
1309
|
outcome = { kind: "failed", error: response.errorMessage || "Unknown error" };
|
|
1305
1310
|
break;
|
|
1306
|
-
case "stop":
|
|
1307
1311
|
case "length":
|
|
1312
|
+
outcome = { kind: "failed", error: incompleteOutputError("Short summary failed") };
|
|
1313
|
+
break;
|
|
1314
|
+
case "stop":
|
|
1308
1315
|
case "toolUse":
|
|
1309
1316
|
outcome = {
|
|
1310
1317
|
kind: "text",
|
|
@@ -1373,7 +1380,7 @@ export interface CompactionPreparation {
|
|
|
1373
1380
|
/** Preserved opaque compaction payload from the previous compaction, if any. */
|
|
1374
1381
|
previousPreserveData?: Record<string, unknown>;
|
|
1375
1382
|
/** File operations extracted from messagesToSummarize */
|
|
1376
|
-
fileOps: FileOperations;
|
|
1383
|
+
fileOps: snapcompact.FileOperations;
|
|
1377
1384
|
/** Compaction settions from settings.jsonl */
|
|
1378
1385
|
settings: CompactionSettings;
|
|
1379
1386
|
}
|
|
@@ -1765,6 +1772,7 @@ export async function compact(
|
|
|
1765
1772
|
: options?.promptCacheKey,
|
|
1766
1773
|
providerSessionState: options?.providerSessionState,
|
|
1767
1774
|
preferWebsockets: options?.preferWebsockets,
|
|
1775
|
+
codexAccessPrograms: options?.codexAccessPrograms,
|
|
1768
1776
|
codexCompaction: options?.codexCompaction,
|
|
1769
1777
|
tools: options?.tools,
|
|
1770
1778
|
fetch: options?.fetch,
|
|
@@ -2000,6 +2008,7 @@ export async function compact(
|
|
|
2000
2008
|
fetch: summaryOptions.fetch,
|
|
2001
2009
|
providerSessionState: summaryOptions.providerSessionState,
|
|
2002
2010
|
preferWebsockets: summaryOptions.preferWebsockets,
|
|
2011
|
+
codexAccessPrograms: summaryOptions.codexAccessPrograms,
|
|
2003
2012
|
codexCompaction: summaryOptions.codexCompaction,
|
|
2004
2013
|
}),
|
|
2005
2014
|
{ signal },
|
|
@@ -2330,8 +2339,8 @@ export async function compact(
|
|
|
2330
2339
|
});
|
|
2331
2340
|
|
|
2332
2341
|
// Compute file lists and append to summary
|
|
2333
|
-
const { readFiles, modifiedFiles } = computeFileLists(fileOps);
|
|
2334
|
-
summary = upsertFileOperations(summary, readFiles, modifiedFiles, fileOps.read);
|
|
2342
|
+
const { readFiles, modifiedFiles } = snapcompact.computeFileLists(fileOps);
|
|
2343
|
+
summary = snapcompact.upsertFileOperations(summary, readFiles, modifiedFiles, fileOps.read);
|
|
2335
2344
|
if (nativeSummary !== undefined) {
|
|
2336
2345
|
// The replayed block (summary and any `tool_changes`) stays
|
|
2337
2346
|
// byte-identical to the API's output so it matches its signature. The
|
|
@@ -2339,7 +2348,7 @@ export async function compact(
|
|
|
2339
2348
|
// summary message with the block and skips its text, so they would
|
|
2340
2349
|
// otherwise be invisible to this provider. Every other provider keeps
|
|
2341
2350
|
// reading the entry text.
|
|
2342
|
-
const filesText = upsertFileOperations("", readFiles, modifiedFiles, fileOps.read) || undefined;
|
|
2351
|
+
const filesText = snapcompact.upsertFileOperations("", readFiles, modifiedFiles, fileOps.read) || undefined;
|
|
2343
2352
|
preserveData = withAnthropicCompactionPreserveData(preserveData, {
|
|
2344
2353
|
provider: model.provider,
|
|
2345
2354
|
content: nativeSummary,
|
|
@@ -2431,6 +2440,9 @@ async function generateTurnPrefixSummary(
|
|
|
2431
2440
|
if (response.stopReason === "error") {
|
|
2432
2441
|
throw createSummarizationError("Turn prefix summarization failed", response);
|
|
2433
2442
|
}
|
|
2443
|
+
if (response.stopReason === "length") {
|
|
2444
|
+
throw new Error(incompleteOutputError("Turn prefix summarization failed"));
|
|
2445
|
+
}
|
|
2434
2446
|
|
|
2435
2447
|
return response.content
|
|
2436
2448
|
.filter((c): c is { type: "text"; text: string } => c.type === "text")
|
package/src/compaction/openai.ts
CHANGED
|
@@ -45,6 +45,7 @@ import {
|
|
|
45
45
|
getOpenAIResponsesHistoryItems,
|
|
46
46
|
getOpenAIResponsesHistoryPayload,
|
|
47
47
|
normalizeResponsesToolCallId,
|
|
48
|
+
stripOpenAIResponsesInternalMetadataForReplay,
|
|
48
49
|
stripOpenAIResponsesOutputOnlyStatusesForReplay,
|
|
49
50
|
truncateResponseItemId,
|
|
50
51
|
} from "@linxiraos/pi-ai/utils";
|
|
@@ -846,6 +847,9 @@ export function buildOpenAiNativeHistory(
|
|
|
846
847
|
msgIndex++;
|
|
847
848
|
}
|
|
848
849
|
|
|
850
|
+
for (let index = 0; index < input.length; index++) {
|
|
851
|
+
input[index] = stripOpenAIResponsesInternalMetadataForReplay(input[index]!);
|
|
852
|
+
}
|
|
849
853
|
return stripOpenAIResponsesOutputOnlyStatusesForReplay(hoistInterleavedResponsesToolBatchMessages(input));
|
|
850
854
|
}
|
|
851
855
|
|
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
|
// ============================================================================
|
|
@@ -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/tokenizer.ts
CHANGED
|
@@ -1,9 +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";
|
|
4
5
|
import { completionsDropsOwnThinking, isLiteLLMThinkingSignature } from "@linxiraos/pi-ai/providers/openai-completions";
|
|
5
6
|
import { isColdReplayableResponsesTurn } from "@linxiraos/pi-ai/providers/openai-shared";
|
|
6
7
|
import {
|
|
8
|
+
dropsForeignReasoningPayload,
|
|
7
9
|
isSameModelTurn,
|
|
8
10
|
shouldDropTruncatedThinkingOnlyAssistant,
|
|
9
11
|
} from "@linxiraos/pi-ai/providers/transform-messages";
|
|
@@ -22,7 +24,6 @@ import { base64ImageSize, estimateImageTokens, type ImageDetail, type ImageSize
|
|
|
22
24
|
import type { AgentMessage } from "./types";
|
|
23
25
|
|
|
24
26
|
const testEnv = Bun.env.NODE_ENV === "test";
|
|
25
|
-
const accurate = process.env.PI_TOKENIZER_ACCURATE === "1" && !testEnv;
|
|
26
27
|
|
|
27
28
|
const NATIVE_ENCODING: Record<ModelTokenizer, natives.Encoding> = {
|
|
28
29
|
"claude-v3": natives.Encoding.ClaudeV3,
|
|
@@ -33,6 +34,7 @@ const NATIVE_ENCODING: Record<ModelTokenizer, natives.Encoding> = {
|
|
|
33
34
|
"deepseek-v3": natives.Encoding.DeepSeekV3,
|
|
34
35
|
"kimi-k2": natives.Encoding.KimiK2,
|
|
35
36
|
glm5: natives.Encoding.Glm5,
|
|
37
|
+
cl100k: natives.Encoding.Cl100kBase,
|
|
36
38
|
o200k: natives.Encoding.O200kBase,
|
|
37
39
|
};
|
|
38
40
|
|
|
@@ -42,7 +44,12 @@ export function tokenizerEncodingForModel(model: Pick<Model, "tokenizer"> | null
|
|
|
42
44
|
}
|
|
43
45
|
|
|
44
46
|
type TokenizerModel = Pick<Model, "tokenizer"> &
|
|
45
|
-
snapcompact.ShapeTarget & {
|
|
47
|
+
snapcompact.ShapeTarget & {
|
|
48
|
+
compat?: Model["compat"];
|
|
49
|
+
thinking?: Model["thinking"];
|
|
50
|
+
reasoning?: boolean;
|
|
51
|
+
requestModelId?: string;
|
|
52
|
+
};
|
|
46
53
|
|
|
47
54
|
/** The model an assistant turn's native reasoning (signed thinking, Responses history) is replayed to. */
|
|
48
55
|
interface ReasoningReplayReader {
|
|
@@ -77,13 +84,12 @@ export interface TokenizerOptions {
|
|
|
77
84
|
}
|
|
78
85
|
|
|
79
86
|
/**
|
|
80
|
-
*
|
|
81
|
-
* when known, o200k_base otherwise
|
|
82
|
-
*
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
*
|
|
86
|
-
* 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.
|
|
87
93
|
*/
|
|
88
94
|
export type TokenCountMode = "strict" | "approximate" | "upperbound";
|
|
89
95
|
|
|
@@ -205,8 +211,8 @@ interface MessageEstimate {
|
|
|
205
211
|
* when the model's encoding, image or thinking-replay pricing, replay
|
|
206
212
|
* identity or native-history replay state changes); one-shot flows construct
|
|
207
213
|
* their own for the model that will be billed. Known tokenizer families use
|
|
208
|
-
* exact native counts;
|
|
209
|
-
*
|
|
214
|
+
* exact native counts; other models are counted in o200k_base, which bills
|
|
215
|
+
* unknown readers closer than a bytes/4 guess.
|
|
210
216
|
*/
|
|
211
217
|
export class Tokenizer {
|
|
212
218
|
readonly #encoding: natives.Encoding | null;
|
|
@@ -217,6 +223,8 @@ export class Tokenizer {
|
|
|
217
223
|
readonly #dropsCompletionsThinking: boolean;
|
|
218
224
|
/** Claude's own API and prefix-bound hosts keep another model's signature from their deployment. */
|
|
219
225
|
readonly #readsDeploymentSignatures: boolean;
|
|
226
|
+
/** Factory's Gemini generate wire, whose replay pass keeps only Google-origin reasoning. */
|
|
227
|
+
readonly #factoryGeminiWire: boolean;
|
|
220
228
|
readonly reasoningReplayKey: string;
|
|
221
229
|
/** How the reader bills replayed signed thinking (catalog `thinking-replay-tokens`). */
|
|
222
230
|
readonly thinkingReplayTokens: ThinkingReplayTokens;
|
|
@@ -259,6 +267,10 @@ export class Tokenizer {
|
|
|
259
267
|
model?.api === "anthropic-messages" &&
|
|
260
268
|
((compat !== undefined && "officialEndpoint" in compat && compat.officialEndpoint) ||
|
|
261
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 });
|
|
262
274
|
this.reasoningReplayKey = reasoningReplayKey(model);
|
|
263
275
|
this.thinkingReplayTokens = resolveThinkingReplayTokens(model ?? {});
|
|
264
276
|
this.nativeHistoryReplay = options?.nativeHistoryReplay ?? true;
|
|
@@ -269,11 +281,8 @@ export class Tokenizer {
|
|
|
269
281
|
}
|
|
270
282
|
|
|
271
283
|
countTokens(text: string | string[], mode: TokenCountMode = "approximate"): number {
|
|
272
|
-
if (mode
|
|
273
|
-
|
|
274
|
-
return countTokensNat(text, this.#encoding, mode, this.#nativeCounts).tokens;
|
|
275
|
-
if (accurate) return countTokensNat(text, undefined, mode, this.#nativeCounts).tokens;
|
|
276
|
-
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;
|
|
277
286
|
}
|
|
278
287
|
|
|
279
288
|
/**
|
|
@@ -365,6 +374,21 @@ export class Tokenizer {
|
|
|
365
374
|
);
|
|
366
375
|
}
|
|
367
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
|
+
|
|
368
392
|
/**
|
|
369
393
|
* The replayed native Responses reasoning {@link countMessage} charges
|
|
370
394
|
* across `messages`: the part of a count that changes with the reading
|
|
@@ -468,15 +492,17 @@ export class Tokenizer {
|
|
|
468
492
|
fragments.push(block.thinking);
|
|
469
493
|
// Providers charge for the opaque signature/reasoning payload that
|
|
470
494
|
// rides alongside the thinking text (OpenAI Responses encrypted
|
|
471
|
-
// reasoning items, Gemini thought signatures)
|
|
472
|
-
// `
|
|
473
|
-
//
|
|
474
|
-
//
|
|
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).
|
|
475
500
|
if (
|
|
476
501
|
block.thinkingSignature &&
|
|
477
502
|
!excludeEncryptedReasoning &&
|
|
478
503
|
signaturesPriced &&
|
|
479
|
-
typeof replayedReasoning !== "number"
|
|
504
|
+
typeof replayedReasoning !== "number" &&
|
|
505
|
+
this.#receivesReasoningPayload(message)
|
|
480
506
|
) {
|
|
481
507
|
fragments.push(block.thinkingSignature);
|
|
482
508
|
}
|
|
@@ -485,10 +511,13 @@ export class Tokenizer {
|
|
|
485
511
|
fragments.push(block.name);
|
|
486
512
|
fragments.push(stringifyJson(block.arguments) ?? "null");
|
|
487
513
|
} else if (block.type === "redactedThinking") {
|
|
488
|
-
// Encrypted reasoning blob the provider still bills for
|
|
489
|
-
// 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.
|
|
490
517
|
signedReasoning = true;
|
|
491
|
-
if (!excludeEncryptedReasoning && signaturesPriced
|
|
518
|
+
if (!excludeEncryptedReasoning && signaturesPriced && this.#receivesReasoningPayload(message)) {
|
|
519
|
+
fragments.push(block.data);
|
|
520
|
+
}
|
|
492
521
|
} else if (block.type === "anthropicServerTool") {
|
|
493
522
|
// Native Anthropic server-tool call/result replayed verbatim on the
|
|
494
523
|
// wire (server_tool_use input and opaque result content). The provider
|
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.
|