pi-agy-acp 0.1.3 → 0.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/src/catalog.ts CHANGED
@@ -64,6 +64,10 @@ export function nearestEffort(
64
64
  return best ?? wanted
65
65
  }
66
66
 
67
+ function isValidContextWindow(value: unknown): value is number {
68
+ return typeof value === 'number' && Number.isInteger(value) && value > 0
69
+ }
70
+
67
71
  /** Observed catalog with a disk cache. */
68
72
  export class ModelCatalog {
69
73
  private models: CatalogModel[]
@@ -71,6 +75,8 @@ export class ModelCatalog {
71
75
  private efforts: Effort[] = [...EFFORTS]
72
76
  /** Efforts per model family; an empty array marks a fixed-effort model. */
73
77
  private byModel = new Map<string, Effort[]>()
78
+ /** Server-reported `max_context_tokens` keyed by model id. */
79
+ private readonly contextWindows = new Map<string, number>()
74
80
  /** Latest `availableModels` snapshot, kept for later option updates. */
75
81
  private available: readonly AvailableModel[] | undefined
76
82
  /** Whether a live ACP session has reported the catalog. */
@@ -83,6 +89,38 @@ export class ModelCatalog {
83
89
  this.models = this.load() ?? [...FALLBACK_MODELS]
84
90
  }
85
91
 
92
+ /**
93
+ * Cached server-issued context window (`max_context_tokens`) for one model.
94
+ * @param modelId - family id.
95
+ * @returns positive token limit, or `undefined` when never observed.
96
+ */
97
+ contextWindowFor(modelId: string): number | undefined {
98
+ return this.contextWindows.get(modelId)
99
+ }
100
+
101
+ /**
102
+ * Persist one observed context window if it is valid and changed.
103
+ * @param modelId - family id.
104
+ * @param contextWindow - observed `max_context_tokens`.
105
+ * @returns whether the stored window changed.
106
+ */
107
+ observeContextWindow(
108
+ modelId: string,
109
+ contextWindow: number | undefined,
110
+ ): boolean {
111
+ if (
112
+ typeof modelId !== 'string' ||
113
+ modelId.length === 0 ||
114
+ !isValidContextWindow(contextWindow)
115
+ ) {
116
+ return false
117
+ }
118
+ if (this.contextWindows.get(modelId) === contextWindow) return false
119
+ this.contextWindows.set(modelId, contextWindow)
120
+ this.save()
121
+ return true
122
+ }
123
+
86
124
  /** Current families. */
87
125
  list(): readonly CatalogModel[] {
88
126
  return this.models
@@ -215,6 +253,7 @@ export class ModelCatalog {
215
253
  models: this.models,
216
254
  efforts: this.efforts,
217
255
  byModel: Object.fromEntries(this.byModel),
256
+ contextWindows: Object.fromEntries(this.contextWindows),
218
257
  tier: this.tierInfo,
219
258
  },
220
259
  null,
@@ -233,8 +272,10 @@ export class ModelCatalog {
233
272
  models?: CatalogModel[]
234
273
  efforts?: string[]
235
274
  byModel?: Record<string, string[]>
275
+ contextWindows?: Record<string, unknown>
236
276
  tier?: AcpTierInfo
237
- }
277
+ } | null
278
+ if (parsed === null || typeof parsed !== 'object') return undefined
238
279
  this.tierInfo = normalizeTier(parsed.tier)
239
280
  if (Array.isArray(parsed.efforts)) {
240
281
  const efforts = parsed.efforts.filter((v): v is Effort =>
@@ -251,6 +292,15 @@ export class ModelCatalog {
251
292
  this.byModel.set(id, efforts)
252
293
  }
253
294
  }
295
+ if (
296
+ parsed.contextWindows !== null &&
297
+ typeof parsed.contextWindows === 'object'
298
+ ) {
299
+ for (const [id, value] of Object.entries(parsed.contextWindows)) {
300
+ if (id.length > 0 && isValidContextWindow(value))
301
+ this.contextWindows.set(id, value)
302
+ }
303
+ }
254
304
  const models = Array.isArray(parsed.models)
255
305
  ? parsed.models.filter(
256
306
  (m) => typeof m?.id === 'string' && typeof m?.name === 'string',
@@ -20,7 +20,11 @@ import type {
20
20
  AcpToolCallMeta,
21
21
  } from './acp-process.ts'
22
22
  import type { BridgeTool, BridgeToolResult } from './mcp-bridge.ts'
23
- import { AGENT_TOOL_PREFIX, CALL_TOOL_NAME } from './history.ts'
23
+ import {
24
+ AGENT_TOOL_PREFIX,
25
+ CALL_TOOL_NAME,
26
+ MCP_SERVER_NAME,
27
+ } from './history.ts'
24
28
  import { AsyncQueue, deferred, type Deferred } from './util.ts'
25
29
 
26
30
  /** Agent-side transport retry notice streamed as message text, e.g. `⚠ API error (attempt 1): …`. */
@@ -150,6 +154,8 @@ export class AcpTurn {
150
154
  readonly calls = new Map<string, ParkedCall>()
151
155
  /** Pi steps this turn has ended with `tool-calls`. */
152
156
  toolSteps = 0
157
+ /** Tool steps completed inside the active `session/prompt` segment. */
158
+ segmentToolSteps = 0
153
159
  /** Long-decode continuations sent in this turn. */
154
160
  continuations = 0
155
161
  /** The agent ended the prompt. */
@@ -157,6 +163,8 @@ export class AcpTurn {
157
163
  /** Settles after the current prompt's result or error has been queued. */
158
164
  promptSettled: Promise<void> = Promise.resolve()
159
165
  usage?: AcpPromptResult['usage']
166
+ /** Latest positive single-call context occupancy reported via `usage_update.used`. */
167
+ contextUsed?: number
160
168
  /** Relayed call ids whose results the agent has not yet re-awaited via `pi_await_result`. */
161
169
  readonly relayedCalls = new Set<string>()
162
170
  /** Bounded output buffered while one or more calls are relayed. */
@@ -249,6 +257,15 @@ export class AcpTurn {
249
257
  * @param update - the agent notification.
250
258
  */
251
259
  onUpdate(update: AcpSessionUpdate): void {
260
+ if (
261
+ update.sessionUpdate === 'usage_update' &&
262
+ typeof update.used === 'number' &&
263
+ Number.isFinite(update.used) &&
264
+ update.used > 0
265
+ ) {
266
+ this.contextUsed = update.used
267
+ return
268
+ }
252
269
  const text =
253
270
  update.content?.type === 'text' ? (update.content.text ?? '') : ''
254
271
  if (update.sessionUpdate === 'agent_message_chunk' && text.length > 0) {
@@ -355,39 +372,90 @@ export interface PumpHost {
355
372
  cancel(): void
356
373
  }
357
374
 
375
+ /** Optional single-call context occupancy inputs for {@link toTokenUsage}. */
376
+ export interface TokenUsageOptions {
377
+ /** Latest single-call context occupancy reported via `usage_update.used`. */
378
+ contextTokens?: number
379
+ /** Final `session/prompt` segment's usage when the turn spanned `max_tokens` continuations. */
380
+ lastSegmentUsage?: AcpPromptResult['usage']
381
+ }
382
+
383
+ function accumulateRawUsage(
384
+ prior: AcpPromptResult['usage'],
385
+ next: AcpPromptResult['usage'],
386
+ ): AcpPromptResult['usage'] {
387
+ if (prior === undefined) return next
388
+ if (next === undefined) return prior
389
+ const add = (a?: number, b?: number): number | undefined =>
390
+ a === undefined && b === undefined ? undefined : (a ?? 0) + (b ?? 0)
391
+ return {
392
+ inputTokens: add(prior.inputTokens, next.inputTokens),
393
+ outputTokens: add(prior.outputTokens, next.outputTokens),
394
+ cachedReadTokens: add(prior.cachedReadTokens, next.cachedReadTokens),
395
+ cachedWriteTokens: add(prior.cachedWriteTokens, next.cachedWriteTokens),
396
+ thoughtTokens: add(prior.thoughtTokens, next.thoughtTokens),
397
+ totalTokens: add(prior.totalTokens, next.totalTokens),
398
+ }
399
+ }
400
+
358
401
  /**
359
- * Map one completed prompt or step sample to Pi token usage. When a single
360
- * sample spanned `calls` internal model steps (tool rounds or continuations),
361
- * prompt buckets are normalized by `calls` so Pi's native ContextMeter reflects
362
- * single-request context occupancy rather than the multi-step sum.
402
+ * Map accumulated ACP turn usage into Pi token usage.
403
+ *
404
+ * Consumption buckets (`inputTokens`, `outputTokens`, `cacheReadTokens`,
405
+ * `cacheWriteTokens`, `reasoningTokens`) stay unscaled cumulative turn totals
406
+ * because intermediate `toolUse` steps emit zero usage and Pi sums those
407
+ * buckets across steps for session accounting and flat pricing overrides.
408
+ *
409
+ * `totalTokens` feeds Pi's `calculateContextTokens` / ContextMeter / compaction
410
+ * threshold as final-call context occupancy: when `options.contextTokens`
411
+ * (from live `usage_update.used`) is positive, it is used directly; otherwise
412
+ * final-segment prompt buckets are normalized by `calls` and added to final-
413
+ * segment output tokens.
363
414
  *
364
415
  * `agy acp` reports `inputTokens` as uncached input only, disjoint from
365
- * `cachedReadTokens` and `cachedWriteTokens`, so every bucket is kept as
366
- * reported and the total is their sum.
367
- * @param usage - the agent's step or turn usage.
368
- * @param calls - model calls executed inside this sample (>= 1).
416
+ * `cachedReadTokens` and `cachedWriteTokens`.
417
+ * @param usage - accumulated turn usage.
418
+ * @param calls - model calls inside the final `session/prompt` segment (>= 1).
419
+ * @param options - optional live `usage_update` count and final segment usage.
369
420
  * @returns Pi usage.
370
421
  */
371
422
  export function toTokenUsage(
372
423
  usage: AcpPromptResult['usage'],
373
424
  calls = 1,
425
+ options?: TokenUsageOptions,
374
426
  ): TokenUsage | undefined {
375
427
  if (usage === undefined) return undefined
376
- const scale = Math.max(1, calls)
377
- const input = Math.max(0, Math.round((usage.inputTokens ?? 0) / scale))
378
- const cacheRead = Math.max(
379
- 0,
380
- Math.round((usage.cachedReadTokens ?? 0) / scale),
381
- )
382
- const cacheWrite = Math.max(
383
- 0,
384
- Math.round((usage.cachedWriteTokens ?? 0) / scale),
385
- )
386
- const output = Math.max(0, usage.outputTokens ?? 0)
428
+ const input = Math.max(0, Math.round(usage.inputTokens ?? 0))
429
+ const cacheRead = Math.max(0, Math.round(usage.cachedReadTokens ?? 0))
430
+ const cacheWrite = Math.max(0, Math.round(usage.cachedWriteTokens ?? 0))
431
+ const output = Math.max(0, Math.round(usage.outputTokens ?? 0))
387
432
  const reasoning =
388
433
  usage.thoughtTokens !== undefined && usage.thoughtTokens > 0
389
- ? Math.min(output, usage.thoughtTokens)
434
+ ? Math.min(output, Math.round(usage.thoughtTokens))
390
435
  : undefined
436
+ const liveContext = options?.contextTokens
437
+ let totalTokens: number
438
+ if (
439
+ typeof liveContext === 'number' &&
440
+ Number.isFinite(liveContext) &&
441
+ liveContext > 0
442
+ ) {
443
+ totalTokens = Math.round(liveContext)
444
+ } else {
445
+ const seg = options?.lastSegmentUsage ?? usage
446
+ const scale = Math.max(1, calls)
447
+ const segPrompt = Math.max(
448
+ 0,
449
+ Math.round(
450
+ ((seg.inputTokens ?? 0) +
451
+ (seg.cachedReadTokens ?? 0) +
452
+ (seg.cachedWriteTokens ?? 0)) /
453
+ scale,
454
+ ),
455
+ )
456
+ const segOutput = Math.max(0, Math.round(seg.outputTokens ?? 0))
457
+ totalTokens = segPrompt + segOutput
458
+ }
391
459
  return {
392
460
  inputTokens: input,
393
461
  outputTokens: output,
@@ -398,7 +466,7 @@ export function toTokenUsage(
398
466
  ...(reasoning !== undefined && reasoning > 0
399
467
  ? { reasoningTokens: reasoning }
400
468
  : {}),
401
- totalTokens: input + cacheRead + cacheWrite + output,
469
+ totalTokens,
402
470
  }
403
471
  }
404
472
 
@@ -538,16 +606,20 @@ async function* stepChunks(
538
606
  }
539
607
  }
540
608
  turn.toolSteps++
609
+ turn.segmentToolSteps++
541
610
  yield { type: 'finish', reason: { kind: 'tool-calls' } }
542
611
  return
543
612
  }
544
613
  case 'done': {
614
+ turn.usage = accumulateRawUsage(turn.usage, event.result.usage)
545
615
  const stop = event.result.stopReason
546
616
  if (
547
617
  stop === 'max_tokens' &&
548
618
  turn.continuations < host.maxContinuations
549
619
  ) {
550
620
  turn.continuations++
621
+ turn.segmentToolSteps = 0
622
+ turn.contextUsed = undefined
551
623
  turn.promptSettled = host.continuePrompt().then(
552
624
  (result) => turn.events.push({ kind: 'done', result }),
553
625
  (error: unknown) =>
@@ -557,9 +629,14 @@ async function* stepChunks(
557
629
  }
558
630
  turn.finished = true
559
631
  yield* close()
560
- const calls = turn.toolSteps + turn.continuations + 1
561
- turn.usage = event.result.usage
562
- const usage = toTokenUsage(event.result.usage, calls)
632
+ const segmentCalls =
633
+ event.result.usage !== undefined
634
+ ? turn.segmentToolSteps + 1
635
+ : turn.toolSteps + turn.continuations + 1
636
+ const usage = toTokenUsage(turn.usage, segmentCalls, {
637
+ contextTokens: turn.contextUsed,
638
+ lastSegmentUsage: event.result.usage ?? turn.usage,
639
+ })
563
640
  if (usage !== undefined) yield { type: 'usage', usage }
564
641
  if (
565
642
  turn.isRelaying &&
@@ -662,8 +739,31 @@ function nonEmpty(value: unknown): string | undefined {
662
739
  }
663
740
 
664
741
  /**
665
- * Extract the structured `(serverName, toolName)` an agent claimed in one
666
- * permission request: top-level `mcpServerName`/`mcpToolName` or `_meta`.
742
+ * Resolve one explicit metadata field across candidate aliases, flagging when
743
+ * any two non-empty candidates disagree.
744
+ */
745
+ function reconcileCandidates(values: readonly unknown[]): {
746
+ value?: string
747
+ conflict: boolean
748
+ } {
749
+ let value: string | undefined
750
+ let conflict = false
751
+ for (const raw of values) {
752
+ const candidate = nonEmpty(raw)
753
+ if (candidate === undefined) continue
754
+ if (value === undefined) value = candidate
755
+ else if (value !== candidate) conflict = true
756
+ }
757
+ return { ...(value !== undefined ? { value } : {}), conflict }
758
+ }
759
+
760
+ /**
761
+ * Extract tool identity `(serverName, toolName)` from `session/update`
762
+ * (`recordReportedToolCall`) or `session/request_permission` (`answerPermission`).
763
+ * Reads top-level `mcpServerName`/`mcpToolName` or `_meta`, and reconciles flat
764
+ * `name` (`mcp_<server>_<tool>`). Non-Pi flat names map to a `non-pi:<name>`
765
+ * server sentinel, and contradictions across explicit fields or `name` set
766
+ * `conflict: true`. Returns `{}` only when no identity fields are present.
667
767
  * `title` and `rawInput` are deliberately not consulted.
668
768
  */
669
769
  export function structuredToolMeta(
@@ -671,21 +771,49 @@ export function structuredToolMeta(
671
771
  ): {
672
772
  serverName?: string
673
773
  toolName?: string
774
+ conflict?: boolean
674
775
  } {
675
776
  const meta: AcpToolCallMeta | undefined = toolCall?._meta
676
- const serverName =
677
- nonEmpty(toolCall?.mcpServerName) ??
678
- nonEmpty(meta?.mcpServerName) ??
679
- nonEmpty(meta?.serverName) ??
680
- nonEmpty(meta?.server)
681
- const toolName =
682
- nonEmpty(toolCall?.mcpToolName) ??
683
- nonEmpty(meta?.mcpToolName) ??
684
- nonEmpty(meta?.toolName) ??
685
- nonEmpty(meta?.tool)
777
+ const server = reconcileCandidates([
778
+ toolCall?.mcpServerName,
779
+ meta?.mcpServerName,
780
+ meta?.serverName,
781
+ meta?.server,
782
+ ])
783
+ const tool = reconcileCandidates([
784
+ toolCall?.mcpToolName,
785
+ meta?.mcpToolName,
786
+ meta?.toolName,
787
+ meta?.tool,
788
+ ])
789
+ const explicitServer = server.value
790
+ const explicitTool = tool.value
791
+ const flat = nonEmpty(toolCall?.name)
792
+ if (flat === undefined) {
793
+ const conflict = server.conflict || tool.conflict
794
+ return {
795
+ ...(explicitServer !== undefined ? { serverName: explicitServer } : {}),
796
+ ...(explicitTool !== undefined ? { toolName: explicitTool } : {}),
797
+ ...(conflict ? { conflict: true } : {}),
798
+ }
799
+ }
800
+ const candidateServer = explicitServer ?? MCP_SERVER_NAME
801
+ const prefix = `mcp_${candidateServer}_`
802
+ const hasPrefixedTool =
803
+ flat.startsWith(prefix) && flat.length > prefix.length
804
+ const flatServer = hasPrefixedTool ? candidateServer : `non-pi:${flat}`
805
+ const flatTool = hasPrefixedTool ? flat.slice(prefix.length) : flat
806
+ const hasExplicit = explicitServer !== undefined || explicitTool !== undefined
807
+ const conflict =
808
+ server.conflict ||
809
+ tool.conflict ||
810
+ (hasExplicit &&
811
+ (!hasPrefixedTool ||
812
+ (explicitTool !== undefined && explicitTool !== flatTool)))
686
813
  return {
687
- ...(serverName !== undefined ? { serverName } : {}),
688
- ...(toolName !== undefined ? { toolName } : {}),
814
+ serverName: explicitServer ?? flatServer,
815
+ toolName: explicitTool ?? flatTool,
816
+ ...(conflict ? { conflict: true } : {}),
689
817
  }
690
818
  }
691
819
 
@@ -709,11 +837,15 @@ export function recordReportedToolCall(
709
837
  return
710
838
  if (typeof update.toolCallId !== 'string' || update.toolCallId.length === 0)
711
839
  return
712
- const { serverName, toolName } = structuredToolMeta(update)
840
+ const {
841
+ serverName,
842
+ toolName,
843
+ conflict: metaConflict,
844
+ } = structuredToolMeta(update)
713
845
  const kind = typeof update.kind === 'string' ? update.kind : undefined
714
846
  const existing = conv.reportedToolCalls.get(update.toolCallId)
715
847
  const merged: ReportedToolCall = existing === undefined ? {} : { ...existing }
716
- let conflict = false
848
+ let conflict = metaConflict === true
717
849
  if (kind !== undefined) {
718
850
  if (merged.kind !== undefined && merged.kind !== kind) conflict = true
719
851
  else merged.kind = kind