@miphamai/cli 0.85.43 → 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.43
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.43",
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` 已经拿**含记忆**的
@@ -832,6 +832,9 @@ export class QueryEngine {
832
832
  let assistantContent = ''
833
833
  let reasoningContent = ''
834
834
  let thinkingContent = ''
835
+ // 本轮为什么被截断。`'max_tokens'` 可续写,`'connection'`/未知不可 —— 见
836
+ // `continueMaxTokensTurn`。
837
+ let truncationCause: 'max_tokens' | 'connection' | undefined
835
838
  let turnApiInputTokens = 0
836
839
  let turnApiOutputTokens = 0
837
840
  const turnStart = Date.now()
@@ -859,6 +862,7 @@ export class QueryEngine {
859
862
  reasoningContent = ''
860
863
  thinkingContent = ''
861
864
  toolUses.length = 0
865
+ truncationCause = undefined
862
866
  // Usage is part of "everything": a provider reports tokens as the
863
867
  // stream runs, so the attempt that failed had already added its
864
868
  // share before `restart` arrived. Keeping it charges the retried
@@ -904,6 +908,25 @@ export class QueryEngine {
904
908
  turnApiInputTokens += chunk.inputTokens
905
909
  turnApiOutputTokens += chunk.outputTokens || 0
906
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
+ }
907
930
  }
908
931
 
909
932
  // Commit the assistant turn **once, after the stream** — not on each `stop`
@@ -1304,6 +1327,7 @@ export class QueryEngine {
1304
1327
  let assistantContent = ''
1305
1328
  let reasoningContent = ''
1306
1329
  let thinkingContent = ''
1330
+ let truncationCause: 'max_tokens' | 'connection' | undefined
1307
1331
  const toolUses: Array<{ id: string; name: string; input: Record<string, unknown> }> = []
1308
1332
 
1309
1333
  try {
@@ -1325,6 +1349,7 @@ export class QueryEngine {
1325
1349
  reasoningContent = ''
1326
1350
  thinkingContent = ''
1327
1351
  toolUses.length = 0
1352
+ truncationCause = undefined
1328
1353
  }
1329
1354
  if (chunk.type === 'error') return
1330
1355
  if (chunk.type === 'text' && chunk.content) {
@@ -1348,6 +1373,10 @@ export class QueryEngine {
1348
1373
  input: chunk.toolUse.input,
1349
1374
  })
1350
1375
  }
1376
+
1377
+ if (chunk.type === 'stop' && chunk.truncated) {
1378
+ truncationCause = chunk.truncationCause ?? 'connection'
1379
+ }
1351
1380
  }
1352
1381
  } catch (err) {
1353
1382
  if (isAbortError(err)) {
@@ -1373,6 +1402,18 @@ export class QueryEngine {
1373
1402
  return
1374
1403
  }
1375
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
+
1376
1417
  if (assistantContent || reasoningContent || thinkingContent) {
1377
1418
  const contentBlocks: import('../shared/types').ContentBlock[] = []
1378
1419
  if (thinkingContent) {
@@ -1692,12 +1733,18 @@ export class QueryEngine {
1692
1733
  }
1693
1734
 
1694
1735
  private getToolDefinitions(): Record<string, unknown>[] {
1695
- return Array.from(this.tools.values()).map((t) => ({
1696
- name: t.name,
1697
- description: t.description,
1698
- parameters: t.parameters,
1699
- input_schema: t.parameters, // Anthropic-style naming
1700
- }))
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
+ }))
1701
1748
  }
1702
1749
 
1703
1750
  getContext(): ContextManager {
@@ -1740,7 +1787,11 @@ export class QueryEngine {
1740
1787
  */
1741
1788
  private async *llmChat(req: ChatRequest): AsyncGenerator<StreamChunk> {
1742
1789
  for await (const chunk of (this.llm ?? this.registry).chat(req)) {
1743
- 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.
1744
1795
  yield { type: 'warning', content: t('errors.turn_truncated') }
1745
1796
  }
1746
1797
  if (chunk.type === 'stop' && chunk.refusal) {
@@ -1754,6 +1805,65 @@ export class QueryEngine {
1754
1805
  }
1755
1806
  }
1756
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
+
1757
1867
  /**
1758
1868
  * Stream a chat response with graceful provider fallback (v2.1.229 alignment).
1759
1869
  *
@@ -148,7 +148,17 @@ function parseHookStdoutFields(stdout: string | null | undefined, _ctx: HookCont
148
148
  if (decision === 'ask') {
149
149
  // The engine stops the call on `ask` and prints `reason`, so the hook's
150
150
  // `permissionDecisionReason` is the only place its explanation can land.
151
- 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
+ }
152
162
  }
153
163
  if (decision === 'defer') {
154
164
  return { allowed: true, permissionDecision: 'defer', additionalContext }
@@ -544,43 +544,176 @@ function skipEnvAssignment(tokens: string[], start: number): number {
544
544
  * `bash -c 'rm -rf /'`. Over-matching is the safe direction for a deny rule.
545
545
  */
546
546
  export function flattenCommand(command: string, depth = 0): string[] {
547
- const out: string[] = []
548
- for (const seg of splitShellSegments(command)) {
549
- out.push(seg)
547
+ return flattenCommandGroups(command, depth).flatMap((group) => group.variants)
548
+ }
549
+
550
+ /** One shell segment plus every normalized reading of it. */
551
+ export interface CommandSegmentGroup {
552
+ /** The segment as written — guards about what the command *really* runs judge this. */
553
+ raw: string
554
+ /** Readings of the same segment; a rule matching **any** of them matches the segment. */
555
+ variants: string[]
556
+ }
557
+
558
+ /**
559
+ * Like `flattenCommand`, but keeps each command segment's normalizations
560
+ * together.
561
+ *
562
+ * Why the grouping matters for an **allow** rule: a rule is a grant, and a
563
+ * compound command must satisfy it in every segment. The normalizations of one
564
+ * segment are alternative readings of the *same* command, so the grant needs
565
+ * only one of them to match — flattening everything into one list made the raw
566
+ * spelling mandatory too, and `NODE_ENV=production npm run build` stopped
567
+ * matching `Bash(npm:*)` (nor did `sudo npm run build`).
568
+ *
569
+ * The raw spelling is still what the foreign-command guard reads (see
570
+ * `matchBashRule`): stripping `--exec-path=…` must not let the normalized form
571
+ * pass a grant the raw form was refused.
572
+ */
573
+ export function flattenCommandGroups(command: string, depth = 0): CommandSegmentGroup[] {
574
+ const groups: CommandSegmentGroup[] = []
575
+ for (const seg of splitShellSegments(joinLineContinuations(command))) {
576
+ const variants: string[] = [seg]
550
577
  // The shell removes quotes before running the command, so `rm "-rf" /tmp`
551
578
  // *is* `rm -rf /tmp` — but the rule text is written without quotes, so the
552
579
  // quoted spelling used to slip past `Bash(rm -rf *)`.
553
- const unquoted = dequoteSimpleTokens(seg)
554
- if (unquoted !== seg) out.push(unquoted)
555
- const stripped = stripPrefixCommand(seg)
556
- if (stripped !== seg) out.push(stripped)
580
+ const push = (v: string) => {
581
+ if (v !== seg && !variants.includes(v)) variants.push(v)
582
+ }
583
+ push(dequoteSimpleTokens(seg))
584
+ push(stripPrefixCommand(seg))
557
585
  // 剥掉前导噪声后的形态也要参与匹配:`IFS=x rm -rf x` / `( rm -rf x )` /
558
586
  // `for …; do rm -rf x; done` 执行的仍是 `rm`,规则必须看得见它。同一个函数
559
587
  // 也被 scanReaderWriterCommands 用(Read/Write/Edit 桥接那条路径)—— 两条
560
588
  // 路径共用一份归一化,只接一条就是只修一半。
561
- const denoised = stripLeadingShellNoise(seg)
562
- if (denoised !== seg) out.push(denoised)
563
- for (const inner of extractSubstitutions(seg)) {
564
- out.push(...flattenCommand(inner, depth + 1))
565
- }
589
+ push(stripLeadingShellNoise(seg))
566
590
  // Wrapper prefixes (`env`, `sudo`, `timeout`, …) are not the command being
567
591
  // run. Without their removal `env X="a b" rm -rf /` matched no `rm …`
568
592
  // rule at all, because the matcher never saw past the assignment.
569
593
  const { base, args, payload } = effectiveCommand(seg.split(/\s+/).filter(Boolean))
570
- if (base) {
571
- const unwrapped = [base, ...args].join(' ')
572
- if (unwrapped !== seg) out.push(unwrapped)
594
+ if (base) push([base, ...args].join(' '))
595
+ // Global options before a subcommand (`git -C /path log`). The allow rule
596
+ // `Bash(git log:*)` names the subcommand, and the option only decides where
597
+ // it runs — not which program does. Guarded variants are judged on `raw`.
598
+ const subcommand = stripGlobalOptions(seg)
599
+ if (subcommand) push(subcommand)
600
+
601
+ groups.push({ raw: seg, variants })
602
+
603
+ for (const inner of extractSubstitutions(seg)) {
604
+ groups.push(...flattenCommandGroups(inner, depth + 1))
573
605
  }
574
606
  // A shell `-c` payload is a command line in its own right, so `Bash(rm *)`
575
607
  // must also match `bash -c 'rm -rf /'`. Past the depth bound recursion stops
576
608
  // outright rather than pushing the raw payload: the raw text
577
609
  // (`bash -c 'rm -rf /'`) matches no `rm …` pattern anyway, and stopping
578
610
  // keeps the boundary predictable.
579
- if (payload && depth < MAX_COMMAND_DEPTH) out.push(...flattenCommand(payload, depth + 1))
611
+ if (payload && depth < MAX_COMMAND_DEPTH)
612
+ groups.push(...flattenCommandGroups(payload, depth + 1))
613
+ }
614
+ return groups
615
+ }
616
+
617
+ /**
618
+ * Remove backslash-newline continuations before splitting a command into
619
+ * segments.
620
+ *
621
+ * `splitShellSegments` splits on `\n`, but a shell removes `\` + newline
622
+ * *before* parsing, so `npm install \⏎left-pad` is one command. Splitting first
623
+ * produced two segments — the first (`npm install \`) matched no allow rule and
624
+ * the whole command fell back to "ask". Inside single quotes the backslash is
625
+ * literal, so the pair stays.
626
+ */
627
+ export function joinLineContinuations(command: string): string {
628
+ let out = ''
629
+ let quote: "'" | '"' | null = null
630
+ for (let i = 0; i < command.length; i++) {
631
+ const ch = command[i]!
632
+ if (ch === '\\' && quote !== "'") {
633
+ if (command[i + 1] === '\n') {
634
+ i += 1
635
+ continue
636
+ }
637
+ if (command[i + 1] === '\r' && command[i + 2] === '\n') {
638
+ i += 2
639
+ continue
640
+ }
641
+ // Any other escaped character: keep both, and do not let the escaped
642
+ // character toggle quote state (`\"` is a literal quote).
643
+ out += ch
644
+ if (i + 1 < command.length) {
645
+ out += command[i + 1]
646
+ i += 1
647
+ }
648
+ continue
649
+ }
650
+ if (ch === "'" && quote !== '"') {
651
+ quote = quote === "'" ? null : "'"
652
+ } else if (ch === '"' && quote !== "'") {
653
+ quote = quote === '"' ? null : '"'
654
+ }
655
+ out += ch
580
656
  }
