@miphamai/cli 0.85.25 → 0.85.26

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,4 +1,4 @@
1
- # Mipham Code v0.85.25
1
+ # Mipham Code v0.85.26
2
2
 
3
3
  **Multi-model open-core intelligent coding terminal** — 12 AI providers, 138 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/bin/mipham.ts CHANGED
@@ -346,6 +346,22 @@ async function runUpdate(): Promise<boolean> {
346
346
  process.exit(0)
347
347
  }
348
348
 
349
+ /**
350
+ * One shape for "the daemon is not answering".
351
+ *
352
+ * Twelve call sites used to print the raw fetch error and exit. The error says
353
+ * what failed and nothing about what to do, and it is the same situation every
354
+ * time — so it gets one message: whether it is still running, and how to bring
355
+ * it back. (The config lives at a fixed `~/.mipham/daemon.pid`, i.e. there is
356
+ * exactly one daemon per user, so there is nothing to disambiguate between.)
357
+ */
358
+ function reportDaemonUnreachable(port: number, err: unknown): never {
359
+ console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
360
+ console.error('Check whether it is still running: mipham daemon status')
361
+ console.error('Start it again: mipham daemon start')
362
+ process.exit(1)
363
+ }
364
+
349
365
  // ── Daemon lifecycle commands ──────────────────────────────────────────────────
350
366
 
351
367
  async function runDaemonCLI(): Promise<boolean> {
@@ -386,6 +402,12 @@ async function runDaemonCLI(): Promise<boolean> {
386
402
  // process is confirmed gone; the old code printed it right after send().
387
403
  if (await terminateDaemonProcess(status.pid)) {
388
404
  console.log(`Daemon stopped (PID: ${status.pid})`)
405
+ // 说清楚这一刀的后果:在这个 daemon 里跑着的后台会话(含 attach 中的那些)
406
+ // 一起结束了。历史仍在库里 —— 重启 daemon 后重新 attach 即可接着用。
407
+ // 不写「会重启」:没有任何东西会替你重启它。
408
+ console.log(
409
+ 'Background sessions running in it have ended. Start it again with "mipham daemon start".',
410
+ )
389
411
  process.exit(0)
390
412
  }
391
413
  console.error(
@@ -507,8 +529,7 @@ async function runAttachCLI(): Promise<boolean> {
507
529
  sessions = data.data.sessions.filter((s) => s.status === 'active' || s.status === 'idle')
508
530
  }
509
531
  } catch (err) {
510
- console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
511
- process.exit(1)
532
+ reportDaemonUnreachable(port, err)
512
533
  }
513
534
 
514
535
  const latestFlag = args.includes('--latest')
@@ -630,8 +651,7 @@ async function runAgentCLI(): Promise<boolean> {
630
651
  }
631
652
  }
632
653
  } catch (err) {
633
- console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
634
- process.exit(1)
654
+ reportDaemonUnreachable(port, err)
635
655
  }
636
656
  process.exit(0)
637
657
  }
@@ -685,8 +705,7 @@ async function runAgentCLI(): Promise<boolean> {
685
705
  }
686
706
  console.log(`Message sent to agent ${agentId}`)
687
707
  } catch (err) {
688
- console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
689
- process.exit(1)
708
+ reportDaemonUnreachable(port, err)
690
709
  }
691
710
  process.exit(0)
692
711
  }
@@ -708,8 +727,7 @@ async function runAgentCLI(): Promise<boolean> {
708
727
  }
709
728
  console.log(`Agent ${agentId} stopped.`)
710
729
  } catch (err) {
711
- console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
712
- process.exit(1)
730
+ reportDaemonUnreachable(port, err)
713
731
  }
714
732
  process.exit(0)
715
733
  }
@@ -760,8 +778,7 @@ async function runAgentCLI(): Promise<boolean> {
760
778
  if (a.branch) console.log(` Branch: ${a.branch}`)
761
779
  if (a.prUrl) console.log(` PR: ${a.prUrl}`)
762
780
  } catch (err) {
763
- console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
764
- process.exit(1)
781
+ reportDaemonUnreachable(port, err)
765
782
  }
