@miphamai/cli 0.85.24 → 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.
Files changed (45) hide show
  1. package/README.md +3 -3
  2. package/bin/mipham.ts +34 -24
  3. package/package.json +1 -1
  4. package/src/agent/agent-context.ts +23 -3
  5. package/src/agent/sub-agent.ts +29 -15
  6. package/src/artifacts/server.ts +5 -1
  7. package/src/commands/git.ts +9 -1
  8. package/src/commands/project.ts +34 -17
  9. package/src/core/context-token.ts +55 -3
  10. package/src/core/context.ts +54 -42
  11. package/src/core/crsi-sandbox.ts +5 -1
  12. package/src/core/engine.ts +91 -10
  13. package/src/core/instructions.ts +130 -18
  14. package/src/core/permission-rule-ack.ts +67 -0
  15. package/src/core/permission-rules.ts +141 -25
  16. package/src/daemon/remote-engine.ts +11 -5
  17. package/src/daemon/schedule-manager.ts +32 -3
  18. package/src/daemon/server.ts +6 -0
  19. package/src/i18n-core/locales/en-US.json +1 -1
  20. package/src/i18n-core/locales/zh-CN.json +1 -1
  21. package/src/index.tsx +34 -4
  22. package/src/mcp/client.ts +37 -2
  23. package/src/mcp/http-transport.ts +20 -1
  24. package/src/mcp/protocol.ts +13 -5
  25. package/src/mcp/registry.ts +8 -3
  26. package/src/mcp/transport.ts +40 -3
  27. package/src/plugin/plugin-manager.ts +23 -2
  28. package/src/providers/anthropic.ts +3 -1
  29. package/src/providers/fetch-utils.ts +40 -6
  30. package/src/providers/openai-compat.ts +2 -1
  31. package/src/providers/registry.ts +23 -1
  32. package/src/shared/git-env.ts +18 -0
  33. package/src/shared/package-info.ts +3 -3
  34. package/src/shared/sanitize.ts +21 -0
  35. package/src/shared/types.ts +9 -0
  36. package/src/skills/loader.ts +14 -0
  37. package/src/tools/exec/bash.ts +168 -6
  38. package/src/tools/exec/enter-worktree.ts +26 -2
  39. package/src/tools/exec/task.ts +144 -21
  40. package/src/tools/network/web-fetch.ts +7 -7
  41. package/src/tools/network/web-search.ts +6 -5
  42. package/src/ui/app.tsx +22 -7
  43. package/src/ui/chat.tsx +3 -2
  44. package/src/ui/commands.ts +65 -5
  45. package/src/workflow/primitives/agent.ts +17 -1
@@ -46,6 +46,7 @@ import { getFileInboxTransport } from '../agent/cross-session/file-inbox'
46
46
  import { registerWakeupHandler, unregisterWakeupHandler } from '../tools/scheduling/schedule-wakeup'
47
47
  import { accumulateGraftSavings } from '../shared/graft-savings'
48
48
  import { deletedCwdSessionMessage, resolveExistingCwd } from '../shared/deleted-cwd'
