@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,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)}`)
@@ -222,22 +238,51 @@ export async function workflowAgent(
222
238
  /* best-effort */
223
239
  }
224
240
 
225
- // Remove worktree and branch
241
+ // Remove worktree and branch.
242
+ //
243
+ // Every step here used to be fire-and-forget: a `worktree remove` that
244
+ // failed left the registration behind, the `branch -D` then failed too
245
+ // ("used by worktree at …"), and the run reported clean either way. So
246
+ // check both exits and say what is left — an unchanged agent worktree
247
+ // that nobody removes is state the next run has to trip over.
248
+ const leftovers: string[] = []
226
249
  try {
227
250
  const rmProc = Bun.spawn(['git', 'worktree', 'remove', '--force', worktreePath], {
228
251
  stdout: 'pipe',
229
252
  stderr: 'pipe',
230
253
  })
231
- await rmProc.exited
254
+ let removed = (await rmProc.exited) === 0
255
+ if (!removed) {
256
+ // A worktree whose directory is already gone leaves only a stale
257
+ // registration; prune clears it so the branch delete can proceed.
258
+ const pruneProc = Bun.spawn(['git', 'worktree', 'prune'], {
259
+ stdout: 'pipe',
260
+ stderr: 'pipe',
261
+ })
262
+ await pruneProc.exited
263
+ const retry = Bun.spawn(['git', 'worktree', 'remove', '--force', worktreePath], {
264
+ stdout: 'pipe',
265
+ stderr: 'pipe',
266
+ })
267
+ removed = (await retry.exited) === 0
268
+ }
269
+ if (!removed) leftovers.push(`worktree ${worktreePath}`)
270
+
232
271
  if (worktreeBranch) {
233
272
  const brProc = Bun.spawn(['git', 'branch', '-D', worktreeBranch], {
234
273
  stdout: 'pipe',
235
274
  stderr: 'pipe',
236
275
  })
237
- await brProc.exited
276
+ if ((await brProc.exited) !== 0) leftovers.push(`branch ${worktreeBranch}`)
238
277
  }
239
- } catch {
240
- /* best-effort */
278
+ } catch (err) {
279
+ leftovers.push(`${worktreePath} (${err instanceof Error ? err.message : String(err)})`)
280
+ }
281
+ if (leftovers.length > 0) {
282
+ process.stderr.write(
283
+ `⚠️ workflow: could not clean up ${leftovers.join(' and ')} — ` +
284
+ `the run finished, but this state needs manual removal.\n`,
285
+ )
241
286
  }
242
287
  }
243
288
  }
@@ -11,15 +11,33 @@
11
11
  * picks the winner, and optionally synthesizes a final result.
12
12
  */
13
13
 
14
- import { workflowAgent } from './agent'
15
14
  import { parallel } from './parallel'
16
- import type { WorkflowAgentOpts } from './agent'
17
15
 
18
- // Agent function signature matching the sandbox-injected pattern:
19
- // (prompt, opts?) → result. In production, the workflow runtime binds
20
- // ProviderRegistry + ToolRegistry into a function of this shape and
21
- // injects it via _mockAgent.
22
- type AgentFn = (prompt: string, opts?: WorkflowAgentOpts) => Promise<unknown>
16
+ // Agent function signature matching the sandbox-injected `agent`:
17
+ // (prompt, opts?) → result. The workflow runtime passes its own wrapped agent
18
+ // in, so every verify()/judge() fan-out is journaled and replayable on resume.
19
+ export type AgentFn = (prompt: string, opts?: Record<string, unknown>) => Promise<unknown>
20
+
21
+ /**
22
+ * These primitives must run **inside** a workflow run.
23
+ *
24
+ * The run's `agent` is what makes an agent call journaled (so resume replays it
25
+ * instead of re-running) and what binds the provider registry, tools and
26
+ * permission system. Without it there is no sensible fallback: calling the raw
27
+ * `workflowAgent` here would need a registry positionally, so it would either
28
+ * crash or — worse — run unbudgeted and unjournaled, and every resumed run
29
+ * would re-run all of its skeptics.
30
+ */
31
+ function resolveAgent(opts: { agent?: AgentFn; _mockAgent?: AgentFn }): AgentFn {
32
+ const fn = opts.agent ?? opts._mockAgent
33
+ if (!fn) {
34
+ throw new Error(
35
+ "verify()/judge() need the run's agent(): they are only callable inside a workflow run, " +
36
+ 'where the runtime injects it.',
37
+ )
38
+ }
39
+ return fn
40
+ }
23
41
 
24
42
  // ── Types ──
25
43
 
@@ -39,8 +57,10 @@ export interface VerifyOpts {
39
57
  voters?: number // consensus: default 3
40
58
  threshold?: number
41
59
  schema: Record<string, unknown>
42
- /** Test-only: inject a mock agent function. When not provided, falls back to workflowAgent. */
43
- _mockAgent?: (prompt: string, opts?: WorkflowAgentOpts) => Promise<unknown>
60
+ /** Injected by the workflow runtime: the run's wrapped `agent` (journal + resume cache). */
61
+ agent?: AgentFn
62
+ /** Test-only: inject a mock agent function. */
63
+ _mockAgent?: AgentFn
44
64
  }
45
65
 
46
66
  interface VerdictVote {
@@ -67,8 +87,10 @@ export interface JudgeOpts {
67
87
  judges?: number // default: 3
68
88
  synthesize?: boolean // default: true
69
89
  schema: Record<string, unknown>
90
+ /** Injected by the workflow runtime: the run's wrapped `agent` (journal + resume cache). */
91
+ agent?: AgentFn
70
92
  /** Test-only: inject a mock agent function. */
71
- _mockAgent?: (prompt: string, opts?: WorkflowAgentOpts) => Promise<unknown>
93
+ _mockAgent?: AgentFn
72
94
  }
73
95
 
74
96
  // ── Helpers ──
@@ -82,10 +104,7 @@ function defaultThreshold(mode: VerifyMode, total: number): number {
82
104
  // ── verify() ──
83
105
 
84
106
  export async function verify(finding: unknown, opts: VerifyOpts): Promise<VerifyResult> {
85
- // Prefer the test hook (_mockAgent), fall back to workflowAgent.
86
- // In production sandbox usage, _mockAgent is set to the pre-bound agent
87
- // function injected by the workflow runtime.
88
- const agentFn: AgentFn = opts._mockAgent ?? (workflowAgent as unknown as AgentFn)
107
+ const agentFn = resolveAgent(opts)
89
108
  const mode = opts.mode
90
109
 
91
110
  const findingStr = JSON.stringify(finding, null, 2)
@@ -126,9 +145,7 @@ export async function verify(finding: unknown, opts: VerifyOpts): Promise<Verify
126
145
 
127
146
  // Fan out all agent calls concurrently
128
147
  const rawVotes = await parallel(
129
- prompts.map(
130
- (p) => () => agentFn(p.prompt, { schema: opts.schema as WorkflowAgentOpts['schema'] }),
131
- ),
148
+ prompts.map((p) => () => agentFn(p.prompt, { schema: opts.schema })),
132
149
  )
133
150
 
134
151
  // Filter out failed agents (null) and build vote objects
@@ -160,8 +177,7 @@ export async function verify(finding: unknown, opts: VerifyOpts): Promise<Verify
160
177
  // ── judge() ──
161
178
 
162
179
  export async function judge(attempts: unknown[], opts: JudgeOpts): Promise<JudgeResult> {
163
- // Prefer the test hook, fall back to workflowAgent.
164
- const agentFn: AgentFn = opts._mockAgent ?? (workflowAgent as unknown as AgentFn)
180
+ const agentFn = resolveAgent(opts)
165
181
  const judgeCount = opts.judges ?? 3
166
182
  const schemaDesc = JSON.stringify(opts.schema)
167
183
 
@@ -198,7 +214,7 @@ export async function judge(attempts: unknown[], opts: JudgeOpts): Promise<Judge
198
214
  `You are judge #${sp.judgeIndex + 1}. Score this attempt against the criteria: ${opts.criteria.join(', ')}.\n\n` +