766
783
  process.exit(0)
767
784
  }
@@ -827,8 +844,7 @@ async function runGoalCLI(): Promise<boolean> {
827
844
  }
828
845
  }
829
846
  } catch (err) {
830
- console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
831
- process.exit(1)
847
+ reportDaemonUnreachable(port, err)
832
848
  }
833
849
  process.exit(0)
834
850
  }
@@ -866,8 +882,7 @@ async function runGoalCLI(): Promise<boolean> {
866
882
  }
867
883
  console.log(`Goal #${data.data!.id} created.`)
868
884
  } catch (err) {
869
- console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
870
- process.exit(1)
885
+ reportDaemonUnreachable(port, err)
871
886
  }
872
887
  process.exit(0)
873
888
  }
@@ -893,8 +908,7 @@ async function runGoalCLI(): Promise<boolean> {
893
908
  }
894
909
  console.log(`Goal #${goalId} marked as done.`)
895
910
  } catch (err) {
896
- console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
897
- process.exit(1)
911
+ reportDaemonUnreachable(port, err)
898
912
  }
899
913
  process.exit(0)
900
914
  }
@@ -920,8 +934,7 @@ async function runGoalCLI(): Promise<boolean> {
920
934
  }
921
935
  console.log(`Goal #${goalId} paused.`)
922
936
  } catch (err) {
923
- console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
924
- process.exit(1)
937
+ reportDaemonUnreachable(port, err)
925
938
  }
926
939
  process.exit(0)
927
940
  }
@@ -995,8 +1008,7 @@ async function runScheduleCLI(): Promise<boolean> {
995
1008
  }
996
1009
  }
997
1010
  } catch (err) {
998
- console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
999
- process.exit(1)
1011
+ reportDaemonUnreachable(port, err)
1000
1012
  }
1001
1013
  process.exit(0)
1002
1014
  }
@@ -1028,8 +1040,7 @@ async function runScheduleCLI(): Promise<boolean> {
1028
1040
  }
1029
1041
  console.log(`Schedule #${data.data!.id} created (cron: ${cronExpr}).`)
1030
1042
  } catch (err) {
1031
- console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
1032
- process.exit(1)
1043
+ reportDaemonUnreachable(port, err)
1033
1044
  }
1034
1045
  process.exit(0)
1035
1046
  }
@@ -1051,8 +1062,7 @@ async function runScheduleCLI(): Promise<boolean> {
1051
1062
  }
1052
1063
  console.log(`Schedule #${scheduleId} removed.`)
1053
1064
  } catch (err) {
1054
- console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
1055
- process.exit(1)
1065
+ reportDaemonUnreachable(port, err)
1056
1066
  }
1057
1067
  process.exit(0)
