@miphamai/cli 0.85.47 → 0.85.49
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 +1 -1
- package/package.json +1 -1
- package/skills/standard/safe-coding.SKILL.md +10 -1
- package/src/core/crsi-modify.ts +4 -0
- package/src/core/crsi-producer.ts +85 -7
- package/src/core/crsi-sandbox.ts +30 -1
- package/src/core/engine.ts +44 -11
- package/src/core/hooks-executor.ts +25 -2
- package/src/core/improvement-track.ts +349 -0
- package/src/core/instructions.ts +12 -3
- package/src/core/task-performance.ts +70 -3
- package/src/i18n-core/locales/en-US.json +3 -0
- package/src/i18n-core/locales/zh-CN.json +3 -0
- package/src/plugin/plugin-manager.ts +12 -3
- package/src/providers/anthropic.ts +5 -0
- package/src/providers/fetch-utils.ts +16 -1
- package/src/providers/openai-compat.ts +4 -0
- package/src/shared/package-info.ts +2 -2
- package/src/skills/bundled-skills.ts +1 -1
- package/src/skills/sanitizer.ts +16 -2
- package/src/ui/chat.tsx +9 -1
- package/src/ui/commands.ts +77 -2
- package/src/ui/input.tsx +23 -3
- package/src/ui/picker.tsx +15 -3
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Mipham Code v0.85.
|
|
1
|
+
# Mipham Code v0.85.49
|
|
2
2
|
|
|
3
3
|
**Multi-model open-core intelligent coding terminal** — 12 AI providers, 141 commands, 31 tools, 28 skills + marketplace, self-update. AI-assisted code generation, security auditing, MCP protocol, and extensible skills — in a single CLI.
|
|
4
4
|
|
package/package.json
CHANGED
|
@@ -1,9 +1,18 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: safe-coding
|
|
3
3
|
description: Safe coding rules for code generation — validate external/user input before use and throw RangeError on invalid input
|
|
4
|
-
version: 1.
|
|
4
|
+
version: 1.1.0
|
|
5
5
|
---
|
|
6
6
|
|
|
7
7
|
# Safe Coding
|
|
8
8
|
|
|
9
9
|
处理外部/用户输入前必须校验:`null`、`undefined`、空字符串、格式非法时,抛出 `RangeError`,消息为 `'invalid input'`。
|
|
10
|
+
|
|
11
|
+
## 校验规则
|
|
12
|
+
|
|
13
|
+
1. **严格整串匹配**:用锚定正则(`/^...$/`)校验字符串格式;不要依赖 `Number()` / `parseInt()` / `parseFloat()` 的宽松解析 —— 它们会接受 `'1e3'`、`'4.2abc'` 这类部分匹配。
|
|
14
|
+
2. **先 trim 再校验**:允许首尾空白时,先 `String(input).trim()`;trim 后为空一律视为非法。
|
|
15
|
+
3. **端值检查**:数值结果必须过 `Number.isFinite()`;`NaN`、`±Infinity` 不是合法结果。
|
|
16
|
+
4. **边界参数**:区间类函数(如 `clamp`)在 `min > max` 时必须抛 `RangeError`,不得静默交换。
|
|
17
|
+
5. **按签名返回**:签名声明 `| null` 的函数用 `null` 表示非法输入;声明抛 `RangeError` 的用异常 —— 两者不混用。
|
|
18
|
+
6. **导出形状**:导出名与签名必须与题目要求逐字一致(`export function name(...)`)。
|
package/src/core/crsi-modify.ts
CHANGED
|
@@ -165,6 +165,10 @@ export async function runCrsiModification(
|
|
|
165
165
|
if (!testResult.passed) {
|
|
166
166
|
sandbox.rollback()
|
|
167
167
|
applied.phase = 'failed'
|
|
168
|
+
// 把沙箱的读数带出去:没有这一行,调用方只显示「❌ 修改未通过(phase: failed)。」
|
|
169
|
+
// 而没有任何原因 —— 真实运行(2026-11-25)里那条原因正是
|
|
170
|
+
// `sh: vitest: command not found`,被吞掉后修复无从下手。
|
|
171
|
+
applied.error = `Sandbox tests failed (${testResult.failedTests} failed):\n${testResult.output.slice(-1500)}`
|
|
168
172
|
return applied
|
|
169
173
|
}
|
|
170
174
|
|
|
@@ -741,19 +741,32 @@ export async function selectTargetSkill(
|
|
|
741
741
|
return extractFilePath(response, skillFiles)
|
|
742
742
|
}
|
|
743
743
|
|
|
744
|
-
const PROSE_GENERATE_PROMPT_VERSION = '1.
|
|
744
|
+
const PROSE_GENERATE_PROMPT_VERSION = '1.4.0'
|
|
745
745
|
|
|
746
746
|
function buildGenerateProsePrompt(
|
|
747
747
|
signal: CrsiSignal,
|
|
748
748
|
filePath: string,
|
|
749
749
|
originalContent: string,
|
|
750
750
|
lessonsBlock: string,
|
|
751
|
+
target: ProseTargetContext,
|
|
751
752
|
): string {
|
|
753
|
+
const { simBlock, taskIds } = target
|
|
752
754
|
return [
|
|
753
755
|
`你是 CRSI producer(producer-prose-generate v${PROSE_GENERATE_PROMPT_VERSION})。基于失败信号,改进目标 skill 的内容。`,
|
|
754
756
|
// 常驻教训**内联**(不是指针):算子是无工具的 `llm.chat` 单条消息,给它指针等于零。
|
|
755
757
|
// 缺席(空串)时不占行 —— 无教训的提示词与从前**逐字相同**(纯增量)。
|
|
756
758
|
...(lessonsBlock ? ['', lessonsBlock] : []),
|
|
759
|
+
// SIM 尝试史同样内联。两个通道**刻意分开**:教训是给策略的(根因),SIM 是给优化器的
|
|
760
|
+
// (实测结果 + 预测命中)。合进一个文件会让「诊断」与「证据」再次分家。
|
|
761
|
+
...(simBlock ? ['', simBlock] : []),
|
|
762
|
+
// P4:可预测的题清单。该 skill 没有可测任务时不占行 —— 提示词与加这条之前逐字相同。
|
|
763
|
+
...(taskIds.length > 0
|
|
764
|
+
? [
|
|
765
|
+
'',
|
|
766
|
+
'可预测会被修好的题 id(expectedFixes 只能取这些,不得编造):',
|
|
767
|
+
...taskIds.map((id) => `- ${id}`),
|
|
768
|
+
]
|
|
769
|
+
: []),
|
|
757
770
|
'',
|
|
758
771
|
'失败信号:',
|
|
759
772
|
`- category: ${signal.category}`,
|
|
@@ -768,9 +781,14 @@ function buildGenerateProsePrompt(
|
|
|
768
781
|
'',
|
|
769
782
|
'返回格式(严格遵守,两段):',
|
|
770
783
|
'第 1 行:一行 JSON,写下你对这次改动的**预期效果**与**风险**:',
|
|
771
|
-
|
|
784
|
+
taskIds.length > 0
|
|
785
|
+
? '{"expectedDelta": <number 或 null>, "risk": "<字符串>", "expectedFixes": ["<题 id>"]}'
|
|
786
|
+
: '{"expectedDelta": <number 或 null>, "risk": "<字符串>"}',
|
|
772
787
|
'- expectedDelta 是预期该 skill 的任务表现提升**点数**(可正可负;无法预测写 null)。',
|
|
773
788
|
'- risk 是这次改动可能在哪方面变差(一句话)。',
|
|
789
|
+
...(taskIds.length > 0
|
|
790
|
+
? ['- expectedFixes 是你预测这次改动会**修好**的题 id 列表(从上面清单里选;没把握写 [])。']
|
|
791
|
+
: []),
|
|
774
792
|
'第 2 行起:改进后的完整 markdown(保持 YAML frontmatter 的 name/description 字段,正文针对失败信号做针对性改进)。不要用代码围栏包住。',
|
|
775
793
|
].join('\n')
|
|
776
794
|
}
|
|
@@ -780,13 +798,34 @@ function stripMarkdownFence(text: string): string {
|
|
|
780
798
|
return match ? match[1]! : text
|
|
781
799
|
}
|
|
782
800
|
|
|
783
|
-
/** prose 提议的解析产物:正文 + 可选的事前预登记(ε
|
|
801
|
+
/** prose 提议的解析产物:正文 + 可选的事前预登记(ε / 风险 / 任务级预测)。 */
|
|
802
|
+
/**
|
|
803
|
+
* 生成算子的**目标上下文** —— 它在选完目标 skill 之后才存在:目标决定 SIM 的 skill 轴,
|
|
804
|
+
* 也决定「可以预测哪些题」。延迟取的理由见 {@link produceProseProposal} 的同名参数。
|
|
805
|
+
*/
|
|
806
|
+
export interface ProseTargetContext {
|
|
807
|
+
/** SIM 块(台账读侧)。空串 = 无历史。 */
|
|
808
|
+
simBlock: string
|
|
809
|
+
/** 目标 skill 可测的题 id(供任务级预测)。空数组 = 该 skill 没有可测任务。 */
|
|
810
|
+
taskIds: string[]
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
export type ProseTargetContextProvider = (
|
|
814
|
+
filePath: string,
|
|
815
|
+
originalContent: string,
|
|
816
|
+
) => ProseTargetContext
|
|
817
|
+
|
|
784
818
|
export interface ProsePrediction {
|
|
785
819
|
body: string
|
|
786
820
|
/** ε:事前写下的预期提升点数。缺席 = 模型没预测(含显式写 null)。 */
|
|
787
821
|
expectedEffect?: number
|
|
788
822
|
/** R:风险声明。缺席 = 未声明。 */
|
|
789
823
|
risk?: string
|
|
824
|
+
/**
|
|
825
|
+
* P4:事前预测会被修好的题 id。缺席 = 没预测;空数组 = 预测「一题都不会修好」。
|
|
826
|
+
* 已按目标 skill 的已知 id **fail-closed 过滤**(编造的 id 进不来)。
|
|
827
|
+
*/
|
|
828
|
+
expectedFixes?: string[]
|
|
790
829
|
}
|
|
791
830
|
|
|
792
831
|
/**
|
|
@@ -860,11 +899,16 @@ export function parseProsePrediction(raw: string): ProsePrediction {
|
|
|
860
899
|
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
|
861
900
|
return { body: stripped }
|
|
862
901
|
}
|
|
863
|
-
const rec = parsed as { expectedDelta?: unknown; risk?: unknown }
|
|
902
|
+
const rec = parsed as { expectedDelta?: unknown; risk?: unknown; expectedFixes?: unknown }
|
|
864
903
|
if (!('expectedDelta' in rec)) return { body: stripped } // 不带 ε 的 JSON 不吃
|
|
865
904
|
|
|
866
905
|
const expectedEffect = typeof rec.expectedDelta === 'number' ? rec.expectedDelta : undefined
|
|
867
906
|
const risk = typeof rec.risk === 'string' ? rec.risk : undefined
|
|
907
|
+
// P4:只收字符串项。**不在这里校验 id 是否存在** —— 那是 generateProseContent 的事,
|
|
908
|
+
// 因为它才知道目标 skill 的题清单(解析器不该依赖调用方数据)。
|
|
909
|
+
const expectedFixes = Array.isArray(rec.expectedFixes)
|
|
910
|
+
? rec.expectedFixes.filter((x): x is string => typeof x === 'string')
|
|
911
|
+
: undefined
|
|
868
912
|
// 剥掉 JSON 行本身 + 紧随其后的空行
|
|
869
913
|
const body = lines
|
|
870
914
|
.slice(firstIdx + 1)
|
|
@@ -875,6 +919,7 @@ export function parseProsePrediction(raw: string): ProsePrediction {
|
|
|
875
919
|
body,
|
|
876
920
|
...(expectedEffect !== undefined ? { expectedEffect } : {}),
|
|
877
921
|
...(risk !== undefined ? { risk } : {}),
|
|
922
|
+
...(expectedFixes !== undefined ? { expectedFixes } : {}),
|
|
878
923
|
}
|
|
879
924
|
}
|
|
880
925
|
|
|
@@ -884,11 +929,27 @@ export async function generateProseContent(
|
|
|
884
929
|
filePath: string,
|
|
885
930
|
originalContent: string,
|
|
886
931
|
lessonsBlock: string,
|
|
932
|
+
/**
|
|
933
|
+
* 目标上下文(SIM 块 + 可预测的题清单)。**故意必填**:漏传会让「优化器读得到实测
|
|
934
|
+
* 结果」这件事静默失效 —— 与本函数常驻教训块同一条纪律。
|
|
935
|
+
*/
|
|
936
|
+
target: ProseTargetContext,
|
|
887
937
|
): Promise<ProsePrediction | null> {
|
|
888
|
-
const prompt = buildGenerateProsePrompt(signal, filePath, originalContent, lessonsBlock)
|
|
938
|
+
const prompt = buildGenerateProsePrompt(signal, filePath, originalContent, lessonsBlock, target)
|
|
889
939
|
const response = await collectLlmText(llm, prompt)
|
|
890
940
|
if (!response) return null
|
|
891
|
-
|
|
941
|
+
const parsed = parseProsePrediction(response)
|
|
942
|
+
// 没有题清单 ⇒ 无从判定,整键剥掉(模型即便猜了 id 也不进记录)。
|
|
943
|
+
if (target.taskIds.length === 0) {
|
|
944
|
+
const answer: ProsePrediction = { body: parsed.body }
|
|
945
|
+
if (parsed.expectedEffect !== undefined) answer.expectedEffect = parsed.expectedEffect
|
|
946
|
+
if (parsed.risk !== undefined) answer.risk = parsed.risk
|
|
947
|
+
return answer
|
|
948
|
+
}
|
|
949
|
+
if (parsed.expectedFixes === undefined) return parsed
|
|
950
|
+
// fail-closed:只认目标 skill 真的有的题 id,编造的丢弃。
|
|
951
|
+
const allowed = new Set(target.taskIds)
|
|
952
|
+
return { ...parsed, expectedFixes: parsed.expectedFixes.filter((id) => allowed.has(id)) }
|
|
892
953
|
}
|
|
893
954
|
|
|
894
955
|
export interface ProseProposalResult {
|
|
@@ -900,6 +961,8 @@ export interface ProseProposalResult {
|
|
|
900
961
|
expectedEffect?: number
|
|
901
962
|
/** R:风险声明。 */
|
|
902
963
|
risk?: string
|
|
964
|
+
/** P4:事前预测会被修好的题 id(已按目标 skill 的题清单过滤)。 */
|
|
965
|
+
expectedFixes?: string[]
|
|
903
966
|
}
|
|
904
967
|
|
|
905
968
|
export async function produceProseProposal(
|
|
@@ -913,6 +976,13 @@ export async function produceProseProposal(
|
|
|
913
976
|
* 必填把「忘了」从静默行为变更变成编译错误。
|
|
914
977
|
*/
|
|
915
978
|
lessonsBlock: string,
|
|
979
|
+
/**
|
|
980
|
+
* 目标上下文的**延迟提供者**。为什么是函数而不是值:规则 8 的 skill 轴与 P4 的可预测
|
|
981
|
+
* 题清单都要拿目标 skill 当基准,而目标在阶段 1(`selectTargetSkill`)之后才存在 ——
|
|
982
|
+
* 在调用方提前取,就等于把一份「还不知道自己在给谁看」的上下文固化进 API。
|
|
983
|
+
* **故意必填**,同 {@link generateProseContent}:漏传是编译错,不是静默降级。
|
|
984
|
+
*/
|
|
985
|
+
targetOf: ProseTargetContextProvider,
|
|
916
986
|
): Promise<ProseProposalResult | null> {
|
|
917
987
|
const filePath = await selectTargetSkill(signal, llm, skillFiles)
|
|
918
988
|
if (!filePath) return null
|
|
@@ -924,7 +994,14 @@ export async function produceProseProposal(
|
|
|
924
994
|
return null
|
|
925
995
|
}
|
|
926
996
|
|
|
927
|
-
const generated = await generateProseContent(
|
|
997
|
+
const generated = await generateProseContent(
|
|
998
|
+
signal,
|
|
999
|
+
llm,
|
|
1000
|
+
filePath,
|
|
1001
|
+
originalContent,
|
|
1002
|
+
lessonsBlock,
|
|
1003
|
+
targetOf(filePath, originalContent),
|
|
1004
|
+
)
|
|
928
1005
|
if (!generated || !generated.body) return null
|
|
929
1006
|
|
|
930
1007
|
return {
|
|
@@ -934,6 +1011,7 @@ export async function produceProseProposal(
|
|
|
934
1011
|
description: signal.title,
|
|
935
1012
|
...(generated.expectedEffect !== undefined ? { expectedEffect: generated.expectedEffect } : {}),
|
|
936
1013
|
...(generated.risk !== undefined ? { risk: generated.risk } : {}),
|
|
1014
|
+
...(generated.expectedFixes !== undefined ? { expectedFixes: generated.expectedFixes } : {}),
|
|
937
1015
|
}
|
|
938
1016
|
}
|
|
939
1017
|
|
package/src/core/crsi-sandbox.ts
CHANGED
|
@@ -523,6 +523,30 @@ export class CrsiSandbox {
|
|
|
523
523
|
const result: CrsiTestResult = { passed: false, totalTests: 0, failedTests: 0, output: '' }
|
|
524
524
|
|
|
525
525
|
try {
|
|
526
|
+
// 依赖供应:worktree 是 `git worktree add … HEAD` 的干净检出,**不含
|
|
527
|
+
// `node_modules`**。不先装,`pnpm test` 会以 `sh: vitest: command not found`
|
|
528
|
+
// 秒失败(2026-11-25 实测:整个 /crsi modify 停在这一步,1 秒即 phase failed)。
|
|
529
|
+
// 离线 + frozen + ignore-scripts:闸里不联网、不改锁文件、不跑 postinstall;
|
|
530
|
+
// 预热过的 pnpm store 下约 3.5s(实测)。装不上 ⇒ 进入 catch,**不跑套件** ——
|
|
531
|
+
// 否则一条凑巧全绿的输出会把「仪器没启动」读成「改动没问题」。
|
|
532
|
+
runIn(this.worktreePath, 'pnpm install --offline --frozen-lockfile --ignore-scripts', {
|
|
533
|
+
timeoutMs: TEST_TIMEOUT_MS,
|
|
534
|
+
})
|
|
535
|
+
|
|
536
|
+
// 派生状态:`src/skills/bundled-skills.ts` 是 skill 文件在磁盘上的快照,freshness
|
|
537
|
+
// 测试逐字比对。只改 skill 正文的 proposal 因此**必被整批打回**(2026-11-25 实测:
|
|
538
|
+
// `1 failed | 5305 passed`,唯一失败就是 snapshot freshness)——而只有 skill 改动
|
|
539
|
+
// 能量化任务表现,测量路径就死在闸前。闸里像构建步骤一样把派生状态对齐;
|
|
540
|
+
// `merge()` 用的是 `git add -A`,重生成结果会一起进 diff,由人类审阅。
|
|
541
|
+
const touchesSkill = this.sessionReport.modifications.some((m) =>
|
|
542
|
+
posix.normalize(m.modification.filePath).startsWith('apps/cli/skills/'),
|
|
543
|
+
)
|
|
544
|
+
if (touchesSkill) {
|
|
545
|
+
runIn(this.worktreePath, 'cd apps/cli && bun run scripts/generate-bundled-skills.ts', {
|
|
546
|
+
timeoutMs: TEST_TIMEOUT_MS,
|
|
547
|
+
})
|
|
548
|
+
}
|
|
549
|
+
|
|
526
550
|
const output = runIn(this.worktreePath, 'pnpm test 2>&1', { timeoutMs: TEST_TIMEOUT_MS })
|
|
527
551
|
|
|
528
552
|
result.output = output.slice(-5000) // Keep last 5000 chars
|
|
@@ -556,7 +580,12 @@ export class CrsiSandbox {
|
|
|
556
580
|
}
|
|
557
581
|
}
|
|
558
582
|
} catch (err) {
|
|
559
|
-
|
|
583
|
+
// 诊断优先取子进程自己的 stderr/stdout:`String(err)` 只有
|
|
584
|
+
// "Command failed: …" 一行,真正的原因(`ERR_PNPM_…` / vitest 的断言输出)
|
|
585
|
+
// 全在错误对象的这两个缓冲区里,被吞掉后调用方只能看到一条空失败。
|
|
586
|
+
const e = err as { stderr?: Buffer | string; stdout?: Buffer | string }
|
|
587
|
+
const detail = [e.stderr?.toString(), e.stdout?.toString()].filter(Boolean).join('\n')
|
|
588
|
+
result.output = (detail || String(err)).slice(0, 5000)
|
|
560
589
|
result.failedTests = 1
|
|
561
590
|
|
|
562
591
|
// Mark all applied modifications as failed
|
package/src/core/engine.ts
CHANGED
|
@@ -1663,7 +1663,9 @@ export class QueryEngine {
|
|
|
1663
1663
|
// command failed (CC 2.1.110-027). A failed result is projected as
|
|
1664
1664
|
// `error || content`, so the warning goes where it is actually read.
|
|
1665
1665
|
if (hookWarnings.length > 0) {
|
|
1666
|
-
|
|
1666
|
+
// Same bound as compaction context: a hook (or a rule) can print a whole
|
|
1667
|
+
// file, and this text is prepended to every matching tool result.
|
|
1668
|
+
const warning = this.capHookContext(hookWarnings.join('\n'))
|
|
1667
1669
|
if (result.success) {
|
|
1668
1670
|
result.content = warning + '\n' + (result.content || '')
|
|
1669
1671
|
} else if (result.error) {
|
|
@@ -1686,9 +1688,8 @@ export class QueryEngine {
|
|
|
1686
1688
|
result.content = postResult.updatedOutput
|
|
1687
1689
|
}
|
|
1688
1690
|
if (postResult.additionalContext) {
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
: postResult.additionalContext
|
|
1691
|
+
const context = this.capHookContext(postResult.additionalContext)
|
|
1692
|
+
result.content = result.content ? result.content + '\n' + context : context
|
|
1692
1693
|
}
|
|
1693
1694
|
}
|
|
1694
1695
|
|
|
@@ -2034,11 +2035,11 @@ export class QueryEngine {
|
|
|
2034
2035
|
type: 'warning',
|
|
2035
2036
|
content: reasoningOnly
|
|
2036
2037
|
? `${activeId} returned only reasoning and no answer — retrying once`
|
|
2037
|
-
: `${activeId} failed (${failure}) — retrying once`,
|
|
2038
|
+
: `${activeId} failed (${explainTransportFailure(failure ?? 'Unknown error')}) — retrying once`,
|
|
2038
2039
|
restart: true,
|
|
2039
2040
|
}
|
|
2040
2041
|
}
|
|
2041
|
-
const detail = failure ?? 'Unknown error'
|
|
2042
|
+
const detail = explainTransportFailure(failure ?? 'Unknown error')
|
|
2042
2043
|
|
|
2043
2044
|
// Deterministic failure: re-sending it to another provider cannot change the
|
|
2044
2045
|
// answer, so surface it once rather than burning the fallback on it.
|
|
@@ -2472,8 +2473,9 @@ export class QueryEngine {
|
|
|
2472
2473
|
return
|
|
2473
2474
|
}
|
|
2474
2475
|
|
|
2475
|
-
// Feed the block reason back to the AI and continue
|
|
2476
|
-
|
|
2476
|
+
// Feed the block reason back to the AI and continue. A hook that blocks with
|
|
2477
|
+
// a whole log attached must not overflow the context it just refused to end.
|
|
2478
|
+
this.context.injectContext(block.source, this.capHookContext(block.text))
|
|
2477
2479
|
yield* this.continueWithTools(signal, roundsLeft)
|
|
2478
2480
|
}
|
|
2479
2481
|
|
|
@@ -2572,16 +2574,47 @@ function toolResultText(content: ContentBlock[]): string {
|
|
|
2572
2574
|
* Kept narrow on purpose: a false positive costs one wasted compaction (the turn
|
|
2573
2575
|
* retries either way), while a false negative ends the turn with a raw upstream
|
|
2574
2576
|
* error the user cannot act on. All of these phrasings are ones the providers
|
|
2575
|
-
* actually send — the
|
|
2576
|
-
*
|
|
2577
|
+
* actually send — the 413 family is what a proxy or gateway in front of the
|
|
2578
|
+
* provider returns when the *request* is over its limit (retrying it verbatim
|
|
2579
|
+
* fails identically; compacting is what changes the size), and the last is the
|
|
2580
|
+
* one a 1M-context model returns while the account has not enabled the charge.
|
|
2577
2581
|
*/
|
|
2578
2582
|
export function isContextOverflowError(message: string | null | undefined): boolean {
|
|
2579
2583
|
if (!message) return false
|
|
2580
|
-
return /context[_ ]length|context window|prompt is too long|input is too long|too many tokens|maximum context length|exceeds? the (?:model'?s )?(?:maximum )?context|usage credits required for 1m context/i.test(
|
|
2584
|
+
return /context[_ ]length|context window|prompt is too long|input is too long|too many tokens|maximum context length|exceeds? the (?:model'?s )?(?:maximum )?context|usage credits required for 1m context|\b413\b|payload too large|request entity too large|request (?:body |size )?too large/i.test(
|
|
2581
2585
|
message,
|
|
2582
2586
|
)
|
|
2583
2587
|
}
|
|
2584
2588
|
|
|
2589
|
+
/**
|
|
2590
|
+
* Turn a transport-level failure into words the user can act on.
|
|
2591
|
+
*
|
|
2592
|
+
* A proxy or gateway that cuts or rewrites a compressed response surfaces as
|
|
2593
|
+
* `ZlibError: incorrect header check` or a bare JSON parse failure. Those are
|
|
2594
|
+
* diagnoses for us, not for the person reading the turn — but dropping them
|
|
2595
|
+
* entirely would take away the only clue, so the plain sentence comes first and
|
|
2596
|
+
* the original follows in parentheses.
|
|
2597
|
+
*/
|
|
2598
|
+
export function explainTransportFailure(message: string): string {
|
|
2599
|
+
if (
|
|
2600
|
+
/zlib|decompress|incorrect header check|invalid (?:stored )?block type|unexpected end of (?:file|stream)/i.test(
|
|
2601
|
+
message,
|
|
2602
|
+
)
|
|
2603
|
+
) {
|
|
2604
|
+
return (
|
|
2605
|
+
'The reply was cut or damaged in transit — a proxy or gateway is the usual cause. ' +
|
|
2606
|
+
`Try again; if it keeps happening, check the proxy. (${message})`
|
|
2607
|
+
)
|
|
2608
|
+
}
|
|
2609
|
+
if (/JSON parse error|unexpected token|unexpected end of JSON input/i.test(message)) {
|
|
2610
|
+
return (
|
|
2611
|
+
"The provider's reply could not be read (malformed JSON — often a proxy or gateway " +
|
|
2612
|
+
`rewriting the response). (${message})`
|
|
2613
|
+
)
|
|
2614
|
+
}
|
|
2615
|
+
return message
|
|
2616
|
+
}
|
|
2617
|
+
|
|
2585
2618
|
function isAbortError(err: unknown): boolean {
|
|
2586
2619
|
if (err instanceof Error && err.name === 'AbortError') return true
|
|
2587
2620
|
if (
|
|
@@ -275,6 +275,29 @@ interface HookProcessResult {
|
|
|
275
275
|
error?: { code?: string; message?: string }
|
|
276
276
|
}
|
|
277
277
|
|
|
278
|
+
/**
|
|
279
|
+
* How much of each hook stream is buffered before the rest is dropped.
|
|
280
|
+
*
|
|
281
|
+
* A hook printing without end used to grow this process's heap for the whole
|
|
282
|
+
* timeout window (60s by default) — the event loop stayed live, but a `yes`-style
|
|
283
|
+
* hook still turned into gigabytes. Keep the first 1 MiB of each stream, which is
|
|
284
|
+
* far more than any structured hook payload, and leave a marker so the truncation
|
|
285
|
+
* is visible rather than silently changing the answer.
|
|
286
|
+
*/
|
|
287
|
+
const MAX_HOOK_STREAM_CHARS = 1_000_000
|
|
288
|
+
|
|
289
|
+
/** Append one chunk to a capped stream buffer. Pure so the bound is testable. */
|
|
290
|
+
export function appendHookStreamChunk(
|
|
291
|
+
previous: string,
|
|
292
|
+
chunk: string,
|
|
293
|
+
cap: number = MAX_HOOK_STREAM_CHARS,
|
|
294
|
+
): string {
|
|
295
|
+
if (previous.length > cap) return previous
|
|
296
|
+
const next = previous + chunk
|
|
297
|
+
if (next.length <= cap) return next
|
|
298
|
+
return `${next.slice(0, cap)}\n[hook output truncated: exceeded ${cap.toLocaleString('en-US')} characters]\n`
|
|
299
|
+
}
|
|
300
|
+
|
|
278
301
|
/**
|
|
279
302
|
* Run a hook command to completion, bounding **both** halves of the wait.
|
|
280
303
|
*
|
|
@@ -368,10 +391,10 @@ async function runHookCommand(
|
|
|
368
391
|
}
|
|
369
392
|
|
|
370
393
|
child.stdout.on('data', (chunk: Buffer) => {
|
|
371
|
-
stdout
|
|
394
|
+
stdout = appendHookStreamChunk(stdout, chunk.toString())
|
|
372
395
|
})
|
|
373
396
|
child.stderr.on('data', (chunk: Buffer) => {
|
|
374
|
-
stderr
|
|
397
|
+
stderr = appendHookStreamChunk(stderr, chunk.toString())
|
|
375
398
|
})
|
|
376
399
|
|
|
377
400
|
child.on('error', (err: NodeJS.ErrnoException) => {
|