199
215
  `Attempt:\n${JSON.stringify(sp.attempt, null, 2)}\n\n` +
200
216
  `Return JSON matching this schema:\n${schemaDesc}`,
201
- { schema: opts.schema as WorkflowAgentOpts['schema'] },
217
+ { schema: opts.schema },
202
218
  ),
203
219
  ),
204
220
  )
@@ -223,8 +223,16 @@ export async function runWorkflow(
223
223
  sandboxCtx.agent = sealValue(agent)
224
224
  sandboxCtx.parallel = sealValue(parallel)
225
225
  sandboxCtx.pipeline = sealValue(pipeline)
226
- sandboxCtx.verify = sealValue(verify)
227
- sandboxCtx.judge = sealValue(judge)
226
+ // verify()/judge() fan out their own agent calls, so they need the run's agent
227
+ // too. Handing them the bare primitive would put those calls outside the
228
+ // journal and the resume cache: a resumed run would replay every agent() it
229
+ // can see and then silently re-run all of verify's skeptics and judge's scores.
230
+ sandboxCtx.verify = sealValue((finding: unknown, opts: Record<string, unknown> = {}) =>
231
+ verify(finding, { ...opts, agent } as Parameters<typeof verify>[1]),
232
+ )
233
+ sandboxCtx.judge = sealValue((attempts: unknown[], opts: Record<string, unknown> = {}) =>
234
+ judge(attempts, { ...opts, agent } as Parameters<typeof judge>[1]),
235
+ )
228
236
  sandboxCtx.loopUntilConvergence = sealValue(loopUntilConvergence)
229
237
  sandboxCtx.phase = sealValue(wrappedPhase)
230
238
  sandboxCtx.log = sealValue(log)