@router-for-me/pi-cliproxyapi-provider 1.4.21 → 1.4.23

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/README.md CHANGED
@@ -206,10 +206,15 @@ From CPA catalog entry → pi model:
206
206
  | `context_window` | `contextWindow` |
207
207
  | `input_modalities` | `input` (`text` / `image`) |
208
208
  | `supported_reasoning_levels[].effort` | `thinkingLevelMap` + `reasoning` |
209
+ | `supports_reasoning_effort_updates` | `compat.supportsMidConvoEffort` |
209
210
  | `visibility: "hide"` | skipped |
210
211
 
211
212
  Unsupported pi thinking levels are set to `null` so they are hidden in the UI. When available, prices are matched against canonical model entries in `models.dev`; `cost.tiers[].tier.size` becomes pi's `inputTokensAbove`, including thresholds such as `272000`. The legacy `context_over_200k` field is used only when no explicit tiers are present. Ambiguous reseller prices are not selected arbitrarily and fall back to zero. These are catalog/list prices, not a guarantee of CPA's own markup or billing.
212
213
 
214
+ ## Cache-preserving thinking level changes
215
+
216
+ Models whose catalog entry sets `supports_reasoning_effort_updates` (GPT-6 on CLIProxyAPI) get pi's cache-preserving mid-session thinking level changes, matching the behavior pi >=1.3.0 ships for the OpenAI provider, with placement following the OpenAI documentation: the effort of the first turn becomes the fixed request-level `reasoning.effort`, and each later change is carried by a `configuration_update` input item placed immediately before the user message it applies to, so switching levels mid-session keeps the prompt prefix — and the upstream prompt cache — intact instead of rewriting it. WebSocket `previous_response_id` continuation also survives level changes. Histories lacking initial recorded levels (for example, sessions started before this support landed) may still need one full-context request while the baseline is being established. The behavior requires a pi >=1.3.0 host (its shared Responses converter); on older hosts the plugin detects the missing support and falls back to the classic request-level effort.
217
+
213
218
  The raw `models.dev` response is cached for 24 hours at `~/.pi/agent/tmp/models-dev-cache.json`. A fresh cache avoids the network request; an expired cache is refreshed with a three-second timeout, and stale data is retained if refresh fails. If neither the network nor a previous cache is available, pricing safely falls back to zero. A small explicit alias table covers known CLIProxyAPI variants such as `gemini-pro-agent` → `gemini-3.1-pro-preview`; unknown variants are not guessed.
214
219
 
215
220
  ## Migration from static models.json
@@ -245,6 +245,534 @@ const EXTRACT_ACCOUNT_ID_PATCH = `function extractAccountId(token) {
245
245
  }
246
246
  }`;
247
247
 