1058
1068
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miphamai/cli",
3
- "version": "0.85.25",
3
+ "version": "0.85.26",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -130,7 +130,27 @@ export function createAgentContext(
130
130
 
131
131
  context.setSystemPrompt(systemPrompt)
132
132
 
133
- // Scope tools
133
+ return { context, allowedTools: selectAgentTools(agentDef, toolRegistry), systemPrompt }
134
+ }
135
+
136
+ /**
137
+ * The tools an agent definition is allowed to use, read from the **current**
138
+ * registry.
139
+ *
140
+ * Exported because the answer is not a one-time fact: MCP servers connect in the
141
+ * background, so a sub-agent that started early would otherwise be pinned to the
142
+ * tool table of the moment it started, and a server that finished connecting a
143
+ * second later could never be used by it — even though calling the tool would
144
+ * have worked (`sub-agent.ts` resolves each call against the live registry).
145
+ *
146
+ * `warnOnEmpty` is for the repeat callers: the warning is worth printing once
147
+ * per run, not once per turn.
148
+ */
149
+ export function selectAgentTools(
150
+ agentDef: AgentDefinition,
151
+ toolRegistry: Map<string, ToolDefinition>,
152
+ warnOnEmpty = true,
153
+ ): ToolDefinition[] {
134
154
  let allowedTools = Array.from(toolRegistry.values())
135
155
 
136
156
  if (agentDef.tools) {
@@ -148,7 +168,7 @@ export function createAgentContext(
148
168
  allowedTools = allowedTools.filter(
149
169
  (t) => allowSet.has(t.name) || serverPrefixes.some((p) => t.name.startsWith(p)),
150
170
  )
151
- if (allowedTools.length === 0) {
171
+ if (allowedTools.length === 0 && warnOnEmpty) {
152
172
  process.stderr.write(
153
173
  `⚠️ Agent "${agentDef.name}": tools list (${allowRules.join(', ')}) matched no registered tool — the agent will run without tools.\n`,
154
174
  )
@@ -165,5 +185,5 @@ export function createAgentContext(
165
185
  allowedTools = allowedTools.filter((t) => !denySet.has(t.name))
166
186
  }
167
187
 
168
- return { context, allowedTools, systemPrompt }
188
+ return allowedTools
169
189
  }
@@ -2,7 +2,7 @@ import type { ProviderRegistry } from '../providers/registry'
2
2
  import type { Llm } from '../providers/llm'
3
3
  import type { Message, ToolDefinition, ToolContext } from '../shared/index.ts'
4
4
  import type { SubAgentType, SubAgentOptions, AgentDefinition } from './types'
5
- import { createAgentContext } from './agent-context'
5
+ import { createAgentContext, selectAgentTools } from './agent-context'
6
6
  import { shrinkAgentMessages } from './auto-compact'
7
7
  import { getBackgroundAgentRegistry } from './background-registry'
8
8
  import { formatInboundMessage, getMessageBus } from './message-bus'
@@ -390,11 +390,11 @@ export class SubAgent {
390
390
  ? Math.min(declaredWindow, contextWindow ?? declaredWindow)
391
391
  : undefined
392
392
  // 这一份**已含 agent memory**,是发出去的那个提示的唯一来源。
393
- const {
394
- context,
395
- allowedTools,
396
- systemPrompt: composedSystemPrompt,
397
- } = createAgentContext(resolvedDef, this.toolRegistry, compactWindow ?? contextWindow)
393
+ const { context, systemPrompt: composedSystemPrompt } = createAgentContext(
394
+ resolvedDef,
395
+ this.toolRegistry,
396
+ compactWindow ?? contextWindow,
397
+ )
398
398
 
399
399
  // 别再 `context.setSystemPrompt(systemPrompt)`:`createAgentContext` 已经拿**含记忆**的
400
400
  // 那一份设过上下文,这里用裸提示再设一遍只会把记忆从上下文里抹掉,而请求读的又不是
@@ -417,15 +417,10 @@ export class SubAgent {
417
417
  context.addMessage({ role: 'user', content: opening })
418
418
 
419
419
  const messages = context.getMessages()
420
- const toolDefs =
421
- allowedTools.length > 0
422
- ? allowedTools.map((t) => ({
423
- name: t.name,
424
- description: t.description,
425
- parameters: t.parameters,
426
- input_schema: t.parameters,
427
- }))
428
- : undefined
420
+ // 广告出去的工具表**每轮**从 registry 现算(见下面 `tools: toolDefs` 前那一段),
421
+ // 不在这里采一次:MCP server 是启动后在后台连的,这一刻的快照会让晚一秒连上的
422
+ // 工具永远进不了这个子代理 —— 而调用本身其实是通的(每轮按 `tu.name` 读的是
423
+ // **当前** registry)。声明与执行必须读同一个事实。
429
424
 
430
425
  const chunks: string[] = []
431
426
  const MAX_TOOL_TURNS = options.maxTurns || 5
@@ -493,6 +488,10 @@ export class SubAgent {
493
488
  // synchronous (see `resolveRunInBackground`). Set on the shared literal so it
494
489
  // covers the synchronous *and* background runs — both go through here.
495
490
  isSubAgent: true,
491
+ // Tools that keep per-session state (the Task list) must file it under the
492
+ // session this work belongs to, not under the literal 'sub-agent' — that
493
+ // one bucket is shared by every nested call from every session.
494
+ parentSessionId: options.toolContext?.sessionId,
496
495
  // A name a peer can hold onto. `sessionId` is the literal 'sub-agent' for
497
496
  // every sub-agent, so `SendMessage` had nothing stable to put on the
498
497
  // envelope and minted `sub-agent-<ms>` afresh per message — two messages
@@ -545,6 +544,21 @@ export class SubAgent {
545
544
  // nothing downstream could tell that from a finished one.
546
545
  let turnTruncated = false
547
546
 
547
+ // Per turn: an MCP server that finished connecting while this turn was
548
+ // running must be usable in the next one. Reading the registry here (and
549
+ // the same registry below when resolving `tu.name`) keeps the advertised
550
+ // list and the executable set from drifting apart.
551
+ const allowedNow = selectAgentTools(resolvedDef, this.toolRegistry, false)
552
+ const toolDefs =
553
+ allowedNow.length > 0
554
+ ? allowedNow.map((t) => ({
555
+ name: t.name,
556
+ description: t.description,
557
+ parameters: t.parameters,
558
+ input_schema: t.parameters,
559
+ }))
560
+ : undefined
561
+
548
562
  for await (const chunk of (this.llm ?? this.registry).chat({
549
563
  model: finalModel,
550
564
  messages: currentMessages,
@@ -130,6 +130,15 @@ export class ContextManager {
130
130
  * 组装时烘进去的话,本次会话里后连上的 server 永远进不了提示 —— 用户只能重启。
131
131
  */
132
132
  private mcpInstructionsSource: (() => string) | null = null
133
+ /**
134
+ * 重建整个系统提示的方式,由 `index.tsx` 在装提示的同时登记。
135
+ *
136
+ * 提示是启动那一刻的快照,而其中最大的那一段 —— 指令文件(`CLAUDE.md` /
137
+ * `AGENTS.md` / `USER.md`)—— 在会话中会被改。压缩之后由引擎调一次
138
+ * `refreshSystemPrompt()`,让规则按磁盘现状生效。**重建方式必须与首次组装
139
+ * 同一条路径**,否则刷新会悄悄丢掉启动时拼进去的那些段(技能提醒、记忆召回…)。
140
+ */
141
+ private systemPromptRebuilder: (() => string) | null = null
133
142
  /**
134
143
  * **消息那部分**的估值,增量累加(提示那部分见 `promptTokens()`,读时派生)。
135
144
  *
@@ -258,6 +267,29 @@ export class ContextManager {
258
267
  this.mcpInstructionsSource = fn
259
268
  }
260
269
 
270
+ /**
271
+ * 接线点(`index.tsx`):重建系统提示的方式。
272
+ *
273
+ * 传 `null` 撤销。**不接**时 `refreshSystemPrompt()` 是空操作 —— daemon 等路径
274
+ * 从不设置系统提示,凭空造一份出来会改变它们每个请求的形状。
275
+ */
276
+ setSystemPromptRebuilder(fn: (() => string) | null): void {
277
+ this.systemPromptRebuilder = fn
278
+ }
279
+
280
+ /**
281
+ * 用登记好的重建器重刷系统提示。返回是否真的重刷了。
282
+ *
283
+ * 调用点是压缩之后(`Engine.compactWithHooks`):对话刚被换成摘要,而指令文件
284
+ * 那一段还是启动那一刻的拷贝。重建器在里面先回读磁盘(`InstructionsLoader.refresh`),
285
+ * 所以这里拿到的是当前磁盘上的规则。
286
+ */
287
+ refreshSystemPrompt(): boolean {
288
+ if (!this.systemPromptRebuilder) return false
289
+ this.systemPrompt = this.systemPromptRebuilder()
290
+ return true
291
+ }
292
+
261
293
  /**
262
294
  * 存储的提示 + 读时派生的段(权限 / MCP instructions)。
263
295
  *
@@ -603,8 +603,8 @@ export class QueryEngine {
603
603
  const summaryPrompt = `You are a conversation summarizer. Create a concise summary (1-3 paragraphs) of this conversation excerpt. Focus on: key topics discussed, decisions made, code changes mentioned, and open questions. Heading: ${heading}`
604
604
 
605
605
  // Collect full summary text from streaming response
606
- let summary = ''
607
- try {
606
+ const requestSummary = async (prompt: string): Promise<string> => {
607
+ let out = ''
608
608
  for await (const chunk of this.llmChat({
609
609
  model: this.registry.getActiveModel(),
610
610
  // The instruction goes in `systemPrompt`, **not** as a `system` message
@@ -614,7 +614,7 @@ export class QueryEngine {
614
614
  // so the array form reached the OpenAI-compatible providers and no one
615
615
  // else — the summarizer's instruction was missing for anthropic users
616
616
  // while it worked here. `systemPrompt` is the one spelling both read.
617
- systemPrompt: summaryPrompt,
617
+ systemPrompt: prompt,
618
618
  messages: [{ role: 'user', content: text }],
619
619
  maxTokens: 2000,
620
620
  // An interrupt has to reach *this* call too. Summarising a long
@@ -624,13 +624,34 @@ export class QueryEngine {
624
624
  signal,
625
625
  })) {
626
626
  if (chunk.type === 'text' && chunk.content) {
627
- summary += chunk.content
627
+ out += chunk.content
628
628
  }
629
629
  if (chunk.type === 'stop') break
630
630
  if (chunk.type === 'error') break
631
631
  }
632
+ return out
633
+ }
634
+
635
+ let summary = ''
636
+ try {
637
+ summary = await requestSummary(summaryPrompt)
632
638
  } catch {
633
- // Return a minimal summary on failure
639
+ // A round trip that failed outright is not retried into: the same
640
+ // provider will fail the same way. Falls through to the placeholder.
641
+ }
642
+
643
+ // 回复里没有摘要(这一趟只回了工具调用 / 空文本)时**再问一次**,而不是
644
+ // 立刻把整段历史换成一个「已省略」占位符:那一步是不可逆的,而模型这一次
645
+ // 什么都没写通常只是没把话放在正文里。第二次把要求说得更死(只要摘要正文),
646
+ // 因为同一个提示重发一遍只会得到同一个空回复。
647
+ if (!summary.trim() && !signal?.aborted) {
648
+ try {
649
+ summary = await requestSummary(
650
+ `${summaryPrompt}\n\nReturn only the summary text itself — no tool calls, no preamble.`,
651
+ )
652
+ } catch {
653
+ // Still nothing usable: the placeholder below is honest about it.
654
+ }
634
655
  }
635
656
 
636
657
  // Surrogate-safe: this string lands in the JSONL transcript, where a lone
@@ -1696,6 +1717,11 @@ export class QueryEngine {
1696
1717
  // fresh attempt after a failed one.
1697
1718
  const ownsFlow = !(this.llm && this.llm !== this.registry)
1698
1719
  let failure: string | null = null
1720
+ // Re-bound after a mid-turn compaction: the request that follows must be the
1721
+ // *new* conversation, not the oversized one the provider just rejected.
1722
+ let msgs = messages
1723
+ let sysPrompt = systemPrompt
1724
+ let compactedForOverflow = false
1699
1725
  // A provider that marks the failure deterministic opts out of both retries. Only
1700
1726
  // an explicit `false` counts: an absent flag means "unknown", which keeps the
1701
1727
  // old try-again behaviour for every provider that says nothing.
@@ -1715,8 +1741,8 @@ export class QueryEngine {
1715
1741
  try {
1716
1742
  for await (const chunk of this.llmChat({
1717
1743
  model: activeModel,
1718
- messages,
1719
- systemPrompt,
1744
+ messages: msgs,
1745
+ systemPrompt: sysPrompt,
1720
1746
  tools: toolDefs,
1721
1747
  signal,
1722
1748
  effort: this.effort,
@@ -1747,6 +1773,35 @@ export class QueryEngine {
1747
1773
  if (isAbortError(err)) throw err
1748
1774
  failure = String(err)
1749
1775
  }
1776
+ // A request the provider rejected as *too large* is the one failure that is
1777
+ // worth a different retry: re-sending it is guaranteed to fail the same way
1778
+ // (the prompt did not get smaller), while compacting changes the thing that
1779
+ // was rejected. It therefore sits **above** the retry budget below — that
1780
+ // budget is for flaky transports, and spending it on an oversized prompt is
1781
+ // how a turn used to end with the raw upstream error.
1782
+ if (
1783
+ !compactedForOverflow &&
1784
+ ownsFlow &&
1785
+ !signal?.aborted &&
1786
+ isContextOverflowError(failure)
1787
+ ) {
1788
+ compactedForOverflow = true
1789
+ yield {
1790
+ type: 'warning',
1791
+ content: `${activeId} rejected the request as too large — compacting the conversation and retrying`,
1792
+ restart: true,
1793
+ }
1794
+ try {
1795
+ await this.compactWithHooks('context overflow', signal)
1796
+ msgs = this.context.getMessages()
1797
+ sysPrompt = this.context.getSystemPrompt()
1798
+ } catch (err) {
1799
+ if (isAbortError(err)) throw err
1800
+ // Compaction itself failed: fall through to the ordinary retry/fallback
1801
+ // path so the turn still ends with an explanation rather than nothing.
1802
+ }
1803
+ continue
1804
+ }
1750
1805
  if (!retryable || !ownsFlow || attempt >= 1) break
1751
1806
  // `restart: true` tells the consumer to drop what the failed attempt already
1752
1807
  // yielded. Without it the retry's tool calls are *added* to the failed
@@ -1820,8 +1875,8 @@ export class QueryEngine {
1820
1875
  try {
1821
1876
  for await (const chunk of this.llmChat({
1822
1877
  model: fallbackModel,
1823
- messages,
1824
- systemPrompt,
1878
+ messages: msgs,
1879
+ systemPrompt: sysPrompt,
1825
1880
  tools: toolDefs,
1826
1881
  signal,
1827
1882
  effort: this.effort,
@@ -2099,6 +2154,12 @@ export class QueryEngine {
2099
2154
 
2100
2155
  await this.context.compact(heading, signal)
2101
2156
 
2157
+ // 规则那一段是启动那一刻的拷贝。会话中被改过的 `CLAUDE.md` / `AGENTS.md` /
2158
+ // `USER.md` 若不重读,压缩换掉的只是对话,规则还是旧的 —— 而压缩正是「对话刚
2159
+ // 被替换」的那一刻,用户会以为模型拿到了新规则。重建器里先回读磁盘再重建;
2160
+ // 没登记重建器时(daemon)是空操作。
2161
+ this.context.refreshSystemPrompt()
2162
+
2102
2163
  if (this.hookEngine) {
2103
2164
  const postResult = await this.hookEngine.executePostCompact(this.sessionId)
2104
2165
  if (postResult.additionalContext) {
@@ -2145,6 +2206,22 @@ export class QueryEngine {
2145
2206
  }
2146
2207
  }
2147
2208
 
2209
+ /**
2210
+ * Does this failure say "the request itself does not fit"?
2211
+ *
2212
+ * Kept narrow on purpose: a false positive costs one wasted compaction (the turn
2213
+ * retries either way), while a false negative ends the turn with a raw upstream
2214
+ * error the user cannot act on. All of these phrasings are ones the providers
2215
+ * actually send — the last is the one a 1M-context model returns while the
2216
+ * account has not enabled the charge.
2217
+ */
2218
+ export function isContextOverflowError(message: string | null | undefined): boolean {
2219
+ if (!message) return false
2220
+ return /context[_ ]length|context window|prompt is too long|too many tokens|maximum context length|exceeds? the (?:model'?s )?(?:maximum )?context|usage credits required for 1m context/i.test(
2221
+ message,
2222
+ )
2223
+ }
2224
+
2148
2225
  function isAbortError(err: unknown): boolean {
2149
2226
  if (err instanceof Error && err.name === 'AbortError') return true
2150
2227
  if (
@@ -687,27 +687,72 @@ Never omit it or present the work as purely human-authored.`)
687
687
  return { totalChars: files.reduce((n, f) => n + f.chars, 0), files }
688
688
  }
689
689
 
690
- private tryLoad(path: string, level: InstructionFile['level']): void {
691
- if (!existsSync(path)) return
690
+ /**
691
+ * A repo-controlled instruction file must be a regular file, not a symlink.
692
+ * A cloned repository can ship `CLAUDE.md -> ~/.ssh/id_rsa`: this loader runs
693
+ * with no permission gate at all, so following the link would put any local
694
+ * file into the system prompt without the model ever asking for it. `lstat`
695
+ * reports the link as itself, which is what makes the shape visible.
696
+ *
697
+ * Only the levels that live *inside* the checkout (`project`, `directory`)
698
+ * are gated. A symlinked `~/.mipham/USER.md` pointing at a dotfiles repo is
699
+ * the user's own arrangement, and the group/company tiers point at the
700
+ * surrounding monorepo the user cloned deliberately — refusing those would
701
+ * break real setups without closing anything a repo did not already control.
702
+ *
703
+ * An unreadable `lstat` counts as unsafe: the shape could not be established.
704
+ */
705
+ private isUnsafePath(path: string, level: InstructionFile['level']): boolean {
706
+ if (level !== 'project' && level !== 'directory') return false
707
+ try {
708
+ return lstatSync(path).isSymbolicLink()
709
+ } catch {
710
+ return true
711
+ }
712
+ }
692
713
 
693
- // A repo-controlled instruction file must be a regular file, not a symlink.
694
- // A cloned repository can ship `CLAUDE.md -> ~/.ssh/id_rsa`: this loader runs
695
- // with no permission gate at all, so following the link would put any local
696
- // file into the system prompt without the model ever asking for it. `lstat`
697
- // reports the link as itself, which is what makes the shape visible.
698
- //
699
- // Only the levels that live *inside* the checkout (`project`, `directory`)
700
- // are gated. A symlinked `~/.mipham/USER.md` pointing at a dotfiles repo is
701
- // the user's own arrangement, and the group/company tiers point at the
702
- // surrounding monorepo the user cloned deliberately — refusing those would
703
- // break real setups without closing anything a repo did not already control.
704
- if (level === 'project' || level === 'directory') {
714
+ /**
715
+ * Re-read every instruction file already in the prompt, and report the paths
716
+ * whose text actually changed.
717
+ *
718
+ * The chain is read once, at `loadAll`. An edit made during the session — the
719
+ * user tightening their `CLAUDE.md`, a skill rewriting `AGENTS.md` — therefore
720
+ * never reached the model. `ContextManager.refreshSystemPrompt()` calls this
721
+ * after compaction, which is the moment the conversation those rules govern
722
+ * has just been replaced anyway.
723
+ *
724
+ * Deliberately does **not** discover new files: which directories to walk is
725
+ * `loadAll`'s decision, and re-walking here would make the prompt depend on
726
+ * what happens to exist at compaction time. A file that disappeared keeps its
727
+ * last-known text rather than silently dropping a rule mid-session, and one
728
+ * that became a symlink keeps it too (same gate as the first read).
729
+ */
730
+ refresh(): string[] {
731
+ const changed: string[] = []
732
+ for (const inst of this.instructions) {
733
+ if (this.isUnsafePath(inst.path, inst.level)) continue
734
+ if (!existsSync(inst.path)) continue
705
735
  try {
706
- if (lstatSync(path).isSymbolicLink()) return
736
+ const { data, content } = parseFrontmatter(readFileSync(inst.path, 'utf-8'))
737
+ const next = capInstructionContent(content, inst.path)
738
+ if (next !== inst.content) {
739
+ inst.content = next
740
+ changed.push(inst.path)
741
+ }
742
+ inst.privacy = (data.privacy as InstructionFile['privacy']) || 'project'
743
+ inst.language = (data.language as string) || 'en-US'
744
+ inst.frontmatter = data
707
745
  } catch {
708
- return
746
+ // Unreadable right now: keep the text the session has been running on.
709
747
  }
710
748
  }
749
+ return changed
750
+ }
751
+
752
+ private tryLoad(path: string, level: InstructionFile['level']): void {
753
+ if (!existsSync(path)) return
754
+
755
+ if (this.isUnsafePath(path, level)) return
711
756
 
712
757
  try {
713
758
  const raw = readFileSync(path, 'utf-8')
@@ -0,0 +1,67 @@
1
+ /**
2
+ * 「这条权限规则写坏了」的告警,每个用户只看一次 —— 直到那条规则本身变了。
3
+ *
4
+ * 规则是从 settings 文件里读的,文件不修,告警就每次启动都会原样重复。重复的
5
+ * 告警不是提醒,是噪音:用户读到第七次时就已经不再读了,于是**新**出现的那条
6
+ * 坏规则混在里面也看不见。认领(ack)按**告警文本**记账,文本变了就是另一条
7
+ * 规则,重新报。
8
+ *
9
+ * 写盘失败一律按「没认领过」处理 —— 宁可多报一次,也不因为盘上写不进去而把
10
+ * 一条本该 fail-closed 的坏规则静默吞掉。
11
+ */
12
+
13
+ import { existsSync, mkdirSync, readFileSync } from 'node:fs'
14
+ import { dirname } from 'node:path'
15
+ import { miphamHome } from './paths'
16
+ import { atomicWriteFileSync } from '../shared/atomic-write'
17
+
18
+ /** 记账文件里保留的条目上限 —— 规则文本会随编辑不断变新,不设上限就是无限长。 */
19
+ const MAX_ACKS = 200
20
+
21
+ interface AckFile {
22
+ acknowledged: string[]
23
+ }
24
+
25
+ function ackPath(): string {
26
+ return miphamHome('permission-rule-acks.json')
27
+ }
28
+
29
+ function readAcks(): string[] {
30
+ const path = ackPath()
31
+ if (!existsSync(path)) return []
32
+ try {
33
+ const parsed: unknown = JSON.parse(readFileSync(path, 'utf-8'))
34
+ const list = (parsed as AckFile | null)?.acknowledged
35
+ if (!Array.isArray(list)) return []
36
+ return list.filter((v): v is string => typeof v === 'string')
37
+ } catch {
38
+ // 文件坏了 = 没有记账。重报一次然后重写。
39
+ return []
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Narrow `messages` to the ones this user has not seen yet, and remember them.
45
+ *
46
+ * Returns the messages to print. A message that was already acknowledged — and
47
+ * whose text has not changed since — is dropped.
48
+ */
49
+ export function unacknowledgedRuleWarnings(messages: readonly string[]): string[] {
50
+ if (messages.length === 0) return []
51
+ const seen = new Set(readAcks())
52
+ const fresh = messages.filter((m) => !seen.has(m))
53
+ if (fresh.length === 0) return []
54
+
55
+ for (const m of fresh) seen.add(m)
56
+ const next = [...seen].slice(-MAX_ACKS)
57
+ try {
58
+ const path = ackPath()
59
+ mkdirSync(dirname(path), { recursive: true })
60
+ atomicWriteFileSync(path, `${JSON.stringify({ acknowledged: next }, null, 2)}\n`, {
61
+ mode: 0o644,
62
+ })
63
+ } catch {
64
+ // 写不进去 ⇒ 下次还会报(见文件头:多报比静默好)
65
+ }
66
+ return fresh
67
+ }