@miphamai/cli 0.85.23 → 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.
Files changed (42) hide show
  1. package/README.md +3 -3
  2. package/bin/mipham.ts +21 -2
  3. package/package.json +1 -1
  4. package/src/agent/agent-registry.ts +42 -2
  5. package/src/agent/message-router.ts +30 -0
  6. package/src/agent/sub-agent.ts +17 -0
  7. package/src/artifacts/server.ts +5 -1
  8. package/src/commands/git.ts +9 -1
  9. package/src/commands/project.ts +34 -17
  10. package/src/core/context-microcompact.ts +1 -1
  11. package/src/core/context-token.ts +55 -3
  12. package/src/core/context.ts +180 -43
  13. package/src/core/crsi-sandbox.ts +5 -1
  14. package/src/core/engine.ts +19 -6
  15. package/src/core/hooks.ts +13 -3
  16. package/src/core/instructions.ts +69 -2
  17. package/src/core/permission-rules.ts +141 -25
  18. package/src/i18n-core/locales/en-US.json +1 -0
  19. package/src/i18n-core/locales/zh-CN.json +1 -0
  20. package/src/mcp/client.ts +22 -8
  21. package/src/plugin/plugin-manager.ts +23 -2
  22. package/src/providers/anthropic.ts +8 -2
  23. package/src/providers/openai-compat.ts +14 -2
  24. package/src/providers/registry.ts +23 -1
  25. package/src/shared/arg-validation.ts +2 -1
  26. package/src/shared/git-env.ts +18 -0
  27. package/src/shared/package-info.ts +3 -3
  28. package/src/shared/sanitize.ts +21 -0
  29. package/src/skills/loader.ts +55 -3
  30. package/src/tools/agent/workflow.ts +9 -2
  31. package/src/tools/exec/bash.ts +206 -17
  32. package/src/tools/exec/enter-worktree.ts +26 -2
  33. package/src/tools/network/web-fetch.ts +11 -3
  34. package/src/tools/network/web-search.ts +5 -1
  35. package/src/tools/scheduling/schedule-wakeup.ts +3 -2
  36. package/src/tools/validation.ts +11 -0
  37. package/src/ui/app.tsx +22 -7
  38. package/src/ui/chat.tsx +3 -2
  39. package/src/ui/commands.ts +61 -7
  40. package/src/workflow/primitives/agent.ts +51 -6
  41. package/src/workflow/primitives/verify.ts +36 -20
  42. package/src/workflow/runtime.ts +10 -2
@@ -5,6 +5,7 @@ import { sanitizeCommand } from '../../shared/sanitize.ts'
5
5
  import { DANGEROUS_GIT_PATTERNS } from './git.ts'
6
6
  import { isUncOrDevicePath, isWithin } from '../../security/path.ts'
7
7
  import { findWorktreeMarker } from '../../core/paths.ts'
8
+ import { splitShellSegments, expandKnownPathVars } from '../../core/permission-rules'
8
9
  import type { Service } from '../../vajra'
9
10
  import { toolKey } from '../seam'
10
11
  import { withValidation } from '../validation'
@@ -16,32 +17,53 @@ import { withValidation } from '../validation'
16
17
  // target being the last thing on the line, so `rm -rf /*` was refused while
17
18
  // `rm -rf /* > log`, `rm -rf /* foo` and `rm -rf /*; echo x` — the same
18
19
  // deletion — were not.
20
+ // Any spelling of the recursive flag: `-rf`, `-fr`, `-r`, `-R`, `--recursive`.
21
+ // Another flag may sit on either side (`-f -r`, `-i -r -v`), because the shell
22
+ // does not care about flag order or which letters share a cluster.
23
+ //
24
+ // Matching only `-rf`/`-fr` made the refusal a spelling test rather than a
25
+ // behaviour test: `rm -r /Volumes` deletes exactly what `rm -rf /Volumes` does
26
+ // and passed. Every guard below needs the same fragment, so it is written once.
27
+ const RM_OTHER_FLAGS = String.raw`(?:-[A-Za-z]+|--[a-z][a-z-]*)`
28
+ const RM_RECURSIVE = String.raw`(?:-[A-Za-z]*[rR][A-Za-z]*|--recursive)`
29
+ const RM_LEAD = String.raw`\brm\s+(?:${RM_OTHER_FLAGS}\s+)*${RM_RECURSIVE}(?:\s+${RM_OTHER_FLAGS})*\s+`
30
+
31
+ /** `rm` with the recursive flag in any spelling, followed by `target`. */
32
+ function rmRecursiveOn(target: string, flags = ''): RegExp {
33
+ return new RegExp(RM_LEAD + target, flags)
34
+ }
35
+
19
36
  const BLOCKED_PATTERNS = [
20
37
  // Recursive root deletion without preserve-root safeguard.
21
38
  // The operand may be quoted: `rm -rf '/'` reaches the same path as `rm -rf /`, so
22
39
  // the quote belongs to the *delimiter* class, not to the path — `['"]?` opens the
23
40
  // operand and the lookahead accepts the closing quote.
24
- /\brm\s+-rf\s+['"]?\/(?=["'\s]|$)/,
25
- /\brm\s+-rf\s+['"]?\/\*(?=["'\s;&|>]|$)/,
41
+ rmRecursiveOn(String.raw`['"]?\/(?=["'\s]|$)`),
42
+ rmRecursiveOn(String.raw`['"]?\/\*(?=["'\s;&|>]|$)`),
26
43
  /\bsudo\s+rm\s+.*\//,
