@miphamai/cli 0.85.11 → 0.85.12

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.
@@ -1,5 +1,35 @@
1
- import { readFileSync } from 'node:fs'
1
+ import { readFileSync, readdirSync, statSync } from 'node:fs'
2
+ import { join } from 'node:path'
2
3
  import type { ToolDefinition } from '../../shared/index.ts'
4
+ import { MIPHAM_DIR } from '../../shared/constants.ts'
5
+
6
+ /**
7
+ * Newest `plan-*.md` under `<cwd>/.mipham/plans/`, or null when there is none.
8
+ *
9
+ * This backs the `planFile` parameter's documented default. Without it the
10
+ * docstring promised a fallback the body never performed (`planFile || ''`), so an
11
+ * omission read as "use the most recent plan" and quietly produced no plan at all.
12
+ */
13
+ function mostRecentPlanFile(cwd: string): string | null {
14
+ const dir = join(cwd, MIPHAM_DIR, 'plans')
15
+ let names: string[]
16
+ try {
17
+ names = readdirSync(dir).filter((n) => n.startsWith('plan-') && n.endsWith('.md'))
18
+ } catch {
19
+ return null // no plans directory — nothing to fall back to
20
+ }
21
+ let newest: { path: string; mtime: number } | null = null
22
+ for (const name of names) {
23
+ const path = join(dir, name)
24
+ try {
25
+ const mtime = statSync(path).mtimeMs
26
+ if (!newest || mtime > newest.mtime) newest = { path, mtime }
27
+ } catch {
28
+ // Unreadable entry — not a fallback candidate.
29
+ }
30
+ }
31
+ return newest?.path ?? null
32
+ }
3
33
 
4
34
  export const exitPlanModeTool: ToolDefinition = {
5
35
  name: 'ExitPlanMode',
@@ -21,27 +51,37 @@ export const exitPlanModeTool: ToolDefinition = {
21
51
  },
22
52
  required: [],
23
53
  },
