@oh-my-pi/pi-agent-core 19.1.0 → 19.2.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 +24 -0
- package/dist/types/agent-loop.d.ts +8 -0
- package/dist/types/agent.d.ts +15 -6
- package/dist/types/output-budget.d.ts +13 -0
- package/dist/types/telemetry.d.ts +2 -2
- package/dist/types/types.d.ts +35 -8
- package/package.json +8 -8
- package/src/agent-loop.ts +60 -19
- package/src/agent.ts +58 -13
- package/src/compaction/compaction.ts +8 -0
- package/src/compaction/openai.ts +1 -0
- package/src/output-budget.ts +31 -2
- package/src/speculative-execution.ts +29 -5
- package/src/telemetry.ts +30 -23
- package/src/types.ts +34 -4
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,30 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [19.2.0] - 2026-11-25
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- Added customizable notices for unmet soft tool requirements, allowing hosts to specify the text shown when a required tool call does not satisfy its requirement.
|
|
10
|
+
- Added `AgentLoopError` and turn-level error metadata so hosts can distinguish an agent loop that ended because a soft tool requirement was not met from a failed request.
|
|
11
|
+
- Added abort-signal support to provider-context transformation and side-request context building.
|
|
12
|
+
- Added optional tool detachment when aborting an agent run, allowing tools that support background execution to continue instead of being terminated.
|
|
13
|
+
- Agents can accept an asynchronous Cursor handler factory; a session opens its execution bridge on the first Cursor request, including after a model switch.
|
|
14
|
+
|
|
15
|
+
### Fixed
|
|
16
|
+
|
|
17
|
+
- Fixed DeepSeek DSML markup leaking into tool-call arguments and being executed or replayed.
|
|
18
|
+
- Fixed DeepSeek DSML markup being incorrectly included in conversation history on OpenRouter Responses requests.
|
|
19
|
+
- Fixed unmet soft tool requirements leaving tool calls unanswered when a run was continued or retried.
|
|
20
|
+
|
|
21
|
+
## [19.1.1] - 2026-11-23
|
|
22
|
+
|
|
23
|
+
### Fixed
|
|
24
|
+
|
|
25
|
+
- Prevented oversized handoffs from reaching the provider by detecting when prepared context exceeds the target model’s context window.
|
|
26
|
+
- Preserved provider error status, error identifiers, retry classification, and cancellation markers on failed or cancelled assistant turns.
|
|
27
|
+
- Fixed speculative tool calls hanging when discarded or aborted before execution completed.
|
|
28
|
+
|
|
5
29
|
## [19.1.0] - 2026-11-21
|
|
6
30
|
|
|
7
31
|
### Added
|
|
@@ -14,6 +14,14 @@ import type { AgentContext, AgentEvent, AgentLoopConfig, AgentMessage, AgentTool
|
|
|
14
14
|
export declare function resolveToolConcurrency(tool: AgentTool<any, any, any> | undefined, args: Record<string, unknown>): "shared" | "exclusive";
|
|
15
15
|
/** Stop-details marker for a provider error after assistant content/tool args already streamed. */
|
|
16
16
|
export declare const STREAM_INTERRUPTED_AFTER_CONTENT_STOP_DETAIL = "stream_interrupted_after_content";
|
|
17
|
+
/**
|
|
18
|
+
* The loop ended the turn itself, not a provider: the model kept missing a soft
|
|
19
|
+
* tool requirement. `Agent` marks the turn's error message `errorFromAgentLoop`
|
|
20
|
+
* so recovery does not report it as a failed request.
|
|
21
|
+
*/
|
|
22
|
+
export declare class AgentLoopError extends Error {
|
|
23
|
+
constructor(message: string);
|
|
24
|
+
}
|
|
17
25
|
/**
|
|
18
26
|
* Cadence (ms) for polling queued steering while an `interruptible` tool is in
|
|
19
27
|
* flight, so a steer cuts the wait short instead of sitting idle until the
|
package/dist/types/agent.d.ts
CHANGED
|
@@ -14,7 +14,7 @@ export interface AgentOptions {
|
|
|
14
14
|
* Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.
|
|
15
15
|
* Default filters to user/assistant/toolResult and converts attachments.
|
|
16
16
|
*/
|
|
17
|
-
convertToLlm?:
|
|
17
|
+
convertToLlm?: AgentLoopConfig["convertToLlm"];
|
|
18
18
|
/**
|
|
19
19
|
* Optional transform applied to context before convertToLlm.
|
|
20
20
|
* Use for context pruning, injecting external context, etc.
|
|
@@ -24,7 +24,7 @@ export interface AgentOptions {
|
|
|
24
24
|
* Optional transform applied after provider context assembly and before
|
|
25
25
|
* telemetry capture/provider send.
|
|
26
26
|
*/
|
|
27
|
-
transformProviderContext?: (context: Context, model: Model) => Context | Promise<Context>;
|
|
27
|
+
transformProviderContext?: (context: Context, model: Model, signal?: AbortSignal) => Context | Promise<Context>;
|
|
28
28
|
/**
|
|
29
29
|
* Steering mode: "all" = send all steering messages at once, "one-at-a-time" = one per turn
|
|
30
30
|
*/
|
|
@@ -184,9 +184,10 @@ export interface AgentOptions {
|
|
|
184
184
|
/** Reject a deferred hard choice when its named tool is no longer active. */
|
|
185
185
|
onToolChoiceUnavailable?: () => void;
|
|
186
186
|
/**
|
|
187
|
-
* Cursor exec handlers for local tool execution
|
|
187
|
+
* Cursor exec handlers for local tool execution, or a factory resolved on the first
|
|
188
|
+
* request dispatched to Cursor (including a mid-session model switch).
|
|
188
189
|
*/
|
|
189
|
-
cursorExecHandlers?: CursorExecHandlers;
|
|
190
|
+
cursorExecHandlers?: CursorExecHandlers | (() => Promise<CursorExecHandlers>);
|
|
190
191
|
/** Additional tools Cursor executes through its MCP request-context bridge, resolved before each provider call. */
|
|
191
192
|
getCursorTools?: () => AgentTool[];
|
|
192
193
|
/**
|
|
@@ -451,7 +452,7 @@ export declare class Agent {
|
|
|
451
452
|
* (e.g. handoff generation, which uses the base prompt rather than a per-turn
|
|
452
453
|
* `before_agent_start` hook override) pass it explicitly.
|
|
453
454
|
*/
|
|
454
|
-
buildSideRequestContext(llmMessages: Message[], systemPrompt?: string[]): Promise<Context>;
|
|
455
|
+
buildSideRequestContext(llmMessages: Message[], systemPrompt?: string[], signal?: AbortSignal): Promise<Context>;
|
|
455
456
|
subscribe(fn: (e: AgentEvent) => void): () => void;
|
|
456
457
|
/** Register a listener notified after any steering/follow-up queue mutator
|
|
457
458
|
* (enqueue, dequeue-on-delivery, clear, restore, live-steering adoption,
|
|
@@ -608,7 +609,15 @@ export declare class Agent {
|
|
|
608
609
|
*/
|
|
609
610
|
popLastFollowUp(): AgentMessage | undefined;
|
|
610
611
|
clearMessages(): void;
|
|
611
|
-
|
|
612
|
+
/**
|
|
613
|
+
* Abort the current run. `detachTools` first raises the running tool batch's
|
|
614
|
+
* cooperative `steeringSignal` (see {@link AgentLoopConfig.detachSignal}), so
|
|
615
|
+
* tools that can move their work into a background job do so instead of being
|
|
616
|
+
* killed; they observe it before the abort.
|
|
617
|
+
*/
|
|
618
|
+
abort(reason?: unknown, options?: {
|
|
619
|
+
detachTools?: boolean;
|
|
620
|
+
}): void;
|
|
612
621
|
waitForIdle(): Promise<void>;
|
|
613
622
|
reset(): void;
|
|
614
623
|
/** Send a prompt with an AgentMessage */
|
|
@@ -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;
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
* cheap pass-throughs.
|
|
24
24
|
*/
|
|
25
25
|
import { type Api, type AssistantMessage, type Context, type Message, type Model, type OneshotRetryOptions, type ServiceTier, type SimpleStreamOptions, type StopReason, type ToolChoice, type Usage } from "@oh-my-pi/pi-ai";
|
|
26
|
-
import {
|
|
26
|
+
import type { Attributes, AttributeValue, Span, SpanKind, SpanStatusCode, Tracer } from "@opentelemetry/api";
|
|
27
27
|
import { AgentRunCollector, type AgentRunCoverage, type AgentRunSummary, type ToolStatus } from "./run-collector.js";
|
|
28
28
|
import type { AgentTool } from "./types.js";
|
|
29
29
|
/** Default tracer name. Override via {@link AgentTelemetryConfig.tracerName}. */
|
|
@@ -677,4 +677,4 @@ export declare function recordHandoff(telemetry: AgentTelemetry | undefined, opt
|
|
|
677
677
|
*/
|
|
678
678
|
export declare function setSpanAttribute(span: Span | undefined, key: string, value: AttributeValue): void;
|
|
679
679
|
/** Re-exports so consumers can write hooks without depending on @opentelemetry/api directly. */
|
|
680
|
-
export {
|
|
680
|
+
export type { Attributes, Span, SpanKind, SpanStatusCode, Tracer };
|
package/dist/types/types.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ApiKey, AssistantMessage, AssistantMessageEvent, AssistantMessageEventStream, Context, Effort, ImageContent, Message, Model, ServiceTier, SimpleStreamOptions, Static, streamSimple, TextContent, Tool, ToolCallProviderMetadata, ToolChoice, ToolResultMessage, ToolResultProviderMetadata, TSchema } from "@oh-my-pi/pi-ai";
|
|
1
|
+
import type { ApiKey, AssistantMessage, AssistantMessageEvent, AssistantMessageEventStream, Context, CursorExecHandlers, Effort, ImageContent, Message, Model, ServiceTier, SimpleStreamOptions, Static, streamSimple, TextContent, Tool, ToolCallProviderMetadata, ToolChoice, ToolResultMessage, ToolResultProviderMetadata, TSchema } 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";
|
|
@@ -76,6 +76,11 @@ export type AgentPreModelCallResult = AgentPreModelCallStop | undefined;
|
|
|
76
76
|
* request, or nothing to proceed; the signal aborts with the run.
|
|
77
77
|
*/
|
|
78
78
|
export type AgentBeforeModelCall = (context: Context, signal?: AbortSignal) => AgentPreModelCallResult | void | Promise<AgentPreModelCallResult | void>;
|
|
79
|
+
/** The tool-call shape a {@link SoftToolRequirement} inspects. */
|
|
80
|
+
export type SoftToolCall = {
|
|
81
|
+
name: string;
|
|
82
|
+
arguments?: Record<string, unknown>;
|
|
83
|
+
};
|
|
79
84
|
/**
|
|
80
85
|
* A soft tool requirement: the host wants `toolName` called before the loop
|
|
81
86
|
* runs other tools or yields, but WITHOUT paying the forced-`toolChoice` cost
|
|
@@ -104,10 +109,13 @@ export interface SoftToolRequirement {
|
|
|
104
109
|
* specific invocation shape (e.g. a `bash` call running a particular tool
|
|
105
110
|
* command) instead of any call to `toolName`. Escalation still forces `toolName`.
|
|
106
111
|
*/
|
|
107
|
-
satisfies?(toolCall:
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
112
|
+
satisfies?(toolCall: SoftToolCall): boolean;
|
|
113
|
+
/**
|
|
114
|
+
* Skipped-result text for a call to `toolName` that fails `satisfies`. Without
|
|
115
|
+
* it, that call gets the generic notice asking for a `toolName` call, which
|
|
116
|
+
* repeats the call the model just made instead of naming the invocation needed.
|
|
117
|
+
*/
|
|
118
|
+
unsatisfiedNotice?(toolCall: SoftToolCall): string;
|
|
111
119
|
/** Host-owned reminder messages, injected once per `id` activation. */
|
|
112
120
|
reminder: AgentMessage[];
|
|
113
121
|
}
|
|
@@ -140,6 +148,8 @@ export interface SteeringQueueState {
|
|
|
140
148
|
* Configuration for the agent loop.
|
|
141
149
|
*/
|
|
142
150
|
export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
151
|
+
/** Resolve the host bridge only when dispatching to the Cursor transport. */
|
|
152
|
+
loadCursorExecHandlers?: () => Promise<CursorExecHandlers>;
|
|
143
153
|
model: Model;
|
|
144
154
|
/** Reports whether this loop has reached a safe process-pause boundary. */
|
|
145
155
|
onPauseChange?: (paused: boolean) => void;
|
|
@@ -168,7 +178,7 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
|
168
178
|
*/
|
|
169
179
|
metadataResolver?: (provider: string) => Record<string, unknown> | undefined;
|
|
170
180
|
/**
|
|
171
|
-
* Converts AgentMessage[] to LLM-compatible Message[]
|
|
181
|
+
* Converts AgentMessage[] to LLM-compatible Message[] for the model receiving this call.
|
|
172
182
|
*
|
|
173
183
|
* Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage
|
|
174
184
|
* that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,
|
|
@@ -190,7 +200,7 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
|
190
200
|
* })
|
|
191
201
|
* ```
|
|
192
202
|
*/
|
|
193
|
-
convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
|
|
203
|
+
convertToLlm: (messages: AgentMessage[], model: Model) => Message[] | Promise<Message[]>;
|
|
194
204
|
/**
|
|
195
205
|
* Optional transform applied to the context before `convertToLlm`.
|
|
196
206
|
*
|
|
@@ -214,7 +224,7 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
|
214
224
|
* normalization, and append-only context handling, but before telemetry capture
|
|
215
225
|
* and provider send.
|
|
216
226
|
*/
|
|
217
|
-
transformProviderContext?: (context: Context, model: Model) => Context | Promise<Context>;
|
|
227
|
+
transformProviderContext?: (context: Context, model: Model, signal?: AbortSignal) => Context | Promise<Context>;
|
|
218
228
|
/** Remembers sent tool definitions to fill {@link Context.inactiveTools}. */
|
|
219
229
|
sentToolDefinitions?: SentToolDefinitions;
|
|
220
230
|
/**
|
|
@@ -263,6 +273,14 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
|
263
273
|
* {@link getSteeringMessages}.
|
|
264
274
|
*/
|
|
265
275
|
waitForSteeringMessages?: (signal?: AbortSignal) => Promise<void>;
|
|
276
|
+
/**
|
|
277
|
+
* Aborted just before the host aborts the run when running tools should keep
|
|
278
|
+
* their work: raises the active tool batch's cooperative
|
|
279
|
+
* {@link ToolCallContext.steeringSignal} (source `"user"`) in either
|
|
280
|
+
* {@link interruptMode}, so a tool that can (auto-background bash/eval)
|
|
281
|
+
* moves its work into a background job instead of being killed.
|
|
282
|
+
*/
|
|
283
|
+
detachSignal?: AbortSignal;
|
|
266
284
|
/**
|
|
267
285
|
* Called when live steering dequeues messages via {@link getSteeringMessages}
|
|
268
286
|
* for the response being streamed. The loop records them in the transcript
|
|
@@ -552,6 +570,8 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
|
552
570
|
* post-turn steering.
|
|
553
571
|
*/
|
|
554
572
|
onTurnEnd?: (messages: AgentMessage[], signal?: AbortSignal, context?: AgentTurnEndContext) => Promise<void> | void;
|
|
573
|
+
/** Called synchronously when the loop pushes `turn_end` onto the event stream. */
|
|
574
|
+
onTurnEndEmitted?: () => void;
|
|
555
575
|
/**
|
|
556
576
|
* Called once an assistant message is finalized from the model stream, before
|
|
557
577
|
* it is appended to the context, emitted as `message_end`, or its tool calls
|
|
@@ -1049,6 +1069,13 @@ export interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any
|
|
|
1049
1069
|
* obtains by delegating to this native tool through `ctx.invokeTool` follow this tool's contract.
|
|
1050
1070
|
*/
|
|
1051
1071
|
readonly delegationGuidance?: string;
|
|
1072
|
+
/**
|
|
1073
|
+
* Whether `command` is traffic this tool must run itself rather than shell work: the transport
|
|
1074
|
+
* host (`bash`) answers true for a line made only of session tool commands, which nothing else
|
|
1075
|
+
* can dispatch. A same-name extension replacement routes such a call back here instead of
|
|
1076
|
+
* executing it, so mounted tools keep working behind an override that does not delegate.
|
|
1077
|
+
*/
|
|
1078
|
+
servesToolCommandLine?(command: string): boolean;
|
|
1052
1079
|
/**
|
|
1053
1080
|
* On-demand documentation topics (`topic → markdown`), readable as
|
|
1054
1081
|
* `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.
|
|
4
|
+
"version": "19.2.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,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.2.0",
|
|
42
|
+
"@oh-my-pi/pi-catalog": "19.2.0",
|
|
43
|
+
"@oh-my-pi/pi-natives": "19.2.0",
|
|
44
|
+
"@oh-my-pi/pi-utils": "19.2.0",
|
|
45
|
+
"@oh-my-pi/pi-wire": "19.2.0",
|
|
46
|
+
"@oh-my-pi/snapcompact": "19.2.0",
|
|
47
47
|
"@opentelemetry/api": "^1.9.1"
|
|
48
48
|
},
|
|
49
49
|
"devDependencies": {
|
|
50
|
-
"@oh-my-pi/omptype": "19.
|
|
50
|
+
"@oh-my-pi/omptype": "19.2.0",
|
|
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
|
@@ -169,6 +169,18 @@ const MAX_DSML_LEAK_NUDGES = 2;
|
|
|
169
169
|
*/
|
|
170
170
|
const MAX_SOFT_TOOL_ESCALATIONS = 3;
|
|
171
171
|
|
|
172
|
+
/**
|
|
173
|
+
* The loop ended the turn itself, not a provider: the model kept missing a soft
|
|
174
|
+
* tool requirement. `Agent` marks the turn's error message `errorFromAgentLoop`
|
|
175
|
+
* so recovery does not report it as a failed request.
|
|
176
|
+
*/
|
|
177
|
+
export class AgentLoopError extends Error {
|
|
178
|
+
constructor(message: string) {
|
|
179
|
+
super(message);
|
|
180
|
+
this.name = "AgentLoopError";
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
172
184
|
/**
|
|
173
185
|
* Whether a hard `toolChoice` for a turn conflicts with a pending soft tool
|
|
174
186
|
* requirement — i.e. forbids tools (`"none"`) or forces a *different* specific
|
|
@@ -826,6 +838,7 @@ async function emitTurnEnd(
|
|
|
826
838
|
runHookOnAbortedMessage = false,
|
|
827
839
|
): Promise<void> {
|
|
828
840
|
stream.push({ type: "turn_end", message, toolResults });
|
|
841
|
+
config.onTurnEndEmitted?.();
|
|
829
842
|
const terminalYield = signal?.reason === TERMINAL_TOOL_RESULT_ABORT_REASON;
|
|
830
843
|
const isAbortedOrError =
|
|
831
844
|
message.role === "assistant" && (message.stopReason === "aborted" || message.stopReason === "error");
|
|
@@ -1340,6 +1353,7 @@ async function runLoopBody(
|
|
|
1340
1353
|
let hostToolChoice: ToolChoice | undefined;
|
|
1341
1354
|
let softRequiredTool: string | undefined;
|
|
1342
1355
|
let softSatisfies: SoftToolRequirement["satisfies"];
|
|
1356
|
+
let softUnsatisfiedNotice: SoftToolRequirement["unsatisfiedNotice"];
|
|
1343
1357
|
let directiveResolvedForTurn = false;
|
|
1344
1358
|
let turnOpen = false;
|
|
1345
1359
|
// A trailing assistant message with unpaired tool calls: the harness
|
|
@@ -1441,6 +1455,7 @@ async function runLoopBody(
|
|
|
1441
1455
|
hostToolChoice = directive === undefined || isSoftToolRequirement(directive) ? undefined : directive;
|
|
1442
1456
|
softRequiredTool = softReq?.toolName;
|
|
1443
1457
|
softSatisfies = softReq?.satisfies;
|
|
1458
|
+
softUnsatisfiedNotice = softReq?.unsatisfiedNotice;
|
|
1444
1459
|
const softRequirementId = softRequirementState.id;
|
|
1445
1460
|
if (softReq !== undefined) {
|
|
1446
1461
|
if (softReq.id !== softRequirementId) {
|
|
@@ -1725,11 +1740,6 @@ async function runLoopBody(
|
|
|
1725
1740
|
const additionalMessages: AgentMessage[] = [];
|
|
1726
1741
|
if (softNonCompliant && softRequiredTool !== undefined) {
|
|
1727
1742
|
SpeculativeOperationCoordinator.discardForMessage(message, "soft tool requirement deferred execution");
|
|
1728
|
-
if (softRequirementState.escalations >= MAX_SOFT_TOOL_ESCALATIONS) {
|
|
1729
|
-
throw new Error(
|
|
1730
|
-
`Soft tool requirement '${softRequiredTool}' was not satisfied after ${MAX_SOFT_TOOL_ESCALATIONS} forced turns; aborting to avoid an unbounded force loop.`,
|
|
1731
|
-
);
|
|
1732
|
-
}
|
|
1733
1743
|
// A soft-required tool is pending but the model called something else
|
|
1734
1744
|
// (or yielded). Do NOT execute the detour — pair each call with a
|
|
1735
1745
|
// skipped result and force the required tool next turn. This is the
|
|
@@ -1737,11 +1747,18 @@ async function runLoopBody(
|
|
|
1737
1747
|
// reminder pays no message-cache invalidation. Re-engage so the loop
|
|
1738
1748
|
// never yields while the requirement is unmet.
|
|
1739
1749
|
for (const toolCall of toolCalls) {
|
|
1750
|
+
// A call to the required tool that fails `satisfies` already did what the
|
|
1751
|
+
// generic notice asks; give it the host's notice naming the invocation needed.
|
|
1752
|
+
const wrongInvocationNotice =
|
|
1753
|
+
toolCall.name === softRequiredTool && softSatisfies?.(toolCall) === false
|
|
1754
|
+
? softUnsatisfiedNotice?.(toolCall)
|
|
1755
|
+
: undefined;
|
|
1740
1756
|
const result = createAbortedToolResult(
|
|
1741
1757
|
toolCall,
|
|
1742
1758
|
stream,
|
|
1743
1759
|
"skipped",
|
|
1744
|
-
|
|
1760
|
+
wrongInvocationNotice ??
|
|
1761
|
+
`Not executed: call the \`${softRequiredTool}\` tool to resolve the pending action before using other tools.`,
|
|
1745
1762
|
);
|
|
1746
1763
|
currentContext.messages.push(result);
|
|
1747
1764
|
newMessages.push(result);
|
|
@@ -1752,6 +1769,14 @@ async function runLoopBody(
|
|
|
1752
1769
|
status: "skipped",
|
|
1753
1770
|
});
|
|
1754
1771
|
}
|
|
1772
|
+
// Abort only after pairing the calls: a retry continues from this
|
|
1773
|
+
// transcript, and `agentLoopContinue` executes an unanswered tool-call
|
|
1774
|
+
// tail, which would run the calls the gate just refused.
|
|
1775
|
+
if (softRequirementState.escalations >= MAX_SOFT_TOOL_ESCALATIONS) {
|
|
1776
|
+
throw new AgentLoopError(
|
|
1777
|
+
`Soft tool requirement '${softRequiredTool}' was not satisfied after ${MAX_SOFT_TOOL_ESCALATIONS} forced turns; aborting to avoid an unbounded force loop.`,
|
|
1778
|
+
);
|
|
1779
|
+
}
|
|
1755
1780
|
softRequirementState.forcedToolChoice = { type: "tool", name: softRequiredTool };
|
|
1756
1781
|
softRequirementState.escalations++;
|
|
1757
1782
|
hasMoreToolCalls = true;
|
|
@@ -2014,7 +2039,10 @@ function openLiveSteering(
|
|
|
2014
2039
|
const transformed = config.transformContext
|
|
2015
2040
|
? await config.transformContext(messages, bound(signal))
|
|
2016
2041
|
: messages;
|
|
2017
|
-
const converted = normalizeMessagesForProvider(
|
|
2042
|
+
const converted = normalizeMessagesForProvider(
|
|
2043
|
+
await config.convertToLlm(transformed, prepared.model),
|
|
2044
|
+
prepared.model,
|
|
2045
|
+
);
|
|
2018
2046
|
const userMessages: UserMessage[] = [];
|
|
2019
2047
|
for (const message of converted) {
|
|
2020
2048
|
if (message.role !== "user") return undefined;
|
|
@@ -2039,7 +2067,7 @@ async function prepareProviderCall(
|
|
|
2039
2067
|
messages = await config.transformContext(messages, signal);
|
|
2040
2068
|
}
|
|
2041
2069
|
|
|
2042
|
-
const llmMessages = await config.convertToLlm(messages);
|
|
2070
|
+
const llmMessages = await config.convertToLlm(messages, model);
|
|
2043
2071
|
const normalizedMessages = normalizeMessagesForProvider(llmMessages, model);
|
|
2044
2072
|
const ownedDialect: Dialect | undefined =
|
|
2045
2073
|
(config.getDialect ? config.getDialect(model) : config.dialect) ?? resolveOwnedDialectFromEnv(Bun.env.PI_DIALECT);
|
|
@@ -2071,7 +2099,7 @@ async function prepareProviderCall(
|
|
|
2071
2099
|
llmContext = config.sentToolDefinitions.withInactiveTools(llmContext, standbyTools);
|
|
2072
2100
|
}
|
|
2073
2101
|
if (config.transformProviderContext) {
|
|
2074
|
-
llmContext = await config.transformProviderContext(llmContext, model);
|
|
2102
|
+
llmContext = await config.transformProviderContext(llmContext, model, signal);
|
|
2075
2103
|
}
|
|
2076
2104
|
|
|
2077
2105
|
let promptToolWireTools: Context["tools"];
|
|
@@ -2256,6 +2284,9 @@ async function streamAssistantResponse(
|
|
|
2256
2284
|
|
|
2257
2285
|
try {
|
|
2258
2286
|
return await runInActiveSpan(chatSpan, async () => {
|
|
2287
|
+
if (model.api === "cursor-agent" && !config.cursorExecHandlers && config.loadCursorExecHandlers) {
|
|
2288
|
+
config.cursorExecHandlers = await config.loadCursorExecHandlers();
|
|
2289
|
+
}
|
|
2259
2290
|
onProviderStart?.();
|
|
2260
2291
|
let response = await streamFunction(model, llmContext, {
|
|
2261
2292
|
...config,
|
|
@@ -2402,16 +2433,7 @@ async function streamAssistantResponse(
|
|
|
2402
2433
|
}
|
|
2403
2434
|
}
|
|
2404
2435
|
finalMessage = snapshotAssistantMessage(finalMessage);
|
|
2405
|
-
|
|
2406
|
-
// and turns with a valid structured call. Only a failed text-only
|
|
2407
|
-
// call needs the recovery nudge.
|
|
2408
|
-
if (dsmlLeakRecoveryEnabled) {
|
|
2409
|
-
const hasToolCall = finalMessage.content.some(block => block.type === "toolCall");
|
|
2410
|
-
const removed = removeDsmlToolMarkupLeak(finalMessage);
|
|
2411
|
-
if (removed && finalMessage.stopReason === "stop" && !hasToolCall) {
|
|
2412
|
-
dsmlLeakMessages.add(finalMessage);
|
|
2413
|
-
}
|
|
2414
|
-
}
|
|
2436
|
+
if (dsmlLeakRecoveryEnabled && removeDsmlLeak(finalMessage)) dsmlLeakMessages.add(finalMessage);
|
|
2415
2437
|
// Expand inline macros (and any other registered rewrite) on the
|
|
2416
2438
|
// finalized message before it reaches the context, the UI, or tool
|
|
2417
2439
|
// dispatch — so a single mutation is the source of truth for all three.
|
|
@@ -2694,10 +2716,12 @@ async function streamAssistantResponse(
|
|
|
2694
2716
|
throw new HarmonyLeakInterruption(detection, removed, recovered);
|
|
2695
2717
|
}
|
|
2696
2718
|
}
|
|
2719
|
+
const dsmlLeakNudge = dsmlLeakRecoveryEnabled && removeDsmlLeak(trailing);
|
|
2697
2720
|
if (config.transformAssistantMessage) {
|
|
2698
2721
|
await config.transformAssistantMessage(trailing, requestSignal);
|
|
2699
2722
|
}
|
|
2700
2723
|
trailing = snapshotAssistantMessage(trailing);
|
|
2724
|
+
if (dsmlLeakNudge) dsmlLeakMessages.add(trailing);
|
|
2701
2725
|
const finalToolCallsCanDispatch =
|
|
2702
2726
|
!requestSignal?.aborted &&
|
|
2703
2727
|
(canDispatchFinalToolCalls?.(trailing) ??
|
|
@@ -2962,6 +2986,16 @@ interface PreparedToolCall {
|
|
|
2962
2986
|
/** Committed assistant messages whose unhealed DSML tool-call markup was stripped; the loop answers them with a failure nudge. */
|
|
2963
2987
|
const dsmlLeakMessages = new WeakSet<AssistantMessage>();
|
|
2964
2988
|
|
|
2989
|
+
/**
|
|
2990
|
+
* Strip unhealed DSML markup from a finalized turn before anything dispatches
|
|
2991
|
+
* or commits it: text, reasoning, and tool-call arguments. Returns whether the
|
|
2992
|
+
* turn was a failed text-only call that needs the recovery nudge.
|
|
2993
|
+
*/
|
|
2994
|
+
function removeDsmlLeak(message: AssistantMessage): boolean {
|
|
2995
|
+
const hasToolCall = message.content.some(block => block.type === "toolCall");
|
|
2996
|
+
return removeDsmlToolMarkupLeak(message) && message.stopReason === "stop" && !hasToolCall;
|
|
2997
|
+
}
|
|
2998
|
+
|
|
2965
2999
|
/**
|
|
2966
3000
|
* Prepare results computed in the stream-done branch (before `message_start`/
|
|
2967
3001
|
* `message_end`) so a `beforeToolCall` args revision is baked into the message
|
|
@@ -3953,6 +3987,12 @@ async function executeToolCalls(
|
|
|
3953
3987
|
}
|
|
3954
3988
|
})()
|
|
3955
3989
|
: undefined;
|
|
3990
|
+
// The host detaching tools ahead of an abort raises the cooperative signal
|
|
3991
|
+
// in either interruptMode; tools see it before the abort that follows.
|
|
3992
|
+
const detachSignal = config.detachSignal;
|
|
3993
|
+
const onDetach = (): void => steeringSoftController.abort("user");
|
|
3994
|
+
if (detachSignal?.aborted) onDetach();
|
|
3995
|
+
else detachSignal?.addEventListener("abort", onDetach, { once: true });
|
|
3956
3996
|
// IRC interrupt records and background completions live in session-owned
|
|
3957
3997
|
// queues with no wake callback. Keep the timer fallback when either peek is
|
|
3958
3998
|
// present; system steering uses the event-driven path above and does not poll.
|
|
@@ -4011,6 +4051,7 @@ async function executeToolCalls(
|
|
|
4011
4051
|
steeringWatchAbortController.abort();
|
|
4012
4052
|
await steeringWatchPromise?.catch(() => undefined);
|
|
4013
4053
|
clearInterval(steeringWatchTimer);
|
|
4054
|
+
detachSignal?.removeEventListener("abort", onDetach);
|
|
4014
4055
|
}
|
|
4015
4056
|
|
|
4016
4057
|
for (const record of records) {
|
package/src/agent.ts
CHANGED
|
@@ -23,11 +23,13 @@ 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";
|
|
29
30
|
import { logger } from "@oh-my-pi/pi-utils";
|
|
30
31
|
import {
|
|
32
|
+
AgentLoopError,
|
|
31
33
|
abortReasonText,
|
|
32
34
|
agentLoop,
|
|
33
35
|
agentLoopContinue,
|
|
@@ -121,7 +123,7 @@ export interface AgentOptions {
|
|
|
121
123
|
* Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.
|
|
122
124
|
* Default filters to user/assistant/toolResult and converts attachments.
|
|
123
125
|
*/
|
|
124
|
-
convertToLlm?:
|
|
126
|
+
convertToLlm?: AgentLoopConfig["convertToLlm"];
|
|
125
127
|
|
|
126
128
|
/**
|
|
127
129
|
* Optional transform applied to context before convertToLlm.
|
|
@@ -133,7 +135,7 @@ export interface AgentOptions {
|
|
|
133
135
|
* Optional transform applied after provider context assembly and before
|
|
134
136
|
* telemetry capture/provider send.
|
|
135
137
|
*/
|
|
136
|
-
transformProviderContext?: (context: Context, model: Model) => Context | Promise<Context>;
|
|
138
|
+
transformProviderContext?: (context: Context, model: Model, signal?: AbortSignal) => Context | Promise<Context>;
|
|
137
139
|
|
|
138
140
|
/**
|
|
139
141
|
* Steering mode: "all" = send all steering messages at once, "one-at-a-time" = one per turn
|
|
@@ -312,9 +314,10 @@ export interface AgentOptions {
|
|
|
312
314
|
onToolChoiceUnavailable?: () => void;
|
|
313
315
|
|
|
314
316
|
/**
|
|
315
|
-
* Cursor exec handlers for local tool execution
|
|
317
|
+
* Cursor exec handlers for local tool execution, or a factory resolved on the first
|
|
318
|
+
* request dispatched to Cursor (including a mid-session model switch).
|
|
316
319
|
*/
|
|
317
|
-
cursorExecHandlers?: CursorExecHandlers;
|
|
320
|
+
cursorExecHandlers?: CursorExecHandlers | (() => Promise<CursorExecHandlers>);
|
|
318
321
|
/** Additional tools Cursor executes through its MCP request-context bridge, resolved before each provider call. */
|
|
319
322
|
getCursorTools?: () => AgentTool[];
|
|
320
323
|
|
|
@@ -429,9 +432,11 @@ export class Agent {
|
|
|
429
432
|
#queueListeners = new Set<() => void>();
|
|
430
433
|
#pauseListeners = new Set<(paused: boolean) => void>();
|
|
431
434
|
#abortController?: AbortController;
|
|
432
|
-
|
|
435
|
+
/** The running loop's `detachSignal` source; see {@link Agent.abort}. */
|
|
436
|
+
#detachController?: AbortController;
|
|
437
|
+
#convertToLlm: AgentLoopConfig["convertToLlm"];
|
|
433
438
|
#transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
|
|
434
|
-
#transformProviderContext?: (context: Context, model: Model) => Context | Promise<Context>;
|
|
439
|
+
#transformProviderContext?: (context: Context, model: Model, signal?: AbortSignal) => Context | Promise<Context>;
|
|
435
440
|
#sentToolDefinitions = new SentToolDefinitions();
|
|
436
441
|
#standbyTools: AgentTool[] = [];
|
|
437
442
|
#steeringQueue: AgentMessage[] = [];
|
|
@@ -482,6 +487,7 @@ export class Agent {
|
|
|
482
487
|
#maxRetryDelayMs?: number;
|
|
483
488
|
#getToolContext?: (toolCall?: ToolCallContext) => AgentToolContext | undefined;
|
|
484
489
|
#cursorExecHandlers?: CursorExecHandlers;
|
|
490
|
+
#loadCursorExecHandlers?: () => Promise<CursorExecHandlers>;
|
|
485
491
|
#getCursorTools?: () => AgentTool[];
|
|
486
492
|
#cursorOnToolResult?: CursorToolResultHandler;
|
|
487
493
|
#cwd?: string;
|
|
@@ -606,7 +612,12 @@ export class Agent {
|
|
|
606
612
|
this.#onResponse = opts.onResponse;
|
|
607
613
|
this.#onSseEvent = opts.onSseEvent;
|
|
608
614
|
this.#getToolContext = opts.getToolContext;
|
|
609
|
-
|
|
615
|
+
if (typeof opts.cursorExecHandlers === "function") {
|
|
616
|
+
const load = opts.cursorExecHandlers;
|
|
617
|
+
this.#loadCursorExecHandlers = async () => (this.#cursorExecHandlers ??= await load());
|
|
618
|
+
} else {
|
|
619
|
+
this.#cursorExecHandlers = opts.cursorExecHandlers;
|
|
620
|
+
}
|
|
610
621
|
this.#getCursorTools = opts.getCursorTools;
|
|
611
622
|
this.#cursorOnToolResult = opts.cursorOnToolResult;
|
|
612
623
|
this.#cwd = opts.cwd;
|
|
@@ -983,6 +994,7 @@ export class Agent {
|
|
|
983
994
|
async buildSideRequestContext(
|
|
984
995
|
llmMessages: Message[],
|
|
985
996
|
systemPrompt: string[] = this.#state.systemPrompt,
|
|
997
|
+
signal?: AbortSignal,
|
|
986
998
|
): Promise<Context> {
|
|
987
999
|
const model = this.#state.model;
|
|
988
1000
|
if (!model) throw new Error("No active model on agent");
|
|
@@ -999,7 +1011,7 @@ export class Agent {
|
|
|
999
1011
|
// Side requests reuse the main loop's sent definitions without recording their own; attached before the
|
|
1000
1012
|
// transform too, so a request-size clamp in it measures them.
|
|
1001
1013
|
context = this.#sentToolDefinitions.withInactiveTools(context, standby);
|
|
1002
|
-
if (this.#transformProviderContext) context = await this.#transformProviderContext(context, model);
|
|
1014
|
+
if (this.#transformProviderContext) context = await this.#transformProviderContext(context, model, signal);
|
|
1003
1015
|
context = this.#sentToolDefinitions.withInactiveTools(context, context.inactiveTools);
|
|
1004
1016
|
return context;
|
|
1005
1017
|
}
|
|
@@ -1694,7 +1706,14 @@ export class Agent {
|
|
|
1694
1706
|
this.#state.messages.length = 0;
|
|
1695
1707
|
}
|
|
1696
1708
|
|
|
1697
|
-
|
|
1709
|
+
/**
|
|
1710
|
+
* Abort the current run. `detachTools` first raises the running tool batch's
|
|
1711
|
+
* cooperative `steeringSignal` (see {@link AgentLoopConfig.detachSignal}), so
|
|
1712
|
+
* tools that can move their work into a background job do so instead of being
|
|
1713
|
+
* killed; they observe it before the abort.
|
|
1714
|
+
*/
|
|
1715
|
+
abort(reason?: unknown, options?: { detachTools?: boolean }) {
|
|
1716
|
+
if (options?.detachTools) this.#detachController?.abort();
|
|
1698
1717
|
this.#abortController?.abort(reason);
|
|
1699
1718
|
}
|
|
1700
1719
|
|
|
@@ -1921,6 +1940,8 @@ export class Agent {
|
|
|
1921
1940
|
const loopSignal = continuationSignal
|
|
1922
1941
|
? AbortSignal.any([loopAbortController.signal, continuationSignal])
|
|
1923
1942
|
: loopAbortController.signal;
|
|
1943
|
+
const detachController = new AbortController();
|
|
1944
|
+
this.#detachController = detachController;
|
|
1924
1945
|
this.#state.isStreaming = true;
|
|
1925
1946
|
this.#state.streamMessage = null;
|
|
1926
1947
|
this.#state.error = undefined;
|
|
@@ -2026,6 +2047,7 @@ export class Agent {
|
|
|
2026
2047
|
return refreshToolChoiceForActiveTools(options?.toolChoice, this.#state.tools);
|
|
2027
2048
|
};
|
|
2028
2049
|
|
|
2050
|
+
let requestModel: Model | undefined;
|
|
2029
2051
|
const config: AgentLoopConfig = {
|
|
2030
2052
|
model,
|
|
2031
2053
|
reasoning,
|
|
@@ -2039,6 +2061,7 @@ export class Agent {
|
|
|
2039
2061
|
serviceTier: this.#serviceTier,
|
|
2040
2062
|
hideThinkingSummary: this.#hideThinkingSummary,
|
|
2041
2063
|
interruptMode: this.#interruptMode,
|
|
2064
|
+
detachSignal: detachController.signal,
|
|
2042
2065
|
sessionId: this.#sessionId,
|
|
2043
2066
|
deadline: this.#deadline,
|
|
2044
2067
|
promptCacheKey: this.#promptCacheKey,
|
|
@@ -2081,6 +2104,7 @@ export class Agent {
|
|
|
2081
2104
|
}
|
|
2082
2105
|
: undefined,
|
|
2083
2106
|
cursorExecHandlers: this.#cursorExecHandlers,
|
|
2107
|
+
loadCursorExecHandlers: this.#loadCursorExecHandlers,
|
|
2084
2108
|
cursorOnToolResult,
|
|
2085
2109
|
cwd: this.#cwd,
|
|
2086
2110
|
getCwd: this.#cwdResolver,
|
|
@@ -2104,6 +2128,9 @@ export class Agent {
|
|
|
2104
2128
|
onAssistantMessageEvent: this.#onAssistantMessageEvent,
|
|
2105
2129
|
onHarmonyLeak: this.#onHarmonyLeak,
|
|
2106
2130
|
onTurnEnd: (messages, signal, context) => this.#onTurnEnd?.(messages, signal, context),
|
|
2131
|
+
onTurnEndEmitted: () => {
|
|
2132
|
+
requestModel = undefined;
|
|
2133
|
+
},
|
|
2107
2134
|
onPauseChange: paused => {
|
|
2108
2135
|
if (this.#isPaused === paused) return;
|
|
2109
2136
|
this.#isPaused = paused;
|
|
@@ -2114,7 +2141,10 @@ export class Agent {
|
|
|
2114
2141
|
onToolChoiceRejected: () => {
|
|
2115
2142
|
if (claimedToolChoice !== undefined) this.#deferredToolChoice = claimedToolChoice;
|
|
2116
2143
|
},
|
|
2117
|
-
getModel: () =>
|
|
2144
|
+
getModel: () => {
|
|
2145
|
+
requestModel = this.#state.model ?? model;
|
|
2146
|
+
return requestModel;
|
|
2147
|
+
},
|
|
2118
2148
|
getReasoning: () => this.#state.thinkingLevel,
|
|
2119
2149
|
getDisableReasoning: () => this.#state.disableReasoning,
|
|
2120
2150
|
getServiceTier: this.#serviceTierResolver,
|
|
@@ -2244,6 +2274,14 @@ export class Agent {
|
|
|
2244
2274
|
: err instanceof Error
|
|
2245
2275
|
? err.message
|
|
2246
2276
|
: String(err);
|
|
2277
|
+
const errorModel = requestModel ?? this.#state.model ?? model;
|
|
2278
|
+
const errorStatus = stoppedForAbort ? undefined : AIError.status(err);
|
|
2279
|
+
const errorId = stoppedForAbort
|
|
2280
|
+
? errorMessage === "Request was aborted"
|
|
2281
|
+
? AIError.create(AIError.Flag.Abort)
|
|
2282
|
+
: AIError.classify(loopSignal.reason) || undefined
|
|
2283
|
+
: AIError.classify(err, errorModel.api) || undefined;
|
|
2284
|
+
const errorFromAgentLoop = (!stoppedForAbort && err instanceof AgentLoopError) || undefined;
|
|
2247
2285
|
const shouldEmitVisibleError = !stoppedForAbort;
|
|
2248
2286
|
const assistantPartial = partial?.role === "assistant" ? partial : undefined;
|
|
2249
2287
|
const hadAssistantStart = assistantPartial !== undefined;
|
|
@@ -2271,13 +2309,16 @@ export class Agent {
|
|
|
2271
2309
|
),
|
|
2272
2310
|
stopReason: "error",
|
|
2273
2311
|
errorMessage,
|
|
2312
|
+
errorStatus,
|
|
2313
|
+
errorId,
|
|
2314
|
+
errorFromAgentLoop,
|
|
2274
2315
|
}
|
|
2275
2316
|
: {
|
|
2276
2317
|
role: "assistant",
|
|
2277
2318
|
content: [{ type: "text", text: "" }],
|
|
2278
|
-
api:
|
|
2279
|
-
provider:
|
|
2280
|
-
model:
|
|
2319
|
+
api: errorModel.api,
|
|
2320
|
+
provider: errorModel.provider,
|
|
2321
|
+
model: errorModel.id,
|
|
2281
2322
|
usage: {
|
|
2282
2323
|
input: 0,
|
|
2283
2324
|
output: 0,
|
|
@@ -2288,6 +2329,9 @@ export class Agent {
|
|
|
2288
2329
|
},
|
|
2289
2330
|
stopReason: stoppedForAbort ? "aborted" : "error",
|
|
2290
2331
|
errorMessage,
|
|
2332
|
+
errorStatus,
|
|
2333
|
+
errorId,
|
|
2334
|
+
errorFromAgentLoop,
|
|
2291
2335
|
timestamp: Date.now(),
|
|
2292
2336
|
};
|
|
2293
2337
|
|
|
@@ -2363,6 +2407,7 @@ export class Agent {
|
|
|
2363
2407
|
this.#isPaused = false;
|
|
2364
2408
|
this.#restoreUndeliveredQueuedMessages(loopAbortController);
|
|
2365
2409
|
resolveRun?.();
|
|
2410
|
+
if (this.#detachController === detachController) this.#detachController = undefined;
|
|
2366
2411
|
if (this.#abortController === loopAbortController) {
|
|
2367
2412
|
this.#state.isStreaming = false;
|
|
2368
2413
|
this.#state.streamMessage = null;
|
|
@@ -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/compaction/openai.ts
CHANGED
|
@@ -958,6 +958,7 @@ export async function requestOpenAiRemoteCompaction(
|
|
|
958
958
|
providerType: model.providerType,
|
|
959
959
|
protocol: "openai",
|
|
960
960
|
sessionId: opts?.sessionId,
|
|
961
|
+
compat: model.compat,
|
|
961
962
|
cacheAffinity: resolveOpenCodeGoCacheAffinity(
|
|
962
963
|
remoteCompactionPolicyModel(model),
|
|
963
964
|
opts?.promptCacheKey ? promptCacheSessionId : undefined,
|
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/telemetry.ts
CHANGED
|
@@ -40,16 +40,21 @@ import {
|
|
|
40
40
|
type Usage,
|
|
41
41
|
} from "@oh-my-pi/pi-ai";
|
|
42
42
|
import { $otelEnv } from "@oh-my-pi/pi-utils";
|
|
43
|
-
import
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
}
|
|
43
|
+
import type * as OtelApi from "@opentelemetry/api";
|
|
44
|
+
import type { Attributes, AttributeValue, Span, SpanKind, SpanStatusCode, Tracer } from "@opentelemetry/api";
|
|
45
|
+
|
|
46
|
+
// Cached lazy loader: keeps @opentelemetry/api (~190ms of CJS require chains)
|
|
47
|
+
// off CLI startup until telemetry is actually enabled or a consumer touches it.
|
|
48
|
+
let otelApiCache: typeof OtelApi | undefined;
|
|
49
|
+
function otelApi(): typeof OtelApi {
|
|
50
|
+
if (!otelApiCache) otelApiCache = require("@opentelemetry/api") as typeof OtelApi;
|
|
51
|
+
return otelApiCache;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Numeric constants matching @opentelemetry/api's SpanKind and SpanStatusCode enums.
|
|
55
|
+
const SPAN_KIND_INTERNAL = 0 as SpanKind;
|
|
56
|
+
const SPAN_KIND_CLIENT = 2 as SpanKind;
|
|
57
|
+
const SPAN_STATUS_ERROR = 2 as SpanStatusCode;
|
|
53
58
|
import { AgentRunCollector, type AgentRunCoverage, type AgentRunSummary, type ToolStatus } from "./run-collector";
|
|
54
59
|
import type { AgentTool } from "./types";
|
|
55
60
|
|
|
@@ -438,7 +443,7 @@ export function resolveTelemetry(
|
|
|
438
443
|
sessionId: string | undefined,
|
|
439
444
|
): AgentTelemetry | undefined {
|
|
440
445
|
if (!config) return undefined;
|
|
441
|
-
const tracer = config.tracer ?? trace.getTracer(config.tracerName ?? DEFAULT_TRACER_NAME);
|
|
446
|
+
const tracer = config.tracer ?? otelApi().trace.getTracer(config.tracerName ?? DEFAULT_TRACER_NAME);
|
|
442
447
|
const contentCapture = resolveContentCapture(config.captureMessageContent);
|
|
443
448
|
return {
|
|
444
449
|
config,
|
|
@@ -516,6 +521,7 @@ function startSpan(
|
|
|
516
521
|
if (dynamicAttributes) Object.assign(attrs, dynamicAttributes);
|
|
517
522
|
if (options.attributes) Object.assign(attrs, options.attributes);
|
|
518
523
|
|
|
524
|
+
const { context, trace } = otelApi();
|
|
519
525
|
const ctx = options.parent ? trace.setSpan(context.active(), options.parent) : context.active();
|
|
520
526
|
const span = telemetry.tracer.startSpan(
|
|
521
527
|
name,
|
|
@@ -703,7 +709,7 @@ function safeOnSpanEnd(telemetry: AgentTelemetry | undefined, ctx: TelemetryHook
|
|
|
703
709
|
export function startInvokeAgentSpan(telemetry: AgentTelemetry | undefined, model: Model): Span | undefined {
|
|
704
710
|
const agentName = telemetry?.agent ? normalizeAgentIdentity(telemetry, telemetry.agent).name : undefined;
|
|
705
711
|
const name = agentName ? `invoke_agent ${agentName}` : "invoke_agent";
|
|
706
|
-
return startSpan(telemetry, "invoke_agent", name, { spanKind:
|
|
712
|
+
return startSpan(telemetry, "invoke_agent", name, { spanKind: SPAN_KIND_INTERNAL, model });
|
|
707
713
|
}
|
|
708
714
|
|
|
709
715
|
/** Stamp the final step count on the `invoke_agent` span. */
|
|
@@ -726,7 +732,7 @@ export function startChatSpan(
|
|
|
726
732
|
},
|
|
727
733
|
): Span | undefined {
|
|
728
734
|
const span = startSpan(telemetry, "chat", `chat ${model.id}`, {
|
|
729
|
-
spanKind:
|
|
735
|
+
spanKind: SPAN_KIND_CLIENT,
|
|
730
736
|
model,
|
|
731
737
|
parent: options.parent,
|
|
732
738
|
stepNumber: options.stepNumber,
|
|
@@ -1215,10 +1221,10 @@ export function failChatSpan(
|
|
|
1215
1221
|
if (err instanceof Error) {
|
|
1216
1222
|
span.recordException(err);
|
|
1217
1223
|
span.setAttribute(GenAIAttr.ErrorType, options.errorType ?? err.name ?? "Error");
|
|
1218
|
-
span.setStatus({ code:
|
|
1224
|
+
span.setStatus({ code: SPAN_STATUS_ERROR, message: err.message });
|
|
1219
1225
|
} else {
|
|
1220
1226
|
span.setAttribute(GenAIAttr.ErrorType, options.errorType ?? "Error");
|
|
1221
|
-
span.setStatus({ code:
|
|
1227
|
+
span.setStatus({ code: SPAN_STATUS_ERROR, message: String(err) });
|
|
1222
1228
|
}
|
|
1223
1229
|
telemetry?.collector.failChat(span, {
|
|
1224
1230
|
errorType: options.errorType ?? (err instanceof Error ? err.name || "Error" : "Error"),
|
|
@@ -1585,7 +1591,7 @@ function mapStopReason(reason: StopReason | undefined): string | undefined {
|
|
|
1585
1591
|
function applyTerminalStatus(span: Span, stopReason: StopReason | undefined, errorMessage: string | undefined): void {
|
|
1586
1592
|
if (stopReason === "error" || stopReason === "aborted") {
|
|
1587
1593
|
span.setAttribute(GenAIAttr.ErrorType, stopReason);
|
|
1588
|
-
span.setStatus({ code:
|
|
1594
|
+
span.setStatus({ code: SPAN_STATUS_ERROR, message: errorMessage ?? stopReason });
|
|
1589
1595
|
}
|
|
1590
1596
|
}
|
|
1591
1597
|
|
|
@@ -1619,7 +1625,7 @@ export async function recordManualChatTelemetry(
|
|
|
1619
1625
|
const span =
|
|
1620
1626
|
options.span ??
|
|
1621
1627
|
startSpan(telemetry, "chat", `chat ${options.model.id}`, {
|
|
1622
|
-
spanKind:
|
|
1628
|
+
spanKind: SPAN_KIND_CLIENT,
|
|
1623
1629
|
model: options.model,
|
|
1624
1630
|
parent: options.parent,
|
|
1625
1631
|
stepNumber: options.stepNumber,
|
|
@@ -1727,7 +1733,7 @@ export async function recordJudgmentTelemetry(
|
|
|
1727
1733
|
attributes[OmpGenAIAttr.JudgmentCachedQuestions] = options.cachedQuestions;
|
|
1728
1734
|
}
|
|
1729
1735
|
const span = startSpan(telemetry, "judgment", `judgment ${options.model}`, {
|
|
1730
|
-
spanKind:
|
|
1736
|
+
spanKind: SPAN_KIND_CLIENT,
|
|
1731
1737
|
attributes,
|
|
1732
1738
|
startTime: options.startTime,
|
|
1733
1739
|
});
|
|
@@ -1940,7 +1946,7 @@ export function startExecuteToolSpan(
|
|
|
1940
1946
|
};
|
|
1941
1947
|
if (options.tool?.description) attrs[GenAIAttr.ToolDescription] = options.tool.description;
|
|
1942
1948
|
const span = startSpan(telemetry, "execute_tool", `execute_tool ${options.toolName}`, {
|
|
1943
|
-
spanKind:
|
|
1949
|
+
spanKind: SPAN_KIND_INTERNAL,
|
|
1944
1950
|
parent: options.parent,
|
|
1945
1951
|
toolCallId: options.toolCallId,
|
|
1946
1952
|
toolName: options.toolName,
|
|
@@ -2006,7 +2012,7 @@ export function finishExecuteToolSpan(
|
|
|
2006
2012
|
span.setAttribute(EXECUTE_TOOL_STATUS_ATTR, status);
|
|
2007
2013
|
const msg =
|
|
2008
2014
|
options.errorObject instanceof Error ? options.errorObject.message : (options.errorMessage ?? errorType);
|
|
2009
|
-
span.setStatus({ code:
|
|
2015
|
+
span.setStatus({ code: SPAN_STATUS_ERROR, message: msg });
|
|
2010
2016
|
} else {
|
|
2011
2017
|
span.setAttribute(EXECUTE_TOOL_STATUS_ATTR, status);
|
|
2012
2018
|
}
|
|
@@ -2083,7 +2089,7 @@ export function finishInvokeAgentSpan(
|
|
|
2083
2089
|
if (options.errorObject instanceof Error) {
|
|
2084
2090
|
span.recordException(options.errorObject);
|
|
2085
2091
|
span.setAttribute(GenAIAttr.ErrorType, options.errorObject.name || "Error");
|
|
2086
|
-
span.setStatus({ code:
|
|
2092
|
+
span.setStatus({ code: SPAN_STATUS_ERROR, message: options.errorObject.message });
|
|
2087
2093
|
}
|
|
2088
2094
|
span.end();
|
|
2089
2095
|
return snapshot;
|
|
@@ -2184,6 +2190,7 @@ function applyAggregateAttributes(span: Span, summary: AgentRunSummary, coverage
|
|
|
2184
2190
|
*/
|
|
2185
2191
|
export function runInActiveSpan<T>(span: Span | undefined, fn: () => Promise<T>): Promise<T> {
|
|
2186
2192
|
if (!span) return fn();
|
|
2193
|
+
const { context, trace } = otelApi();
|
|
2187
2194
|
return context.with(trace.setSpan(context.active(), span), fn);
|
|
2188
2195
|
}
|
|
2189
2196
|
|
|
@@ -2215,7 +2222,7 @@ export function recordHandoff(
|
|
|
2215
2222
|
: `handoff to ${toAgent.name}`
|
|
2216
2223
|
: "handoff";
|
|
2217
2224
|
const span = startSpan(telemetry, "handoff", name, {
|
|
2218
|
-
spanKind:
|
|
2225
|
+
spanKind: SPAN_KIND_INTERNAL,
|
|
2219
2226
|
parent: options.parent,
|
|
2220
2227
|
attributes: { ...attrs, ...options.attributes },
|
|
2221
2228
|
});
|
|
@@ -2240,7 +2247,7 @@ export function setSpanAttribute(span: Span | undefined, key: string, value: Att
|
|
|
2240
2247
|
}
|
|
2241
2248
|
|
|
2242
2249
|
/** Re-exports so consumers can write hooks without depending on @opentelemetry/api directly. */
|
|
2243
|
-
export {
|
|
2250
|
+
export type { Attributes, Span, SpanKind, SpanStatusCode, Tracer };
|
|
2244
2251
|
|
|
2245
2252
|
function safeJson(value: unknown): string {
|
|
2246
2253
|
try {
|
package/src/types.ts
CHANGED
|
@@ -4,6 +4,7 @@ import type {
|
|
|
4
4
|
AssistantMessageEvent,
|
|
5
5
|
AssistantMessageEventStream,
|
|
6
6
|
Context,
|
|
7
|
+
CursorExecHandlers,
|
|
7
8
|
Effort,
|
|
8
9
|
ImageContent,
|
|
9
10
|
Message,
|
|
@@ -120,6 +121,9 @@ export type AgentBeforeModelCall = (
|
|
|
120
121
|
signal?: AbortSignal,
|
|
121
122
|
) => AgentPreModelCallResult | void | Promise<AgentPreModelCallResult | void>;
|
|
122
123
|
|
|
124
|
+
/** The tool-call shape a {@link SoftToolRequirement} inspects. */
|
|
125
|
+
export type SoftToolCall = { name: string; arguments?: Record<string, unknown> };
|
|
126
|
+
|
|
123
127
|
/**
|
|
124
128
|
* A soft tool requirement: the host wants `toolName` called before the loop
|
|
125
129
|
* runs other tools or yields, but WITHOUT paying the forced-`toolChoice` cost
|
|
@@ -148,7 +152,13 @@ export interface SoftToolRequirement {
|
|
|
148
152
|
* specific invocation shape (e.g. a `bash` call running a particular tool
|
|
149
153
|
* command) instead of any call to `toolName`. Escalation still forces `toolName`.
|
|
150
154
|
*/
|
|
151
|
-
satisfies?(toolCall:
|
|
155
|
+
satisfies?(toolCall: SoftToolCall): boolean;
|
|
156
|
+
/**
|
|
157
|
+
* Skipped-result text for a call to `toolName` that fails `satisfies`. Without
|
|
158
|
+
* it, that call gets the generic notice asking for a `toolName` call, which
|
|
159
|
+
* repeats the call the model just made instead of naming the invocation needed.
|
|
160
|
+
*/
|
|
161
|
+
unsatisfiedNotice?(toolCall: SoftToolCall): string;
|
|
152
162
|
/** Host-owned reminder messages, injected once per `id` activation. */
|
|
153
163
|
reminder: AgentMessage[];
|
|
154
164
|
}
|
|
@@ -189,6 +199,8 @@ export interface SteeringQueueState {
|
|
|
189
199
|
* Configuration for the agent loop.
|
|
190
200
|
*/
|
|
191
201
|
export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
202
|
+
/** Resolve the host bridge only when dispatching to the Cursor transport. */
|
|
203
|
+
loadCursorExecHandlers?: () => Promise<CursorExecHandlers>;
|
|
192
204
|
model: Model;
|
|
193
205
|
|
|
194
206
|
/** Reports whether this loop has reached a safe process-pause boundary. */
|
|
@@ -223,7 +235,7 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
|
223
235
|
metadataResolver?: (provider: string) => Record<string, unknown> | undefined;
|
|
224
236
|
|
|
225
237
|
/**
|
|
226
|
-
* Converts AgentMessage[] to LLM-compatible Message[]
|
|
238
|
+
* Converts AgentMessage[] to LLM-compatible Message[] for the model receiving this call.
|
|
227
239
|
*
|
|
228
240
|
* Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage
|
|
229
241
|
* that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,
|
|
@@ -245,7 +257,7 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
|
245
257
|
* })
|
|
246
258
|
* ```
|
|
247
259
|
*/
|
|
248
|
-
convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
|
|
260
|
+
convertToLlm: (messages: AgentMessage[], model: Model) => Message[] | Promise<Message[]>;
|
|
249
261
|
|
|
250
262
|
/**
|
|
251
263
|
* Optional transform applied to the context before `convertToLlm`.
|
|
@@ -271,7 +283,7 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
|
271
283
|
* normalization, and append-only context handling, but before telemetry capture
|
|
272
284
|
* and provider send.
|
|
273
285
|
*/
|
|
274
|
-
transformProviderContext?: (context: Context, model: Model) => Context | Promise<Context>;
|
|
286
|
+
transformProviderContext?: (context: Context, model: Model, signal?: AbortSignal) => Context | Promise<Context>;
|
|
275
287
|
|
|
276
288
|
/** Remembers sent tool definitions to fill {@link Context.inactiveTools}. */
|
|
277
289
|
sentToolDefinitions?: SentToolDefinitions;
|
|
@@ -327,6 +339,15 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
|
327
339
|
*/
|
|
328
340
|
waitForSteeringMessages?: (signal?: AbortSignal) => Promise<void>;
|
|
329
341
|
|
|
342
|
+
/**
|
|
343
|
+
* Aborted just before the host aborts the run when running tools should keep
|
|
344
|
+
* their work: raises the active tool batch's cooperative
|
|
345
|
+
* {@link ToolCallContext.steeringSignal} (source `"user"`) in either
|
|
346
|
+
* {@link interruptMode}, so a tool that can (auto-background bash/eval)
|
|
347
|
+
* moves its work into a background job instead of being killed.
|
|
348
|
+
*/
|
|
349
|
+
detachSignal?: AbortSignal;
|
|
350
|
+
|
|
330
351
|
/**
|
|
331
352
|
* Called when live steering dequeues messages via {@link getSteeringMessages}
|
|
332
353
|
* for the response being streamed. The loop records them in the transcript
|
|
@@ -634,6 +655,8 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
|
634
655
|
* post-turn steering.
|
|
635
656
|
*/
|
|
636
657
|
onTurnEnd?: (messages: AgentMessage[], signal?: AbortSignal, context?: AgentTurnEndContext) => Promise<void> | void;
|
|
658
|
+
/** Called synchronously when the loop pushes `turn_end` onto the event stream. */
|
|
659
|
+
onTurnEndEmitted?: () => void;
|
|
637
660
|
|
|
638
661
|
/**
|
|
639
662
|
* Called once an assistant message is finalized from the model stream, before
|
|
@@ -1188,6 +1211,13 @@ export interface AgentTool<
|
|
|
1188
1211
|
* obtains by delegating to this native tool through `ctx.invokeTool` follow this tool's contract.
|
|
1189
1212
|
*/
|
|
1190
1213
|
readonly delegationGuidance?: string;
|
|
1214
|
+
/**
|
|
1215
|
+
* Whether `command` is traffic this tool must run itself rather than shell work: the transport
|
|
1216
|
+
* host (`bash`) answers true for a line made only of session tool commands, which nothing else
|
|
1217
|
+
* can dispatch. A same-name extension replacement routes such a call back here instead of
|
|
1218
|
+
* executing it, so mounted tools keep working behind an override that does not delegate.
|
|
1219
|
+
*/
|
|
1220
|
+
servesToolCommandLine?(command: string): boolean;
|
|
1191
1221
|
/**
|
|
1192
1222
|
* On-demand documentation topics (`topic → markdown`), readable as
|
|
1193
1223
|
* `help://<tool>/<topic>`. Lets a tool keep large sub-surfaces out of its
|