@linxiraos/pi-agent-core 1.5.13 → 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.
Files changed (46) hide show
  1. package/CHANGELOG.md +51 -47
  2. package/README.md +7 -9
  3. package/THIRD-PARTY-NOTICES.txt +1 -1
  4. package/dist/types/agent-loop.d.ts +22 -0
  5. package/dist/types/agent.d.ts +21 -10
  6. package/dist/types/compaction/anthropic.d.ts +5 -6
  7. package/dist/types/compaction/bedrock.d.ts +3 -2
  8. package/dist/types/compaction/compaction-v2-streaming.d.ts +7 -3
  9. package/dist/types/compaction/compaction.d.ts +14 -2
  10. package/dist/types/compaction/entries.d.ts +2 -0
  11. package/dist/types/compaction/messages.d.ts +5 -2
  12. package/dist/types/compaction/openai.d.ts +3 -0
  13. package/dist/types/compaction/tool-protection.d.ts +1 -1
  14. package/dist/types/output-budget.d.ts +13 -0
  15. package/dist/types/replay-policy.d.ts +15 -1
  16. package/dist/types/sent-tool-definitions.d.ts +6 -3
  17. package/dist/types/telemetry.d.ts +2 -2
  18. package/dist/types/tool-arguments.d.ts +2 -1
  19. package/dist/types/types.d.ts +55 -26
  20. package/package.json +43 -43
  21. package/src/agent-loop.ts +120 -47
  22. package/src/agent.ts +103 -55
  23. package/src/compaction/anthropic.ts +26 -8
  24. package/src/compaction/bedrock.ts +6 -13
  25. package/src/compaction/branch-summarization.ts +2 -0
  26. package/src/compaction/compaction-v2-streaming.ts +22 -12
  27. package/src/compaction/compaction.ts +83 -7
  28. package/src/compaction/entries.ts +2 -0
  29. package/src/compaction/messages.ts +8 -2
  30. package/src/compaction/openai.ts +28 -24
  31. package/src/compaction/prompts/branch-summary.md +6 -0
  32. package/src/compaction/prompts/compaction-summary.md +9 -0
  33. package/src/compaction/prompts/compaction-turn-prefix.md +2 -0
  34. package/src/compaction/prompts/compaction-update-summary.md +10 -0
  35. package/src/compaction/prompts/handoff-document.md +9 -0
  36. package/src/compaction/prompts/handoff-summary-context.md +2 -1
  37. package/src/compaction/tool-protection.ts +8 -4
  38. package/src/compaction/utils.ts +1 -1
  39. package/src/output-budget.ts +31 -2
  40. package/src/replay-policy.ts +38 -3
  41. package/src/sent-tool-definitions.ts +20 -10
  42. package/src/speculative-execution.ts +29 -5
  43. package/src/telemetry.ts +31 -23
  44. package/src/tokenizer.ts +8 -1
  45. package/src/tool-arguments.ts +2 -1
  46. package/src/types.ts +54 -22
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
@@ -683,6 +695,26 @@ export function agentLoop(
683
695
  return stream;
684
696
  }
685
697
 
