@miphamai/cli 0.85.42 → 0.85.44

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
@@ -1,6 +1,6 @@
1
- # Mipham Code v0.85.42
1
+ # Mipham Code v0.85.44
2
2
 
3
- **Multi-model open-core intelligent coding terminal** — 12 AI providers, 139 commands, 31 tools, 28 skills + marketplace, self-update. AI-assisted code generation, security auditing, MCP protocol, and extensible skills — in a single CLI.
3
+ **Multi-model open-core intelligent coding terminal** — 12 AI providers, 140 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
 
5
5
  Built by [One Mipham Corporation](https://onemipham.com) (北京华安麦逄科技有限公司) | Brand: MiphamAI
6
6
 
@@ -16,7 +16,7 @@ Requirements: **Bun 1.2+** (recommended) or **Node.js 22+**
16
16
  ## Features
17
17
 
18
18
  - **12 AI Providers** — Anthropic Claude · OpenAI GPT · DeepSeek · Kimi (Moonshot) · Google Gemini · Doubao 豆包 · Tencent Hunyuan 混元 · Qwen 通义千问 · MiniMax(国内 / 国际)· Ollama(本地)· MiphamAI
19
- - **139 Slash Commands** — Interactive command picker (↑↓ Enter Esc), intuitive command interface, zero re-learning
19
+ - **140 Slash Commands** — Interactive command picker (↑↓ Enter Esc), intuitive command interface, zero re-learning
20
20
  - **31 Built-in Tools** — File ops, shell execution, agent dispatch, MCP integration, web search
21
21
  - **28 Skills + Marketplace** — 22 standard + 6 Mipham-exclusive skills. `/browse-skills` `/install-skill` community marketplace
22
22
  - **Self-Update** — `mipham update` / `/upgrade` — one command to check, backup config, upgrade, restore. API keys preserved
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miphamai/cli",
3
- "version": "0.85.42",
3
+ "version": "0.85.44",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -10,6 +10,7 @@ import { AgentExperience } from './agent-experience'
10
10
  import { ExperienceRuleExtractor } from './experience-rules.js'
11
11
  import { miphamHome } from '../core/paths.ts'
12
12
  import { MIPHAM_DIR } from '../shared/constants.ts'
13
+ import { sanitizeSkillBody } from '../skills/sanitizer'
13
14
 
14
15
  export interface AgentContextResult {
15
16
  context: ContextManager
@@ -104,11 +105,55 @@ function loadAgentMemory(
104
105
  * Agent memory: if agentDef.memory is set, loads memory files from the
105
106
  * appropriate scope and injects them into the system prompt.
106
107
  */
108
+ /** The slice of `SkillsLoader` this module needs (kept structural so the agent
109
+ * layer does not import the skills loader just for a type). */
110
+ export interface DeclaredSkillLookup {
111
+ get(name: string): { name: string; description: string; body?: string } | undefined
112
+ }
113
+
114
+ /**
115
+ * Render the skills an agent declared in its frontmatter into its system prompt.
116
+ *
117
+ * `skills:` was parsed into `AgentDefinition` but read by nobody, so an agent
118
+ * that declared skills ran without their instructions — the field was
119
+ * advertised and never applied. Unknown names are reported once (to stderr,
120
+ * like the loader's other warnings) rather than silently dropped: a typo and a
121
+ * missing file are the same thing to the agent, and both mean the same thing
122
+ * to the user.
123
+ */
124
+ function loadDeclaredSkills(
125
+ agentName: string,
126
+ names: string[],
127
+ lookup: DeclaredSkillLookup | undefined,
128
+ ): string {
129
+ if (!lookup) {
130
+ process.stderr.write(
131
+ `⚠️ Agent "${agentName}": declares skills (${names.join(', ')}) but no skills loader is available — skipped.\n`,
132
+ )
133
+ return ''
134
+ }
135
+ const blocks: string[] = []
136
+ for (const name of names) {
137
+ const skill = lookup.get(name)
138
+ if (!skill) {
139
+ process.stderr.write(
140
+ `⚠️ Agent "${agentName}": declared skill "${name}" not found — skipped.\n`,
141
+ )
142
+ continue
143
+ }
144
+ const body = skill.body ? sanitizeSkillBody(skill.body).text : ''
145
+ blocks.push([`## ${skill.name}`, skill.description, body].filter(Boolean).join('\n'))
146
+ }
147
+ if (blocks.length === 0) return ''
148
+ return ['[Agent Skills — declared in frontmatter]', ...blocks].join('\n\n')
149
+ }
150
+
107
151
  export function createAgentContext(
108
152
  agentDef: AgentDefinition,
109
153
  toolRegistry: Map<string, ToolDefinition>,
110
154
  contextWindow?: number,
111
155
  crsiConfig?: Partial<CrsiConfig>,
156
+ skills?: DeclaredSkillLookup,
112
157
  ): AgentContextResult {
113
158
  // Create isolated context, sized to the resolved model's window when known.
114
159
  // Passing contextWindow (not just maxTokens) enables adaptive thresholds.
@@ -127,6 +172,10 @@ export function createAgentContext(
127
172
  systemPrompt = `${systemPrompt}\n\n---\n\n${memory}`
128
173
  }
129
174
  }
175
+ if (agentDef.skills?.length) {
176
+ const declared = loadDeclaredSkills(agentDef.name, agentDef.skills, skills)
177
+ if (declared) systemPrompt = `${systemPrompt}\n\n---\n\n${declared}`
178
+ }
130
179
 
131
180
  context.setSystemPrompt(systemPrompt)
132
181
 
@@ -170,6 +170,12 @@ export class AgentRegistry {
170
170
  name: builtinType,
171
171
  description: BUILTIN_DESCRIPTIONS[builtinType],
172
172
  systemPrompt: BUILTIN_SYSTEM_PROMPTS[builtinType],
173
+ // `explore` is advertised as a "Read-only search agent". Without an
174
+ // explicit list `selectAgentTools` hands it the whole registry, and an
175
+ // exploration run can Write/Edit — which is how the "unwanted .md
176
+ // investigation files" this builtin exists to avoid get created. The
177
+ // description and the grant must name the same set.
178
+ ...(builtinType === 'explore' ? { tools: 'Read,Grep,Glob' } : {}),
173
179
  model: 'inherit',
174
180
  permissionMode: 'inherit',
175
181
  source: 'builtin',
@@ -416,6 +416,11 @@ export class SubAgent {
416
416
  resolvedDef,
417
417
  this.toolRegistry,
418
418
  compactWindow ?? contextWindow,
419
+ undefined,
420
+ // `skills:` in agent frontmatter is applied here — the loader is already
421
+ // inherited through `options.toolContext` (it is how the Skill tool works
422
+ // one level down), so the declared skills resolve against the same set.
423
+ options.toolContext?.skillsLoader,
419
424
  )
420
425
 
421
426
  // 别再 `context.setSystemPrompt(systemPrompt)`:`createAgentContext` 已经拿**含记忆**的
@@ -924,7 +924,9 @@ Current directory: ${process.cwd()}`,
924
924
  Nothing was registered — this build has no workspace-directory allowlist.
925
925
 
926
926
  How access is actually decided:
927
- • Reads — not limited by directory. What refuses a file is a deny rule
927
+ • Reads — must resolve inside the session directory. Read/Grep/Glob/Edit/
928
+ Write all go through the same workspace check, so a path outside
929
+ it is rejected. Inside it, a deny rule can still refuse a file
928
930
  (\`Read(<path>)\`, which also covers Bash readers like cat/head).
929
931
  • Writes — gated by the permission mode (Shift+Tab cycles:
930
932
  ${renderCycleLine()}).
@@ -466,6 +466,13 @@ function loadMcpJson(cwd: string, warn?: (message: string) => void): McpServerCo
466
466
  */
467
467
  export interface SettingsJson {
468
468
  hooks: SettingsHooks
469
+ /**
470
+ * `disableAllHooks: true` — the Claude Code setting name, honoured for the
471
+ * hooks this file can configure (settings.json's own list). Omitted unless
472
+ * true, so the absent/`false` distinction stays visible. Built-in product
473
+ * hooks are not user-configured and are disabled only by `--safe-mode`.
474
+ */
475
+ disableAllHooks?: true
469
476
  /**
470
477
  * `allow` is the **user-level** file's list; a project-level one is withheld
471
478
  * (`projectAllowSkipped`) because a rule that widens is the approval gate by
@@ -591,6 +598,7 @@ export function loadSettingsJson(
591
598
  let projectModeSkipped = false
592
599
  let projectAllowSkipped = false
593
600
  let projectClassifierSkipped = false
601
+ let disableAllHooks = false
594
602
  // The project file's entries, kept out of the merge so provenance survives it.
595
603
  const projectHooks: SettingsHooks = {}
596
604
 
@@ -636,6 +644,7 @@ export function loadSettingsJson(
636
644
  }
637
645
  const parsed = JSON.parse(raw) as {
638
646
  hooks?: Record<string, unknown>
647
+ disableAllHooks?: unknown
639
648
  permissions?: {
640
649
  allow?: unknown
641
650
  deny?: unknown
@@ -645,6 +654,19 @@ export function loadSettingsJson(
645
654
  }
646
655
  }
647
656
 
657
+ if (parsed.disableAllHooks !== undefined) {
658
+ if (parsed.disableAllHooks === true) {
659
+ // Additive across levels and narrowing in every direction: whichever
660
+ // file said it, fewer shell commands run. A project file therefore may
661
+ // say it too — unlike `allow`, this is not a widening.
662
+ disableAllHooks = true
663
+ } else if (parsed.disableAllHooks !== false) {
664
+ process.stderr.write(
665
+ `⚠ Mipham Code: ignoring disableAllHooks from ${path} — expected true or false.\n`,
666
+ )
667
+ }
668
+ }
669
+
648
670
  if (!readHooks) {
649
671
  // "Was anything actually withheld?" is answered from the same parse that
650
672
  // would have read it, so the skip notice cannot outrun the fact.
@@ -686,8 +708,22 @@ export function loadSettingsJson(
686
708
  }
687
709
  for (const key of ['allow', 'deny'] as const) {
688
710
  const list = parsed.permissions[key]
689
- if (!Array.isArray(list)) continue
711
+ if (list === undefined) continue
712
+ // A hand-written `"deny": "Read(**/.env)"` (the YAML habit) used to be
713
+ // dropped here without a word. For `deny` that is fail-open: the user
714
+ // wrote a rule, believes it is in force, and nothing is. Say it.
715
+ if (!Array.isArray(list)) {
716
+ process.stderr.write(
717
+ `⚠ Mipham Code: ignoring permissions.${key} from ${path} — expected an array of rule strings, got ${typeof list}.\n`,
718
+ )
719
+ continue
720
+ }
690
721
  const strings = list.filter((p): p is string => typeof p === 'string')
722
+ if (strings.length !== list.length) {
723
+ process.stderr.write(
724
+ `⚠ Mipham Code: ignoring ${list.length - strings.length} non-string entry(s) in permissions.${key} from ${path}.\n`,
725
+ )
726
+ }
691
727
  // `deny` narrows, so a repository may ship it. `allow` widens — and the
692
728
  // question "does it widen past what is permitted?" is **not** answered by
693
729
  // the mode ceiling unless someone configured one: `allowRuleDecision`
@@ -756,6 +792,7 @@ export function loadSettingsJson(
756
792
  // "nothing to report" — an empty marker would let a caller tag user hooks as
757
793
  // gated on the strength of a file with nothing in it.
758
794
  const result: SettingsJson = { hooks, permissions }
795
+ if (disableAllHooks) result.disableAllHooks = true
759
796
  if (projectHooksSkipped) result.projectHooksSkipped = true
760
797
  if (projectModeSkipped) result.projectModeSkipped = true
761
798
  if (projectAllowSkipped) result.projectAllowSkipped = true
@@ -762,6 +762,11 @@ export class QueryEngine {
762
762
  // Fire UserPromptSubmit hooks before processing
763
763
  if (this.hookEngine) {
764
764
  const submitResult = await this.hookEngine.executeUserPromptSubmit(userInput, this.sessionId)
765
+ // `systemMessage` is the hook's channel to the operator — show it here
766
+ // rather than folding it into model context.
767
+ if (submitResult.systemMessage) {
768
+ yield { type: 'warning', content: submitResult.systemMessage }
769
+ }
765
770
  if (submitResult.additionalContext) {
766
771
  this.context.addMessage({
767
772
  role: 'user',
@@ -827,6 +832,9 @@ export class QueryEngine {
827
832
  let assistantContent = ''
828
833
  let reasoningContent = ''
829
834
  let thinkingContent = ''
835
+ // 本轮为什么被截断。`'max_tokens'` 可续写,`'connection'`/未知不可 —— 见
836
+ // `continueMaxTokensTurn`。
837
+ let truncationCause: 'max_tokens' | 'connection' | undefined
830
838
  let turnApiInputTokens = 0
831
839
  let turnApiOutputTokens = 0
832
840
  const turnStart = Date.now()
@@ -854,6 +862,7 @@ export class QueryEngine {
854
862
  reasoningContent = ''
855
863
  thinkingContent = ''
856
864
  toolUses.length = 0
865
+ truncationCause = undefined
857
866
  // Usage is part of "everything": a provider reports tokens as the
858
867
  // stream runs, so the attempt that failed had already added its
859
868
  // share before `restart` arrived. Keeping it charges the retried
@@ -899,6 +908,25 @@ export class QueryEngine {
899
908
  turnApiInputTokens += chunk.inputTokens
900
909
  turnApiOutputTokens += chunk.outputTokens || 0
901
910
  }
911
+
912
+ if (chunk.type === 'stop' && chunk.truncated) {
913
+ // Absent cause = the provider cannot tell; treat it as a connection cut.
914
+ truncationCause = chunk.truncationCause ?? 'connection'
915
+ }
916
+ }
917
+
918
+ // Output-limit cut: ask once for the rest, then commit the joined text.
919
+ // Only when nothing else already ended the round — a cut with tool calls
920
+ // pending has a half-formed call, and a hit budget has its own notice.
921
+ if (truncationCause === 'max_tokens' && !budget.hit && !signal?.aborted) {
922
+ if (toolUses.length === 0 && assistantContent) {
923
+ yield { type: 'warning', content: t('errors.turn_continuing') }
924
+ const acc = { text: assistantContent, reasoning: reasoningContent }
925
+ yield* this.continueMaxTokensTurn(messages, systemPrompt, acc, budget, signal)
926
+ assistantContent = acc.text
927
+ } else {
928
+ yield { type: 'warning', content: t('errors.turn_truncated_limit') }
929
+ }
902
930
  }
903
931
 
904
932
  // Commit the assistant turn **once, after the stream** — not on each `stop`
@@ -1241,6 +1269,15 @@ export class QueryEngine {
1241
1269
  signal?: AbortSignal,
1242
1270
  roundsLeft: number = MAX_TOOL_TURNS,
1243
1271
  ): AsyncGenerator<StreamChunk> {
1272
+ // No rounds left: the turn ends here. `Stop` means "the agent finished
1273
+ // responding", and a turn whose tool-round budget ran out finished too. It
1274
+ // used to return silently, so a hook was never told — and a hook asking for
1275
+ // more work gets the budget-spent notice instead of being ignored.
1276
+ if (roundsLeft <= 0) {
1277
+ yield* this.checkStopHook(signal, 0)
1278
+ return
1279
+ }
1280
+
1244
1281
  // Task-level stall guard: a turn that produces no text or tool result for
1245
1282
  // this long is considered stalled and stopped (prevents ~40-min idle spins).
1246
1283
  //
@@ -1290,6 +1327,7 @@ export class QueryEngine {
1290
1327
  let assistantContent = ''
1291
1328
  let reasoningContent = ''
1292
1329
  let thinkingContent = ''
1330
+ let truncationCause: 'max_tokens' | 'connection' | undefined
1293
1331
  const toolUses: Array<{ id: string; name: string; input: Record<string, unknown> }> = []
1294
1332
 
1295
1333
  try {
@@ -1311,6 +1349,7 @@ export class QueryEngine {
1311
1349
  reasoningContent = ''
1312
1350
  thinkingContent = ''
1313
1351
  toolUses.length = 0
1352
+ truncationCause = undefined
1314
1353
  }
1315
1354
  if (chunk.type === 'error') return
1316
1355
  if (chunk.type === 'text' && chunk.content) {
@@ -1334,6 +1373,10 @@ export class QueryEngine {
1334
1373
  input: chunk.toolUse.input,
1335
1374
  })
1336
1375
  }
1376
+
1377
+ if (chunk.type === 'stop' && chunk.truncated) {
1378
+ truncationCause = chunk.truncationCause ?? 'connection'
1379
+ }
1337
1380
  }
1338
1381
  } catch (err) {
1339
1382
  if (isAbortError(err)) {
@@ -1359,6 +1402,18 @@ export class QueryEngine {
1359
1402
  return
1360
1403
  }
1361
1404
 
1405
+ // Output-limit cut — same bounded continuation as the first round.
1406
+ if (truncationCause === 'max_tokens' && !budget.hit && !signal?.aborted) {
1407
+ if (toolUses.length === 0 && assistantContent) {
1408
+ yield { type: 'warning', content: t('errors.turn_continuing') }
1409
+ const acc = { text: assistantContent, reasoning: reasoningContent }
1410
+ yield* this.continueMaxTokensTurn(messages, systemPrompt, acc, budget, signal)
1411
+ assistantContent = acc.text
1412
+ } else {
1413
+ yield { type: 'warning', content: t('errors.turn_truncated_limit') }
1414
+ }
1415
+ }
1416
+
1362
1417
  if (assistantContent || reasoningContent || thinkingContent) {
1363
1418
  const contentBlocks: import('../shared/types').ContentBlock[] = []
1364
1419
  if (thinkingContent) {
@@ -1407,6 +1462,9 @@ export class QueryEngine {
1407
1462
  error: t('errors.max_tool_turns', { max: String(MAX_TOOL_TURNS) }),
1408
1463
  }
1409
1464
  }
1465
+ // The forced summary *is* the final answer for this turn, so Stop fires
1466
+ // here too. With no rounds left, a blocking hook can only be told so.
1467
+ yield* this.checkStopHook(signal, 0)
1410
1468
  return
1411
1469
  }
1412
1470
 
@@ -1675,12 +1733,18 @@ export class QueryEngine {
1675
1733
  }
1676
1734
 
1677
1735
  private getToolDefinitions(): Record<string, unknown>[] {
1678
- return Array.from(this.tools.values()).map((t) => ({
1679
- name: t.name,
1680
- description: t.description,
1681
- parameters: t.parameters,
1682
- input_schema: t.parameters, // Anthropic-style naming
1683
- }))
1736
+ // A tool named by a bare deny rule can never run, so it must not be offered:
1737
+ // the model sees a tool it can call, calls it, and the gate refuses — every
1738
+ // time. Input-scoped rules (`Bash(rm:*)`) are NOT filtered here; they deny
1739
+ // some invocations, and the tool itself is still usable.
1740
+ return Array.from(this.tools.values())
1741
+ .filter((t) => !this.permission.isToolNameDenied(t.name))
1742
+ .map((t) => ({
1743
+ name: t.name,
1744
+ description: t.description,
1745
+ parameters: t.parameters,
1746
+ input_schema: t.parameters, // Anthropic-style naming
1747
+ }))
1684
1748
  }
1685
1749
 
1686
1750
  getContext(): ContextManager {
@@ -1723,7 +1787,11 @@ export class QueryEngine {
1723
1787
  */
1724
1788
  private async *llmChat(req: ChatRequest): AsyncGenerator<StreamChunk> {
1725
1789
  for await (const chunk of (this.llm ?? this.registry).chat(req)) {
1726
- if (chunk.type === 'stop' && chunk.truncated) {
1790
+ if (chunk.type === 'stop' && chunk.truncated && chunk.truncationCause !== 'max_tokens') {
1791
+ // An output-limit cut is handled by the caller: it may continue the turn
1792
+ // (`continueMaxTokensTurn`), and then "check your proxy/VPN" would be
1793
+ // both alarming and wrong. Connection cuts have no recovery — this is
1794
+ // the only place that says so.
1727
1795
  yield { type: 'warning', content: t('errors.turn_truncated') }
1728
1796
  }
1729
1797
  if (chunk.type === 'stop' && chunk.refusal) {
@@ -1737,6 +1805,65 @@ export class QueryEngine {
1737
1805
  }
1738
1806
  }
1739
1807
 
1808
+ /**
1809
+ * 有界续写:一轮因**输出上限**(`max_tokens`)被切断后,追问一次「接着写」。
1810
+ *
1811
+ * 只续一次,且只由调用方在「没有工具调用、没有撞上回合预算、未被中断」时调用。
1812
+ * 连接中断**不**续:那里没有「接着写」可言,重发只会让模型把同一段残句重写一遍。
1813
+ *
1814
+ * 续写的正文并进**同一个** assistant 消息(`acc.text`),而不是再提交一条 ——
1815
+ * 否则历史里会出现两条连续的 assistant 消息,渲染成两个气泡,而用户看到的
1816
+ * 明明是一段话。
1817
+ */
1818
+ private async *continueMaxTokensTurn(
1819
+ messages: import('../shared/types').Message[],
1820
+ systemPrompt: string,
1821
+ acc: { text: string; reasoning: string },
1822
+ budget: TurnBudget,
1823
+ signal?: AbortSignal,
1824
+ ): AsyncGenerator<StreamChunk> {
1825
+ const continuation: import('../shared/types').Message[] = [
1826
+ ...messages,
1827
+ { role: 'assistant', content: acc.text },
1828
+ { role: 'user', content: t('errors.continuation_prompt') },
1829
+ ]
1830
+ let added = ''
1831
+ let cutAgain = false
1832
+ try {
1833
+ for await (const chunk of this.streamUnderTurnBudget(budget, signal, (innerSignal) =>
1834
+ // No tools on a continuation: this request asks the model to *finish the
1835
+ // sentence*, and a tool call produced here would have no execution path
1836
+ // (the round's tool loop has already ended) — it would render as a call
1837
+ // that silently never runs.
1838
+ this.chatWithFallback(continuation, systemPrompt, undefined, innerSignal),
1839
+ )) {
1840
+ yield chunk
1841
+ // A retried continuation re-streams: drop what the failed attempt added.
1842
+ if (chunk.restart) {
1843
+ added = ''
1844
+ continue
1845
+ }
1846
+ if (chunk.type === 'error') return
1847
+ if (chunk.type === 'text' && chunk.content) {
1848
+ added += chunk.content
1849
+ this.context.recordChunk(chunk.content)
1850
+ }
1851
+ if (chunk.type === 'stop' && chunk.truncated && chunk.truncationCause === 'max_tokens') {
1852
+ cutAgain = true
1853
+ }
1854
+ }
1855
+ } catch (err) {
1856
+ acc.text += added
1857
+ if (isAbortError(err)) return
1858
+ yield { type: 'error', error: String(err) }
1859
+ return
1860
+ }
1861
+ acc.text += added
1862
+ // Bounded: a second ceiling hit ends the turn. Say it plainly — the user is
1863
+ // looking at text that stops mid-sentence.
1864
+ if (cutAgain) yield { type: 'warning', content: t('errors.turn_truncated_limit') }
1865
+ }
1866
+
1740
1867
  /**
1741
1868
  * Stream a chat response with graceful provider fallback (v2.1.229 alignment).
1742
1869
  *
@@ -2301,7 +2428,8 @@ export class QueryEngine {
2301
2428
  signal?: AbortSignal,
2302
2429
  roundsLeft: number = MAX_TOOL_TURNS,
2303
2430
  ): AsyncGenerator<StreamChunk> {
2304
- const block = await this.stopBlock()
2431
+ const { block, systemMessage } = await this.stopCheck()
2432
+ if (systemMessage) yield { type: 'warning', content: systemMessage }
2305
2433
  if (!block) return
2306
2434
 
2307
2435
  // A block asks for more work, and more work means another round — which the
@@ -2329,27 +2457,38 @@ export class QueryEngine {
2329
2457
  * 两条来源,同一个后果:用户配置的 Stop 钩子(它先说话,先到先得),以及内置的
2330
2458
  * 数字出处判定。后者不需要钩子引擎 —— 它是产品行为,不是可配置项。
2331
2459
  */
2332
- private async stopBlock(): Promise<{ source: string; text: string; reason: string } | null> {
2460
+ private async stopCheck(): Promise<{
2461
+ block: { source: string; text: string; reason: string } | null
2462
+ systemMessage?: string
2463
+ }> {
2464
+ let systemMessage: string | undefined
2333
2465
  if (this.hookEngine) {
2334
2466
  const stopResult = await this.hookEngine.executeStop(this.sessionId)
2467
+ systemMessage = stopResult.systemMessage
2335
2468
  if (stopResult.decision === 'block') {
2336
2469
  const reason = stopResult.reason || 'Continue working.'
2337
2470
  return {
2338
- source: 'stop-hook',
2339
- text: t('system.context.stop_blocked', { reason }),
2340
- reason,
2471
+ block: {
2472
+ source: 'stop-hook',
2473
+ text: t('system.context.stop_blocked', { reason }),
2474
+ reason,
2475
+ },
2476
+ systemMessage,
2341
2477
  }
2342
2478
  }
2343
2479
  }
2344
2480
 
2345
2481
  const claims = this.unprovenNumbers()
2346
- if (!claims) return null
2482
+ if (!claims) return { block: null, systemMessage }
2347
2483
  // 提示语给模型,`reason` 只留数字本身 —— 预算用完时那条告警是给**人**看的,
2348
2484
  // 把整段问话塞进 warning 只会让人读一屏。
2349
2485
  return {
2350
- source: 'number-provenance',
2351
- text: t('system.context.numbers_unproven', { claims }),
2352
- reason: claims,
2486
+ block: {
2487
+ source: 'number-provenance',
2488
+ text: t('system.context.numbers_unproven', { claims }),
2489
+ reason: claims,
2490
+ },
2491
+ systemMessage,
2353
2492
  }
2354
2493
  }
2355
2494
 
@@ -99,7 +99,25 @@ export function buildHookStdin(ctx: HookContext, cwd: string): Record<string, un
99
99
  * (permissionDecision / updatedInput / additionalContext) plus the legacy
100
100
  * root-level `decision` and `continue` fields. Non-JSON or empty stdout = allow.
101
101
  */
102
- export function parseHookStdout(stdout: string | null | undefined, _ctx: HookContext): HookResult {
102
+ export function parseHookStdout(stdout: string | null | undefined, ctx: HookContext): HookResult {
103
+ const result = parseHookStdoutFields(stdout, ctx)
104
+ if (!stdout) return result
105
+ // Root-level `systemMessage` is common to every event in the Claude hook
106
+ // contract — it is the one output meant for the *user*, not the model. It sat
107
+ // unread here: a hook could warn the operator and the message went nowhere.
108
+ try {
109
+ const parsed = JSON.parse(stdout) as Record<string, unknown>
110
+ const message = parsed.systemMessage
111
+ if (typeof message === 'string' && message.trim() !== '') {
112
+ return { ...result, systemMessage: message }
113
+ }
114
+ } catch {
115
+ // Non-JSON stdout already parsed as "allow"; there is nothing to attach.
116
+ }
117
+ return result
118
+ }
119
+
120
+ function parseHookStdoutFields(stdout: string | null | undefined, _ctx: HookContext): HookResult {
103
121
  if (!stdout) return { allowed: true }
104
122
 
105
123
  let parsed: Record<string, unknown>
@@ -130,7 +148,17 @@ export function parseHookStdout(stdout: string | null | undefined, _ctx: HookCon
130
148
  if (decision === 'ask') {
131
149
  // The engine stops the call on `ask` and prints `reason`, so the hook's
132
150
  // `permissionDecisionReason` is the only place its explanation can land.
133
- return { allowed: true, permissionDecision: 'ask', reason, additionalContext }
151
+ // `updatedInput` travels too even though this CLI treats `ask` as a hard
152
+ // refusal: the gate reports that a rewrite was *proposed and discarded*,
153
+ // which is information the operator can act on. Dropping it here made the
154
+ // hook's rewrite invisible rather than unexecutable.
155
+ return {
156
+ allowed: true,
157
+ permissionDecision: 'ask',
158
+ reason,
159
+ additionalContext,
160
+ modifiedInput: updatedInput,
161
+ }
134
162
  }
135
163
  if (decision === 'defer') {
136
164
  return { allowed: true, permissionDecision: 'defer', additionalContext }
@@ -414,10 +442,6 @@ async function executeCommand(
414
442
  const { loadUserCredentialMaskingConfig } = await import('../config/loader')
415
443
  const { filterEnv } = await import('./credential-masker')
416
444
  const masking = loadUserCredentialMaskingConfig()
417
- const env =
418
- masking.enabled && masking.env_filter.enabled
419
- ? filterEnv(process.env as Record<string, string | undefined>, masking)
420
- : undefined
421
445
 
422
446
  // Which workspace the hook is *for* is the session's business, not this
423
447
  // process's — the daemon runs many sessions and its own cwd belongs to none of
@@ -425,6 +449,16 @@ async function executeCommand(
425
449
  // hand, and is exactly right for the one-shot CLI.
426
450
  const cwd = ctx.cwd ?? process.cwd()
427
451
 
452
+ // A copy, not `undefined`: the CC hook contract exposes the project
453
+ // directory as `$CLAUDE_PROJECT_DIR`, and migrated scripts read it. With
454
+ // `undefined` the child inherited `process.env` and the variable expanded to
455
+ // empty. Copying also keeps the injected value out of this process's env.
456
+ const env =
457
+ masking.enabled && masking.env_filter.enabled
458
+ ? filterEnv(process.env as Record<string, string | undefined>, masking)
459
+ : ({ ...process.env } as Record<string, string | undefined>)
460
+ env.CLAUDE_PROJECT_DIR = cwd
461
+
428
462
  // Array args — no shell, so no command injection. The Claude-protocol stdin JSON
429
463
  // goes in so scripts can read structured context.
430
464
  const input = JSON.stringify(buildHookStdin(ctx, cwd))
package/src/core/hooks.ts CHANGED
@@ -455,6 +455,14 @@ export class HookEngine {
455
455
  : hookResult.additionalContext
456
456
  }
457
457
 
458
+ // `systemMessage` is addressed to the user, so collect it too instead of
459
+ // letting the last hook's warning win.
460
+ if (hookResult.systemMessage) {
461
+ result.systemMessage = result.systemMessage
462
+ ? result.systemMessage + '\n' + hookResult.systemMessage
463
+ : hookResult.systemMessage
464
+ }
465
+
458
466
  // PostToolUse: replace output if provided
459
467
  if (hookResult.updatedOutput) {
460
468
  result.updatedOutput = hookResult.updatedOutput