@miphamai/cli 0.85.24 → 0.85.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +3 -3
  2. package/bin/mipham.ts +34 -24
  3. package/package.json +1 -1
  4. package/src/agent/agent-context.ts +23 -3
  5. package/src/agent/sub-agent.ts +29 -15
  6. package/src/artifacts/server.ts +5 -1
  7. package/src/commands/git.ts +9 -1
  8. package/src/commands/project.ts +34 -17
  9. package/src/core/context-token.ts +55 -3
  10. package/src/core/context.ts +54 -42
  11. package/src/core/crsi-sandbox.ts +5 -1
  12. package/src/core/engine.ts +91 -10
  13. package/src/core/instructions.ts +130 -18
  14. package/src/core/permission-rule-ack.ts +67 -0
  15. package/src/core/permission-rules.ts +141 -25
  16. package/src/daemon/remote-engine.ts +11 -5
  17. package/src/daemon/schedule-manager.ts +32 -3
  18. package/src/daemon/server.ts +6 -0
  19. package/src/i18n-core/locales/en-US.json +1 -1
  20. package/src/i18n-core/locales/zh-CN.json +1 -1
  21. package/src/index.tsx +34 -4
  22. package/src/mcp/client.ts +37 -2
  23. package/src/mcp/http-transport.ts +20 -1
  24. package/src/mcp/protocol.ts +13 -5
  25. package/src/mcp/registry.ts +8 -3
  26. package/src/mcp/transport.ts +40 -3
  27. package/src/plugin/plugin-manager.ts +23 -2
  28. package/src/providers/anthropic.ts +3 -1
  29. package/src/providers/fetch-utils.ts +40 -6
  30. package/src/providers/openai-compat.ts +2 -1
  31. package/src/providers/registry.ts +23 -1
  32. package/src/shared/git-env.ts +18 -0
  33. package/src/shared/package-info.ts +3 -3
  34. package/src/shared/sanitize.ts +21 -0
  35. package/src/shared/types.ts +9 -0
  36. package/src/skills/loader.ts +14 -0
  37. package/src/tools/exec/bash.ts +168 -6
  38. package/src/tools/exec/enter-worktree.ts +26 -2
  39. package/src/tools/exec/task.ts +144 -21
  40. package/src/tools/network/web-fetch.ts +7 -7
  41. package/src/tools/network/web-search.ts +6 -5
  42. package/src/ui/app.tsx +22 -7
  43. package/src/ui/chat.tsx +3 -2
  44. package/src/ui/commands.ts +65 -5
  45. package/src/workflow/primitives/agent.ts +17 -1
@@ -132,14 +132,15 @@ export const webSearchTool: ToolDefinition = {
132
132
  }
133
133
  }
134
134
 