698
+ /**
699
+ * Whether `message` is kept out of model context: drawn and saved, never sent (a `!!` bash run, a
700
+ * custom row sent with `excludeFromContext`).
701
+ */
702
+ export function isExcludedFromContext(message: AgentMessage): boolean {
703
+ return "excludeFromContext" in message && message.excludeFromContext === true;
704
+ }
705
+
706
+ /** Index of the last message the model sees, or -1; rows kept out of context after it do not change the request tail. */
707
+ export function lastContextIndex(messages: readonly AgentMessage[]): number {
708
+ let i = messages.length - 1;
709
+ while (i >= 0 && isExcludedFromContext(messages[i])) i--;
710
+ return i;
711
+ }
712
+
713
+ /** The last message the model sees (see {@link lastContextIndex}). */
714
+ export function lastContextMessage(messages: readonly AgentMessage[]): AgentMessage | undefined {
715
+ return messages[lastContextIndex(messages)];
716
+ }
717
+
686
718
  /**
687
719
  * Trailing assistant message whose runnable tool calls have no results yet.
688
720
  *
@@ -806,6 +838,7 @@ async function emitTurnEnd(
806
838
  runHookOnAbortedMessage = false,
807
839
  ): Promise<void> {
808
840
  stream.push({ type: "turn_end", message, toolResults });
841
+ config.onTurnEndEmitted?.();
809
842
  const terminalYield = signal?.reason === TERMINAL_TOOL_RESULT_ABORT_REASON;
810
843
  const isAbortedOrError =
811
844
  message.role === "assistant" && (message.stopReason === "aborted" || message.stopReason === "error");
@@ -1097,7 +1130,11 @@ function resolveIntentMode(intent: AgentTool["intent"]): "require" | "optional"
1097
1130
  return "require";
1098
1131
  }
1099
1132
 
1100
- function extractIntent(args: Record<string, unknown>): { intent?: string; strippedArgs: Record<string, unknown> } {
1133
+ /** Split a traced call's intent (`i`, trimmed, trailing periods dropped) from the arguments its tool reads. */
1134
+ export function extractIntent(args: Record<string, unknown>): {
1135
+ intent?: string;
1136
+ strippedArgs: Record<string, unknown>;
1137
+ } {
1101
1138
  const { [INTENT_FIELD]: intent, ...strippedArgs } = args;
1102
1139
  if (typeof intent !== "string") {
1103
1140
  return { strippedArgs };
@@ -1316,6 +1353,7 @@ async function runLoopBody(
1316
1353
  let hostToolChoice: ToolChoice | undefined;
1317
1354
  let softRequiredTool: string | undefined;
1318
1355
  let softSatisfies: SoftToolRequirement["satisfies"];
1356
+ let softUnsatisfiedNotice: SoftToolRequirement["unsatisfiedNotice"];
1319
1357
  let directiveResolvedForTurn = false;
1320
1358
  let turnOpen = false;
1321
1359
  // A trailing assistant message with unpaired tool calls: the harness
@@ -1417,6 +1455,7 @@ async function runLoopBody(
1417
1455
  hostToolChoice = directive === undefined || isSoftToolRequirement(directive) ? undefined : directive;
1418
1456
  softRequiredTool = softReq?.toolName;
1419
1457
  softSatisfies = softReq?.satisfies;
1458
+ softUnsatisfiedNotice = softReq?.unsatisfiedNotice;
1420
1459
  const softRequirementId = softRequirementState.id;
1421
1460
  if (softReq !== undefined) {
1422
1461
  if (softReq.id !== softRequirementId) {
@@ -1701,11 +1740,6 @@ async function runLoopBody(
1701
1740
  const additionalMessages: AgentMessage[] = [];
1702
1741
  if (softNonCompliant && softRequiredTool !== undefined) {
1703
1742
  SpeculativeOperationCoordinator.discardForMessage(message, "soft tool requirement deferred execution");
1704
- if (softRequirementState.escalations >= MAX_SOFT_TOOL_ESCALATIONS) {
1705
- throw new Error(
1706
- `Soft tool requirement '${softRequiredTool}' was not satisfied after ${MAX_SOFT_TOOL_ESCALATIONS} forced turns; aborting to avoid an unbounded force loop.`,
1707
- );
1708
- }
1709
1743
  // A soft-required tool is pending but the model called something else
1710
1744
  // (or yielded). Do NOT execute the detour — pair each call with a
1711
1745
  // skipped result and force the required tool next turn. This is the
@@ -1713,11 +1747,18 @@ async function runLoopBody(
1713
1747
  // reminder pays no message-cache invalidation. Re-engage so the loop
1714
1748
  // never yields while the requirement is unmet.
1715
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;
1716
1756
  const result = createAbortedToolResult(
1717
1757
  toolCall,
1718
1758
  stream,
1719
1759
  "skipped",
1720
- `Not executed: call the \`${softRequiredTool}\` tool to resolve the pending action before using other tools.`,
1760
+ wrongInvocationNotice ??
1761
+ `Not executed: call the \`${softRequiredTool}\` tool to resolve the pending action before using other tools.`,
1721
1762
  );
1722
1763
  currentContext.messages.push(result);
1723
1764
  newMessages.push(result);
@@ -1728,6 +1769,14 @@ async function runLoopBody(
1728
1769
  status: "skipped",
1729
1770
  });
1730
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
+ }
1731
1780
  softRequirementState.forcedToolChoice = { type: "tool", name: softRequiredTool };
1732
1781
  softRequirementState.escalations++;
1733
1782
  hasMoreToolCalls = true;
@@ -1990,7 +2039,10 @@ function openLiveSteering(
1990
2039
  const transformed = config.transformContext
1991
2040
  ? await config.transformContext(messages, bound(signal))
1992
2041
  : messages;
1993
- const converted = normalizeMessagesForProvider(await config.convertToLlm(transformed), prepared.model);
2042
+ const converted = normalizeMessagesForProvider(
2043
+ await config.convertToLlm(transformed, prepared.model),
2044
+ prepared.model,
2045
+ );
1994
2046
  const userMessages: UserMessage[] = [];
1995
2047
  for (const message of converted) {
1996
2048
  if (message.role !== "user") return undefined;
@@ -2015,35 +2067,39 @@ async function prepareProviderCall(
2015
2067
  messages = await config.transformContext(messages, signal);
2016
2068
  }
2017
2069
 
2018
- const llmMessages = await config.convertToLlm(messages);
2070
+ const llmMessages = await config.convertToLlm(messages, model);
2019
2071
  const normalizedMessages = normalizeMessagesForProvider(llmMessages, model);
2020
2072
  const ownedDialect: Dialect | undefined =
2021
2073
  (config.getDialect ? config.getDialect(model) : config.dialect) ?? resolveOwnedDialectFromEnv(Bun.env.PI_DIALECT);
2022
- const pruneToolDescriptions = !!config.pruneToolDescriptions && !ownedDialect;
2074
+ const toolOptions: NormalizeToolsOptions = {
2075
+ injectIntent: !!config.intentTracing,
2076
+ intentDescription: config.intentDescription,
2077
+ pruneDescriptions: !!config.pruneToolDescriptions && !ownedDialect,
2078
+ };
2023
2079
  let llmContext: Context;
2024
2080
  if (config.appendOnlyContext) {
2025
2081
  config.appendOnlyContext.syncMessages(normalizedMessages);
2026
2082
  llmContext = config.appendOnlyContext.build(context, {
2027
- intentTracing: !!config.intentTracing,
2028
- intentDescription: config.intentDescription,
2029
- pruneToolDescriptions,
2083
+ intentTracing: toolOptions.injectIntent,
2084
+ intentDescription: toolOptions.intentDescription,
2085
+ pruneToolDescriptions: toolOptions.pruneDescriptions,
2030
2086
  });
2031
2087
  } else {
2032
2088
  llmContext = {
2033
2089
  systemPrompt: context.systemPrompt,
2034
2090
  messages: normalizedMessages,
2035
- tools: normalizeTools(context.tools, {
2036
- injectIntent: !!config.intentTracing,
2037
- intentDescription: config.intentDescription,
2038
- pruneDescriptions: pruneToolDescriptions,
2039
- }),
2091
+ tools: normalizeTools(context.tools, toolOptions),
2040
2092
  };
2041
2093
  }
2042
2094
  // Before the transform too, so a request-size clamp in it measures the withdrawn definitions the provider
2043
- // re-declares; recomputed below against what the transform returns.
2044
- if (config.sentToolDefinitions) llmContext = config.sentToolDefinitions.withInactiveTools(llmContext);
2095
+ // re-declares; recomputed below against what the transform returns. Standby tools are normalized like
2096
+ // `tools`, so a standby tool's definition matches the one it is sent with once active.
2097
+ if (config.sentToolDefinitions) {
2098
+ const standbyTools = normalizeTools(context.standbyTools, toolOptions);
2099
+ llmContext = config.sentToolDefinitions.withInactiveTools(llmContext, standbyTools);
2100
+ }
2045
2101
  if (config.transformProviderContext) {
2046
- llmContext = await config.transformProviderContext(llmContext, model);
2102
+ llmContext = await config.transformProviderContext(llmContext, model, signal);
2047
2103
  }
2048
2104
 
2049
2105
  let promptToolWireTools: Context["tools"];
@@ -2059,7 +2115,9 @@ async function prepareProviderCall(
2059
2115
  // After `transformProviderContext`, so the recorded definitions are exactly what the provider receives.
2060
2116
  if (config.sentToolDefinitions) {
2061
2117
  if (llmContext.tools) config.sentToolDefinitions.record(llmContext.tools);
2062
- llmContext = config.sentToolDefinitions.withInactiveTools(llmContext);
2118
+ if (llmContext.inactiveTools) config.sentToolDefinitions.record(llmContext.inactiveTools);
2119
+ // The transformed standby definitions, when no request has declared tools yet.
2120
+ llmContext = config.sentToolDefinitions.withInactiveTools(llmContext, llmContext.inactiveTools);
2063
2121
  }
2064
2122
  return { model, context: llmContext, promptToolWireTools, ownedDialect };
2065
2123
  }
@@ -2226,6 +2284,9 @@ async function streamAssistantResponse(
2226
2284
 
2227
2285
  try {
2228
2286
  return await runInActiveSpan(chatSpan, async () => {
2287
+ if (model.api === "cursor-agent" && !config.cursorExecHandlers && config.loadCursorExecHandlers) {
2288
+ config.cursorExecHandlers = await config.loadCursorExecHandlers();
2289
+ }
2229
2290
  onProviderStart?.();
2230
2291
  let response = await streamFunction(model, llmContext, {
2231
2292
  ...config,
@@ -2372,16 +2433,7 @@ async function streamAssistantResponse(
2372
2433
  }
2373
2434
  }
2374
2435
  finalMessage = snapshotAssistantMessage(finalMessage);
2375
- // Unhealed DSML markup must not reach history, including reasoning
2376
- // and turns with a valid structured call. Only a failed text-only
2377
- // call needs the recovery nudge.
2378
- if (dsmlLeakRecoveryEnabled) {
2379
- const hasToolCall = finalMessage.content.some(block => block.type === "toolCall");
2380
- const removed = removeDsmlToolMarkupLeak(finalMessage);
2381
- if (removed && finalMessage.stopReason === "stop" && !hasToolCall) {
2382
- dsmlLeakMessages.add(finalMessage);
2383
- }
2384
- }
2436
+ if (dsmlLeakRecoveryEnabled && removeDsmlLeak(finalMessage)) dsmlLeakMessages.add(finalMessage);
2385
2437
  // Expand inline macros (and any other registered rewrite) on the
2386
2438
  // finalized message before it reaches the context, the UI, or tool
2387
2439
  // dispatch — so a single mutation is the source of truth for all three.
@@ -2664,10 +2716,12 @@ async function streamAssistantResponse(
2664
2716
  throw new HarmonyLeakInterruption(detection, removed, recovered);
2665
2717
  }
2666
2718
  }
2719
+ const dsmlLeakNudge = dsmlLeakRecoveryEnabled && removeDsmlLeak(trailing);
2667
2720
  if (config.transformAssistantMessage) {
2668
2721
  await config.transformAssistantMessage(trailing, requestSignal);
2669
2722
  }
2670
2723
  trailing = snapshotAssistantMessage(trailing);
2724
+ if (dsmlLeakNudge) dsmlLeakMessages.add(trailing);
2671
2725
  const finalToolCallsCanDispatch =
2672
2726
  !requestSignal?.aborted &&
2673
2727
  (canDispatchFinalToolCalls?.(trailing) ??
@@ -2932,6 +2986,16 @@ interface PreparedToolCall {
2932
2986
  /** Committed assistant messages whose unhealed DSML tool-call markup was stripped; the loop answers them with a failure nudge. */
2933
2987
  const dsmlLeakMessages = new WeakSet<AssistantMessage>();
2934
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
+
2935
2999
  /**
2936
3000
  * Prepare results computed in the stream-done branch (before `message_start`/
2937
3001
  * `message_end`) so a `beforeToolCall` args revision is baked into the message
@@ -2953,10 +3017,11 @@ function resolveToolForCall(
2953
3017
  return (
2954
3018
  tools?.find(t => t.name === toolCall.name) ??
2955
3019
  tools?.find(t => t.customWireName !== undefined && t.customWireName === toolCall.name) ??
2956
- // Not in the advertised set: let the host route side-transport tools
2957
- // (e.g. xd:// device mounts) called by their top-level name. It receives
2958
- // the snapshot searched above, never the agent's live tools, so a
2959
- // mid-stream roster change cannot widen what this request can reach.
3020
+ // Not in the advertised set: let the host route tools reached through a
3021
+ // side transport (e.g. mounted tool commands run through `bash`) called
3022
+ // by their top-level name. It receives the snapshot searched above, never
3023
+ // the agent's live tools, so a mid-stream roster change cannot widen what
3024
+ // this request can reach.
2960
3025
  resolveFallbackTool?.(toolCall.name, tools ?? [])
2961
3026
  );
2962
3027
  }
@@ -2977,9 +3042,10 @@ const MAX_TOOL_NAME_SUGGESTIONS = 3;
2977
3042
  * Both the last `__` and last `_` boundary are tried, so a name that lost only
2978
3043
  * its separator (`…__resolve_library_id`) and one that lost a whole id segment
2979
3044
  * (`…__read`) both recover. `fallbackNames` adds targets the host can route but
2980
- * never advertises (`xd://` device mounts); without them a corrupted device
2981
- * call is the one miss with nothing to suggest, because the capability exists
2982
- * in the session yet appears in no advertised name. Purely advisory: this only
3045
+ * never advertises (tools reached only as mounted tool commands through
3046
+ * `bash`); without them a corrupted command name is the one miss with nothing
3047
+ * to suggest, because the capability exists in the session yet appears in no
3048
+ * advertised name. Purely advisory: this only
2983
3049
  * builds an error string and never selects a tool, so dispatch semantics are
2984
3050
  * unchanged.
2985
3051
  */
@@ -3155,8 +3221,8 @@ async function prepareToolCallDispatch(
3155
3221
  if (toolCall.type !== "toolCall") continue;
3156
3222
  if ((toolCall as CursorExecResolvedCarrier)[kCursorExecResolved] === true) continue;
3157
3223
  const tool = resolveToolForCall(context.tools, toolCall, resolveFallbackTool);
3158
- // A host fallback accepts aliases (`xd://recall`, a mis-separated MCP
3159
- // name) that providers reject when replayed as a function-call name.
3224
+ // A host fallback accepts aliases (`recal`, a mis-separated MCP name)
3225
+ // that providers reject when replayed as a function-call name.
3160
3226
  // Record the call under the resolved tool's canonical name so history,
3161
3227
  // persistence, and replay agree; custom-wire calls keep their wire name.
3162
3228
  if (tool && toolCall.name !== tool.name && toolCall.name !== tool.customWireName) {
@@ -3701,9 +3767,9 @@ async function executeToolCalls(
3701
3767
  // ride the loop-owned ToolCallContext (surfacing as
3702
3768
  // `ctx.toolCall.*`); the host surfaces the sink on the context it
3703
3769
  // builds, and the loop hands that object to the tool untouched.
3704
- // Wrapper-dispatched nested calls (for example `write xd://…`)
3705
- // inherit the context, so their passive hook context joins this
3706
- // root call at the batch boundary.
3770
+ // Wrapper-dispatched nested calls (for example a `bash` call
3771
+ // running a mounted tool command) inherit the context, so their
3772
+ // passive hook context joins this root call at the batch boundary.
3707
3773
  const toolContext = getToolContext?.({
3708
3774
  batchId,
3709
3775
  index,
@@ -3921,6 +3987,12 @@ async function executeToolCalls(
3921
3987
  }
3922
3988
  })()
3923
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 });
3924
3996
  // IRC interrupt records and background completions live in session-owned
3925
3997
  // queues with no wake callback. Keep the timer fallback when either peek is
3926
3998
  // present; system steering uses the event-driven path above and does not poll.
@@ -3979,6 +4051,7 @@ async function executeToolCalls(
3979
4051
  steeringWatchAbortController.abort();
3980
4052
  await steeringWatchPromise?.catch(() => undefined);
3981
4053
  clearInterval(steeringWatchTimer);
4054
+ detachSignal?.removeEventListener("abort", onDetach);
3982
4055
  }
3983
4056
 
3984
4057
  for (const record of records) {
@@ -3996,9 +4069,9 @@ async function executeToolCalls(
3996
4069
 
3997
4070
  // Skipped calls never ran. Hook-prepared context also requires a non-error
3998
4071
  // final result; context the tool itself reported during execution stands.
3999
- // Within a call, tool-reported context (including nested `xd://` dispatch)
4000
- // precedes the hook's: wrappers release hook context only after the call
4001
- // succeeds, so this is the one order every dispatch path can produce.
4072
+ // Within a call, tool-reported context (including nested tool command
4073
+ // dispatch) precedes the hook's: wrappers release hook context only after
4074
+ // the call succeeds, so this is the one order every dispatch path can produce.
4002
4075
  const additionalContext = joinAdditionalContext(
4003
4076
  records
4004
4077
  .filter(record => !record.skipped)