@oh-my-pi/pi-agent-core 18.19.0 → 18.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,18 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [18.20.1] - 2026-11-14
6
+
7
+ ### Fixed
8
+
9
+ - Corrected context cost estimates for requests that omit reasoning history, so billing estimates now include thinking text only when it is sent or reconstructed for a tool call.
10
+
11
+ ## [18.20.0] - 2026-11-12
12
+
13
+ ### Changed
14
+
15
+ - `prepareCompaction()` runs as the `compaction.prepare` loop phase, so a `ui.loop-blocked` stall from a cold token walk over a long branch names compaction instead of "unknown" ([#15027](https://github.com/can1357/oh-my-pi/issues/15027), [#18867](https://github.com/can1357/oh-my-pi/pull/18867) by [@wolfiesch](https://github.com/wolfiesch))
16
+
5
17
  ## [18.18.9] - 2026-11-11
6
18
 
7
19
  ### Added
@@ -104,7 +104,7 @@ export declare function shouldUseProviderNativeCompaction(model: Model, settings
104
104
  * components. Provider-side orchestration tokens are billable but never replay
105
105
  * into the conversation prefix, so they are excluded from context sizing.
106
106
  */
107
- export declare function calculateContextTokens(usage: Usage): number;
107
+ export declare function calculateContextTokens(usage: Pick<Usage, "input" | "output" | "cacheRead" | "cacheWrite" | "totalTokens" | "contextTokens" | "orchestration">): number;
108
108
  export declare function calculatePromptTokens(usage: Usage): number;
109
109
  export declare function hasContextTokenUsage(usage: Usage): boolean;
110
110
  /**
@@ -416,7 +416,9 @@ export declare function findReadableCompactionIndex(pathEntries: SessionEntry[],
416
416
  /**
417
417
  * Pass the caller's warm `tokenizer` (the Agent's for the active model) so the
418
418
  * full-branch estimate walk hits its memo; the cold default is for one-shot
419
- * callers that have no live agent.
419
+ * callers that have no live agent. A cold walk over a long branch blocks the
420
+ * event loop for hundreds of milliseconds, so it runs as the
421
+ * `compaction.prepare` loop phase.
420
422
  */
421
423
  export declare function prepareCompaction(pathEntries: SessionEntry[], settings: CompactionSettings, activeModel?: Model, tokenizer?: Tokenizer): CompactionPreparation | undefined;
422
424
  /**
@@ -482,7 +482,7 @@ export interface JudgmentTelemetryOptions {
482
482
  readonly provider: string;
483
483
  /** Requested model id. */
484
484
  readonly model: string;
485
- /** Model that answered, when the provider resolves an alias (`jev-latest` → `jev-1.13.0`). */
485
+ /** Model that answered, when the provider resolves an alias (`jev-latest` → `jev-1.14.0`). */
486
486
  readonly responseModel?: string;
487
487
  /** Caller-level reason the judgment ran; stamped as {@link OmpGenAIAttr.JudgmentPurpose}. */
488
488
  readonly purpose: string;
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": "18.19.0",
4
+ "version": "18.20.1",
5
5
  "description": "General-purpose agent with transport abstraction, state management, and attachment support",
6
6
  "homepage": "https://omp.sh",
7
7
  "author": {
@@ -38,16 +38,16 @@
38
38
  "fmt": "oxfmt --no-error-on-unmatched-pattern 'src/**/*.{ts,tsx}' '{test,bench,examples,scripts}/**/*.ts' '*.ts'"
39
39
  },
40
40
  "dependencies": {
41
- "@oh-my-pi/pi-ai": "18.19.0",
42
- "@oh-my-pi/pi-catalog": "18.19.0",
43
- "@oh-my-pi/pi-natives": "18.19.0",
44
- "@oh-my-pi/pi-utils": "18.19.0",
45
- "@oh-my-pi/pi-wire": "18.19.0",
46
- "@oh-my-pi/snapcompact": "18.19.0",
41
+ "@oh-my-pi/pi-ai": "18.20.1",
42
+ "@oh-my-pi/pi-catalog": "18.20.1",
43
+ "@oh-my-pi/pi-natives": "18.20.1",
44
+ "@oh-my-pi/pi-utils": "18.20.1",
45
+ "@oh-my-pi/pi-wire": "18.20.1",
46
+ "@oh-my-pi/snapcompact": "18.20.1",
47
47
  "@opentelemetry/api": "^1.9.1"
48
48
  },
49
49
  "devDependencies": {
50
- "@oh-my-pi/omptype": "18.19.0",
50
+ "@oh-my-pi/omptype": "18.20.1",
51
51
  "@opentelemetry/context-async-hooks": "2.9.0",
52
52
  "@opentelemetry/sdk-trace-base": "2.9.0",
53
53
  "@types/bun": "^1.3.14"
@@ -35,7 +35,7 @@ import { stripOpenAIResponsesOutputOnlyStatusesForReplay } from "@oh-my-pi/pi-ai
35
35
  import { resolveCatalogPolicy } from "@oh-my-pi/pi-catalog/compat/catalog-policy";
36
36
  import { preferredDialect } from "@oh-my-pi/pi-catalog/identity";
37
37
  import { clampThinkingLevelForModel } from "@oh-my-pi/pi-catalog/model-thinking";
38
- import { isRecord, logger, prompt } from "@oh-my-pi/pi-utils";
38
+ import { isRecord, logger, prompt, withLoopPhase } from "@oh-my-pi/pi-utils";
39
39
  import * as snapcompact from "@oh-my-pi/snapcompact";
40
40
  import { type AgentTelemetry, instrumentedCompleteSimple } from "../telemetry";
41
41
  import { ThinkingLevel } from "../thinking";
@@ -262,7 +262,12 @@ export function shouldUseProviderNativeCompaction(
262
262
  * components. Provider-side orchestration tokens are billable but never replay
263
263
  * into the conversation prefix, so they are excluded from context sizing.
264
264
  */
265
- export function calculateContextTokens(usage: Usage): number {
265
+ export function calculateContextTokens(
266
+ usage: Pick<
267
+ Usage,
268
+ "input" | "output" | "cacheRead" | "cacheWrite" | "totalTokens" | "contextTokens" | "orchestration"
269
+ >,
270
+ ): number {
266
271
  if (usage.contextTokens !== undefined) {
267
272
  return Math.max(0, usage.contextTokens);
268
273
  }
@@ -1470,13 +1475,26 @@ export function findReadableCompactionIndex(
1470
1475
  /**
1471
1476
  * Pass the caller's warm `tokenizer` (the Agent's for the active model) so the
1472
1477
  * full-branch estimate walk hits its memo; the cold default is for one-shot
1473
- * callers that have no live agent.
1478
+ * callers that have no live agent. A cold walk over a long branch blocks the
1479
+ * event loop for hundreds of milliseconds, so it runs as the
1480
+ * `compaction.prepare` loop phase.
1474
1481
  */
1475
1482
  export function prepareCompaction(
1476
1483
  pathEntries: SessionEntry[],
1477
1484
  settings: CompactionSettings,
1478
1485
  activeModel?: Model,
1479
1486
  tokenizer: Tokenizer = new Tokenizer(activeModel),
1487
+ ): CompactionPreparation | undefined {
1488
+ return withLoopPhase("compaction.prepare", () =>
1489
+ prepareCompactionUnlabeled(pathEntries, settings, activeModel, tokenizer),
1490
+ );
1491
+ }
1492
+
1493
+ function prepareCompactionUnlabeled(
1494
+ pathEntries: SessionEntry[],
1495
+ settings: CompactionSettings,
1496
+ activeModel: Model | undefined,
1497
+ tokenizer: Tokenizer,
1480
1498
  ): CompactionPreparation | undefined {
1481
1499
  const lastEntry = pathEntries[pathEntries.length - 1];
1482
1500
  // A speculative native record may leave uncovered messages before the record.
package/src/telemetry.ts CHANGED
@@ -1687,7 +1687,7 @@ export interface JudgmentTelemetryOptions {
1687
1687
  readonly provider: string;
1688
1688
  /** Requested model id. */
1689
1689
  readonly model: string;
1690
- /** Model that answered, when the provider resolves an alias (`jev-latest` → `jev-1.13.0`). */
1690
+ /** Model that answered, when the provider resolves an alias (`jev-latest` → `jev-1.14.0`). */
1691
1691
  readonly responseModel?: string;
1692
1692
  /** Caller-level reason the judgment ran; stamped as {@link OmpGenAIAttr.JudgmentPurpose}. */
1693
1693
  readonly purpose: string;
package/src/tokenizer.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { AssistantMessage, Model } from "@oh-my-pi/pi-ai";
1
+ import type { Api, AssistantMessage, Model } from "@oh-my-pi/pi-ai";
2
2
  import { renderDemotedThinking } from "@oh-my-pi/pi-ai/dialect/demotion";
3
3
  import { isFactoryDroidGeminiWire, keepsFactoryGeminiReasoning } from "@oh-my-pi/pi-ai/providers/factory-droid/gemini";
4
4
  import { ollamaChatDropsOwnThinking } from "@oh-my-pi/pi-ai/providers/ollama";
@@ -51,21 +51,71 @@ type TokenizerModel = Pick<Model, "tokenizer"> &
51
51
  requestModelId?: string;
52
52
  };
53
53
 
54
- /** The model an assistant turn's native reasoning (signed thinking, Responses history) is replayed to. */
55
- interface ReasoningReplayReader {
56
- api: string;
54
+ /** The api/provider/model a {@link Tokenizer} counts for. */
55
+ interface ModelIdentity {
56
+ api: Api;
57
57
  provider: string;
58
58
  id: string;
59
59
  }
60
60
 
61
- function reasoningReplayReader(model: TokenizerModel | null | undefined): ReasoningReplayReader | undefined {
61
+ function modelIdentity(model: TokenizerModel | null | undefined): ModelIdentity | undefined {
62
62
  if (!model?.api || !model.provider || !model.id) return undefined;
63
- // Filtering targets strip native reasoning items before the request is encoded.
64
- const compat = model.compat;
65
- if (compat && "filterReasoningHistory" in compat && compat.filterReasoningHistory) return undefined;
66
63
  return { api: model.api, provider: model.provider, id: model.id };
67
64
  }
68
65
 
66
+ /**
67
+ * Whether the reader's resolved compat strips native `type: "reasoning"` items
68
+ * from replayed Responses history (`Model.compat.filterReasoningHistory`, a
69
+ * resolved boolean the request builders read too).
70
+ */
71
+ function filtersReasoningHistory(model: TokenizerModel | null | undefined): boolean {
72
+ const compat = model?.compat;
73
+ return compat !== undefined && "filterReasoningHistory" in compat && compat.filterReasoningHistory === true;
74
+ }
75
+
76
+ /** Which of a filtered reader's turns its encoder rebuilds thinking items for; `null` for none. */
77
+ type RebuiltThinkingTurns = "all-turns" | "tool-calls";
78
+
79
+ /**
80
+ * Whether the reader's Responses encoder rebuilds a filtered turn's own thinking
81
+ * into a synthetic reasoning item. `filterReasoningHistory` drops the native
82
+ * item, but the `requiresReasoningContent*` safety net puts the turn's thinking
83
+ * text back on the wire as the rebuilt item's `reasoning_text` — unless the
84
+ * target rejects synthetic items (`allowsSyntheticReasoningContentForToolCalls`),
85
+ * in which case reconstruction is off and the text is dropped with the item.
86
+ * Mirrors `buildParams`' `canReconstructReasoningReplay` and
87
+ * `convertResponsesAssistantMessage`' `carriedReasoningTexts`.
88
+ */
89
+ function rebuiltThinkingTurns(model: TokenizerModel | null | undefined): RebuiltThinkingTurns | null {
90
+ const compat = model?.compat;
91
+ // `buildParams` gates both reconstructions on a requested reasoning effort,
92
+ // which a per-message count cannot see; a model that cannot reason never
93
+ // reconstructs, and one that can counts the text it may send.
94
+ if (model?.reasoning !== true || !filtersReasoningHistory(model) || compat === undefined) return null;
95
+ if (
96
+ !("allowsSyntheticReasoningContentForToolCalls" in compat) ||
97
+ compat.allowsSyntheticReasoningContentForToolCalls !== true
98
+ ) {
99
+ return null;
100
+ }
101
+ if (
102
+ "requiresReasoningContentForAllAssistantTurns" in compat &&
103
+ compat.requiresReasoningContentForAllAssistantTurns === true
104
+ ) {
105
+ return "all-turns";
106
+ }
107
+ if ("requiresReasoningContentForToolCalls" in compat && compat.requiresReasoningContentForToolCalls === true) {
108
+ return "tool-calls";
109
+ }
110
+ return null;
111
+ }
112
+
113
+ /** The model an assistant turn's native reasoning (signed thinking, Responses history) is replayed to. */
114
+ function reasoningReplayReader(model: TokenizerModel | null | undefined): ModelIdentity | undefined {
115
+ // Filtering targets strip native reasoning items before the request is encoded.
116
+ return filtersReasoningHistory(model) ? undefined : modelIdentity(model);
117
+ }
118
+
69
119
  /** Identity of the reader whose replayed reasoning a {@link Tokenizer} counts; equal keys count it alike. */
70
120
  export function reasoningReplayKey(model: TokenizerModel | null | undefined): string {
71
121
  const reader = reasoningReplayReader(model);
@@ -218,7 +268,13 @@ export class Tokenizer {
218
268
  readonly #encoding: natives.Encoding | null;
219
269
  readonly #frameBilling: snapcompact.FrameBilling;
220
270
  readonly frameBillingKey: string;
221
- readonly #reasoningReader: ReasoningReplayReader | undefined;
271
+ readonly #reasoningReader: ModelIdentity | undefined;
272
+ /** The counted model's identity, set even when filtering leaves no reasoning reader. */
273
+ readonly #model: ModelIdentity | undefined;
274
+ /** Whether the reader strips native reasoning items out of its Responses requests. */
275
+ readonly #filtersReasoningHistory: boolean;
276
+ /** Which turns the reader's encoder rebuilds a stripped reasoning item for, carrying the thinking text. */
277
+ readonly #rebuiltThinkingTurns: RebuiltThinkingTurns | null;
222
278
  readonly #dropsOllamaThinking: boolean;
223
279
  readonly #dropsCompletionsThinking: boolean;
224
280
  /** Claude's own API and prefix-bound hosts keep another model's signature from their deployment. */
@@ -260,6 +316,9 @@ export class Tokenizer {
260
316
  this.#frameBilling = snapcompact.frameBilling(model ?? undefined);
261
317
  this.frameBillingKey = snapcompact.frameBillingKey(this.#frameBilling);
262
318
  this.#reasoningReader = reasoningReplayReader(model);
319
+ this.#model = modelIdentity(model);
320
+ this.#filtersReasoningHistory = filtersReasoningHistory(model);
321
+ this.#rebuiltThinkingTurns = rebuiltThinkingTurns(model);
263
322
  this.#dropsOllamaThinking = ollamaChatDropsOwnThinking(model);
264
323
  this.#dropsCompletionsThinking = completionsDropsOwnThinking(model);
265
324
  const compat = model?.compat;
@@ -474,12 +533,35 @@ export class Tokenizer {
474
533
  message.stopReason !== "toolUse" &&
475
534
  content.some(block => block.type === "toolCall");
476
535
  const untrustedIndex = invalidStop ? content.length - 1 : -1;
536
+ // A filtering Responses reader replays no reasoning item and its encoder
537
+ // drops the turn's own thinking blocks, so usually neither their text nor
538
+ // their signature reaches the wire (the reconstruction below is the one
539
+ // exception). Another model's thinking has no native slot there either;
540
+ // the transform demotes it to visible text, which is sent.
541
+ const ownThinkingFiltered =
542
+ this.#filtersReasoningHistory && this.#model !== undefined && isSameModelTurn(message, this.#model);
543
+ // A filtering reader drops the turn's own reasoning item, but its
544
+ // encoder rebuilds one — carrying this turn's thinking text — for
545
+ // targets that require reasoning content and accept a synthetic item.
546
+ // The item is only attached to a turn that emits another item.
547
+ const ownThinkingRebuilt =
548
+ ownThinkingFiltered &&
549
+ this.#rebuiltThinkingTurns !== null &&
550
+ message.stopReason !== "error" &&
551
+ (this.#rebuiltThinkingTurns === "all-turns" || content.some(block => block.type === "toolCall")) &&
552
+ content.some(block => block.type === "text" || block.type === "toolCall");
477
553
  let signedReasoning = false;
478
554
  for (let index = 0; index < content.length; index++) {
479
555
  const block = content[index];
480
556
  if (block.type === "text") {
481
557
  fragments.push(block.text);
482
558
  } else if (block.type === "thinking") {
559
+ if (ownThinkingFiltered) {
560
+ // The rebuilt item carries the thinking text verbatim; the
561
+ // signature stays off the wire either way.
562
+ if (ownThinkingRebuilt) fragments.push(block.thinking);
563
+ continue;
564
+ }
483
565
  // `transformMessages` drops another model's empty thinking and demotes the
484
566
  // rest to visible text; only the reader's own thinking stays native.
485
567
  if (ollamaReader && !ownOllamaTurn) {
@@ -489,6 +571,11 @@ export class Tokenizer {
489
571
  if (this.#dropsOllamaThinking && ownOllamaTurn) continue;
490
572
  // Chat-completions drops it unless LiteLLM replays it in `thinking_blocks`.
491
573
  if (ownDroppedCompletionsTurn && !isLiteLLMThinkingSignature(block.thinkingSignature)) continue;
574
+ if (this.#filtersReasoningHistory && this.#model !== undefined) {
575
+ // The demoted rendering is the visible text the request carries.
576
+ if (block.thinking.trim()) fragments.push(renderDemotedThinking(this.#model.id, block.thinking));
577
+ continue;
578
+ }
492
579
  fragments.push(block.thinking);
493
580
  // Providers charge for the opaque signature/reasoning payload that
494
581
  // rides alongside the thinking text (OpenAI Responses encrypted
@@ -617,6 +704,8 @@ export class Tokenizer {
617
704
  tokenizerEncodingForModel(model) === this.#encoding &&
618
705
  snapcompact.frameBillingKey(snapcompact.frameBilling(model ?? undefined)) === this.frameBillingKey &&
619
706
  reasoningReplayKey(model) === this.reasoningReplayKey &&
707
+ filtersReasoningHistory(model) === this.#filtersReasoningHistory &&
708
+ rebuiltThinkingTurns(model) === this.#rebuiltThinkingTurns &&
620
709
  resolveThinkingReplayTokens(model ?? {}) === this.thinkingReplayTokens &&
621
710
  ollamaChatDropsOwnThinking(model) === this.#dropsOllamaThinking &&
622
711
  completionsDropsOwnThinking(model) === this.#dropsCompletionsThinking &&