49
+ import { safeSlice } from '../shared/sanitize'
49
50
  import {
50
51
  getMessageBus,
51
52
  formatInboundMessage,
@@ -602,8 +603,8 @@ export class QueryEngine {
602
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}`
603
604
 
604
605
  // Collect full summary text from streaming response
605
- let summary = ''
606
- try {
606
+ const requestSummary = async (prompt: string): Promise<string> => {
607
+ let out = ''
607
608
  for await (const chunk of this.llmChat({
608
609
  model: this.registry.getActiveModel(),
609
610
  // The instruction goes in `systemPrompt`, **not** as a `system` message
@@ -613,7 +614,7 @@ export class QueryEngine {
613
614
  // so the array form reached the OpenAI-compatible providers and no one
614
615
  // else — the summarizer's instruction was missing for anthropic users
615
616
  // while it worked here. `systemPrompt` is the one spelling both read.
616
- systemPrompt: summaryPrompt,
617
+ systemPrompt: prompt,
617
618
  messages: [{ role: 'user', content: text }],
618
619
  maxTokens: 2000,
619
620
  // An interrupt has to reach *this* call too. Summarising a long
@@ -623,16 +624,40 @@ export class QueryEngine {
623
624
  signal,
624
625
  })) {
625
626
  if (chunk.type === 'text' && chunk.content) {
626
- summary += chunk.content
627
+ out += chunk.content
627
628
  }
628
629
  if (chunk.type === 'stop') break
629
630
  if (chunk.type === 'error') break
630
631
  }
632
+ return out
633
+ }
634
+
635
+ let summary = ''
636
+ try {
637
+ summary = await requestSummary(summaryPrompt)
631
638
  } catch {
632
- // 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.
633
641
  }
634
642
 
635
- return summary.slice(0, 8000) || t('system.context.omitted')
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
+ }
655
+ }
656
+
657
+ // Surrogate-safe: this string lands in the JSONL transcript, where a lone
658
+ // half-pair makes the serializer emit an invalid escape and strict parsers
659
+ // reject the entire line.
660
+ return safeSlice(summary, 8000) || t('system.context.omitted')
636
661
  })
637
662
  }
638
663
 
@@ -1692,6 +1717,11 @@ export class QueryEngine {
1692
1717
  // fresh attempt after a failed one.
1693
1718
  const ownsFlow = !(this.llm && this.llm !== this.registry)
1694
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
1695
1725
  // A provider that marks the failure deterministic opts out of both retries. Only
1696
1726
  // an explicit `false` counts: an absent flag means "unknown", which keeps the
1697
1727
  // old try-again behaviour for every provider that says nothing.
@@ -1711,8 +1741,8 @@ export class QueryEngine {
1711
1741
  try {
1712
1742
  for await (const chunk of this.llmChat({
1713
1743
  model: activeModel,
1714
- messages,
1715
- systemPrompt,
1744
+ messages: msgs,
1745
+ systemPrompt: sysPrompt,
1716
1746
  tools: toolDefs,
1717
1747
  signal,
1718
1748
  effort: this.effort,
@@ -1743,6 +1773,35 @@ export class QueryEngine {
1743
1773
  if (isAbortError(err)) throw err
1744
1774
  failure = String(err)
1745
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
+ }
1746
1805
  if (!retryable || !ownsFlow || attempt >= 1) break
1747
1806
  // `restart: true` tells the consumer to drop what the failed attempt already
1748
1807
  // yielded. Without it the retry's tool calls are *added* to the failed
@@ -1816,8 +1875,8 @@ export class QueryEngine {
1816
1875
  try {
1817
1876
  for await (const chunk of this.llmChat({
1818
1877
  model: fallbackModel,
1819
- messages,
1820
- systemPrompt,
1878
+ messages: msgs,
1879
+ systemPrompt: sysPrompt,
1821
1880
  tools: toolDefs,
1822
1881
  signal,
1823
1882
  effort: this.effort,
@@ -2095,6 +2154,12 @@ export class QueryEngine {
2095
2154
 
2096
2155
  await this.context.compact(heading, signal)
2097
2156
 
2157
+ // 规则那一段是启动那一刻的拷贝。会话中被改过的 `CLAUDE.md` / `AGENTS.md` /
2158
+ // `USER.md` 若不重读,压缩换掉的只是对话,规则还是旧的 —— 而压缩正是「对话刚
2159
+ // 被替换」的那一刻,用户会以为模型拿到了新规则。重建器里先回读磁盘再重建;
2160
+ // 没登记重建器时(daemon)是空操作。
2161
+ this.context.refreshSystemPrompt()
2162
+
2098
2163
  if (this.hookEngine) {
2099
2164
  const postResult = await this.hookEngine.executePostCompact(this.sessionId)
2100
2165
  if (postResult.additionalContext) {
@@ -2141,6 +2206,22 @@ export class QueryEngine {
2141
2206
  }
2142
2207
  }
2143
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
+
2144
2225
  function isAbortError(err: unknown): boolean {
2145
2226
  if (err instanceof Error && err.name === 'AbortError') return true
2146
2227
  if (
@@ -14,6 +14,7 @@ import {
14
14
  type CrsiLessonSummary,
15
15
  } from './crsi-producer'
16
16
  import { miphamHome } from './paths.ts'
17
+ import { safeSlice } from '../shared/sanitize'
17
18
 
18
19
  export interface FrontmatterResult {
19
20
  data: Record<string, unknown>
@@ -71,7 +72,8 @@ export function parsePromptExclude(value: unknown): string[] {
71
72
  * 就能看见)。但 stdout 仍须是管道 —— 换成 `'ignore'`(`commands.ts` 里那种 stdout
72
73
  * 不用的形状)会让这里永远拿到空串、永远回退 cwd,**连在仓库里都失效**。
73
74
  */
74
- export function gitRoot(cwd: string): string {
75
+ export function gitRoot(cwd: string, available: boolean = gitAvailable()): string {
76
+ if (!available) return cwd
75
77
  try {
76
78
  return execSync('git rev-parse --show-toplevel', {
77
79
  cwd,
@@ -84,6 +86,34 @@ export function gitRoot(cwd: string): string {
84
86
  }
85
87
  }
86
88
 
89
+ let gitAvailableCache: boolean | undefined
90
+
91
+ /**
92
+ * macOS 上 `/usr/bin/git` 是个 **shim**:Command Line Tools 没装时,任何一次调用
93
+ * 都会弹「Install Command Line Developer Tools」的 **GUI 对话框** —— `stdio: 'ignore'`
94
+ * 挡得住 stderr 文本,挡不住这个窗口。本函数每次启动都会被调用(`loadAll`),
95
+ * 所以先花一次 `xcode-select -p`(系统自带、无 CLT 时只退非零、不弹窗)探一下。
96
+ *
97
+ * 探测结果缓存:进程生命周期内工具链不会装上,每个 cwd 各探一次纯属浪费。
98
+ * 非 darwin 平台原样 `true` —— 那些平台的 git 不会弹窗。
99
+ */
100
+ function gitAvailable(): boolean {
101
+ if (process.platform !== 'darwin') return true
102
+ if (gitAvailableCache !== undefined) return gitAvailableCache
103
+ try {
104
+ execSync('/usr/bin/xcode-select -p', {
105
+ timeout: 2000,
106
+ encoding: 'utf-8',
107
+ stdio: ['ignore', 'ignore', 'ignore'],
108
+ })
109
+ gitAvailableCache = true
110
+ } catch {
111
+ // 交互式 shell 里的 `/usr/bin/git` 在这种状态下会弹窗 —— 不要碰它。
112
+ gitAvailableCache = false
113
+ }
114
+ return gitAvailableCache
115
+ }
116
+
87
117
  /** True when `p` is `root` itself or sits underneath it. */
88
118
  function isInside(root: string, p: string): boolean {
89
119
  const rel = relative(root, p)
@@ -221,6 +251,43 @@ export interface InstructionSizeReport {
221
251
  */
222
252
  export const INSTRUCTION_BUDGET_CHARS = 40_000
223
253
 
254
+ /**
255
+ * Hard ceiling on a single instruction file's contribution.
256
+ *
257
+ * The budget above is a **report**: it says the payload has grown past a
258
+ * governance file's size, and the user decides what to trim. A nested
259
+ * `CLAUDE.md` discovered mid-session had no ceiling at all — a generated or
260
+ * concatenated file went into the prompt whole, on every request, and the only
261
+ * signal was a notice arriving after the fact. The two failure modes differ:
262
+ * a startup-tier file lands in the **system prompt** (never compressed, so it
263
+ * can make `needsCompaction()` true turn after turn), a nested file arrives as
264
+ * a **message** (compressible, but injected whole at that moment).
265
+ *
266
+ * Equal to the total budget on purpose: no single file may be worth the whole
267
+ * instruction allowance. The head is kept because instruction files put their
268
+ * rules first and their appendices last.
269
+ */
270
+ export const INSTRUCTION_FILE_MAX_CHARS = INSTRUCTION_BUDGET_CHARS
271
+
272
+ /**
273
+ * Keep the head of an oversized instruction file, and say so **in the payload**.
274
+ *
275
+ * A silent cut is the worse option: the model would follow a partial rule set
276
+ * without knowing anything was missing, and the user would see the usual budget
277
+ * notice (or nothing, if the rest of the payload is small). The marker costs a
278
+ * line and makes the truncation visible to both readers.
279
+ */
280
+ export function capInstructionContent(content: string, path: string): string {
281
+ if (content.length <= INSTRUCTION_FILE_MAX_CHARS) return content
282
+ const num = (n: number) => n.toLocaleString('en-US')
283
+ return (
284
+ safeSlice(content, INSTRUCTION_FILE_MAX_CHARS) +
285
+ `\n\n⚠ [truncated] ${path} is ${num(content.length)} characters; only the first ` +
286
+ `${num(INSTRUCTION_FILE_MAX_CHARS)} were loaded. Trim the file, or move doc-only ` +
287
+ 'sections under a `prompt-exclude` frontmatter key.'
288
+ )
289
+ }
290
+
224
291
  /**
225
292
  * The startup notice, or `null` while the payload is within budget.
226
293
  *
@@ -620,27 +687,72 @@ Never omit it or present the work as purely human-authored.`)
620
687
  return { totalChars: files.reduce((n, f) => n + f.chars, 0), files }
