@oh-my-pi/pi-agent-core 19.1.1 → 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 +16 -0
- package/dist/types/agent-loop.d.ts +8 -0
- package/dist/types/agent.d.ts +15 -6
- package/dist/types/telemetry.d.ts +2 -2
- package/dist/types/types.d.ts +26 -8
- package/package.json +8 -8
- package/src/agent-loop.ts +59 -19
- package/src/agent.ts +35 -9
- package/src/compaction/openai.ts +1 -0
- package/src/telemetry.ts +30 -23
- package/src/types.ts +25 -4
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,22 @@
|
|
|
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
|
+
|
|
5
21
|
## [19.1.1] - 2026-11-23
|
|
6
22
|
|
|
7
23
|
### Fixed
|
|
@@ -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 */
|
|
@@ -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
|
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
|
|
@@ -1341,6 +1353,7 @@ async function runLoopBody(
|
|
|
1341
1353
|
let hostToolChoice: ToolChoice | undefined;
|
|
1342
1354
|
let softRequiredTool: string | undefined;
|
|
1343
1355
|
let softSatisfies: SoftToolRequirement["satisfies"];
|
|
1356
|
+
let softUnsatisfiedNotice: SoftToolRequirement["unsatisfiedNotice"];
|
|
1344
1357
|
let directiveResolvedForTurn = false;
|
|
1345
1358
|
let turnOpen = false;
|
|
1346
1359
|
// A trailing assistant message with unpaired tool calls: the harness
|
|
@@ -1442,6 +1455,7 @@ async function runLoopBody(
|
|
|
1442
1455
|
hostToolChoice = directive === undefined || isSoftToolRequirement(directive) ? undefined : directive;
|
|
1443
1456
|
softRequiredTool = softReq?.toolName;
|
|
1444
1457
|
softSatisfies = softReq?.satisfies;
|
|
1458
|
+
softUnsatisfiedNotice = softReq?.unsatisfiedNotice;
|
|
1445
1459
|
const softRequirementId = softRequirementState.id;
|
|
1446
1460
|
if (softReq !== undefined) {
|
|
1447
1461
|
if (softReq.id !== softRequirementId) {
|
|
@@ -1726,11 +1740,6 @@ async function runLoopBody(
|
|
|
1726
1740
|
const additionalMessages: AgentMessage[] = [];
|
|
1727
1741
|
if (softNonCompliant && softRequiredTool !== undefined) {
|
|
1728
1742
|
SpeculativeOperationCoordinator.discardForMessage(message, "soft tool requirement deferred execution");
|
|
1729
|
-
if (softRequirementState.escalations >= MAX_SOFT_TOOL_ESCALATIONS) {
|
|
1730
|
-
throw new Error(
|
|
1731
|
-
`Soft tool requirement '${softRequiredTool}' was not satisfied after ${MAX_SOFT_TOOL_ESCALATIONS} forced turns; aborting to avoid an unbounded force loop.`,
|
|
1732
|
-
);
|
|
1733
|
-
}
|
|
1734
1743
|
// A soft-required tool is pending but the model called something else
|
|
1735
1744
|
// (or yielded). Do NOT execute the detour — pair each call with a
|
|
1736
1745
|
// skipped result and force the required tool next turn. This is the
|
|
@@ -1738,11 +1747,18 @@ async function runLoopBody(
|
|
|
1738
1747
|
// reminder pays no message-cache invalidation. Re-engage so the loop
|
|
1739
1748
|
// never yields while the requirement is unmet.
|
|
1740
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;
|
|
1741
1756
|
const result = createAbortedToolResult(
|
|
1742
1757
|
toolCall,
|
|
1743
1758
|
stream,
|
|
1744
1759
|
"skipped",
|
|
1745
|
-
|
|
1760
|
+
wrongInvocationNotice ??
|
|
1761
|
+
`Not executed: call the \`${softRequiredTool}\` tool to resolve the pending action before using other tools.`,
|
|
1746
1762
|
);
|
|
1747
1763
|
currentContext.messages.push(result);
|
|
1748
1764
|
newMessages.push(result);
|
|
@@ -1753,6 +1769,14 @@ async function runLoopBody(
|
|
|
1753
1769
|
status: "skipped",
|
|
1754
1770
|
});
|
|
1755
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
|
+
}
|
|
1756
1780
|
softRequirementState.forcedToolChoice = { type: "tool", name: softRequiredTool };
|
|
1757
1781
|
softRequirementState.escalations++;
|
|
1758
1782
|
hasMoreToolCalls = true;
|
|
@@ -2015,7 +2039,10 @@ function openLiveSteering(
|
|
|
2015
2039
|
const transformed = config.transformContext
|
|
2016
2040
|
? await config.transformContext(messages, bound(signal))
|
|
2017
2041
|
: messages;
|
|
2018
|
-
const converted = normalizeMessagesForProvider(
|
|
2042
|
+
const converted = normalizeMessagesForProvider(
|
|
2043
|
+
await config.convertToLlm(transformed, prepared.model),
|
|
2044
|
+
prepared.model,
|
|
2045
|
+
);
|
|
2019
2046
|
const userMessages: UserMessage[] = [];
|
|
2020
2047
|
for (const message of converted) {
|
|
2021
2048
|
if (message.role !== "user") return undefined;
|
|
@@ -2040,7 +2067,7 @@ async function prepareProviderCall(
|
|
|
2040
2067
|
messages = await config.transformContext(messages, signal);
|
|
2041
2068
|
}
|
|
2042
2069
|
|
|
2043
|
-
const llmMessages = await config.convertToLlm(messages);
|
|
2070
|
+
const llmMessages = await config.convertToLlm(messages, model);
|
|
2044
2071
|
const normalizedMessages = normalizeMessagesForProvider(llmMessages, model);
|
|
2045
2072
|
const ownedDialect: Dialect | undefined =
|
|
2046
2073
|
(config.getDialect ? config.getDialect(model) : config.dialect) ?? resolveOwnedDialectFromEnv(Bun.env.PI_DIALECT);
|
|
@@ -2072,7 +2099,7 @@ async function prepareProviderCall(
|
|
|
2072
2099
|
llmContext = config.sentToolDefinitions.withInactiveTools(llmContext, standbyTools);
|
|
2073
2100
|
}
|
|
2074
2101
|
if (config.transformProviderContext) {
|
|
2075
|
-
llmContext = await config.transformProviderContext(llmContext, model);
|
|
2102
|
+
llmContext = await config.transformProviderContext(llmContext, model, signal);
|
|
2076
2103
|
}
|
|
2077
2104
|
|
|
2078
2105
|
let promptToolWireTools: Context["tools"];
|
|
@@ -2257,6 +2284,9 @@ async function streamAssistantResponse(
|
|
|
2257
2284
|
|
|
2258
2285
|
try {
|
|
2259
2286
|
return await runInActiveSpan(chatSpan, async () => {
|
|
2287
|
+
if (model.api === "cursor-agent" && !config.cursorExecHandlers && config.loadCursorExecHandlers) {
|
|
2288
|
+
config.cursorExecHandlers = await config.loadCursorExecHandlers();
|
|
2289
|
+
}
|
|
2260
2290
|
onProviderStart?.();
|
|
2261
2291
|
let response = await streamFunction(model, llmContext, {
|
|
2262
2292
|
...config,
|
|
@@ -2403,16 +2433,7 @@ async function streamAssistantResponse(
|
|
|
2403
2433
|
}
|
|
2404
2434
|
}
|
|
2405
2435
|
finalMessage = snapshotAssistantMessage(finalMessage);
|
|
2406
|
-
|
|
2407
|
-
// and turns with a valid structured call. Only a failed text-only
|
|
2408
|
-
// call needs the recovery nudge.
|
|
2409
|
-
if (dsmlLeakRecoveryEnabled) {
|
|
2410
|
-
const hasToolCall = finalMessage.content.some(block => block.type === "toolCall");
|
|
2411
|
-
const removed = removeDsmlToolMarkupLeak(finalMessage);
|
|
2412
|
-
if (removed && finalMessage.stopReason === "stop" && !hasToolCall) {
|
|
2413
|
-
dsmlLeakMessages.add(finalMessage);
|
|
2414
|
-
}
|
|
2415
|
-
}
|
|
2436
|
+
if (dsmlLeakRecoveryEnabled && removeDsmlLeak(finalMessage)) dsmlLeakMessages.add(finalMessage);
|
|
2416
2437
|
// Expand inline macros (and any other registered rewrite) on the
|
|
2417
2438
|
// finalized message before it reaches the context, the UI, or tool
|
|
2418
2439
|
// dispatch — so a single mutation is the source of truth for all three.
|
|
@@ -2695,10 +2716,12 @@ async function streamAssistantResponse(
|
|
|
2695
2716
|
throw new HarmonyLeakInterruption(detection, removed, recovered);
|
|
2696
2717
|
}
|
|
2697
2718
|
}
|
|
2719
|
+
const dsmlLeakNudge = dsmlLeakRecoveryEnabled && removeDsmlLeak(trailing);
|
|
2698
2720
|
if (config.transformAssistantMessage) {
|
|
2699
2721
|
await config.transformAssistantMessage(trailing, requestSignal);
|
|
2700
2722
|
}
|
|
2701
2723
|
trailing = snapshotAssistantMessage(trailing);
|
|
2724
|
+
if (dsmlLeakNudge) dsmlLeakMessages.add(trailing);
|
|
2702
2725
|
const finalToolCallsCanDispatch =
|
|
2703
2726
|
!requestSignal?.aborted &&
|
|
2704
2727
|
(canDispatchFinalToolCalls?.(trailing) ??
|
|
@@ -2963,6 +2986,16 @@ interface PreparedToolCall {
|
|
|
2963
2986
|
/** Committed assistant messages whose unhealed DSML tool-call markup was stripped; the loop answers them with a failure nudge. */
|
|
2964
2987
|
const dsmlLeakMessages = new WeakSet<AssistantMessage>();
|
|
2965
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
|
+
|
|
2966
2999
|
/**
|
|
2967
3000
|
* Prepare results computed in the stream-done branch (before `message_start`/
|
|
2968
3001
|
* `message_end`) so a `beforeToolCall` args revision is baked into the message
|
|
@@ -3954,6 +3987,12 @@ async function executeToolCalls(
|
|
|
3954
3987
|
}
|
|
3955
3988
|
})()
|
|
3956
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 });
|
|
3957
3996
|
// IRC interrupt records and background completions live in session-owned
|
|
3958
3997
|
// queues with no wake callback. Keep the timer fallback when either peek is
|
|
3959
3998
|
// present; system steering uses the event-driven path above and does not poll.
|
|
@@ -4012,6 +4051,7 @@ async function executeToolCalls(
|
|
|
4012
4051
|
steeringWatchAbortController.abort();
|
|
4013
4052
|
await steeringWatchPromise?.catch(() => undefined);
|
|
4014
4053
|
clearInterval(steeringWatchTimer);
|
|
4054
|
+
detachSignal?.removeEventListener("abort", onDetach);
|
|
4015
4055
|
}
|
|
4016
4056
|
|
|
4017
4057
|
for (const record of records) {
|
package/src/agent.ts
CHANGED
|
@@ -29,6 +29,7 @@ import type { HarmonyAuditEvent } from "@oh-my-pi/pi-ai/utils/harmony-leak";
|
|
|
29
29
|
import { getBundledModel } from "@oh-my-pi/pi-catalog/models";
|
|
30
30
|
import { logger } from "@oh-my-pi/pi-utils";
|
|
31
31
|
import {
|
|
32
|
+
AgentLoopError,
|
|
32
33
|
abortReasonText,
|
|
33
34
|
agentLoop,
|
|
34
35
|
agentLoopContinue,
|
|
@@ -122,7 +123,7 @@ export interface AgentOptions {
|
|
|
122
123
|
* Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.
|
|
123
124
|
* Default filters to user/assistant/toolResult and converts attachments.
|
|
124
125
|
*/
|
|
125
|
-
convertToLlm?:
|
|
126
|
+
convertToLlm?: AgentLoopConfig["convertToLlm"];
|
|
126
127
|
|
|
127
128
|
/**
|
|
128
129
|
* Optional transform applied to context before convertToLlm.
|
|
@@ -134,7 +135,7 @@ export interface AgentOptions {
|
|
|
134
135
|
* Optional transform applied after provider context assembly and before
|
|
135
136
|
* telemetry capture/provider send.
|
|
136
137
|
*/
|
|
137
|
-
transformProviderContext?: (context: Context, model: Model) => Context | Promise<Context>;
|
|
138
|
+
transformProviderContext?: (context: Context, model: Model, signal?: AbortSignal) => Context | Promise<Context>;
|
|
138
139
|
|
|
139
140
|
/**
|
|
140
141
|
* Steering mode: "all" = send all steering messages at once, "one-at-a-time" = one per turn
|
|
@@ -313,9 +314,10 @@ export interface AgentOptions {
|
|
|
313
314
|
onToolChoiceUnavailable?: () => void;
|
|
314
315
|
|
|
315
316
|
/**
|
|
316
|
-
* 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).
|
|
317
319
|
*/
|
|
318
|
-
cursorExecHandlers?: CursorExecHandlers;
|
|
320
|
+
cursorExecHandlers?: CursorExecHandlers | (() => Promise<CursorExecHandlers>);
|
|
319
321
|
/** Additional tools Cursor executes through its MCP request-context bridge, resolved before each provider call. */
|
|
320
322
|
getCursorTools?: () => AgentTool[];
|
|
321
323
|
|
|
@@ -430,9 +432,11 @@ export class Agent {
|
|
|
430
432
|
#queueListeners = new Set<() => void>();
|
|
431
433
|
#pauseListeners = new Set<(paused: boolean) => void>();
|
|
432
434
|
#abortController?: AbortController;
|
|
433
|
-
|
|
435
|
+
/** The running loop's `detachSignal` source; see {@link Agent.abort}. */
|
|
436
|
+
#detachController?: AbortController;
|
|
437
|
+
#convertToLlm: AgentLoopConfig["convertToLlm"];
|
|
434
438
|
#transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
|
|
435
|
-
#transformProviderContext?: (context: Context, model: Model) => Context | Promise<Context>;
|
|
439
|
+
#transformProviderContext?: (context: Context, model: Model, signal?: AbortSignal) => Context | Promise<Context>;
|
|
436
440
|
#sentToolDefinitions = new SentToolDefinitions();
|
|
437
441
|
#standbyTools: AgentTool[] = [];
|
|
438
442
|
#steeringQueue: AgentMessage[] = [];
|
|
@@ -483,6 +487,7 @@ export class Agent {
|
|
|
483
487
|
#maxRetryDelayMs?: number;
|
|
484
488
|
#getToolContext?: (toolCall?: ToolCallContext) => AgentToolContext | undefined;
|
|
485
489
|
#cursorExecHandlers?: CursorExecHandlers;
|
|
490
|
+
#loadCursorExecHandlers?: () => Promise<CursorExecHandlers>;
|
|
486
491
|
#getCursorTools?: () => AgentTool[];
|
|
487
492
|
#cursorOnToolResult?: CursorToolResultHandler;
|
|
488
493
|
#cwd?: string;
|
|
@@ -607,7 +612,12 @@ export class Agent {
|
|
|
607
612
|
this.#onResponse = opts.onResponse;
|
|
608
613
|
this.#onSseEvent = opts.onSseEvent;
|
|
609
614
|
this.#getToolContext = opts.getToolContext;
|
|
610
|
-
|
|
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
|
+
}
|
|
611
621
|
this.#getCursorTools = opts.getCursorTools;
|
|
612
622
|
this.#cursorOnToolResult = opts.cursorOnToolResult;
|
|
613
623
|
this.#cwd = opts.cwd;
|
|
@@ -984,6 +994,7 @@ export class Agent {
|
|
|
984
994
|
async buildSideRequestContext(
|
|
985
995
|
llmMessages: Message[],
|
|
986
996
|
systemPrompt: string[] = this.#state.systemPrompt,
|
|
997
|
+
signal?: AbortSignal,
|
|
987
998
|
): Promise<Context> {
|
|
988
999
|
const model = this.#state.model;
|
|
989
1000
|
if (!model) throw new Error("No active model on agent");
|
|
@@ -1000,7 +1011,7 @@ export class Agent {
|
|
|
1000
1011
|
// Side requests reuse the main loop's sent definitions without recording their own; attached before the
|
|
1001
1012
|
// transform too, so a request-size clamp in it measures them.
|
|
1002
1013
|
context = this.#sentToolDefinitions.withInactiveTools(context, standby);
|
|
1003
|
-
if (this.#transformProviderContext) context = await this.#transformProviderContext(context, model);
|
|
1014
|
+
if (this.#transformProviderContext) context = await this.#transformProviderContext(context, model, signal);
|
|
1004
1015
|
context = this.#sentToolDefinitions.withInactiveTools(context, context.inactiveTools);
|
|
1005
1016
|
return context;
|
|
1006
1017
|
}
|
|
@@ -1695,7 +1706,14 @@ export class Agent {
|
|
|
1695
1706
|
this.#state.messages.length = 0;
|
|
1696
1707
|
}
|
|
1697
1708
|
|
|
1698
|
-
|
|
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();
|
|
1699
1717
|
this.#abortController?.abort(reason);
|
|
1700
1718
|
}
|
|
1701
1719
|
|
|
@@ -1922,6 +1940,8 @@ export class Agent {
|
|
|
1922
1940
|
const loopSignal = continuationSignal
|
|
1923
1941
|
? AbortSignal.any([loopAbortController.signal, continuationSignal])
|
|
1924
1942
|
: loopAbortController.signal;
|
|
1943
|
+
const detachController = new AbortController();
|
|
1944
|
+
this.#detachController = detachController;
|
|
1925
1945
|
this.#state.isStreaming = true;
|
|
1926
1946
|
this.#state.streamMessage = null;
|
|
1927
1947
|
this.#state.error = undefined;
|
|
@@ -2041,6 +2061,7 @@ export class Agent {
|
|
|
2041
2061
|
serviceTier: this.#serviceTier,
|
|
2042
2062
|
hideThinkingSummary: this.#hideThinkingSummary,
|
|
2043
2063
|
interruptMode: this.#interruptMode,
|
|
2064
|
+
detachSignal: detachController.signal,
|
|
2044
2065
|
sessionId: this.#sessionId,
|
|
2045
2066
|
deadline: this.#deadline,
|
|
2046
2067
|
promptCacheKey: this.#promptCacheKey,
|
|
@@ -2083,6 +2104,7 @@ export class Agent {
|
|
|
2083
2104
|
}
|
|
2084
2105
|
: undefined,
|
|
2085
2106
|
cursorExecHandlers: this.#cursorExecHandlers,
|
|
2107
|
+
loadCursorExecHandlers: this.#loadCursorExecHandlers,
|
|
2086
2108
|
cursorOnToolResult,
|
|
2087
2109
|
cwd: this.#cwd,
|
|
2088
2110
|
getCwd: this.#cwdResolver,
|
|
@@ -2259,6 +2281,7 @@ export class Agent {
|
|
|
2259
2281
|
? AIError.create(AIError.Flag.Abort)
|
|
2260
2282
|
: AIError.classify(loopSignal.reason) || undefined
|
|
2261
2283
|
: AIError.classify(err, errorModel.api) || undefined;
|
|
2284
|
+
const errorFromAgentLoop = (!stoppedForAbort && err instanceof AgentLoopError) || undefined;
|
|
2262
2285
|
const shouldEmitVisibleError = !stoppedForAbort;
|
|
2263
2286
|
const assistantPartial = partial?.role === "assistant" ? partial : undefined;
|
|
2264
2287
|
const hadAssistantStart = assistantPartial !== undefined;
|
|
@@ -2288,6 +2311,7 @@ export class Agent {
|
|
|
2288
2311
|
errorMessage,
|
|
2289
2312
|
errorStatus,
|
|
2290
2313
|
errorId,
|
|
2314
|
+
errorFromAgentLoop,
|
|
2291
2315
|
}
|
|
2292
2316
|
: {
|
|
2293
2317
|
role: "assistant",
|
|
@@ -2307,6 +2331,7 @@ export class Agent {
|
|
|
2307
2331
|
errorMessage,
|
|
2308
2332
|
errorStatus,
|
|
2309
2333
|
errorId,
|
|
2334
|
+
errorFromAgentLoop,
|
|
2310
2335
|
timestamp: Date.now(),
|
|
2311
2336
|
};
|
|
2312
2337
|
|
|
@@ -2382,6 +2407,7 @@ export class Agent {
|
|
|
2382
2407
|
this.#isPaused = false;
|
|
2383
2408
|
this.#restoreUndeliveredQueuedMessages(loopAbortController);
|
|
2384
2409
|
resolveRun?.();
|
|
2410
|
+
if (this.#detachController === detachController) this.#detachController = undefined;
|
|
2385
2411
|
if (this.#abortController === loopAbortController) {
|
|
2386
2412
|
this.#state.isStreaming = false;
|
|
2387
2413
|
this.#state.streamMessage = null;
|
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/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
|