@oh-my-pi/pi-agent-core 19.0.1 → 19.1.1
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 +14 -0
- package/dist/types/agent-loop.d.ts +5 -0
- package/dist/types/agent.d.ts +6 -4
- package/dist/types/output-budget.d.ts +13 -0
- package/dist/types/sent-tool-definitions.d.ts +6 -3
- package/dist/types/tool-arguments.d.ts +2 -1
- package/dist/types/types.d.ts +26 -16
- package/package.json +8 -8
- package/src/agent-loop.ts +41 -28
- package/src/agent.ts +45 -17
- package/src/compaction/compaction-v2-streaming.ts +0 -1
- package/src/compaction/compaction.ts +8 -0
- package/src/output-budget.ts +31 -2
- package/src/sent-tool-definitions.ts +20 -10
- package/src/speculative-execution.ts +29 -5
- package/src/tokenizer.ts +10 -2
- package/src/tool-arguments.ts +2 -1
- package/src/types.ts +26 -16
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,20 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [19.1.1] - 2026-11-23
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
|
|
9
|
+
- Prevented oversized handoffs from reaching the provider by detecting when prepared context exceeds the target model’s context window.
|
|
10
|
+
- Preserved provider error status, error identifiers, retry classification, and cancellation markers on failed or cancelled assistant turns.
|
|
11
|
+
- Fixed speculative tool calls hanging when discarded or aborted before execution completed.
|
|
12
|
+
|
|
13
|
+
## [19.1.0] - 2026-11-21
|
|
14
|
+
|
|
15
|
+
### Added
|
|
16
|
+
|
|
17
|
+
- Added standby tools support through `Agent.setStandbyTools()` and `AgentContext.standbyTools`, allowing tools to remain inactive until a request explicitly enables tool use.
|
|
18
|
+
|
|
5
19
|
## [19.0.0] - 2026-11-18
|
|
6
20
|
|
|
7
21
|
### Added
|
|
@@ -123,6 +123,11 @@ export interface NormalizeToolsOptions {
|
|
|
123
123
|
pruneDescriptions?: boolean;
|
|
124
124
|
}
|
|
125
125
|
export declare function normalizeTools(tools: AgentContext["tools"], options: NormalizeToolsOptions): Context["tools"];
|
|
126
|
+
/** Split a traced call's intent (`i`, trimmed, trailing periods dropped) from the arguments its tool reads. */
|
|
127
|
+
export declare function extractIntent(args: Record<string, unknown>): {
|
|
128
|
+
intent?: string;
|
|
129
|
+
strippedArgs: Record<string, unknown>;
|
|
130
|
+
};
|
|
126
131
|
/**
|
|
127
132
|
* Classify the first `count` steering messages for a tool-batch interrupt:
|
|
128
133
|
* any user-authored message wins, then agent-attributed user messages, else
|
package/dist/types/agent.d.ts
CHANGED
|
@@ -145,14 +145,14 @@ export interface AgentOptions {
|
|
|
145
145
|
speculativeToolExecution?: SpeculativeToolExecutionConfig;
|
|
146
146
|
/**
|
|
147
147
|
* Resolve a tool call whose name matched no advertised tool. Lets hosts
|
|
148
|
-
* route calls to tools
|
|
149
|
-
*
|
|
148
|
+
* route calls to tools reached through a side transport (e.g. mounted
|
|
149
|
+
* tool commands run through `bash`) instead of failing with "Tool not found".
|
|
150
150
|
*/
|
|
151
151
|
resolveFallbackTool?: (name: string, advertised: readonly AgentTool<any>[]) => AgentTool<any> | undefined;
|
|
152
152
|
/**
|
|
153
153
|
* Names routable by {@link resolveFallbackTool} that the advertised set
|
|
154
|
-
* omits (e.g.
|
|
155
|
-
* call misses.
|
|
154
|
+
* omits (e.g. mounted tool commands run through `bash`), used only to
|
|
155
|
+
* suggest a target when a call misses.
|
|
156
156
|
*/
|
|
157
157
|
suggestFallbackToolNames?: () => Iterable<string>;
|
|
158
158
|
/** Enable intent tracing schema injection/stripping in the harness. */
|
|
@@ -525,6 +525,8 @@ export declare class Agent {
|
|
|
525
525
|
setInterruptMode(mode: "immediate" | "wait"): void;
|
|
526
526
|
getInterruptMode(): "immediate" | "wait";
|
|
527
527
|
setTools(t: AgentTool<any>[]): void;
|
|
528
|
+
/** Set the inactive tools that may become active later ({@link AgentContext.standbyTools}). */
|
|
529
|
+
setStandbyTools(tools: AgentTool[]): void;
|
|
528
530
|
replaceMessages(ms: AgentMessage[]): void;
|
|
529
531
|
replaceQueues(steering: AgentMessage[], followUp: AgentMessage[]): void;
|
|
530
532
|
/**
|
|
@@ -62,3 +62,16 @@ export declare const OUTPUT_FIT_HEADWAY_TOKENS = 64;
|
|
|
62
62
|
* and the request can still exceed the window as before.
|
|
63
63
|
*/
|
|
64
64
|
export declare function fitOutputTokensToContextWindow(model: Model, context: Context, maxTokens: number | undefined, tokenizer: Tokenizer): number | undefined;
|
|
65
|
+
/**
|
|
66
|
+
* Local prompt count of `context` when it leaves `model` no room for the
|
|
67
|
+
* smallest output the transport requests, else `undefined` (also when the
|
|
68
|
+
* window is unknown). Counting stops at the first message past the window, so
|
|
69
|
+
* the count is a floor.
|
|
70
|
+
*
|
|
71
|
+
* Unlike {@link fitOutputTokensToContextWindow}, no usage anchor is trusted:
|
|
72
|
+
* history re-expanded behind a native compaction the model cannot replay
|
|
73
|
+
* carries reports describing the compacted prefix. Nor is a tokenizer margin
|
|
74
|
+
* added: a caller refuses on this verdict, so only a clear overrun counts, and
|
|
75
|
+
* a near-full request is still left to the provider.
|
|
76
|
+
*/
|
|
77
|
+
export declare function countContextOverrun(context: Context, model: Model, tokenizer: Tokenizer): number | undefined;
|
|
@@ -16,8 +16,11 @@ export declare class SentToolDefinitions {
|
|
|
16
16
|
/**
|
|
17
17
|
* `context` with {@link Context.inactiveTools} set to the definitions for names the latest
|
|
18
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.
|
|
20
|
-
*
|
|
19
|
+
* there are none or the request declares no tools. A declared name this Agent never sent takes its
|
|
20
|
+
* `standby` definition (a resumed transcript declares standby tools a fresh process has not sent);
|
|
21
|
+
* names with neither are skipped, and the provider drops them from the declaration. Before any
|
|
22
|
+
* request declared tools, `standby` (minus active names) stands in, so the first declaration
|
|
23
|
+
* already holds tools that may activate later.
|
|
21
24
|
*/
|
|
22
|
-
withInactiveTools(context: Context): Context;
|
|
25
|
+
withInactiveTools(context: Context, standby?: readonly Tool[]): Context;
|
|
23
26
|
}
|
|
@@ -5,7 +5,8 @@ import type { AgentTool } from "./types.js";
|
|
|
5
5
|
* - `"parsed"`: a provider stream parsed the arguments, so `__parseError` is a
|
|
6
6
|
* genuine parse-failure sentinel and is never handed to a tool.
|
|
7
7
|
* - `"payload"`: the arguments are a payload the model wrote (eval tool bridge,
|
|
8
|
-
*
|
|
8
|
+
* a tool command line parsed into arguments), so those keys are forged and
|
|
9
|
+
* only stripped.
|
|
9
10
|
*/
|
|
10
11
|
export type ToolArgumentSource = "parsed" | "payload";
|
|
11
12
|
/**
|
package/dist/types/types.d.ts
CHANGED
|
@@ -101,8 +101,8 @@ export interface SoftToolRequirement {
|
|
|
101
101
|
/**
|
|
102
102
|
* Per-call compliance check: a turn satisfies the requirement only when every
|
|
103
103
|
* tool call passes. Defaults to `name === toolName`. Lets a host demand a
|
|
104
|
-
* specific invocation shape (e.g. `
|
|
105
|
-
* instead of any call to `toolName`. Escalation still forces `toolName`.
|
|
104
|
+
* specific invocation shape (e.g. a `bash` call running a particular tool
|
|
105
|
+
* command) instead of any call to `toolName`. Escalation still forces `toolName`.
|
|
106
106
|
*/
|
|
107
107
|
satisfies?(toolCall: {
|
|
108
108
|
name: string;
|
|
@@ -384,8 +384,8 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
|
384
384
|
/**
|
|
385
385
|
* Resolve a tool call whose name matched no advertised tool (including
|
|
386
386
|
* `customWireName` aliases). Lets hosts route calls to tools they expose
|
|
387
|
-
* through side
|
|
388
|
-
* with "Tool not found". Returning `undefined` keeps the failure.
|
|
387
|
+
* through a side transport (e.g. mounted tool commands run through `bash`)
|
|
388
|
+
* instead of failing with "Tool not found". Returning `undefined` keeps the failure.
|
|
389
389
|
*
|
|
390
390
|
* `advertised` is the very snapshot exact-name dispatch just searched — the
|
|
391
391
|
* set offered to THIS request. A host must resolve against it rather than
|
|
@@ -397,9 +397,9 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
|
397
397
|
resolveFallbackTool?: (name: string, advertised: readonly AgentTool<any>[]) => AgentTool<any> | undefined;
|
|
398
398
|
/**
|
|
399
399
|
* Names reachable through {@link resolveFallbackTool} but absent from the
|
|
400
|
-
* advertised set (e.g.
|
|
401
|
-
* plausible target when a call misses, so a mis-transcribed
|
|
402
|
-
* recoverable; never a dispatch source.
|
|
400
|
+
* advertised set (e.g. mounted tool commands run through `bash`). Consulted
|
|
401
|
+
* only to name a plausible target when a call misses, so a mis-transcribed
|
|
402
|
+
* command name is recoverable; never a dispatch source.
|
|
403
403
|
*/
|
|
404
404
|
suggestFallbackToolNames?: () => Iterable<string>;
|
|
405
405
|
/**
|
|
@@ -552,6 +552,8 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
|
552
552
|
* post-turn steering.
|
|
553
553
|
*/
|
|
554
554
|
onTurnEnd?: (messages: AgentMessage[], signal?: AbortSignal, context?: AgentTurnEndContext) => Promise<void> | void;
|
|
555
|
+
/** Called synchronously when the loop pushes `turn_end` onto the event stream. */
|
|
556
|
+
onTurnEndEmitted?: () => void;
|
|
555
557
|
/**
|
|
556
558
|
* Called once an assistant message is finalized from the model stream, before
|
|
557
559
|
* it is appended to the context, emitted as `message_end`, or its tool calls
|
|
@@ -969,9 +971,9 @@ export type ToolTier = "read" | "write" | "exec";
|
|
|
969
971
|
/**
|
|
970
972
|
* How an enabled tool is presented to the model. `"essential"` tools are exposed
|
|
971
973
|
* as normal top-level tools. `"discoverable"` tools are removed from the top-level
|
|
972
|
-
* schema and either mounted
|
|
973
|
-
* active) or surfaced through BM25 tool search — keeping their schemas
|
|
974
|
-
* request. Selection (settings, `hidden`, `defaultInactive`, explicit `--tools`,
|
|
974
|
+
* schema and either mounted as a tool command in the `bash` tool (when that
|
|
975
|
+
* tool is active) or surfaced through BM25 tool search — keeping their schemas
|
|
976
|
+
* off every request. Selection (settings, `hidden`, `defaultInactive`, explicit `--tools`,
|
|
975
977
|
* provider availability) decides whether a tool is enabled; `loadMode` only
|
|
976
978
|
* decides how an enabled tool is presented.
|
|
977
979
|
*/
|
|
@@ -991,11 +993,6 @@ export type ToolApprovalDecision = ToolTier | {
|
|
|
991
993
|
reason?: string;
|
|
992
994
|
override?: boolean;
|
|
993
995
|
policy?: "allow" | "deny" | "prompt";
|
|
994
|
-
/** User-policy key for this decision. When set, `tools.approval.<policyKey>`
|
|
995
|
-
* is consulted instead of `tools.approval.<tool.name>`. Lets a dispatcher
|
|
996
|
-
* tool (e.g. `write` for an `xd://` device call) scope user allow/deny/
|
|
997
|
-
* prompt policies to the tool it dispatches into. */
|
|
998
|
-
policyKey?: string;
|
|
999
996
|
};
|
|
1000
997
|
export type ToolApproval = ToolApprovalDecision | ((args: unknown, context?: AgentToolContext) => ToolApprovalDecision);
|
|
1001
998
|
/**
|
|
@@ -1054,9 +1051,16 @@ export interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any
|
|
|
1054
1051
|
* obtains by delegating to this native tool through `ctx.invokeTool` follow this tool's contract.
|
|
1055
1052
|
*/
|
|
1056
1053
|
readonly delegationGuidance?: string;
|
|
1054
|
+
/**
|
|
1055
|
+
* Whether `command` is traffic this tool must run itself rather than shell work: the transport
|
|
1056
|
+
* host (`bash`) answers true for a line made only of session tool commands, which nothing else
|
|
1057
|
+
* can dispatch. A same-name extension replacement routes such a call back here instead of
|
|
1058
|
+
* executing it, so mounted tools keep working behind an override that does not delegate.
|
|
1059
|
+
*/
|
|
1060
|
+
servesToolCommandLine?(command: string): boolean;
|
|
1057
1061
|
/**
|
|
1058
1062
|
* On-demand documentation topics (`topic → markdown`), readable as
|
|
1059
|
-
* `
|
|
1063
|
+
* `help://<tool>/<topic>`. Lets a tool keep large sub-surfaces out of its
|
|
1060
1064
|
* description and advertise only a one-line pointer per topic.
|
|
1061
1065
|
*/
|
|
1062
1066
|
docTopics?(): Readonly<Record<string, string>>;
|
|
@@ -1164,6 +1168,12 @@ export interface AgentContext {
|
|
|
1164
1168
|
systemPrompt: string[];
|
|
1165
1169
|
messages: AgentMessage[];
|
|
1166
1170
|
tools?: AgentTool<any>[];
|
|
1171
|
+
/**
|
|
1172
|
+
* Inactive tools that may become active later in the conversation. A provider that announces tool changes
|
|
1173
|
+
* in-band (Anthropic `tool_addition`) declares them from the first request, so activating one leaves the
|
|
1174
|
+
* cached prefix intact. See {@link SentToolDefinitions.withInactiveTools}.
|
|
1175
|
+
*/
|
|
1176
|
+
standbyTools?: AgentTool<any>[];
|
|
1167
1177
|
}
|
|
1168
1178
|
/**
|
|
1169
1179
|
* Events emitted by the Agent for UI updates.
|
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.1.1",
|
|
5
5
|
"description": "General-purpose agent with transport abstraction, state management, and attachment support",
|
|
6
6
|
"homepage": "https://omp.sh",
|
|
7
7
|
"author": {
|
|
@@ -38,16 +38,16 @@
|
|
|
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.
|
|
41
|
+
"@oh-my-pi/pi-ai": "19.1.1",
|
|
42
|
+
"@oh-my-pi/pi-catalog": "19.1.1",
|
|
43
|
+
"@oh-my-pi/pi-natives": "19.1.1",
|
|
44
|
+
"@oh-my-pi/pi-utils": "19.1.1",
|
|
45
|
+
"@oh-my-pi/pi-wire": "19.1.1",
|
|
46
|
+
"@oh-my-pi/snapcompact": "19.1.1",
|
|
47
47
|
"@opentelemetry/api": "^1.9.1"
|
|
48
48
|
},
|
|
49
49
|
"devDependencies": {
|
|
50
|
-
"@oh-my-pi/omptype": "19.
|
|
50
|
+
"@oh-my-pi/omptype": "19.1.1",
|
|
51
51
|
"@opentelemetry/context-async-hooks": "2.9.0",
|
|
52
52
|
"@opentelemetry/sdk-trace-base": "2.9.0",
|
|
53
53
|
"@types/bun": "^1.3.14"
|
package/src/agent-loop.ts
CHANGED
|
@@ -826,6 +826,7 @@ async function emitTurnEnd(
|
|
|
826
826
|
runHookOnAbortedMessage = false,
|
|
827
827
|
): Promise<void> {
|
|
828
828
|
stream.push({ type: "turn_end", message, toolResults });
|
|
829
|
+
config.onTurnEndEmitted?.();
|
|
829
830
|
const terminalYield = signal?.reason === TERMINAL_TOOL_RESULT_ABORT_REASON;
|
|
830
831
|
const isAbortedOrError =
|
|
831
832
|
message.role === "assistant" && (message.stopReason === "aborted" || message.stopReason === "error");
|
|
@@ -1117,7 +1118,11 @@ function resolveIntentMode(intent: AgentTool["intent"]): "require" | "optional"
|
|
|
1117
1118
|
return "require";
|
|
1118
1119
|
}
|
|
1119
1120
|
|
|
1120
|
-
|
|
1121
|
+
/** Split a traced call's intent (`i`, trimmed, trailing periods dropped) from the arguments its tool reads. */
|
|
1122
|
+
export function extractIntent(args: Record<string, unknown>): {
|
|
1123
|
+
intent?: string;
|
|
1124
|
+
strippedArgs: Record<string, unknown>;
|
|
1125
|
+
} {
|
|
1121
1126
|
const { [INTENT_FIELD]: intent, ...strippedArgs } = args;
|
|
1122
1127
|
if (typeof intent !== "string") {
|
|
1123
1128
|
return { strippedArgs };
|
|
@@ -2039,29 +2044,33 @@ async function prepareProviderCall(
|
|
|
2039
2044
|
const normalizedMessages = normalizeMessagesForProvider(llmMessages, model);
|
|
2040
2045
|
const ownedDialect: Dialect | undefined =
|
|
2041
2046
|
(config.getDialect ? config.getDialect(model) : config.dialect) ?? resolveOwnedDialectFromEnv(Bun.env.PI_DIALECT);
|
|
2042
|
-
const
|
|
2047
|
+
const toolOptions: NormalizeToolsOptions = {
|
|
2048
|
+
injectIntent: !!config.intentTracing,
|
|
2049
|
+
intentDescription: config.intentDescription,
|
|
2050
|
+
pruneDescriptions: !!config.pruneToolDescriptions && !ownedDialect,
|
|
2051
|
+
};
|
|
2043
2052
|
let llmContext: Context;
|
|
2044
2053
|
if (config.appendOnlyContext) {
|
|
2045
2054
|
config.appendOnlyContext.syncMessages(normalizedMessages);
|
|
2046
2055
|
llmContext = config.appendOnlyContext.build(context, {
|
|
2047
|
-
intentTracing:
|
|
2048
|
-
intentDescription:
|
|
2049
|
-
pruneToolDescriptions,
|
|
2056
|
+
intentTracing: toolOptions.injectIntent,
|
|
2057
|
+
intentDescription: toolOptions.intentDescription,
|
|
2058
|
+
pruneToolDescriptions: toolOptions.pruneDescriptions,
|
|
2050
2059
|
});
|
|
2051
2060
|
} else {
|
|
2052
2061
|
llmContext = {
|
|
2053
2062
|
systemPrompt: context.systemPrompt,
|
|
2054
2063
|
messages: normalizedMessages,
|
|
2055
|
-
tools: normalizeTools(context.tools,
|
|
2056
|
-
injectIntent: !!config.intentTracing,
|
|
2057
|
-
intentDescription: config.intentDescription,
|
|
2058
|
-
pruneDescriptions: pruneToolDescriptions,
|
|
2059
|
-
}),
|
|
2064
|
+
tools: normalizeTools(context.tools, toolOptions),
|
|
2060
2065
|
};
|
|
2061
2066
|
}
|
|
2062
2067
|
// Before the transform too, so a request-size clamp in it measures the withdrawn definitions the provider
|
|
2063
|
-
// re-declares; recomputed below against what the transform returns.
|
|
2064
|
-
|
|
2068
|
+
// re-declares; recomputed below against what the transform returns. Standby tools are normalized like
|
|
2069
|
+
// `tools`, so a standby tool's definition matches the one it is sent with once active.
|
|
2070
|
+
if (config.sentToolDefinitions) {
|
|
2071
|
+
const standbyTools = normalizeTools(context.standbyTools, toolOptions);
|
|
2072
|
+
llmContext = config.sentToolDefinitions.withInactiveTools(llmContext, standbyTools);
|
|
2073
|
+
}
|
|
2065
2074
|
if (config.transformProviderContext) {
|
|
2066
2075
|
llmContext = await config.transformProviderContext(llmContext, model);
|
|
2067
2076
|
}
|
|
@@ -2079,7 +2088,9 @@ async function prepareProviderCall(
|
|
|
2079
2088
|
// After `transformProviderContext`, so the recorded definitions are exactly what the provider receives.
|
|
2080
2089
|
if (config.sentToolDefinitions) {
|
|
2081
2090
|
if (llmContext.tools) config.sentToolDefinitions.record(llmContext.tools);
|
|
2082
|
-
llmContext
|
|
2091
|
+
if (llmContext.inactiveTools) config.sentToolDefinitions.record(llmContext.inactiveTools);
|
|
2092
|
+
// The transformed standby definitions, when no request has declared tools yet.
|
|
2093
|
+
llmContext = config.sentToolDefinitions.withInactiveTools(llmContext, llmContext.inactiveTools);
|
|
2083
2094
|
}
|
|
2084
2095
|
return { model, context: llmContext, promptToolWireTools, ownedDialect };
|
|
2085
2096
|
}
|
|
@@ -2973,10 +2984,11 @@ function resolveToolForCall(
|
|
|
2973
2984
|
return (
|
|
2974
2985
|
tools?.find(t => t.name === toolCall.name) ??
|
|
2975
2986
|
tools?.find(t => t.customWireName !== undefined && t.customWireName === toolCall.name) ??
|
|
2976
|
-
// Not in the advertised set: let the host route
|
|
2977
|
-
// (e.g.
|
|
2978
|
-
//
|
|
2979
|
-
// mid-stream roster change cannot widen what
|
|
2987
|
+
// Not in the advertised set: let the host route tools reached through a
|
|
2988
|
+
// side transport (e.g. mounted tool commands run through `bash`) called
|
|
2989
|
+
// by their top-level name. It receives the snapshot searched above, never
|
|
2990
|
+
// the agent's live tools, so a mid-stream roster change cannot widen what
|
|
2991
|
+
// this request can reach.
|
|
2980
2992
|
resolveFallbackTool?.(toolCall.name, tools ?? [])
|
|
2981
2993
|
);
|
|
2982
2994
|
}
|
|
@@ -2997,9 +3009,10 @@ const MAX_TOOL_NAME_SUGGESTIONS = 3;
|
|
|
2997
3009
|
* Both the last `__` and last `_` boundary are tried, so a name that lost only
|
|
2998
3010
|
* its separator (`…__resolve_library_id`) and one that lost a whole id segment
|
|
2999
3011
|
* (`…__read`) both recover. `fallbackNames` adds targets the host can route but
|
|
3000
|
-
* never advertises (
|
|
3001
|
-
*
|
|
3002
|
-
* in the session yet appears in no
|
|
3012
|
+
* never advertises (tools reached only as mounted tool commands through
|
|
3013
|
+
* `bash`); without them a corrupted command name is the one miss with nothing
|
|
3014
|
+
* to suggest, because the capability exists in the session yet appears in no
|
|
3015
|
+
* advertised name. Purely advisory: this only
|
|
3003
3016
|
* builds an error string and never selects a tool, so dispatch semantics are
|
|
3004
3017
|
* unchanged.
|
|
3005
3018
|
*/
|
|
@@ -3175,8 +3188,8 @@ async function prepareToolCallDispatch(
|
|
|
3175
3188
|
if (toolCall.type !== "toolCall") continue;
|
|
3176
3189
|
if ((toolCall as CursorExecResolvedCarrier)[kCursorExecResolved] === true) continue;
|
|
3177
3190
|
const tool = resolveToolForCall(context.tools, toolCall, resolveFallbackTool);
|
|
3178
|
-
// A host fallback accepts aliases (`
|
|
3179
|
-
//
|
|
3191
|
+
// A host fallback accepts aliases (`recal`, a mis-separated MCP name)
|
|
3192
|
+
// that providers reject when replayed as a function-call name.
|
|
3180
3193
|
// Record the call under the resolved tool's canonical name so history,
|
|
3181
3194
|
// persistence, and replay agree; custom-wire calls keep their wire name.
|
|
3182
3195
|
if (tool && toolCall.name !== tool.name && toolCall.name !== tool.customWireName) {
|
|
@@ -3721,9 +3734,9 @@ async function executeToolCalls(
|
|
|
3721
3734
|
// ride the loop-owned ToolCallContext (surfacing as
|
|
3722
3735
|
// `ctx.toolCall.*`); the host surfaces the sink on the context it
|
|
3723
3736
|
// builds, and the loop hands that object to the tool untouched.
|
|
3724
|
-
// Wrapper-dispatched nested calls (for example `
|
|
3725
|
-
// inherit the context, so their
|
|
3726
|
-
// root call at the batch boundary.
|
|
3737
|
+
// Wrapper-dispatched nested calls (for example a `bash` call
|
|
3738
|
+
// running a mounted tool command) inherit the context, so their
|
|
3739
|
+
// passive hook context joins this root call at the batch boundary.
|
|
3727
3740
|
const toolContext = getToolContext?.({
|
|
3728
3741
|
batchId,
|
|
3729
3742
|
index,
|
|
@@ -4016,9 +4029,9 @@ async function executeToolCalls(
|
|
|
4016
4029
|
|
|
4017
4030
|
// Skipped calls never ran. Hook-prepared context also requires a non-error
|
|
4018
4031
|
// final result; context the tool itself reported during execution stands.
|
|
4019
|
-
// Within a call, tool-reported context (including nested
|
|
4020
|
-
// precedes the hook's: wrappers release hook context only after
|
|
4021
|
-
// succeeds, so this is the one order every dispatch path can produce.
|
|
4032
|
+
// Within a call, tool-reported context (including nested tool command
|
|
4033
|
+
// dispatch) precedes the hook's: wrappers release hook context only after
|
|
4034
|
+
// the call succeeds, so this is the one order every dispatch path can produce.
|
|
4022
4035
|
const additionalContext = joinAdditionalContext(
|
|
4023
4036
|
records
|
|
4024
4037
|
.filter(record => !record.skipped)
|
package/src/agent.ts
CHANGED
|
@@ -23,6 +23,7 @@ import {
|
|
|
23
23
|
type ToolResultMessage,
|
|
24
24
|
} from "@oh-my-pi/pi-ai";
|
|
25
25
|
import type { Dialect } from "@oh-my-pi/pi-ai/dialect";
|
|
26
|
+
import * as AIError from "@oh-my-pi/pi-ai/error";
|
|
26
27
|
import { openAIResponsesReplaysNativeHistory } from "@oh-my-pi/pi-ai/providers/openai-responses-state";
|
|
27
28
|
import type { HarmonyAuditEvent } from "@oh-my-pi/pi-ai/utils/harmony-leak";
|
|
28
29
|
import { getBundledModel } from "@oh-my-pi/pi-catalog/models";
|
|
@@ -33,6 +34,7 @@ import {
|
|
|
33
34
|
agentLoopContinue,
|
|
34
35
|
createSyntheticToolResultMessage,
|
|
35
36
|
lastContextMessage,
|
|
37
|
+
type NormalizeToolsOptions,
|
|
36
38
|
normalizeMessagesForProvider,
|
|
37
39
|
normalizeTools,
|
|
38
40
|
resolveOwnedDialectFromEnv,
|
|
@@ -269,15 +271,15 @@ export interface AgentOptions {
|
|
|
269
271
|
|
|
270
272
|
/**
|
|
271
273
|
* Resolve a tool call whose name matched no advertised tool. Lets hosts
|
|
272
|
-
* route calls to tools
|
|
273
|
-
*
|
|
274
|
+
* route calls to tools reached through a side transport (e.g. mounted
|
|
275
|
+
* tool commands run through `bash`) instead of failing with "Tool not found".
|
|
274
276
|
*/
|
|
275
277
|
resolveFallbackTool?: (name: string, advertised: readonly AgentTool<any>[]) => AgentTool<any> | undefined;
|
|
276
278
|
|
|
277
279
|
/**
|
|
278
280
|
* Names routable by {@link resolveFallbackTool} that the advertised set
|
|
279
|
-
* omits (e.g.
|
|
280
|
-
* call misses.
|
|
281
|
+
* omits (e.g. mounted tool commands run through `bash`), used only to
|
|
282
|
+
* suggest a target when a call misses.
|
|
281
283
|
*/
|
|
282
284
|
suggestFallbackToolNames?: () => Iterable<string>;
|
|
283
285
|
|
|
@@ -432,6 +434,7 @@ export class Agent {
|
|
|
432
434
|
#transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
|
|
433
435
|
#transformProviderContext?: (context: Context, model: Model) => Context | Promise<Context>;
|
|
434
436
|
#sentToolDefinitions = new SentToolDefinitions();
|
|
437
|
+
#standbyTools: AgentTool[] = [];
|
|
435
438
|
#steeringQueue: AgentMessage[] = [];
|
|
436
439
|
#followUpQueue: AgentMessage[] = [];
|
|
437
440
|
#queuedMessageClaims: Partial<Record<QueuedMessageQueue, QueuedMessageClaim>> = {};
|
|
@@ -986,19 +989,19 @@ export class Agent {
|
|
|
986
989
|
if (!model) throw new Error("No active model on agent");
|
|
987
990
|
const ownedDialect = this.#ownedDialect(model);
|
|
988
991
|
const messages = normalizeMessagesForProvider(llmMessages, model);
|
|
989
|
-
const
|
|
990
|
-
|
|
991
|
-
:
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
992
|
+
const toolOptions: NormalizeToolsOptions = {
|
|
993
|
+
injectIntent: this.#intentTracing,
|
|
994
|
+
intentDescription: this.#intentDescription,
|
|
995
|
+
pruneDescriptions: this.#pruneToolDescriptions,
|
|
996
|
+
};
|
|
997
|
+
const tools = ownedDialect ? [] : (normalizeTools(this.#toolsForModel(model), toolOptions) ?? []);
|
|
998
|
+
const standby = ownedDialect ? undefined : normalizeTools(this.#standbyTools, toolOptions);
|
|
996
999
|
let context: Context = { systemPrompt, messages, tools };
|
|
997
1000
|
// Side requests reuse the main loop's sent definitions without recording their own; attached before the
|
|
998
1001
|
// transform too, so a request-size clamp in it measures them.
|
|
999
|
-
context = this.#sentToolDefinitions.withInactiveTools(context);
|
|
1002
|
+
context = this.#sentToolDefinitions.withInactiveTools(context, standby);
|
|
1000
1003
|
if (this.#transformProviderContext) context = await this.#transformProviderContext(context, model);
|
|
1001
|
-
context = this.#sentToolDefinitions.withInactiveTools(context);
|
|
1004
|
+
context = this.#sentToolDefinitions.withInactiveTools(context, context.inactiveTools);
|
|
1002
1005
|
return context;
|
|
1003
1006
|
}
|
|
1004
1007
|
|
|
@@ -1367,6 +1370,11 @@ export class Agent {
|
|
|
1367
1370
|
this.#state.tools = t;
|
|
1368
1371
|
}
|
|
1369
1372
|
|
|
1373
|
+
/** Set the inactive tools that may become active later ({@link AgentContext.standbyTools}). */
|
|
1374
|
+
setStandbyTools(tools: AgentTool[]) {
|
|
1375
|
+
this.#standbyTools = tools;
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1370
1378
|
replaceMessages(ms: AgentMessage[]) {
|
|
1371
1379
|
// New array assignment is intentional: caller-owned `ms` may be mutated
|
|
1372
1380
|
// after handoff; snapshot it so external mutations cannot leak in.
|
|
@@ -1928,6 +1936,7 @@ export class Agent {
|
|
|
1928
1936
|
systemPrompt: this.#state.systemPrompt,
|
|
1929
1937
|
messages: this.#state.messages.slice(),
|
|
1930
1938
|
tools: this.#state.tools,
|
|
1939
|
+
standbyTools: this.#standbyTools,
|
|
1931
1940
|
};
|
|
1932
1941
|
|
|
1933
1942
|
// Installed unconditionally. Both `cursorExecHandlers` and
|
|
@@ -2018,6 +2027,7 @@ export class Agent {
|
|
|
2018
2027
|
return refreshToolChoiceForActiveTools(options?.toolChoice, this.#state.tools);
|
|
2019
2028
|
};
|
|
2020
2029
|
|
|
2030
|
+
let requestModel: Model | undefined;
|
|
2021
2031
|
const config: AgentLoopConfig = {
|
|
2022
2032
|
model,
|
|
2023
2033
|
reasoning,
|
|
@@ -2058,6 +2068,7 @@ export class Agent {
|
|
|
2058
2068
|
context.systemPrompt = this.#state.systemPrompt;
|
|
2059
2069
|
this.#onModelCallSystemPrompt?.(context.systemPrompt);
|
|
2060
2070
|
context.tools = this.#toolsForModel(this.#state.model ?? model);
|
|
2071
|
+
context.standbyTools = this.#standbyTools;
|
|
2061
2072
|
},
|
|
2062
2073
|
beforeModelCall:
|
|
2063
2074
|
this.#beforeModelCall || this.#additionalBeforeModelCalls.size > 0
|
|
@@ -2095,6 +2106,9 @@ export class Agent {
|
|
|
2095
2106
|
onAssistantMessageEvent: this.#onAssistantMessageEvent,
|
|
2096
2107
|
onHarmonyLeak: this.#onHarmonyLeak,
|
|
2097
2108
|
onTurnEnd: (messages, signal, context) => this.#onTurnEnd?.(messages, signal, context),
|
|
2109
|
+
onTurnEndEmitted: () => {
|
|
2110
|
+
requestModel = undefined;
|
|
2111
|
+
},
|
|
2098
2112
|
onPauseChange: paused => {
|
|
2099
2113
|
if (this.#isPaused === paused) return;
|
|
2100
2114
|
this.#isPaused = paused;
|
|
@@ -2105,7 +2119,10 @@ export class Agent {
|
|
|
2105
2119
|
onToolChoiceRejected: () => {
|
|
2106
2120
|
if (claimedToolChoice !== undefined) this.#deferredToolChoice = claimedToolChoice;
|
|
2107
2121
|
},
|
|
2108
|
-
getModel: () =>
|
|
2122
|
+
getModel: () => {
|
|
2123
|
+
requestModel = this.#state.model ?? model;
|
|
2124
|
+
return requestModel;
|
|
2125
|
+
},
|
|
2109
2126
|
getReasoning: () => this.#state.thinkingLevel,
|
|
2110
2127
|
getDisableReasoning: () => this.#state.disableReasoning,
|
|
2111
2128
|
getServiceTier: this.#serviceTierResolver,
|
|
@@ -2235,6 +2252,13 @@ export class Agent {
|
|
|
2235
2252
|
: err instanceof Error
|
|
2236
2253
|
? err.message
|
|
2237
2254
|
: String(err);
|
|
2255
|
+
const errorModel = requestModel ?? this.#state.model ?? model;
|
|
2256
|
+
const errorStatus = stoppedForAbort ? undefined : AIError.status(err);
|
|
2257
|
+
const errorId = stoppedForAbort
|
|
2258
|
+
? errorMessage === "Request was aborted"
|
|
2259
|
+
? AIError.create(AIError.Flag.Abort)
|
|
2260
|
+
: AIError.classify(loopSignal.reason) || undefined
|
|
2261
|
+
: AIError.classify(err, errorModel.api) || undefined;
|
|
2238
2262
|
const shouldEmitVisibleError = !stoppedForAbort;
|
|
2239
2263
|
const assistantPartial = partial?.role === "assistant" ? partial : undefined;
|
|
2240
2264
|
const hadAssistantStart = assistantPartial !== undefined;
|
|
@@ -2262,13 +2286,15 @@ export class Agent {
|
|
|
2262
2286
|
),
|
|
2263
2287
|
stopReason: "error",
|
|
2264
2288
|
errorMessage,
|
|
2289
|
+
errorStatus,
|
|
2290
|
+
errorId,
|
|
2265
2291
|
}
|
|
2266
2292
|
: {
|
|
2267
2293
|
role: "assistant",
|
|
2268
2294
|
content: [{ type: "text", text: "" }],
|
|
2269
|
-
api:
|
|
2270
|
-
provider:
|
|
2271
|
-
model:
|
|
2295
|
+
api: errorModel.api,
|
|
2296
|
+
provider: errorModel.provider,
|
|
2297
|
+
model: errorModel.id,
|
|
2272
2298
|
usage: {
|
|
2273
2299
|
input: 0,
|
|
2274
2300
|
output: 0,
|
|
@@ -2279,6 +2305,8 @@ export class Agent {
|
|
|
2279
2305
|
},
|
|
2280
2306
|
stopReason: stoppedForAbort ? "aborted" : "error",
|
|
2281
2307
|
errorMessage,
|
|
2308
|
+
errorStatus,
|
|
2309
|
+
errorId,
|
|
2282
2310
|
timestamp: Date.now(),
|
|
2283
2311
|
};
|
|
2284
2312
|
|
|
@@ -478,7 +478,6 @@ function buildCompactionV2Headers(
|
|
|
478
478
|
}
|
|
479
479
|
applyCodexResidencyHeader(headers, apiKey);
|
|
480
480
|
if (routingSessionId) {
|
|
481
|
-
headers[OPENAI_HEADERS.CONVERSATION_ID] = routingSessionId;
|
|
482
481
|
headers[OPENAI_HEADERS.SESSION_ID] = routingSessionId;
|
|
483
482
|
headers["x-client-request-id"] = routingSessionId;
|
|
484
483
|
}
|
|
@@ -42,6 +42,7 @@ import { preferredDialect } from "@oh-my-pi/pi-catalog/identity";
|
|
|
42
42
|
import { clampThinkingLevelForModel } from "@oh-my-pi/pi-catalog/model-thinking";
|
|
43
43
|
import { isRecord, logger, prompt, withLoopPhase } from "@oh-my-pi/pi-utils";
|
|
44
44
|
import * as snapcompact from "@oh-my-pi/snapcompact";
|
|
45
|
+
import { countContextOverrun } from "../output-budget";
|
|
45
46
|
import { type AgentTelemetry, instrumentedCompleteSimple } from "../telemetry";
|
|
46
47
|
import { ThinkingLevel } from "../thinking";
|
|
47
48
|
import { Tokenizer } from "../tokenizer";
|
|
@@ -1219,6 +1220,13 @@ export async function generateHandoffFromContext(
|
|
|
1219
1220
|
model: Model,
|
|
1220
1221
|
options: HandoffFromContextOptions,
|
|
1221
1222
|
): Promise<string> {
|
|
1223
|
+
const overrun = countContextOverrun(context, model, new Tokenizer(model));
|
|
1224
|
+
if (overrun !== undefined) {
|
|
1225
|
+
throw new Error(
|
|
1226
|
+
`Handoff input does not fit ${model.provider}/${model.id}: at least ${overrun} prompt tokens ` +
|
|
1227
|
+
`leave no room for output in its ${model.contextWindow}-token window`,
|
|
1228
|
+
);
|
|
1229
|
+
}
|
|
1222
1230
|
const requestOptions = {
|
|
1223
1231
|
...options.streamOptions,
|
|
1224
1232
|
reasoning: resolveCompactionEffort(model, options.thinkingLevel),
|
package/src/output-budget.ts
CHANGED
|
@@ -144,12 +144,41 @@ function countPromptTokens(context: Context, tokenizer: Tokenizer): number {
|
|
|
144
144
|
}
|
|
145
145
|
|
|
146
146
|
function countContextTokens(context: Context, tokenizer: Tokenizer): number {
|
|
147
|
+
return countFramingTokens(context, tokenizer) + tokenizer.countMessages(context.messages);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** System prompt and tool schemas: the request prefix outside `messages`. */
|
|
151
|
+
function countFramingTokens(context: Context, tokenizer: Tokenizer): number {
|
|
147
152
|
const { systemPrompt, tools, inactiveTools } = context;
|
|
148
153
|
return (
|
|
149
154
|
countFraming(systemPrompt, tokenizer, () => [...(systemPrompt ?? [])]) +
|
|
150
155
|
countFraming(tools, tokenizer, () => toolFragments(tools ?? [])) +
|
|
151
156
|
// Anthropic replays retired tool definitions, so they are prompt too.
|
|
152
|
-
countFraming(inactiveTools, tokenizer, () => toolFragments(inactiveTools ?? []))
|
|
153
|
-
tokenizer.countMessages(context.messages)
|
|
157
|
+
countFraming(inactiveTools, tokenizer, () => toolFragments(inactiveTools ?? []))
|
|
154
158
|
);
|
|
155
159
|
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Local prompt count of `context` when it leaves `model` no room for the
|
|
163
|
+
* smallest output the transport requests, else `undefined` (also when the
|
|
164
|
+
* window is unknown). Counting stops at the first message past the window, so
|
|
165
|
+
* the count is a floor.
|
|
166
|
+
*
|
|
167
|
+
* Unlike {@link fitOutputTokensToContextWindow}, no usage anchor is trusted:
|
|
168
|
+
* history re-expanded behind a native compaction the model cannot replay
|
|
169
|
+
* carries reports describing the compacted prefix. Nor is a tokenizer margin
|
|
170
|
+
* added: a caller refuses on this verdict, so only a clear overrun counts, and
|
|
171
|
+
* a near-full request is still left to the provider.
|
|
172
|
+
*/
|
|
173
|
+
export function countContextOverrun(context: Context, model: Model, tokenizer: Tokenizer): number | undefined {
|
|
174
|
+
const contextWindow = model.contextWindow;
|
|
175
|
+
if (!contextWindow || contextWindow <= 0) return undefined;
|
|
176
|
+
const budget = contextWindow - OUTPUT_FIT_HEADWAY_TOKENS - MIN_FITTED_OUTPUT_TOKENS;
|
|
177
|
+
let tokens = countFramingTokens(context, tokenizer);
|
|
178
|
+
for (const message of context.messages) {
|
|
179
|
+
if (tokens > budget) break;
|
|
180
|
+
// Encrypted reasoning bytes overstate what the provider bills; a floor leaves them out.
|
|
181
|
+
tokens += tokenizer.countMessage(message, { excludeEncryptedReasoning: true });
|
|
182
|
+
}
|
|
183
|
+
return tokens > budget ? tokens : undefined;
|
|
184
|
+
}
|
|
@@ -26,16 +26,21 @@ export class SentToolDefinitions {
|
|
|
26
26
|
/**
|
|
27
27
|
* `context` with {@link Context.inactiveTools} set to the definitions for names the latest
|
|
28
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.
|
|
30
|
-
*
|
|
29
|
+
* there are none or the request declares no tools. A declared name this Agent never sent takes its
|
|
30
|
+
* `standby` definition (a resumed transcript declares standby tools a fresh process has not sent);
|
|
31
|
+
* names with neither are skipped, and the provider drops them from the declaration. Before any
|
|
32
|
+
* request declared tools, `standby` (minus active names) stands in, so the first declaration
|
|
33
|
+
* already holds tools that may activate later.
|
|
31
34
|
*/
|
|
32
|
-
withInactiveTools(context: Context): Context {
|
|
33
|
-
const inactiveTools = context.tools?.length
|
|
35
|
+
withInactiveTools(context: Context, standby?: readonly Tool[]): Context {
|
|
36
|
+
const inactiveTools = context.tools?.length
|
|
37
|
+
? this.#inactiveFor(context.messages, context.tools, standby)
|
|
38
|
+
: undefined;
|
|
34
39
|
if (!inactiveTools && !context.inactiveTools) return context;
|
|
35
40
|
return { ...context, inactiveTools };
|
|
36
41
|
}
|
|
37
42
|
|
|
38
|
-
#inactiveFor(messages: readonly Message[], active: readonly Tool[]): Tool[] | undefined {
|
|
43
|
+
#inactiveFor(messages: readonly Message[], active: readonly Tool[], standby?: readonly Tool[]): Tool[] | undefined {
|
|
39
44
|
let declared: readonly string[] | undefined;
|
|
40
45
|
for (let index = messages.length - 1; index >= 0; index--) {
|
|
41
46
|
const message = messages[index];
|
|
@@ -44,13 +49,18 @@ export class SentToolDefinitions {
|
|
|
44
49
|
break;
|
|
45
50
|
}
|
|
46
51
|
}
|
|
47
|
-
if (!declared) return undefined;
|
|
48
52
|
const activeNames = new Set(active.map(tool => tool.name));
|
|
49
53
|
const inactive: Tool[] = [];
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
+
if (declared) {
|
|
55
|
+
for (const name of declared) {
|
|
56
|
+
if (activeNames.has(name)) continue;
|
|
57
|
+
const tool = this.#byName.get(name) ?? standby?.find(candidate => candidate.name === name);
|
|
58
|
+
if (tool) inactive.push(tool);
|
|
59
|
+
}
|
|
60
|
+
} else if (standby) {
|
|
61
|
+
for (const tool of standby) {
|
|
62
|
+
if (!activeNames.has(tool.name)) inactive.push(tool);
|
|
63
|
+
}
|
|
54
64
|
}
|
|
55
65
|
return inactive.length > 0 ? inactive : undefined;
|
|
56
66
|
}
|
|
@@ -398,8 +398,18 @@ export class SpeculativeOperationCoordinator {
|
|
|
398
398
|
reason: string,
|
|
399
399
|
descendants = true,
|
|
400
400
|
): Promise<void> {
|
|
401
|
-
|
|
401
|
+
// Once execution completes with a usable result, #commitCandidate owns
|
|
402
|
+
// validation, commit, and rollback; discarding while claimed before
|
|
403
|
+
// completion must still proceed so pending claim()/commit() waiters unblock.
|
|
404
|
+
if (
|
|
405
|
+
candidate.state === "discarded" ||
|
|
406
|
+
candidate.committed ||
|
|
407
|
+
(candidate.claimed && candidate.state === "completed")
|
|
408
|
+
) {
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
402
411
|
candidate.state = "discarded";
|
|
412
|
+
candidate.claimed = false;
|
|
403
413
|
candidate.controller.abort();
|
|
404
414
|
candidate.rejectOutcome(new Error(reason));
|
|
405
415
|
const context = this.#createContext(candidate);
|
|
@@ -548,16 +558,26 @@ export class SpeculativeOperationCoordinator {
|
|
|
548
558
|
.map(candidate => this.#discardCandidate(candidate, "discarded", reason)),
|
|
549
559
|
);
|
|
550
560
|
}
|
|
561
|
+
#isClaimable(candidate: SpeculativeToolCandidate): boolean {
|
|
562
|
+
return !this.#closed && !candidate.claimed && candidate.state !== "discarded";
|
|
563
|
+
}
|
|
564
|
+
|
|
551
565
|
async #commitCandidate(
|
|
552
566
|
candidate: SpeculativeToolCandidate,
|
|
553
567
|
tool: AgentTool | undefined,
|
|
554
568
|
toolCall: AgentToolCall,
|
|
555
569
|
args: Readonly<Record<string, unknown>>,
|
|
570
|
+
signal?: AbortSignal,
|
|
556
571
|
): Promise<SpeculativeRawOutcome | undefined> {
|
|
557
|
-
if (candidate
|
|
572
|
+
if (!this.#isClaimable(candidate)) return undefined;
|
|
558
573
|
candidate.dispatchReachedAt = Date.now();
|
|
559
574
|
|
|
560
575
|
const fingerprintMatches = await candidateMatchesFingerprint(candidate, toolCall, args);
|
|
576
|
+
if (signal?.aborted) {
|
|
577
|
+
await this.#discardCandidate(candidate, "aborted", "speculative execution aborted");
|
|
578
|
+
signal.throwIfAborted();
|
|
579
|
+
}
|
|
580
|
+
if (!this.#isClaimable(candidate)) return undefined;
|
|
561
581
|
if (candidate.tool !== tool || !fingerprintMatches) {
|
|
562
582
|
await this.#discardCandidate(candidate, "fingerprint_mismatch", "final speculation fingerprint changed");
|
|
563
583
|
return undefined;
|
|
@@ -565,9 +585,13 @@ export class SpeculativeOperationCoordinator {
|
|
|
565
585
|
candidate.claimed = true;
|
|
566
586
|
let physicalOutcome: SpeculativePhysicalOutcome;
|
|
567
587
|
try {
|
|
568
|
-
physicalOutcome = await candidate.outcome;
|
|
569
|
-
} catch {
|
|
588
|
+
physicalOutcome = await (signal ? untilAborted(signal, candidate.outcome) : candidate.outcome);
|
|
589
|
+
} catch (error) {
|
|
570
590
|
candidate.claimed = false;
|
|
591
|
+
if (signal?.aborted) {
|
|
592
|
+
await this.#discardCandidate(candidate, "aborted", "speculative execution aborted");
|
|
593
|
+
throw error;
|
|
594
|
+
}
|
|
571
595
|
await this.#discardCandidate(candidate, "discarded", "speculative execution failed");
|
|
572
596
|
return undefined;
|
|
573
597
|
}
|
|
@@ -627,7 +651,7 @@ export class SpeculativeOperationCoordinator {
|
|
|
627
651
|
// after the earlier shared writers have exposed their final effects.
|
|
628
652
|
if (earlierEffectsSettled) await untilAborted(signal, earlierEffectsSettled);
|
|
629
653
|
signal?.throwIfAborted();
|
|
630
|
-
return this.#commitCandidate(candidate, tool, toolCall, args);
|
|
654
|
+
return this.#commitCandidate(candidate, tool, toolCall, args, signal);
|
|
631
655
|
}
|
|
632
656
|
|
|
633
657
|
admitFinalized(
|
package/src/tokenizer.ts
CHANGED
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
isSameModelTurn,
|
|
14
14
|
shouldDropTruncatedThinkingOnlyAssistant,
|
|
15
15
|
} from "@oh-my-pi/pi-ai/providers/transform-messages";
|
|
16
|
+
import { replaysSignedReasoningText } from "@oh-my-pi/pi-ai/utils/reasoning-source";
|
|
16
17
|
import { resolveThinkingReplayTokens, type ThinkingReplayTokens } from "@oh-my-pi/pi-catalog/compat/thinking-replay";
|
|
17
18
|
import type { ModelTokenizer } from "@oh-my-pi/pi-catalog/types";
|
|
18
19
|
import * as natives from "@oh-my-pi/pi-natives";
|
|
@@ -569,8 +570,15 @@ export class Tokenizer {
|
|
|
569
570
|
continue;
|
|
570
571
|
}
|
|
571
572
|
if (this.#dropsOllamaThinking && ownOllamaTurn) continue;
|
|
572
|
-
// Chat-completions drops it unless LiteLLM replays it in `thinking_blocks
|
|
573
|
-
|
|
573
|
+
// Chat-completions drops it unless LiteLLM replays it in `thinking_blocks`
|
|
574
|
+
// or signed `reasoning_details` text replays with it.
|
|
575
|
+
if (
|
|
576
|
+
ownDroppedCompletionsTurn &&
|
|
577
|
+
!isLiteLLMThinkingSignature(block.thinkingSignature) &&
|
|
578
|
+
!replaysSignedReasoningText(block.thinkingSignature)
|
|
579
|
+
) {
|
|
580
|
+
continue;
|
|
581
|
+
}
|
|
574
582
|
if (this.#filtersReasoningHistory && this.#model !== undefined) {
|
|
575
583
|
// The demoted rendering is the visible text the request carries.
|
|
576
584
|
if (block.thinking.trim()) fragments.push(renderDemotedThinking(this.#model.id, block.thinking));
|
package/src/tool-arguments.ts
CHANGED
|
@@ -6,7 +6,8 @@ import type { AgentTool } from "./types";
|
|
|
6
6
|
* - `"parsed"`: a provider stream parsed the arguments, so `__parseError` is a
|
|
7
7
|
* genuine parse-failure sentinel and is never handed to a tool.
|
|
8
8
|
* - `"payload"`: the arguments are a payload the model wrote (eval tool bridge,
|
|
9
|
-
*
|
|
9
|
+
* a tool command line parsed into arguments), so those keys are forged and
|
|
10
|
+
* only stripped.
|
|
10
11
|
*/
|
|
11
12
|
export type ToolArgumentSource = "parsed" | "payload";
|
|
12
13
|
|
package/src/types.ts
CHANGED
|
@@ -145,8 +145,8 @@ export interface SoftToolRequirement {
|
|
|
145
145
|
/**
|
|
146
146
|
* Per-call compliance check: a turn satisfies the requirement only when every
|
|
147
147
|
* tool call passes. Defaults to `name === toolName`. Lets a host demand a
|
|
148
|
-
* specific invocation shape (e.g. `
|
|
149
|
-
* instead of any call to `toolName`. Escalation still forces `toolName`.
|
|
148
|
+
* specific invocation shape (e.g. a `bash` call running a particular tool
|
|
149
|
+
* command) instead of any call to `toolName`. Escalation still forces `toolName`.
|
|
150
150
|
*/
|
|
151
151
|
satisfies?(toolCall: { name: string; arguments?: Record<string, unknown> }): boolean;
|
|
152
152
|
/** Host-owned reminder messages, injected once per `id` activation. */
|
|
@@ -452,8 +452,8 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
|
452
452
|
/**
|
|
453
453
|
* Resolve a tool call whose name matched no advertised tool (including
|
|
454
454
|
* `customWireName` aliases). Lets hosts route calls to tools they expose
|
|
455
|
-
* through side
|
|
456
|
-
* with "Tool not found". Returning `undefined` keeps the failure.
|
|
455
|
+
* through a side transport (e.g. mounted tool commands run through `bash`)
|
|
456
|
+
* instead of failing with "Tool not found". Returning `undefined` keeps the failure.
|
|
457
457
|
*
|
|
458
458
|
* `advertised` is the very snapshot exact-name dispatch just searched — the
|
|
459
459
|
* set offered to THIS request. A host must resolve against it rather than
|
|
@@ -465,9 +465,9 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
|
465
465
|
resolveFallbackTool?: (name: string, advertised: readonly AgentTool<any>[]) => AgentTool<any> | undefined;
|
|
466
466
|
/**
|
|
467
467
|
* Names reachable through {@link resolveFallbackTool} but absent from the
|
|
468
|
-
* advertised set (e.g.
|
|
469
|
-
* plausible target when a call misses, so a mis-transcribed
|
|
470
|
-
* recoverable; never a dispatch source.
|
|
468
|
+
* advertised set (e.g. mounted tool commands run through `bash`). Consulted
|
|
469
|
+
* only to name a plausible target when a call misses, so a mis-transcribed
|
|
470
|
+
* command name is recoverable; never a dispatch source.
|
|
471
471
|
*/
|
|
472
472
|
suggestFallbackToolNames?: () => Iterable<string>;
|
|
473
473
|
|
|
@@ -634,6 +634,8 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
|
634
634
|
* post-turn steering.
|
|
635
635
|
*/
|
|
636
636
|
onTurnEnd?: (messages: AgentMessage[], signal?: AbortSignal, context?: AgentTurnEndContext) => Promise<void> | void;
|
|
637
|
+
/** Called synchronously when the loop pushes `turn_end` onto the event stream. */
|
|
638
|
+
onTurnEndEmitted?: () => void;
|
|
637
639
|
|
|
638
640
|
/**
|
|
639
641
|
* Called once an assistant message is finalized from the model stream, before
|
|
@@ -1087,9 +1089,9 @@ export type ToolTier = "read" | "write" | "exec";
|
|
|
1087
1089
|
/**
|
|
1088
1090
|
* How an enabled tool is presented to the model. `"essential"` tools are exposed
|
|
1089
1091
|
* as normal top-level tools. `"discoverable"` tools are removed from the top-level
|
|
1090
|
-
* schema and either mounted
|
|
1091
|
-
* active) or surfaced through BM25 tool search — keeping their schemas
|
|
1092
|
-
* request. Selection (settings, `hidden`, `defaultInactive`, explicit `--tools`,
|
|
1092
|
+
* schema and either mounted as a tool command in the `bash` tool (when that
|
|
1093
|
+
* tool is active) or surfaced through BM25 tool search — keeping their schemas
|
|
1094
|
+
* off every request. Selection (settings, `hidden`, `defaultInactive`, explicit `--tools`,
|
|
1093
1095
|
* provider availability) decides whether a tool is enabled; `loadMode` only
|
|
1094
1096
|
* decides how an enabled tool is presented.
|
|
1095
1097
|
*/
|
|
@@ -1112,11 +1114,6 @@ export type ToolApprovalDecision =
|
|
|
1112
1114
|
reason?: string;
|
|
1113
1115
|
override?: boolean;
|
|
1114
1116
|
policy?: "allow" | "deny" | "prompt";
|
|
1115
|
-
/** User-policy key for this decision. When set, `tools.approval.<policyKey>`
|
|
1116
|
-
* is consulted instead of `tools.approval.<tool.name>`. Lets a dispatcher
|
|
1117
|
-
* tool (e.g. `write` for an `xd://` device call) scope user allow/deny/
|
|
1118
|
-
* prompt policies to the tool it dispatches into. */
|
|
1119
|
-
policyKey?: string;
|
|
1120
1117
|
};
|
|
1121
1118
|
export type ToolApproval = ToolApprovalDecision | ((args: unknown, context?: AgentToolContext) => ToolApprovalDecision);
|
|
1122
1119
|
|
|
@@ -1193,9 +1190,16 @@ export interface AgentTool<
|
|
|
1193
1190
|
* obtains by delegating to this native tool through `ctx.invokeTool` follow this tool's contract.
|
|
1194
1191
|
*/
|
|
1195
1192
|
readonly delegationGuidance?: string;
|
|
1193
|
+
/**
|
|
1194
|
+
* Whether `command` is traffic this tool must run itself rather than shell work: the transport
|
|
1195
|
+
* host (`bash`) answers true for a line made only of session tool commands, which nothing else
|
|
1196
|
+
* can dispatch. A same-name extension replacement routes such a call back here instead of
|
|
1197
|
+
* executing it, so mounted tools keep working behind an override that does not delegate.
|
|
1198
|
+
*/
|
|
1199
|
+
servesToolCommandLine?(command: string): boolean;
|
|
1196
1200
|
/**
|
|
1197
1201
|
* On-demand documentation topics (`topic → markdown`), readable as
|
|
1198
|
-
* `
|
|
1202
|
+
* `help://<tool>/<topic>`. Lets a tool keep large sub-surfaces out of its
|
|
1199
1203
|
* description and advertise only a one-line pointer per topic.
|
|
1200
1204
|
*/
|
|
1201
1205
|
docTopics?(): Readonly<Record<string, string>>;
|
|
@@ -1318,6 +1322,12 @@ export interface AgentContext {
|
|
|
1318
1322
|
systemPrompt: string[];
|
|
1319
1323
|
messages: AgentMessage[];
|
|
1320
1324
|
tools?: AgentTool<any>[];
|
|
1325
|
+
/**
|
|
1326
|
+
* Inactive tools that may become active later in the conversation. A provider that announces tool changes
|
|
1327
|
+
* in-band (Anthropic `tool_addition`) declares them from the first request, so activating one leaves the
|
|
1328
|
+
* cached prefix intact. See {@link SentToolDefinitions.withInactiveTools}.
|
|
1329
|
+
*/
|
|
1330
|
+
standbyTools?: AgentTool<any>[];
|
|
1321
1331
|
}
|
|
1322
1332
|
|
|
1323
1333
|
/**
|