@herbertgao/pi-extensions 2026.10.12 → 2026.10.13

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
@@ -41,7 +41,7 @@ The package bundles 5 active `@herbertgao/*` child packages—`pi-agency`, `pi-b
41
41
 
42
42
  Pi loads their extensions and skills through `node_modules/` paths inside one package root. The upstream companions are pinned and bundled, not forked or renamed.
43
43
 
44
- The locally customized CC package follows upstream `pi-cc-extensions@1.0.8`; SoL-Pi follows its complete main baseline `e1a586af` with Pi 1.x/codemode compatibility updates through `21956803`. Local behavior not already covered upstream is retained. SoL-Pi's `update_plan` now follows upstream's model-only contract: invoke it directly, not inside codemode scripts. Action Fusion and ccstyle write rich diffs coexist without disabling either feature. All four SoL-Pi features remain opt-in; its new non-persistent-session evidence archives remain on disk for consumers and require host or caller cleanup.
44
+ The locally customized CC package follows upstream `pi-cc-extensions@1.0.9`; SoL-Pi follows its complete main baseline `e1a586af` with Pi 1.x/codemode compatibility updates through `21956803`. Local behavior not already covered upstream is retained. SoL-Pi's `update_plan` now follows upstream's model-only contract: invoke it directly, not inside codemode scripts. Action Fusion and ccstyle write rich diffs coexist without disabling either feature. All four SoL-Pi features remain opt-in; its new non-persistent-session evidence archives remain on disk for consumers and require host or caller cleanup.
45
45
 
46
46
  Antigravity `0.11.0` enriches search citations by visiting source sites by default (`ANTIGRAVITY_NO_SOURCE_ENRICH=1` disables enrichment). It refreshes a curated model catalog and upgrades the existing model cache; previously listed model IDs may disappear. Ask `2.13.9` lets other extensions in the same process answer or cancel TUI questionnaires through its event channel, without sender authentication. Web Access `0.44.0` keeps direct tool exposure and `toolActivation: auto` by default. Linkup, DeepSeek search and fetch, provider gateways, `toolActivation: "none"`, deferred exposure, and GCE ADC support require explicit configuration.
47
47
 
@@ -163,4 +163,4 @@ THE SOFTWARE.
163
163
 
164
164
  ## `pi-provider-qoder`
165
165
 
166
- The aggregate bundles [`pi-provider-qoder`](https://github.com/simonsmh/pi-provider-qoder) version 0.6.2 under its original package name. npm metadata and the repository README declare the MIT license. The published tarball does not include a LICENSE file. The published package corresponds to git commit [`9764217c0c2c8db9f442b87e045153a11a6dfb1c`](https://github.com/simonsmh/pi-provider-qoder/commit/9764217c0c2c8db9f442b87e045153a11a6dfb1c).
166
+ The aggregate bundles [`pi-provider-qoder`](https://github.com/simonsmh/pi-provider-qoder) version 0.6.5 under its original package name. npm metadata and the repository README declare the MIT license. The published tarball does not include a LICENSE file. The published package corresponds to git commit [`fa5067d1bf0c4accc2fc88ad672e23390a2d6f16`](https://github.com/simonsmh/pi-provider-qoder/commit/fa5067d1bf0c4accc2fc88ad672e23390a2d6f16).
@@ -4,7 +4,7 @@
4
4
 
5
5
  # pi-cc-extensions
6
6
 
7
- > Claude Code-style TUI output with some personal touches and handy utilities.
7
+ > Claude Code-style TUI output with some personal touches and handy utilities (no extra built-in tools).
8
8
 
9
9
  ## Preview
10
10
 
@@ -34,7 +34,7 @@ Run `/reload` after installation.
34
34
  | Context inspection | Usage breakdown and previews for the system prompt, memory, skills, tools definition, and messages | `/context` |
35
35
  | Session/Subagent references | Search and inject effective context from previous Sessions or existing SubAgents | `@` |
36
36
  | Status bar | Shows model, context, cache, cost, and git; also works with `@narumitw/pi-usage` for live quota. Git/cache Nerd Font icons can be turned off | `/ccstyle` |
37
- | Theme | Bundled CC Dark and CC Light themes | `/theme` |
37
+ | Theme | Bundled CC Dark and CC Light themes | `/settings` → Theme |
38
38
 
39
39
  Renderer snapshots for `on` / `compact` modes: [default](./docs/tool-render-examples-default.md) · [compact](./docs/tool-render-examples-compact.md)
40
40
 
@@ -55,7 +55,7 @@ Renderer snapshots for `on` / `compact` modes: [default](./docs/tool-render-exam
55
55
  "enableAgentSummary": true, // per-turn tool summary
56
56
  "enableWorkingMessage": true, // Working... bottom token/elapsed
57
57
  "enableAliases": true, // /clear, /exit aliases
58
- "enableMarkdownEnhance": true, // markdown pass: Mermaid dialects and circled-number conversion; false hands it to other extensions
58
+ "enableMarkdownEnhance": true, // markdown pass: Mermaid dialects and circled-number conversion; false hands it to other extensions
59
59
  "enableEditorPrefix": true, // editor ❯ prefix
60
60
 
61
61
  // ui
@@ -97,12 +97,10 @@ Renderer snapshots for `on` / `compact` modes: [default](./docs/tool-render-exam
97
97
  ```
98
98
 
99
99
  > [!TIP]
100
- > **Fullscreen**: click `click to show more` to expand tool cards, thinking, Skill, and compact summaries. An expanded diff always shows every line; when expanded Input/Output exceeds the line cap, the footer `… +N more lines · click to show more` opens a full preview. Click to collapse.
101
- >
102
- > Both `scrollButtonMode` values show the same `Back to bottom` / `N new message(s)` text: `dock` draws it in a dedicated row, `native` in Pi’s floating overlay.
100
+ > **Fullscreen**: expanded diffs always show every line. When expanded Input/Output exceeds the line cap, the footer shows `… +N more lines`; click for the full preview, click again to collapse.
103
101
 
104
102
  > [!NOTE]
105
- > **Mermaid rendering**: set `markdown.mermaid` to `final` via `~/.pi/agent/settings.json` or the Mermaid diagrams option in `/settings`. Default `streaming` redraws per frame; `final` renders once at completion.
103
+ > **Mermaid rendering**: set `markdown.mermaid` to `final` via `~/.pi/agent/settings.json` or `/settings`. Default `streaming` redraws every frame; `final` renders once.
106
104
 
107
105
  ## Local development
108
106
 
@@ -128,7 +126,7 @@ pi -e . # one run, does not edit settings.json
128
126
 
129
127
  ## Credits
130
128
 