581
657
  return out
582
658
  }
583
659
 
660
+ /** git global options that consume the next token. */
661
+ const GIT_GLOBAL_WITH_ARG = new Set([
662
+ '-C',
663
+ '-c',
664
+ '--git-dir',
665
+ '--work-tree',
666
+ '--namespace',
667
+ '--exec-path',
668
+ '--config-env',
669
+ '--super-prefix',
670
+ ])
671
+ /** git global options that stand alone. */
672
+ const GIT_GLOBAL_FLAGS = new Set([
673
+ '-p',
674
+ '--paginate',
675
+ '-P',
676
+ '--no-pager',
677
+ '--bare',
678
+ '--no-replace-objects',
679
+ '--literal-pathspecs',
680
+ '--no-optional-locks',
681
+ '--no-advice',
682
+ '--no-lazy-fetch',
683
+ ])
684
+
685
+ /**
686
+ * Normalize a known command by dropping global options that precede its
687
+ * subcommand (`git -C /path log` → `git log`).
688
+ *
689
+ * Only commands whose global-option grammar is known are normalized — a generic
690
+ * "skip everything that starts with -" would drop flags that *are* the command's
691
+ * behaviour. Returns null when there is nothing to strip.
692
+ */
693
+ export function stripGlobalOptions(segment: string): string | null {
694
+ const tokens = segment.trim().split(/\s+/)
695
+ if (tokens[0] !== 'git') return null
696
+ let i = 1
697
+ while (i < tokens.length) {
698
+ const token = tokens[i]!
699
+ if (GIT_GLOBAL_FLAGS.has(token)) {
700
+ i += 1
701
+ continue
702
+ }
703
+ if (GIT_GLOBAL_WITH_ARG.has(token)) {
704
+ i += 2
705
+ continue
706
+ }
707
+ if ([...GIT_GLOBAL_WITH_ARG].some((opt) => token.startsWith(`${opt}=`))) {
708
+ i += 1
709
+ continue
710
+ }
711
+ break
712
+ }
713
+ if (i === 1 || i >= tokens.length) return null
714
+ return ['git', ...tokens.slice(i)].join(' ')
715
+ }
716
+
584
717
  /**
585
718
  * Resolve the effective command and its arguments after any wrapper prefix
586
719
  * commands (`sudo`, `env`, `timeout`, …). Skips the wrapper and its own options
@@ -1016,7 +1149,7 @@ export function matchBashRule(
1016
1149
  // The `length > 0` guard is load-bearing: `[].every()` is `true`, so a
1017
1150
  // command with no matchable segment (or no extracted file access) would
1018
1151
  // otherwise satisfy **any** allow rule — a fail-open of its own.
1019
- const qualifies = (items: string[], match: (s: string) => boolean): boolean =>
1152
+ const qualifies = <T>(items: T[], match: (item: T) => boolean): boolean =>
1020
1153
  segmentMode === 'all' ? items.length > 0 && items.every(match) : items.some(match)
1021
1154
 
1022
1155
  // A Read/Write/Edit rule must also refuse a Bash command that touches the
@@ -1066,24 +1199,30 @@ export function matchBashRule(
1066
1199
  // the safe direction.
1067
1200
  const anchored = segmentMode === 'all' ? /^([\w./-]+)\*/.exec(subPattern!) : null
