@miphamai/cli 0.85.24 → 0.85.25

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.24
1
+ # Mipham Code v0.85.25
2
2
 
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.
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
 
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
- - **137 Slash Commands** — Interactive command picker (↑↓ Enter Esc), intuitive command interface, zero re-learning
19
+ - **138 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.24",
3
+ "version": "0.85.25",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -124,7 +124,11 @@ export class ArtifactServer {
124
124
  socket.on('close', () => this.sockets.delete(socket))
125
125
  })
126
126
  srv.on('error', reject)
127
- srv.listen(port, () => {
127
+ // Loopback only. Without a host argument `listen()` binds **every**
128
+ // interface, so any artifact — including whatever the model just wrote —
129
+ // would be readable by the whole LAN. The URLs we hand out are
130
+ // `http://localhost:…`, which resolves here either way.
131
+ srv.listen(port, '127.0.0.1', () => {
128
132
  this.server = srv
129
133
  resolve()
130
134
  })
@@ -8,11 +8,19 @@ import type { CommandHandler } from '../ui/commands.js'
8
8
 
9
9
  export { commitCmd, pushCmd, prCmd, issueCmd }
10
10
 
11
- /** Run a git command asynchronously — avoids blocking the TUI event loop. */
11
+ /**
12
+ * Run a git command asynchronously — avoids blocking the TUI event loop.
13
+ *
14
+ * `LC_ALL=C` is load-bearing for the callers that parse output: `git remote show
15
+ * origin` prints `HEAD branch:` / `HEAD 分支:` depending on the locale, and the
16
+ * English regex then quietly falls back to `main` on a machine whose git speaks
17
+ * Chinese. Forcing the C locale makes the text we match against fixed.
18
+ */
12
19
  async function git(args: string[], timeoutMs = 5000): Promise<string> {
13
20
  const proc = Bun.spawn(['git', ...args], {
14
21
  stdout: 'pipe',
15
22
  stderr: 'pipe',
23
+ env: { ...process.env, LC_ALL: 'C', LANG: 'C' },
16
24
  })
17
25
  const exitCode = await Promise.race([
18
26
  proc.exited,
@@ -889,24 +889,30 @@ For help at any time: /help`,
889
889
  }
890
890
  }
891
891
 
892
+ // `/add-dir` 从前会回「✓ Directory registered」并把 `.mipham/config.yml` 的
893
+ // `workspace.extraDirs` 当兑现方式 —— 而那个键全仓**零读者**,命令本身也没有
894
+ // 任何状态可供后续工具查询。一句话:广告的能力没有落点。
895
+ //
896
+ // 现在它只做两件真事:校验路径存在,并如实说明访问实际由什么决定。删掉命令是
897
+ // 更省事的做法,但 `/add-dir` 是用户会去敲的名字 —— 让它给出**错的**答案,比留下
898
+ // 一个说真话的入口更坏。
892
899
  const addDirCmd: CommandHandler = async (_ctx, args) => {
893
900
  const dir = args[0]
894
901
  if (!dir) {
895
902
  return {
896
903
  content: `Usage: /add-dir <path>
897
904
 
898
- Add a directory to Mipham Code's allowed workspace paths.
899
- This grants the AI permission to read/write files in that directory.
905
+ Check a path and show how file access to it is actually decided.
906
+
907
+ This build has NO workspace-directory allowlist: running /add-dir does not
908
+ register anything and does not by itself change what the AI may read or write.
909
+ See /add-dir <path> for the mechanism.
900
910
 
901
911
  Examples:
902
912
  /add-dir ~/projects/my-api
903
913
  /add-dir /usr/local/share/data
904
914
 
905
- Current allowed directories:
906
- • ${process.cwd()} (project root, always allowed)
907
-
908
- Note: For security, tools like bash already respect .mipham/config.yml
909
- permission boundaries. Adding directories here extends read/write access.`,
915
+ Current directory: ${process.cwd()}`,
910
916
  }
911
917
  }
912
918
 
@@ -919,16 +925,27 @@ permission boundaries. Adding directories here extends read/write access.`,
919
925
  }
920
926
 
921
927
  return {
922
- content: `✓ Directory registered: ${resolved}
923
-
924
- To persist across sessions, add to .mipham/config.yml:
925
- workspace:
926
- extraDirs:
927
- - ${resolved}
928
-
929
- The AI can now access files in this directory.
930
- Permission mode: Shift+Tab cycles ${renderCycleLine()} (this session);
931
- \`permission:\` in .mipham/config.yml persists one.`,
928
+ content: `✓ Path exists: ${resolved}
929
+
930
+ Nothing was registered — this build has no workspace-directory allowlist.
931
+
932
+ How access is actually decided:
933
+ • Reads — not limited by directory. What refuses a file is a deny rule
934
+ (\`Read(<path>)\`, which also covers Bash readers like cat/head).
935
+ • Writes — gated by the permission mode (Shift+Tab cycles:
936
+ ${renderCycleLine()}).
937
+ In the default mode a Write/Edit resolves to \`ask\`, and this CLI
938
+ has no interactive approval prompt: \`ask\` is a hard refusal.
939
+
940
+ To allow writes under this directory without changing the mode, add path
941
+ allow rules to your USER settings (~/.mipham/settings.json). The project-level
942
+ allow list is deliberately ignored, because a repository must not widen its
943
+ own permissions:
944
+ {
945
+ "permissions": {
946
+ "allow": ["Write(${resolved}/**)","Edit(${resolved}/**)"]
947
+ }
948
+ }`,
932
949
  }
933
950
  }
934
951
 
@@ -123,11 +123,52 @@ function extractMessageText(msg: Message): string {
123
123
  return ''
124
124
  }
125
125
 
126
- function estimateStringTokens(text: string): number {
126
+ /**
127
+ * A run of at least this many non-space ASCII characters, with at least
128
+ * `DENSE_DISTINCT` distinct characters in it, is treated as encoded or
129
+ * unbroken payload (base64, hex, minified JSON, a single-line SVG) — text a
130
+ * BPE tokenizer splits at roughly 1.5–3 characters per token rather than the
131
+ * ~4 that prose and code average.
132
+ *
133
+ * Both halves matter:
134
+ * - the length threshold keeps ordinary identifiers (`some_long_function_name`)
135
+ * in the prose bucket;
136
+ * - the distinct-character threshold keeps `'A'.repeat(400)` there too — a
137
+ * filler run of one repeated character merges into very few tokens, and
138
+ * charging it as dense would overestimate by an order of magnitude.
139
+ *
140
+ * The divisor (`dense / 2`) is a deliberately conservative lower bound, not a
141
+ * measurement: this repository has no tokenizer, and the direction that matters
142
+ * is under-estimation (a request that is longer than the budget claimed). Being
143
+ * wrong the other way only compacts a little early.
144
+ */
145
+ const DENSE_RUN_MIN = 40
146
+ const DENSE_DISTINCT = 8
147
+
148
+ /**
149
+ * Estimate the token count for a text string.
150
+ *
151
+ * Character-class heuristic:
152
+ * - CJK / emoji: ~1.5 chars per token
153
+ * - dense ASCII runs (see above): ~2 chars per token
154
+ * - everything else (Latin, Cyrillic, Arabic, whitespace, short code): ~4
155
+ */
156
+ export function estimateStringTokens(text: string): number {
127
157
  if (!text) return 0
128
158
 
129
159
  let cjk = 0
130
160
  let latin = 0
161
+ let dense = 0
162
+ let runLength = 0
163
+ const runChars = new Set<string>()
164
+ const flushRun = (): void => {
165
+ if (runLength >= DENSE_RUN_MIN && runChars.size >= DENSE_DISTINCT) {
166
+ dense += runLength
167
+ latin -= runLength
168
+ }
169
+ runLength = 0
170
+ runChars.clear()
171
+ }
131
172
 
132
173
  for (const ch of text) {
133
174
  const cp = ch.codePointAt(0)!
@@ -141,12 +182,23 @@ function estimateStringTokens(text: string): number {
141
182
  (cp >= 0xff01 && cp <= 0xff60) || // Fullwidth
142
183
  (cp >= 0x1f300 && cp <= 0x1f9ff) // Emoji / pictographs
143
184
  ) {
185
+ flushRun()
144
186
  cjk++
187
+ } else if (cp > 0x7f) {
188
+ flushRun()
189
+ latin++
145
190
  } else {
146
191
  latin++
192
+ // Whitespace ends a run but still counts as loose text, exactly as before.
193
+ if (cp === 0x20 || cp === 0x09 || cp === 0x0a || cp === 0x0d || cp === 0x0b || cp === 0x0c) {
194
+ flushRun()
195
+ } else {
196
+ runLength++
197
+ if (runChars.size < DENSE_DISTINCT) runChars.add(ch)
198
+ }
147
199
  }
148
200
  }
201
+ flushRun()
149
202
 
150
- // CJK: ~1.5 chars/token, Latin/other: ~4 chars/token
151
- return Math.max(1, Math.ceil(cjk / 1.5 + latin / 4))
203
+ return Math.max(1, Math.ceil(cjk / 1.5 + latin / 4 + dense / 2))
152
204
  }
@@ -5,10 +5,12 @@ import type {
5
5
  ToolResult,
6
6
  ToolResultContent,
7
7
  } from '../shared/index.ts'
8
+ import { safeSlice } from '../shared/sanitize'
8
9
  import { snipMessages } from './context-snip'
9
10
  import { microcompact, shouldMicrocompact, isToolResultUserMessage } from './context-microcompact'
10
11
  import {
11
12
  estimateMessageTokens,
13
+ estimateStringTokens,
12
14
  NoopCacheTracker,
13
15
  type CacheTracker,
14
16
  type CacheStatus,
@@ -39,7 +41,7 @@ function shrinkText(text: string, maxTokens: number): string {
39
41
 
40
42
  let out = text
41
43
  for (let guard = 0; guard < 32 && out.length > 0 && estimate(out) > maxTokens; guard++) {
42
- out = out.slice(0, Math.floor(out.length / 2))
44
+ out = safeSlice(out, Math.floor(out.length / 2))
43
45
  }
44
46
  return `${out}\n… [truncated to fit the context budget; ${text.length - out.length} characters omitted]`
45
47
  }
@@ -431,14 +433,6 @@ export class ContextManager {
431
433
  const dropped = this.messages.slice(0, cut)
432
434
  let kept = this.messages.slice(cut)
433
435
 
434
- // 一条消息自己就超预算(单条巨型结果 / 整篇文档)⇒ 没有可丢的,只能截内容。
435
- // 每条分到的是它自己那份预算,不是整份额度 —— 否则几条各占三分之一的消息谁也
436
- // 没超,削完还是超。
437
- if (dropped.length === 0 && kept.length > 0) {
438
- const perMessage = Math.max(1, Math.floor(target / kept.length))
439
- kept = kept.map((m) => truncateToBudget(m, perMessage))
440
- }
441
-
442
436
  const omittedNotice = (n: number): Message => ({
443
437
  role: 'user',
444
438
  content:
@@ -447,6 +441,21 @@ export class ContextManager {
447
441
  `they said.]`,
448
442
  })
449
443
 
444
+ // 幸存的那半自己就超预算(单条巨型结果 / 整篇文档)⇒ 没有可再丢的,只能截内容。
445
+ //
446
+ // 判据必须是**量出来的**「这份超没超」,不能是 `dropped.length === 0`:
447
+ // 只要有**一条**前面的消息被丢掉,那个条件就为假,而超额的恰恰可以是最后那条
448
+ // (丢弃循环对最后一条无条件保留)—— 于是「削完还超」,下一轮再进这里做同一个
449
+ // 空操作。通知自己也要占预算,所以按去掉通知后的额度分。
450
+ // 每条分到的是它自己那份,不是整份额度 —— 否则几条各占三分之一的消息谁也没超,
451
+ // 削完还是超。
452
+ const noticeTokens = dropped.length > 0 ? est(omittedNotice(dropped.length)) : 0
453
+ const bodyTarget = Math.max(1, target - noticeTokens)
454
+ if (kept.length > 0 && this.estimateTokensForMessages(kept) > bodyTarget) {
455
+ const perMessage = Math.max(1, Math.floor(bodyTarget / kept.length))
456
+ kept = kept.map((m) => truncateToBudget(m, perMessage))
457
+ }
458
+
450
459
  // 通知自己也占预算,所以头部再补削,直到**含通知**的整份落进预算。少了这一步,
451
460
  // 「刚好削到线内」的会话会因多出这一条而重新超线 —— 下一轮再削一次,逐轮掉消息。
452
461
  // 顺带保住配对:若补削后的第一条是 `tool_result`,它的调用已在被丢的那半里,
@@ -760,40 +769,11 @@ export class ContextManager {
760
769
  /**
761
770
  * Estimate token count for a text string.
762
771
  *
763
- * Uses a character-class-aware heuristic:
764
- * - CJK / emoji: ~1.5 chars per token
765
- * - Other scripts (Latin, Cyrillic, Arabic): ~4 chars per token
766
- * - Whitespace-heavy (code): ~3 chars per token
767
- *
768
- * This is ~30-40% more accurate than flat 4 chars/token for mixed-language text.
772
+ * Delegates to `estimateStringTokens` — the same function the message counter
773
+ * uses. Two copies of the formula are two chances for the budget and the
774
+ * compaction trigger to disagree about the same text.
769
775
  */
770
776
  private estimateTokens(text: string): number {
771
- if (!text) return 0
772
-
773
- let cjk = 0
774
- let latin = 0
775
-
776
- for (const ch of text) {
777
- const cp = ch.codePointAt(0)!
778
- // CJK Unified Ideographs, Hangul, Kana, CJK Extensions, fullwidth forms
779
- if (
780
- (cp >= 0x4e00 && cp <= 0x9fff) || // CJK Unified
781
- (cp >= 0x3400 && cp <= 0x4dbf) || // CJK Ext-A
782
- (cp >= 0x20000 && cp <= 0x2a6df) || // CJK Ext-B
783
- (cp >= 0xac00 && cp <= 0xd7af) || // Hangul
784
- (cp >= 0x3040 && cp <= 0x30ff) || // Hiragana + Katakana
785
- (cp >= 0xff01 && cp <= 0xff60) || // Fullwidth
786
- (cp >= 0x1f300 && cp <= 0x1f9ff) // Emoji / pictographs
787
- ) {
788
- cjk++
789
- } else if (cp > 0x7f) {
790
- latin++
791
- } else {
792
- latin++
793
- }
794
- }
795
-
796
- // CJK: ~1.5 chars/token, Latin/other: ~4 chars/token
797
- return Math.max(1, Math.ceil(cjk / 1.5 + latin / 4))
777
+ return estimateStringTokens(text)
798
778
  }
799
779
  }
@@ -25,6 +25,7 @@ import {
25
25
  realpathSync,
26
26
  } from 'node:fs'
27
27
  import { atomicWriteFileSync } from '../shared/atomic-write'
28
+ import { internalGitEnv } from '../shared/git-env'
28
29
  import { join, resolve, sep, posix } from 'node:path'
29
30
  import { tmpdir } from 'node:os'
30
31
  import { randomUUID } from 'node:crypto'
@@ -296,7 +297,7 @@ function shq(s: string): string {
296
297
  * 对象字面量怎么变都动不了它们。下面那个字面量被抹成 `{}` 只会丢掉超时与编码,
297
298
  * 丢不掉「哪棵树」。**有意不再传 `cwd`** —— 留着它,下一个人会以为承重的是它。
298
299
  *
299
- * 守卫 `test/integrity/crsi-sandbox-command-root.test.ts` 静态钉住这个形状。
300
+ * 守卫 `test/integrity/crsi-sandbox-root.test.ts` 静态钉住这个形状。
300
301
  */
301
302
  function runIn(
302
303
  root: string,
@@ -309,6 +310,9 @@ function runIn(
309
310
  return execSync(rooted, {
310
311
  timeout: opts.timeoutMs ?? 10_000,
311
312
  encoding: 'utf-8',
313
+ // The sandbox derives its worktree from `HEAD`; a `refs/replace/*` entry
314
+ // would make that tree differ from the object graph the user actually has.
315
+ env: internalGitEnv(),
312
316
  ...(opts.quiet ? { stdio: ['ignore', 'pipe', 'ignore'] as StdioOptions } : {}),
313
317
  })
314
318
  }
@@ -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,
@@ -632,7 +633,10 @@ export class QueryEngine {
632
633
  // Return a minimal summary on failure
633
634
  }
634
635
 
635
- return summary.slice(0, 8000) || t('system.context.omitted')
636
+ // Surrogate-safe: this string lands in the JSONL transcript, where a lone
637
+ // half-pair makes the serializer emit an invalid escape and strict parsers
638
+ // reject the entire line.
639
+ return safeSlice(summary, 8000) || t('system.context.omitted')
636
640
  })
637
641
  }
638
642
 
@@ -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
  *
@@ -650,7 +717,7 @@ Never omit it or present the work as purely human-authored.`)
650
717
  level,
651
718
  privacy: (data.privacy as InstructionFile['privacy']) || 'project',
652
719
  language: (data.language as string) || 'en-US',
653
- content,
720
+ content: capInstructionContent(content, path),
654
721
  frontmatter: data,
655
722
  })
656
723
  } catch {