248
+ /** Request-level reasoning.effort pinned while configuration_update items carry the level. */
249
+ export const MID_CONVO_BASELINE_EFFORT = "medium";
250
+
251
+ interface MidConvoModelLike {
252
+ compat?: { supportsMidConvoEffort?: boolean };
253
+ thinkingLevelMap?: Record<string, string | null | undefined>;
254
+ }
255
+
256
+ /**
257
+ * Resolve the effort to carry in configuration_update items, or undefined to
258
+ * keep the classic request-level effort. Mirrors pi-ai openai-responses, plus
259
+ * the Codex adapter's special case: raw efforts of "none" route through the
260
+ * thinkingLevelMap off entry, whose null disables the update entirely.
261
+ */
262
+ export function resolveConfigurationUpdateEffort(
263
+ model: MidConvoModelLike,
264
+ options?: { reasoningEffort?: string; reasoningSummary?: string },
265
+ ): string | undefined {
266
+ if (model.compat?.supportsMidConvoEffort !== true || !options?.reasoningEffort) {
267
+ return undefined;
268
+ }
269
+ if (options.reasoningEffort === "none") {
270
+ const offEffort = model.thinkingLevelMap?.off === undefined ? "none" : model.thinkingLevelMap.off;
271
+ return offEffort ?? undefined;
272
+ }
273
+ return model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;
274
+ }
275
+
276
+ interface WireInputItemLike {
277
+ type?: string;
278
+ role?: string;
279
+ reasoning?: { effort?: unknown };
280
+ }
281
+
282
+ /**
283
+ * Reshape configuration_update placement to the documented mid-conversation
284
+ * semantics (https://developers.openai.com/api/docs/guides/reasoning#change-reasoning-mid-conversation):
285
+ * the effort in force for the first assistant turn becomes the request-level
286
+ * reasoning.effort (which then never changes), and each later effort change
287
+ * is a single configuration_update item placed immediately before the user
288
+ * message it applies to. The shared converter instead emits one update
289
+ * immediately before the assistant turn it governed, plus a trailing one
290
+ * for the current turn; that layout must be mapped per turn: the update
291
+ * before an assistant turn belongs before the user message that prompted
292
+ * it, and a trailing update is pulled back before the last user message.
293
+ * Only effort changes survive, so adjacent duplicates cannot occur.
294
+ *
295
+ * Bodies without any configuration_update item are returned unchanged.
296
+ */
297
+ export function reshapeConfigurationUpdates<T extends Record<string, unknown>>(body: T): T {
298
+ const input = (body as { input?: unknown }).input;
299
+ if (!Array.isArray(input)) {
300
+ return body;
301
+ }
302
+ const items = input as WireInputItemLike[];
303
+ const firstUpdate = items.find((item) => item?.type === "configuration_update");
304
+ if (!firstUpdate) {
305
+ return body;
306
+ }
307
+ const firstEffort = typeof firstUpdate.reasoning?.effort === "string" ? firstUpdate.reasoning.effort : undefined;
308
+
309
+ const ASSISTANT_ITEM_TYPES = new Set([
310
+ "reasoning",
311
+ "message",
312
+ "function_call",
313
+ "custom_tool_call",
314
+ "tool_search_call",
315
+ "web_search_call",
316
+ "programmatic_tool_calling",
317
+ ]);
318
+ const isAssistantItem = (item: WireInputItemLike | undefined): boolean => {
319
+ if (!item || item.type === undefined || !ASSISTANT_ITEM_TYPES.has(item.type)) {
320
+ return false;
321
+ }
322
+ // Typed user/developer messages are prompts, not assistant output.
323
+ return item.type !== "message" || item.role === "assistant" || item.role === undefined;
324
+ };
325
+ const isTurnStart = (item: WireInputItemLike | undefined): boolean =>
326
+ item?.role === "user" || item?.type === "function_call_output" || item?.type === "custom_tool_call_output";
327
+ const isPertinent = (item: WireInputItemLike | undefined): boolean => isTurnStart(item) || isAssistantItem(item);
328
+ const effortOf = (update: WireInputItemLike): string | undefined =>
329
+ typeof update.reasoning?.effort === "string" ? update.reasoning.effort : undefined;
330
+
331
+ // Gather the turns of a single origin pass: each turn starts at a user
332
+ // message or a block of tool outputs and ends at the next turn start.
333
+ // Tool-continuation turns remember the exact prompt boundary where their
334
+ // update was transmitted (last tool output, trailing metadata included).
335
+ interface TurnSegment {
336
+ startIndex: number;
337
+ update: WireInputItemLike | undefined;
338
+ answered: boolean;
339
+ toolContinuation: boolean;
340
+ lastToolOutputIndex: number;
341
+ promptBoundaryIndex: number;
342
+ }
343
+ const turns: TurnSegment[] = [];
344
+ let seenFirstUpdate = false;
345
+ let pendingForwardUpdate: WireInputItemLike | undefined;
346
+ let trailingForwardUpdate: WireInputItemLike | undefined;
347
+ let trailingForwardIsTrailing = false;
348
+ const orphanUpdates: Array<{ update: WireInputItemLike; anchorIndex: number }> = [];
349
+ for (let index = 0; index < items.length; index++) {
350
+ const item = items[index];
351
+ const previousPertinent = [...items.slice(0, index)].reverse().find((entry) => isPertinent(entry));
352
+ if (isTurnStart(item) && !(previousPertinent && isTurnStart(previousPertinent))) {
353
+ turns.push({
354
+ startIndex: index,
355
+ update: pendingForwardUpdate,
356
+ answered: false,
357
+ toolContinuation: item?.role !== "user",
358
+ lastToolOutputIndex: -1,
359
+ promptBoundaryIndex: -1,
360
+ });
361
+ pendingForwardUpdate = undefined;
362
+ }
363
+ const currentTurn = turns[turns.length - 1];
364
+ if (currentTurn) {
365
+ if (isAssistantItem(item)) {
366
+ currentTurn.answered = true;
367
+ } else if (currentTurn.toolContinuation && !currentTurn.answered && item?.type !== "configuration_update") {
368
+ if (isTurnStart(item)) {
369
+ currentTurn.lastToolOutputIndex = index;
370
+ }
371
+ currentTurn.promptBoundaryIndex = index;
372
+ }
373
+ }
374
+ if (item?.type !== "configuration_update") {
375
+ continue;
376
+ }
377
+ if (!seenFirstUpdate) {
378
+ seenFirstUpdate = true;
379
+ continue;
380
+ }
381
+ let nextPertinent: WireInputItemLike | undefined;
382
+ for (let scan = index + 1; scan < items.length; scan++) {
383
+ if (isPertinent(items[scan])) {
384
+ nextPertinent = items[scan];
385
+ break;
386
+ }
387
+ }
388
+ if (nextPertinent && isAssistantItem(nextPertinent)) {
389
+ // Historical update governing the assistant output that follows.
390
+ if (currentTurn) {
391
+ currentTurn.update ??= item;
392
+ } else {
393
+ orphanUpdates.push({ update: item, anchorIndex: index });
394
+ }
395
+ } else {
396
+ // Forward or trailing update; the last one of a run wins.
397
+ pendingForwardUpdate = item;
398
+ trailingForwardUpdate = item;
399
+ trailingForwardIsTrailing = items.slice(index + 1).every((entry) => !isPertinent(entry));
400
+ }
401
+ }
402
+
403
+ // Orphan updates (history starting mid-conversation, before any turn)
404
+ // stay at the exact chronological boundary where they were recorded;
405
+ // seed the tracked effort from them in order so later changes compare
406
+ // against the actual wire state.
407
+ let trackedEffort = firstEffort ?? MID_CONVO_BASELINE_EFFORT;
408
+ const orphanByAnchorIndex = new Map<number, WireInputItemLike>();
409
+ for (const orphan of orphanUpdates) {
410
+ const orphanEffort = effortOf(orphan.update);
411
+ if (orphanEffort !== undefined) {
412
+ trackedEffort = orphanEffort;
413
+ }
414
+ orphanByAnchorIndex.set(orphan.anchorIndex, orphan.update);
415
+ }
416
+ const announcementByIndex = new Map<number, WireInputItemLike>();
417
+ const announcementAfterIndex = new Map<number, WireInputItemLike>();
418
+ let currentEffort = trackedEffort;
419
+ for (const turn of turns) {
420
+ const effort = turn.update ? effortOf(turn.update) : undefined;
421
+ if (effort !== undefined && effort !== currentEffort) {
422
+ if (turn.toolContinuation) {
423
+ // Tool continuations announce right after their full prompt
424
+ // (tool outputs plus any trailing metadata), the same boundary
425
+ // the update occupied when first transmitted.
426
+ const boundaryIndex =
427
+ turn.promptBoundaryIndex !== -1
428
+ ? turn.promptBoundaryIndex
429
+ : turn.lastToolOutputIndex !== -1
430
+ ? turn.lastToolOutputIndex
431
+ : turn.startIndex;
432
+ announcementAfterIndex.set(boundaryIndex, turn.update!);
433
+ } else {
434
+ announcementByIndex.set(turn.startIndex, turn.update!);
435
+ }
436
+ currentEffort = effort;
437
+ }
438
+ }
439
+ const trailingTarget = [...turns].reverse().find((turn) => !turn.answered);
440
+ let trailingAtEnd = false;
441
+ if (trailingForwardUpdate && trailingForwardIsTrailing) {
442
+ // The last forward update governs the current (unanswered) turn. The
443
+ // converter already attached it to that turn; re-decide it here so its
444
+ // announcement is placed before the turn's user message.
445
+ if (trailingTarget && announcementByIndex.get(trailingTarget.startIndex) === trailingForwardUpdate) {
446
+ announcementByIndex.delete(trailingTarget.startIndex);
447
+ // Announcing it advanced the tracked effort; step back to the
448
+ // effort announced by the preceding turns before comparing.
449
+ let effortBefore = firstEffort ?? MID_CONVO_BASELINE_EFFORT;
450
+ for (const turn of turns) {
451
+ if (turn === trailingTarget) {
452
+ break;
453
+ }
454
+ const announced = announcementByIndex.get(turn.startIndex);
455
+ const announcedEffort = announced ? effortOf(announced) : undefined;
456
+ if (announcedEffort !== undefined) {
457
+ effortBefore = announcedEffort;
458
+ }
459
+ }
460
+ currentEffort = effortBefore;
461
+ }
462
+ const effort = effortOf(trailingForwardUpdate);
463
+ if (effort === undefined || effort !== currentEffort) {
464
+ if (trailingTarget && items[trailingTarget.startIndex]?.role === "user") {
465
+ announcementByIndex.set(trailingTarget.startIndex, trailingForwardUpdate);
466
+ } else {
467
+ // Tool-loop continuation or no turn to attach to: keep the
468
+ // update in force from the end instead of rewriting history.
469
+ trailingAtEnd = true;
470
+ }
471
+ }
472
+ }
473
+
474
+ const reshaped: WireInputItemLike[] = [];
475
+ for (let index = 0; index < items.length; index++) {
476
+ const item = items[index];
477
+ if (item?.type === "configuration_update") {
478
+ const orphan = orphanByAnchorIndex.get(index);
479
+ if (orphan) {
480
+ reshaped.push(orphan);
481
+ }
482
+ continue;
483
+ }
484
+ const announced = announcementByIndex.get(index);
485
+ if (announced) {
486
+ reshaped.push(announced);
487
+ }
488
+ reshaped.push(item);
489
+ const announcedAfter = announcementAfterIndex.get(index);
490
+ if (announcedAfter) {
491
+ reshaped.push(announcedAfter);
492
+ }
493
+ }
494
+ if (trailingAtEnd && trailingForwardUpdate) {
495
+ reshaped.push(trailingForwardUpdate);
496
+ }
497
+
498
+ const reasoning = (body as { reasoning?: { effort?: unknown } }).reasoning;
499
+ const nextReasoning =
500
+ reasoning && typeof reasoning === "object"
501
+ ? { ...reasoning, effort: firstEffort ?? MID_CONVO_BASELINE_EFFORT }
502
+ : { effort: firstEffort ?? MID_CONVO_BASELINE_EFFORT, summary: "auto" };
503
+ return { ...body, input: reshaped, reasoning: nextReasoning };
504
+ }
505
+
506
+ const MID_CONVO_RESOLVER_SNIPPET = `/** Effort to send in configuration_update items, or undefined to send it as reasoning.effort. */
507
+ function cpaGetConfigurationUpdateEffort(model, options) {
508
+ if (model.compat?.supportsMidConvoEffort !== true ||
509
+ !options?.reasoningEffort) {
510
+ return undefined;
511
+ }
512
+ if (options.reasoningEffort === "none") {
513
+ // Mirror the Codex adapter: "none" resolves through the off mapping.
514
+ const offEffort = model.thinkingLevelMap?.off === undefined ? "none" : model.thinkingLevelMap.off;
515
+ return offEffort ?? undefined;
516
+ }
517
+ return model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;
518
+ }
519
+ // Documented mid-conversation semantics: the first turn's effort becomes the
520
+ // fixed request-level reasoning.effort; later changes ride as configuration_update
521
+ // items placed immediately before the user message they apply to. The shared
522
+ // converter emits one update right before the assistant turn it governed plus
523
+ // a trailing one for the current turn, so map each update back to the start
524
+ // of its prompt chain (user message or preceding tool outputs), pull a
525
+ // trailing update back before the last user message, and drop repeats.
526
+ const CPA_CONFIGURATION_UPDATE_REQUEST_EFFORT = ${JSON.stringify(MID_CONVO_BASELINE_EFFORT)};
527
+ function cpaReshapeConfigurationUpdates(input) {
528
+ if (!Array.isArray(input)) {
529
+ return { input, firstEffort: undefined };
530
+ }
531
+ const firstUpdate = input.find((item) => item?.type === "configuration_update");
532
+ if (!firstUpdate) {
533
+ return { input, firstEffort: undefined };
534
+ }
535
+ const firstEffort = typeof firstUpdate.reasoning?.effort === "string" ? firstUpdate.reasoning.effort : undefined;
536
+ const ASSISTANT_ITEM_TYPES = new Set(["reasoning", "message", "function_call", "custom_tool_call", "tool_search_call", "web_search_call", "programmatic_tool_calling"]);
537
+ const isAssistantItem = (item) => {
538
+ if (!item || item.type === undefined || !ASSISTANT_ITEM_TYPES.has(item.type)) {
539
+ return false;
540
+ }
541
+ return item.type !== "message" || item.role === "assistant" || item.role === undefined;
542
+ };
543
+ const isTurnStart = (item) => item?.role === "user" || item?.type === "function_call_output" || item?.type === "custom_tool_call_output";
544
+ const isPertinent = (item) => isTurnStart(item) || isAssistantItem(item);
545
+ const effortOf = (update) => typeof update.reasoning?.effort === "string" ? update.reasoning.effort : undefined;
546
+ const turns = [];
547
+ let seenFirstUpdate = false;
548
+ let pendingForwardUpdate;
549
+ let trailingForwardUpdate;
550
+ let trailingForwardIsTrailing = false;
551
+ const orphanUpdates = [];
552
+ for (let index = 0; index < input.length; index++) {
553
+ const item = input[index];
554
+ const previousPertinent = [...input.slice(0, index)].reverse().find((entry) => isPertinent(entry));
555
+ if (isTurnStart(item) && !(previousPertinent && isTurnStart(previousPertinent))) {
556
+ turns.push({ startIndex: index, update: pendingForwardUpdate, answered: false, toolContinuation: item?.role !== "user", lastToolOutputIndex: -1, promptBoundaryIndex: -1 });
557
+ pendingForwardUpdate = undefined;
558
+ }
559
+ const currentTurn = turns[turns.length - 1];
560
+ if (currentTurn) {
561
+ if (isAssistantItem(item)) {
562
+ currentTurn.answered = true;
563
+ }
564
+ else if (currentTurn.toolContinuation && !currentTurn.answered && item?.type !== "configuration_update") {
565
+ if (isTurnStart(item)) {
566
+ currentTurn.lastToolOutputIndex = index;
567
+ }
568
+ currentTurn.promptBoundaryIndex = index;
569
+ }
570
+ }
571
+ if (item?.type !== "configuration_update") {
572
+ continue;
573
+ }
574
+ if (!seenFirstUpdate) {
575
+ seenFirstUpdate = true;
576
+ continue;
577
+ }
578
+ let nextPertinent;
579
+ for (let scan = index + 1; scan < input.length; scan++) {
580
+ if (isPertinent(input[scan])) {
581
+ nextPertinent = input[scan];
582
+ break;
583
+ }
584
+ }
585
+ if (nextPertinent && isAssistantItem(nextPertinent)) {
586
+ if (currentTurn) {
587
+ currentTurn.update ??= item;
588
+ }
589
+ else {
590
+ orphanUpdates.push({ update: item, anchorIndex: index });
591
+ }
592
+ }
593
+ else {
594
+ pendingForwardUpdate = item;
595
+ trailingForwardUpdate = item;
596
+ trailingForwardIsTrailing = input.slice(index + 1).every((entry) => !isPertinent(entry));
597
+ }
598
+ }
599
+ let trackedEffort = firstEffort ?? CPA_CONFIGURATION_UPDATE_REQUEST_EFFORT;
600
+ const orphanByAnchorIndex = new Map();
601
+ for (const orphan of orphanUpdates) {
602
+ const orphanEffort = effortOf(orphan.update);
603
+ if (orphanEffort !== undefined) {
604
+ trackedEffort = orphanEffort;
605
+ }
606
+ orphanByAnchorIndex.set(orphan.anchorIndex, orphan.update);
607
+ }
608
+ const announcementByIndex = new Map();
609
+ const announcementAfterIndex = new Map();
610
+ let currentEffort = trackedEffort;
611
+ for (const turn of turns) {
612
+ const effort = turn.update ? effortOf(turn.update) : undefined;
613
+ if (effort !== undefined && effort !== currentEffort) {
614
+ if (turn.toolContinuation) {
615
+ const boundaryIndex = turn.promptBoundaryIndex !== -1 ? turn.promptBoundaryIndex : turn.lastToolOutputIndex !== -1 ? turn.lastToolOutputIndex : turn.startIndex;
616
+ announcementAfterIndex.set(boundaryIndex, turn.update);
617
+ }
618
+ else {
619
+ announcementByIndex.set(turn.startIndex, turn.update);
620
+ }
621
+ currentEffort = effort;
622
+ }
623
+ }
624
+ const trailingTarget = [...turns].reverse().find((turn) => !turn.answered);
625
+ let trailingAtEnd = false;
626
+ if (trailingForwardUpdate && trailingForwardIsTrailing) {
627
+ if (trailingTarget && announcementByIndex.get(trailingTarget.startIndex) === trailingForwardUpdate) {
628
+ announcementByIndex.delete(trailingTarget.startIndex);
629
+ let effortBefore = firstEffort ?? CPA_CONFIGURATION_UPDATE_REQUEST_EFFORT;
630
+ for (const turn of turns) {
631
+ if (turn === trailingTarget) {
632
+ break;
633
+ }
634
+ const announced = announcementByIndex.get(turn.startIndex);
635
+ const announcedEffort = announced ? effortOf(announced) : undefined;
636
+ if (announcedEffort !== undefined) {
637
+ effortBefore = announcedEffort;
638
+ }
639
+ }
640
+ currentEffort = effortBefore;
641
+ }
642
+ const effort = effortOf(trailingForwardUpdate);
643
+ if (effort === undefined || effort !== currentEffort) {
644
+ if (trailingTarget && input[trailingTarget.startIndex]?.role === "user") {
645
+ announcementByIndex.set(trailingTarget.startIndex, trailingForwardUpdate);
646
+ }
647
+ else {
648
+ trailingAtEnd = true;
649
+ }
650
+ }
651
+ }
652
+ const reshaped = [];
653
+ for (let index = 0; index < input.length; index++) {
654
+ const item = input[index];
655
+ if (item?.type === "configuration_update") {
656
+ const orphan = orphanByAnchorIndex.get(index);
657
+ if (orphan) {
658
+ reshaped.push(orphan);
659
+ }
660
+ continue;
661
+ }
662
+ const announced = announcementByIndex.get(index);
663
+ if (announced) {
664
+ reshaped.push(announced);
665
+ }
666
+ reshaped.push(item);
667
+ const announcedAfter = announcementAfterIndex.get(index);
668
+ if (announcedAfter) {
669
+ reshaped.push(announcedAfter);
670
+ }
671
+ }
672
+ if (trailingAtEnd && trailingForwardUpdate) {
673
+ reshaped.push(trailingForwardUpdate);
674
+ }
675
+ return { input: reshaped, firstEffort };
676
+ }`;
677
+
678
+ /**
679
+ * Whether the installed openai-responses-shared converter honors the
680
+ * configurationUpdateEffort option (pi >=1.3.0). Older hosts ignore the
681
+ * unknown option, so the mid-convo machinery must stay disabled there.
682
+ */
683
+ export function sharedSupportsConfigurationUpdate(sharedSource: string): boolean {
684
+ return (
685
+ sharedSource.includes('type: "configuration_update"') &&
686
+ sharedSource.includes("options?.configurationUpdateEffort")
687
+ );
688
+ }
689
+
690
+ /**
691
+ * Whether a Codex adapter source already wires configuration_update support
692
+ * natively. Uses the upstream resolver's exact wiring so stray mentions in
693
+ * comments or identifiers do not count.
694
+ */
695
+ export function hasNativeMidConvoEffort(source: string): boolean {
696
+ return (
697
+ source.includes("function getConfigurationUpdateEffort(") &&
698
+ source.includes("const configurationUpdateEffort = getConfigurationUpdateEffort(")
699
+ );
700
+ }
701
+
702
+ /**
703
+ * Port pi 1.3.0 cache-preserving thinking level changes to the Codex adapter.
704
+ *
705
+ * Mirrors pi-ai openai-responses: when the model declares
706
+ * compat.supportsMidConvoEffort, the real level travels as configuration_update
707
+ * input items (replayed from providerThinkingLevel recorded on each reply),
708
+ * so switching levels mid-session keeps the prompt prefix — and the prompt
709
+ * cache — intact. On top of the converter layout, the built message list is
710
+ * reshaped to the documented placement: the first turn's effort becomes the
711
+ * fixed request-level reasoning.effort, and each later change sits right
712
+ * before the user message it applies to.
713
+ * The conversion itself is delegated to the shared openai-responses-shared
714
+ * module via its configurationUpdateEffort option; callers only apply this
715
+ * patch when that module supports it. The WebSocket response replay is left
716
+ * untouched on purpose: the previous full request already ends with the
717
+ * trailing configuration_update, so stored response items must not repeat it.
718
+ */
719
+ function patchMidConvoEffort(source: string): string {
720
+ const ANCHORS: Array<[string, string, string]> = [
721
+ [
722
+ "request build",
723
+ "let body = buildRequestBody(model, normalizedContext, options, codexSessionId, grammarToolInputProperties);",
724
+ "let body = buildRequestBody(model, normalizedContext, options, codexSessionId, grammarToolInputProperties, cpaConfigurationUpdateEffort);",
725
+ ],
726
+ [
727
+ "buildRequestBody signature",
728
+ "model.compat?.supportsOpenAIGrammarTools ?? false)) {",
729
+ "model.compat?.supportsOpenAIGrammarTools ?? false), cpaConfigurationUpdateEffort) {",
730
+ ],
731
+ [
732
+ "message conversion",
733
+ " toolOptions: { strict: null, supportsStrictMode, supportsOpenAIGrammarTools },\n });",
734
+ " toolOptions: { strict: null, supportsStrictMode, supportsOpenAIGrammarTools },\n configurationUpdateEffort: cpaConfigurationUpdateEffort,\n });",
735
+ ],
736
+ [
737
+ "body input field",
738
+ " input: messages,",
739
+ " input: cpaReshapeConfigurationUpdates(messages).input,",
740
+ ],
741
+ [
742
+ "reasoning block",
743
+ ` if (effort !== null) {\n body.reasoning = {\n effort,`,
744
+ ` if (effort !== null) {\n body.reasoning = {\n effort: cpaConfigurationUpdateEffort === undefined ? effort : (cpaReshapeConfigurationUpdates(messages).firstEffort ?? CPA_CONFIGURATION_UPDATE_REQUEST_EFFORT),`,
745
+ ],
746
+ ];
747
+
748
+ for (const [name, anchor] of ANCHORS) {
749
+ if (!source.includes(anchor)) {
750
+ throw new Error(`openai-codex-responses source no longer supports the mid-convo effort patch (${name})`);
751
+ }
752
+ }
753
+
754
+ let src = `${source}\n${MID_CONVO_RESOLVER_SNIPPET}\n`;
755
+ // The output construction sits right after the stream's single async IIFE
756
+ // opener; anchor the providerThinkingLevel injection on that block instead
757
+ // of guessing the exact indentation of the role line.
758
+ const iifeIndex = src.indexOf(" (async () => {");
759
+ const roleIndex = iifeIndex === -1 ? -1 : src.indexOf('role: "assistant"', iifeIndex);
760
+ const roleLineEnd = roleIndex === -1 ? -1 : src.indexOf("\n", roleIndex);
761
+ if (iifeIndex === -1 || roleIndex === -1 || roleLineEnd === -1) {
762
+ throw new Error("openai-codex-responses source no longer supports the mid-convo effort patch (output role)");
763
+ }
764
+ src =
765
+ src.slice(0, iifeIndex) +
766
+ " const cpaConfigurationUpdateEffort = cpaGetConfigurationUpdateEffort(model, options);\n" +
767
+ src.slice(iifeIndex, roleLineEnd) +
768
+ "\n ...(cpaConfigurationUpdateEffort === undefined ? {} : { providerThinkingLevel: cpaConfigurationUpdateEffort })," +
769
+ src.slice(roleLineEnd);
770
+ for (const [, anchor, replacement] of ANCHORS) {
771
+ src = src.replace(anchor, replacement);
772
+ }
773
+ return src;
774
+ }
775
+
248
776
  const IMPORT_FROM_SPECIFIER = /from\s+(["'])([^"']+)\1/g;
249
777
 
250
778
  function stripSourceMappingUrl(source: string): string {
@@ -450,7 +978,12 @@ function patchWebSocketTransport(source: string): string {
450
978
  );
451
979
  }
452
980
 
453
- export function patchCodexSource(source: string, providerIds: string[]): string {
981
+ export interface PatchCodexSourceOptions {
982
+ /** Whether the shared converter honors configurationUpdateEffort (pi >=1.3.0). */
983
+ supportsConfigurationUpdate?: boolean;
984
+ }
985
+
986
+ export function patchCodexSource(source: string, providerIds: string[], options: PatchCodexSourceOptions = {}): string {
454
987
  let src = source;
455
988
 
456
989
  if (!/function extractAccountId\(token\) \{/.test(src)) {
@@ -485,6 +1018,13 @@ export function patchCodexSource(source: string, providerIds: string[]): string
485
1018
 
486
1019
  // CLIProxyAPI prefers a persistent WebSocket transport. Reconnect before the
487
1020
  // response starts, and gracefully fall back to SSE if retries are exhausted.
1021
+ // Cache-preserving thinking level changes (pi 1.3.0 openai-responses parity).
1022
+ // Requires a shared converter that honors configurationUpdateEffort; skipped
1023
+ // when the source already implements the resolver with upstream wiring.
1024
+ if (options.supportsConfigurationUpdate === true && !hasNativeMidConvoEffort(source)) {
1025
+ src = patchMidConvoEffort(src);
1026
+ }
1027
+
488
1028
  src = patchWebSocketTransport(src);
489
1029
 
490
1030
  // The generated module lives outside the original source map directory.
@@ -657,7 +1197,20 @@ export async function loadCliproxyCodexStreams(
657
1197
  ): Promise<CliproxyCodexStreams> {
658
1198
  const { path: originalPath } = resolveOriginalCodexModulePath();
659
1199
  const originalSource = readFileSync(originalPath, "utf8");
660
- const patched = patchCodexSource(originalSource, providerIds);
1200
+
1201
+ // The shared converter only honors configurationUpdateEffort on pi >=1.3.0.
1202
+ // Gate the optional patch (and the compat flag below) on that capability so
1203
+ // older hosts keep the classic request-level effort instead of pinning it
1204
+ // to the baseline without carrying the real level.
1205
+ const sharedSource = (() => {
1206
+ try {
1207
+ return readFileSync(join(dirname(originalPath), "openai-responses-shared.js"), "utf8");
1208
+ } catch {
1209
+ return "";
1210
+ }
1211
+ })();
1212
+ const supportsConfigurationUpdate = sharedSupportsConfigurationUpdate(sharedSource);
1213
+ const patched = patchCodexSource(originalSource, providerIds, { supportsConfigurationUpdate });
661
1214
 
662
1215
  const outPath = computePatchedModuleCachePath(originalPath, patched);
663
1216
  const cacheDir = dirname(outPath);
@@ -690,11 +1243,37 @@ export async function loadCliproxyCodexStreams(
690
1243
  const supportsTranscript = supportsTranscriptSource(originalSource);
691
1244
  const adaptContext = (context: Context): Context => adaptContextForModule(context, supportsTranscript);
692
1245
 
1246
+ const adaptModel = (model: Model<Api>): Model<Api> => {
1247
+ const compat = model.compat as unknown as { supportsMidConvoEffort?: boolean } | undefined;
1248
+ if (supportsConfigurationUpdate || compat?.supportsMidConvoEffort !== true) {
1249
+ return model;
1250
+ }
1251
+ return { ...model, compat: { ...compat, supportsMidConvoEffort: false } } as Model<Api>;
1252
+ };
1253
+
1254
+ // When the host adapter implements mid-convo effort natively, its placement
1255
+ // follows pi's converter layout; reshape payloads to the documented layout
1256
+ // in the wrapper instead of inside the patched module.
1257
+ const nativeMidConvoEffort = hasNativeMidConvoEffort(originalSource);
1258
+ const adaptOptions = (streamOptions?: SimpleStreamOptions): SimpleStreamOptions | undefined => {
1259
+ if (!nativeMidConvoEffort) {
1260
+ return streamOptions;
1261
+ }
1262
+ return {
1263
+ ...streamOptions,
1264
+ onPayload: async (payload, payloadModel) => {
1265
+ const nextPayload = await streamOptions?.onPayload?.(payload, payloadModel);
1266
+ const effective = (nextPayload === undefined ? payload : nextPayload) as Record<string, unknown>;
1267
+ return effective && typeof effective === "object" ? reshapeConfigurationUpdates(effective) : effective;
1268
+ },
1269
+ };
1270
+ };
1271
+
693
1272
  const adaptedStreamSimple: CliproxyCodexStreamSimple = (model, context, streamOptions) => {
694
- return mod.streamSimple(model, adaptContext(context), streamOptions);
1273
+ return mod.streamSimple(adaptModel(model), adaptContext(context), adaptOptions(streamOptions));
695
1274
  };
696
1275
  const adaptedStream: CliproxyCodexStreamSimple = (model, context, streamOptions) => {
697
- return mod.stream(model, adaptContext(context), streamOptions);
1276
+ return mod.stream(adaptModel(model), adaptContext(context), adaptOptions(streamOptions));
698
1277
  };
699
1278
 
700
1279
  const streamSimple = wrapStreamSimpleForFast(adaptedStreamSimple, options.shouldUseFast);
@@ -721,6 +721,7 @@ export function registerRefreshCommand(options: {
721
721
  const refresh = refreshCoordinator?.begin();
722
722
  const { loaded } = await resolveMappedModels(agentDir, connection.baseUrlInput, connection.apiKey, {
723
723
  forceRefresh: true,
724
+ replaceCache: true,
724
725
  fastMode: fastMode.isEnabled(),
725
726
  signal: refresh?.signal,
726
727
  shouldCommit: refresh ? () => refreshCoordinator?.isCurrent(refresh.generation) ?? true : undefined,
@@ -1000,7 +1001,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1000
1001
  const connection = resolveConnection(agentDir, identity.providerId);
1001
1002
  const registerConfiguredProvider = async (
1002
1003
  currentConnection: { baseUrlInput: string; apiKey: string },
1003
- options: { forceRefresh?: boolean } = {},
1004
+ options: { forceRefresh?: boolean; replaceCache?: boolean } = {},
1004
1005
  ): Promise<RefreshResult | undefined> => {
1005
1006
  const refresh = modelRefreshCoordinator.begin();
1006
1007
  try {
@@ -1010,6 +1011,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1010
1011
  currentConnection.apiKey,
1011
1012
  {
1012
1013
  forceRefresh: options.forceRefresh,
1014
+ replaceCache: options.replaceCache,
1013
1015
  fastMode: fastMode.isEnabled(),
1014
1016
  signal: refresh.signal,
1015
1017
  shouldCommit: () => modelRefreshCoordinator.isCurrent(refresh.generation),
@@ -1101,7 +1103,8 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1101
1103
  streamSimple,
1102
1104
  fastMode,
1103
1105
  refreshCoordinator: modelRefreshCoordinator,
1104
- onRefresh: (currentConnection) => registerConfiguredProvider(currentConnection, { forceRefresh: true }),
1106
+ onRefresh: (currentConnection) =>
1107
+ registerConfiguredProvider(currentConnection, { forceRefresh: true, replaceCache: true }),
1105
1108
  });
1106
1109
 
1107
1110
  if (!connection) {
package/extensions/lib.ts CHANGED
@@ -12,6 +12,11 @@ export type ThinkingLevelMap = Partial<
12
12
  Record<"off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max" | "ultra", string | null>
13
13
  >;
14
14
 
15
+ // Local subset of pi OpenAIResponsesCompat; only the flags this plugin emits.
16
+ export interface PiProviderModelCompat {
17
+ supportsMidConvoEffort?: boolean;
18
+ }
19
+
15
20
  export const DEFAULT_PROVIDER_ID = "cliproxyapi";
16
21
  export const DEFAULT_PROVIDER_NAME = "CLIProxyAPI";
17
22
  export const DEFAULT_BASE_URL = "http://127.0.0.1:8317";
@@ -76,6 +81,7 @@ export interface CodexClientModel {
76
81
  max_completion_tokens?: number;
77
82
  input_modalities?: string[];
78
83
  supported_reasoning_levels?: CodexReasoningLevel[] | string[];
84
+ supports_reasoning_effort_updates?: boolean;
79
85
  default_service_tier?: string | null;
80
86
  service_tiers?: Array<CodexServiceTier | string>;
81
87
  additional_speed_tiers?: string[];
@@ -113,6 +119,7 @@ export interface PiProviderModel {
113
119
  contextWindow: number;
114
120
  maxTokens: number;
115
121
  thinkingLevelMap?: ThinkingLevelMap;
122
+ compat?: PiProviderModelCompat;
116
123
  stale?: boolean;
117
124
  lastSeenAt?: number;
118
125
  staleSince?: number;
@@ -513,6 +520,10 @@ export function supportsFastServiceTier(model: CodexClientModel): boolean {
513
520
  return Array.isArray(model.service_tiers) && model.service_tiers.length > 0;
514
521
  }
515
522
 
523
+ export function supportsReasoningEffortUpdates(model: CodexClientModel): boolean {
524
+ return model.supports_reasoning_effort_updates === true;
525
+ }
526
+
516
527
  export function toPiModel(
517
528
  model: CodexClientModel,
518
529
  costCatalog?: ModelsDevCostCatalog,
@@ -564,6 +575,7 @@ export function toPiModel(
564
575
  contextWindow,
565
576
  maxTokens,
566
577
  thinkingLevelMap: buildThinkingLevelMap(efforts),
578
+ ...(hasReasoning && supportsReasoningEffortUpdates(model) ? { compat: { supportsMidConvoEffort: true } } : {}),
567
579
  };
568
580
  }
569
581
 
@@ -1043,7 +1055,8 @@ export function mergeModelsWithExistingCache(
1043
1055
 
1044
1056
  /**
1045
1057
  * Load mapped models from the matching cache, or fetch remotely and update the cache.
1046
- * A forced refresh always bypasses the cache.
1058
+ * A forced refresh bypasses the cache read but still retains models missing from the
1059
+ * fresh catalog. replaceCache writes that catalog as-is after a successful fetch.
1047
1060
  */
1048
1061
  export async function resolveMappedModels(
1049
1062
  agentDir: string,
@@ -1051,6 +1064,7 @@ export async function resolveMappedModels(
1051
1064
  apiKey: string,
1052
1065
  options: {
1053
1066
  forceRefresh?: boolean;
1067
+ replaceCache?: boolean;
1054
1068
  fastMode?: boolean;
1055
1069
  signal?: AbortSignal;
1056
1070
  shouldCommit?: () => boolean;
@@ -1061,14 +1075,19 @@ export async function resolveMappedModels(
1061
1075
  options.fastMode === undefined || (cache.fastMode ?? false) === options.fastMode;
1062
1076
 
1063
1077
  const existingCache = loadModelsCache(agentDir, baseUrlInput);
1064
- if (!options.forceRefresh) {
1078
+ if (!options.forceRefresh && !options.replaceCache) {
1065
1079
  if (existingCache && cacheMatchesFastMode(existingCache)) {
1066
1080
  return { loaded: existingCache, fromCache: true };
1067
1081
  }
1068
1082
  }
1069
1083
 
1070
1084
  const fresh = await loadMappedModels(baseUrlInput, apiKey, options.fastMode, agentDir, options.signal);
1071
- const { merged } = mergeModelsWithExistingCache(existingCache, fresh, Date.now(), options.staleTtlMs);
1085
+ const { merged } = mergeModelsWithExistingCache(
1086
+ options.replaceCache ? null : existingCache,
1087
+ fresh,
1088
+ Date.now(),
1089
+ options.staleTtlMs,
1090
+ );
1072
1091
  if (!options.signal?.aborted && (options.shouldCommit?.() ?? true)) {
1073
1092
  saveModelsCache(agentDir, merged);
1074
1093
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@router-for-me/pi-cliproxyapi-provider",
3
- "version": "1.4.21",
3
+ "version": "1.4.23",
4
4
  "description": "Pi provider extension that auto-registers CLIProxyAPI models, plus TUI elapsed/TPS status",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -43,8 +43,8 @@
43
43
  },
44
44
  "devDependencies": {
45
45
  "@biomejs/biome": "2.5.3",
46
- "@earendil-works/pi-ai": "0.84.3",
47
- "@earendil-works/pi-coding-agent": "0.84.3",
46
+ "@earendil-works/pi-ai": "^1.3.0",
47
+ "@earendil-works/pi-coding-agent": "^1.3.0",
48
48
  "@types/node": "^22.15.21",
49
49
  "typescript": "6.0.3",
50
50
  "vitest": "4.1.9"