621
688
  }
622
689
 
623
- private tryLoad(path: string, level: InstructionFile['level']): void {
624
- 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
+ }
625
713
 
626
- // A repo-controlled instruction file must be a regular file, not a symlink.
627
- // A cloned repository can ship `CLAUDE.md -> ~/.ssh/id_rsa`: this loader runs
628
- // with no permission gate at all, so following the link would put any local
629
- // file into the system prompt without the model ever asking for it. `lstat`
630
- // reports the link as itself, which is what makes the shape visible.
631
- //
632
- // Only the levels that live *inside* the checkout (`project`, `directory`)
633
- // are gated. A symlinked `~/.mipham/USER.md` pointing at a dotfiles repo is
634
- // the user's own arrangement, and the group/company tiers point at the
635
- // surrounding monorepo the user cloned deliberately — refusing those would
636
- // break real setups without closing anything a repo did not already control.
637
- 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
638
735
  try {
639
- 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
640
745
  } catch {
641
- return
746
+ // Unreadable right now: keep the text the session has been running on.
642
747
  }
643
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
644
756
 
645
757
  try {
646
758
  const raw = readFileSync(path, 'utf-8')
@@ -650,7 +762,7 @@ Never omit it or present the work as purely human-authored.`)
650
762
  level,
651
763
  privacy: (data.privacy as InstructionFile['privacy']) || 'project',
652
764
  language: (data.language as string) || 'en-US',
653
- content,
765
+ content: capInstructionContent(content, path),
654
766
  frontmatter: data,
655
767
  })
656
768
  } catch {
@@ -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
+ }
@@ -247,38 +247,145 @@ const LEADING_ASSIGNMENT_RE = /^[A-Za-z_][A-Za-z0-9_]*=/
247
247
  * 不剥尾随符号(`rm -rf x )` 里的 `)`):`wildcardMatch` 的 `*` 已经吃掉它。
248
248
  */
249
249
  export function stripLeadingShellNoise(segment: string): string {
250
- let tokens = segment.trim().split(/\s+/).filter(Boolean)
250
+ const n = segment.length
251
+ let i = 0
251
252
  let stripped = false
252
- let skipFlags = false
253
- for (;;) {
254
- const head = tokens[0]
255
- if (!head) break
256
- if (skipFlags && /^--?[A-Za-z]/.test(head)) {
257
- tokens = tokens.slice(1)
258
- stripped = true
259
- continue
253
+ const skipSpace = (): void => {
254
+ while (i < n && /\s/.test(segment[i]!)) i++
255
+ }
256
+
257
+ /**
258
+ * Consume one `NAME=value`, returning the index just past the value.
259
+ *
260
+ * Splitting on whitespace was the bug: `X="a b" rm …` became the tokens
261
+ * `['X="a', 'b"', 'rm', …]`, so stripping the first "assignment" left
262
+ * `b" rm …` — and the real command vanished from every gate that reads this
263
+ * normalized form (parameterized deny rules, dangerous `rm`, world-writable
264
+ * `chmod`). Values therefore have to be scanned with shell quoting rules,
265
+ * not tokenized by spaces.
266
+ */
267
+ const consumeAssignment = (start: number): number | null => {
268
+ const m = LEADING_ASSIGNMENT_RE.exec(segment.slice(start))
269
+ if (!m) return null
270
+ let j = start + m[0].length
271
+ while (j < n) {
272
+ const c = segment[j]!
273
+ if (/\s/.test(c)) break
274
+ if (c === '\\') {
275
+ j += 2
276
+ continue
277
+ }
278
+ if (c === "'") {
279
+ j++
280
+ while (j < n && segment[j] !== "'") j++
281
+ if (j < n) j++
282
+ continue
283
+ }
284
+ if (c === '"') {
285
+ j++
286
+ while (j < n) {
287
+ if (segment[j] === '\\') {
288
+ j += 2
289
+ continue
290
+ }
291
+ if (segment[j] === '"') {
292
+ j++
293
+ break
294
+ }
295
+ j++
296
+ }
297
+ continue
298
+ }
299
+ if (c === '`') {
300
+ j++
301
+ while (j < n && segment[j] !== '`') {
302
+ if (segment[j] === '\\') j++
303
+ j++
304
+ }
305
+ if (j < n) j++
306
+ continue
307
+ }
308
+ if (c === '$' && segment[j + 1] === '(') {
309
+ j += 2
310
+ let depth = 1
311
+ while (j < n && depth > 0) {
312
+ if (segment[j] === '(') depth++
313
+ else if (segment[j] === ')') depth--
314
+ j++
315
+ }
316
+ continue
317
+ }
318
+ if (c === '$' && segment[j + 1] === '{') {
319
+ j += 2
320
+ while (j < n && segment[j] !== '}') j++
321
+ if (j < n) j++
322
+ continue
323
+ }
324
+ if (c === '(') {
325
+ // Array assignment (`arr=(a b) cmd`): the whole parenthesized list is
326
+ // the value, spaces included.
327
+ let depth = 0
328
+ while (j < n) {
329
+ if (segment[j] === '(') depth++
330
+ else if (segment[j] === ')') {
331
+ depth--
332
+ if (depth === 0) {
333
+ j++
334
+ break
335
+ }
336
+ }
337
+ j++
338
+ }
339
+ continue
340
+ }
341
+ j++
260
342
  }
261
- skipFlags = false
262
- const bare = head.replace(/^[({!]+/, '') // `(!` 这类连写
263
- if (bare !== head) {
264
- tokens = bare ? [bare, ...tokens.slice(1)] : tokens.slice(1)
343
+ return j
344
+ }
345
+
346
+ for (;;) {
347
+ skipSpace()
348
+ if (i >= n) break
349
+ const c = segment[i]!
350
+
351
+ // Grouping / negation punctuation. Consume runs (`(!` / `((`).
352
+ if (LEADING_SHELL_PUNCT.has(c)) {
353
+ i++
265
354
  stripped = true
266
355
  continue
267
356
  }
268
- if (LEADING_SHELL_PUNCT.has(head) || LEADING_ASSIGNMENT_RE.test(head)) {
269
- tokens = tokens.slice(1)
270
- stripped = true
271
- continue
357
+
358
+ const word = /^[A-Za-z_][A-Za-z0-9_]*/.exec(segment.slice(i))?.[0]
359
+ if (word) {
360
+ const after = i + word.length
361
+ const atBoundary = after === n || /\s/.test(segment[after]!)
362
+ if (LEADING_SHELL_KEYWORDS.has(word) && atBoundary) {
363
+ i = after
364
+ stripped = true
365
+ // `time -p rm …` — the keyword's own bare flags are not the command.
366
+ for (;;) {
367
+ skipSpace()
368
+ if (i < n && segment[i] === '-' && /[A-Za-z]/.test(segment[i + 1] ?? '')) {
369
+ while (i < n && !/\s/.test(segment[i]!)) i++
370
+ continue
371
+ }
372
+ break
373
+ }
374
+ continue
375
+ }
272
376
  }
273
- if (LEADING_SHELL_KEYWORDS.has(head)) {
274
- tokens = tokens.slice(1)
377
+
378
+ const assignmentEnd = consumeAssignment(i)
379
+ if (assignmentEnd !== null) {
380
+ i = assignmentEnd
275
381
  stripped = true
276
- skipFlags = true // `time -p rm …` —— 关键字自己的裸 flag 不是命令
277
382
  continue
278
383
  }
384
+
279
385
  break
280
386
  }
281
- return stripped ? tokens.join(' ') : segment
387
+
388
+ return stripped ? segment.slice(i).trim() : segment
282
389
  }
283
390
 
284
391
  function uniq(items: string[]): string[] {
@@ -325,14 +432,19 @@ export function extractBashFileAccess(command: string): BashFileAccess {
325
432
  const read: string[] = []
326
433
  const write: string[] = []
327
434
 
328
- // 1. Redirect targets. Handles `> file` and `>file`, optional fd prefix
329
- // (`2>`, `&>`). Heredocs (`<<`) and fd-dup targets (`2>&1`) are skipped —
330
- // their "target" is a delimiter or file descriptor, not a path.
331
- const redirectRe = /(?:^|[\s;|&])([0-9]*&?)?(>>|<<|<|>)\s*([^\s;|&<>]+)/g
435
+ // 1. Redirect targets. Handles `> file`, `>file`, and the same operators
436
+ // right after a substitution/subshell (`(echo x)>file`, `x=$(date)>file`).
437
+ // Requiring a separator before the operator (the old shape) missed every
438
+ // no-space form, so `Edit(path)`/`Write(path)` deny rules were bypassable
439
+ // with `echo hi>path`. Heredocs (`<<`) and fd-dup targets (`2>&1`) are
440
+ // skipped — their "target" is a delimiter or file descriptor, not a path.
441
+ const redirectRe = /([0-9]*&?)?(>>|<<|<|>)\s*([^\s;|&<>]+)/g
332
442
  let m: RegExpExecArray | null
333
443
  while ((m = redirectRe.exec(command)) !== null) {
334
444
  const op = m[2]!
335
445
  if (op === '<<') continue // heredoc delimiter
446
+ // Process substitution `<(...)` / `>(...)` is not a redirect to a file.
447
+ if (m[3]!.startsWith('(')) continue
336
448
  const target = stripQuotes(m[3]!)
337
449
  if (op === '<') read.push(target)
338
450
  else write.push(target)
@@ -526,6 +638,10 @@ function scanReaderWriterCommands(
526
638
  // `sed -i` / `perl -i` read AND write their file args.
527
639
  const inPlace = args.some((a) => a === '-i' || a.startsWith('--in-place'))
528
640
  for (const arg of args) {
641
+ // Redirection operators are syntax, not paths: `cat < /etc/hosts`
642
+ // already contributed `/etc/hosts` in the redirect pass. Keeping the
643
+ // bare `<` here made it look like a read target of its own.
644
+ if (/^[0-9]*[<>]{1,2}&?[0-9-]*$/.test(arg)) continue
529
645
  if (arg.startsWith('-')) {
530
646
  // `--include=*secret*` / `--file=.env`: the option VALUE is a path the
531
647
  // reader opens, but the `-` guard used to drop the whole token, so a
@@ -155,11 +155,17 @@ export class RemoteEngine {
155
155
 
156
156
  ws.onclose = () => {
157
157
  // Only signal to the generator if there is an active wait.
158
- if (this.resolveNext) {
159
- const doneChunk: StreamChunk = { type: 'stop' }
160
- this.resolveNext(doneChunk)
161
- this.resolveNext = null
162
- }
158
+ if (!this.resolveNext) return
159
+ // 还在等流而连接没了 = 会话进程退出(daemon 停了/被杀),这一轮**没有写完**。
160
+ // 回一个裸 `stop` 会让它在屏幕上与一次正常结束完全同形:用户拿到半截回答,
161
+ // 既不知道被中断,也不知道下一步能做什么。报错并点名恢复动作。
162
+ this.resolveNext({
163
+ type: 'error',
164
+ error:
165
+ 'The daemon stopped — the process running this session has exited, and this turn did not finish. ' +
166
+ `Start it again with "mipham daemon start", then reattach with "mipham attach ${this.sessionId}".`,
167
+ })
168
+ this.resolveNext = null
163
169
  }
164
170
 
165
171
  ws.onerror = () => {