1068
1201
  const firstWord = anchored?.[1]
1069
- return qualifies(flattenCommand(cmd), (seg) => {
1070
- if (firstWord) {
1071
- // The wildcard has to start at a word boundary in the command: `ls`
1072
- // exactly, or `ls` followed by whitespace/`:` — not the `ls` inside
1073
- // `lsof`.
1074
- const boundary = new RegExp(
1075
- '^' + firstWord.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?:$|[:\\s])',
1076
- )
1077
- if (!boundary.test(seg)) return false
1078
- }
1202
+ // The wildcard has to start at a word boundary in the command: `ls`
1203
+ // exactly, or `ls` followed by whitespace/`:` — not the `ls` inside
1204
+ // `lsof`.
1205
+ const boundary = firstWord
1206
+ ? new RegExp('^' + firstWord.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?:$|[:\\s])')
1207
+ : null
1208
+ return qualifies(flattenCommandGroups(cmd), (group) => {
1079
1209
  // An allow rule names a program; these options make that program run a
1080
1210
  // **different** one (`find -exec rm`, `git --upload-pack=…`,
1081
1211
  // `awk system(…)`). Matching the outer word alone would hand over the
1082
1212
  // inner command too, so the segment is not covered by the grant. This
1083
1213
  // list is a floor, not a ceiling — every entry is a construct that
1084
1214
  // executes a command the rule did not name.
1085
- if (segmentMode === 'all' && embedsForeignCommand(seg)) return false
1086
- return wildcardMatch(subPattern!, seg)
1215
+ //
1216
+ // Judged on the segment **as written**: the normalized variants exist to
1217
+ // let benign prefixes match, and letting them carry a stripped
1218
+ // `--exec-path=…` past this guard would turn the fix into a bypass.
1219
+ if (segmentMode === 'all' && embedsForeignCommand(group.raw)) return false
1220
+ // The variants are alternative readings of *this* command — any one of
1221
+ // them matching is enough. (Across segments the caller still applies
1222
+ // 'all' / 'any'; this is the within-segment OR.)
1223
+ return group.variants.some(
1224
+ (seg) => (!boundary || boundary.test(seg)) && wildcardMatch(subPattern!, seg),
1225
+ )
1087
1226
  })
1088
1227
  }