131
- - Based on [`minuque/pi-cc-extensions`](https://github.com/minuque/pi-cc-extensions) 1.0.8 (MIT), upstream baseline [`2cb2c1e`](https://github.com/minuque/pi-cc-extensions/commit/2cb2c1ec7240f183ff68cbab0ea6ae3239529f23), with this repository's configuration migration and compatibility patches retained.
129
+ - Based on [`minuque/pi-cc-extensions`](https://github.com/minuque/pi-cc-extensions) 1.0.9 (MIT), upstream baseline [`6519fad`](https://github.com/minuque/pi-cc-extensions/commit/6519fadd5e0bc84109f3359f2afe8f67337bdaad), with this repository's configuration migration and compatibility patches retained.
132
130
  - Rich diffs are adapted from [`MasuRii/pi-tool-display`](https://github.com/MasuRii/pi-tool-display) (MIT). See [`extensions/renderer/tool/diff/ATTRIBUTION.md`](./extensions/renderer/tool/diff/ATTRIBUTION.md).
133
131
 
134
132
  ## License
@@ -4,7 +4,7 @@
4
4
 
5
5
  # pi-cc-extensions
6
6
 
7
- > 类 Claude Code TUI 输出风格,并融入了一些个人喜好,和一些实用小功能。
7
+ > 类 Claude Code TUI 输出风格,并融入了一些个人喜好,和一些实用小功能(无额外内置工具)。
8
8
 
9
9
  ## 界面预览
10
10
 
@@ -34,7 +34,7 @@ pi install git:github.com/HerbertGao/pi-extensions
34
34
  | 上下文检查 | 查看上下文占用,并预览 System prompt、Memory、Skills、Tools definition 和消息内容 | `/context` |
35
35
  | Session/Subagent 引用 | 搜索并注入历史 Session 或现有 SubAgent 的有效上下文 | `@` |
36
36
  | 状态栏 | 显示:模型、上下文、缓存、费用、git并适配 @narumitw/pi-usage 实时显示额度;git/缓存图标可关 Nerd Font | `/ccstyle` |
37
- | 主题 | 随包提供内置 CC Dark、CC Light 主题 | `/theme` |
37
+ | 主题 | 随包提供内置 CC Dark、CC Light 主题 | `/settings` → Theme |
38
38
 
39
39
  `on` / `compact` 两种模式的渲染样例:[默认模式](./docs/tool-render-examples-default.md) · [紧凑模式](./docs/tool-render-examples-compact.md)
40
40
 
@@ -55,7 +55,7 @@ pi install git:github.com/HerbertGao/pi-extensions
55
55
  "enableAgentSummary": true, // 每回合工具摘要
56
56
  "enableWorkingMessage": true, // Working... 底部 token/耗时
57
57
  "enableAliases": true, // /clear、/exit 别名
58
- "enableMarkdownEnhance": true, // markdown 转换:Mermaid 方言渲染、圈数字转半角括号;false 让位给其他扩展
58
+ "enableMarkdownEnhance": true, // markdown 转换:Mermaid 方言渲染、圈数字转半角括号;false 让位给其他扩展
59
59
  "enableEditorPrefix": true, // 输入框 ❯ 前缀
60
60
 
61
61
  // ui
@@ -96,12 +96,10 @@ pi install git:github.com/HerbertGao/pi-extensions
96
96
  ```
97
97
 
98
98
  > [!TIP]
99
- > **全屏模式**:单击 `click to show more` 展开工具卡、思考、Skill 和 compact 摘要;工具卡展开态 diff 全量显示,Input/Output 超行时末行 `… +N more lines · click to show more` 打开全量预览,单击收起。
100
- >
101
- > `scrollButtonMode` 两种模式文案相同(`Back to bottom` / `N new message(s)`):`dock` 画在独占行,`native` 画在 Pi 原生浮层。
99
+ > **全屏模式**:展开态 diff 全量显示。Input/Output 超行时末行给 `… +N more lines`,单击看全量,再击收起。
102
100
 
103
101
  > [!NOTE]
104
- > **Mermaid 渲染**:建议把 `markdown.mermaid` 设为 `final`(`~/.pi/agent/settings.json` 或 `/settings` 面板的 Mermaid diagrams 选项)。默认 `streaming` 逐帧重绘,`final` 渲染最终版更稳定。
102
+ > **Mermaid 渲染**:`markdown.mermaid` 建议设为 `final`(`~/.pi/agent/settings.json` 或 `/settings`)。默认 `streaming` 逐帧重绘,`final` 只渲染最终版。
105
103
 
106
104
  ## 本地开发
107
105
 
@@ -127,7 +125,7 @@ pi -e . # 只跑一次,不改 settings.json
127
125
 
128
126
  ## 致谢
129
127
 
130
- - 基于 [`minuque/pi-cc-extensions`](https://github.com/minuque/pi-cc-extensions) 1.0.8(MIT),上游基线 [`2cb2c1e`](https://github.com/minuque/pi-cc-extensions/commit/2cb2c1ec7240f183ff68cbab0ea6ae3239529f23);保留本仓库的配置迁移与兼容性补丁。
128
+ - 基于 [`minuque/pi-cc-extensions`](https://github.com/minuque/pi-cc-extensions) 1.0.9(MIT),上游基线 [`6519fad`](https://github.com/minuque/pi-cc-extensions/commit/6519fadd5e0bc84109f3359f2afe8f67337bdaad);保留本仓库的配置迁移与兼容性补丁。
131
129
  - Rich diff 改编自 [`MasuRii/pi-tool-display`](https://github.com/MasuRii/pi-tool-display)(MIT);详见 [`extensions/renderer/tool/diff/ATTRIBUTION.md`](./extensions/renderer/tool/diff/ATTRIBUTION.md)。
132
130
 
133
131
  ## 许可证
@@ -432,6 +432,11 @@ export async function showCcstylePanel(
432
432
  return;
433
433
  }
434
434
 
435
+ // 编辑器插槽只能在面板关闭后替换:面板自己就挂在 editorContainer 上,面板开着时调
436
+ // setEditorComponent 会把面板踢出渲染树、done() 再也走不到,`ctx.ui.custom()` 永不落定,
437
+ // 整个输入管线随之卡死。
438
+ let editorPrefixChanged = false;
439
+
435
440
  await ctx.ui.custom((tui: any, theme: any, _keybindings: any, done: () => void) => {
436
441
  const modeSetting = {
437
442
  id: "mode",
@@ -881,8 +886,7 @@ export async function showCcstylePanel(
881
886
  editorPrefixSetting.description = enabled
882
887
  ? "Show ❯ before the input line; color follows thinking level / bash mode."
883
888
  : "Plain input line, no ❯ glyph.";
884
- if (enabled) applyPromptEditor(ctx);
885
- else clearPromptEditor(ctx);
889
+ editorPrefixChanged = true;
886
890
  ctx.ui.notify(`Updated ${id}: ${value}`, "info");
887
891
  return;
888
892
  }
@@ -1210,6 +1214,11 @@ export async function showCcstylePanel(
1210
1214
  },
1211
1215
  };
1212
1216
  });
1217
+ // 面板已经卸下,插槽此时替换才不会踢掉对话框。
1218
+ if (editorPrefixChanged) {
1219
+ if (config.enableEditorPrefix) applyPromptEditor(ctx);
1220
+ else clearPromptEditor(ctx);
1221
+ }
1213
1222
  // 面板卸下后主 transcript 重新挂载;再刷一次,吃掉打开期间扫树失败的切换。
1214
1223
  hooks.refreshCurrentTranscript(ctx, toolGrouping);
1215
1224
  }
@@ -385,12 +385,24 @@ const createCustomFooterFactory =
385
385
  return 0;
386
386
  };
387
387
 
388
- const render = (width: number): string[] => {
388
+ // 三个会话统计每帧重算会全量遍历 session,长会话把 pi 钉在 100% CPU(issue #80)。
389
+ // leaf/model/thinking 任一变化立即重算;不变时 1s TTL,流式期间每秒刷新一次。
390
+ const SESSION_STATS_TTL_MS = 1_000;
391
+ let statsMemoKey = "";
392
+ let statsMemoAt = 0;
393
+ let statsMemo:
394
+ | { contextUsage: ReturnType<typeof ctx.getContextUsage>; cost: number; cachePct: number }
395
+ | undefined;
396
+ const sessionStats = () => {
389
397
  const model = ctx.model;
390
- const contextUsage = ctx.getContextUsage();
391
- const contextWindow = contextUsage?.contextWindow ?? model?.contextWindow ?? 0;
392
- const percent = contextUsage?.percent;
393
-
398
+ const key = `${ctx.sessionManager.getLeafId() ?? ""}|${model?.provider}/${model?.id}|${ctx.thinkingLevel ?? ""}`;
399
+ if (
400
+ statsMemo &&
401
+ key === statsMemoKey &&
402
+ performance.now() - statsMemoAt < SESSION_STATS_TTL_MS
403
+ ) {
404
+ return statsMemo;
405
+ }
394
406
  let cost = 0;
395
407
  for (const entry of ctx.sessionManager.getEntries()) {
396
408
  if (entry.type === "message") {
@@ -404,6 +416,17 @@ const createCustomFooterFactory =
404
416
  cost += entry.usage.cost?.total || 0;
405
417
  }
406
418
  }
419
+ statsMemo = { contextUsage: ctx.getContextUsage(), cost, cachePct: getCachePct() };
420
+ statsMemoKey = key;
421
+ statsMemoAt = performance.now();
422
+ return statsMemo;
423
+ };
424
+
425
+ const render = (width: number): string[] => {
426
+ const model = ctx.model;
427
+ const { contextUsage, cost, cachePct } = sessionStats();
428
+ const contextWindow = contextUsage?.contextWindow ?? model?.contextWindow ?? 0;
429
+ const percent = contextUsage?.percent;
407
430
 
408
431
  // cwd 默认只显示最底层路径(根目录时回退完整路径)
409
432
  const cwdLabel = ctx.cwd.split(/[\\/]/).filter(Boolean).pop() || ctx.cwd;
@@ -430,7 +453,6 @@ const createCustomFooterFactory =
430
453
  const dimPlugin = (text: string) => colorUsageChip(theme, text);
431
454
 
432
455
  const pctLabel = percent === null || percent === undefined ? "?" : `${Math.floor(percent)}%`;
433
- const cachePct = getCachePct();
434
456
  const glyphs = footerGlyphs(config.footerNerdIcons);
435
457
  const cacheLabel =
436
458
  cachePct > 0 ? `${glyphs.cache ? `${glyphs.cache} ` : ""}${Math.floor(cachePct)}%` : "";
@@ -59,27 +59,48 @@ const promptEditorFactory: EditorFactory = (tui, theme, keybindings) =>
59
59
  let active = false;
60
60
  let previousEditorFactory: EditorFactory | undefined;
61
61
 
62
- /** 撤销本扩展占据的插槽;从未占用就不碰插槽。 */
62
+ /**
63
+ * 撤销本扩展占据的插槽;从未占用就不碰插槽。
64
+ *
65
+ * 插槽可能已经被其他扩展包在外层(pi-inline-skills 会把当前工厂再包一层),
66
+ * 那种结构里无法只拆内层,直接还回占据前的工厂;外层扩展会在下次终端输入时
67
+ * 自己重新包装,前缀不会因此复活。
68
+ *
69
+ * 例外:插槽被 pi 重置回占据前的工厂时(/new、/reload 走 resetExtensionUI),
70
+ * 我们已经不在槽里,再写一次会把 pi 刚重置的结果又覆盖掉;此时只清状态。
71
+ */
63
72
  function releasePromptEditor(ctx: ExtensionContext): void {
64
73
  if (!active) return;
65
- ctx.ui.setEditorComponent(previousEditorFactory);
74
+ const previous = previousEditorFactory;
66
75
  active = false;
67
76
  previousEditorFactory = undefined;
77
+ if (ctx.ui.getEditorComponent?.() === previous) return;
78
+ ctx.ui.setEditorComponent(previous);
68
79
  }
69
80
 
70
- /** 应用输入框前缀;enableEditorPrefix=false 时只撤自己装的那层。 */
81
+ /**
82
+ * 应用输入框前缀;enableEditorPrefix=false 时只撤自己装的那层。
83
+ *
84
+ * 只在没有扩展对话框开着时调用:pi 的 setEditorComponent 会清空 editorContainer 并
85
+ * 抢走焦点,把正在设置面板里的对话框踢出渲染树,对话框的 done() 再也走不到,
86
+ * `ctx.ui.custom()` 的 Promise 永不落定,后续输入全部卡死。设置面板自己不做替换,
87
+ * 等 `ctx.ui.custom()` 返回后再调本函数。
88
+ *
89
+ * 插槽已经装着本扩展的编辑器时直接返回:重复安装只会重建实例,丢掉撤销栈、
90
+ * 历史等编辑器状态,还会打断其他扩展包在外层的编辑器。
91
+ */
71
92
  export function applyPromptEditor(ctx: ExtensionContext): void {
72
93
  if (!ctx?.hasUI || typeof ctx.ui?.setEditorComponent !== "function") return;
94
+ if (!config.enableEditorPrefix) {
95
+ releasePromptEditor(ctx);
96
+ return;
97
+ }
98
+ const current = ctx.ui.getEditorComponent?.();
99
+ if (current === promptEditorFactory) return;
73
100
  try {
74
- if (!config.enableEditorPrefix) {
75
- releasePromptEditor(ctx);
76
- return;
77
- }
78
- if (!active) {
79
- // pi 的插槽是硬替换、没有栈,先记住是谁占着,撤销时还回去。
80
- previousEditorFactory = ctx.ui.getEditorComponent?.();
81
- active = true;
82
- }
101
+ // pi 的插槽是硬替换、没有栈,先记住是谁占着,撤销时还回去。
102
+ previousEditorFactory = current;
103
+ active = true;
83
104
  ctx.ui.setEditorComponent(promptEditorFactory);
84
105
  } catch (err) {
85
106
  ctx.ui.notify(
@@ -1057,6 +1057,14 @@ function compactStopStatusLine(status: string, pad = 0): any {
1057
1057
  /** 展开入口的动作词:我们的 `click to show more`、pi 的 `<key> to expand`(键名可能取不到)。 */
1058
1058
  const EXPAND_ACTION = String.raw`(?:click to show more|(?:[\w/+]+\s+)?to (?:show more|expand))`;
1059
1059
 
1060
+ /**
1061
+ * 展开入口只挂在行尾:正则只看行尾这一段,单行代价与行长无关。
1062
+ * 图片负载(kitty 图形数据的 Base64)一行可达数百 KB,整行过正则会拖住渲染帧。
1063
+ */
1064
+ const SLOT_HINT_WINDOW = 200;
1065
+ /** 窗口里出现这些词才可能有展开入口,其余行(负载、代码)直接放过正则。 */
1066
+ const SLOT_HINT_MARKERS = ["to expand", "to show more"];
1067
+
1060
1068
  const SLOT_HINT_PATTERNS: RegExp[] = [
1061
1069
  // 卡在括号里:`(9 more lines, click to show more)` / `(195 earlier lines, ctrl+o to expand)`,
1062
1070
  // 只去掉动作词,收尾括号与计数保留。
@@ -1066,13 +1074,18 @@ const SLOT_HINT_PATTERNS: RegExp[] = [
1066
1074
  new RegExp(String.raw`\s*(?:[•·]\s*)?${EXPAND_ACTION}\s*$`),
1067
1075
  ];
1068
1076
 
1069
- function stripSlotHint(line: string): string {
1070
- const plain = stripTerminalSequencesPreservingLayout(line);
1077
+ /** 导出供单测:窗口边界与键名长度是性能与裁剪行为的关键,需要逐条钉住。 */
1078
+ export function stripSlotHint(line: string): string {
1079
+ // 切点可能落在转义序列中间,残片只当作窗口头部文本;两个模式都锚在行尾,不受影响。
1080
+ const head = line.slice(0, Math.max(0, line.length - SLOT_HINT_WINDOW));
1081
+ const tail = line.slice(head.length);
1082
+ const plain = stripTerminalSequencesPreservingLayout(tail);
1083
+ if (!SLOT_HINT_MARKERS.some((marker) => plain.includes(marker))) return line;
1071
1084
  for (const re of SLOT_HINT_PATTERNS) {
1072
1085
  const match = re.exec(plain);
1073
1086
  if (!match) continue;
1074
1087
  // 删除区间而非截断后拼纯文本:收尾括号留在原样式里(dim),不会掉回默认前景色。
1075
- return removeStyledRange(line, match.index, match.index + match[0].length);
1088
+ return head + removeStyledRange(tail, match.index, match.index + match[0].length);
1076
1089
  }
1077
1090
  return line;
1078
1091
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@herbertgao/pi-cc-extensions",
3
- "version": "1.0.8-local.1",
3
+ "version": "1.0.9-local.2",
4
4
  "license": "MIT",
5
5
  "description": "A Pi productivity suite with Claude Code-style UI, context inspection, and agent/session references",
6
6
  "type": "module",
@@ -71,10 +71,10 @@
71
71
  },
72
72
  "x-upstream": {
73
73
  "package": "pi-cc-extensions",
74
- "version": "1.0.8",
75
- "reviewedVersion": "1.0.8",
74
+ "version": "1.0.9",
75
+ "reviewedVersion": "1.0.9",
76
76
  "repository": "https://github.com/minuque/pi-cc-extensions",
77
- "commit": "2cb2c1ec7240f183ff68cbab0ea6ae3239529f23",
77
+ "commit": "6519fadd5e0bc84109f3359f2afe8f67337bdaad",
78
78
  "trackVersion": true
79
79
  }
80
80
  }
@@ -719,6 +719,24 @@ function buildThinkingLevelMap(entry) {
719
719
  }
720
720
  return void 0;
721
721
  }
722
+ function buildThinkingConfig(entry) {
723
+ const tc = entry.thinking_config;
724
+ const efforts = tc?.enabled?.efforts;
725
+ if (!efforts || typeof efforts !== "object") return void 0;
726
+ const supported = new Set(Object.keys(efforts));
727
+ const ordered = PI_THINKING_LEVELS.filter((level) => supported.has(level));
728
+ if (ordered.length === 0) return void 0;
729
+ const defaultLevel = PI_THINKING_LEVELS.find((level) => efforts[level]?.is_default);
730
+ return {
731
+ mode: "effort",
732
+ efforts: ordered,
733
+ ...defaultLevel ? { defaultLevel } : {},
734
+ // Qoder's catalog marks a `disabled` branch when thinking can be turned
735
+ // off. Without it reasoning is mandatory upstream, so omp clamps "off" to
736
+ // the lowest supported effort instead of disabling.
737
+ requiresEffort: !tc?.disabled
738
+ };
739
+ }
722
740
  function getCachedModels(mode) {
723
741
  const data = readParsedModelCache(mode);
724
742
  if (data && Array.isArray(data.models)) {
@@ -730,7 +748,7 @@ function getCachedModels(mode) {
730
748
  if (staticModel) return { ...model, id: staticModel.id, name: staticModel.name };
731
749
  return model.name ? { ...model, id: toQoderModelId(model.name) } : model;
732
750
  });
733
- if (data.configs && typeof data.configs === "object" && !data.configs.auto) {
751
+ if (data.configs && typeof data.configs === "object" && !data.configs.auto && !data.configs.Auto) {
734
752
  return models.filter((model) => model.id.toLowerCase() !== "auto");
735
753
  }
736
754
  return models;
@@ -830,6 +848,7 @@ async function updateQoderModelsCache(authToken, userID, name, email, mode) {
830
848
  const isReasoning = !!entry.is_reasoning || !!entry.thinking_config;
831
849
  const supportsEffort = !!entry.thinking_config?.enabled?.efforts;
832
850
  const thinkingLevelMap = buildThinkingLevelMap(entry);
851
+ const thinking = buildThinkingConfig(entry);
833
852
  const modelInfo = { id: toQoderModelId(display), name: display };
834
853
  configs[modelInfo.id] = entry;
835
854
  newModels.push({
@@ -841,6 +860,7 @@ async function updateQoderModelsCache(authToken, userID, name, email, mode) {
841
860
  reasoning: isReasoning,
842
861
  supportsEffort,
843
862
  thinkingLevelMap,
863
+ thinking,
844
864
  input: isVL ? ["text", "image"] : ["text"],
845
865
  cost: ZERO_COST,
846
866
  contextWindow: ctxLen,
@@ -9830,6 +9850,61 @@ function transformMessagesForQoder(messages) {
9830
9850
  }
9831
9851
 
9832
9852
  // src/protocol/stream.ts
9853
+ var MODEL_BUSY_CODE = "10605";
9854
+ var DEFAULT_MODEL_BUSY_RETRIES = 2;
9855
+ var MAX_MODEL_BUSY_RETRIES = 10;
9856
+ var MODEL_BUSY_MAX_WAIT_MS = 5e3;
9857
+ var QoderModelBusyError = class extends Error {
9858
+ constructor(message, retryAfterMs, sawModelOutput = false) {
9859
+ super(message);
9860
+ this.retryAfterMs = retryAfterMs;
9861
+ this.sawModelOutput = sawModelOutput;
9862
+ this.name = "QoderModelBusyError";
9863
+ }
9864
+ retryAfterMs;
9865
+ sawModelOutput;
9866
+ };
9867
+ function parseJsonObject(value, depth = 0) {
9868
+ if (depth > 4) return void 0;
9869
+ if (typeof value === "string") {
9870
+ try {
9871
+ return parseJsonObject(JSON.parse(value), depth + 1);
9872
+ } catch {
9873
+ return void 0;
9874
+ }
9875
+ }
9876
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
9877
+ }
9878
+ function parseModelBusyRejection(body) {
9879
+ const outer = parseJsonObject(body);
9880
+ const busy = parseJsonObject(outer?.message);
9881
+ if (busy?.code !== MODEL_BUSY_CODE) return void 0;
9882
+ const queue = parseJsonObject(busy.message);
9883
+ if (!queue) return void 0;
9884
+ if (queue.isQueued !== false || queue.serviceAvailable !== true) return void 0;
9885
+ const seconds = queue.retryAfterSeconds;
9886
+ const retryAfterMs = typeof seconds === "number" && Number.isFinite(seconds) && seconds > 0 ? Math.round(seconds * 1e3) : 0;
9887
+ return { retryAfterMs };
9888
+ }
9889
+ function sleepWithAbort(ms, signal) {
9890
+ if (signal?.aborted) return Promise.reject(new Error("Aborted"));
9891
+ if (ms <= 0) return Promise.resolve();
9892
+ return new Promise((resolve2, reject) => {
9893
+ if (signal?.aborted) {
9894
+ reject(new Error("Aborted"));
9895
+ return;
9896
+ }
9897
+ const onAbort = () => {
9898
+ clearTimeout(timer);
9899
+ reject(new Error("Aborted"));
9900
+ };
9901
+ const timer = setTimeout(() => {
9902
+ signal?.removeEventListener("abort", onAbort);
9903
+ resolve2();
9904
+ }, ms);
9905
+ signal?.addEventListener("abort", onAbort, { once: true });
9906
+ });
9907
+ }
9833
9908
  function refreshToolIndexes(output, toolCalls) {
9834
9909
  const lastToolState = toolCalls.lastToolState;
9835
9910
  if (!lastToolState || output.content[lastToolState.contentIndex] === lastToolState.block) return;
@@ -10052,7 +10127,9 @@ function streamQoder(model, context, options) {
10052
10127
  const toolsRaw = resolved.tools.length > 0 ? transformTools(resolved.tools) : void 0;
10053
10128
  const recordID = stableChatRecordID(qoderModel, normalizedMessages, toolsRaw, maxTokens);
10054
10129
  const requestedLevel = options?.reasoning;
10055
- const clamped = requestedLevel ? clampThinkingLevel(model, requestedLevel) : void 0;
10130
+ const extOptions = options;
10131
+ const explicitlyOff = extOptions?.disableReasoning === true || extOptions?.forceReasoningOff === true || requestedLevel === false || requestedLevel === "off";
10132
+ const clamped = !explicitlyOff && requestedLevel ? clampThinkingLevel(model, requestedLevel) : void 0;
10056
10133
  const reasoningLevel = clamped === "off" ? void 0 : clamped;
10057
10134
  const parameters = { max_tokens: maxTokens };
10058
10135
  if (reasoningLevel) {
@@ -10064,6 +10141,11 @@ function streamQoder(model, context, options) {
10064
10141
  }
10065
10142
  } else {
10066
10143
  parameters.enable_thinking = false;
10144
+ const tc = modelConfig?.thinking_config;
10145
+ const lacksDisabledBranch = tc?.enabled?.efforts && !tc.disabled || model.thinkingLevelMap?.off === null;
10146
+ if (!lacksDisabledBranch) {
10147
+ parameters.reasoning_effort = "none";
10148
+ }
10067
10149
  }
10068
10150
  const reqBody = {
10069
10151
  request_id: crypto3.randomUUID(),
@@ -10097,14 +10179,14 @@ function streamQoder(model, context, options) {
10097
10179
  context: [],
10098
10180
  modelConfig: {
10099
10181
  key: qoderModel,
10100
- is_reasoning: isReasoning
10182
+ is_reasoning: reasoningLevel ? isReasoning : false
10101
10183
  },
10102
10184
  originalContent: lastUserText
10103
10185
  },
10104
10186
  features: [],
10105
10187
  text: lastUserText
10106
10188
  },
10107
- model_config: modelConfig,
10189
+ model_config: reasoningLevel ? modelConfig : { ...modelConfig, is_reasoning: false },
10108
10190
  business: {
10109
10191
  product: "cli",
10110
10192
  version: "1.0.0",
@@ -10115,328 +10197,401 @@ function streamQoder(model, context, options) {
10115
10197
  begin_at: Date.now()
10116
10198
  }
10117
10199
  };
10118
- const bodyBytes = Buffer.from(JSON.stringify(reqBody));
10119
- const encodedBytes = qoderEncodeBody(bodyBytes);
10120
10200
  const chatURL = getQoderChatURL(providerMode);
10121
- const headers = buildAuthHeaders(encodedBytes, chatURL, {
10201
+ const modelSource = modelConfig.source || "system";
10202
+ const requestedRetries = options?.maxRetries;
10203
+ const modelBusyRetries = Math.min(
10204
+ Math.max(
10205
+ 0,
10206
+ typeof requestedRetries === "number" && Number.isFinite(requestedRetries) ? Math.floor(requestedRetries) : DEFAULT_MODEL_BUSY_RETRIES
10207
+ ),
10208
+ MAX_MODEL_BUSY_RETRIES
10209
+ );
10210
+ const requestedMaxWaitMs = options?.maxRetryDelayMs;
10211
+ const modelBusyMaxWaitMs = typeof requestedMaxWaitMs === "number" && Number.isFinite(requestedMaxWaitMs) && requestedMaxWaitMs > 0 ? Math.min(MODEL_BUSY_MAX_WAIT_MS, requestedMaxWaitMs) : MODEL_BUSY_MAX_WAIT_MS;
10212
+ let encodedBytes = qoderEncodeBody(Buffer.from(JSON.stringify(reqBody)));
10213
+ let headers = buildAuthHeaders(encodedBytes, chatURL, {
10122
10214
  userID,
10123
10215
  authToken: accessToken,
10124
10216
  name,
10125
10217
  email,
10126
10218
  machineID
10127
10219
  });
10128
- const modelSource = modelConfig.source || "system";
10129
- const response = await fetch(chatURL, {
10130
- method: "POST",
10131
- headers: {
10132
- "Content-Type": "application/json",
10133
- Accept: "text/event-stream",
10134
- "Cache-Control": "no-cache",
10135
- "Accept-Encoding": "identity",
10136
- "X-Model-Key": qoderModel,
10137
- "X-Model-Source": modelSource,
10138
- ...headers
10139
- },
10140
- body: encodedBytes,
10141
- signal: options?.signal
10142
- });
10143
- if (!response.ok) {
10144
- const errText = await response.text();
10145
- throw new Error(`Qoder API request failed: ${response.status} ${response.statusText}. Response: ${errText}`);
10146
- }
10147
- const reader = response.body?.getReader();
10148
- if (!reader) throw new Error("No response body");
10149
- const decoder = new TextDecoder();
10150
- let buffer = "";
10151
- let bufferStart = 0;
10152
- let contentBlockIndex = -1;
10153
- let thinkingBlockIndex = -1;
10154
- let rawReasoningTail = "";
10155
- let toolCalls;
10156
10220
  const thinkingEnabled = options?.reasoning !== false && options?.reasoning !== "off";
10157
- const thinkingParser = thinkingEnabled ? new ThinkingTagParser(output, stream) : null;
10158
10221
  stream.push({ type: "start", partial: output });
10159
- let sawDone = false;
10160
- try {
10161
- while (!sawDone) {
10162
- const { done, value } = await reader.read();
10163
- if (done) break;
10164
- if (bufferStart > 0) {
10165
- buffer = buffer.substring(bufferStart);
10166
- bufferStart = 0;
10167
- }
10168
- buffer += decoder.decode(value, { stream: true });
10169
- while (true) {
10170
- const lineEnd = buffer.indexOf("\n", bufferStart);
10171
- if (lineEnd === -1) break;
10172
- const line = buffer.substring(bufferStart, lineEnd).trim();
10173
- bufferStart = lineEnd + 1;
10174
- if (!line.startsWith("data:")) continue;
10175
- const dataStr = line.substring(5).trim();
10176
- if (dataStr === "[DONE]") {
10177
- sawDone = true;
10178
- break;
10222
+ const runAttempt = async () => {
10223
+ options?.signal?.throwIfAborted();
10224
+ output.stopReason = "stop";
10225
+ output.errorMessage = void 0;
10226
+ output.responseId = void 0;
10227
+ output.responseModel = void 0;
10228
+ output.usage = {
10229
+ input: 0,
10230
+ output: 0,
10231
+ cacheRead: 0,
10232
+ cacheWrite: 0,
10233
+ totalTokens: 0,
10234
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
10235
+ };
10236
+ const response = await fetch(chatURL, {
10237
+ method: "POST",
10238
+ headers: {
10239
+ "Content-Type": "application/json",
10240
+ Accept: "text/event-stream",
10241
+ "Cache-Control": "no-cache",
10242
+ "Accept-Encoding": "identity",
10243
+ "X-Model-Key": qoderModel,
10244
+ "X-Model-Source": modelSource,
10245
+ ...headers
10246
+ },
10247
+ body: encodedBytes,
10248
+ signal: options?.signal
10249
+ });
10250
+ if (!response.ok) {
10251
+ const errText = await response.text();
10252
+ throw new Error(`Qoder API request failed: ${response.status} ${response.statusText}. Response: ${errText}`);
10253
+ }
10254
+ const reader = response.body?.getReader();
10255
+ if (!reader) throw new Error("No response body");
10256
+ const decoder = new TextDecoder();
10257
+ let buffer = "";
10258
+ let bufferStart = 0;
10259
+ let contentBlockIndex = -1;
10260
+ let thinkingBlockIndex = -1;
10261
+ let rawReasoningTail = "";
10262
+ let toolCalls;
10263
+ const thinkingParser = thinkingEnabled ? new ThinkingTagParser(output, stream) : null;
10264
+ let sawModelOutput = false;
10265
+ let sawDone = false;
10266
+ try {
10267
+ while (!sawDone) {
10268
+ const { done, value } = await reader.read();
10269
+ if (done) break;
10270
+ if (bufferStart > 0) {
10271
+ buffer = buffer.substring(bufferStart);
10272
+ bufferStart = 0;
10179
10273
  }
10180
- try {
10181
- const envelope = JSON.parse(dataStr);
10182
- if (envelope.statusCodeValue && envelope.statusCodeValue !== 200) {
10183
- throw new Error(`Upstream status ${envelope.statusCodeValue}: ${envelope.body}`);
10184
- }
10185
- const innerStr = envelope.body;
10186
- if (innerStr === "[DONE]") {
10274
+ buffer += decoder.decode(value, { stream: true });
10275
+ while (true) {
10276
+ const lineEnd = buffer.indexOf("\n", bufferStart);
10277
+ if (lineEnd === -1) break;
10278
+ const line = buffer.substring(bufferStart, lineEnd).trim();
10279
+ bufferStart = lineEnd + 1;
10280
+ if (!line.startsWith("data:")) continue;
10281
+ const dataStr = line.substring(5).trim();
10282
+ if (dataStr === "[DONE]") {
10187
10283
  sawDone = true;
10188
10284
  break;
10189
10285
  }
10190
- if (!innerStr) continue;
10191
- const inner = JSON.parse(innerStr);
10192
- if (inner.id) output.responseId = inner.id;
10193
- if (inner.model) output.responseModel = inner.model;
10194
- if (inner.usage) {
10195
- applyQoderCredits(output.usage, inner.usage, model.provider === "qoder-cn" ? "qoder-cn" : "qoder");
10196
- const u = inner.usage;
10197
- const promptTokens = u.prompt_tokens ?? 0;
10198
- const cacheReadTokens = u.prompt_tokens_details?.cached_tokens ?? 0;
10199
- const cacheWriteTokens = u.prompt_tokens_details?.cache_write_tokens ?? 0;
10200
- output.usage.input = Math.max(0, promptTokens - cacheReadTokens - cacheWriteTokens);
10201
- output.usage.output = u.completion_tokens ?? 0;
10202
- output.usage.totalTokens = u.total_tokens ?? 0;
10203
- output.usage.cacheRead = cacheReadTokens;
10204
- output.usage.cacheWrite = cacheWriteTokens;
10205
- }
10206
- if (inner.choices && inner.choices.length > 0) {
10207
- const choice = inner.choices[0];
10208
- const delta = choice.delta;
10209
- if (delta) {
10210
- if (delta.reasoning_content) {
10211
- rawReasoningTail = (rawReasoningTail + delta.reasoning_content).slice(-512);
10212
- const reasoningChunk = stripDsmlResidue(stripThinkingTags(delta.reasoning_content));
10213
- if (reasoningChunk) {
10214
- if (thinkingBlockIndex === -1) {
10215
- thinkingBlockIndex = output.content.length;
10216
- output.content.push({ type: "thinking", thinking: "" });
10217
- stream.push({ type: "thinking_start", contentIndex: thinkingBlockIndex, partial: output });
10218
- }
10219
- const block = output.content[thinkingBlockIndex];
10220
- block.thinking += reasoningChunk;
10221
- stream.push({
10222
- type: "thinking_delta",
10223
- contentIndex: thinkingBlockIndex,
10224
- delta: reasoningChunk,
10225
- partial: output
10226
- });
10227
- }
10286
+ try {
10287
+ const envelope = JSON.parse(dataStr);
10288
+ if (envelope.statusCodeValue && envelope.statusCodeValue !== 200) {
10289
+ const busy = parseModelBusyRejection(envelope.body);
10290
+ if (busy) {
10291
+ throw new QoderModelBusyError(
10292
+ `Upstream status ${envelope.statusCodeValue}: ${envelope.body}`,
10293
+ busy.retryAfterMs,
10294
+ sawModelOutput
10295
+ );
10228
10296
  }
10229
- if (delta.content) {
10230
- if (thinkingBlockIndex !== -1) {
10231
- const block = output.content[thinkingBlockIndex];
10232
- stream.push({
10233
- type: "thinking_end",
10234
- contentIndex: thinkingBlockIndex,
10235
- content: block.thinking,
10236
- partial: output
10237
- });
10238
- thinkingBlockIndex = -1;
10297
+ throw new Error(`Upstream status ${envelope.statusCodeValue}: ${envelope.body}`);
10298
+ }
10299
+ const innerStr = envelope.body;
10300
+ if (innerStr === "[DONE]") {
10301
+ sawDone = true;
10302
+ break;
10303
+ }
10304
+ if (!innerStr) continue;
10305
+ const inner = JSON.parse(innerStr);
10306
+ if (inner.id) output.responseId = inner.id;
10307
+ if (inner.model) output.responseModel = inner.model;
10308
+ if (inner.usage) {
10309
+ applyQoderCredits(output.usage, inner.usage, model.provider === "qoder-cn" ? "qoder-cn" : "qoder");
10310
+ const u = inner.usage;
10311
+ const promptTokens = u.prompt_tokens ?? 0;
10312
+ const cacheReadTokens = u.prompt_tokens_details?.cached_tokens ?? 0;
10313
+ const cacheWriteTokens = u.prompt_tokens_details?.cache_write_tokens ?? 0;
10314
+ output.usage.input = Math.max(0, promptTokens - cacheReadTokens - cacheWriteTokens);
10315
+ output.usage.output = u.completion_tokens ?? 0;
10316
+ output.usage.totalTokens = u.total_tokens ?? 0;
10317
+ output.usage.cacheRead = cacheReadTokens;
10318
+ output.usage.cacheWrite = cacheWriteTokens;
10319
+ }
10320
+ if (inner.choices && inner.choices.length > 0) {
10321
+ const choice = inner.choices[0];
10322
+ const delta = choice.delta;
10323
+ if (delta) {
10324
+ if (delta.reasoning_content || delta.content || Array.isArray(delta.tool_calls) && delta.tool_calls.length > 0) {
10325
+ sawModelOutput = true;
10239
10326
  }
10240
- if (thinkingParser) {
10241
- thinkingParser.processChunk(delta.content);
10242
- if (toolCalls?.lastToolState) refreshToolIndexes(output, toolCalls);
10243
- } else {
10244
- if (contentBlockIndex === -1) {
10245
- contentBlockIndex = output.content.length;
10246
- output.content.push({ type: "text", text: "" });
10247
- stream.push({ type: "text_start", contentIndex: contentBlockIndex, partial: output });
10327
+ if (delta.reasoning_content) {
10328
+ rawReasoningTail = (rawReasoningTail + delta.reasoning_content).slice(-512);
10329
+ const reasoningChunk = stripDsmlResidue(stripThinkingTags(delta.reasoning_content));
10330
+ if (reasoningChunk) {
10331
+ if (thinkingBlockIndex === -1) {
10332
+ thinkingBlockIndex = output.content.length;
10333
+ output.content.push({ type: "thinking", thinking: "" });
10334
+ stream.push({ type: "thinking_start", contentIndex: thinkingBlockIndex, partial: output });
10335
+ }
10336
+ const block = output.content[thinkingBlockIndex];
10337
+ block.thinking += reasoningChunk;
10338
+ stream.push({
10339
+ type: "thinking_delta",
10340
+ contentIndex: thinkingBlockIndex,
10341
+ delta: reasoningChunk,
10342
+ partial: output
10343
+ });
10248
10344
  }
10249
- const block = output.content[contentBlockIndex];
10250
- block.text += delta.content;
10251
- stream.push({
10252
- type: "text_delta",
10253
- contentIndex: contentBlockIndex,
10254
- delta: delta.content,
10255
- partial: output
10256
- });
10257
10345
  }
10258
- }
10259
- if (delta.tool_calls && Array.isArray(delta.tool_calls)) {
10260
- for (const tc of delta.tool_calls) {
10261
- const id = tc.id || "";
10262
- const name2 = tc.function?.name || "";
10263
- const argDelta = tc.function?.arguments ?? "";
10264
- if (typeof id !== "string" || typeof name2 !== "string") {
10265
- throw new Error("Tool-call identity conflict: invalid metadata");
10346
+ if (delta.content) {
10347
+ if (thinkingBlockIndex !== -1) {
10348
+ const block = output.content[thinkingBlockIndex];
10349
+ stream.push({
10350
+ type: "thinking_end",
10351
+ contentIndex: thinkingBlockIndex,
10352
+ content: block.thinking,
10353
+ partial: output
10354
+ });
10355
+ thinkingBlockIndex = -1;
10266
10356
  }
10267
- if (typeof argDelta !== "string") throw new Error("Invalid tool-call argument fragment");
10268
- if (!id && !name2 && !argDelta) continue;
10269
- toolCalls ??= {
10270
- states: [],
10271
- byId: /* @__PURE__ */ new Map(),
10272
- byIndex: /* @__PURE__ */ new Map(),
10273
- unscopedCandidates: /* @__PURE__ */ new Set(),
10274
- statesByBlock: /* @__PURE__ */ new Map()
10275
- };
10276
- const index = typeof tc.index === "number" ? tc.index : void 0;
10277
- let candidates;
10278
- if (index !== void 0) {
10279
- candidates = toolCalls.byIndex.get(index);
10280
- if (!candidates) {
10281
- candidates = { states: /* @__PURE__ */ new Set(), complete: /* @__PURE__ */ new Set(), unique: void 0 };
10282
- toolCalls.byIndex.set(index, candidates);
10357
+ if (thinkingParser) {
10358
+ thinkingParser.processChunk(delta.content);
10359
+ if (toolCalls?.lastToolState) refreshToolIndexes(output, toolCalls);
10360
+ } else {
10361
+ if (contentBlockIndex === -1) {
10362
+ contentBlockIndex = output.content.length;
10363
+ output.content.push({ type: "text", text: "" });
10364
+ stream.push({ type: "text_start", contentIndex: contentBlockIndex, partial: output });
10283
10365
  }
10366
+ const block = output.content[contentBlockIndex];
10367
+ block.text += delta.content;
10368
+ stream.push({
10369
+ type: "text_delta",
10370
+ contentIndex: contentBlockIndex,
10371
+ delta: delta.content,
10372
+ partial: output
10373
+ });
10284
10374
  }
10285
- let state = id ? toolCalls.byId.get(id) : void 0;
10286
- let associated = !!state && !!candidates && candidates.states.has(state);
10287
- if (id && candidates && !associated && candidates.complete.size > 0) {
10288
- retireCompleteCandidates(toolCalls, candidates);
10289
- }
10290
- const available = candidates?.states ?? toolCalls.unscopedCandidates;
10291
- if (!state) {
10292
- const only = available.size === 1 ? candidates ? candidates.unique : available.values().next().value : void 0;
10293
- if (!id && available.size > 1) {
10294
- throw new Error(`Ambiguous tool-call continuation (candidates=${available.size})`);
10375
+ }
10376
+ if (delta.tool_calls && Array.isArray(delta.tool_calls)) {
10377
+ for (const tc of delta.tool_calls) {
10378
+ const id = tc.id || "";
10379
+ const name2 = tc.function?.name || "";
10380
+ const argDelta = tc.function?.arguments ?? "";
10381
+ if (typeof id !== "string" || typeof name2 !== "string") {
10382
+ throw new Error("Tool-call identity conflict: invalid metadata");
10295
10383
  }
10296
- if (only && (!id || !only.id)) {
10297
- state = only;
10298
- associated = candidates !== void 0;
10299
- } else {
10300
- state = {
10301
- argumentChunks: [],
10302
- argumentLength: 0,
10303
- depth: 0,
10304
- inString: false,
10305
- escaped: false,
10306
- complete: false,
10307
- id: "",
10308
- name: "",
10309
- contentIndex: -1,
10310
- candidates: /* @__PURE__ */ new Set(),
10311
- unindexed: index === void 0
10312
- };
10313
- toolCalls.states.push(state);
10384
+ if (typeof argDelta !== "string") throw new Error("Invalid tool-call argument fragment");
10385
+ if (!id && !name2 && !argDelta) continue;
10386
+ toolCalls ??= {
10387
+ states: [],
10388
+ byId: /* @__PURE__ */ new Map(),
10389
+ byIndex: /* @__PURE__ */ new Map(),
10390
+ unscopedCandidates: /* @__PURE__ */ new Set(),
10391
+ statesByBlock: /* @__PURE__ */ new Map()
10392
+ };
10393
+ const index = typeof tc.index === "number" ? tc.index : void 0;
10394
+ let candidates;
10395
+ if (index !== void 0) {
10396
+ candidates = toolCalls.byIndex.get(index);
10397
+ if (!candidates) {
10398
+ candidates = { states: /* @__PURE__ */ new Set(), complete: /* @__PURE__ */ new Set(), unique: void 0 };
10399
+ toolCalls.byIndex.set(index, candidates);
10400
+ }
10314
10401
  }
10315
- }
10316
- if (name2 && state.name && name2 !== state.name) {
10317
- throw new Error("Tool-call identity conflict: inconsistent name");
10318
- }
10319
- const newlyIdentified = !!id && !state.id;
10320
- const newlyNamed = !!name2 && !state.name;
10321
- if (newlyIdentified) {
10322
- state.id = id;
10323
- toolCalls.byId.set(id, state);
10324
- }
10325
- if (newlyNamed) state.name = name2;
10326
- if (!associated) {
10327
- toolCalls.unscopedCandidates.add(state);
10328
- if (candidates) {
10329
- state.unindexed = false;
10330
- state.candidates.add(candidates);
10331
- candidates.states.add(state);
10332
- candidates.unique = candidates.states.size === 1 ? state : void 0;
10333
- if (state.complete && state.id) candidates.complete.add(state);
10402
+ let state = id ? toolCalls.byId.get(id) : void 0;
10403
+ let associated = !!state && !!candidates && candidates.states.has(state);
10404
+ if (id && candidates && !associated && candidates.complete.size > 0) {
10405
+ retireCompleteCandidates(toolCalls, candidates);
10334
10406
  }
10335
- }
10336
- const wasComplete = state.complete;
10337
- if (argDelta) appendToolArguments(state, argDelta);
10338
- if (state.complete && state.id && (!wasComplete || newlyIdentified)) {
10339
- for (const scope of state.candidates) scope.complete.add(state);
10340
- }
10341
- if (!state.block && (state.id || state.name)) {
10342
- state.block = { type: "toolCall", id: state.id, name: state.name, arguments: {} };
10343
- state.contentIndex = output.content.length;
10344
- output.content.push(state.block);
10345
- toolCalls.statesByBlock.set(state.block, state);
10346
- toolCalls.lastToolState = state;
10347
- stream.push({ type: "toolcall_start", contentIndex: state.contentIndex, partial: output });
10348
- for (const fragment of state.argumentChunks) {
10349
- stream.push({
10350
- type: "toolcall_delta",
10351
- contentIndex: state.contentIndex,
10352
- delta: fragment,
10353
- partial: output
10354
- });
10407
+ const available = candidates?.states ?? toolCalls.unscopedCandidates;
10408
+ if (!state) {
10409
+ const only = available.size === 1 ? candidates ? candidates.unique : available.values().next().value : void 0;
10410
+ if (!id && available.size > 1) {
10411
+ throw new Error(`Ambiguous tool-call continuation (candidates=${available.size})`);
10412
+ }
10413
+ if (only && (!id || !only.id)) {
10414
+ state = only;
10415
+ associated = candidates !== void 0;
10416
+ } else {
10417
+ state = {
10418
+ argumentChunks: [],
10419
+ argumentLength: 0,
10420
+ depth: 0,
10421
+ inString: false,
10422
+ escaped: false,
10423
+ complete: false,
10424
+ id: "",
10425
+ name: "",
10426
+ contentIndex: -1,
10427
+ candidates: /* @__PURE__ */ new Set(),
10428
+ unindexed: index === void 0
10429
+ };
10430
+ toolCalls.states.push(state);
10431
+ }
10432
+ }
10433
+ if (name2 && state.name && name2 !== state.name) {
10434
+ throw new Error("Tool-call identity conflict: inconsistent name");
10435
+ }
10436
+ const newlyIdentified = !!id && !state.id;
10437
+ const newlyNamed = !!name2 && !state.name;
10438
+ if (newlyIdentified) {
10439
+ state.id = id;
10440
+ toolCalls.byId.set(id, state);
10355
10441
  }
10356
- } else if (state.block) {
10357
- if (newlyIdentified) state.block.id = state.id;
10358
- if (newlyNamed) state.block.name = state.name;
10359
- if (argDelta) {
10360
- stream.push({
10361
- type: "toolcall_delta",
10362
- contentIndex: state.contentIndex,
10363
- delta: argDelta,
10364
- partial: output
10365
- });
10442
+ if (newlyNamed) state.name = name2;
10443
+ if (!associated) {
10444
+ toolCalls.unscopedCandidates.add(state);
10445
+ if (candidates) {
10446
+ state.unindexed = false;
10447
+ state.candidates.add(candidates);
10448
+ candidates.states.add(state);
10449
+ candidates.unique = candidates.states.size === 1 ? state : void 0;
10450
+ if (state.complete && state.id) candidates.complete.add(state);
10451
+ }
10452
+ }
10453
+ const wasComplete = state.complete;
10454
+ if (argDelta) appendToolArguments(state, argDelta);
10455
+ if (state.complete && state.id && (!wasComplete || newlyIdentified)) {
10456
+ for (const scope of state.candidates) scope.complete.add(state);
10457
+ }
10458
+ if (!state.block && (state.id || state.name)) {
10459
+ state.block = { type: "toolCall", id: state.id, name: state.name, arguments: {} };
10460
+ state.contentIndex = output.content.length;
10461
+ output.content.push(state.block);
10462
+ toolCalls.statesByBlock.set(state.block, state);
10463
+ toolCalls.lastToolState = state;
10464
+ stream.push({ type: "toolcall_start", contentIndex: state.contentIndex, partial: output });
10465
+ for (const fragment of state.argumentChunks) {
10466
+ stream.push({
10467
+ type: "toolcall_delta",
10468
+ contentIndex: state.contentIndex,
10469
+ delta: fragment,
10470
+ partial: output
10471
+ });
10472
+ }
10473
+ } else if (state.block) {
10474
+ if (newlyIdentified) state.block.id = state.id;
10475
+ if (newlyNamed) state.block.name = state.name;
10476
+ if (argDelta) {
10477
+ stream.push({
10478
+ type: "toolcall_delta",
10479
+ contentIndex: state.contentIndex,
10480
+ delta: argDelta,
10481
+ partial: output
10482
+ });
10483
+ }
10366
10484
  }
10367
10485
  }
10368
10486
  }
10369
10487
  }
10488
+ if (choice.finish_reason) {
10489
+ output.stopReason = choice.finish_reason;
10490
+ }
10370
10491
  }
10371
- if (choice.finish_reason) {
10372
- output.stopReason = choice.finish_reason;
10373
- }
10374
- }
10375
- } catch (e) {
10376
- if (e instanceof SyntaxError) {
10377
- if (process.env.QODER_DEBUG) {
10378
- console.error("[pi-provider-qoder] skipping malformed SSE line:", dataStr.slice(0, 200));
10492
+ } catch (e) {
10493
+ if (e instanceof SyntaxError) {
10494
+ if (process.env.QODER_DEBUG) {
10495
+ console.error("[pi-provider-qoder] skipping malformed SSE line:", dataStr.slice(0, 200));
10496
+ }
10497
+ continue;
10379
10498
  }
10380
- continue;
10499
+ throw e;
10381
10500
  }
10382
- throw e;
10383
10501
  }
10384
10502
  }
10385
- }
10386
- } finally {
10387
- try {
10388
- await reader.cancel().catch(() => {
10389
- });
10390
10503
  } finally {
10391
- reader.releaseLock();
10392
- }
10393
- }
10394
- if (thinkingParser) {
10395
- thinkingParser.finalize();
10396
- if (toolCalls?.lastToolState) refreshToolIndexes(output, toolCalls);
10397
- }
10398
- if (thinkingBlockIndex !== -1) {
10399
- const block = output.content[thinkingBlockIndex];
10400
- stream.push({
10401
- type: "thinking_end",
10402
- contentIndex: thinkingBlockIndex,
10403
- content: block.thinking,
10404
- partial: output
10405
- });
10406
- }
10407
- if (toolCalls) {
10408
- for (const state of toolCalls.states) {
10409
- if (!state.id || !state.name) {
10410
- throw new Error(`Unresolved tool-call identity (characters=${state.argumentLength})`);
10504
+ try {
10505
+ await reader.cancel().catch(() => {
10506
+ });
10507
+ } finally {
10508
+ reader.releaseLock();
10411
10509
  }
10412
- parseToolArguments(state);
10413
10510
  }
10414
- for (const [block, state] of toolCalls.statesByBlock) {
10415
- block.arguments = parseToolArguments(state);
10511
+ if (thinkingParser) {
10512
+ thinkingParser.finalize();
10513
+ if (toolCalls?.lastToolState) refreshToolIndexes(output, toolCalls);
10514
+ }
10515
+ if (thinkingBlockIndex !== -1) {
10516
+ const block = output.content[thinkingBlockIndex];
10416
10517
  stream.push({
10417
- type: "toolcall_end",
10418
- contentIndex: state.contentIndex,
10419
- toolCall: block,
10518
+ type: "thinking_end",
10519
+ contentIndex: thinkingBlockIndex,
10520
+ content: block.thinking,
10420
10521
  partial: output
10421
10522
  });
10422
10523
  }
10423
- if (toolCalls.statesByBlock.size > 0 && output.stopReason !== "length") {
10424
- output.stopReason = "toolUse";
10524
+ if (toolCalls) {
10525
+ for (const state of toolCalls.states) {
10526
+ if (!state.id || !state.name) {
10527
+ throw new Error(`Unresolved tool-call identity (characters=${state.argumentLength})`);
10528
+ }
10529
+ parseToolArguments(state);
10530
+ }
10531
+ for (const [block, state] of toolCalls.statesByBlock) {
10532
+ block.arguments = parseToolArguments(state);
10533
+ stream.push({
10534
+ type: "toolcall_end",
10535
+ contentIndex: state.contentIndex,
10536
+ toolCall: block,
10537
+ partial: output
10538
+ });
10539
+ }
10540
+ if (toolCalls.statesByBlock.size > 0 && output.stopReason !== "length") {
10541
+ output.stopReason = "toolUse";
10542
+ }
10425
10543
  }
10426
- }
10427
- if (isDegenerateDsmlTurn(output, rawReasoningTail)) {
10428
- output.stopReason = "error";
10429
- output.errorMessage = "Qoder server error: degenerate model output (unparseable DSML tool-call markup, no tool call executed)";
10430
- stream.push({ type: "error", reason: "error", error: output });
10544
+ if (isDegenerateDsmlTurn(output, rawReasoningTail)) {
10545
+ output.stopReason = "error";
10546
+ output.errorMessage = "Qoder server error: degenerate model output (unparseable DSML tool-call markup, no tool call executed)";
10547
+ stream.push({ type: "error", reason: "error", error: output });
10548
+ stream.end();
10549
+ return;
10550
+ }
10551
+ stream.push({
10552
+ type: "done",
10553
+ reason: output.stopReason,
10554
+ message: output
10555
+ });
10431
10556
  stream.end();
10432
- return;
10557
+ };
10558
+ for (let attempt = 0; ; attempt++) {
10559
+ try {
10560
+ await runAttempt();
10561
+ return;
10562
+ } catch (e) {
10563
+ if (!(e instanceof QoderModelBusyError)) throw e;
10564
+ if (e.sawModelOutput || output.content.length > 0) {
10565
+ throw new Error("Qoder model rejected the request after partial output (10605 RESOURCE_LIMIT)");
10566
+ }
10567
+ const requestedWaitMs = e.retryAfterMs ?? 0;
10568
+ if (attempt >= modelBusyRetries) {
10569
+ throw new QoderModelBusyError(
10570
+ `Qoder server error: model is busy (10605 RESOURCE_LIMIT, retryAfterSeconds=${Math.round(requestedWaitMs / 1e3)}, attempts=${attempt + 1})`,
10571
+ requestedWaitMs
10572
+ );
10573
+ }
10574
+ if (requestedWaitMs > modelBusyMaxWaitMs) {
10575
+ throw new QoderModelBusyError(
10576
+ `Qoder server error: model is busy (10605 RESOURCE_LIMIT, requested delay ${requestedWaitMs}ms exceeds local cap ${modelBusyMaxWaitMs}ms)`,
10577
+ requestedWaitMs
10578
+ );
10579
+ }
10580
+ await sleepWithAbort(requestedWaitMs, options?.signal);
10581
+ options?.signal?.throwIfAborted();
10582
+ const nextId = crypto3.randomUUID();
10583
+ reqBody.request_id = nextId;
10584
+ reqBody.chat_record_id = nextId;
10585
+ encodedBytes = qoderEncodeBody(Buffer.from(JSON.stringify(reqBody)));
10586
+ headers = buildAuthHeaders(encodedBytes, chatURL, {
10587
+ userID,
10588
+ authToken: accessToken,
10589
+ name,
10590
+ email,
10591
+ machineID
10592
+ });
10593
+ }
10433
10594
  }
10434
- stream.push({
10435
- type: "done",
10436
- reason: output.stopReason,
10437
- message: output
10438
- });
10439
- stream.end();
10440
10595
  } catch (e) {
10441
10596
  output.stopReason = options?.signal?.aborted ? "aborted" : "error";
10442
10597
  output.errorMessage = e instanceof Error ? e.message : String(e);
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-provider-qoder",
3
- "version": "0.6.2",
3
+ "version": "0.6.5",
4
4
  "description": "Pi extension for Qoder AI — with OAuth authentication, COSY signatures and WAF bypass",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@herbertgao/pi-extensions",
3
- "version": "2026.10.12",
3
+ "version": "2026.10.13",
4
4
  "description": "Aggregate installer for HerbertGao-maintained Pi extensions.",
5
5
  "keywords": [
6
6
  "extensions",
@@ -40,7 +40,7 @@
40
40
  "@dietrichgebert/ponytail": "5.3.2",
41
41
  "@herbertgao/pi-agency": "0.1.2",
42
42
  "@herbertgao/pi-bark": "0.2.1",
43
- "@herbertgao/pi-cc-extensions": "1.0.8-local.1",
43
+ "@herbertgao/pi-cc-extensions": "1.0.9-local.2",
44
44
  "@herbertgao/pi-subagents": "0.22.0-local.2",
45
45
  "@herbertgao/sol-pi": "0.4.2",
46
46
  "@juicesharp/rpiv-ask-user-question": "2.13.9",
@@ -74,7 +74,7 @@
74
74
  "pi-antigravity": "0.11.0",
75
75
  "pi-lens": "4.4.4",
76
76
  "pi-next-cue": "1.0.7",
77
- "pi-provider-qoder": "0.6.2",
77
+ "pi-provider-qoder": "0.6.5",
78
78
  "pi-typesafe": "0.10.0",
79
79
  "pi-web-access": "0.44.0",
80
80
  "pidusage": "^4.0.1",