@miphamai/cli 0.85.32 → 0.85.34

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 (53) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/src/agent/services.ts +21 -0
  4. package/src/agent/sub-agent.ts +129 -21
  5. package/src/commands/environment.ts +14 -11
  6. package/src/commands/project.ts +43 -12
  7. package/src/config/loader.ts +65 -35
  8. package/src/core/alignment-vocabulary.json +2 -2
  9. package/src/core/constitution-loader.ts +85 -24
  10. package/src/core/credential-masker/env-filter.ts +37 -0
  11. package/src/core/engine.ts +59 -140
  12. package/src/core/permission-rules.ts +163 -14
  13. package/src/core/permission.ts +14 -1
  14. package/src/core/session-log.ts +11 -0
  15. package/src/core/session-store.ts +4 -3
  16. package/src/core/tool-gate.ts +222 -0
  17. package/src/core/workspace-trust.ts +50 -17
  18. package/src/daemon/remote-engine.ts +3 -0
  19. package/src/i18n-core/locales/en-US.json +1 -0
  20. package/src/i18n-core/locales/zh-CN.json +1 -0
  21. package/src/index.tsx +6 -0
  22. package/src/mcp/client.ts +22 -2
  23. package/src/mcp/protocol.ts +16 -2
  24. package/src/plugin/plugin-manager.ts +29 -3
  25. package/src/providers/fetch-utils.ts +49 -0
  26. package/src/providers/openai-compat.ts +28 -2
  27. package/src/shared/git-env.ts +37 -13
  28. package/src/shared/package-info.ts +2 -2
  29. package/src/shared/sanitize.ts +17 -0
  30. package/src/shared/types.ts +8 -0
  31. package/src/skills/fork-executor.ts +11 -1
  32. package/src/skills/marketplace.ts +44 -13
  33. package/src/skills/registry.ts +12 -1
  34. package/src/tools/agent/agent.ts +3 -0
  35. package/src/tools/agent/enter-plan.ts +22 -4
  36. package/src/tools/agent/exit-plan.ts +9 -1
  37. package/src/tools/agent/skill.ts +1 -0
  38. package/src/tools/agent/workflow.ts +1 -0
  39. package/src/tools/computer/browser.ts +13 -0
  40. package/src/tools/exec/git.ts +113 -69
  41. package/src/tools/file/edit.ts +19 -3
  42. package/src/tools/file/grep.ts +5 -1
  43. package/src/tools/file/write.ts +18 -1
  44. package/src/tools/index.ts +2 -2
  45. package/src/tools/network/web-fetch.ts +12 -0
  46. package/src/tools/system/tool-search.ts +35 -3
  47. package/src/ui/app.tsx +105 -4
  48. package/src/ui/chat.tsx +21 -7
  49. package/src/ui/commands.ts +127 -18
  50. package/src/workflow/primitives/agent.ts +12 -1
  51. package/src/workflow/primitives/loop.ts +14 -0
  52. package/src/workflow/primitives/verify.ts +13 -1
  53. package/src/workflow/runtime.ts +1 -0
