@oh-my-pi/pi-agent-core 19.2.1 → 19.3.0
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 +22 -0
- package/dist/types/agent-loop.d.ts +3 -0
- package/dist/types/agent.d.ts +13 -1
- package/dist/types/append-only-context.d.ts +3 -0
- package/dist/types/compaction/compaction.d.ts +19 -2
- package/dist/types/compaction/messages.d.ts +2 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/inherited-tool-descriptions.d.ts +23 -0
- package/dist/types/types.d.ts +16 -2
- package/package.json +12 -12
- package/src/agent-loop.ts +36 -4
- package/src/agent.ts +35 -5
- package/src/append-only-context.ts +9 -1
- package/src/compaction/compaction.ts +125 -99
- package/src/compaction/messages.ts +2 -0
- package/src/compaction/shake.ts +3 -1
- package/src/index.ts +2 -0
- package/src/inherited-tool-descriptions.ts +43 -0
- package/src/telemetry.ts +6 -5
- package/src/tokenizer.ts +69 -19
- package/src/types.ts +20 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,28 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [19.3.0] - 2026-11-28
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- Added `Agent.inheritToolDescriptions()` and `Agent.normalizedTools()` so forked agents can reuse their parent’s prompt cache when tool descriptions differ only in wording.
|
|
10
|
+
- Added `CompactionSettings.summaryMaxTokens` to control the output token budget for regular compaction summaries. Compaction preserves history that fits alongside the previous summary and the requested output budget ([#18688](https://github.com/can1357/oh-my-pi/issues/18688)).
|
|
11
|
+
|
|
12
|
+
### Changed
|
|
13
|
+
|
|
14
|
+
- Capped the default reserve-based compaction threshold at 690,000 tokens for large context windows. Explicit percentage and fixed thresholds, as well as `baseWindowTokens` overrides, remain uncapped.
|
|
15
|
+
|
|
16
|
+
### Fixed
|
|
17
|
+
|
|
18
|
+
- Turn-end hooks can now identify calls that did not name a tool through `AgentTurnEndContext.unresolvedToolCallIds` ([#10876](https://github.com/can1357/oh-my-pi/issues/10876)).
|
|
19
|
+
- `generateHandoffFromContext` now sets an output limit so handoffs cannot stream indefinitely on servers without their own limit. Handoffs that reach the limit without finishing report an incomplete-output error ([#18031](https://github.com/can1357/oh-my-pi/issues/18031)).
|
|
20
|
+
- Reduced authentication-gateway request sizes by excluding internal host state from tool definitions.
|
|
21
|
+
- OpenTelemetry chat spans now report the model that actually served the response.
|
|
22
|
+
- Fixed shake recovery increasing context size by replacing tool results that were smaller than the replacement text ([#7204](https://github.com/can1357/oh-my-pi/issues/7204)).
|
|
23
|
+
- Fixed context token counts used by the status line and compaction to include `$` Python output, `@file` mentions, and terminal images from `!` commands, while excluding `!!` output that is not sent to the model ([#20834](https://github.com/can1357/oh-my-pi/pull/20834) by [@sjawhar](https://github.com/sjawhar)).
|
|
24
|
+
- Fixed token counting failing on stored custom messages whose content is neither text nor content blocks ([#20834](https://github.com/can1357/oh-my-pi/pull/20834) by [@sjawhar](https://github.com/sjawhar)).
|
|
25
|
+
- Compaction now stops in-flight summary requests and avoids sending new ones after cancellation or failure, including during split-turn compaction ([#20713](https://github.com/can1357/oh-my-pi/pull/20713) by [@sjawhar](https://github.com/sjawhar), [#20887](https://github.com/can1357/oh-my-pi/pull/20887) by [@sjawhar](https://github.com/sjawhar)).
|
|
26
|
+
|
|
5
27
|
## [19.2.1] - 2026-11-25
|
|
6
28
|
|
|
7
29
|
### Added
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
import { type AssistantMessage, type Context, EventStream, type ToolResultMessage } from "@oh-my-pi/pi-ai";
|
|
6
6
|
import { type Dialect } from "@oh-my-pi/pi-ai/dialect";
|
|
7
7
|
import { type AgentRunCoverage, type AgentRunSummary } from "./run-collector.js";
|
|
8
|
+
import type { InheritedToolDescriptions } from "./inherited-tool-descriptions.js";
|
|
8
9
|
import type { AgentContext, AgentEvent, AgentLoopConfig, AgentMessage, AgentTool, SteeringQueueState, StreamFn } from "./types.js";
|
|
9
10
|
/**
|
|
10
11
|
* A tool's batch concurrency for one call: an unset mode is shared, and a
|
|
@@ -129,6 +130,8 @@ export interface NormalizeToolsOptions {
|
|
|
129
130
|
intentDescription?: string;
|
|
130
131
|
/** Strip descriptions from the wire specs when the catalog rides in the system prompt. */
|
|
131
132
|
pruneDescriptions?: boolean;
|
|
133
|
+
/** A fork's owner-worded descriptions; see {@link InheritedToolDescriptions}. */
|
|
134
|
+
inheritedDescriptions?: InheritedToolDescriptions;
|
|
132
135
|
}
|
|
133
136
|
export declare function normalizeTools(tools: AgentContext["tools"], options: NormalizeToolsOptions): Context["tools"];
|
|
134
137
|
/** Split a traced call's intent (`i`, trimmed, trailing periods dropped) from the arguments its tool reads. */
|
package/dist/types/agent.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type ApiKey, type AssistantMessage, type AssistantMessageEvent, type Context, type CursorExecHandlers, type CursorToolResultHandler, type Effort, type ImageContent, type Message, type Model, type ProviderSessionState, type ServiceTier, type SimpleStreamOptions, type ThinkingBudgets, type ToolChoice, type ToolResultMessage } from "@oh-my-pi/pi-ai";
|
|
1
|
+
import { type ApiKey, type AssistantMessage, type AssistantMessageEvent, type Context, type CursorExecHandlers, type CursorToolResultHandler, type Effort, type ImageContent, type Message, type Model, type ProviderSessionState, type ServiceTier, type SimpleStreamOptions, type ThinkingBudgets, type Tool, type ToolChoice, type ToolResultMessage } from "@oh-my-pi/pi-ai";
|
|
2
2
|
import type { Dialect } from "@oh-my-pi/pi-ai/dialect";
|
|
3
3
|
import type { HarmonyAuditEvent } from "@oh-my-pi/pi-ai/utils/harmony-leak";
|
|
4
4
|
import type { AppendOnlyContextManager } from "./append-only-context.js";
|
|
@@ -315,6 +315,18 @@ export declare class Agent {
|
|
|
315
315
|
* names `keep` rejects.
|
|
316
316
|
*/
|
|
317
317
|
copySentToolDefinitions(keep?: (name: string) => boolean): SentToolDefinitions;
|
|
318
|
+
/**
|
|
319
|
+
* Provider-bound specs of the tools the next request to the active model declares, before the
|
|
320
|
+
* provider-context transform; empty without a model or under an owned dialect. A fork passes
|
|
321
|
+
* its owner's to {@link inheritToolDescriptions}.
|
|
322
|
+
*/
|
|
323
|
+
normalizedTools(): Tool[];
|
|
324
|
+
/**
|
|
325
|
+
* Send `owner`'s wording for every current tool that differs from it only in description, so
|
|
326
|
+
* this fork's requests open with the owner's cached prefix. Call once the fork's tool set is
|
|
327
|
+
* final; see {@link InheritedToolDescriptions}.
|
|
328
|
+
*/
|
|
329
|
+
inheritToolDescriptions(owner: readonly Tool[]): void;
|
|
318
330
|
/**
|
|
319
331
|
* Fields added to every log record written while this agent runs (the
|
|
320
332
|
* owning session's `sessionId`), so in-process agents' records stay apart.
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
* message delta is a cache miss each turn.
|
|
15
15
|
*/
|
|
16
16
|
import type { Context, Message, Tool } from "@oh-my-pi/pi-ai";
|
|
17
|
+
import type { InheritedToolDescriptions } from "./inherited-tool-descriptions.js";
|
|
17
18
|
import type { AgentContext } from "./types.js";
|
|
18
19
|
/** Frozen system prompt + tool spec snapshot. */
|
|
19
20
|
export interface StablePrefixSnapshot {
|
|
@@ -29,6 +30,8 @@ export interface BuildOptions {
|
|
|
29
30
|
intentDescription?: string;
|
|
30
31
|
/** Strip tool descriptions from the provider-bound specs (must match normalizeTools). */
|
|
31
32
|
pruneToolDescriptions?: boolean;
|
|
33
|
+
/** A fork's owner-worded descriptions (must match normalizeTools). */
|
|
34
|
+
inheritedToolDescriptions?: InheritedToolDescriptions;
|
|
32
35
|
}
|
|
33
36
|
/**
|
|
34
37
|
* A frozen prefix (system prompt + tools) that produces stable byte
|
|
@@ -58,6 +58,13 @@ export interface CompactionSettings {
|
|
|
58
58
|
* explicit value — even one equal to the default — is always honored.
|
|
59
59
|
*/
|
|
60
60
|
reserveTokens?: number;
|
|
61
|
+
/**
|
|
62
|
+
* Opt-in output budget for regular history summaries, replacing the default
|
|
63
|
+
* `min(floor(0.8 × reserveTokens), MAX_SUMMARY_TOKENS)` and clamped to the
|
|
64
|
+
* summarizer's own output limit. Turn-prefix and provider-native summaries
|
|
65
|
+
* keep their defaults. Unset keeps the default budget.
|
|
66
|
+
*/
|
|
67
|
+
summaryMaxTokens?: number;
|
|
61
68
|
keepRecentTokens: number;
|
|
62
69
|
autoContinue?: boolean;
|
|
63
70
|
remoteEnabled?: boolean;
|
|
@@ -67,6 +74,14 @@ export interface CompactionSettings {
|
|
|
67
74
|
}
|
|
68
75
|
/** Reserve applied when {@link CompactionSettings.reserveTokens} is unset. */
|
|
69
76
|
export declare const DEFAULT_RESERVE_TOKENS = 16384;
|
|
77
|
+
/**
|
|
78
|
+
* Ceiling on the default compaction trigger (`thresholdPercent`/`thresholdTokens`
|
|
79
|
+
* unset). Every request re-reads the whole context from the prompt cache, so the
|
|
80
|
+
* cost of a long cycle grows with absolute size, not with the window's share:
|
|
81
|
+
* 1M-class windows (past ~812K, where 85% would land above this) compact here.
|
|
82
|
+
* A configured percentage, fixed trigger, or model base is not capped.
|
|
83
|
+
*/
|
|
84
|
+
export declare const DEFAULT_THRESHOLD_CEILING_TOKENS = 690000;
|
|
70
85
|
/**
|
|
71
86
|
* Hysteresis band under the compaction trigger. Maintenance counts as having
|
|
72
87
|
* resolved threshold pressure only when residual context lands at or below
|
|
@@ -208,6 +223,8 @@ export interface SummaryOptions {
|
|
|
208
223
|
/** Additional summary context fetched only when a compaction request consumes it. */
|
|
209
224
|
loadExtraContext?: () => Promise<string[] | undefined>;
|
|
210
225
|
remoteEndpoint?: string;
|
|
226
|
+
/** Configured regular-summary output budget; see {@link CompactionSettings.summaryMaxTokens}. */
|
|
227
|
+
summaryMaxTokens?: number;
|
|
211
228
|
/** Stable system-prompt segments from the live turn, preserved for provider cache reuse. */
|
|
212
229
|
remoteSystemPrompt?: string[];
|
|
213
230
|
initiatorOverride?: MessageAttribution;
|
|
@@ -330,8 +347,8 @@ export interface HandoffFromContextOptions {
|
|
|
330
347
|
* session's payload/response hooks. Sending the same routing + payload shape
|
|
331
348
|
* the main loop uses is what lets the handoff oneshot READ the provider
|
|
332
349
|
* prompt cache the live turn populated instead of cold-missing the whole
|
|
333
|
-
* prefix. `reasoning` and `toolChoice` are set internally and
|
|
334
|
-
* anything provided here.
|
|
350
|
+
* prefix. `maxTokens`, `reasoning` and `toolChoice` are set internally and
|
|
351
|
+
* override anything provided here.
|
|
335
352
|
*/
|
|
336
353
|
streamOptions: SimpleStreamOptions;
|
|
337
354
|
/** Optional completion transport override for host-level request wrappers. */
|
|
@@ -32,6 +32,8 @@ export interface BranchSummaryMessage {
|
|
|
32
32
|
}
|
|
33
33
|
export interface CompactionSummaryMessage {
|
|
34
34
|
role: "compactionSummary";
|
|
35
|
+
/** Runtime replay state: a spoken delegation was still open at the retained-history boundary. */
|
|
36
|
+
liveVoiceOpen?: true;
|
|
35
37
|
summary: string;
|
|
36
38
|
shortSummary?: string;
|
|
37
39
|
tokensBefore: number;
|
package/dist/types/index.d.ts
CHANGED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Tool } from "@oh-my-pi/pi-ai";
|
|
2
|
+
/**
|
|
3
|
+
* Tool descriptions a fork sends in its owner's wording, so its requests open
|
|
4
|
+
* with the owner's cached prefix.
|
|
5
|
+
*
|
|
6
|
+
* A fork (`/tan`) continues its owner's transcript, but its tools render their
|
|
7
|
+
* descriptions from session state it does not share: no UI, no TUI transcript,
|
|
8
|
+
* a headless approval mode. Any byte of that drift sits ahead of the transcript,
|
|
9
|
+
* so the fork misses the owner's prompt cache entirely and, on prefix-bound
|
|
10
|
+
* reasoning (Claude, GPT-6.2), the provider drops every inherited thinking block.
|
|
11
|
+
*
|
|
12
|
+
* Only wording is inherited: a tool whose wire schema differs from the owner's
|
|
13
|
+
* keeps its own spec, so the model never sees arguments the fork's tool rejects.
|
|
14
|
+
* A pin holds while the fork's own description still renders as it did when
|
|
15
|
+
* pinned; once it changes (a setting, an MCP reload), the fork's own wording wins.
|
|
16
|
+
*/
|
|
17
|
+
export declare class InheritedToolDescriptions {
|
|
18
|
+
#private;
|
|
19
|
+
/** Pin `owner`'s description of every tool `own` declares with the same wire schema but other wording. */
|
|
20
|
+
constructor(own: readonly Tool[], owner: readonly Tool[]);
|
|
21
|
+
/** The description to send for `name`, given the one the fork renders now. */
|
|
22
|
+
resolve(name: string, description: string): string;
|
|
23
|
+
}
|
package/dist/types/types.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type { Dialect } from "@oh-my-pi/pi-ai/dialect";
|
|
|
3
3
|
import type { HarmonyAuditEvent } from "@oh-my-pi/pi-ai/utils/harmony-leak";
|
|
4
4
|
import type { AppendOnlyContextManager } from "./append-only-context.js";
|
|
5
5
|
import type { AgentRunCoverage, AgentRunSummary } from "./run-collector.js";
|
|
6
|
+
import type { InheritedToolDescriptions } from "./inherited-tool-descriptions.js";
|
|
6
7
|
import type { SentToolDefinitions } from "./sent-tool-definitions.js";
|
|
7
8
|
import type { AgentTelemetryConfig } from "./telemetry.js";
|
|
8
9
|
/** Stream function - can return sync or Promise for async config lookup */
|
|
@@ -63,6 +64,8 @@ export interface AgentTurnEndContext {
|
|
|
63
64
|
additionalMessages?: AgentMessage[];
|
|
64
65
|
/** True when the current tool-loop batch is continuing without yielding to post-turn steering. */
|
|
65
66
|
willContinue: boolean;
|
|
67
|
+
/** Tool calls in `message` that resolved to no tool (unknown name), so nothing ran. */
|
|
68
|
+
unresolvedToolCallIds?: string[];
|
|
66
69
|
}
|
|
67
70
|
export interface AgentPreModelCallStop {
|
|
68
71
|
/** Stop the agent loop before sending the next provider request. */
|
|
@@ -227,6 +230,8 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
|
227
230
|
transformProviderContext?: (context: Context, model: Model, signal?: AbortSignal) => Context | Promise<Context>;
|
|
228
231
|
/** Remembers sent tool definitions to fill {@link Context.inactiveTools}. */
|
|
229
232
|
sentToolDefinitions?: SentToolDefinitions;
|
|
233
|
+
/** A fork's owner-worded tool descriptions; see {@link InheritedToolDescriptions}. */
|
|
234
|
+
inheritedToolDescriptions?: InheritedToolDescriptions;
|
|
230
235
|
/**
|
|
231
236
|
* Resolves the API key or resolver for the current model before each LLM call.
|
|
232
237
|
*
|
|
@@ -1002,7 +1007,7 @@ export type ToolLoadMode = "essential" | "discoverable";
|
|
|
1002
1007
|
* - object form — adds a `reason` (shown in the prompt) and/or `override: true`
|
|
1003
1008
|
* (force-prompt even in modes that would otherwise auto-approve this tier).
|
|
1004
1009
|
* `policy: "deny"` blocks the call at the approval gate.
|
|
1005
|
-
* - function — dynamic, given parsed args. Returns either form above.
|
|
1010
|
+
* - function — dynamic, given parsed args and an optional {@link ToolApprovalQuery}. Returns either form above.
|
|
1006
1011
|
*
|
|
1007
1012
|
* Omitted approvals are treated as "exec" by callers that enforce approvals.
|
|
1008
1013
|
*/
|
|
@@ -1012,7 +1017,16 @@ export type ToolApprovalDecision = ToolTier | {
|
|
|
1012
1017
|
override?: boolean;
|
|
1013
1018
|
policy?: "allow" | "deny" | "prompt";
|
|
1014
1019
|
};
|
|
1015
|
-
export type ToolApproval = ToolApprovalDecision | ((args: unknown, context?: AgentToolContext) => ToolApprovalDecision);
|
|
1020
|
+
export type ToolApproval = ToolApprovalDecision | ((args: unknown, context?: AgentToolContext, query?: ToolApprovalQuery) => ToolApprovalDecision);
|
|
1021
|
+
/** How the caller of a dynamic {@link ToolApproval} uses its decision. */
|
|
1022
|
+
export interface ToolApprovalQuery {
|
|
1023
|
+
/**
|
|
1024
|
+
* `false` when only `tier` and an explicit `policy` can affect the outcome: the gate
|
|
1025
|
+
* auto-approves every tier (yolo), or the caller reads just the tier. The tool may then
|
|
1026
|
+
* skip work that only feeds a prompt (`override`, `reason`). Absent means it may prompt.
|
|
1027
|
+
*/
|
|
1028
|
+
prompts?: boolean;
|
|
1029
|
+
}
|
|
1016
1030
|
/**
|
|
1017
1031
|
* Context passed to tool execution.
|
|
1018
1032
|
* Apps can extend via declaration merging.
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"type": "module",
|
|
3
3
|
"name": "@oh-my-pi/pi-agent-core",
|
|
4
|
-
"version": "19.
|
|
4
|
+
"version": "19.3.0",
|
|
5
5
|
"description": "General-purpose agent with transport abstraction, state management, and attachment support",
|
|
6
6
|
"homepage": "https://omp.sh",
|
|
7
7
|
"author": {
|
|
@@ -38,19 +38,19 @@
|
|
|
38
38
|
"fmt": "oxfmt --no-error-on-unmatched-pattern 'src/**/*.{ts,tsx}' '{test,bench,examples,scripts}/**/*.ts' '*.ts'"
|
|
39
39
|
},
|
|
40
40
|
"dependencies": {
|
|
41
|
-
"@oh-my-pi/pi-ai": "19.
|
|
42
|
-
"@oh-my-pi/pi-catalog": "19.
|
|
43
|
-
"@oh-my-pi/pi-natives": "19.
|
|
44
|
-
"@oh-my-pi/pi-utils": "19.
|
|
45
|
-
"@oh-my-pi/pi-wire": "19.
|
|
46
|
-
"@oh-my-pi/snapcompact": "19.
|
|
47
|
-
"@opentelemetry/api": "^1.
|
|
41
|
+
"@oh-my-pi/pi-ai": "19.3.0",
|
|
42
|
+
"@oh-my-pi/pi-catalog": "19.3.0",
|
|
43
|
+
"@oh-my-pi/pi-natives": "19.3.0",
|
|
44
|
+
"@oh-my-pi/pi-utils": "19.3.0",
|
|
45
|
+
"@oh-my-pi/pi-wire": "19.3.0",
|
|
46
|
+
"@oh-my-pi/snapcompact": "19.3.0",
|
|
47
|
+
"@opentelemetry/api": "^1.10.0"
|
|
48
48
|
},
|
|
49
49
|
"devDependencies": {
|
|
50
|
-
"@oh-my-pi/omptype": "19.
|
|
51
|
-
"@opentelemetry/context-async-hooks": "
|
|
52
|
-
"@opentelemetry/sdk-trace
|
|
53
|
-
"@types/bun": "^1.
|
|
50
|
+
"@oh-my-pi/omptype": "19.3.0",
|
|
51
|
+
"@opentelemetry/context-async-hooks": "3.1.1",
|
|
52
|
+
"@opentelemetry/sdk-trace": "3.1.1",
|
|
53
|
+
"@types/bun": "^1.4.5"
|
|
54
54
|
},
|
|
55
55
|
"engines": {
|
|
56
56
|
"bun": ">=1.4.4"
|
package/src/agent-loop.ts
CHANGED
|
@@ -16,6 +16,7 @@ import {
|
|
|
16
16
|
seedApiKeyResolver,
|
|
17
17
|
streamSimple,
|
|
18
18
|
stripSchemaDescriptions,
|
|
19
|
+
type Tool,
|
|
19
20
|
type ToolCallProviderMetadata,
|
|
20
21
|
type ToolChoice,
|
|
21
22
|
type ToolResultMessage,
|
|
@@ -76,6 +77,7 @@ import {
|
|
|
76
77
|
startExecuteToolSpan,
|
|
77
78
|
startInvokeAgentSpan,
|
|
78
79
|
} from "./telemetry";
|
|
80
|
+
import type { InheritedToolDescriptions } from "./inherited-tool-descriptions";
|
|
79
81
|
import { validateAgentToolArguments } from "./tool-arguments";
|
|
80
82
|
import {
|
|
81
83
|
createAdditionalContextMessage,
|
|
@@ -1091,6 +1093,8 @@ export interface NormalizeToolsOptions {
|
|
|
1091
1093
|
intentDescription?: string;
|
|
1092
1094
|
/** Strip descriptions from the wire specs when the catalog rides in the system prompt. */
|
|
1093
1095
|
pruneDescriptions?: boolean;
|
|
1096
|
+
/** A fork's owner-worded descriptions; see {@link InheritedToolDescriptions}. */
|
|
1097
|
+
inheritedDescriptions?: InheritedToolDescriptions;
|
|
1094
1098
|
}
|
|
1095
1099
|
|
|
1096
1100
|
export function normalizeTools(tools: AgentContext["tools"], options: NormalizeToolsOptions): Context["tools"] {
|
|
@@ -1112,7 +1116,7 @@ export function normalizeTools(tools: AgentContext["tools"], options: NormalizeT
|
|
|
1112
1116
|
const parameters = (
|
|
1113
1117
|
doInjectIntent ? memoizedInjectIntentIntoSchema(stripped, intentMode, undefined) : stripped
|
|
1114
1118
|
) as TSchema;
|
|
1115
|
-
return
|
|
1119
|
+
return toolSpec(t, parameters, "");
|
|
1116
1120
|
}
|
|
1117
1121
|
const wire = toolWireSchema(t);
|
|
1118
1122
|
const parameters = (
|
|
@@ -1121,10 +1125,31 @@ export function normalizeTools(tools: AgentContext["tools"], options: NormalizeT
|
|
|
1121
1125
|
const description = t.description ?? "";
|
|
1122
1126
|
const examplesBlock = renderToolExamples({ ...t, parameters }, doInjectIntent ? INTENT_FIELD : undefined);
|
|
1123
1127
|
const finalDescription = examplesBlock ? `${description}\n\n${examplesBlock}` : description;
|
|
1124
|
-
return
|
|
1128
|
+
return toolSpec(
|
|
1129
|
+
t,
|
|
1130
|
+
parameters,
|
|
1131
|
+
options.inheritedDescriptions?.resolve(t.name, finalDescription) ?? finalDescription,
|
|
1132
|
+
);
|
|
1125
1133
|
});
|
|
1126
1134
|
}
|
|
1127
1135
|
|
|
1136
|
+
/**
|
|
1137
|
+
* The provider-bound spec of `t`: its {@link Tool} fields and nothing else.
|
|
1138
|
+
* Tool instances carry host state (a tool's `session`, renderers, caches) that a
|
|
1139
|
+
* spread would copy into the context, where transports serializing it whole
|
|
1140
|
+
* (`pi-native`, proxy) ship it with every request.
|
|
1141
|
+
*/
|
|
1142
|
+
function toolSpec(t: AgentTool, parameters: TSchema, description: string): Tool {
|
|
1143
|
+
const spec: Tool = { name: t.name, description, parameters };
|
|
1144
|
+
if (t.strict !== undefined) spec.strict = t.strict;
|
|
1145
|
+
if (t.deferLoading !== undefined) spec.deferLoading = t.deferLoading;
|
|
1146
|
+
if (t.customFormat !== undefined) spec.customFormat = t.customFormat;
|
|
1147
|
+
if (t.customWireName !== undefined) spec.customWireName = t.customWireName;
|
|
1148
|
+
if (t.native !== undefined) spec.native = t.native;
|
|
1149
|
+
if (t.examples !== undefined) spec.examples = t.examples;
|
|
1150
|
+
return spec;
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1128
1153
|
function resolveIntentMode(intent: AgentTool["intent"]): "require" | "optional" | "omit" {
|
|
1129
1154
|
if (typeof intent === "function") return "omit";
|
|
1130
1155
|
if (intent === "optional" || intent === "omit") return intent;
|
|
@@ -1396,6 +1421,7 @@ async function runLoopBody(
|
|
|
1396
1421
|
);
|
|
1397
1422
|
await emitTurnEnd(stream, currentContext, resumeTail, executionResult.toolResults, config, signal, {
|
|
1398
1423
|
willContinue: !isDeadlineExceeded(config.deadline),
|
|
1424
|
+
unresolvedToolCallIds: executionResult.unresolvedToolCallIds,
|
|
1399
1425
|
...(resumeContextMessage ? { additionalMessages: [resumeContextMessage] } : {}),
|
|
1400
1426
|
});
|
|
1401
1427
|
turnOpen = false;
|
|
@@ -1757,6 +1783,7 @@ async function runLoopBody(
|
|
|
1757
1783
|
|
|
1758
1784
|
const toolResults: ToolResultMessage[] = [];
|
|
1759
1785
|
const additionalMessages: AgentMessage[] = [];
|
|
1786
|
+
let unresolvedToolCallIds: string[] | undefined;
|
|
1760
1787
|
if (softNonCompliant && softRequiredTool !== undefined) {
|
|
1761
1788
|
SpeculativeOperationCoordinator.discardForMessage(message, "soft tool requirement deferred execution");
|
|
1762
1789
|
// A soft-required tool is pending but the model called something else
|
|
@@ -1811,6 +1838,7 @@ async function runLoopBody(
|
|
|
1811
1838
|
[...liveAccepted, ...liveDeferred],
|
|
1812
1839
|
);
|
|
1813
1840
|
toolResults.push(...executionResult.toolResults);
|
|
1841
|
+
unresolvedToolCallIds = executionResult.unresolvedToolCallIds;
|
|
1814
1842
|
|
|
1815
1843
|
for (const result of toolResults) {
|
|
1816
1844
|
currentContext.messages.push(result);
|
|
@@ -1895,6 +1923,7 @@ async function runLoopBody(
|
|
|
1895
1923
|
await emitTurnEnd(stream, currentContext, message, toolResults, config, signal, {
|
|
1896
1924
|
additionalMessages,
|
|
1897
1925
|
willContinue: hasMoreToolCalls && !isDeadlineExceeded(config.deadline),
|
|
1926
|
+
unresolvedToolCallIds,
|
|
1898
1927
|
});
|
|
1899
1928
|
turnOpen = false;
|
|
1900
1929
|
|
|
@@ -2104,6 +2133,7 @@ async function prepareProviderCall(
|
|
|
2104
2133
|
injectIntent: !!config.intentTracing,
|
|
2105
2134
|
intentDescription: config.intentDescription,
|
|
2106
2135
|
pruneDescriptions: !!config.pruneToolDescriptions && !ownedDialect,
|
|
2136
|
+
inheritedDescriptions: config.inheritedToolDescriptions,
|
|
2107
2137
|
};
|
|
2108
2138
|
let llmContext: Context;
|
|
2109
2139
|
if (config.appendOnlyContext) {
|
|
@@ -2112,6 +2142,7 @@ async function prepareProviderCall(
|
|
|
2112
2142
|
intentTracing: toolOptions.injectIntent,
|
|
2113
2143
|
intentDescription: toolOptions.intentDescription,
|
|
2114
2144
|
pruneToolDescriptions: toolOptions.pruneDescriptions,
|
|
2145
|
+
inheritedToolDescriptions: toolOptions.inheritedDescriptions,
|
|
2115
2146
|
});
|
|
2116
2147
|
} else {
|
|
2117
2148
|
llmContext = {
|
|
@@ -3425,7 +3456,7 @@ async function executeToolCalls(
|
|
|
3425
3456
|
// Steering the provider took off the queue during the response that emitted
|
|
3426
3457
|
// this batch; it injects at this batch's boundary like queued steering.
|
|
3427
3458
|
liveSteering: readonly AgentMessage[],
|
|
3428
|
-
): Promise<{ toolResults: ToolResultMessage[]; additionalContext?: string }> {
|
|
3459
|
+
): Promise<{ toolResults: ToolResultMessage[]; additionalContext?: string; unresolvedToolCallIds: string[] }> {
|
|
3429
3460
|
const tools = currentContext.tools;
|
|
3430
3461
|
const {
|
|
3431
3462
|
hasSteeringMessages,
|
|
@@ -4068,7 +4099,7 @@ async function executeToolCalls(
|
|
|
4068
4099
|
const approval = record.tool?.approval;
|
|
4069
4100
|
let decision: ToolApprovalDecision | undefined;
|
|
4070
4101
|
try {
|
|
4071
|
-
decision = typeof approval === "function" ? approval(record.args) : approval;
|
|
4102
|
+
decision = typeof approval === "function" ? approval(record.args, undefined, { prompts: false }) : approval;
|
|
4072
4103
|
} catch {
|
|
4073
4104
|
decision = undefined;
|
|
4074
4105
|
}
|
|
@@ -4116,6 +4147,7 @@ async function executeToolCalls(
|
|
|
4116
4147
|
return {
|
|
4117
4148
|
toolResults: emittedToolResults,
|
|
4118
4149
|
...(additionalContext !== undefined ? { additionalContext } : {}),
|
|
4150
|
+
unresolvedToolCallIds: records.filter(record => record.tool === undefined).map(record => record.toolCall.id),
|
|
4119
4151
|
};
|
|
4120
4152
|
}
|
|
4121
4153
|
|
package/src/agent.ts
CHANGED
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
streamSimple,
|
|
20
20
|
type TextContent,
|
|
21
21
|
type ThinkingBudgets,
|
|
22
|
+
type Tool,
|
|
22
23
|
type ToolChoice,
|
|
23
24
|
type ToolResultMessage,
|
|
24
25
|
} from "@oh-my-pi/pi-ai";
|
|
@@ -45,6 +46,7 @@ import {
|
|
|
45
46
|
import type { AppendOnlyContextManager } from "./append-only-context";
|
|
46
47
|
import { agentPauseGate } from "./pause";
|
|
47
48
|
import { filterProviderReplayMessages } from "./replay-policy";
|
|
49
|
+
import { InheritedToolDescriptions } from "./inherited-tool-descriptions";
|
|
48
50
|
import { SentToolDefinitions } from "./sent-tool-definitions";
|
|
49
51
|
import { Tokenizer } from "./tokenizer";
|
|
50
52
|
import {
|
|
@@ -510,6 +512,7 @@ export class Agent {
|
|
|
510
512
|
#intentTracing: boolean;
|
|
511
513
|
#intentDescription?: string;
|
|
512
514
|
#pruneToolDescriptions: boolean;
|
|
515
|
+
#inheritedToolDescriptions?: InheritedToolDescriptions;
|
|
513
516
|
#dialect?: Dialect;
|
|
514
517
|
#dialectResolver?: (model: Model) => Dialect | undefined;
|
|
515
518
|
#abortOnFabricatedToolResult?: boolean;
|
|
@@ -684,6 +687,36 @@ export class Agent {
|
|
|
684
687
|
return this.#sentToolDefinitions.copy(keep);
|
|
685
688
|
}
|
|
686
689
|
|
|
690
|
+
/**
|
|
691
|
+
* Provider-bound specs of the tools the next request to the active model declares, before the
|
|
692
|
+
* provider-context transform; empty without a model or under an owned dialect. A fork passes
|
|
693
|
+
* its owner's to {@link inheritToolDescriptions}.
|
|
694
|
+
*/
|
|
695
|
+
normalizedTools(): Tool[] {
|
|
696
|
+
const model = this.#state.model;
|
|
697
|
+
if (!model || this.#ownedDialect(model)) return [];
|
|
698
|
+
return normalizeTools(this.#toolsForModel(model), this.#toolOptions()) ?? [];
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
/**
|
|
702
|
+
* Send `owner`'s wording for every current tool that differs from it only in description, so
|
|
703
|
+
* this fork's requests open with the owner's cached prefix. Call once the fork's tool set is
|
|
704
|
+
* final; see {@link InheritedToolDescriptions}.
|
|
705
|
+
*/
|
|
706
|
+
inheritToolDescriptions(owner: readonly Tool[]): void {
|
|
707
|
+
this.#inheritedToolDescriptions = undefined;
|
|
708
|
+
this.#inheritedToolDescriptions = new InheritedToolDescriptions(this.normalizedTools(), owner);
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
#toolOptions(): NormalizeToolsOptions {
|
|
712
|
+
return {
|
|
713
|
+
injectIntent: this.#intentTracing,
|
|
714
|
+
intentDescription: this.#intentDescription,
|
|
715
|
+
pruneDescriptions: this.#pruneToolDescriptions,
|
|
716
|
+
inheritedDescriptions: this.#inheritedToolDescriptions,
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
|
|
687
720
|
/**
|
|
688
721
|
* Fields added to every log record written while this agent runs (the
|
|
689
722
|
* owning session's `sessionId`), so in-process agents' records stay apart.
|
|
@@ -1000,11 +1033,7 @@ export class Agent {
|
|
|
1000
1033
|
if (!model) throw new Error("No active model on agent");
|
|
1001
1034
|
const ownedDialect = this.#ownedDialect(model);
|
|
1002
1035
|
const messages = normalizeMessagesForProvider(llmMessages, model);
|
|
1003
|
-
const toolOptions
|
|
1004
|
-
injectIntent: this.#intentTracing,
|
|
1005
|
-
intentDescription: this.#intentDescription,
|
|
1006
|
-
pruneDescriptions: this.#pruneToolDescriptions,
|
|
1007
|
-
};
|
|
1036
|
+
const toolOptions = this.#toolOptions();
|
|
1008
1037
|
const tools = ownedDialect ? [] : (normalizeTools(this.#toolsForModel(model), toolOptions) ?? []);
|
|
1009
1038
|
const standby = ownedDialect ? undefined : normalizeTools(this.#standbyTools, toolOptions);
|
|
1010
1039
|
let context: Context = { systemPrompt, messages, tools };
|
|
@@ -2126,6 +2155,7 @@ export class Agent {
|
|
|
2126
2155
|
intentTracing: this.#intentTracing,
|
|
2127
2156
|
intentDescription: this.#intentDescription,
|
|
2128
2157
|
pruneToolDescriptions: this.#pruneToolDescriptions,
|
|
2158
|
+
inheritedToolDescriptions: this.#inheritedToolDescriptions,
|
|
2129
2159
|
dialect: this.#dialect,
|
|
2130
2160
|
getDialect: this.#dialectResolver,
|
|
2131
2161
|
abortOnFabricatedToolResult: this.#abortOnFabricatedToolResult,
|
|
@@ -18,6 +18,7 @@ import type { AgentTool } from "./types";
|
|
|
18
18
|
import type { Context, Message, Tool } from "@oh-my-pi/pi-ai";
|
|
19
19
|
import { toolWireSchema } from "@oh-my-pi/pi-ai";
|
|
20
20
|
import { normalizeTools } from "./agent-loop";
|
|
21
|
+
import type { InheritedToolDescriptions } from "./inherited-tool-descriptions";
|
|
21
22
|
import { messageEstimateVersion } from "./compaction/message-cache";
|
|
22
23
|
import type { AgentContext, AgentMessage } from "./types";
|
|
23
24
|
|
|
@@ -86,6 +87,8 @@ export interface BuildOptions {
|
|
|
86
87
|
intentDescription?: string;
|
|
87
88
|
/** Strip tool descriptions from the provider-bound specs (must match normalizeTools). */
|
|
88
89
|
pruneToolDescriptions?: boolean;
|
|
90
|
+
/** A fork's owner-worded descriptions (must match normalizeTools). */
|
|
91
|
+
inheritedToolDescriptions?: InheritedToolDescriptions;
|
|
89
92
|
}
|
|
90
93
|
|
|
91
94
|
/**
|
|
@@ -140,6 +143,7 @@ export class StablePrefix {
|
|
|
140
143
|
#lastIntentTracing: boolean | undefined;
|
|
141
144
|
#lastIntentDescription: string | undefined;
|
|
142
145
|
#lastPruneToolDescriptions: boolean | undefined;
|
|
146
|
+
#lastInheritedToolDescriptions: InheritedToolDescriptions | undefined;
|
|
143
147
|
|
|
144
148
|
build(context: AgentContext, options: BuildOptions): boolean {
|
|
145
149
|
const prev = this.#snapshot;
|
|
@@ -170,7 +174,8 @@ export class StablePrefix {
|
|
|
170
174
|
if (
|
|
171
175
|
this.#lastIntentTracing !== options.intentTracing ||
|
|
172
176
|
this.#lastIntentDescription !== options.intentDescription ||
|
|
173
|
-
this.#lastPruneToolDescriptions !== options.pruneToolDescriptions
|
|
177
|
+
this.#lastPruneToolDescriptions !== options.pruneToolDescriptions ||
|
|
178
|
+
this.#lastInheritedToolDescriptions !== options.inheritedToolDescriptions
|
|
174
179
|
) {
|
|
175
180
|
return false;
|
|
176
181
|
}
|
|
@@ -202,6 +207,7 @@ export class StablePrefix {
|
|
|
202
207
|
this.#lastIntentTracing = options.intentTracing;
|
|
203
208
|
this.#lastIntentDescription = options.intentDescription;
|
|
204
209
|
this.#lastPruneToolDescriptions = options.pruneToolDescriptions;
|
|
210
|
+
this.#lastInheritedToolDescriptions = options.inheritedToolDescriptions;
|
|
205
211
|
this.#lastToolKey = renderedToolKeys;
|
|
206
212
|
}
|
|
207
213
|
|
|
@@ -212,6 +218,7 @@ export class StablePrefix {
|
|
|
212
218
|
this.#lastToolKey = undefined;
|
|
213
219
|
this.#lastIntentTracing = undefined;
|
|
214
220
|
this.#lastPruneToolDescriptions = undefined;
|
|
221
|
+
this.#lastInheritedToolDescriptions = undefined;
|
|
215
222
|
}
|
|
216
223
|
|
|
217
224
|
/**
|
|
@@ -489,6 +496,7 @@ function normalizeWireTools(tools: AgentContext["tools"], options: BuildOptions)
|
|
|
489
496
|
injectIntent: options.intentTracing,
|
|
490
497
|
intentDescription: options.intentDescription,
|
|
491
498
|
pruneDescriptions: options.pruneToolDescriptions,
|
|
499
|
+
inheritedDescriptions: options.inheritedToolDescriptions,
|
|
492
500
|
}) ?? []
|
|
493
501
|
);
|
|
494
502
|
}
|
|
@@ -24,7 +24,6 @@ import {
|
|
|
24
24
|
type Usage,
|
|
25
25
|
withAuth,
|
|
26
26
|
} from "@oh-my-pi/pi-ai";
|
|
27
|
-
import type { Dialect } from "@oh-my-pi/pi-ai/dialect";
|
|
28
27
|
import * as AIError from "@oh-my-pi/pi-ai/error";
|
|
29
28
|
import { createOpenAICodexCompactionRequestContext } from "@oh-my-pi/pi-ai/providers/openai-codex-compaction";
|
|
30
29
|
import type { OpenAICodexCompactionBody } from "@oh-my-pi/pi-ai/providers/openai-codex-responses";
|
|
@@ -190,6 +189,13 @@ export interface CompactionSettings {
|
|
|
190
189
|
* explicit value — even one equal to the default — is always honored.
|
|
191
190
|
*/
|
|
192
191
|
reserveTokens?: number;
|
|
192
|
+
/**
|
|
193
|
+
* Opt-in output budget for regular history summaries, replacing the default
|
|
194
|
+
* `min(floor(0.8 × reserveTokens), MAX_SUMMARY_TOKENS)` and clamped to the
|
|
195
|
+
* summarizer's own output limit. Turn-prefix and provider-native summaries
|
|
196
|
+
* keep their defaults. Unset keeps the default budget.
|
|
197
|
+
*/
|
|
198
|
+
summaryMaxTokens?: number;
|
|
193
199
|
keepRecentTokens: number;
|
|
194
200
|
autoContinue?: boolean;
|
|
195
201
|
remoteEnabled?: boolean;
|
|
@@ -201,6 +207,15 @@ export interface CompactionSettings {
|
|
|
201
207
|
/** Reserve applied when {@link CompactionSettings.reserveTokens} is unset. */
|
|
202
208
|
export const DEFAULT_RESERVE_TOKENS = 16384;
|
|
203
209
|
|
|
210
|
+
/**
|
|
211
|
+
* Ceiling on the default compaction trigger (`thresholdPercent`/`thresholdTokens`
|
|
212
|
+
* unset). Every request re-reads the whole context from the prompt cache, so the
|
|
213
|
+
* cost of a long cycle grows with absolute size, not with the window's share:
|
|
214
|
+
* 1M-class windows (past ~812K, where 85% would land above this) compact here.
|
|
215
|
+
* A configured percentage, fixed trigger, or model base is not capped.
|
|
216
|
+
*/
|
|
217
|
+
export const DEFAULT_THRESHOLD_CEILING_TOKENS = 690_000;
|
|
218
|
+
|
|
204
219
|
/**
|
|
205
220
|
* Hysteresis band under the compaction trigger. Maintenance counts as having
|
|
206
221
|
* resolved threshold pressure only when residual context lands at or below
|
|
@@ -226,6 +241,19 @@ export const COMPACTION_RECOVERY_BAND = 0.8;
|
|
|
226
241
|
*/
|
|
227
242
|
export const MAX_SUMMARY_TOKENS = DEFAULT_RESERVE_TOKENS;
|
|
228
243
|
|
|
244
|
+
/**
|
|
245
|
+
* Output budget for one regular history summary. The default is the reserve
|
|
246
|
+
* fraction under {@link MAX_SUMMARY_TOKENS}; a positive configured
|
|
247
|
+
* `summaryMaxTokens` replaces it, bounded by the summarizer's output limit.
|
|
248
|
+
*/
|
|
249
|
+
function regularSummaryMaxTokens(model: Model, reserveTokens: number, summaryMaxTokens: number | undefined): number {
|
|
250
|
+
if (summaryMaxTokens === undefined || !Number.isFinite(summaryMaxTokens) || summaryMaxTokens <= 0) {
|
|
251
|
+
return Math.min(Math.floor(0.8 * reserveTokens), MAX_SUMMARY_TOKENS);
|
|
252
|
+
}
|
|
253
|
+
const requested = Math.floor(summaryMaxTokens);
|
|
254
|
+
return model.maxTokens && model.maxTokens > 0 ? Math.min(requested, model.maxTokens) : requested;
|
|
255
|
+
}
|
|
256
|
+
|
|
229
257
|
// reserveTokens is deliberately absent: an unset reserve is what marks it as
|
|
230
258
|
// defaulted, which resolveBudgetReserveTokens needs to distinguish "user never
|
|
231
259
|
// chose a reserve" from "user explicitly configured the default value".
|
|
@@ -419,9 +447,9 @@ export function resolveThresholdTokens(contextWindow: number, settings: Compacti
|
|
|
419
447
|
return Math.min(contextWindow - 1, Math.max(1, thresholdTokens));
|
|
420
448
|
}
|
|
421
449
|
const baseWindowTokens = settings.baseWindowTokens;
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
450
|
+
const scaledFromBase =
|
|
451
|
+
typeof baseWindowTokens === "number" && Number.isFinite(baseWindowTokens) && baseWindowTokens > 0;
|
|
452
|
+
if (scaledFromBase) contextWindow = Math.min(contextWindow, baseWindowTokens);
|
|
425
453
|
|
|
426
454
|
// Percentage-based threshold. The default absolute reserve can exceed bundled
|
|
427
455
|
// small-context windows, or nearly consume a 16k-class window; in those
|
|
@@ -430,7 +458,9 @@ export function resolveThresholdTokens(contextWindow: number, settings: Compacti
|
|
|
430
458
|
// configured reserves still define the usable prompt budget.
|
|
431
459
|
const thresholdPercent = settings.thresholdPercent;
|
|
432
460
|
if (typeof thresholdPercent !== "number" || !Number.isFinite(thresholdPercent) || thresholdPercent <= 0) {
|
|
433
|
-
|
|
461
|
+
const budget = promptBudgetTokens(contextWindow, settings);
|
|
462
|
+
// A model entry's base is a window the user chose to scale from; only the bare default stops at the ceiling.
|
|
463
|
+
return scaledFromBase ? budget : Math.min(budget, DEFAULT_THRESHOLD_CEILING_TOKENS);
|
|
434
464
|
}
|
|
435
465
|
const clampedThresholdPercent = Math.min(99, Math.max(1, thresholdPercent));
|
|
436
466
|
return Math.floor(contextWindow * (clampedThresholdPercent / 100));
|
|
@@ -708,6 +738,8 @@ export interface SummaryOptions {
|
|
|
708
738
|
/** Additional summary context fetched only when a compaction request consumes it. */
|
|
709
739
|
loadExtraContext?: () => Promise<string[] | undefined>;
|
|
710
740
|
remoteEndpoint?: string;
|
|
741
|
+
/** Configured regular-summary output budget; see {@link CompactionSettings.summaryMaxTokens}. */
|
|
742
|
+
summaryMaxTokens?: number;
|
|
711
743
|
/** Stable system-prompt segments from the live turn, preserved for provider cache reuse. */
|
|
712
744
|
remoteSystemPrompt?: string[];
|
|
713
745
|
initiatorOverride?: MessageAttribution;
|
|
@@ -891,9 +923,8 @@ function createSnapcompactArchiveMigrationMessage(archiveText: string): Message
|
|
|
891
923
|
const DEFAULT_SUMMARY_INPUT_WINDOW = 200_000;
|
|
892
924
|
|
|
893
925
|
/**
|
|
894
|
-
*
|
|
895
|
-
* Scaled down (never below 1k) for
|
|
896
|
-
* floor next to the carried summary and output reserves.
|
|
926
|
+
* Smallest conversation window worth retrying after a provider overflow.
|
|
927
|
+
* Scaled down (never below 1k) for small-context summarizers.
|
|
897
928
|
*/
|
|
898
929
|
const MIN_SUMMARY_INPUT_TOKENS = 16_384;
|
|
899
930
|
|
|
@@ -904,17 +935,16 @@ function minSummaryInputTokens(model: Model): number {
|
|
|
904
935
|
}
|
|
905
936
|
|
|
906
937
|
/**
|
|
907
|
-
*
|
|
908
|
-
*
|
|
909
|
-
*
|
|
910
|
-
* estimate, so the window is discounted before the fixed reserves come off.
|
|
938
|
+
* Input available for the conversation and carried summary together, after
|
|
939
|
+
* reserving output and discounting the window for prompt scaffolding and
|
|
940
|
+
* differences between provider and local tokenizer counts.
|
|
911
941
|
*/
|
|
912
942
|
function summaryInputBudgetTokens(model: Model, maxTokens: number): number {
|
|
913
943
|
const window = model.contextWindow && model.contextWindow > 0 ? model.contextWindow : DEFAULT_SUMMARY_INPUT_WINDOW;
|
|
914
944
|
// 0.8, not "window minus reserves": provider tokenizers disagree with the
|
|
915
945
|
// local cl100k estimate by a few percent, and being wrong here is a hard
|
|
916
946
|
// 400 on the one call that is supposed to rescue an oversized session.
|
|
917
|
-
return Math.max(
|
|
947
|
+
return Math.max(1, Math.floor(window * 0.8) - maxTokens);
|
|
918
948
|
}
|
|
919
949
|
|
|
920
950
|
/**
|
|
@@ -930,43 +960,6 @@ function clampConversationToBudget(text: string, budgetTokens: number, tokens: n
|
|
|
930
960
|
return `${text.slice(0, keep)}\n\n[... ${text.length - keep} more characters truncated]`;
|
|
931
961
|
}
|
|
932
962
|
|
|
933
|
-
/** One planned summarization call: its messages and the budget they were packed for. */
|
|
934
|
-
interface SummaryWindow {
|
|
935
|
-
messages: Message[];
|
|
936
|
-
budgetTokens: number;
|
|
937
|
-
/** Serialization reused from the fit check, so the common path serializes once. */
|
|
938
|
-
text?: string;
|
|
939
|
-
}
|
|
940
|
-
|
|
941
|
-
/**
|
|
942
|
-
* Partition a conversation into windows that each fit `budgetTokens`, splitting
|
|
943
|
-
* on message boundaries. Only called when the whole conversation does not fit —
|
|
944
|
-
* the common single-window path never pays this per-message sizing pass.
|
|
945
|
-
*/
|
|
946
|
-
function planSummaryWindows(
|
|
947
|
-
messages: Message[],
|
|
948
|
-
tokenizer: Tokenizer,
|
|
949
|
-
dialect: Dialect | undefined,
|
|
950
|
-
dropThinking: boolean,
|
|
951
|
-
budgetTokens: number,
|
|
952
|
-
): Message[][] {
|
|
953
|
-
const windows: Message[][] = [];
|
|
954
|
-
let current: Message[] = [];
|
|
955
|
-
let currentTokens = 0;
|
|
956
|
-
for (const message of messages) {
|
|
957
|
-
const tokens = tokenizer.countTokens(serializeConversationForSummary([message], dialect, dropThinking));
|
|
958
|
-
if (currentTokens > 0 && currentTokens + tokens > budgetTokens) {
|
|
959
|
-
windows.push(current);
|
|
960
|
-
current = [];
|
|
961
|
-
currentTokens = 0;
|
|
962
|
-
}
|
|
963
|
-
current.push(message);
|
|
964
|
-
currentTokens += tokens;
|
|
965
|
-
}
|
|
966
|
-
if (current.length > 0) windows.push(current);
|
|
967
|
-
return windows;
|
|
968
|
-
}
|
|
969
|
-
|
|
970
963
|
export async function generateSummary(
|
|
971
964
|
currentMessages: AgentMessage[],
|
|
972
965
|
model: Model,
|
|
@@ -977,7 +970,7 @@ export async function generateSummary(
|
|
|
977
970
|
previousSummary?: string,
|
|
978
971
|
options?: SummaryOptions,
|
|
979
972
|
): Promise<string> {
|
|
980
|
-
const maxTokens =
|
|
973
|
+
const maxTokens = regularSummaryMaxTokens(model, reserveTokens, options?.summaryMaxTokens);
|
|
981
974
|
|
|
982
975
|
// Serialize conversation to text so model doesn't try to continue it
|
|
983
976
|
// Convert to LLM messages first (handles custom app messages when caller provides a transformer).
|
|
@@ -985,34 +978,52 @@ export async function generateSummary(
|
|
|
985
978
|
const dialect = preferredDialect(model.id);
|
|
986
979
|
const dropThinking = resolveCatalogPolicy(model).classifierCotExtraction === true;
|
|
987
980
|
const tokenizer = new Tokenizer(model);
|
|
988
|
-
const wholeConversation = serializeConversationForSummary(llmMessages, dialect, dropThinking);
|
|
989
|
-
const budgetTokens = summaryInputBudgetTokens(model, maxTokens);
|
|
990
|
-
// A span that outgrew the summarizer's window is summarized as a fold: each
|
|
991
|
-
// window updates the summary carried out of the previous one, which is the
|
|
992
|
-
// same contract the update prompt already implements for iterative
|
|
993
|
-
// compaction. The alternative is a hard provider rejection on a prompt no
|
|
994
|
-
// retry can shrink — the state a cross-provider compaction boundary
|
|
995
|
-
// (see `prepareCompaction`) puts a long session into. One window is the
|
|
996
|
-
// common case and costs exactly the one call it always did.
|
|
997
|
-
const pending: SummaryWindow[] = tokenizer.checkTokenBudget(wholeConversation, budgetTokens).fits
|
|
998
|
-
? [{ messages: llmMessages, budgetTokens, text: wholeConversation }]
|
|
999
|
-
: planSummaryWindows(llmMessages, tokenizer, dialect, dropThinking, budgetTokens).map(messages => ({
|
|
1000
|
-
messages,
|
|
1001
|
-
budgetTokens,
|
|
1002
|
-
}));
|
|
1003
|
-
|
|
1004
981
|
let carriedSummary = previousSummary;
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
//
|
|
1011
|
-
|
|
982
|
+
let start = 0;
|
|
983
|
+
const catalogBudget = summaryInputBudgetTokens(model, maxTokens);
|
|
984
|
+
let inputBudget = catalogBudget;
|
|
985
|
+
let messageTokens: number[] | undefined;
|
|
986
|
+
function nextWindow(budgetTokens: number) {
|
|
987
|
+
// Most histories fit without a per-message sizing pass.
|
|
988
|
+
if (start === 0 && inputBudget === catalogBudget) {
|
|
989
|
+
const text = serializeConversationForSummary(llmMessages, dialect, dropThinking);
|
|
990
|
+
const budget = tokenizer.checkTokenBudget(text, budgetTokens);
|
|
991
|
+
if (budget.fits || llmMessages.length <= 1) return { text, budget, end: llmMessages.length };
|
|
992
|
+
}
|
|
993
|
+
messageTokens ??= [];
|
|
994
|
+
let tokens = 0;
|
|
995
|
+
let end = start;
|
|
996
|
+
while (end < llmMessages.length) {
|
|
997
|
+
const count = (messageTokens[end] ??= tokenizer.countTokens(
|
|
998
|
+
serializeConversationForSummary([llmMessages[end]], dialect, dropThinking),
|
|
999
|
+
"strict",
|
|
1000
|
+
));
|
|
1001
|
+
if (end > start && tokens + count > budgetTokens) break;
|
|
1002
|
+
tokens += count;
|
|
1003
|
+
end++;
|
|
1004
|
+
}
|
|
1005
|
+
// Separators can make the packed conversation larger than the sum of
|
|
1006
|
+
// its parts. Split at a message boundary rather than discard its tail.
|
|
1007
|
+
for (;;) {
|
|
1008
|
+
const text = serializeConversationForSummary(llmMessages.slice(start, end), dialect, dropThinking);
|
|
1009
|
+
const budget = tokenizer.checkTokenBudget(text, budgetTokens);
|
|
1010
|
+
if (budget.fits || end <= start + 1) return { text, budget, end };
|
|
1011
|
+
end--;
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
do {
|
|
1015
|
+
// Cancellation ends the fold: no window starts on an aborted signal.
|
|
1016
|
+
if (signal?.aborted) throw new AIError.AbortError("Summarization aborted", { cause: signal.reason });
|
|
1017
|
+
// The previous call's actual output is input to this one. Pack only
|
|
1018
|
+
// this window, not the remaining windows against a hypothetical cap.
|
|
1019
|
+
const escapedSummary = carriedSummary && escapeSummaryBoundaryTags(carriedSummary);
|
|
1020
|
+
const carriedTokens = escapedSummary ? tokenizer.countTokens(escapedSummary, "strict") : 0;
|
|
1021
|
+
const budgetTokens = Math.max(1, inputBudget - carriedTokens);
|
|
1022
|
+
const { text, budget, end } = nextWindow(budgetTokens);
|
|
1012
1023
|
try {
|
|
1013
1024
|
carriedSummary = await summarizeConversationWindow(
|
|
1014
|
-
budget.fits ? text : clampConversationToBudget(text,
|
|
1015
|
-
|
|
1025
|
+
budget.fits ? text : clampConversationToBudget(text, budgetTokens, budget.tokens),
|
|
1026
|
+
escapedSummary,
|
|
1016
1027
|
model,
|
|
1017
1028
|
maxTokens,
|
|
1018
1029
|
apiKey,
|
|
@@ -1032,32 +1043,25 @@ export async function generateSummary(
|
|
|
1032
1043
|
// fit path never counted this window, so pay for the exact size here —
|
|
1033
1044
|
// one tokenization is nothing against the provider round trip already lost.
|
|
1034
1045
|
const sentTokens = budget.exact ? budget.tokens : tokenizer.countTokens(text, "strict");
|
|
1035
|
-
const
|
|
1046
|
+
const sent = Math.min(budgetTokens, sentTokens);
|
|
1036
1047
|
if (
|
|
1037
1048
|
!AIError.is(AIError.classify(error), AIError.Flag.ContextOverflow) ||
|
|
1038
|
-
|
|
1049
|
+
sent <= minSummaryInputTokens(model)
|
|
1039
1050
|
) {
|
|
1040
1051
|
throw error;
|
|
1041
1052
|
}
|
|
1042
|
-
|
|
1043
|
-
0,
|
|
1044
|
-
1,
|
|
1045
|
-
...planSummaryWindows(window.messages, tokenizer, dialect, dropThinking, halved).map(messages => ({
|
|
1046
|
-
messages,
|
|
1047
|
-
budgetTokens: halved,
|
|
1048
|
-
})),
|
|
1049
|
-
);
|
|
1053
|
+
inputBudget = carriedTokens + Math.max(minSummaryInputTokens(model), Math.floor(sent / 2));
|
|
1050
1054
|
continue;
|
|
1051
1055
|
}
|
|
1052
|
-
|
|
1053
|
-
}
|
|
1056
|
+
start = end;
|
|
1057
|
+
} while (start < llmMessages.length);
|
|
1054
1058
|
return carriedSummary ?? "";
|
|
1055
1059
|
}
|
|
1056
1060
|
|
|
1057
1061
|
/** One summarization call over a single conversation window. */
|
|
1058
1062
|
async function summarizeConversationWindow(
|
|
1059
1063
|
conversationText: string,
|
|
1060
|
-
|
|
1064
|
+
escapedPreviousSummary: string | undefined,
|
|
1061
1065
|
model: Model,
|
|
1062
1066
|
maxTokens: number,
|
|
1063
1067
|
apiKey: ApiKey,
|
|
@@ -1066,7 +1070,7 @@ async function summarizeConversationWindow(
|
|
|
1066
1070
|
options: SummaryOptions | undefined,
|
|
1067
1071
|
): Promise<string> {
|
|
1068
1072
|
// Use update prompt if we have a previous summary, otherwise initial prompt
|
|
1069
|
-
let basePrompt =
|
|
1073
|
+
let basePrompt = escapedPreviousSummary ? UPDATE_SUMMARIZATION_PROMPT : SUMMARIZATION_PROMPT;
|
|
1070
1074
|
if (options?.promptOverride) {
|
|
1071
1075
|
basePrompt = options.promptOverride;
|
|
1072
1076
|
}
|
|
@@ -1076,8 +1080,8 @@ async function summarizeConversationWindow(
|
|
|
1076
1080
|
|
|
1077
1081
|
// Build the prompt with conversation wrapped in tags
|
|
1078
1082
|
let promptText = `<conversation>\n${conversationText}\n</conversation>\n\n`;
|
|
1079
|
-
if (
|
|
1080
|
-
promptText += `<previous-summary>\n${
|
|
1083
|
+
if (escapedPreviousSummary) {
|
|
1084
|
+
promptText += `<previous-summary>\n${escapedPreviousSummary}\n</previous-summary>\n\n`;
|
|
1081
1085
|
}
|
|
1082
1086
|
promptText += formatAdditionalContext(options?.extraContext);
|
|
1083
1087
|
promptText += basePrompt;
|
|
@@ -1130,6 +1134,11 @@ async function summarizeConversationWindow(
|
|
|
1130
1134
|
},
|
|
1131
1135
|
);
|
|
1132
1136
|
|
|
1137
|
+
// Providers report cancellation as a resolved message with partial output.
|
|
1138
|
+
// It is no summary, and the next window would start on the same aborted signal.
|
|
1139
|
+
if (response.stopReason === "aborted") {
|
|
1140
|
+
throw new AIError.AbortError("Summarization aborted", { cause: signal?.reason });
|
|
1141
|
+
}
|
|
1133
1142
|
if (response.stopReason === "error") {
|
|
1134
1143
|
throw createSummarizationError("Summarization failed", response);
|
|
1135
1144
|
}
|
|
@@ -1186,8 +1195,8 @@ export interface HandoffFromContextOptions {
|
|
|
1186
1195
|
* session's payload/response hooks. Sending the same routing + payload shape
|
|
1187
1196
|
* the main loop uses is what lets the handoff oneshot READ the provider
|
|
1188
1197
|
* prompt cache the live turn populated instead of cold-missing the whole
|
|
1189
|
-
* prefix. `reasoning` and `toolChoice` are set internally and
|
|
1190
|
-
* anything provided here.
|
|
1198
|
+
* prefix. `maxTokens`, `reasoning` and `toolChoice` are set internally and
|
|
1199
|
+
* override anything provided here.
|
|
1191
1200
|
*/
|
|
1192
1201
|
streamOptions: SimpleStreamOptions;
|
|
1193
1202
|
/** Optional completion transport override for host-level request wrappers. */
|
|
@@ -1229,6 +1238,11 @@ export async function generateHandoffFromContext(
|
|
|
1229
1238
|
}
|
|
1230
1239
|
const requestOptions = {
|
|
1231
1240
|
...options.streamOptions,
|
|
1241
|
+
// Bound the document like a summary: without an explicit cap a local
|
|
1242
|
+
// server falls back to its own (possibly unlimited) output limit, so a
|
|
1243
|
+
// runaway stream never ends and maintenance never reaches its next method.
|
|
1244
|
+
// Hitting the cap ends with `stopReason: "length"`, rejected below.
|
|
1245
|
+
maxTokens: MAX_SUMMARY_TOKENS,
|
|
1232
1246
|
reasoning: resolveCompactionEffort(model, options.thinkingLevel),
|
|
1233
1247
|
toolChoice: "none" as const,
|
|
1234
1248
|
};
|
|
@@ -1852,6 +1866,7 @@ export async function compact(
|
|
|
1852
1866
|
promptOverride: options?.promptOverride,
|
|
1853
1867
|
extraContext: options?.extraContext,
|
|
1854
1868
|
remoteEndpoint: settings.remoteEnabled === false ? undefined : settings.remoteEndpoint,
|
|
1869
|
+
summaryMaxTokens: options?.summaryMaxTokens ?? settings.summaryMaxTokens,
|
|
1855
1870
|
remoteSystemPrompt: options?.remoteSystemPrompt,
|
|
1856
1871
|
initiatorOverride: options?.initiatorOverride,
|
|
1857
1872
|
metadata: options?.metadata,
|
|
@@ -2414,22 +2429,33 @@ export async function compact(
|
|
|
2414
2429
|
const inputTokens = getCompactionV2PreserveData(preserveData)?.usedTokens ?? 0;
|
|
2415
2430
|
summary = formatRemoteCompactionSummary(inputTokens);
|
|
2416
2431
|
} else if (isSplitTurn && turnPrefixMessages.length > 0) {
|
|
2417
|
-
// Generate both summaries in parallel
|
|
2418
|
-
|
|
2432
|
+
// Generate both summaries in parallel. The first failure aborts the other
|
|
2433
|
+
// request with that failure as the reason, and compaction throws it only
|
|
2434
|
+
// after both requests have stopped, so no summary request outlives the
|
|
2435
|
+
// compaction that started it. The caller's signal, with its own reason,
|
|
2436
|
+
// still reaches both requests.
|
|
2437
|
+
const splitAbort = new AbortController();
|
|
2438
|
+
const summarySignal = signal ? AbortSignal.any([signal, splitAbort.signal]) : splitAbort.signal;
|
|
2439
|
+
const requests = [
|
|
2419
2440
|
messagesToSummarize.length > 0 || previousSummaryForCompaction
|
|
2420
2441
|
? generateSummary(
|
|
2421
2442
|
messagesToSummarize,
|
|
2422
2443
|
model,
|
|
2423
2444
|
reserveTokens,
|
|
2424
2445
|
apiKey,
|
|
2425
|
-
|
|
2446
|
+
summarySignal,
|
|
2426
2447
|
customInstructions,
|
|
2427
2448
|
previousSummaryForCompaction,
|
|
2428
2449
|
summaryOptions,
|
|
2429
2450
|
)
|
|
2430
2451
|
: Promise.resolve("No prior history."),
|
|
2431
|
-
generateTurnPrefixSummary(turnPrefixMessages, model, reserveTokens, apiKey,
|
|
2432
|
-
]
|
|
2452
|
+
generateTurnPrefixSummary(turnPrefixMessages, model, reserveTokens, apiKey, summarySignal, summaryOptions),
|
|
2453
|
+
] as const;
|
|
2454
|
+
const [historyResult, turnPrefixResult] = await Promise.all(requests).catch(async (error: unknown) => {
|
|
2455
|
+
splitAbort.abort(error);
|
|
2456
|
+
await Promise.allSettled(requests);
|
|
2457
|
+
throw error;
|
|
2458
|
+
});
|
|
2433
2459
|
// Merge into single summary
|
|
2434
2460
|
summary = `${historyResult}\n\n---\n\n**Turn Context (split turn):**\n\n${turnPrefixResult}`;
|
|
2435
2461
|
} else if (messagesToSummarize.length > 0) {
|
|
@@ -51,6 +51,8 @@ export interface BranchSummaryMessage {
|
|
|
51
51
|
|
|
52
52
|
export interface CompactionSummaryMessage {
|
|
53
53
|
role: "compactionSummary";
|
|
54
|
+
/** Runtime replay state: a spoken delegation was still open at the retained-history boundary. */
|
|
55
|
+
liveVoiceOpen?: true;
|
|
54
56
|
summary: string;
|
|
55
57
|
shortSummary?: string;
|
|
56
58
|
tokensBefore: number;
|
package/src/compaction/shake.ts
CHANGED
|
@@ -75,7 +75,7 @@ export const RESCUE_SHAKE_CONFIG: ShakeConfig = {
|
|
|
75
75
|
protectedTools: [...AGGRESSIVE_SHAKE_CONFIG.protectedTools, isArtifactRecoveryToolResult],
|
|
76
76
|
};
|
|
77
77
|
|
|
78
|
-
/** Rough token cost of a placeholder line;
|
|
78
|
+
/** Rough token cost of a placeholder line; floors tool-result regions and feeds the savings gate. */
|
|
79
79
|
const PLACEHOLDER_TOKEN_ESTIMATE = 16;
|
|
80
80
|
|
|
81
81
|
/** A located eligible region. */
|
|
@@ -347,6 +347,8 @@ export function collectShakeRegions(entries: SessionEntry[], tokenizer: Tokenize
|
|
|
347
347
|
continue;
|
|
348
348
|
const text = toolResultText(toolResult, tokenizer);
|
|
349
349
|
if (!text) continue;
|
|
350
|
+
// Replacing a result no larger than its placeholder only grows context.
|
|
351
|
+
if (text.tokens <= PLACEHOLDER_TOKEN_ESTIMATE) continue;
|
|
350
352
|
regions.push({
|
|
351
353
|
kind: "toolResult",
|
|
352
354
|
entry: entry as SessionMessageEntry,
|
package/src/index.ts
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
export * from "./agent";
|
|
3
3
|
// Loop functions
|
|
4
4
|
export * from "./agent-loop";
|
|
5
|
+
// Owner-worded tool descriptions a fork sends to share its owner's cached prefix
|
|
6
|
+
export * from "./inherited-tool-descriptions";
|
|
5
7
|
// Append-only context mode
|
|
6
8
|
export * from "./append-only-context";
|
|
7
9
|
// Compaction
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { Tool } from "@oh-my-pi/pi-ai";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Tool descriptions a fork sends in its owner's wording, so its requests open
|
|
5
|
+
* with the owner's cached prefix.
|
|
6
|
+
*
|
|
7
|
+
* A fork (`/tan`) continues its owner's transcript, but its tools render their
|
|
8
|
+
* descriptions from session state it does not share: no UI, no TUI transcript,
|
|
9
|
+
* a headless approval mode. Any byte of that drift sits ahead of the transcript,
|
|
10
|
+
* so the fork misses the owner's prompt cache entirely and, on prefix-bound
|
|
11
|
+
* reasoning (Claude, GPT-6.2), the provider drops every inherited thinking block.
|
|
12
|
+
*
|
|
13
|
+
* Only wording is inherited: a tool whose wire schema differs from the owner's
|
|
14
|
+
* keeps its own spec, so the model never sees arguments the fork's tool rejects.
|
|
15
|
+
* A pin holds while the fork's own description still renders as it did when
|
|
16
|
+
* pinned; once it changes (a setting, an MCP reload), the fork's own wording wins.
|
|
17
|
+
*/
|
|
18
|
+
export class InheritedToolDescriptions {
|
|
19
|
+
#byName = new Map<string, { own: string; owner: string }>();
|
|
20
|
+
|
|
21
|
+
/** Pin `owner`'s description of every tool `own` declares with the same wire schema but other wording. */
|
|
22
|
+
constructor(own: readonly Tool[], owner: readonly Tool[]) {
|
|
23
|
+
const ownerByName = new Map(owner.map(tool => [tool.name, tool]));
|
|
24
|
+
for (const tool of own) {
|
|
25
|
+
const ownerTool = ownerByName.get(tool.name);
|
|
26
|
+
if (!ownerTool || ownerTool.description === tool.description) continue;
|
|
27
|
+
if (wireShape(ownerTool) !== wireShape(tool)) continue;
|
|
28
|
+
this.#byName.set(tool.name, { own: tool.description, owner: ownerTool.description });
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The description to send for `name`, given the one the fork renders now. */
|
|
33
|
+
resolve(name: string, description: string): string {
|
|
34
|
+
const pin = this.#byName.get(name);
|
|
35
|
+
return pin?.own === description ? pin.owner : description;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Every wire field of `tool` except its description. */
|
|
40
|
+
function wireShape(tool: Tool): string {
|
|
41
|
+
const { description: _, ...shape } = tool;
|
|
42
|
+
return JSON.stringify(shape);
|
|
43
|
+
}
|
package/src/telemetry.ts
CHANGED
|
@@ -616,8 +616,6 @@ function mapProviderNameToOtel(provider: string | undefined): string | undefined
|
|
|
616
616
|
case "amazon-bedrock":
|
|
617
617
|
return "aws.bedrock";
|
|
618
618
|
case "google":
|
|
619
|
-
case "google-antigravity":
|
|
620
|
-
case "google-gemini-cli":
|
|
621
619
|
return "gcp.gemini";
|
|
622
620
|
case "google-vertex":
|
|
623
621
|
return "gcp.vertex_ai";
|
|
@@ -1161,7 +1159,7 @@ export async function finishChatSpan(
|
|
|
1161
1159
|
},
|
|
1162
1160
|
): Promise<void> {
|
|
1163
1161
|
if (!span) return;
|
|
1164
|
-
applyChatResponseAttributes(span, message);
|
|
1162
|
+
applyChatResponseAttributes(span, message, options.modelId);
|
|
1165
1163
|
applyUsageAttributes(span, message.usage);
|
|
1166
1164
|
applyGatewayAttributes(span, options.responseHeaders, options.baseUrl);
|
|
1167
1165
|
const cost = applyCostEstimate(telemetry, span, message, options.serviceTier, options.stepNumber, options.modelId);
|
|
@@ -1232,8 +1230,11 @@ export function failChatSpan(
|
|
|
1232
1230
|
span.end();
|
|
1233
1231
|
}
|
|
1234
1232
|
|
|
1235
|
-
function applyChatResponseAttributes(span: Span, message: AssistantMessage): void {
|
|
1236
|
-
|
|
1233
|
+
function applyChatResponseAttributes(span: Span, message: AssistantMessage, requestedModelId?: string): void {
|
|
1234
|
+
// A provider that promoted `model` to a served fallback has named the serving model;
|
|
1235
|
+
// `upstreamModel` can still hold the declined primary's signed id.
|
|
1236
|
+
const promoted = requestedModelId !== undefined && message.model !== requestedModelId;
|
|
1237
|
+
span.setAttribute(GenAIAttr.ResponseModel, promoted ? message.model : (message.upstreamModel ?? message.model));
|
|
1237
1238
|
if (message.responseId) span.setAttribute(GenAIAttr.ResponseId, message.responseId);
|
|
1238
1239
|
if (message.upstreamProvider) {
|
|
1239
1240
|
span.setAttribute(OmpGenAIAttr.ResponseUpstreamProvider, message.upstreamProvider);
|
package/src/tokenizer.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Api, AssistantMessage, Model } from "@oh-my-pi/pi-ai";
|
|
1
|
+
import type { Api, AssistantMessage, ImageContent, Model } from "@oh-my-pi/pi-ai";
|
|
2
2
|
import { renderDemotedThinking } from "@oh-my-pi/pi-ai/dialect/demotion";
|
|
3
3
|
import { isFactoryDroidGeminiWire, keepsFactoryGeminiReasoning } from "@oh-my-pi/pi-ai/providers/factory-droid/gemini";
|
|
4
4
|
import { ollamaChatDropsOwnThinking } from "@oh-my-pi/pi-ai/providers/ollama";
|
|
@@ -17,7 +17,7 @@ import { replaysSignedReasoningText } from "@oh-my-pi/pi-ai/utils/reasoning-sour
|
|
|
17
17
|
import { resolveThinkingReplayTokens, type ThinkingReplayTokens } from "@oh-my-pi/pi-catalog/compat/thinking-replay";
|
|
18
18
|
import type { ModelTokenizer } from "@oh-my-pi/pi-catalog/types";
|
|
19
19
|
import * as natives from "@oh-my-pi/pi-natives";
|
|
20
|
-
import { materializeString, stringifyJson } from "@oh-my-pi/pi-utils";
|
|
20
|
+
import { isRecord, materializeString, stringifyJson } from "@oh-my-pi/pi-utils";
|
|
21
21
|
import { LRUCache } from "@oh-my-pi/pi-utils/lru";
|
|
22
22
|
import * as snapcompact from "@oh-my-pi/snapcompact";
|
|
23
23
|
import { isEstimateCacheable, messageEstimateVersion } from "./compaction/message-cache";
|
|
@@ -174,6 +174,11 @@ function sumFragments(text: string | string[], perFragment: (t: string) => numbe
|
|
|
174
174
|
return Array.isArray(text) ? text.reduce((sum, t) => sum + perFragment(t), 0) : perFragment(text);
|
|
175
175
|
}
|
|
176
176
|
|
|
177
|
+
/** Whether `value`, a field of an app role read as data, is an image block a request can carry. */
|
|
178
|
+
function isImageBlock(value: unknown): value is ImageContent {
|
|
179
|
+
return isRecord(value) && value.type === "image" && typeof value.data === "string";
|
|
180
|
+
}
|
|
181
|
+
|
|
177
182
|
interface NativeTokenCount {
|
|
178
183
|
tokens: number;
|
|
179
184
|
exact: boolean;
|
|
@@ -417,6 +422,11 @@ export class Tokenizer {
|
|
|
417
422
|
return estimateImageTokens(size, detail, this.#frameBilling.rule);
|
|
418
423
|
}
|
|
419
424
|
|
|
425
|
+
/** {@link imageTokens} for an image block a request carries. */
|
|
426
|
+
#imageBlockTokens(image: ImageContent): number {
|
|
427
|
+
return this.imageTokens(base64ImageSize(image.data), image.detail);
|
|
428
|
+
}
|
|
429
|
+
|
|
420
430
|
/**
|
|
421
431
|
* Whether `message`'s signed reasoning reaches this reader natively: from
|
|
422
432
|
* the same model, host and wire, or from another Claude model on the same
|
|
@@ -469,25 +479,21 @@ export class Tokenizer {
|
|
|
469
479
|
}
|
|
470
480
|
|
|
471
481
|
#measureMessage(message: AgentMessage, excludeEncryptedReasoning: boolean, latestTurn: boolean): number {
|
|
482
|
+
const appTokens = this.#measureAppMessage(message);
|
|
483
|
+
if (appTokens !== undefined) return appTokens;
|
|
472
484
|
const fragments: string[] = [];
|
|
473
485
|
let extra = 0;
|
|
474
|
-
// Declaration-merged app roles (the coding-agent's bashExecution) are
|
|
475
|
-
// invisible to this package's union, so the discriminant is read as data.
|
|
476
|
-
const role: string = message.role;
|
|
477
|
-
if (role === "bashExecution") {
|
|
478
|
-
if ("command" in message && typeof message.command === "string") fragments.push(message.command);
|
|
479
|
-
if ("output" in message && typeof message.output === "string") fragments.push(message.output);
|
|
480
|
-
return fragments.length === 0 ? 0 : this.countTokens(fragments);
|
|
481
|
-
}
|
|
482
486
|
|
|
483
487
|
switch (message.role) {
|
|
484
488
|
case "user":
|
|
485
|
-
case "developer":
|
|
486
|
-
|
|
489
|
+
case "developer":
|
|
490
|
+
case "custom":
|
|
491
|
+
case "hookMessage": {
|
|
492
|
+
// All four roles carry `string | (TextContent | ImageContent)[]` and all are
|
|
487
493
|
// sent to the provider -- convertMessageToLlm handles developer alongside
|
|
488
|
-
// user -- so they are counted alike.
|
|
489
|
-
//
|
|
490
|
-
//
|
|
494
|
+
// user -- so they are counted alike. Content that is neither (a malformed
|
|
495
|
+
// persisted custom message) is in no request: the coding-agent's
|
|
496
|
+
// `convertToLlm` drops it, and it counts 0.
|
|
491
497
|
const content = message.content;
|
|
492
498
|
if (typeof content === "string") {
|
|
493
499
|
fragments.push(content);
|
|
@@ -496,7 +502,7 @@ export class Tokenizer {
|
|
|
496
502
|
if (block.type === "text" && block.text) {
|
|
497
503
|
fragments.push(block.text);
|
|
498
504
|
} else if (block.type === "image") {
|
|
499
|
-
extra += this
|
|
505
|
+
extra += this.#imageBlockTokens(block);
|
|
500
506
|
}
|
|
501
507
|
}
|
|
502
508
|
}
|
|
@@ -637,8 +643,6 @@ export class Tokenizer {
|
|
|
637
643
|
}
|
|
638
644
|
break;
|
|
639
645
|
}
|
|
640
|
-
case "custom":
|
|
641
|
-
case "hookMessage":
|
|
642
646
|
case "toolResult": {
|
|
643
647
|
if (typeof message.content === "string") {
|
|
644
648
|
fragments.push(message.content);
|
|
@@ -647,7 +651,7 @@ export class Tokenizer {
|
|
|
647
651
|
if (block.type === "text" && block.text) {
|
|
648
652
|
fragments.push(block.text);
|
|
649
653
|
} else if (block.type === "image") {
|
|
650
|
-
extra += this
|
|
654
|
+
extra += this.#imageBlockTokens(block);
|
|
651
655
|
}
|
|
652
656
|
}
|
|
653
657
|
}
|
|
@@ -678,6 +682,52 @@ export class Tokenizer {
|
|
|
678
682
|
return extra + this.countTokens(fragments);
|
|
679
683
|
}
|
|
680
684
|
|
|
685
|
+
/**
|
|
686
|
+
* Tokens the coding-agent's `convertToLlm` sends for one of its app roles,
|
|
687
|
+
* or `undefined` for a role this package's union names. Declaration
|
|
688
|
+
* merging keeps those roles out of that union, so the discriminant and
|
|
689
|
+
* every field are read as data.
|
|
690
|
+
*
|
|
691
|
+
* - `bashExecution` and `pythonExecution` (`!` and `$`): one user message
|
|
692
|
+
* rendering the command or code and its output, beside a bash run's
|
|
693
|
+
* terminal images. A run excluded from context (`!!` and `$$`) is in no
|
|
694
|
+
* request and costs nothing.
|
|
695
|
+
* - `fileMention` (`@file`): each file's path and content, and each
|
|
696
|
+
* attached image at the rate the user arm charges it.
|
|
697
|
+
*
|
|
698
|
+
* The rendering's fixed framing (the `Ran` lead-in, code fences, `<file>`
|
|
699
|
+
* tags, exit and truncation notices) adds a few tokens per message that
|
|
700
|
+
* this leaves out.
|
|
701
|
+
*/
|
|
702
|
+
#measureAppMessage(message: AgentMessage): number | undefined {
|
|
703
|
+
const role: string = message.role;
|
|
704
|
+
const execution = role === "bashExecution" || role === "pythonExecution";
|
|
705
|
+
if (!execution && role !== "fileMention") return undefined;
|
|
706
|
+
if (execution && "excludeFromContext" in message && message.excludeFromContext) return 0;
|
|
707
|
+
const fragments: string[] = [];
|
|
708
|
+
let extra = 0;
|
|
709
|
+
if (execution) {
|
|
710
|
+
if ("command" in message && typeof message.command === "string") fragments.push(message.command);
|
|
711
|
+
if ("code" in message && typeof message.code === "string") fragments.push(message.code);
|
|
712
|
+
if ("output" in message && typeof message.output === "string") fragments.push(message.output);
|
|
713
|
+
if (role === "bashExecution" && "images" in message && Array.isArray(message.images)) {
|
|
714
|
+
const images: readonly unknown[] = message.images;
|
|
715
|
+
for (const image of images) {
|
|
716
|
+
if (isImageBlock(image)) extra += this.#imageBlockTokens(image);
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
} else if ("files" in message && Array.isArray(message.files)) {
|
|
720
|
+
const files: readonly unknown[] = message.files;
|
|
721
|
+
for (const file of files) {
|
|
722
|
+
if (!isRecord(file)) continue;
|
|
723
|
+
if (typeof file.path === "string") fragments.push(file.path);
|
|
724
|
+
if (typeof file.content === "string") fragments.push(file.content);
|
|
725
|
+
if (isImageBlock(file.image)) extra += this.#imageBlockTokens(file.image);
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
return fragments.length === 0 ? extra : extra + this.countTokens(fragments);
|
|
729
|
+
}
|
|
730
|
+
|
|
681
731
|
/**
|
|
682
732
|
* Input tokens this reader bills for replaying `message`'s native Responses
|
|
683
733
|
* reasoning; `undefined` when the reader re-encodes the turn from its
|
package/src/types.ts
CHANGED
|
@@ -25,6 +25,7 @@ import type { Dialect } from "@oh-my-pi/pi-ai/dialect";
|
|
|
25
25
|
import type { HarmonyAuditEvent } from "@oh-my-pi/pi-ai/utils/harmony-leak";
|
|
26
26
|
import type { AppendOnlyContextManager } from "./append-only-context";
|
|
27
27
|
import type { AgentRunCoverage, AgentRunSummary } from "./run-collector";
|
|
28
|
+
import type { InheritedToolDescriptions } from "./inherited-tool-descriptions";
|
|
28
29
|
import type { SentToolDefinitions } from "./sent-tool-definitions";
|
|
29
30
|
import type { AgentTelemetryConfig } from "./telemetry";
|
|
30
31
|
|
|
@@ -101,6 +102,8 @@ export interface AgentTurnEndContext {
|
|
|
101
102
|
additionalMessages?: AgentMessage[];
|
|
102
103
|
/** True when the current tool-loop batch is continuing without yielding to post-turn steering. */
|
|
103
104
|
willContinue: boolean;
|
|
105
|
+
/** Tool calls in `message` that resolved to no tool (unknown name), so nothing ran. */
|
|
106
|
+
unresolvedToolCallIds?: string[];
|
|
104
107
|
}
|
|
105
108
|
|
|
106
109
|
export interface AgentPreModelCallStop {
|
|
@@ -288,6 +291,9 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
|
288
291
|
/** Remembers sent tool definitions to fill {@link Context.inactiveTools}. */
|
|
289
292
|
sentToolDefinitions?: SentToolDefinitions;
|
|
290
293
|
|
|
294
|
+
/** A fork's owner-worded tool descriptions; see {@link InheritedToolDescriptions}. */
|
|
295
|
+
inheritedToolDescriptions?: InheritedToolDescriptions;
|
|
296
|
+
|
|
291
297
|
/**
|
|
292
298
|
* Resolves the API key or resolver for the current model before each LLM call.
|
|
293
299
|
*
|
|
@@ -1124,7 +1130,7 @@ export type ToolLoadMode = "essential" | "discoverable";
|
|
|
1124
1130
|
* - object form — adds a `reason` (shown in the prompt) and/or `override: true`
|
|
1125
1131
|
* (force-prompt even in modes that would otherwise auto-approve this tier).
|
|
1126
1132
|
* `policy: "deny"` blocks the call at the approval gate.
|
|
1127
|
-
* - function — dynamic, given parsed args. Returns either form above.
|
|
1133
|
+
* - function — dynamic, given parsed args and an optional {@link ToolApprovalQuery}. Returns either form above.
|
|
1128
1134
|
*
|
|
1129
1135
|
* Omitted approvals are treated as "exec" by callers that enforce approvals.
|
|
1130
1136
|
*/
|
|
@@ -1136,7 +1142,19 @@ export type ToolApprovalDecision =
|
|
|
1136
1142
|
override?: boolean;
|
|
1137
1143
|
policy?: "allow" | "deny" | "prompt";
|
|
1138
1144
|
};
|
|
1139
|
-
export type ToolApproval =
|
|
1145
|
+
export type ToolApproval =
|
|
1146
|
+
| ToolApprovalDecision
|
|
1147
|
+
| ((args: unknown, context?: AgentToolContext, query?: ToolApprovalQuery) => ToolApprovalDecision);
|
|
1148
|
+
|
|
1149
|
+
/** How the caller of a dynamic {@link ToolApproval} uses its decision. */
|
|
1150
|
+
export interface ToolApprovalQuery {
|
|
1151
|
+
/**
|
|
1152
|
+
* `false` when only `tier` and an explicit `policy` can affect the outcome: the gate
|
|
1153
|
+
* auto-approves every tier (yolo), or the caller reads just the tier. The tool may then
|
|
1154
|
+
* skip work that only feeds a prompt (`override`, `reason`). Absent means it may prompt.
|
|
1155
|
+
*/
|
|
1156
|
+
prompts?: boolean;
|
|
1157
|
+
}
|
|
1140
1158
|
|
|
1141
1159
|
/**
|
|
1142
1160
|
* Context passed to tool execution.
|