@oh-my-pi/pi-agent-core 19.1.0 → 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 +8 -0
- package/dist/types/output-budget.d.ts +13 -0
- package/dist/types/types.d.ts +9 -0
- package/package.json +8 -8
- package/src/agent-loop.ts +1 -0
- package/src/agent.ts +23 -4
- package/src/compaction/compaction.ts +8 -0
- package/src/output-budget.ts +31 -2
- package/src/speculative-execution.ts +29 -5
- package/src/types.ts +9 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,14 @@
|
|
|
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
|
+
|
|
5
13
|
## [19.1.0] - 2026-11-21
|
|
6
14
|
|
|
7
15
|
### Added
|
|
@@ -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;
|
package/dist/types/types.d.ts
CHANGED
|
@@ -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
|
|
@@ -1049,6 +1051,13 @@ export interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any
|
|
|
1049
1051
|
* obtains by delegating to this native tool through `ctx.invokeTool` follow this tool's contract.
|
|
1050
1052
|
*/
|
|
1051
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;
|
|
1052
1061
|
/**
|
|
1053
1062
|
* On-demand documentation topics (`topic → markdown`), readable as
|
|
1054
1063
|
* `help://<tool>/<topic>`. Lets a tool keep large sub-surfaces out of its
|
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.1.
|
|
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.1.
|
|
42
|
-
"@oh-my-pi/pi-catalog": "19.1.
|
|
43
|
-
"@oh-my-pi/pi-natives": "19.1.
|
|
44
|
-
"@oh-my-pi/pi-utils": "19.1.
|
|
45
|
-
"@oh-my-pi/pi-wire": "19.1.
|
|
46
|
-
"@oh-my-pi/snapcompact": "19.1.
|
|
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.1.
|
|
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");
|
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";
|
|
@@ -2026,6 +2027,7 @@ export class Agent {
|
|
|
2026
2027
|
return refreshToolChoiceForActiveTools(options?.toolChoice, this.#state.tools);
|
|
2027
2028
|
};
|
|
2028
2029
|
|
|
2030
|
+
let requestModel: Model | undefined;
|
|
2029
2031
|
const config: AgentLoopConfig = {
|
|
2030
2032
|
model,
|
|
2031
2033
|
reasoning,
|
|
@@ -2104,6 +2106,9 @@ export class Agent {
|
|
|
2104
2106
|
onAssistantMessageEvent: this.#onAssistantMessageEvent,
|
|
2105
2107
|
onHarmonyLeak: this.#onHarmonyLeak,
|
|
2106
2108
|
onTurnEnd: (messages, signal, context) => this.#onTurnEnd?.(messages, signal, context),
|
|
2109
|
+
onTurnEndEmitted: () => {
|
|
2110
|
+
requestModel = undefined;
|
|
2111
|
+
},
|
|
2107
2112
|
onPauseChange: paused => {
|
|
2108
2113
|
if (this.#isPaused === paused) return;
|
|
2109
2114
|
this.#isPaused = paused;
|
|
@@ -2114,7 +2119,10 @@ export class Agent {
|
|
|
2114
2119
|
onToolChoiceRejected: () => {
|
|
2115
2120
|
if (claimedToolChoice !== undefined) this.#deferredToolChoice = claimedToolChoice;
|
|
2116
2121
|
},
|
|
2117
|
-
getModel: () =>
|
|
2122
|
+
getModel: () => {
|
|
2123
|
+
requestModel = this.#state.model ?? model;
|
|
2124
|
+
return requestModel;
|
|
2125
|
+
},
|
|
2118
2126
|
getReasoning: () => this.#state.thinkingLevel,
|
|
2119
2127
|
getDisableReasoning: () => this.#state.disableReasoning,
|
|
2120
2128
|
getServiceTier: this.#serviceTierResolver,
|
|
@@ -2244,6 +2252,13 @@ export class Agent {
|
|
|
2244
2252
|
: err instanceof Error
|
|
2245
2253
|
? err.message
|
|
2246
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;
|
|
2247
2262
|
const shouldEmitVisibleError = !stoppedForAbort;
|
|
2248
2263
|
const assistantPartial = partial?.role === "assistant" ? partial : undefined;
|
|
2249
2264
|
const hadAssistantStart = assistantPartial !== undefined;
|
|
@@ -2271,13 +2286,15 @@ export class Agent {
|
|
|
2271
2286
|
),
|
|
2272
2287
|
stopReason: "error",
|
|
2273
2288
|
errorMessage,
|
|
2289
|
+
errorStatus,
|
|
2290
|
+
errorId,
|
|
2274
2291
|
}
|
|
2275
2292
|
: {
|
|
2276
2293
|
role: "assistant",
|
|
2277
2294
|
content: [{ type: "text", text: "" }],
|
|
2278
|
-
api:
|
|
2279
|
-
provider:
|
|
2280
|
-
model:
|
|
2295
|
+
api: errorModel.api,
|
|
2296
|
+
provider: errorModel.provider,
|
|
2297
|
+
model: errorModel.id,
|
|
2281
2298
|
usage: {
|
|
2282
2299
|
input: 0,
|
|
2283
2300
|
output: 0,
|
|
@@ -2288,6 +2305,8 @@ export class Agent {
|
|
|
2288
2305
|
},
|
|
2289
2306
|
stopReason: stoppedForAbort ? "aborted" : "error",
|
|
2290
2307
|
errorMessage,
|
|
2308
|
+
errorStatus,
|
|
2309
|
+
errorId,
|
|
2291
2310
|
timestamp: Date.now(),
|
|
2292
2311
|
};
|
|
2293
2312
|
|
|
@@ -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
|
+
}
|
|
@@ -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/types.ts
CHANGED
|
@@ -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
|
|
@@ -1188,6 +1190,13 @@ export interface AgentTool<
|
|
|
1188
1190
|
* obtains by delegating to this native tool through `ctx.invokeTool` follow this tool's contract.
|
|
1189
1191
|
*/
|
|
1190
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;
|
|
1191
1200
|
/**
|
|
1192
1201
|
* On-demand documentation topics (`topic → markdown`), readable as
|
|
1193
1202
|
* `help://<tool>/<topic>`. Lets a tool keep large sub-surfaces out of its
|