24
- async execute(params, _ctx) {
25
- const planFile = (params.planFile as string) || ''
54
+ async execute(params, ctx) {
55
+ const planFile = (params.planFile as string) || mostRecentPlanFile(ctx.cwd) || ''
26
56
 
27
57
  // Try to read the plan to confirm it exists
28
58
  let planContent = ''
59
+ let readError = ''
29
60
  try {
30
- const planPath = planFile || ''
31
- if (planPath) {
32
- planContent = readFileSync(planPath, 'utf-8')
61
+ if (planFile) {
62
+ planContent = readFileSync(planFile, 'utf-8')
33
63
  }
34
- } catch {
35
- // Plan file not found — still exit plan mode
64
+ } catch (err) {
65
+ readError = err instanceof Error ? err.message : String(err)
36
66
  }
37
67
 
68
+ // Say which of the three states we are actually in. The old text asserted
69
+ // "Plan file saved" unconditionally, so a missing or unreadable plan still read
70
+ // as success and the model would present a plan it never retrieved.
71
+ const planStatus = planContent
72
+ ? '✓ Plan file read. Present your plan to the user now.'
73
+ : planFile
74
+ ? `⚠️ Plan file not readable (${planFile}): ${readError}`
75
+ : '⚠️ No plan file found — present the plan from your own context.'
76
+
38
77
  return {
39
78
  success: true,
40
79
  content: [
41
80
  '── Plan Ready for Review ──',
42
81
  '',
43
82
  '✓ Exiting plan mode.',
44
- '✓ Plan file saved. Present your plan to the user now.',
83
+ planStatus,
84
+ planFile ? `Plan file: ${planFile}` : '',
45
85
  '',
46
86
  '⚠️ IMPORTANT: You are still in limited permission mode.',
47
87
  ' The user must explicitly approve before you can make changes.',
@@ -145,7 +145,6 @@ export const artifactTool: ToolDefinition = {
145
145
  galleryLine,
146
146
  '',
147
147
  `Open in browser: /artifact open ${name}`,
148
- `List all: /artifact list`,
149
148
  ]
150
149
  .filter(Boolean)
151
150
  .join('\n'),
@@ -439,8 +439,24 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
439
439
  timedOut = true
440
440
  killProcessGroup(proc.pid)
441
441
  }, timeout)
442
+
443
+ // Cancellation. The turn's signal used to stop at the approval prompt and the
444
+ // model stream, so a long-running command had no way to be stopped: nothing
445
+ // it received ever changed. Abort has to reach the process group, or Escape
446
+ // kills the turn while the command keeps writing to the user's disk.
447
+ let aborted = false
448
+ const onAbort = () => {
449
+ aborted = true
450
+ killProcessGroup(proc.pid)
451
+ }
452
+ if (ctx.signal) {
453
+ if (ctx.signal.aborted) onAbort()
454
+ else ctx.signal.addEventListener('abort', onAbort, { once: true })
455
+ }
456
+
442
457
  const exitCode = await proc.exited
443
458
  clearTimeout(timer)
459
+ ctx.signal?.removeEventListener('abort', onAbort)
444
460
 
445
461
  // The shell is gone, so only a pipe-holding descendant can still be
446
462
  // holding these up. Released by the group kill, at most once.
@@ -493,12 +509,21 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
493
509
  return {
494
510
  success: false,
495
511
  content: errorContent,
496
- error: timedOut
497
- ? `Command timed out after ${timeout}ms (killed): ${stderr.slice(0, 1_000)}`
498
- : `Exit code ${exitCode}: ${stderr.slice(0, 1_000)}`,
512
+ error: aborted
513
+ ? `Command cancelled (SIGKILL to its process group)`
514
+ : timedOut
515
+ ? `Command timed out after ${timeout}ms (killed): ${stderr.slice(0, 1_000)}`
516
+ : `Exit code ${exitCode}: ${stderr.slice(0, 1_000)}`,
499
517
  }
500
518
  }
501
519
 
520
+ // An aborted command may also exit 0 (SIGKILL raced the natural exit). Report
521
+ // the cancellation either way, so a half-finished command is never handed back
522
+ // as a clean success.
523
+ if (aborted) {
524
+ return { success: false, content: output.slice(0, 5_000), error: 'Command cancelled' }
525
+ }
526
+
502
527
  let successContent = output.slice(0, 100_000) || '(no output)'
503
528
  if (violations.length > 0) {
504
529
  successContent += '\n\n── Sandbox Violations ──\n' + violations.join('\n')
@@ -74,7 +74,13 @@ export function createToolRegistry(
74
74
  sendMessageTool,
75
75
  listAgentsTool,
76
76
  // Network tools
77
- webFetchTool,
77
+ // `MIPHAM_DISABLE_WEB_FETCH=1` removes WebFetch from the registry entirely, so
78
+ // it is never advertised to the model. A `permissionRules.deny: ["WebFetch"]`
79
+ // reaches the same endpoint by a different mechanism — the tool is still listed
80
+ // in the schema and only rejected when called, which costs a wasted turn (and a
81
+ // perplexed model) before the refusal lands. An env kill-switch has to act at
82
+ // registration, not at call time.
83
+ ...(process.env.MIPHAM_DISABLE_WEB_FETCH === '1' ? [] : [webFetchTool]),
78
84
  webSearchTool,
79
85
  // System tools
80
86
  mcpTool,
@@ -1,4 +1,5 @@
1
1
  import type { ToolDefinition } from '../../shared/index.ts'
2
+ import { PACKAGE_VERSION } from '../../shared/package-info'
2
3
  import { validateUrl } from '../../security/url'
3
4
 
4
5
  // ── In-memory cache (15-min TTL per URL) ──
@@ -195,7 +196,7 @@ export const webFetchTool: ToolDefinition = {
195
196
  for (let hop = 0; hop <= 5; hop++) {
196
197
  response = await fetch(currentUrl, {
197
198
  headers: {
198
- 'User-Agent': 'Mipham-Code/0.24.0',
199
+ 'User-Agent': `Mipham-Code/${PACKAGE_VERSION}`,
199
200
  Accept: 'text/html,application/xhtml+xml,*/*',
200
201
  },
201
202
  redirect: 'manual',
package/src/ui/chat.tsx CHANGED
@@ -2,6 +2,7 @@ import React, { useMemo } from 'react'
2
2
  import { Box, Text } from 'ink'
3
3
  import { useI18n } from '../i18n-context'
4
4
  import type { ChatMessage } from './app'
5
+ import { decodeDisplayEntities } from '../shared/sanitize'
5
6
  import { homedir } from 'node:os'
6
7
 
7
8
  interface ChatPanelProps {
@@ -93,7 +94,7 @@ const MessageRow = React.memo(
93
94
  ⚠ {t('ui.system.role_label')}:
94
95
  </Text>
95
96
  ) : null}
96
- <Text>{msg.content}</Text>
97
+ <Text>{msg.toolMeta ? msg.content : decodeDisplayEntities(msg.content)}</Text>
97
98
  </>
98
99
  )}
99
100
  </Box>
@@ -7,6 +7,7 @@
7
7
  import type { QueryEngine } from '../core/engine'
8
8
  import type { MiphamConfig } from '../shared/index.ts'
9
9
  import { formatContextWindow } from '../shared/format'
10
+ import { sanitizeInlineField } from '../shared/sanitize'
10
11
  import type { SkillsLoader } from '../skills/loader'
11
12
  import { loadSkillUsage } from '../skills/usage'
12
13
  import type { PluginManager } from '../plugin/plugin-manager'
@@ -4948,7 +4949,7 @@ const mcpCmd: CommandHandler = async (ctx, args) => {
4948
4949
  const config = mcpServers.find((s) => s.name === name)
4949
4950
  if (!config) {
4950
4951
  return {
4951
- content: `Server "${name}" not found in config.\n\nConfigured: ${mcpServers.map((s) => s.name).join(', ') || '(none)'}`,
4952
+ content: `Server "${sanitizeInlineField(name)}" not found in config.\n\nConfigured: ${mcpServers.map((s) => sanitizeInlineField(s.name)).join(', ') || '(none)'}`,
4952
4953
  }
4953
4954
  }
4954
4955
  if (config.auth?.type === 'oauth') {
@@ -4968,7 +4969,7 @@ const mcpCmd: CommandHandler = async (ctx, args) => {
4968
4969
  const headerKeys = config.headers ? Object.keys(config.headers) : []
4969
4970
  const headerLine = headerKeys.length > 0 ? `\nHeaders to send: ${headerKeys.join(', ')}` : ''
4970
4971
  return {
4971
- content: `── MCP Connect: ${name} ──\n\nConnecting via HTTP\nURL: ${config.url}${headerLine}\n\n⚠️ Verify the URL — any configured headers (e.g. Authorization) will be sent to this server.`,
4972
+ content: `── MCP Connect: ${sanitizeInlineField(name)} ──\n\nConnecting via HTTP\nURL: ${sanitizeInlineField(config.url)}${headerLine}\n\n⚠️ Verify the URL — any configured headers (e.g. Authorization) will be sent to this server.`,
4972
4973
  forwardToAI: `Connect to MCP server "${name}" using McpClient.getInstance().connect(config), then register its tools. Report the result.`,
4973
4974
  }
4974
4975
  }
@@ -5058,15 +5059,15 @@ const mcpCmd: CommandHandler = async (ctx, args) => {
5058
5059
  : '⚪'
5059
5060
  const statusLabel = live ? live.status : 'not started'
5060
5061
  const oauthTag = s.auth?.type === 'oauth' ? ' [OAuth]' : ''
5061
- lines.push(` ${statusIcon} ${s.name}${oauthTag} [${statusLabel}]`)
5062
+ lines.push(` ${statusIcon} ${sanitizeInlineField(s.name)}${oauthTag} [${statusLabel}]`)
5062
5063
  const transportInfo = s.url
5063
- ? `URL: ${s.url}`
5064
- : `Command: ${s.command ?? ''} ${(s.args ?? []).join(' ')}`
5064
+ ? `URL: ${sanitizeInlineField(s.url)}`
5065
+ : `Command: ${sanitizeInlineField(s.command ?? '')} ${(s.args ?? []).map(sanitizeInlineField).join(' ')}`
5065
5066
  lines.push(` ${transportInfo}`)
5066
5067
  if (live?.tools && live.tools.length > 0) {
5067
5068
  lines.push(` Tools: ${live.tools.length} registered`)
5068
5069
  }
5069
- if (live?.error) lines.push(` Error: ${live.error}`)
5070
+ if (live?.error) lines.push(` Error: ${sanitizeInlineField(live.error)}`)
5070
5071
  lines.push('')
5071
5072
  }
5072
5073
  } else {
package/src/ui/input.tsx CHANGED
@@ -399,6 +399,11 @@ export function InputBar({
399
399
  useInput((input, key) => {
400
400
  // ── Escape: cancel loading → clear draft ──
401
401
  if (key.escape) {
402
+ // While the command picker is open, Escape belongs to it. Ink 7 runs every
403
+ // registered `useInput` listener for one keypress (no stopPropagation), so
404
+ // without this the picker closes AND this branch wipes the draft — the exact
405
+ // text the picker's `onClose` is written to preserve.
406
+ if (pickerActive) return
402
407
  // Escape while loading → abort
403
408
  if (isLoading) {
404
409
  onCancel?.()
@@ -18,6 +18,19 @@ export class WorkflowEventBus extends EventEmitter {
18
18
  }
19
19
 
20
20
  emitEvent(event: WorkflowEvent): void {
21
+ // `error` here is a **payload type**, not EventEmitter's crash channel — and the
22
+ // two are wired to the same string. Node makes `emit('error', …)` throw
23
+ // ERR_UNHANDLED_ERROR when no listener is attached, so a workflow that failed
24
+ // while nothing was watching the bus replaced its own diagnostic with
25
+ // `Unhandled error. ({ type: 'error', message: '…' })`, and the carefully
26
+ // written `throw new Error('Workflow script execution failed: …')` further down
27
+ // never ran. It looked fine because the UI progress view subscribes to `error`,
28
+ // so the throw only happened headless.
29
+ //
30
+ // Nothing is lost by skipping it: whoever needs the failure has the journal entry
31
+ // and the thrown error; the one subscriber drops `error` on the floor anyway
32
+ // (`workflow-progress.tsx`'s `case 'error': break`).
33
+ if (event.type === 'error' && this.listenerCount('error') === 0) return
21
34
  this.emit(event.type, event)
22
35
  }
23
36
 
@@ -13,6 +13,14 @@ export interface JournalEntry {
13
13
  opts?: Record<string, unknown>
14
14
  result?: unknown
15
15
  message?: string
16
+ /**
17
+ * Why an `agent` entry has no `result`.
18
+ *
19
+ * Kept out of `result` on purpose: the resume cache is keyed on `result !==
20
+ * undefined`, so parking the message there would make a failed call replay as a
21
+ * successful cached answer.
22
+ */
23
+ error?: string
16
24
  }
17
25
 
18
26
  export interface JournalState {
@@ -108,7 +108,7 @@ export async function runWorkflow(
108
108
  const budget = createBudget(budgetTotal)
109
109
 
110
110
  // Wrap primitives with journal recording + cache support
111
- const agent = async (prompt: string, opts?: Record<string, unknown>) => {
111
+ const runAgent = async (prompt: string, opts?: Record<string, unknown>) => {
112
112
  // Check cache first
113
113
  if (resultCache) {
114
114
  const key = agentCacheKey(prompt, opts || {})
@@ -125,16 +125,42 @@ export async function runWorkflow(
125
125
 
126
126
  bus.emitEvent({ type: 'agent:start', agentId, label: agentId, phase })
127
127
 
128
- const result = await workflowAgent(
129
- prompt,
130
- registry,
131
- toolRegistry,
132
- {
133
- ...(opts || {}),
134
- permissionSystem: permission,
135
- } as Record<string, unknown>,
136
- llm,
137
- )
128
+ let result: unknown
129
+ try {
130
+ result = await workflowAgent(
131
+ prompt,
132
+ registry,
133
+ toolRegistry,
134
+ {
135
+ ...(opts || {}),
136
+ permissionSystem: permission,
137
+ } as Record<string, unknown>,
138
+ llm,
139
+ )
140
+ } catch (err) {
141
+ // A failed call is still a call: it gets the same start/end pair and a journal
142
+ // entry, so the run reads as "this agent failed" rather than as a run that
143
+ // silently never mentioned it. The message goes in `error`, not `result` —
144
+ // the resume cache replays on `result !== undefined`.
145
+ const message = err instanceof Error ? err.message : String(err)
146
+ bus.emitEvent({
147
+ type: 'agent:end',
148
+ agentId,
149
+ label: agentId,
150
+ success: false,
151
+ durationMs: Date.now() - startTime,
152
+ })
153
+ bus.emitEvent({ type: 'error', agentId, message })
154
+ appendJournal(runId, {
155
+ type: 'agent',
156
+ prompt,
157
+ opts: opts as Record<string, unknown> | undefined,
158
+ error: message,
159
+ })
160
+ // Still rethrow: a script that awaits this call must see the rejection, and
161
+ // the catch below turns it into the run's own error message.
162
+ throw err
163
+ }
138
164
 
139
165
  const durationMs = Date.now() - startTime
140
166
  bus.emitEvent({ type: 'agent:end', agentId, label: agentId, success: true, durationMs })
@@ -148,6 +174,28 @@ export async function runWorkflow(
148
174
  return result
149
175
  }
150
176
 
177
+ /**
178
+ * The `agent` the sandbox script sees.
179
+ *
180
+ * Not `async`, because the promise it returns needs a handler attached before it
181
+ * leaves this function. A script that calls `agent(...)` **without awaiting it** —
182
+ * a fire-and-forget fan-out, or `agent('A'); await agent('B')` — leaves the
183
+ * rejection unhandled in the host realm, and the crash reporter is installed
184
+ * unconditionally, so `handleFatal` ends the process: one un-awaited call and the
185
+ * CLI exits with a message about unhandled rejections in a workflow script.
186
+ *
187
+ * Attaching the handler here marks the rejection handled **without swallowing it**:
188
+ * the promise returned to the script is the same one, so `await agent(...)` still
189
+ * throws into the script's own `try`. What changes is only the case where nobody is
190
+ * listening — that case now belongs to the run (journal + `error` event, both
191
+ * written by `runAgent`), not to the process.
192
+ */
193
+ const agent = (prompt: string, opts?: Record<string, unknown>) => {
194
+ const pending = runAgent(prompt, opts)
195
+ pending.catch(() => {})
196
+ return pending
197
+ }
198
+
151
199
  const wrappedPhase = (title: string) => {
152
200
  phasePrimitive(title)
153
201
  bus.emitEvent({ type: 'phase:start', phase: title, timestamp: Date.now() })