@linxiraos/pi-agent-core 1.5.14 → 1.5.15
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 +47 -49
- package/README.md +7 -9
- package/THIRD-PARTY-NOTICES.txt +1 -1
- package/dist/types/agent-loop.d.ts +22 -0
- package/dist/types/agent.d.ts +21 -10
- package/dist/types/compaction/anthropic.d.ts +5 -6
- package/dist/types/compaction/bedrock.d.ts +3 -2
- package/dist/types/compaction/compaction-v2-streaming.d.ts +7 -3
- package/dist/types/compaction/compaction.d.ts +14 -2
- package/dist/types/compaction/entries.d.ts +2 -0
- package/dist/types/compaction/messages.d.ts +5 -2
- package/dist/types/compaction/openai.d.ts +3 -0
- package/dist/types/compaction/tool-protection.d.ts +1 -1
- package/dist/types/output-budget.d.ts +13 -0
- package/dist/types/replay-policy.d.ts +15 -1
- package/dist/types/sent-tool-definitions.d.ts +6 -3
- package/dist/types/telemetry.d.ts +2 -2
- package/dist/types/tool-arguments.d.ts +2 -1
- package/dist/types/types.d.ts +55 -26
- package/package.json +43 -43
- package/src/agent-loop.ts +120 -47
- package/src/agent.ts +103 -55
- package/src/compaction/anthropic.ts +26 -8
- package/src/compaction/bedrock.ts +6 -13
- package/src/compaction/branch-summarization.ts +2 -0
- package/src/compaction/compaction-v2-streaming.ts +22 -12
- package/src/compaction/compaction.ts +83 -7
- package/src/compaction/entries.ts +2 -0
- package/src/compaction/messages.ts +8 -2
- package/src/compaction/openai.ts +28 -24
- package/src/compaction/prompts/branch-summary.md +6 -0
- package/src/compaction/prompts/compaction-summary.md +9 -0
- package/src/compaction/prompts/compaction-turn-prefix.md +2 -0
- package/src/compaction/prompts/compaction-update-summary.md +10 -0
- package/src/compaction/prompts/handoff-document.md +9 -0
- package/src/compaction/prompts/handoff-summary-context.md +2 -1
- package/src/compaction/tool-protection.ts +8 -4
- package/src/compaction/utils.ts +1 -1
- package/src/output-budget.ts +31 -2
- package/src/replay-policy.ts +38 -3
- package/src/sent-tool-definitions.ts +20 -10
- package/src/speculative-execution.ts +29 -5
- package/src/telemetry.ts +31 -23
- package/src/tokenizer.ts +8 -1
- package/src/tool-arguments.ts +2 -1
- package/src/types.ts +54 -22
package/src/replay-policy.ts
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
1
|
-
import type { AssistantMessage, Message } from "@linxiraos/pi-ai";
|
|
1
|
+
import type { AssistantMessage, Message, ToolResultMessage } from "@linxiraos/pi-ai";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Model-facing text of a tool call the provider stream ended before it could run.
|
|
5
|
+
* The provider's error (`details.upstreamError`) stays in the session for the UI.
|
|
6
|
+
*/
|
|
7
|
+
export const PROVIDER_ERROR_NOT_EXECUTED_TEXT =
|
|
8
|
+
"Tool call was not executed because the provider stream ended with an error before the tool could run.";
|
|
2
9
|
|
|
3
10
|
/** Detects API-level provider refusals that are terminal errors, not dialogue to replay. */
|
|
4
11
|
export function isProviderRefusalMessage(message: AssistantMessage): boolean {
|
|
@@ -7,7 +14,35 @@ export function isProviderRefusalMessage(message: AssistantMessage): boolean {
|
|
|
7
14
|
return stopType === "refusal" || stopType === "sensitive";
|
|
8
15
|
}
|
|
9
16
|
|
|
10
|
-
/**
|
|
17
|
+
/**
|
|
18
|
+
* Detects the placeholder result agent-loop persists for a tool call whose
|
|
19
|
+
* assistant turn ended on a provider error (`source: "assistant_stop_error"`).
|
|
20
|
+
*/
|
|
21
|
+
function isProviderErrorPlaceholder(message: ToolResultMessage): boolean {
|
|
22
|
+
const details = message.details as { __synthetic?: unknown; source?: unknown } | undefined;
|
|
23
|
+
return details?.__synthetic === true && details.source === "assistant_stop_error";
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The provider replay form of one converted message, or `undefined` when it is
|
|
28
|
+
* not replayed. API-level refusals are dropped. A provider-error placeholder
|
|
29
|
+
* keeps its "not executed" fact but loses the provider's error text: replaying a
|
|
30
|
+
* refusal explanation ("…reverse engineering or duplicating model outputs…")
|
|
31
|
+
* feeds the classifier its own verdict and makes every later turn of the
|
|
32
|
+
* session likelier to be refused.
|
|
33
|
+
*/
|
|
34
|
+
export function toProviderReplayMessage(message: Message): Message | undefined {
|
|
35
|
+
if (message.role === "assistant") return isProviderRefusalMessage(message) ? undefined : message;
|
|
36
|
+
if (message.role !== "toolResult" || !isProviderErrorPlaceholder(message)) return message;
|
|
37
|
+
return { ...message, content: [{ type: "text", text: PROVIDER_ERROR_NOT_EXECUTED_TEXT }] };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Applies {@link toProviderReplayMessage} to live provider replay. */
|
|
11
41
|
export function filterProviderReplayMessages(messages: readonly Message[]): Message[] {
|
|
12
|
-
|
|
42
|
+
const replayed: Message[] = [];
|
|
43
|
+
for (const message of messages) {
|
|
44
|
+
const replay = toProviderReplayMessage(message);
|
|
45
|
+
if (replay) replayed.push(replay);
|
|
46
|
+
}
|
|
47
|
+
return replayed;
|
|
13
48
|
}
|
|
@@ -26,16 +26,21 @@ export class SentToolDefinitions {
|
|
|
26
26
|
/**
|
|
27
27
|
* `context` with {@link Context.inactiveTools} set to the definitions for names the latest
|
|
28
28
|
* `requestControls.tools.declared` in its messages holds that are not in its `tools`; cleared when
|
|
29
|
-
* there are none or the request declares no tools.
|
|
30
|
-
*
|
|
29
|
+
* there are none or the request declares no tools. A declared name this Agent never sent takes its
|
|
30
|
+
* `standby` definition (a resumed transcript declares standby tools a fresh process has not sent);
|
|
31
|
+
* names with neither are skipped, and the provider drops them from the declaration. Before any
|
|
32
|
+
* request declared tools, `standby` (minus active names) stands in, so the first declaration
|
|
33
|
+
* already holds tools that may activate later.
|
|
31
34
|
*/
|
|
32
|
-
withInactiveTools(context: Context): Context {
|
|
33
|
-
const inactiveTools = context.tools?.length
|
|
35
|
+
withInactiveTools(context: Context, standby?: readonly Tool[]): Context {
|
|
36
|
+
const inactiveTools = context.tools?.length
|
|
37
|
+
? this.#inactiveFor(context.messages, context.tools, standby)
|
|
38
|
+
: undefined;
|
|
34
39
|
if (!inactiveTools && !context.inactiveTools) return context;
|
|
35
40
|
return { ...context, inactiveTools };
|
|
36
41
|
}
|
|
37
42
|
|
|
38
|
-
#inactiveFor(messages: readonly Message[], active: readonly Tool[]): Tool[] | undefined {
|
|
43
|
+
#inactiveFor(messages: readonly Message[], active: readonly Tool[], standby?: readonly Tool[]): Tool[] | undefined {
|
|
39
44
|
let declared: readonly string[] | undefined;
|
|
40
45
|
for (let index = messages.length - 1; index >= 0; index--) {
|
|
41
46
|
const message = messages[index];
|
|
@@ -44,13 +49,18 @@ export class SentToolDefinitions {
|
|
|
44
49
|
break;
|
|
45
50
|
}
|
|
46
51
|
}
|
|
47
|
-
if (!declared) return undefined;
|
|
48
52
|
const activeNames = new Set(active.map(tool => tool.name));
|
|
49
53
|
const inactive: Tool[] = [];
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
+
if (declared) {
|
|
55
|
+
for (const name of declared) {
|
|
56
|
+
if (activeNames.has(name)) continue;
|
|
57
|
+
const tool = this.#byName.get(name) ?? standby?.find(candidate => candidate.name === name);
|
|
58
|
+
if (tool) inactive.push(tool);
|
|
59
|
+
}
|
|
60
|
+
} else if (standby) {
|
|
61
|
+
for (const tool of standby) {
|
|
62
|
+
if (!activeNames.has(tool.name)) inactive.push(tool);
|
|
63
|
+
}
|
|
54
64
|
}
|
|
55
65
|
return inactive.length > 0 ? inactive : undefined;
|
|
56
66
|
}
|
|
@@ -398,8 +398,18 @@ export class SpeculativeOperationCoordinator {
|
|
|
398
398
|
reason: string,
|
|
399
399
|
descendants = true,
|
|
400
400
|
): Promise<void> {
|
|
401
|
-
|
|
401
|
+
// Once execution completes with a usable result, #commitCandidate owns
|
|
402
|
+
// validation, commit, and rollback; discarding while claimed before
|
|
403
|
+
// completion must still proceed so pending claim()/commit() waiters unblock.
|
|
404
|
+
if (
|
|
405
|
+
candidate.state === "discarded" ||
|
|
406
|
+
candidate.committed ||
|
|
407
|
+
(candidate.claimed && candidate.state === "completed")
|
|
408
|
+
) {
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
402
411
|
candidate.state = "discarded";
|
|
412
|
+
candidate.claimed = false;
|
|
403
413
|
candidate.controller.abort();
|
|
404
414
|
candidate.rejectOutcome(new Error(reason));
|
|
405
415
|
const context = this.#createContext(candidate);
|
|
@@ -548,16 +558,26 @@ export class SpeculativeOperationCoordinator {
|
|
|
548
558
|
.map(candidate => this.#discardCandidate(candidate, "discarded", reason)),
|
|
549
559
|
);
|
|
550
560
|
}
|
|
561
|
+
#isClaimable(candidate: SpeculativeToolCandidate): boolean {
|
|
562
|
+
return !this.#closed && !candidate.claimed && candidate.state !== "discarded";
|
|
563
|
+
}
|
|
564
|
+
|
|
551
565
|
async #commitCandidate(
|
|
552
566
|
candidate: SpeculativeToolCandidate,
|
|
553
567
|
tool: AgentTool | undefined,
|
|
554
568
|
toolCall: AgentToolCall,
|
|
555
569
|
args: Readonly<Record<string, unknown>>,
|
|
570
|
+
signal?: AbortSignal,
|
|
556
571
|
): Promise<SpeculativeRawOutcome | undefined> {
|
|
557
|
-
if (candidate
|
|
572
|
+
if (!this.#isClaimable(candidate)) return undefined;
|
|
558
573
|
candidate.dispatchReachedAt = Date.now();
|
|
559
574
|
|
|
560
575
|
const fingerprintMatches = await candidateMatchesFingerprint(candidate, toolCall, args);
|
|
576
|
+
if (signal?.aborted) {
|
|
577
|
+
await this.#discardCandidate(candidate, "aborted", "speculative execution aborted");
|
|
578
|
+
signal.throwIfAborted();
|
|
579
|
+
}
|
|
580
|
+
if (!this.#isClaimable(candidate)) return undefined;
|
|
561
581
|
if (candidate.tool !== tool || !fingerprintMatches) {
|
|
562
582
|
await this.#discardCandidate(candidate, "fingerprint_mismatch", "final speculation fingerprint changed");
|
|
563
583
|
return undefined;
|
|
@@ -565,9 +585,13 @@ export class SpeculativeOperationCoordinator {
|
|
|
565
585
|
candidate.claimed = true;
|
|
566
586
|
let physicalOutcome: SpeculativePhysicalOutcome;
|
|
567
587
|
try {
|
|
568
|
-
physicalOutcome = await candidate.outcome;
|
|
569
|
-
} catch {
|
|
588
|
+
physicalOutcome = await (signal ? untilAborted(signal, candidate.outcome) : candidate.outcome);
|
|
589
|
+
} catch (error) {
|
|
570
590
|
candidate.claimed = false;
|
|
591
|
+
if (signal?.aborted) {
|
|
592
|
+
await this.#discardCandidate(candidate, "aborted", "speculative execution aborted");
|
|
593
|
+
throw error;
|
|
594
|
+
}
|
|
571
595
|
await this.#discardCandidate(candidate, "discarded", "speculative execution failed");
|
|
572
596
|
return undefined;
|
|
573
597
|
}
|
|
@@ -627,7 +651,7 @@ export class SpeculativeOperationCoordinator {
|
|
|
627
651
|
// after the earlier shared writers have exposed their final effects.
|
|
628
652
|
if (earlierEffectsSettled) await untilAborted(signal, earlierEffectsSettled);
|
|
629
653
|
signal?.throwIfAborted();
|
|
630
|
-
return this.#commitCandidate(candidate, tool, toolCall, args);
|
|
654
|
+
return this.#commitCandidate(candidate, tool, toolCall, args, signal);
|
|
631
655
|
}
|
|
632
656
|
|
|
633
657
|
admitFinalized(
|
package/src/telemetry.ts
CHANGED
|
@@ -40,16 +40,21 @@ import {
|
|
|
40
40
|
type Usage,
|
|
41
41
|
} from "@linxiraos/pi-ai";
|
|
42
42
|
import { $otelEnv } from "@linxiraos/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
|
});
|
|
@@ -1892,6 +1898,7 @@ export async function instrumentedCompleteSimple<TApi extends Api>(
|
|
|
1892
1898
|
? await retryTransientCompletion(runOnce, {
|
|
1893
1899
|
...span.retry,
|
|
1894
1900
|
provider: model.provider,
|
|
1901
|
+
baseUrl: model.baseUrl,
|
|
1895
1902
|
// Framework-owned: the caller must not be able to detach the
|
|
1896
1903
|
// abort signal or the header source by passing them itself.
|
|
1897
1904
|
signal: options.signal,
|
|
@@ -1939,7 +1946,7 @@ export function startExecuteToolSpan(
|
|
|
1939
1946
|
};
|
|
1940
1947
|
if (options.tool?.description) attrs[GenAIAttr.ToolDescription] = options.tool.description;
|
|
1941
1948
|
const span = startSpan(telemetry, "execute_tool", `execute_tool ${options.toolName}`, {
|
|
1942
|
-
spanKind:
|
|
1949
|
+
spanKind: SPAN_KIND_INTERNAL,
|
|
1943
1950
|
parent: options.parent,
|
|
1944
1951
|
toolCallId: options.toolCallId,
|
|
1945
1952
|
toolName: options.toolName,
|
|
@@ -2005,7 +2012,7 @@ export function finishExecuteToolSpan(
|
|
|
2005
2012
|
span.setAttribute(EXECUTE_TOOL_STATUS_ATTR, status);
|
|
2006
2013
|
const msg =
|
|
2007
2014
|
options.errorObject instanceof Error ? options.errorObject.message : (options.errorMessage ?? errorType);
|
|
2008
|
-
span.setStatus({ code:
|
|
2015
|
+
span.setStatus({ code: SPAN_STATUS_ERROR, message: msg });
|
|
2009
2016
|
} else {
|
|
2010
2017
|
span.setAttribute(EXECUTE_TOOL_STATUS_ATTR, status);
|
|
2011
2018
|
}
|
|
@@ -2082,7 +2089,7 @@ export function finishInvokeAgentSpan(
|
|
|
2082
2089
|
if (options.errorObject instanceof Error) {
|
|
2083
2090
|
span.recordException(options.errorObject);
|
|
2084
2091
|
span.setAttribute(GenAIAttr.ErrorType, options.errorObject.name || "Error");
|
|
2085
|
-
span.setStatus({ code:
|
|
2092
|
+
span.setStatus({ code: SPAN_STATUS_ERROR, message: options.errorObject.message });
|
|
2086
2093
|
}
|
|
2087
2094
|
span.end();
|
|
2088
2095
|
return snapshot;
|
|
@@ -2183,6 +2190,7 @@ function applyAggregateAttributes(span: Span, summary: AgentRunSummary, coverage
|
|
|
2183
2190
|
*/
|
|
2184
2191
|
export function runInActiveSpan<T>(span: Span | undefined, fn: () => Promise<T>): Promise<T> {
|
|
2185
2192
|
if (!span) return fn();
|
|
2193
|
+
const { context, trace } = otelApi();
|
|
2186
2194
|
return context.with(trace.setSpan(context.active(), span), fn);
|
|
2187
2195
|
}
|
|
2188
2196
|
|
|
@@ -2214,7 +2222,7 @@ export function recordHandoff(
|
|
|
2214
2222
|
: `handoff to ${toAgent.name}`
|
|
2215
2223
|
: "handoff";
|
|
2216
2224
|
const span = startSpan(telemetry, "handoff", name, {
|
|
2217
|
-
spanKind:
|
|
2225
|
+
spanKind: SPAN_KIND_INTERNAL,
|
|
2218
2226
|
parent: options.parent,
|
|
2219
2227
|
attributes: { ...attrs, ...options.attributes },
|
|
2220
2228
|
});
|
|
@@ -2239,7 +2247,7 @@ export function setSpanAttribute(span: Span | undefined, key: string, value: Att
|
|
|
2239
2247
|
}
|
|
2240
2248
|
|
|
2241
2249
|
/** Re-exports so consumers can write hooks without depending on @opentelemetry/api directly. */
|
|
2242
|
-
export {
|
|
2250
|
+
export type { Attributes, Span, SpanKind, SpanStatusCode, Tracer };
|
|
2243
2251
|
|
|
2244
2252
|
function safeJson(value: unknown): string {
|
|
2245
2253
|
try {
|
package/src/tokenizer.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { renderDemotedThinking } from "@linxiraos/pi-ai/dialect/demotion";
|
|
|
3
3
|
import { isFactoryDroidGeminiWire, keepsFactoryGeminiReasoning } from "@linxiraos/pi-ai/providers/factory-droid/gemini";
|
|
4
4
|
import { ollamaChatDropsOwnThinking } from "@linxiraos/pi-ai/providers/ollama";
|
|
5
5
|
import { completionsDropsOwnThinking, isLiteLLMThinkingSignature } from "@linxiraos/pi-ai/providers/openai-completions";
|
|
6
|
+
import { replaysSignedReasoningText } from "@linxiraos/pi-ai/utils/reasoning-source";
|
|
6
7
|
import {
|
|
7
8
|
getNativeResponsesHistoryItems,
|
|
8
9
|
getReplayableNativeResponsesHistoryItems,
|
|
@@ -570,7 +571,13 @@ export class Tokenizer {
|
|
|
570
571
|
}
|
|
571
572
|
if (this.#dropsOllamaThinking && ownOllamaTurn) continue;
|
|
572
573
|
// Chat-completions drops it unless LiteLLM replays it in `thinking_blocks`.
|
|
573
|
-
if (
|
|
574
|
+
if (
|
|
575
|
+
ownDroppedCompletionsTurn &&
|
|
576
|
+
!isLiteLLMThinkingSignature(block.thinkingSignature) &&
|
|
577
|
+
!replaysSignedReasoningText(block.thinkingSignature)
|
|
578
|
+
) {
|
|
579
|
+
continue;
|
|
580
|
+
}
|
|
574
581
|
if (this.#filtersReasoningHistory && this.#model !== undefined) {
|
|
575
582
|
// The demoted rendering is the visible text the request carries.
|
|
576
583
|
if (block.thinking.trim()) fragments.push(renderDemotedThinking(this.#model.id, block.thinking));
|
package/src/tool-arguments.ts
CHANGED
|
@@ -6,7 +6,8 @@ import type { AgentTool } from "./types";
|
|
|
6
6
|
* - `"parsed"`: a provider stream parsed the arguments, so `__parseError` is a
|
|
7
7
|
* genuine parse-failure sentinel and is never handed to a tool.
|
|
8
8
|
* - `"payload"`: the arguments are a payload the model wrote (eval tool bridge,
|
|
9
|
-
*
|
|
9
|
+
* a tool command line parsed into arguments), so those keys are forged and
|
|
10
|
+
* only stripped.
|
|
10
11
|
*/
|
|
11
12
|
export type ToolArgumentSource = "parsed" | "payload";
|
|
12
13
|
|
package/src/types.ts
CHANGED
|
@@ -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
|
|
@@ -145,10 +149,16 @@ export interface SoftToolRequirement {
|
|
|
145
149
|
/**
|
|
146
150
|
* Per-call compliance check: a turn satisfies the requirement only when every
|
|
147
151
|
* tool call passes. Defaults to `name === toolName`. Lets a host demand a
|
|
148
|
-
* specific invocation shape (e.g. `
|
|
149
|
-
* instead of any call to `toolName`. Escalation still forces `toolName`.
|
|
152
|
+
* specific invocation shape (e.g. a `bash` call running a particular tool
|
|
153
|
+
* command) instead of any call to `toolName`. Escalation still forces `toolName`.
|
|
154
|
+
*/
|
|
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.
|
|
150
160
|
*/
|
|
151
|
-
|
|
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
|
|
@@ -345,8 +366,9 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
|
345
366
|
*/
|
|
346
367
|
hasIrcInterrupts?: () => boolean | Promise<boolean>;
|
|
347
368
|
/**
|
|
348
|
-
* Peeks whether a background
|
|
349
|
-
* process) is queued for aside
|
|
369
|
+
* Peeks whether a background notice (finished job, exited supervised
|
|
370
|
+
* process, output a running job was asked to report) is queued for aside
|
|
371
|
+
* injection at the next boundary.
|
|
350
372
|
*
|
|
351
373
|
* Same rules as {@link hasIrcInterrupts}: non-consuming, only cuts
|
|
352
374
|
* *interruptible* waits short, in either interruptMode. Without
|
|
@@ -451,8 +473,8 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
|
451
473
|
/**
|
|
452
474
|
* Resolve a tool call whose name matched no advertised tool (including
|
|
453
475
|
* `customWireName` aliases). Lets hosts route calls to tools they expose
|
|
454
|
-
* through side
|
|
455
|
-
* with "Tool not found". Returning `undefined` keeps the failure.
|
|
476
|
+
* through a side transport (e.g. mounted tool commands run through `bash`)
|
|
477
|
+
* instead of failing with "Tool not found". Returning `undefined` keeps the failure.
|
|
456
478
|
*
|
|
457
479
|
* `advertised` is the very snapshot exact-name dispatch just searched — the
|
|
458
480
|
* set offered to THIS request. A host must resolve against it rather than
|
|
@@ -464,9 +486,9 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
|
464
486
|
resolveFallbackTool?: (name: string, advertised: readonly AgentTool<any>[]) => AgentTool<any> | undefined;
|
|
465
487
|
/**
|
|
466
488
|
* Names reachable through {@link resolveFallbackTool} but absent from the
|
|
467
|
-
* advertised set (e.g.
|
|
468
|
-
* plausible target when a call misses, so a mis-transcribed
|
|
469
|
-
* recoverable; never a dispatch source.
|
|
489
|
+
* advertised set (e.g. mounted tool commands run through `bash`). Consulted
|
|
490
|
+
* only to name a plausible target when a call misses, so a mis-transcribed
|
|
491
|
+
* command name is recoverable; never a dispatch source.
|
|
470
492
|
*/
|
|
471
493
|
suggestFallbackToolNames?: () => Iterable<string>;
|
|
472
494
|
|
|
@@ -633,6 +655,8 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
|
633
655
|
* post-turn steering.
|
|
634
656
|
*/
|
|
635
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;
|
|
636
660
|
|
|
637
661
|
/**
|
|
638
662
|
* Called once an assistant message is finalized from the model stream, before
|
|
@@ -1086,9 +1110,9 @@ export type ToolTier = "read" | "write" | "exec";
|
|
|
1086
1110
|
/**
|
|
1087
1111
|
* How an enabled tool is presented to the model. `"essential"` tools are exposed
|
|
1088
1112
|
* as normal top-level tools. `"discoverable"` tools are removed from the top-level
|
|
1089
|
-
* schema and either mounted
|
|
1090
|
-
* active) or surfaced through BM25 tool search — keeping their schemas
|
|
1091
|
-
* request. Selection (settings, `hidden`, `defaultInactive`, explicit `--tools`,
|
|
1113
|
+
* schema and either mounted as a tool command in the `bash` tool (when that
|
|
1114
|
+
* tool is active) or surfaced through BM25 tool search — keeping their schemas
|
|
1115
|
+
* off every request. Selection (settings, `hidden`, `defaultInactive`, explicit `--tools`,
|
|
1092
1116
|
* provider availability) decides whether a tool is enabled; `loadMode` only
|
|
1093
1117
|
* decides how an enabled tool is presented.
|
|
1094
1118
|
*/
|
|
@@ -1111,11 +1135,6 @@ export type ToolApprovalDecision =
|
|
|
1111
1135
|
reason?: string;
|
|
1112
1136
|
override?: boolean;
|
|
1113
1137
|
policy?: "allow" | "deny" | "prompt";
|
|
1114
|
-
/** User-policy key for this decision. When set, `tools.approval.<policyKey>`
|
|
1115
|
-
* is consulted instead of `tools.approval.<tool.name>`. Lets a dispatcher
|
|
1116
|
-
* tool (e.g. `write` for an `xd://` device call) scope user allow/deny/
|
|
1117
|
-
* prompt policies to the tool it dispatches into. */
|
|
1118
|
-
policyKey?: string;
|
|
1119
1138
|
};
|
|
1120
1139
|
export type ToolApproval = ToolApprovalDecision | ((args: unknown, context?: AgentToolContext) => ToolApprovalDecision);
|
|
1121
1140
|
|
|
@@ -1192,9 +1211,16 @@ export interface AgentTool<
|
|
|
1192
1211
|
* obtains by delegating to this native tool through `ctx.invokeTool` follow this tool's contract.
|
|
1193
1212
|
*/
|
|
1194
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;
|
|
1195
1221
|
/**
|
|
1196
1222
|
* On-demand documentation topics (`topic → markdown`), readable as
|
|
1197
|
-
* `
|
|
1223
|
+
* `help://<tool>/<topic>`. Lets a tool keep large sub-surfaces out of its
|
|
1198
1224
|
* description and advertise only a one-line pointer per topic.
|
|
1199
1225
|
*/
|
|
1200
1226
|
docTopics?(): Readonly<Record<string, string>>;
|
|
@@ -1317,6 +1343,12 @@ export interface AgentContext {
|
|
|
1317
1343
|
systemPrompt: string[];
|
|
1318
1344
|
messages: AgentMessage[];
|
|
1319
1345
|
tools?: AgentTool<any>[];
|
|
1346
|
+
/**
|
|
1347
|
+
* Inactive tools that may become active later in the conversation. A provider that announces tool changes
|
|
1348
|
+
* in-band (Anthropic `tool_addition`) declares them from the first request, so activating one leaves the
|
|
1349
|
+
* cached prefix intact. See {@link SentToolDefinitions.withInactiveTools}.
|
|
1350
|
+
*/
|
|
1351
|
+
standbyTools?: AgentTool<any>[];
|
|
1320
1352
|
}
|
|
1321
1353
|
|
|
1322
1354
|
/**
|