@miphamai/cli 0.85.17 → 0.85.19

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 (40) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/src/agent/sub-agent.ts +11 -0
  4. package/src/agent/types.ts +8 -0
  5. package/src/agent-view/agent-view-manager.ts +50 -0
  6. package/src/config/defaults.ts +6 -1
  7. package/src/core/credential-masker/output-scrub.ts +8 -1
  8. package/src/core/engine.ts +88 -9
  9. package/src/core/instructions.ts +97 -2
  10. package/src/core/permission-rules.ts +52 -4
  11. package/src/core/permission.ts +6 -2
  12. package/src/core/session-log.ts +10 -0
  13. package/src/daemon/channel-message.ts +8 -1
  14. package/src/daemon/session-worker.ts +17 -2
  15. package/src/i18n-core/locales/en-US.json +4 -2
  16. package/src/i18n-core/locales/zh-CN.json +4 -2
  17. package/src/index.tsx +22 -1
  18. package/src/mcp/client.ts +20 -1
  19. package/src/mcp/http-transport.ts +48 -3
  20. package/src/mcp/instructions.ts +25 -1
  21. package/src/mcp/protocol.ts +69 -2
  22. package/src/providers/anthropic.ts +47 -12
  23. package/src/providers/fetch-utils.ts +72 -4
  24. package/src/providers/openai-compat.ts +13 -10
  25. package/src/shared/package-info.ts +2 -2
  26. package/src/shared/types.ts +12 -0
  27. package/src/skills/loader.ts +13 -2
  28. package/src/skills/sanitizer.ts +16 -8
  29. package/src/tools/agent/agent.ts +24 -0
  30. package/src/tools/agent/skill.ts +13 -0
  31. package/src/tools/artifact/artifact.ts +9 -9
  32. package/src/tools/exec/bash.ts +10 -0
  33. package/src/tools/file/grep.ts +11 -2
  34. package/src/tools/file/read.ts +21 -0
  35. package/src/tools/network/web-fetch.ts +87 -22
  36. package/src/tools/scheduling/schedule-wakeup.ts +156 -32
  37. package/src/ui/app.tsx +47 -6
  38. package/src/ui/chat.tsx +15 -1
  39. package/src/ui/input.tsx +25 -1
  40. package/src/workflow/primitives/agent.ts +1 -0
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # Mipham Code v0.85.17
1
+ # Mipham Code v0.85.19
2
2
 
3
3
  **Multi-model open-core intelligent coding terminal** — 12 AI providers, 137 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,6 +1,6 @@