package/src/ui/chat.tsx CHANGED
@@ -68,10 +68,13 @@ function capRenderedLines(text: string): string {
68
68
  function displayCwd(): string {
69
69
  const cwd = process.cwd()
70
70
  const home = homedir()
71
- if (home && cwd.startsWith(home)) {
72
- return '~' + cwd.slice(home.length)
73
- }
74
- return cwd
71
+ const shown = home && cwd.startsWith(home) ? '~' + cwd.slice(home.length) : cwd
72
+ // A folder name can contain a newline or an escape sequence (they are just
73
+ // bytes on every filesystem this runs on). The header is one line and is
74
+ // written to the terminal verbatim, so the same inline strip the tool name
75
+ // gets applies here — otherwise the "header" can split into lines or carry a
76
+ // raw SGR the user cannot see.
77
+ return sanitizeInlineField(shown)
75
78
  }
76
79
 
77
80
  /** Map tool names to dot colors — Claude Code parity */
@@ -133,6 +136,14 @@ const MessageRow = React.memo(
133
136
  {t('ui.tool.not_run')}
134
137
  {msg.toolMeta.output ? ` — ${safeSlice(display(msg.toolMeta.output), 300)}` : ''}
135
138
  </Text>
139
+ ) : msg.toolMeta.noResult ? (
140
+ // The call ended without output. Saying so is the point: an empty
141
+ // result line is indistinguishable from a call that is still
142
+ // running (323-079).
143
+ <Text dimColor>
144
+ {' ⎿ '}
145
+ {t('ui.tool.no_result_recorded')}
146
+ </Text>
136
147
  ) : msg.toolMeta.output ? (
137
148
  <Text dimColor>
138
149
  {' ⎿ '}
@@ -256,8 +267,10 @@ function compactToolGroups(messages: ChatMessage[]): ChatMessage[] {
256
267
  continue
257
268
  }
258
269
 
259
- // Tool result (no name, has output) → merge output into current tool
260
- if (msg.toolMeta && !msg.toolMeta.name && msg.toolMeta.output) {
270
+ // Tool result (no name, has output or records its ending) → merge into
271
+ // the current tool. `noResult` rows carry no output, so a merge condition
272
+ // that only looked at `output` left them as separate nameless rows.
273
+ if (msg.toolMeta && !msg.toolMeta.name && (msg.toolMeta.output || msg.toolMeta.noResult)) {
261
274
  if (current) {
262
275
  current = {
263
276
  ...current,
@@ -268,6 +281,7 @@ function compactToolGroups(messages: ChatMessage[]): ChatMessage[] {
268
281
  // 结果行上的标记必须跟着合并走:合并把结果行的 toolMeta 并进工具调用行,
269
282
  // 漏掉它,`notRun` 就停在**没人渲染的那一份**上(296-056)。
270
283
  ...(msg.toolMeta.notRun ? { notRun: true } : {}),
284
+ ...(msg.toolMeta.noResult ? { noResult: true } : {}),
271
285
  },
272
286
  }
273
287
  }
@@ -281,7 +295,7 @@ function compactToolGroups(messages: ChatMessage[]): ChatMessage[] {
281
295
  current = null
282
296
  }
283
297
  // Skip orphan tool-result messages without a preceding tool_use
284
- if (msg.toolMeta && !msg.toolMeta.name && msg.toolMeta.output) {
298
+ if (msg.toolMeta && !msg.toolMeta.name && (msg.toolMeta.output || msg.toolMeta.noResult)) {
285
299
  continue
286
300
  }
287
301
  result.push(msg)
@@ -647,6 +647,20 @@ const switchCmd: CommandHandler = (ctx, args) => {
647
647
  return { content: t('commands.switch.usage') }
648
648
  }
649
649
 
650
+ // 远程 attach 模式:`switchProvider` 在 RemoteEngine 上是 no-op。从前这里照样
651
+ // 回「✓ Switched」并把 nextProvider/nextModel 交给页脚 —— 页脚换了、daemon 还跑
652
+ // 着原来的模型,一次没发生的切换与一次成功的切换长得一模一样。
653
+ //
654
+ // 放在 provider/API key 检查**之前**:attach 时本地这份配置不是判据 ——
655
+ // 「这个 provider 没配 key」在这里既不真(key 在 daemon 那边)也不是用户能修的东西。
656
+ if (ctx.engine.isRemote) {
657
+ return {
658
+ content:
659
+ `Cannot switch to ${newProvider}/${newModel}: this session is attached to a daemon, ` +
660
+ 'and the model is chosen on the daemon side. Change it there, or start a local session.',
661
+ }
662
+ }
663
+
650
664
  const provider = ctx.config.providers.find((p) => p.id === newProvider)
651
665
  if (!provider) {
652
666
  return { content: t('commands.switch.unknown_provider', { provider: newProvider }) }
@@ -2245,8 +2259,16 @@ const changelogCmd: CommandHandler = async (ctx) => {
2245
2259
  const lines: string[] = [t('commands.changelog.title'), '']
2246
2260
 
2247
2261
  try {
2248
- const { execSync } = await import('node:child_process')
2249
- const tags = execSync('git tag --sort=-creatordate', { encoding: 'utf-8', timeout: 5000 })
2262
+ // A tag name is repository-controlled data, not a word we chose: a cloned
2263
+ // repository can contain `v1$(rm -rf …)`, and a shell string would run it.
2264
+ // `execFileSync` passes argv without a shell, so nothing in a tag is ever
2265
+ // interpreted. The log window is sliced here for the same reason — a
2266
+ // `| head -8` inside the command string is a second shell.
2267
+ const { execFileSync } = await import('node:child_process')
2268
+ const tags = execFileSync('git', ['tag', '--sort=-creatordate'], {
2269
+ encoding: 'utf-8',
2270
+ timeout: 5000,
2271
+ })
2250
2272
  .trim()
2251
2273
  .split('\n')
2252
2274
  .filter(Boolean)
@@ -2264,13 +2286,14 @@ const changelogCmd: CommandHandler = async (ctx) => {
2264
2286
  const nextTag = tags[i + 1]
2265
2287
  try {
2266
2288
  const range = nextTag ? `${nextTag}..${tag}` : tag
2267
- const log = execSync(
2268
- `git log --oneline --no-merges ${range} --format="%s" 2>/dev/null | head -8`,
2269
- { encoding: 'utf-8', timeout: 5000 },
2270
- )
2289
+ const log = execFileSync('git', ['log', '--oneline', '--no-merges', '--format=%s', range], {
2290
+ encoding: 'utf-8',
2291
+ timeout: 5000,
2292
+ })
2271
2293
  .trim()
2272
2294
  .split('\n')
2273
2295
  .filter(Boolean)
2296
+ .slice(0, 8)
2274
2297
 
2275
2298
  const isCurrent = tag === `v${ctx.version}`
2276
2299
  lines.push(`### ${tag}${isCurrent ? t('commands.changelog.current_marker') : ''}`, '')
@@ -4103,6 +4126,57 @@ const cdCmd: CommandHandler = async (ctx, args) => {
4103
4126
  try {
4104
4127
  process.chdir(resolved)
4105
4128
 
4129
+ // `/cd` 只搬了 cwd,而**按目录装载的闸门**分两半:
4130
+ // • 能在这里重放的 —— `.mipham/rules/*.md` 与 settings.json 的 permission 规则;
4131
+ // • 启动时一次性装载、搬不动的 —— config.yml 的 permissionRules、hooks、
4132
+ // 指令文件(CLAUDE.md 链)。它们仍然属于**原来的**目录。
4133
+ // 后半段必须说出口:否则用户以为自己已经在新项目的策略下,而实际生效的
4134
+ // 是上一个仓库的那一套。重放前半段是纯收紧/纯重放,不会放宽任何东西。
4135
+ const notes: string[] = []
4136
+ try {
4137
+ const { loadSettingsJson } = await import('../config/loader')
4138
+ const { RulesLoader } = await import('../core/rules-loader')
4139
+ // attach 模式下 `getPermission()` 是个只有 `setMode`/`getMode` 的门面
4140
+ // (闸门在 daemon 那边),在本地重放规则既改不动任何东西,也会在
4141
+ // `listRules`/`allow` 上抛 —— 与其把这句内部报错印给用户,不如说清楚归属。
4142
+ if (ctx.engine.isRemote) {
4143
+ notes.push(
4144
+ 'This session is attached to a daemon: permission rules and project rules ' +
4145
+ 'belong to the daemon, so nothing was reloaded here.',
4146
+ )
4147
+ } else {
4148
+ const perm = ctx.engine.getPermission()
4149
+ const settings = loadSettingsJson(resolved)
4150
+ // `allow`/`deny` 是**追加**语义(`PermissionSystem.allow` 直接 push),
4151
+ // 而用户级 allow 规则启动时已经施加过一遍 —— 不查重的话,每 `/cd` 一次
4152
+ // 规则数组就长一截,`applied` 也会把「重放」报成「新施加」。
4153
+ const live = perm.listRules()
4154
+ let applied = 0
4155
+ for (const rule of settings.permissions.allow) {
4156
+ if (live.has(rule)) continue
4157
+ perm.allow(rule)
4158
+ live.set(rule, 'bypass')
4159
+ applied++
4160
+ }
4161
+ for (const rule of settings.permissions.deny) {
4162
+ if (live.has(rule)) continue
4163
+ perm.deny(rule)
4164
+ live.set(rule, 'ask')
4165
+ applied++
4166
+ }
4167
+ if (applied > 0)
4168
+ notes.push(`Applied ${applied} settings.json permission rule(s) from this directory.`)
4169
+ ctx.engine.setRulesLoader(new RulesLoader(resolved))
4170
+ notes.push('Project rules now read from this directory.')
4171
+ }
4172
+ } catch (err) {
4173
+ notes.push(`Could not reload this directory's policy: ${(err as Error).message}`)
4174
+ }
4175
+ notes.push(
4176
+ 'Loaded at startup and still belonging to the original directory until restart: ' +
4177
+ 'config.yml permissionRules, hooks, and instruction files (CLAUDE.md chain).',
4178
+ )
4179
+
4106
4180
  try {
4107
4181
  const { SessionStore } = await import('../core/session-store')
4108
4182
  const saved = SessionStore.load(ctx.sessionId)
@@ -4126,7 +4200,7 @@ const cdCmd: CommandHandler = async (ctx, args) => {
4126
4200
  /* session persistence is best-effort */
4127
4201
  }
4128
4202
 
4129
- return { content: t('commands.cd.content', { path: resolved }) }
4203
+ return { content: [t('commands.cd.content', { path: resolved }), '', ...notes].join('\n') }
4130
4204
  } catch (err) {
4131
4205
  return { content: t('commands.cd.failed', { error: (err as Error).message }) }
4132
4206
  }
@@ -5603,6 +5677,7 @@ Background agents appear in the Agent View dashboard (/agents).`,
5603
5677
  undefined,
5604
5678
  undefined,
5605
5679
  ctx.engine.getLlm(),
5680
+ ctx.engine.getSubAgentServices(),
5606
5681
  )
5607
5682
  try {
5608
5683
  // The prompt came from the user typing `/bg …`, so it stays unframed —
@@ -5742,6 +5817,7 @@ const forkCmd: CommandHandler = async (ctx, args) => {
5742
5817
  undefined,
5743
5818
  undefined,
5744
5819
  ctx.engine.getLlm(),
5820
+ ctx.engine.getSubAgentServices(),
5745
5821
  )
5746
5822
  const parentContext = ctx.engine.getContext()
5747
5823
  // The row has to come back from `working` on both outcomes: the fork
@@ -5755,28 +5831,61 @@ const forkCmd: CommandHandler = async (ctx, args) => {
5755
5831
  inheritContext: { messages: parentContext.getMessages() },
5756
5832
  signal,
5757
5833
  })
5834
+ // Same contract as the `worktree add` above: argv, no shell. This block
5835
+ // was the half that still built shell strings — and it interpolated both
5836
+ // `wtPath` (derived from the cwd) and `prompt` (the user's text), so a
5837
+ // directory or a task containing `"`, `$(…)` or `;` ran as commands.
5838
+ //
5839
+ // It also swallowed every failure (`/* best-effort */`) and still
5840
+ // reported "Fork done" with a branch name, so a commit that never
5841
+ // happened and a push that was rejected looked exactly like success.
5842
+ let publish: string
5758
5843
  try {
5759
- const { execSync: ex } = await import('node:child_process')
5760
- ex(`git -C ${wtPath} add -A`, { stdio: 'ignore', timeout: 10_000 })
5761
- const st = ex(`git -C ${wtPath} status --porcelain`, {
5844
+ execFileSync('git', ['add', '-A'], {
5845
+ cwd: wtPath,
5846
+ stdio: 'ignore',
5847
+ timeout: 10_000,
5848
+ env: internalGitEnv(),
5849
+ })
5850
+ const st = execFileSync('git', ['status', '--porcelain'], {
5851
+ cwd: wtPath,
5762
5852
  encoding: 'utf-8',
5763
5853
  timeout: 10_000,
5854
+ env: internalGitEnv(),
5764
5855
  })
5765
- if (st.trim()) {
5766
- ex(`git -C ${wtPath} commit -m "feat: ${prompt.slice(0, 60)}\n\n${COAUTHOR_TRAILER}"`, {
5767
- stdio: 'ignore',
5768
- timeout: 10_000,
5769
- })
5770
- ex(`git push origin ${branch}`, { stdio: 'ignore', timeout: 30_000 })
5856
+ if (!st.trim()) {
5857
+ publish = 'No changes to commit.'
5858
+ } else {
5859
+ execFileSync(
5860
+ 'git',
5861
+ ['commit', '-m', `feat: ${prompt.slice(0, 60)}\n\n${COAUTHOR_TRAILER}`],
5862
+ { cwd: wtPath, stdio: 'ignore', timeout: 10_000, env: internalGitEnv() },
5863
+ )
5864
+ try {
5865
+ execFileSync('git', ['push', 'origin', branch], {
5866
+ cwd: wtPath,
5867
+ stdio: 'ignore',
5868
+ timeout: 30_000,
5869
+ env: internalGitEnv(),
5870
+ })
5871
+ publish = `Committed and pushed \`${branch}\` to origin.`
5872
+ } catch (pushErr) {
5873
+ publish =
5874
+ `Committed locally, but the **push failed** (${pushErr instanceof Error ? pushErr.message : String(pushErr)}). ` +
5875
+ `The commit is on \`${branch}\` in \`${wtPath}\` — push it yourself when the remote is reachable.`
5876
+ }
5771
5877
  }
5772
- } catch {
5773
- /* best-effort */
5878
+ } catch (err) {
5879
+ publish =
5880
+ `**Auto-commit failed** (${err instanceof Error ? err.message : String(err)}). ` +
5881
+ `Changes are uncommitted in \`${wtPath}\`.`
5774
5882
  }
5775
5883
  const summary = [
5776
5884
  `## Fork done: ${prompt}`,
5777
5885
  '',
5778
5886
  `Branch: \`${branch}\``,
5779
5887
  `Worktree: \`${wtPath}\``,
5888
+ publish,
5780
5889
  '',
5781
5890
  result || '(no output)',
5782
5891
  ].join('\n')
@@ -4,6 +4,7 @@ import type { ProviderRegistry } from '../../providers/registry'
4
4
  import type { Llm } from '../../providers/llm'
5
5
  import type { ToolDefinition } from '../../shared/index.ts'
6
6
  import type { PermissionSystem } from '../../core/permission'
7
+ import type { SubAgentServices } from '../../agent/services'
7
8
  import { worktreeRoot } from '../../core/paths.ts'
8
9
  import { internalGitEnv } from '../../shared/git-env'
9
10
  import { validateJSONSchema, formatValidationErrors } from '../schema-validator'
@@ -37,6 +38,8 @@ export interface WorkflowAgentOpts {
37
38
  maxRetries?: number
38
39
  /** Permission system for sub-agent tool execution (optional). */
39
40
  permissionSystem?: PermissionSystem
41
+ /** Hooks, gates and DLP handed down by the engine running the workflow. */
42
+ services?: SubAgentServices
40
43
  /** Run the agent in an isolated git worktree (optional). */
41
44
  isolation?: 'worktree'
42
45
  }
@@ -115,7 +118,15 @@ export async function workflowAgent(
115
118
  `Return ONLY the JSON object, no other text. Do not wrap in markdown code fences.`
116
119
  }
117
120
 
118
- const sub = new SubAgent(registry, toolRegistry, opts.permissionSystem, undefined, undefined, llm)
121
+ const sub = new SubAgent(
122
+ registry,
123
+ toolRegistry,
124
+ opts.permissionSystem,
125
+ undefined,
126
+ undefined,
127
+ llm,
128
+ opts.services,
129
+ )
119
130
 
120
131
  // ── Execute with optional schema validation + retry ──
121
132
  let result: unknown = ''
@@ -58,6 +58,14 @@ export async function loopUntilConvergence<T>(
58
58
  // FAN OUT: all finders run in parallel
59
59
  const raw = await parallel(opts.finders.map((f) => () => f()))
60
60
 
61
+ // A round in which **every** finder failed is not "nothing new was found"
62
+ // — it is "nothing was searched for". Counting it as dry let two crashed
63
+ // finders report `converged: true` with an empty confirmed list. A partial
64
+ // failure is still tolerated (the survivors carry the round).
65
+ if (raw.length > 0 && raw.every((r) => r === null)) {
66
+ throw new Error(`loopUntilConvergence(): every finder failed in round ${rounds}`)
67
+ }
68
+
61
69
  // EDGE LOGIC: flatMap + dedup (pure JS, zero tokens)
62
70
  const items: T[] = []
63
71
  for (const result of raw) {
@@ -84,6 +92,12 @@ export async function loopUntilConvergence<T>(
84
92
  // VERIFY: optional quality gate
85
93
  if (opts.verify) {
86
94
  const judged = await parallel(fresh.map((item) => () => opts.verify!(item)))
95
+ // Same rule one level down: `parallel` turns a throwing verify into null,
96
+ // so "every verify call failed" would otherwise be read as "every finding
97
+ // was refuted" and the loop would converge on nothing.
98
+ if (judged.every((j) => j === null)) {
99
+ throw new Error(`loopUntilConvergence(): every verify call failed in round ${rounds}`)
100
+ }
87
101
  for (const j of judged) {
88
102
  if (j && j.survives) {
89
103
  confirmed.push(j.finding as T)
@@ -164,7 +164,12 @@ export async function verify(finding: unknown, opts: VerifyOpts): Promise<Verify
164
164
 
165
165
  const threshold = opts.threshold ?? defaultThreshold(mode, votes.length)
166
166
  const realCount = votes.filter((v) => v.real).length
167
- const survives = realCount >= threshold
167
+ // A fan-out in which every voter failed is not a verdict. `defaultThreshold`
168
+ // returns 0 when there are no votes — correct for "all must agree" and for a
169
+ // majority of zero — so `0 >= 0` reported **survives: true** for adversarial
170
+ // and consensus while `score` said 0. Nothing confirmed the finding, so it is
171
+ // not confirmed.
172
+ const survives = votes.length > 0 && realCount >= threshold
168
173
 
169
174
  return {
170
175
  finding,
@@ -241,6 +246,13 @@ export async function judge(attempts: unknown[], opts: JudgeOpts): Promise<Judge
241
246
  }
242
247
  }
243
248
 
249
+ // No judge produced a score ⇒ there is no winner. Falling through left
250
+ // `winnerIndex` at its initial 0 and handed back `attempts[0]` as "the
251
+ // winner" — a fabricated verdict for a round in which every judge failed.
252
+ if (scores.length === 0 && scorePrompts.length > 0) {
253
+ throw new Error('judge(): every judge call failed — no attempt could be scored')
254
+ }
255
+
244
256
  // Compute winner: highest average total across judges
245
257
  const attemptTotals = new Map<number, number>()
246
258
  const attemptCounts = new Map<number, number>()
@@ -134,6 +134,7 @@ export async function runWorkflow(
134
134
  {
135
135
  ...(opts || {}),
136
136
  permissionSystem: permission,
137
+ services: engine.getSubAgentServices(),
137
138
  } as Record<string, unknown>,
138
139
  llm,
139
140
  )