27
44
  // rm -rf on home directory or any absolute path (relative dirs like node_modules stay allowed)
28
- /\brm\s+-(?:rf|fr)\s+['"]?~(?:["'\s\/]|$)/,
29
- /\brm\s+-(?:rf|fr)\s+['"]?\/(?![\s*])/,
45
+ rmRecursiveOn(String.raw`['"]?~(?:["'\s\/]|$)`),
46
+ rmRecursiveOn(String.raw`['"]?\/(?![\s*])`),
30
47
  // rm -rf on dangerous cwd globs
31
- /\brm\s+-(?:rf|fr)\s+['"]?\*(?=["'\s;&|>]|$)/,
48
+ rmRecursiveOn(String.raw`['"]?\*(?=["'\s;&|>]|$)`),
32
49
  // `rm -rf .` and its path spellings `./` and `../` delete the working directory;
33
50
  // `./build` and `../vendor` name an entry inside it and stay allowed.
34
- /\brm\s+-(?:rf|fr)\s+['"]?\.\.?(?:\/)?(?=["'\s;&|>]|$)/,
51
+ rmRecursiveOn(String.raw`['"]?\.\.?(?:\/)?(?=["'\s;&|>]|$)`),
35
52
  // The home directory under another name is still the home directory. `$HOME`
36
53
  // expands to the same tree as `~`; on Windows `C:\Users\<name>` *is* the profile
37
54
  // directory, long or in its 8.3 short form (`C:\Users\GUOHUA~1`). Guarding only
38
55
  // the literal spellings above leaves each of these a one-word bypass.