1
1
  {
2
2
  "name": "@miphamai/cli",
3
- "version": "0.85.17",
3
+ "version": "0.85.19",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -491,6 +491,13 @@ export class SubAgent {
491
491
  // (`ui/app.tsx`) and the experience logs below: the definition's name, else
492
492
  // the type.
493
493
  agentName: agentDef?.name || agentType,
494
+ // Artifacts need a bucket of their own. `sessionId` is the shared literal
495
+ // 'sub-agent' (kept — `SendMessage` addresses the parent off it), so every
496
+ // sub-agent in every session would file artifacts in one directory and
497
+ // `archiveVersion` would treat another agent's same-named artifact as the
498
+ // "previous version" of this one. Parent session plus this agent's name
499
+ // keeps two agents apart without touching the messaging contract.
500
+ artifactSessionId: `${options.toolContext?.sessionId ?? 'main'}:sub:${agentDef?.name || agentType}`,
494
501
  }
495
502
 
496
503
  try {
@@ -514,6 +521,10 @@ export class SubAgent {
514
521
  systemPrompt: currentSystemPrompt,
515
522
  tools: toolDefs,
516
523
  maxTokens: 4096,
524
+ // Scales the provider's streaming idle timeout (fetch-utils
525
+ // `streamIdleTimeoutMs`). Omitted ⇒ 1× base, so a caller that asked for
526
+ // a high-effort sub-agent would otherwise get the default budget.
527
+ effort: options.effort,
517
528
  })) {
518
529
  // Check abort signal mid-stream
519
530
  if (signal?.aborted) {
@@ -43,6 +43,14 @@ export interface SubAgentOptions {
43
43
  systemPrompt?: string
44
44
  allowedTools?: string[]
45
45
  modelOverride?: string
46
+ /**
47
+ * Reasoning effort (`low|medium|high|xhigh|max`) for this run, matching the
48
+ * session-level level `/effort` sets. Threaded into the provider request as
49
+ * `ChatRequest.effort`, where it scales the streaming idle timeout — a
50
+ * sub-agent left at the default would inherit the base timeout regardless of
51
+ * the level the caller asked for.
52
+ */
53
+ effort?: string
46
54
  /** Maximum tool-calling turns (default: 5) to prevent infinite loops. */
47
55
  maxTurns?: number
48
56
  /** When true, execute in background and return immediately with a task ID. */
@@ -126,6 +126,56 @@ export class AgentViewManager {
126
126
  return session
127
127
  }
128
128
 
129
+ /**
130
+ * Mirror background-agent tasks into the panel, and return how many rows were
131
+ * added.
132
+ *
133
+ * Rows created by `/bg` and `/fork` used to be the only ones that existed. The
134
+ * Agent tool — whose sub-agents are **background by default** — registers them
135
+ * with the background registry and nothing else, so the ordinary way to fan out
136
+ * work produced no panel rows at all: the pane stayed empty the whole time the
137
+ * agents ran, which a viewer cannot tell apart from "nothing was spawned".
138
+ *
139
+ * Keyed on the registry's task id. `/bg` and `/fork` already link their row
140
+ * through `session.taskId`, so those are matched and updated rather than
141
+ * duplicated; anything else is a task this panel has not seen.
142
+ *
143
+ * Status is a projection, not a source: the registry owns it, and a row whose
144
+ * status disagrees with the registry is corrected here on the next round.
145
+ */
146
+ syncBackgroundTasks(
147
+ tasks: ReadonlyArray<{ id: string; description: string; status: string }>,
148
+ ): number {
149
+ const byTaskId = new Map<string, AgentSession>()
150
+ for (const id of this.sessionOrder) {
151
+ const session = this.sessions.get(id)
152
+ if (session?.taskId) byTaskId.set(session.taskId, session)
153
+ }
154
+
155
+ let added = 0
156
+ for (const task of tasks) {
157
+ const status: SessionStatus =
158
+ task.status === 'running' ? 'working' : task.status === 'failed' ? 'failed' : 'completed'
159
+
160
+ const existing = byTaskId.get(task.id)
161
+ if (existing) {
162
+ if (existing.status !== status) this.updateStatus(existing.id, status)
163
+ continue
164
+ }
165
+
166
+ const session = this.create(task.description, task.description)
167
+ session.taskId = task.id
168
+ // Not `interactive`: nobody is steering this row, and the dashboard's
169
+ // grouping keys off the kind as well as the status.
170
+ session.kind = 'unattended'
171
+ this.updateStatus(session.id, status)
172
+ byTaskId.set(task.id, session)
173
+ added++
174
+ }
175
+
176
+ return added
177
+ }
178
+
129
179
  /**
130
180
  * List all sessions in creation order (newest first).
131
181
  */
@@ -72,8 +72,13 @@ export const DEFAULT_CREDENTIAL_MASKING_CONFIG: CredentialMaskingConfig = {
72
72
  // 名字那一段:`_key` 出现在标识符**中间**也算(`AWS_ACCESS_KEY_ID=…`),但**不许吞掉
73
73
  // 词后面的字符** —— 否则 `"keys": […]`、`total tokens: 1234` 这类**不是秘密**的输出
74
74
  // 会被整段擦掉。中间那对引号可选,为的是 JSON 形状的 `"apiKey": "…"`。
75
+ //
76
+ // 环绕 `[_-]key` 的两段量词**有界**(`{0,64}`),且这个界是承重的,不是装饰。无界的
77
+ // `[A-Za-z0-9_.-]*` 后面跟着必须匹配的 `[_-]key` 时,在一段没有 `_` 的长串(`keykey…`、
78
+ // 一段长 token)上会在每个起点回溯扫过整条尾巴,退化成 O(n²)(实测 16k 字符 ~2.2s,
79
+ // 每翻倍 ×4)。真实标识符名字远到不了 64 字符,加界零代价,却让每个起点的扫描变成线性。
75
80
  patterns: [
76
- '(?i)(api[_-]?key|[A-Za-z0-9_.-]*[_-]key[A-Za-z0-9_.-]*|secret|token|password|credential|[_-]pat)["\']?\\s*[:=]\\s*["\']?\\S+',
81
+ '(?i)(api[_-]?key|[A-Za-z0-9_.-]{0,64}[_-]key[A-Za-z0-9_.-]{0,64}|secret|token|password|credential|[_-]pat)["\']?\\s*[:=]\\s*["\']?\\S+',
77
82
  ],
78
83
  },
79
84
  env_filter: {
@@ -25,7 +25,14 @@ const TOKEN_REDACTION_PATTERN =
25
25
  // *first* `@`, redacting only `p` and leaving `ss@host` in the clear. Greedy
26
26
  // `[^/\s]+` runs to the last `@` on the line and backtracks, so the whole password
27
27
  // goes and the host survives.
28
- const URL_USERINFO_PATTERN = /([a-z][a-z0-9+.-]*:\/\/)([^/\s:@]+):([^/\s]+)@/gi
28
+ //
29
+ // The scheme's `*` is **bounded** (`{0,63}`), and that bound is load-bearing, not
30
+ // cosmetic. An unbounded `[a-z0-9+.-]*` followed by a required `://` re-scans the
31
+ // whole tail from every start position on a long run with no `://` (minified JS,
32
+ // base64, a long token — none of which contain `://`), giving O(n²) behaviour:
33
+ // measured ~2.5 s at 40 k chars, ×4 per doubling. No real scheme name approaches
34
+ // 63 chars, so the bound costs nothing and makes the scan linear per position.
35
+ const URL_USERINFO_PATTERN = /([a-z][a-z0-9+.-]{0,63}:\/\/)([^/\s:@]+):([^/\s]+)@/gi
29
36
 
30
37
  /**
31
38
  * Zero-width and formatting characters stripped before anything is matched.
@@ -23,6 +23,7 @@ import type { AgentViewManager } from '../agent-view/agent-view-manager'
23
23
  import type { Skills } from '../skills/seam'
24
24
  import { getBackgroundAgentRegistry } from '../agent/background-registry'
25
25
  import { RulesLoader } from './rules-loader'
26
+ import { extractBashFileAccess } from './permission-rules'
26
27
  import type { InstructionsLoader } from './instructions'
27
28
  import { ExperienceRuleEngine } from './rule-engine.js'
28
29
  import { PatternAnalyzer } from '../agent/pattern-analyzer.js'
@@ -406,6 +407,19 @@ export class QueryEngine {
406
407
 
407
408
  /** Track files touched by tools for rules matching. */
408
409
  private trackTouchedFile(toolName: string, params: Record<string, unknown>): void {
410
+ if (toolName === 'Bash') {
411
+ // A single-file `cat`/`head`/`sed -n`/`grep` reads the same file the Read
412
+ // tool would, so the rules scoped to it have to see that path too. Reuses
413
+ // the extractor the permission layer already runs for Bash↔Read/Write rule
414
+ // bridging rather than a second, drifting spelling of "which paths did this
415
+ // command touch" — it already covers redirects, `$()`/backtick
416
+ // substitutions, `bash -c` payloads and `~`/`$HOME` expansion.
417
+ const command = params.command
418
+ if (typeof command !== 'string') return
419
+ const access = extractBashFileAccess(command)
420
+ for (const p of [...access.read, ...access.write]) this.touchedFiles.add(p)
421
+ return
422
+ }
409
423
  const fileTools = ['Read', 'Write', 'Edit', 'Glob', 'Grep']
410
424
  if (!fileTools.includes(toolName)) return
411
425
  const filePath = (params.file_path || params.path || params.file) as string | undefined
@@ -414,14 +428,32 @@ export class QueryEngine {
414
428
  }
415
429
  }
416
430
 
417
- /** Inject matching rules as context after tool execution. */
431
+ /**
432
+ * Inject path-scoped context for the files touched this round: matching rules
433
+ * (`.mipham/rules/*.md`) and any nested instruction files (`CLAUDE.md` and
434
+ * friends) that were not part of the startup chain.
435
+ *
436
+ * Both halves ride the same trigger on purpose — a rule file and a nested
437
+ * `CLAUDE.md` are the same kind of thing (the loader labels the level
438
+ * "Directory Rules"), and a path that activates one almost always activates
439
+ * the other. They also share the call-timing constraint below.
440
+ *
441
+ * Must run **after** every `tool_result` of the round has been appended:
442
+ * `injectContext` pushes a user message, and landing it between an assistant
443
+ * `tool_use` and its paired user `tool_result` breaks the pairing.
444
+ */
418
445
  private injectRules(): void {
419
- if (!this.rulesLoader || this.touchedFiles.size === 0) return
446
+ if (this.touchedFiles.size === 0) return
420
447
  const files = Array.from(this.touchedFiles)
421
- const block = this.rulesLoader.buildContextBlock(files)
422
- if (!block) return
423
- this.context.injectContext('rules', block)
424
448
  this.touchedFiles.clear()
449
+
450
+ if (this.rulesLoader) {
451
+ const block = this.rulesLoader.buildContextBlock(files)
452
+ if (block) this.context.injectContext('rules', block)
453
+ }
454
+
455
+ const nested = this.instructionsLoader?.loadForPaths(files, process.cwd())
456
+ if (nested) this.context.injectContext('directory-rules', nested)
425
457
  }
426
458
 
427
459
  /**
@@ -459,6 +491,14 @@ export class QueryEngine {
459
491
  const tasks = bgRegistry.list()
460
492
  const chunks: StreamChunk[] = []
461
493
 
494
+ // Mirror every background task into Agent View — including the running ones,
495
+ // which the loop below deliberately skips. The panel previously carried only
496
+ // `/bg` and `/fork` rows, so a background sub-agent spawned by the Agent tool
497
+ // (the default) was invisible in it for its whole lifetime. Projecting from
498
+ // the registry rather than from each spawn site means every present and future
499
+ // producer is covered by one call.
500
+ this.agentViewManager?.syncBackgroundTasks(tasks)
501
+
462
502
  for (const task of tasks) {
463
503
  if (task.status === 'running') continue
464
504
 
@@ -608,6 +648,16 @@ export class QueryEngine {
608
648
  // Add user message to context
609
649
  this.context.addMessage({ role: 'user', content: userInput })
610
650
 
651
+ // ── Restore point for `/rewind` ──
652
+ // Taken **here** — the prompt is in history, none of the reply is. That is what
653
+ // makes `/rewind` ("Undo last AI turn") mean what it says: the prompt survives,
654
+ // the answer and its tool results go. A checkpoint taken at the *end* of a turn
655
+ // already contains that turn's reply, so restoring it is a no-op and nothing
656
+ // but an older turn is reachable. One site covers every entry point — the TUI,
657
+ // `/loop` turns, goal mode (`processWithGoal` delegates here) and daemon
658
+ // sessions — so no caller can be the one that forgot.
659
+ this.context.saveCheckpoint('pre-turn')
660
+
611
661
  // Check compaction before processing
612
662
  if (this.context.needsCompaction()) {
613
663
  await this.compactWithHooks('conversation summary')
@@ -971,12 +1021,20 @@ export class QueryEngine {
971
1021
  ): AsyncGenerator<StreamChunk> {
972
1022
  // Task-level stall guard: a turn that produces no text or tool result for
973
1023
  // this long is considered stalled and stopped (prevents ~40-min idle spins).
1024
+ //
1025
+ // The clock is `performance.now()` (monotonic, and it does not advance while
1026
+ // the machine is suspended) rather than `Date.now()` (wall clock). A laptop
1027
+ // that sleeps mid-turn jumps the wall clock forward by the whole nap, which
1028
+ // reads as "no activity for 8 hours" and kills a turn that was never stalled
1029
+ // — the failure shows up as a spurious timeout, exactly when the user
1030
+ // returns to their desk.
974
1031
  const TURN_TIMEOUT_MS = 15 * 60 * 1000
975
- let lastActivity = Date.now()
1032
+ const monotonicNow = (): number => performance.now()
1033
+ let lastActivity = monotonicNow()
976
1034
  const toolDefs = this.getToolDefinitions()
977
1035
 
978
1036
  for (let turn = 0; turn < roundsLeft; turn++) {
979
- if (Date.now() - lastActivity > TURN_TIMEOUT_MS) {
1037
+ if (monotonicNow() - lastActivity > TURN_TIMEOUT_MS) {
980
1038
  yield {
981
1039
  type: 'warning',
982
1040
  content: t('errors.turn_timeout', {
@@ -1038,7 +1096,7 @@ export class QueryEngine {
1038
1096
  if (chunk.type === 'text' && chunk.content) {
1039
1097
  assistantContent += chunk.content
1040
1098
  this.context.recordChunk(chunk.content)
1041
- lastActivity = Date.now()
1099
+ lastActivity = monotonicNow()
1042
1100
  }
1043
1101
 
1044
1102
  if (chunk.reasoning_content) {
@@ -1138,7 +1196,7 @@ export class QueryEngine {
1138
1196
  for (const toolUse of toolUses) {
1139
1197
  const result = await this.executeTool(toolUse.name, toolUse.input, signal)
1140
1198
  if (!result.success) this.pendingToolFailure = true
1141
- lastActivity = Date.now()
1199
+ lastActivity = monotonicNow()
1142
1200
  yield {
1143
1201
  type: 'tool_result',
1144
1202
  tool_use_id: toolUse.id,
@@ -1353,6 +1411,27 @@ export class QueryEngine {
1353
1411
  }
1354
1412
  }
1355
1413
 
1414
+ // The gate at the top of this method ruled on `params`. Everything since —
1415
+ // the PreToolUse hook's `modifiedInput`, the CRSI RuleEngine's `modified`, the
1416
+ // SIS preflight `fix` — can rewrite the params the tool actually receives
1417
+ // (`effectiveParams`), and the tool runs on those. A gate that ruled on input
1418
+ // X must not stand as the gate for input Y: a repository-supplied hook could
1419
+ // pass a benign call and swap in a destructive one *after* the check, and the
1420
+ // substitution would never be re-judged. Whenever any stage changed the
1421
+ // params, run the same approval resolution again on what will actually run.
1422
+ // (This mirrors the correct order in `agent/sub-agent.ts`: hook → apply
1423
+ // `modifiedInput` → resolve approval on the effective input.)
1424
+ if (effectiveParams !== params) {
1425
+ const recheck = await this.permission.resolveApproval(tool, effectiveParams, { signal })
1426
+ if (recheck.level === 'ask') {
1427
+ return {
1428
+ success: false,
1429
+ content: '',
1430
+ error: this.buildDenialError(name, tool, effectiveParams, recheck),
1431
+ }
1432
+ }
1433
+ }
1434
+
1356
1435
  try {
1357
1436
  // Every tool is handed the session's working directory, and that directory
1358
1437
  // can be deleted while the session runs. Nothing upstream notices: Node
@@ -1,5 +1,5 @@
1
- import { readFileSync, existsSync } from 'node:fs'
2
- import { join, resolve, relative, sep, isAbsolute } from 'node:path'
1
+ import { readFileSync, existsSync, lstatSync, statSync } from 'node:fs'
2
+ import { join, resolve, relative, sep, isAbsolute, dirname } from 'node:path'
3
3
  import { execSync } from 'node:child_process'
4
4
  import { parse as parseYaml } from 'yaml'
5
5
  import type { InstructionFile } from '../shared/index.ts'
@@ -84,6 +84,12 @@ export function gitRoot(cwd: string): string {
84
84
  }
85
85
  }
86
86
 
87
+ /** True when `p` is `root` itself or sits underneath it. */
88
+ function isInside(root: string, p: string): boolean {
89
+ const rel = relative(root, p)
90
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
91
+ }
92
+
87
93
  /** 从仓库根到 cwd 的目录链(含两端),就近(cwd)在最后。cwd 不在 root 下时退化为 [cwd]。 */
88
94
  export function discoverDirectories(root: string, cwd: string): string[] {
89
95
  const absRoot = resolve(root)
@@ -252,11 +258,14 @@ export class InstructionsLoader {
252
258
  private instructions: InstructionFile[] = []
253
259
  private crsiLessonSummaries: CrsiLessonSummary[] = []
254
260
  private lessonsPath: string | null = null
261
+ /** Checkout root resolved at `loadAll`, reused by `loadForPaths`. */
262
+ private root: string | null = null
255
263
 
256
264
  loadAll(cwd: string): void {
257
265
  this.instructions = []
258
266
  this.lessonsPath = null
259
267
  const root = gitRoot(cwd)
268
+ this.root = root
260
269
 
261
270
  // Tier 1: 集团/公司策略(锚定仓库根,从任意子目录启动都正确;不读 AGENTS.md)
262
271
  this.tryLoad(join(root, '..', '..', 'CLAUDE.md'), 'group') // Rismed_Ronxin_Capital
@@ -522,6 +531,73 @@ Never omit it or present the work as purely human-authored.`)
522
531
  return [...this.instructions]
523
532
  }
524
533
 
534
+ /**
535
+ * Load the instruction files of the directories a path the model just looked at
536
+ * lives under, and return the text of whatever was **not** already loaded.
537
+ *
538
+ * The baseline chain is git-root → cwd, walked once at startup (`loadAll`). A
539
+ * file deeper than cwd (`src/parser/lex.ts`) or on a sibling branch therefore
540
+ * contributes nothing — even though the `CLAUDE.md` sitting next to it is
541
+ * precisely the rule set that governs it. Upstream reported the Bash half of
542
+ * this (`cat`/`head`/`sed -n`/`grep` on a single file skipped its rules); the
543
+ * Read tool had the same hole, so the gate here is the **path**, not the tool
544
+ * that produced it: "did the model see a file here".
545
+ *
546
+ * Only directories inside the checkout are considered. The tiers above it are
547
+ * anchored deliberately (`loadAll`), and walking the ancestors of, say,
548
+ * `/etc/hosts` would pull arbitrary local files into the prompt on the strength
549
+ * of a command — so an outside path contributes nothing by construction.
550
+ * Directories already visited cost one `existsSync` per candidate name.
551
+ *
552
+ * Returns `null` when nothing new was loaded, so callers can skip an empty
553
+ * injection. Text goes through `instructionPartText` — the same projection the
554
+ * system prompt uses — so `privacy: private` and `prompt-exclude` are honored
555
+ * here too, and the two cannot drift.
556
+ */
557
+ loadForPaths(paths: Iterable<string>, cwd: string): string | null {
558
+ // Reused rather than re-resolved: `gitRoot` spawns `git rev-parse`, and this
559
+ // runs on the tool-execution path once per round. The fallback keeps the
560
+ // method correct for a caller that never ran `loadAll`.
561
+ const root = this.root ?? resolve(gitRoot(cwd))
562
+ const loaded = new Set(this.instructions.map((f) => f.path))
563
+ const added: InstructionFile[] = []
564
+
565
+ for (const raw of paths) {
566
+ let dir = resolve(cwd, raw)
567
+ if (!isInside(root, dir)) continue
568
+ // A touched path is a directory when the tool searched one (Grep's root,
569
+ // Glob) and a file otherwise. A path that does not exist yet is treated as
570
+ // a file, which is the right reading for `Write` on a new path.
571
+ try {
572
+ if (!statSync(dir).isDirectory()) dir = dirname(dir)
573
+ } catch {
574
+ dir = dirname(dir)
575
+ }
576
+
577
+ for (;;) {
578
+ for (const name of INSTRUCTION_FILENAMES) {
579
+ const file = join(dir, name)
580
+ if (loaded.has(file)) continue
581
+ loaded.add(file)
582
+ this.tryLoad(file, 'directory')
583
+ const loadedFile = this.instructions[this.instructions.length - 1]
584
+ if (loadedFile?.path === file) added.push(loadedFile)
585
+ }
586
+ if (dir === root) break
587
+ const parent = dirname(dir)
588
+ if (parent === dir) break
589
+ dir = parent
590
+ }
591
+ }
592
+
593
+ const parts: string[] = []
594
+ for (const inst of added) {
595
+ const text = instructionPartText(inst)
596
+ if (text) parts.push(text)
597
+ }
598
+ return parts.length > 0 ? parts.join('\n\n---\n\n') : null
599
+ }
600
+
525
601
  /**
526
602
  * How much instruction text this loader puts in the system prompt, per file.
527
603
  *
@@ -547,6 +623,25 @@ Never omit it or present the work as purely human-authored.`)
547
623
  private tryLoad(path: string, level: InstructionFile['level']): void {
548
624
  if (!existsSync(path)) return
549
625
 
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') {
638
+ try {
639
+ if (lstatSync(path).isSymbolicLink()) return
640
+ } catch {
641
+ return
642
+ }
643
+ }
644
+
550
645
  try {
551
646
  const raw = readFileSync(path, 'utf-8')
552
647
  const { data, content } = parseFrontmatter(raw)
@@ -202,7 +202,19 @@ function stripQuotes(s: string): string {
202
202
  /** Shell 结构符号:分组与取反 —— 它们自身不是命令,紧跟其后的是。 */
203
203
  const LEADING_SHELL_PUNCT = new Set(['(', '{', '!'])
204
204
 
205
- /** Shell 关键字:其后才是真正的命令(`do rm -rf x` 执行的命令是 `rm`)。 */
205
+ /**
206
+ * Shell 关键字:其后才是真正的命令(`do rm -rf x` 执行的命令是 `rm`)。
207
+ *
208
+ * **`export` / `declare` / `readonly` / `typeset` 刻意不在表里**,尽管它们同样出现在
209
+ * 命令前。区别在语义:一条裸赋值把这段环境交给**后面的命令**,而这四个是 bash 内建
210
+ * **命令本身**,其后的词全是它的参数 —— `export FOO=1 rm -rf x` 执行的是 `export`,
211
+ * `rm` 一次都不跑(本机实测,用 victim 文件作判据:`X=1 rm -f victim` 删掉了 victim;
212
+ * `export`/`declare`/`readonly`/`typeset` 四种写法 victim 全在,只有 "not a valid
213
+ * identifier" 的报错)。剥掉它们不会补上漏洞,只会让匹配器声称一条**没跑过**的命令
214
+ * 在跑。命令替换形态(`export FOO=$(rm -rf x)`)由 `extractSubstitutions` 覆盖,
215
+ * 与这四个词在不在表里无关。边界用例见 `test/core/permission-rules.test.ts`
216
+ * 「前导赋值的边界」。
217
+ */
206
218
  const LEADING_SHELL_KEYWORDS = new Set([
207
219
  'do',
208
220
  'then',
@@ -514,14 +526,34 @@ function scanReaderWriterCommands(
514
526
  // `sed -i` / `perl -i` read AND write their file args.
515
527
  const inPlace = args.some((a) => a === '-i' || a.startsWith('--in-place'))
516
528
  for (const arg of args) {
517
- if (arg.startsWith('-')) continue
529
+ if (arg.startsWith('-')) {
530
+ // `--include=*secret*` / `--file=.env`: the option VALUE is a path the
531
+ // reader opens, but the `-` guard used to drop the whole token, so a
532
+ // Read() deny rule never saw it. Pull the value after the first `=`
533
+ // and treat it as a path candidate. (`--opt value` needs nothing here
534
+ // — the value is already a separate, non-`-` token handled below.)
535
+ const eq = arg.indexOf('=')
536
+ if (eq === -1) continue
537
+ const v = stripQuotes(arg.slice(eq + 1))
538
+ if (v === '' || v.startsWith('-')) continue
539
+ read.push(v)
540
+ if (inPlace) write.push(v)
541
+ continue
542
+ }
518
543
  const p = stripQuotes(arg)
519
544
  read.push(p)
520
545
  if (inPlace) write.push(p)
521
546
  }
522
547
  } else if (WRITER_COMMANDS.has(base)) {
523
548
  for (const arg of args) {
524
- if (arg.startsWith('-')) continue
549
+ if (arg.startsWith('-')) {
550
+ const eq = arg.indexOf('=')
551
+ if (eq === -1) continue
552
+ const v = stripQuotes(arg.slice(eq + 1))
553
+ if (v === '' || v.startsWith('-')) continue
554
+ write.push(v)
555
+ continue
556
+ }
525
557
  write.push(stripQuotes(arg))
526
558
  }
527
559
  }
@@ -637,7 +669,14 @@ function matchPathRule(path: string, pattern: string, segmentMode: 'any' | 'all'
637
669
  }
638
670
  }
639
671
 
640
- // Match a tool(parameter) rule against an actual tool call.
672
+ /**
673
+ * A reader/writer argument that still carries shell wildcards is **unresolved**:
674
+ * the shell expands it to a file set the extracted token does not name. Used to
675
+ * fail a deny/ask rule closed rather than let the anchored path match miss it.
676
+ */
677
+ function hasGlobMeta(path: string): boolean {
678
+ return /[*?[\]]/.test(path)
679
+ }
641
680
  //
642
681
  // Pattern formats:
643
682
  // "Bash" → matches any Bash call
@@ -684,6 +723,15 @@ export function matchBashRule(
684
723
  const cmd = String(toolInput.command || '')
685
724
  const access = extractBashFileAccess(cmd)
686
725
  const paths = baseTool === 'Read' ? access.read : access.write
726
+ // A shell glob in a reader/writer argument expands to an unknown file set —
727
+ // `cat *secret*` reads files the literal argument `*secret*` does not name —
728
+ // so the anchored path match below would miss a `Read(**/secret*)` deny
729
+ // entirely. Fail closed: under deny/ask (`'any'`) an unresolved glob counts
730
+ // as a match (refuse). Under allow (`'all'`) a glob path cannot satisfy a
731
+ // concrete grant anyway, so the grant direction already fails closed. This
732
+ // is deliberately blunt — one extra ask beats reading a file a deny rule was
733
+ // written to protect.
734
+ if (segmentMode !== 'all' && paths.some(hasGlobMeta)) return true
687
735
  return qualifies(paths, (p) => matchPathRule(p, subPattern!, segmentMode))
688
736
  }
689
737
 
@@ -47,8 +47,12 @@ function isVerificationCommand(input: Record<string, unknown>): boolean {
47
47
  const cmd = (input.command as string) || ''
48
48
  // A verification command must be a single simple command — any shell
49
49
  // metacharacter (&&, ;, |, >, <, backtick, $) means it can chain a destructive
50
- // action (e.g. `cat x && rm -rf ~`), so never auto-approve it.
51
- if (/[;&|><`$]/.test(cmd)) return false
50
+ // action (e.g. `cat x && rm -rf ~`), so never auto-approve it. A shell
51
+ // wildcard (`*`, `?`, `[`, `]`) is refused for the same reason: the shell
52
+ // expands it to a file set the rule-matcher never saw, so `cat *secret*` is
53
+ // not `cat secret` — auto-approving it would read files a `Read(...)` rule
54
+ // means to protect.
55
+ if (/[;&|><`$*?\[\]]/.test(cmd)) return false
52
56
  // Patterns for verification-only commands (no side effects on codebase)
53
57
  const verifyPatterns = [
54
58
  /\bpnpm\s+test\b/, // test runner
@@ -14,6 +14,16 @@ export type SessionEvent =
14
14
  provider?: string
15
15
  model?: string
16
16
  cwd?: string
17
+ /**
18
+ * The permission mode this session started in.
19
+ *
20
+ * Not reconstructible from the transcript: the same tool call appears in
21
+ * the log whether it was auto-approved or approved by hand, so a resumed
22
+ * session could not tell which gate it was running under. Recorded here so
23
+ * `--resume` can put the mode back instead of silently dropping to the
24
+ * config default (plan mode in particular was lost on every resume).
25
+ */
26
+ permissionMode?: string
17
27
  }
18
28
  | { type: 'user/message'; at: number; message: Message }
19
29
  | { type: 'assistant/message'; at: number; message: Message }
@@ -45,7 +45,14 @@ export async function handleChannelMessage(opts: ChannelMessageOptions): Promise
45
45
  await sendText(externalId, '(会话初始化失败,请稍后重试)')
46
46
  return
47
47
  }
48
- await worker.processPrompt(text)
48
+ const outcome = await worker.processPrompt(text)
49
+ // A `busy` outcome means this turn never ran — the concurrency guard refused
50
+ // it. Reading `getLastAssistantContent()` here would replay the *previous*
51
+ // turn's reply as if it answered the message just sent, so say what happened.
52
+ if (!outcome.ok) {
53
+ await sendText(externalId, '(上一条消息仍在处理中,请稍候再发)')
54
+ return
55
+ }
49
56
  const result = worker.getLastAssistantContent()
50
57
  await sendText(externalId, result ? result.slice(0, maxLen) : '(无回复)')
51
58
  } catch (err) {
@@ -51,6 +51,19 @@ export interface SessionStateSnapshot {
51
51
  permissionMode: PermissionMode
52
52
  }
53
53
 
54
+ // ── Prompt-processing outcome ─────────────────────────────────────────────
55
+
56
+ /**
57
+ * Result of a `processPrompt` call.
58
+ *
59
+ * `busy` is *reported*, not swallowed. A second message arriving mid-turn used to
60
+ * fall out of the concurrency guard — which only broadcasts to WS viewers — and
61
+ * then be answered by the caller with `getLastAssistantContent()`, i.e. the
62
+ * *previous* turn's reply. The user got an answer to a question they had not
63
+ * asked. Naming the refusal lets the channel say "still working" instead.
64
+ */
65
+ export type ProcessPromptResult = { ok: true } | { ok: false; reason: 'busy' }
66
+
54
67
  // ── SessionWorker ─────────────────────────────────────────────────────────
55
68
 
56
69
  export class SessionWorker {
@@ -110,10 +123,10 @@ export class SessionWorker {
110
123
  * 7. On interrupt: save partial content, broadcast `done` with stop_reason
111
124
  * 'interrupted'
112
125
  */
113
- async processPrompt(prompt: string): Promise<void> {
126
+ async processPrompt(prompt: string): Promise<ProcessPromptResult> {
114
127
  if (this.processing) {
115
128
  this.broadcast(this.errorMessage('A prompt is already being processed'))
116
- return
129
+ return { ok: false, reason: 'busy' }
117
130
  }
118
131
 
119
132
  this.processing = true
@@ -215,6 +228,8 @@ export class SessionWorker {
215
228
 
216
229
  this.currentController = null
217
230
  this.processing = false
231
+
232
+ return { ok: true }
218
233
  }
219
234
 
220
235
  // ── Interrupt ──────────────────────────────────────────────────────────