@miphamai/cli 0.85.21 → 0.85.23

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.
@@ -277,8 +277,15 @@ export class HttpTransport implements Transport {
277
277
  ...(params ? { params } : {}),
278
278
  }
279
279
 
280
- // Fire-and-forget: do not await the response.
281
- void this.fetchImpl(this.url, {
280
+ // Fire-and-forget: do not await the response — but bound it. Without a
281
+ // signal the request inherits the platform fetch timeout (none, in Node),
282
+ // so a server that never answers pins a socket for the life of the process.
283
+ const url = this.url
284
+ const controller = new AbortController()
285
+ const timer = setTimeout(() => controller.abort(), this.requestTimeoutMs)
286
+ // A best-effort notification must not keep the process alive on exit.
287
+ timer.unref?.()
288
+ void this.fetchImpl(url, {
282
289
  method: 'POST',
283
290
  headers: {
284
291
  'Content-Type': 'application/json',
@@ -287,9 +294,17 @@ export class HttpTransport implements Transport {
287
294
  },
288
295
  body: JSON.stringify(notification),
289
296
  redirect: 'manual',
290
- }).catch(() => {
291
- /* notifications are best-effort */
297
+ signal: controller.signal,
292
298
  })
299
+ .then((res) => {
300
+ // Nobody reads this body; release it so an undrained keep-alive
301
+ // response cannot hold the socket open either.
302
+ void res.body?.cancel().catch(() => {})
303
+ })
304
+ .catch(() => {
305
+ /* notifications are best-effort */
306
+ })
307
+ .finally(() => clearTimeout(timer))
293
308
  }
294
309
 
295
310
  onNotification(handler: NotificationHandler): void {
@@ -48,6 +48,45 @@ function buildToolName(serverName: string, toolName: string): string {
48
48
  return prefix + sanitizeName(toolName).slice(0, maxToolLen)
49
49
  }
50
50
 
51
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
52
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
53
+ }
54
+
55
+ /**
56
+ * Coerce a server-declared `inputSchema` into a shape every provider accepts.
57
+ *
58
+ * `inputSchema` comes from another process and is not validated against JSON
59
+ * Schema. Passing it through put the same malformed schema in front of the
60
+ * model on *every* turn, so one broken server could make the whole session
61
+ * unusable — not just the one tool. Only the top level is repaired: property
62
+ * schemas that are themselves objects are kept verbatim, so this narrows
63
+ * malformed input without rewriting a server's intent.
64
+ */
65
+ export function sanitizeInputSchema(schema: unknown): {
66
+ properties: Record<string, unknown>
67
+ required?: string[]
68
+ } {
69
+ const root = isPlainObject(schema) ? schema : {}
70
+ const rawProperties = isPlainObject(root.properties) ? root.properties : {}
71
+ const properties: Record<string, unknown> = {}
72
+ for (const [name, property] of Object.entries(rawProperties)) {
73
+ if (isPlainObject(property)) properties[name] = property
74
+ }
75
+
76
+ const required = Array.isArray(root.required)
77
+ ? [
78
+ ...new Set(
79
+ root.required.filter(
80
+ (name): name is string =>
81
+ typeof name === 'string' && Object.prototype.hasOwnProperty.call(properties, name),
82
+ ),
83
+ ),
84
+ ]
85
+ : []
86
+
87
+ return required.length > 0 ? { properties, required } : { properties }
88
+ }
89
+
51
90
  /**
52
91
  * Convert an MCP server ToolDefinition into the main ToolDefinition format
53
92
  * that can be registered in the central tool registry.
@@ -55,13 +94,9 @@ function buildToolName(serverName: string, toolName: string): string {
55
94
  export function convertMcpTool(serverName: string, mcpTool: McpToolDefinition): ToolDefinition {
56
95
  const toolName = buildToolName(serverName, mcpTool.name)
57
96
 
58
- // Build parameters schema — pass through MCP inputSchema as-is
59
97
  const parameters: Record<string, unknown> = {
60
98
  type: 'object',
61
- properties: (mcpTool.inputSchema.properties as Record<string, unknown>) ?? {},
62
- }
63
- if (mcpTool.inputSchema.required) {
64
- parameters.required = mcpTool.inputSchema.required
99
+ ...sanitizeInputSchema(mcpTool.inputSchema),
65
100
  }
66
101
 
67
102
  return {
@@ -149,6 +149,10 @@ export function loadPlugins(
149
149
  // its command, its health would be tracked under the bare event
150
150
  // name, and the cleanup below would have nothing to scope to.
151
151
  source: plugin.name,
152
+ // Same reason as `loadHookConfigs`: the engine's own failure
153
+ // paths read the definition, and an opted-open guard must stay
154
+ // open when its handler throws or it is auto-disabled.
155
+ failureMode: hookCfg.failureMode,
152
156
  handler: async (ctx) => executeHook(hookCfg, ctx, plugin.name),
153
157
  })
154
158
  }
@@ -9,7 +9,7 @@
9
9
  export const PACKAGE_NAME = '@miphamai/cli' as const
10
10
 
11
11
  /** 当前发布版本 */
12
- export const PACKAGE_VERSION = '0.85.21' as const
12
+ export const PACKAGE_VERSION = '0.85.23' as const
13
13
 
14
14
  /** npm install 全局安装命令 */
15
15
  export const NPM_INSTALL_COMMAND = `npm install -g ${PACKAGE_NAME}` as const
@@ -90,4 +90,4 @@ export const TOOL_COUNT = 31 as const
90
90
  * —— `test/e2e/full-pipeline.test.ts` 在 Linux 上整文件 skip、在 macOS 上跑 ——
91
91
  * 但**总数相同**(两边都把被 skip 的算进去)。
92
92
  */
93
- export const TEST_COUNT = 4231 as const
93
+ export const TEST_COUNT = 4342 as const
@@ -320,6 +320,18 @@ export interface HookConfig {
320
320
  /** Command timeout in seconds (Claude Code default is 60). */
321
321
  timeout?: number
322
322
  continueOnBlock?: boolean
323
+ /**
324
+ * What a failure to *run* this hook means.
325
+ *
326
+ * Defaults to `'closed'` for `PreToolUse` and `'open'` for every other event.
327
+ * A guard exists to decide before the tool runs; if it cannot start, time out,
328
+ * or hand back an answer, there is no decision, and allowing the call turns a
329
+ * broken guard into a silent bypass. Other events observe something that
330
+ * already happened — there is nothing left to refuse — so their failures stay
331
+ * context. Set `'open'` on a `PreToolUse` hook to opt it back into the old
332
+ * behaviour.
333
+ */
334
+ failureMode?: 'open' | 'closed'
323
335
  }
324
336
 
325
337
  export interface HookDefinition {
@@ -333,6 +345,12 @@ export interface HookDefinition {
333
345
  * health is tracked per key, and removal has nothing to scope to.
334
346
  */
335
347
  source?: string
348
+ /**
349
+ * Failure policy for this hook — see `HookConfig.failureMode`. Defaults to
350
+ * `'closed'` on `PreToolUse`, where a handler that throws is a guard that
351
+ * could not answer.
352
+ */
353
+ failureMode?: 'open' | 'closed'
336
354
  handler: (context: HookContext) => Promise<HookResult>
337
355
  }
338
356
 
@@ -26,6 +26,24 @@ export function parseFrontmatter(raw: string): FrontmatterResult {
26
26
  }
27
27
  }
28
28
 
29
+ /**
30
+ * Skill names are interpolated verbatim into the `<system-reminder>` block and
31
+ * used as the map key for the Skill tool. A name carrying control characters,
32
+ * bidirectional/format controls, line separators, exotic spaces or angle
33
+ * brackets can forge reminder lines or make the listing unreadable.
34
+ *
35
+ * Returns a short reason when the name is unusable, null when it is fine.
36
+ * Callers reject rather than strip: a name the author did not choose is worse
37
+ * than falling back to the path-derived name.
38
+ */
39
+ export function invalidSkillNameReason(name: string): string | null {
40
+ if (!name.trim()) return 'empty name'
41
+ if (/[\p{Cc}\p{Cf}<>]/u.test(name)) return 'control, format or angle-bracket characters'
42
+ if (/[\p{Zl}\p{Zp}]/u.test(name)) return 'line/paragraph separators'
43
+ if (/[\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]/u.test(name)) return 'non-ASCII spacing'
44
+ return null
45
+ }
46
+
29
47
  export class SkillsLoader implements Skills {
30
48
  private skills = new Map<string, SkillDefinition>()
31
49
 
@@ -147,7 +165,33 @@ export class SkillsLoader implements Skills {
147
165
 
148
166
  const rawDescription = (data.description as string) || ''
149
167
  const rawBody = content.trim() || undefined
150
- const skillName = (data.name as string) || this.nameFromPath(sourceName)
168
+
169
+ // Name gate (see `invalidSkillNameReason`). A declared name that fails is
170
+ // ignored in favour of the path-derived one; if that fails too the skill
171
+ // is skipped. Only a string counts — `name: 42` is a malformed declaration,
172
+ // not a name.
173
+ const declaredName = typeof data.name === 'string' ? data.name.trim() : ''
174
+ let skillName = ''
175
+ if (declaredName) {
176
+ const reason = invalidSkillNameReason(declaredName)
177
+ if (reason) {
178
+ process.stderr.write(
179
+ `⚠️ Skill at ${sourceName}: frontmatter name rejected (${reason}) — using the path-derived name.\n`,
180
+ )
181
+ } else {
182
+ skillName = declaredName
183
+ }
184
+ }
185
+ if (!skillName) {
186
+ skillName = this.nameFromPath(sourceName)
187
+ const reason = invalidSkillNameReason(skillName)
188
+ if (reason) {
189
+ process.stderr.write(
190
+ `⚠️ Skill at ${sourceName}: path-derived name rejected (${reason}) — skipped.\n`,
191
+ )
192
+ return
193
+ }
194
+ }
151
195
 
152
196
  // ── Safety: check for command/MCP shadowing ──
153
197
  const shadowCheck = checkSkillShadow(skillName, rawDescription)
@@ -128,6 +128,42 @@ export const exitWorktreeTool: ToolDefinition = {
128
128
  // Branch detection is best-effort
129
129
  }
130
130
 
131
+ // Unmerged-commit guard. `status --porcelain` above only sees the working
132
+ // tree: a clean worktree whose branch holds commits that exist nowhere
133
+ // else passes it, and `git worktree remove` succeeds too — then the
134
+ // `git branch -D` below silently destroys those commits. Ask git what the
135
+ // branch has that HEAD and every remote do not.
136
+ let branchSafeToDelete = true
137
+ if (!discardChanges && branchName && branchName !== 'HEAD') {
138
+ try {
139
+ const countProc = Bun.spawn(
140
+ ['git', 'rev-list', '--count', branchName, '--not', 'HEAD', '--remotes'],
141
+ { cwd, stdout: 'pipe', stderr: 'pipe' },
142
+ )
143
+ const countText = (await new Response(countProc.stdout).text()).trim()
144
+ const countExit = await countProc.exited
145
+ if (countExit !== 0) {
146
+ // Can't prove it is safe ⇒ keep the branch (never delete blind).
147
+ branchSafeToDelete = false
148
+ } else {
149
+ const unmerged = Number.parseInt(countText, 10)
150
+ if (Number.isFinite(unmerged) && unmerged > 0) {
151
+ return {
152
+ success: false,
153
+ content: '',
154
+ error:
155
+ `Branch "${branchName}" has ${unmerged} commit(s) not on HEAD or any remote:\n\n` +
156
+ `Removing the worktree would delete them (git branch -D).\n\n` +
157
+ `Set discard_changes: true to force removal and discard these commits.\n` +
158
+ `Or merge/push the branch first, then retry.`,
159
+ }
160
+ }
161
+ }
162
+ } catch {
163
+ branchSafeToDelete = false
164
+ }
165
+ }
166
+
131
167
  // Remove the worktree
132
168
  const removeArgs = discardChanges
133
169
  ? ['git', 'worktree', 'remove', '--force', worktreePath]
@@ -149,27 +185,32 @@ export const exitWorktreeTool: ToolDefinition = {
149
185
  }
150
186
  }
151
187
 
152
- // Clean up the branch if we have its name
153
- if (branchName && branchName !== 'HEAD') {
188
+ // Clean up the branch if we have its name and proved it is safe to delete
189
+ let branchDeleted = false
190
+ if (branchSafeToDelete && branchName && branchName !== 'HEAD') {
154
191
  try {
155
192
  const branchProc = Bun.spawn(['git', 'branch', '-D', branchName], {
156
193
  cwd,
157
194
  stdout: 'pipe',
158
195
  stderr: 'pipe',
159
196
  })
160
- await branchProc.exited
197
+ branchDeleted = (await branchProc.exited) === 0
161
198
  // Best-effort — branch cleanup failure is not fatal
162
199
  } catch {
163
200
  // Ignore branch cleanup failures
164
201
  }
165
202
  }
166
203
 
204
+ const branchLine = branchName
205
+ ? `Branch: ${branchName} (${branchDeleted ? 'deleted' : 'kept — could not prove it is safe to delete'})\n`
206
+ : ''
207
+
167
208
  return {
168
209
  success: true,
169
210
  content:
170
211
  `── Worktree Removed ──\n\n` +
171
212
  `Path: ${worktreePath}\n` +
172
- (branchName ? `Branch: ${branchName} (deleted)\n` : '') +
213
+ branchLine +
173
214
  `\nThe worktree has been removed.`,
174
215
  }
175
216
  } catch (err) {
@@ -157,9 +157,12 @@ export function createReadTool(credentialConfig?: CredentialMaskingConfig): Tool
157
157
 
158
158
  // O_NOFOLLOW: fail closed if the path was swapped to a symlink after
159
159
  // resolveSafe (TOCTOU) — never follow it to read outside the workspace.
160
+ // O_NONBLOCK: opening a FIFO blocks until a writer appears, and no timer
161
+ // or signal handler can run inside a synchronous open — without this a
162
+ // `read` of a socket/FIFO would hang the CLI forever.
160
163
  let fd: number
161
164
  try {
162
- fd = openNoFollow(filePath, constants.O_RDONLY)
165
+ fd = openNoFollow(filePath, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0))
163
166
  } catch (err) {
164
167
  if (isSymlinkLoop(err)) {
165
168
  return { success: false, content: '', error: `Path is a symbolic link: ${filePath}` }
@@ -171,9 +174,20 @@ export function createReadTool(credentialConfig?: CredentialMaskingConfig): Tool
171
174
  }
172
175
 
173
176
  try {
174
- if (fstatSync(fd).isDirectory()) {
177
+ const stat = fstatSync(fd)
178
+ if (stat.isDirectory()) {
175
179
  return { success: false, content: '', error: `Path is a directory: ${filePath}` }
176
180
  }
181
+ // FIFOs, sockets and device nodes are not files this tool can read a
182
+ // window out of; O_NONBLOCK got us past the open, so refuse here
183
+ // instead of blocking on the first read (or streaming /dev/zero).
184
+ if (!stat.isFile()) {
185
+ return {
186
+ success: false,
187
+ content: '',
188
+ error: `Path is not a regular file (FIFO, socket or device): ${filePath}`,
189
+ }
190
+ }
177
191
 
178
192
  const offset = (params.offset as number) || 0
179
193
  const limit = (params.limit as number) || DEFAULT_LIMIT
@@ -34,7 +34,8 @@ export interface CronJob {
34
34
  sessionId?: string
35
35
  }
36
36
 
37
- function jobPath(id: string): string {
37
+ /** Location of a job's JSON file. Also the base name its claim directory uses. */
38
+ export function jobPath(id: string): string {
38
39
  return join(CRON_DIR, `${id}.json`)
39
40
  }
40
41
 
@@ -23,13 +23,27 @@ const activeTimers = new Map<string, ReturnType<typeof setTimeout>>()
23
23
  */
24
24
  const WAKEUP_DIR = miphamHome('wakeups')
25
25
 
26
- let wakeupHandler: ((sessionId: string, prompt: string, noop?: boolean) => void) | null = null
26
+ type WakeupHandler = (sessionId: string, prompt: string, noop?: boolean) => void
27
+
28
+ /**
29
+ * Handlers keyed by session — **not** a single slot.
30
+ *
31
+ * The daemon keeps one engine per session in the same process, and every engine
32
+ * construction used to overwrite the previous handler. A wakeup armed for session
33
+ * A then fired into whichever engine was built last, handing the loop prompt to a
34
+ * different conversation. The key is the session the timer was armed for, so a
35
+ * wakeup can only reach its own engine.
36
+ */
37
+ const wakeupHandlers = new Map<string, WakeupHandler>()
27
38
 
28
39
  /** 引擎在启动时注入——timer 到期后回调,把 loop prompt 交回引擎 re-invoke。 */
29
- export function registerWakeupHandler(
30
- fn: (sessionId: string, prompt: string, noop?: boolean) => void,
31
- ): void {
32
- wakeupHandler = fn
40
+ export function registerWakeupHandler(sessionId: string, fn: WakeupHandler): void {
41
+ wakeupHandlers.set(sessionId, fn)
42
+ }
43
+
44
+ /** Drop a session's handler. Call this when the engine that owns it goes away. */
45
+ export function unregisterWakeupHandler(sessionId: string): void {
46
+ wakeupHandlers.delete(sessionId)
33
47
  }
34
48
 
35
49
  /** One session's pending wakeup, as written to disk. */
@@ -98,7 +112,7 @@ function armTimer(sessionId: string, prompt: string, noop: boolean, delayMs: num
98
112
  const timeoutId = setTimeout(() => {
99
113
  activeTimers.delete(timerKey)
100
114
  clearPersistedWakeup(sessionId)
101
- wakeupHandler?.(sessionId, prompt, noop)
115
+ wakeupHandlers.get(sessionId)?.(sessionId, prompt, noop)
102
116
  }, delayMs)
103
117
  activeTimers.set(timerKey, timeoutId)
104
118
  }
package/src/ui/app.tsx CHANGED
@@ -66,6 +66,7 @@ import { recordLoopTurn, readAutoloopJournal } from '../commands/autoloop-journa
66
66
  import { cancelAllSessionTimers, resumeWakeups } from '../tools/scheduling/schedule-wakeup.js'
67
67
  import type { LostWakeup } from '../tools/scheduling/schedule-wakeup.js'
68
68
  import { startCronPoller } from '../core/cron-poller'
69
+ import { exitSession } from '../core/session-exit'
69
70
 
70
71
  interface AppProps {
71
72
  engine: QueryEngine | RemoteEngine
@@ -1075,7 +1076,7 @@ export function App({
1075
1076
  if (result.nextProvider) setProviderId(result.nextProvider)
1076
1077
  if (result.nextModel) setModelId(result.nextModel)
1077
1078
  }
1078
- if (result.exit) process.exit(0)
1079
+ if (result.exit) void exitSession(0)
1079
1080
  return
1080
1081
  }
1081
1082
 
@@ -1087,7 +1088,7 @@ export function App({
1087
1088
 
1088
1089
  // /quit and /exit are special
1089
1090
  if (command === '/exit' || command === '/quit') {
1090
- process.exit(0)
1091
+ void exitSession(0)
1091
1092
  }
1092
1093
 
1093
1094
  // /focus toggle
@@ -1125,13 +1126,13 @@ export function App({
1125
1126
  })
1126
1127
  if (result.needsApiKey) {
1127
1128
  // Don't process nextProvider/model when waiting for API key
1128
- if (result.exit) process.exit(0)
1129
+ if (result.exit) void exitSession(0)
1129
1130
  return
1130
1131
  }
1131
1132
  if (result.clearMessages) setMessages([])
1132
1133
  if (result.nextProvider) setProviderId(result.nextProvider)
1133
1134
  if (result.nextModel) setModelId(result.nextModel)
1134
- if (result.exit) process.exit(0)
1135
+ if (result.exit) void exitSession(0)
1135
1136
  if (result.clearMessages || (result.forwardedMessages?.length ?? 0) > 0) {
1136
1137
  // The conversation this session is looking at just changed (/clear,
1137
1138
  // /resume) — the read-before-write record belongs to the old one.
@@ -1276,7 +1277,7 @@ export function App({
1276
1277
  return
1277
1278
  }
1278
1279
  if (ctrlC.isArmed()) {
1279
- process.exit(0)
1280
+ void exitSession(0)
1280
1281
  }
1281
1282
  ctrlC.arm()
1282
1283
  return
@@ -2460,7 +2460,14 @@ const usageCmd: CommandHandler = (ctx) => {
2460
2460
  const estTokens = c.getEstimatedTokens()
2461
2461
  const msgs = c.getMessages()
2462
2462
  const maxTokens = c.getMaxTokens()
2463
- const pct = ((estTokens / maxTokens) * 100).toFixed(1)
2463
+ // Guard the ratio before formatting: an unknown/zero window makes it NaN or
2464
+ // Infinity, and a NaN `pct` later reaches `'░'.repeat(20 - …)` as a negative
2465
+ // or non-integer count — a RangeError that kills the whole `/usage` command.
2466
+ const maxTokensShown = Number.isFinite(maxTokens) && maxTokens > 0 ? maxTokens : 0
2467
+ const rawPct = maxTokensShown > 0 ? (estTokens / maxTokensShown) * 100 : 0
2468
+ const pctNum = Number.isFinite(rawPct) ? Math.min(100, Math.max(0, rawPct)) : 0
2469
+ const pct = pctNum.toFixed(1)
2470
+ const filledCells = Math.min(20, Math.max(0, Math.ceil(pctNum / 5)))
2464
2471
 
2465
2472
  const tracker = ctx.engine.getUsageTracker()
2466
2473
  const summary = tracker.getSummary()
@@ -2501,12 +2508,12 @@ const usageCmd: CommandHandler = (ctx) => {
2501
2508
  content: stripIndent`
2502
2509
  ${t('commands.usage.title')}
2503
2510
  ${apiLine}
2504
- ${t('commands.usage.context_line', { est: estTokens.toLocaleString(), max: maxTokens.toLocaleString(), pct })}
2511
+ ${t('commands.usage.context_line', { est: estTokens.toLocaleString(), max: maxTokensShown.toLocaleString(), pct })}
2505
2512
  ${t('commands.usage.messages_line', { count: String(msgs.length) })}
2506
2513
  ${t('commands.usage.provider_line', { provider: ctx.providerId })}
2507
2514
  ${t('commands.usage.model_line', { model: ctx.modelId })}
2508
2515
 
2509
- ${'█'.repeat(Math.ceil(Number(pct) / 5))}${'░'.repeat(20 - Math.ceil(Number(pct) / 5))} ${pct}%
2516
+ ${'█'.repeat(filledCells)}${'░'.repeat(20 - filledCells)} ${pct}%
2510
2517
  ${toolSection}${loopSection}
2511
2518
 
2512
2519
  ${t('commands.usage.hint')}