1089
1228
 
@@ -514,6 +514,26 @@ export class PermissionSystem {
514
514
  return this.agentCapWarnings
515
515
  }
516
516
 
517
+ /**
518
+ * Does a deny rule name this tool **outright**?
519
+ *
520
+ * A rule with an input pattern (`Bash(rm:*)`, a path-scoped `Read`) denies
521
+ * *some* invocations, not the tool — those stay visible. A bare name, or a
522
+ * server wildcard (`mcp__srv__*`), denies every call; a tool the model can
523
+ * never run is not worth offering, and naming it in the request only invites
524
+ * calls that are guaranteed to fail.
525
+ *
526
+ * Read by `QueryEngine.getToolDefinitions()` to keep denied tools out of the
527
+ * model-facing list (the rule itself still decides at call time — this is a
528
+ * visibility filter, not a second gate).
529
+ */
530
+ isToolNameDenied(toolName: string): boolean {
531
+ return this.denyRules.some(
532
+ (rule) =>
533
+ !rule.pattern.includes('(') && (rule.pattern === toolName || rule.compiled.test(toolName)),
534
+ )
535
+ }
536
+
517
537
  // ── Rule management ──
518
538
 
519
539
  allow(rule: string): void {
@@ -1,4 +1,4 @@
1
- import { mkdirSync, openSync, readSync, closeSync, statSync } from 'node:fs'
1
+ import { mkdirSync, openSync, readSync, closeSync, statSync, existsSync, renameSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
3
  import { createHash } from 'node:crypto'
4
4
  import type { Message, ToolUseContent, ToolResultContent, ToolResult } from '../shared/types'
@@ -278,6 +278,44 @@ export class SessionLog {
278
278
  this.save()
279
279
  }
280
280
 
281
+ /** 当前会话名(`/rename` 之后是**新**名字 —— 落盘路径按它推导)。 */
282
+ getName(): string {
283
+ return this.name
284
+ }
285
+
286
+ /**
287
+ * 把会话日志改名 —— 让 `/rename` 与 `/resume <name>` 落在**同一个命名空间**。
288
+ *
289
+ * 从前 `/rename` 只改内存标题与跨会话登记表,`<旧名>.jsonl` 原封不动:用户
290
+ * `/rename Bug Fix` 之后 `/resume Bug Fix` 找不到任何东西,而 `/resume <旧名>`
291
+ * 又读得到 —— 两个名字指向同一段对话,却只有一个是活的。
292
+ *
293
+ * 必须改 `this.name` 而不是只搬文件:`save()` 每次都按名字重算路径,文件搬走了
294
+ * 而字段没变,下一次 `append` 会**新建一个旧名字的空文件**,历史当场分叉。
295
+ *
296
+ * 返回 `'conflict'` 时什么都没动(目标名已有别的会话),调用方必须如实说出来:
297
+ * 静默覆盖别人的会话,或静默假称已改名,都是把「失败」渲染成「成功」。
298
+ */
299
+ rename(newName: string): 'renamed' | 'unchanged' | 'conflict' {
300
+ if (newName === this.name) return 'unchanged'
301
+ const oldPath = join(this.dir, `${sanitizeSessionName(this.name)}.jsonl`)
302
+ const newPath = join(this.dir, `${sanitizeSessionName(newName)}.jsonl`)
303
+ // 两个不同名字可能消毒到同一个文件名(`a/b` 与 `a_b`):此时文件已经是
304
+ // 目标路径,不需要也不能 rename。
305
+ if (oldPath !== newPath) {
306
+ if (existsSync(newPath)) return 'conflict'
307
+ if (existsSync(oldPath)) {
308
+ try {
309
+ renameSync(oldPath, newPath)
310
+ } catch {
311
+ return 'conflict'
312
+ }
313
+ }
314
+ }
315
+ this.name = newName
316
+ return 'renamed'
317
+ }
318
+
281
319
  /** 不可变快照(浅拷贝,事件本身视为不可变)。 */
282
320
  events(): SessionEvent[] {
283
321
  return [...this.buf]