135
+ // The timer spans the body read too: headers followed by a stalled body is
136
+ // the same hang as a request that never answers.
137
+ const controller = new AbortController()
138
+ const timer = setTimeout(() => controller.abort(), 15_000) // 15s timeout
135
139
  try {
136
140
  const url = new URL(BRAVE_API)
137
141
  url.searchParams.set('q', query)
138
142
  url.searchParams.set('count', String(MAX_RESULTS))
139
143
 
140
- const controller = new AbortController()
141
- const timer = setTimeout(() => controller.abort(), 15_000) // 15s timeout
142
-
143
144
  const response = await fetch(url.toString(), {
144
145
  headers: {
145
146
  Accept: 'application/json',
@@ -149,8 +150,6 @@ export const webSearchTool: ToolDefinition = {
149
150
  signal: controller.signal,
150
151
  })
151
152
 
152
- clearTimeout(timer)
153
-
154
153
  if (!response.ok) {
155
154
  const body = await response.text().catch(() => '')
156
155
  // 429 = rate limit, 401 = bad key
@@ -207,6 +206,8 @@ export const webSearchTool: ToolDefinition = {
207
206
  ? 'Search timed out (15s). Try a more specific query.'
208
207
  : `Search failed: ${String(err)}. If direct network is blocked, retry via the web-access skill (CDP through the user's logged-in Chrome).`
209
208
  return { success: false, content: '', error: message }
209
+ } finally {
210
+ clearTimeout(timer)
210
211
  }
211
212
  },
212
213
  }
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 { internalGitEnv } from '../shared/git-env'
11
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'
@@ -118,7 +119,7 @@ import { listActiveAutoloops, formatLoopRows } from '../commands/autoloop-journa
118
119
  import { execSync } from 'node:child_process'
119
120
  import { MIPHAM_DIR, OLLAMA_PRESET_MODELS } from '../shared/constants'
120
121
  import { renameActiveSession } from '../agent/cross-session/discovery'
121
- import { formatTaskList } from '../tools/exec/task'
122
+ import { clearTasks, formatTaskList } from '../tools/exec/task'
122
123
 
123
124
  export interface CommandContext {
124
125
  engine: QueryEngine
@@ -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
 
@@ -335,6 +340,10 @@ const versionCmd: CommandHandler = (ctx) => {
335
340
 
336
341
  const clearCmd: CommandHandler = (ctx) => {
337
342
  ctx.engine.getContext().clear()
343
+ // The task list outlives the process now, so "start over" has to say so
344
+ // explicitly — otherwise the old plan comes back on resume and the panel keeps
345
+ // showing tasks from a conversation the user just discarded.
346
+ clearTasks(ctx.sessionId)
338
347
  const t = resolveT(ctx)
339
348
  return { content: t('commands.clear.confirmed'), clearMessages: true }
340
349
  }
@@ -408,6 +417,48 @@ function liveMode(ctx: CommandContext): string {
408
417
  return ctx.engine.getPermission().getMode()
409
418
  }
410
419
 
420
+ /**
421
+ * `ExitPlanMode` tells the model, in its tool result, that the user can approve
422
+ * by saying "approved" **or `/approve`**. Before this handler existed that second
423
+ * half was advice with no landing point: `/approve` fell through to the
424
+ * unknown-command path, nothing switched modes, and the next turn began in the
425
+ * same limited mode the model had just been told would lift.
426
+ *
427
+ * Only `plan` is approvable. Every other mode either has no plan pending, or is
428
+ * already wider than what approval grants — silently widening those would make a
429
+ * stray `/approve` a permission escalation.
430
+ */
431
+ const approveCmd: CommandHandler = async (ctx) => {
432
+ const mode = liveMode(ctx)
433
+ if (mode !== 'plan') {
434
+ return {
435
+ content:
436
+ `Nothing to approve — not in plan mode (current mode: ${mode}).\n` +
437
+ 'Approval only switches a plan under review to acceptEdits.',
438
+ }
439
+ }
440
+ if (!ctx.setPermissionMode) {
441
+ return {
442
+ content:
443
+ 'This surface cannot switch permission modes. Use Shift+Tab to cycle to acceptEdits.',
444
+ }
445
+ }
446
+ ctx.setPermissionMode('acceptEdits')
447
+ const now = liveMode(ctx)
448
+ if (now !== 'acceptEdits') {
449
+ return {
450
+ content:
451
+ `Plan approved, but the organisation's permission limit kept the mode at ${now} ` +
452
+ '(not acceptEdits) — edits will still be refused.',
453
+ }
454
+ }
455
+ return {
456
+ content:
457
+ '✓ Plan approved — switched to acceptEdits. File writes and edits are applied without ' +
458
+ 'prompting; commands still follow the usual rules. Shift+Tab to narrow it again.',
459
+ }
460
+ }
461
+
411
462
  const statusCmd: CommandHandler = async (ctx) => {
412
463
  const t = resolveT(ctx)
413
464
  const c = ctx.engine.getContext()
@@ -3049,7 +3100,7 @@ const tasksCmd: CommandHandler = (ctx) => {
3049
3100
  // 却有历史时又会说「检测到 N 次任务操作」。面板自称 "Background tasks"、标题写
3050
3101
  // 「后台任务」、空态写「尚未跟踪任何任务」—— 全是登记表词汇,而登记表就在
3051
3102
  // 一步之外(`getTasks()`,`GoalProgress` 早就接了)。
3052
- const taskList = formatTaskList()
3103
+ const taskList = formatTaskList(ctx.sessionId)
3053
3104
  const hasTasks = taskList !== '(no tasks)'
3054
3105
 
3055
3106
  return {
@@ -3783,7 +3834,11 @@ const codeReviewCmd = gitDiffBridgeCmd({
3783
3834
  : maxFindings.value === 'default'
3784
3835
  ? ''
3785
3836
  : ` Report at most ${maxFindings.value} findings, most severe first.`
3786
- return `use the code-review skill to review all uncommitted changes. Check all 7 dimensions: correctness, security, performance, code quality, architecture & design, testing, and language-specific issues. Use effort level: ${getPreference('lastCodeReviewEffort', 'high')}.${cap}`
3837
+ // 档位放在**最前**:它是这一轮的工作量,后面那句「查哪七个维度」是它的宾语。
3838
+ // 写成句末时模型容易先按默认深度铺开、再拿档位去追认。`max` 另有一句上限:
3839
+ // 仓里存的可能是上一轮自己挑的,而不是用户这一轮要的 —— 只有**用户点名**才用。
3840
+ const effort = getPreference('lastCodeReviewEffort', 'high')
3841
+ return `Use effort level: ${effort} — settle this before you start; never pick max on your own, only when the user asked for it. Then use the code-review skill to review all uncommitted changes. Check all 7 dimensions: correctness, security, performance, code quality, architecture & design, testing, and language-specific issues.${cap}`
3787
3842
  },
3788
3843
  })
3789
3844
 
@@ -4318,10 +4373,13 @@ const prCommentsCmd: CommandHandler = async () => {
4318
4373
  encoding: 'utf-8',
4319
4374
  timeout: 3000,
4320
4375
  }).trim()
4376
+ // The pipeline greps the English header, so git must not localize it:
4377
+ // a Chinese git prints `HEAD 分支:` and this silently lands on `main`.
4321
4378
  const mainBranch =
4322
4379
  execSync('git remote show origin 2>/dev/null | grep "HEAD branch" | cut -d: -f2', {
4323
4380
  encoding: 'utf-8',
4324
4381
  timeout: 3000,
4382
+ env: { ...process.env, LC_ALL: 'C', LANG: 'C' },
4325
4383
  }).trim() || 'main'
4326
4384
 
4327
4385
  // Get diff stats vs main
@@ -5594,6 +5652,7 @@ const forkCmd: CommandHandler = async (ctx, args) => {
5594
5652
  execFileSync('git', ['worktree', 'add', '-b', branch, wtPath, 'HEAD'], {
5595
5653
  stdio: 'ignore',
5596
5654
  timeout: 30_000,
5655
+ env: internalGitEnv(),
5597
5656
  })
5598
5657
  } catch (err) {
5599
5658
  try {
@@ -6097,6 +6156,7 @@ registry.set('/init', initCmd)
6097
6156
  registry.set('/setup', setupCmd)
6098
6157
  registry.set('/recommend', recommendCmd)
6099
6158
  registry.set('/permissions', permissionsCmd)
6159
+ registry.set('/approve', approveCmd)
6100
6160
  registry.set('/add-dir', addDirCmd)
6101
6161
  registry.set('/security', securityCmd)
6102
6162
  registry.set('/audit', securityCmd)
@@ -5,8 +5,12 @@ import type { Llm } from '../../providers/llm'
5
5
  import type { ToolDefinition } from '../../shared/index.ts'
6
6
  import type { PermissionSystem } from '../../core/permission'
7
7
  import { worktreeRoot } from '../../core/paths.ts'
8
+ import { internalGitEnv } from '../../shared/git-env'
8
9
  import { validateJSONSchema, formatValidationErrors } from '../schema-validator'
9
10
 
11
+ /** Upper bound for `git worktree add` — a hung fetch must not hang the run. */
12
+ const WORKTREE_ADD_TIMEOUT_MS = 60_000
13
+
10
14
  /**
11
15
  * Effective model for a workflow agent.
12
16
  *
@@ -80,8 +84,20 @@ export async function workflowAgent(
80
84
  const proc = Bun.spawn(['git', 'worktree', 'add', '-b', worktreeBranch, worktreePath, 'HEAD'], {
81
85
  stdout: 'pipe',
82
86
  stderr: 'pipe',
87
+ env: internalGitEnv(),
83
88
  })
84
- const exitCode = await proc.exited
89
+ let timer: ReturnType<typeof setTimeout> | undefined
90
+ const exitCode = await Promise.race([
91
+ proc.exited,
92
+ new Promise<number>((resolve) => {
93
+ timer = setTimeout(() => resolve(-1), WORKTREE_ADD_TIMEOUT_MS)
94
+ }),
95
+ ])
96
+ clearTimeout(timer)
97
+ if (exitCode === -1) {
98
+ proc.kill()
99
+ throw new Error(`Worktree creation timed out after ${WORKTREE_ADD_TIMEOUT_MS / 1000}s`)
100
+ }
85
101
  if (exitCode !== 0) {
86
102
  const stderr = await new Response(proc.stderr).text()
87
103
  throw new Error(`Worktree creation failed: ${stderr.slice(0, 500)}`)