39
- /\brm\s+-(?:rf|fr)\s+['"]?\$\{?HOME\}?(?:["'\s/]|$)/,
40
- /\brm\s+-(?:rf|fr)\s+['"]?[A-Za-z]:[\\/](?=["'\s;&|>]|$)/,
41
- /\brm\s+-(?:rf|fr)\s+['"]?[A-Za-z]:[\\/]Users[\\/][^\\/\s"']+[\\/]?(?=["'\s;&|>]|$)/i,
56
+ rmRecursiveOn(String.raw`['"]?\$\{?HOME\}?(?:["'\s/]|$)`),
57
+ rmRecursiveOn(String.raw`['"]?[A-Za-z]:[\\/](?=["'\s;&|>]|$)`),
58
+ // `C:\Users` itself is the parent of every profile on the drive — the drive's
59
+ // equivalent of `/home`, so the profile name is optional rather than required.
60
+ rmRecursiveOn(
61
+ String.raw`['"]?[A-Za-z]:[\\/]Users(?:[\\/](?:[^\\/\s"']+(?:[\\/])?)?)?(?=["'\s;&|>]|$)`,
62
+ 'i',
63
+ ),
42
64
  // cmd.exe spells the same directories with percent signs; in scope whenever a
43
65
  // command hands off to cmd (`cmd /c …`).
44
- /\brm\s+-(?:rf|fr)\s+['"]?%(?:USERPROFILE|HOMEPATH|HOMEDRIVE)%/i,
66
+ rmRecursiveOn(String.raw`['"]?%(?:USERPROFILE|HOMEPATH|HOMEDRIVE)%`, 'i'),
45
67
  // Filesystem manipulation
46
68
  /\bmkfs\./,
47
69
  /\bdd\s+if=/,
@@ -355,16 +377,177 @@ export function resolveWorktreeEscape(
355
377
  worktreeRoot: string,
356
378
  command: string,
357
379
  ): string | null {
358
- const cdRe = /\bcd\s+(?:"([^"]+)"|'([^']+)'|([^\s;|&]+))/g
359
- for (const m of command.matchAll(cdRe)) {
360
- const target = m[1] ?? m[2] ?? m[3]
361
- if (!target) continue
362
- const resolved = resolve(cwd, target)
363
- if (!isWithin(resolved, cwd) && !isWithin(resolved, worktreeRoot)) return target
380
+ for (const segment of splitShellSegments(command)) {
381
+ for (const target of changeDirectoryTargets(shellWords(segment))) {
382
+ // `resolve` does not expand `~` or `$HOME`: `cd ~` would otherwise be
383
+ // resolved as a directory literally named `~` under the worktree, i.e.
384
+ // "inside", while the shell lands in the home directory.
385
+ const resolved = resolve(cwd, expandKnownPathVars(target))
386
+ if (!isWithin(resolved, cwd) && !isWithin(resolved, worktreeRoot)) return target
387
+ }
364
388
  }
365
389
  return null
366
390
  }
367
391
 
392
+ /** Shell structure that can precede the command word without being one. */
393
+ const LEADING_SHELL_PUNCT = new Set(['(', '{', '!', ')', '}'])
394
+ /** Keywords after which the *next* word is the command (`if cd /x; then`). */
395
+ const LEADING_SHELL_KEYWORDS = new Set([
396
+ 'if',
397
+ 'then',
398
+ 'else',
399
+ 'elif',
400
+ 'while',
401
+ 'until',
402
+ 'do',
403
+ 'for',
404
+ 'time',
405
+ 'coproc',
406
+ ])
407
+ /** Wrappers that run a command of their own; the wrapped words are re-scanned. */
408
+ const WRAPPERS = new Set(['command', 'builtin'])
409
+ const LEADING_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/
410
+ const CD_COMMANDS = new Set(['cd', 'pushd'])
411
+
412
+ /**
413
+ * Quote-aware word split of one simple command, with the quotes removed.
414
+ *
415
+ * The previous implementation matched `\bcd\s+` against the raw text. A quoted
416
+ * **command word** (`'cd' /etc`, `"cd" /etc`, `\cd /etc`) is still the `cd`
417
+ * builtin to bash, but there is no word boundary followed by whitespace in
418
+ * that spelling, so the guard never saw it. Reconstructing the words first also
419
+ * lets `pushd` and `env -C` be recognized as what they are.
420
+ *
421
+ * Over-splitting is the safe direction here: a word that is not really a
422
+ * command word simply fails to match `cd`.
423
+ */
424
+ function shellWords(segment: string): string[] {
425
+ const words: string[] = []
426
+ let cur = ''
427
+ let started = false
428
+ let quote: '"' | "'" | null = null
429
+ for (let i = 0; i < segment.length; i++) {
430
+ const ch = segment[i]!
431
+ if (quote === "'") {
432
+ if (ch === "'") quote = null
433
+ else cur += ch
434
+ continue
435
+ }
436
+ if (quote === '"') {
437
+ if (ch === '"') quote = null
438
+ else if (ch === '\\' && i + 1 < segment.length) cur += segment[++i]
439
+ else cur += ch
440
+ continue
441
+ }
442
+ if (ch === "'" || ch === '"') {
443
+ quote = ch
444
+ started = true
445
+ } else if (ch === '\\' && i + 1 < segment.length) {
446
+ cur += segment[++i]
447
+ started = true
448
+ } else if (/\s/.test(ch)) {
449
+ if (started) {
450
+ words.push(cur)
451
+ cur = ''
452
+ started = false
453
+ }
454
+ } else {
455
+ cur += ch
456
+ started = true
457
+ }
458
+ }
459
+ if (started) words.push(cur)
460
+ return words
461
+ }
462
+
463
+ /**
464
+ * Every directory this simple command changes the shell's cwd to.
465
+ *
466
+ * A bare `cd` goes to `$HOME`, which is outside any worktree — it is reported
467
+ * as the home directory rather than skipped. Re-scanning wrapped words is what
468
+ * catches `env A=1 -C /etc cd /tmp`: both directories are candidates, and
469
+ * either one leaving the worktree is enough to refuse the command.
470
+ */
471
+ function changeDirectoryTargets(words: string[], depth = 0): string[] {
472
+ if (depth > 4) return []
473
+ const out: string[] = []
474
+ let i = 0
475
+ const skipNoise = (): void => {
476
+ for (;;) {
477
+ while (i < words.length && LEADING_ASSIGNMENT.test(words[i]!)) i++
478
+ const word = words[i]
479
+ if (word === undefined) return
480
+ if (LEADING_SHELL_PUNCT.has(word)) {
481
+ i++
482
+ continue
483
+ }
484
+ if (LEADING_SHELL_KEYWORDS.has(word)) {
485
+ i++
486
+ // A keyword's own flags (`time -p rm …`) are not the command word.
487
+ while (i < words.length && /^-[A-Za-z]+$/.test(words[i]!)) i++
488
+ continue
489
+ }
490
+ return
491
+ }
492
+ }
493
+
494
+ skipNoise()
495
+ const cmd = words[i]
496
+ if (cmd === undefined) return out
497
+
498
+ if (WRAPPERS.has(cmd)) {
499
+ return changeDirectoryTargets(words.slice(i + 1), depth + 1)
500
+ }
501
+
502
+ if (cmd === 'env') {
503
+ i++
504
+ while (i < words.length) {
505
+ const w = words[i]!
506
+ if (w === '-C' || w === '--chdir') {
507
+ const dir = words[i + 1]
508
+ if (dir !== undefined) out.push(dir)
509
+ i += 2
510
+ continue
511
+ }
512
+ if (w.startsWith('--chdir=')) {
513
+ out.push(w.slice('--chdir='.length))
514
+ i++
515
+ continue
516
+ }
517
+ if (w === '-u' || w === '--unset') {
518
+ i += 2 // takes an argument
519
+ continue
520
+ }
521
+ if (LEADING_ASSIGNMENT.test(w)) {
522
+ i++ // `env A=1 -C /etc cmd` — assignments may sit among the options
523
+ continue
524
+ }
525
+ if (w === '-S' || w === '--split-string' || w === '--') break
526
+ if (w.startsWith('-')) {
527
+ i++
528
+ continue
529
+ }
530
+ break
531
+ }
532
+ return out.concat(changeDirectoryTargets(words.slice(i), depth + 1))
533
+ }
534
+
535
+ if (!CD_COMMANDS.has(cmd)) return out
536
+
537
+ let j = i + 1
538
+ while (j < words.length && /^-[A-Za-z]+$/.test(words[j]!)) j++
539
+ if (words[j] === '--') j++
540
+ const target = words[j]
541
+ if (target === undefined) {
542
+ // `cd` / `pushd` alone: `cd` goes home. (`pushd` with no argument swaps the
543
+ // directory stack, which cannot leave the shell it is already in.)
544
+ if (cmd === 'cd') out.push('~')
545
+ } else {
546
+ out.push(target)
547
+ }
548
+ return out
549
+ }
550
+
368
551
  export function createBashTool(credentialConfig?: CredentialMaskingConfig): ToolDefinition {
369
552
  return {
370
553
  name: 'Bash',
@@ -531,6 +714,10 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
531
714
  )
532
715
  .join('\n')
533
716
  }
717
+ // A full disk is the one failure whose raw form (`ENOSPC … /some/path`)
718
+ // reads like a *path* problem, so the model starts checking permissions
719
+ // on a path that is fine. Say what happened instead.
720
+ const diskFull = /ENOSPC|No space left on device/i.test(stderr)
534
721
  return {
535
722
  success: false,
536
723
  content: errorContent,
@@ -538,7 +725,9 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
538
725
  ? `Command cancelled (SIGKILL to its process group)`
539
726
  : timedOut
540
727
  ? `Command timed out after ${timeout}ms (killed): ${stderr.slice(0, 1_000)}`
541
- : `Exit code ${exitCode}: ${stderr.slice(0, 1_000)}`,
728
+ : diskFull
729
+ ? `The disk is full (ENOSPC) — the command could not finish, and anything it had written may be partial: ${stderr.slice(0, 1_000)}`
730
+ : `Exit code ${exitCode}: ${stderr.slice(0, 1_000)}`,
542
731
  }
543
732
  }
544
733
 
@@ -1,6 +1,10 @@
1
1
  import type { ToolDefinition } from '../../shared/index.ts'
2
+ import { internalGitEnv } from '../../shared/git-env'
2
3
  import { listsWorktree, worktreeRoot } from '../../core/paths.ts'
3
4
 
5
+ /** Upper bound for `git worktree add` — a hung fetch must not hang the tool. */
6
+ const WORKTREE_ADD_TIMEOUT_MS = 60_000
7
+
4
8
  export const enterWorktreeTool: ToolDefinition = {
5
9
  name: 'EnterWorktree',
6
10
  description:
@@ -78,6 +82,7 @@ export const enterWorktreeTool: ToolDefinition = {
78
82
  cwd,
79
83
  stdout: 'pipe',
80
84
  stderr: 'pipe',
85
+ env: internalGitEnv(),
81
86
  })
82
87
  const gitCheckExit = await gitCheck.exited
83
88
  if (gitCheckExit !== 0) {
@@ -93,6 +98,7 @@ export const enterWorktreeTool: ToolDefinition = {
93
98
  cwd,
94
99
  stdout: 'pipe',
95
100
  stderr: 'pipe',
101
+ env: internalGitEnv(),
96
102
  })
97
103
  const existingWorktrees = await new Response(checkProc.stdout).text()
98
104
  if (listsWorktree(existingWorktrees, worktreePath)) {
@@ -116,6 +122,7 @@ export const enterWorktreeTool: ToolDefinition = {
116
122
  cwd,
117
123
  stdout: 'pipe',
118
124
  stderr: 'pipe',
125
+ env: internalGitEnv(),
119
126
  })
120
127
  const branch = (await new Response(branchProc.stdout).text()).trim()
121
128
  resolvedBaseRef = branch || 'HEAD'
@@ -134,10 +141,27 @@ export const enterWorktreeTool: ToolDefinition = {
134
141
  // nonsense, which is what a bad base ref should do.
135
142
  const proc = Bun.spawn(
136
143
  ['git', 'worktree', 'add', '-b', branchName, worktreePath, '--', resolvedBaseRef],
137
- { cwd, stdout: 'pipe', stderr: 'pipe' },
144
+ { cwd, stdout: 'pipe', stderr: 'pipe', env: internalGitEnv() },
138
145
  )
139
146
  const _stdout = await new Response(proc.stdout).text()
140
- const exitCode = await proc.exited
147
+ // A worktree that cannot be created (a promisor remote that is gone, a
148
+ // lock from a crashed run) otherwise hangs this tool with no answer at all.
149
+ let timer: ReturnType<typeof setTimeout> | undefined
150
+ const exitCode = await Promise.race([
151
+ proc.exited,
152
+ new Promise<number>((resolve) => {
153
+ timer = setTimeout(() => resolve(-1), WORKTREE_ADD_TIMEOUT_MS)
154
+ }),
155
+ ])
156
+ clearTimeout(timer)
157
+ if (exitCode === -1) {
158
+ proc.kill()
159
+ return {
160
+ success: false,
161
+ content: '',
162
+ error: `git worktree add did not finish within ${WORKTREE_ADD_TIMEOUT_MS / 1000}s.`,
163
+ }
164
+ }
141
165
 
142
166
  if (exitCode !== 0) {
143
167
  const stderr = await new Response(proc.stderr).text()
@@ -307,11 +307,19 @@ export const webFetchTool: ToolDefinition = {
307
307
  const contentType = response.headers.get('content-type') || ''
308
308
  const isHtml = contentType.includes('text/html') || contentType.includes('application/xhtml')
309
309
 
310
+ // A 4xx/5xx is a statement about the site, not a failure of the tool:
311
+ // hand the status and whatever body it returned to the model as a normal
312
+ // result, so it can re-aim the request instead of treating the fetch as
313
+ // broken. Deliberately not cached — a 404 today may be a 200 tomorrow.
310
314
  if (!response.ok) {
315
+ const body = await response.text().catch(() => '')
316
+ const text = isHtml ? htmlToMarkdown(body, response.url || url) : body
311
317
  return {
312
- success: false,
313
- content: '',
314
- error: `HTTP ${response.status}: ${response.statusText}`,
318
+ success: true,
319
+ content:
320
+ `HTTP ${response.status}: ${response.statusText}` +
321
+ (text ? `\n\n${text.slice(0, MAX_RETURN_CHARS)}` : ''),
322
+ metadata: { url, status: response.status },
315
323
  }
316
324
  }
317
325
 
@@ -158,8 +158,12 @@ export const webSearchTool: ToolDefinition = {
158
158
  return {
159
159
  success: false,
160
160
  content: '',
161
+ // 说清楚「绕不过去」:不写这一句,模型最常见的下一步是改用 WebFetch
162
+ // 或浏览器去同一个站点再问一遍 —— 那既不会恢复配额,又是另一份预算。
161
163
  error:
162
- 'Brave Search API rate limit reached (2,000/month on free tier). Try again later.',
164
+ 'Brave Search API rate limit reached (2,000/month on free tier). ' +
165
+ 'Do not route around it with WebFetch or a browser — the quota is spent ' +
166
+ 'either way. Tell the user and wait for it to reset.',
163
167
  }
164
168
  }
165
169
  if (response.status === 401) {
@@ -173,7 +173,7 @@ export function resumeWakeups(opts: { sessionId: string; now?: Date }): LostWake
173
173
  export const scheduleWakeupTool: ToolDefinition = {
174
174
  name: 'ScheduleWakeup',
175
175
  description:
176
- 'Schedule when to resume work in /loop dynamic mode — the user invoked /loop without an interval, asking you to self-pace iterations of a specific task. Do NOT schedule a short-interval wakeup to poll for background work you started — when harness-tracked work finishes, you are re-invoked automatically. The runtime clamps to [60, 3600].',
176
+ 'Schedule when to resume work in /loop dynamic mode — the user invoked /loop without an interval, asking you to self-pace iterations of a specific task. Do NOT schedule a short-interval wakeup to poll for background work you started — when harness-tracked work finishes, you are re-invoked automatically. The runtime clamps to [60, 3600]. Pick the delay by cache window, not by round minutes: sleeping past 300s means the next turn re-reads the conversation uncached. Use 60–270s while actively watching something nothing else will notify you about, 1200–1800s for idle waits. Avoid exactly 300s (pays the cache miss without buying a long wait), and do NOT pick 3600 — that fires just after the 1-hour prompt cache expires, so the full re-read buys nothing; 3300 or less lands inside the window.',
177
177
  category: 'scheduling',
178
178
  permission: 'self',
179
179
  parameters: {
@@ -181,7 +181,8 @@ export const scheduleWakeupTool: ToolDefinition = {
181
181
  properties: {
182
182
  delaySeconds: {
183
183
  type: 'number',
184
- description: 'Seconds from now to wake up. Clamped to [60, 3600] by the runtime.',
184
+ description:
185
+ 'Seconds from now to wake up. Clamped to [60, 3600] by the runtime; prefer 3300 or less so the next turn stays inside the prompt-cache window.',
185
186
  },
186
187
  reason: {
187
188
  type: 'string',
@@ -76,6 +76,17 @@ export function withValidation(tool: ToolDefinition): ToolDefinition {
76
76
  return {
77
77
  ...tool,
78
78
  async execute(params, ctx): Promise<ToolResult> {
79
+ // 参数不是合法 JSON 时,providers 交回的是 `{ _parseError, _raw }` 而不是
80
+ // `{}`。照常校验的话,模型会读到「缺少必需参数 url」—— 一个它明明写过的
81
+ // 参数,于是它去补参数,而不是去补那半个 JSON。先把这个事实说清楚。
82
+ if (typeof params._parseError === 'string') {
83
+ return {
84
+ success: false,
85
+ content: '',
86
+ error: t('errors.unparseable_args', { detail: params._parseError }),
87
+ }
88
+ }
89
+
79
90
  const cleanParams = sanitizeParams(params)
80
91
  const errors = validateParams(schema, cleanParams)
81
92
  if (errors.length > 0) {
package/src/ui/app.tsx CHANGED
@@ -61,7 +61,7 @@ import {
61
61
  } from './commands'
62
62
  import { useI18n } from '../i18n-context'
63
63
  import type { PermissionMode } from '../shared/index.ts'
64
- import { sanitizeForDisplay } from '../shared/sanitize.ts'
64
+ import { safeSlice, sanitizeForDisplay } from '../shared/sanitize.ts'
65
65
  import { recordLoopTurn, readAutoloopJournal } from '../commands/autoloop-journal.js'
66
66
  import { cancelAllSessionTimers, resumeWakeups } from '../tools/scheduling/schedule-wakeup.js'
67
67
  import type { LostWakeup } from '../tools/scheduling/schedule-wakeup.js'
@@ -188,10 +188,7 @@ export function cyclePermissionMode(
188
188
  /** 预览截断按 UTF-16 码元计数,落点若正好夹在一个代理对中间,切完就留下
189
189
  * **半个** emoji(终端渲染成 U+FFFD)。落点是高代理时后退一个码元即可。 */
190
190
  export function truncateForDisplay(text: string, max: number): string {
191
- if (text.length <= max) return text
192
- const last = text.charCodeAt(max - 1)
193
- const end = last >= 0xd800 && last <= 0xdbff ? max - 1 : max
194
- return text.slice(0, end)
191
+ return safeSlice(text, max)
195
192
  }
196
193
 
197
194
  /** Format a tool's input parameters into a compact one-line detail string.
@@ -539,11 +536,29 @@ export function App({
539
536
  setGoal: (text: string) => setGoalText(text),
540
537
  setUltracodeMode: (on: boolean) => setUltracodeMode(on),
541
538
  setUpdateStatus: (s: UpdateStatus) => setUpdateStatus(s),
539
+ // Same read-back as Shift+Tab: `setMode` may clamp the request (org
540
+ // `maxAllowedMode` / `forbiddenModes`), so the footer and the gate must
541
+ // both read the mode that took effect, not the one we asked for.
542
+ setPermissionMode: (mode: PermissionMode) => {
543
+ const permission = engine.getPermission() as PermissionSource
544
+ permission.setMode(mode)
545
+ setPermissionMode(permission.getMode())
546
+ },
542
547
  skillsLoader,
543
548
  pluginManager,
544
549
  t,
545
550
  }),
546
- [engine, config, providerId, modelId, skillsLoader, pluginManager, sessionId, t],
551
+ [
552
+ engine,
553
+ config,
554
+ providerId,
555
+ modelId,
556
+ skillsLoader,
557
+ pluginManager,
558
+ sessionId,
559
+ t,
560
+ setPermissionMode,
561
+ ],
547
562
  )
548
563
 
549
564
  const handleApiKeySubmit = useCallback(
@@ -806,7 +821,7 @@ export function App({
806
821
  const lineCount = newContent.split('\n').length
807
822
  preview = `Updated ${filePath} · ${lineCount} lines`
808
823
  } else {
809
- const firstLine = output.split('\n')[0]!.slice(0, 200)
824
+ const firstLine = safeSlice(output.split('\n')[0]!, 200)
810
825
  preview = firstLine.length < output.length ? `${firstLine}...` : firstLine
811
826
  }
812
827
  setMessages((prev) => [
package/src/ui/chat.tsx CHANGED
@@ -4,6 +4,7 @@ import { useI18n } from '../i18n-context'
4
4
  import type { ChatMessage } from './app'
5
5
  import {
6
6
  decodeDisplayEntities,
7
+ safeSlice,
7
8
  sanitizeInlineField,
8
9
  stripControlCharsForDisplay,
9
10
  } from '../shared/sanitize'
@@ -130,12 +131,12 @@ const MessageRow = React.memo(
130
131
  <Text dimColor>
131
132
  {' ⎿ '}
132
133
  {t('ui.tool.not_run')}
133
- {msg.toolMeta.output ? ` — ${display(msg.toolMeta.output).slice(0, 300)}` : ''}
134
+ {msg.toolMeta.output ? ` — ${safeSlice(display(msg.toolMeta.output), 300)}` : ''}
134
135
  </Text>
135
136
  ) : msg.toolMeta.output ? (
136
137
  <Text dimColor>
137
138
  {' ⎿ '}
138
- {display(msg.toolMeta.output).slice(0, 300)}
139
+ {safeSlice(display(msg.toolMeta.output), 300)}
139
140
  </Text>
140
141
  ) : msg.content && !msg.toolMeta.collapsed ? (
141
142
  <Text dimColor>{display(msg.content)}</Text>
@@ -8,10 +8,11 @@ import type { QueryEngine } from '../core/engine'
8
8
  import type { MiphamConfig } from '../shared/index.ts'
9
9
  import { formatContextWindow } from '../shared/format'
10
10
  import { sanitizeInlineField } from '../shared/sanitize'
11
- import type { SkillsLoader } from '../skills/loader'
11
+ import { internalGitEnv } from '../shared/git-env'
12
+ import { truncateSkillDescription, type SkillsLoader } from '../skills/loader'
12
13
  import { loadSkillUsage } from '../skills/usage'
13
14
  import type { PluginManager } from '../plugin/plugin-manager'
14
- import type { Message } from '../shared/types.js'
15
+ import type { Message, PermissionMode } from '../shared/types.js'
15
16
  import type { CopyPickerItem } from './copy-picker'
16
17
  import type { InstallState, UpdateStatus } from '../shared/update'
17
18
  import { McpClient } from '../mcp/client'
@@ -134,6 +135,10 @@ export interface CommandContext {
134
135
  setGoal: (text: string) => void
135
136
  setUltracodeMode: (on: boolean) => void
136
137
  setUpdateStatus: (s: UpdateStatus) => void
138
+ /** Request a permission-mode change and let the App read back the mode that
139
+ * actually took effect (org limits can clamp it). Absent on surfaces that
140
+ * cannot switch modes (e.g. a remote attach stub). */
141
+ setPermissionMode?: (mode: PermissionMode) => void
137
142
  skillsLoader?: SkillsLoader
138
143
  pluginManager?: PluginManager
139
144
  /** i18n translate function — populated from React tree via useI18n().
@@ -281,7 +286,7 @@ const helpCmd: CommandHandler = (ctx) => {
281
286
  /setup Guided project setup wizard
282
287
  /recommend Analyze project + recommend setup
283
288
  /permissions Show or persist permission rules
284
- /add-dir <dir> Add workspace directory
289
+ /add-dir <dir> Check a path + how access is decided
285
290
  /security Security review checklist
286
291
  /audit Same as /security
287
292
 
@@ -408,6 +413,48 @@ function liveMode(ctx: CommandContext): string {
408
413
  return ctx.engine.getPermission().getMode()
409
414
  }
410
415
 
416
+ /**
417
+ * `ExitPlanMode` tells the model, in its tool result, that the user can approve
418
+ * by saying "approved" **or `/approve`**. Before this handler existed that second
419
+ * half was advice with no landing point: `/approve` fell through to the
420
+ * unknown-command path, nothing switched modes, and the next turn began in the
421
+ * same limited mode the model had just been told would lift.
422
+ *
423
+ * Only `plan` is approvable. Every other mode either has no plan pending, or is
424
+ * already wider than what approval grants — silently widening those would make a
425
+ * stray `/approve` a permission escalation.
426
+ */
427
+ const approveCmd: CommandHandler = async (ctx) => {
428
+ const mode = liveMode(ctx)
429
+ if (mode !== 'plan') {
430
+ return {
431
+ content:
432
+ `Nothing to approve — not in plan mode (current mode: ${mode}).\n` +
433
+ 'Approval only switches a plan under review to acceptEdits.',
434
+ }
435
+ }
436
+ if (!ctx.setPermissionMode) {
437
+ return {
438
+ content:
439
+ 'This surface cannot switch permission modes. Use Shift+Tab to cycle to acceptEdits.',
440
+ }
441
+ }
442
+ ctx.setPermissionMode('acceptEdits')
443
+ const now = liveMode(ctx)
444
+ if (now !== 'acceptEdits') {
445
+ return {
446
+ content:
447
+ `Plan approved, but the organisation's permission limit kept the mode at ${now} ` +
448
+ '(not acceptEdits) — edits will still be refused.',
449
+ }
450
+ }
451
+ return {
452
+ content:
453
+ '✓ Plan approved — switched to acceptEdits. File writes and edits are applied without ' +
454
+ 'prompting; commands still follow the usual rules. Shift+Tab to narrow it again.',
455
+ }
456
+ }
457
+
411
458
  const statusCmd: CommandHandler = async (ctx) => {
412
459
  const t = resolveT(ctx)
413
460
  const c = ctx.engine.getContext()
@@ -677,10 +724,11 @@ const skillsCmd: CommandHandler = (ctx) => {
677
724
 
678
725
  const lines: string[] = [
679
726
  `── Standard Skills (${counts.standard}) ──`,
680
- ...standard.map((s) => ` ${s.name.padEnd(28)} ${s.description}`),
727
+ // 描述是写给模型的(常是好几段指令),不是终端里的一行摘要。
728
+ ...standard.map((s) => ` ${s.name.padEnd(28)} ${truncateSkillDescription(s.description)}`),
681
729
  '',
682
730
  `── Mipham Exclusive (${counts.mipham}) ──`,
683
- ...mipham.map((s) => ` ${s.name.padEnd(20)} ${s.description}`),
731
+ ...mipham.map((s) => ` ${s.name.padEnd(20)} ${truncateSkillDescription(s.description)}`),
684
732
  '',
685
733
  t('commands.skills.loaded', { count: String(counts.total) }),
686
734
  ]
@@ -2534,7 +2582,7 @@ const reloadSkillsCmd: CommandHandler = (ctx) => {
2534
2582
  }
2535
2583
  const skills = ctx.skillsLoader.list()
2536
2584
  return {
2537
- content: `${t('commands.reload_skills.confirmed', { count: String(skills.length) })}\n\n${skills.map((s) => ` ${s.name.padEnd(28)} ${s.type.padEnd(10)} ${s.description}`).join('\n')}`,
2585
+ content: `${t('commands.reload_skills.confirmed', { count: String(skills.length) })}\n\n${skills.map((s) => ` ${s.name.padEnd(28)} ${s.type.padEnd(10)} ${truncateSkillDescription(s.description)}`).join('\n')}`,
2538
2586
  }
2539
2587
  } catch (err) {
2540
2588
  return { content: t('commands.reload_skills.failed', { error: String(err) }) }
@@ -3230,7 +3278,8 @@ const loopCmd: CommandHandler = async (ctx, args) => {
3230
3278
  `You are in an autonomous loop. Each iteration:\n` +
3231
3279
  `1. Make progress on the task above\n` +
3232
3280
  `2. When you need to wait (e.g., for a deploy, CI, external event), call ScheduleWakeup with:\n` +
3233
- ` - delaySeconds: your best estimate of how long to wait (60-3600)\n` +
3281
+ ` - delaySeconds: your best estimate of how long to wait (60-3600; prefer ≤3300\n` +
3282
+ ` so the wake-up stays inside the prompt-cache window)\n` +
3234
3283
  ` - reason: one sentence explaining why\n` +
3235
3284
  ` - prompt: include this full autonomous loop ID: ${sessionId}\n` +
3236
3285
  `3. When the task is COMPLETE, call ScheduleWakeup with stop:true\n` +
@@ -4316,10 +4365,13 @@ const prCommentsCmd: CommandHandler = async () => {
4316
4365
  encoding: 'utf-8',
4317
4366
  timeout: 3000,
4318
4367
  }).trim()
4368
+ // The pipeline greps the English header, so git must not localize it:
4369
+ // a Chinese git prints `HEAD 分支:` and this silently lands on `main`.
4319
4370
  const mainBranch =
4320
4371
  execSync('git remote show origin 2>/dev/null | grep "HEAD branch" | cut -d: -f2', {
4321
4372
  encoding: 'utf-8',
4322
4373
  timeout: 3000,
4374
+ env: { ...process.env, LC_ALL: 'C', LANG: 'C' },
4323
4375
  }).trim() || 'main'
4324
4376
 
4325
4377
  // Get diff stats vs main
@@ -5592,6 +5644,7 @@ const forkCmd: CommandHandler = async (ctx, args) => {
5592
5644
  execFileSync('git', ['worktree', 'add', '-b', branch, wtPath, 'HEAD'], {
5593
5645
  stdio: 'ignore',
5594
5646
  timeout: 30_000,
5647
+ env: internalGitEnv(),
5595
5648
  })
5596
5649
  } catch (err) {
5597
5650
  try {
@@ -6095,6 +6148,7 @@ registry.set('/init', initCmd)
6095
6148
  registry.set('/setup', setupCmd)
6096
6149
  registry.set('/recommend', recommendCmd)
6097
6150
  registry.set('/permissions', permissionsCmd)
6151
+ registry.set('/approve', approveCmd)
6098
6152
  registry.set('/add-dir', addDirCmd)
6099
6153
  registry.set('/security', securityCmd)
6100
6154
  registry.set('/audit', securityCmd)