@miphamai/cli 0.85.22 → 0.85.24

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 (49) hide show
  1. package/README.md +1 -1
  2. package/bin/mipham.ts +40 -13
  3. package/package.json +1 -1
  4. package/src/agent/agent-context.ts +19 -6
  5. package/src/agent/agent-registry.ts +42 -2
  6. package/src/agent/message-router.ts +30 -0
  7. package/src/agent/sub-agent.ts +17 -0
  8. package/src/config/loader.ts +41 -0
  9. package/src/core/context-microcompact.ts +1 -1
  10. package/src/core/context.ts +167 -10
  11. package/src/core/cron-poller.ts +74 -6
  12. package/src/core/engine.ts +34 -7
  13. package/src/core/hooks-config.ts +4 -0
  14. package/src/core/hooks-executor.ts +96 -28
  15. package/src/core/hooks.ts +49 -3
  16. package/src/core/permission-rules.ts +32 -2
  17. package/src/core/safe-mode.ts +11 -0
  18. package/src/core/session-exit.ts +73 -0
  19. package/src/core/session-log.ts +36 -1
  20. package/src/daemon/engine-capabilities.ts +13 -4
  21. package/src/daemon/launch.ts +37 -0
  22. package/src/daemon/server.ts +9 -1
  23. package/src/i18n-core/locales/en-US.json +1 -0
  24. package/src/i18n-core/locales/zh-CN.json +1 -0
  25. package/src/index.tsx +68 -27
  26. package/src/mcp/client.ts +22 -8
  27. package/src/mcp/http-transport.ts +19 -4
  28. package/src/mcp/registry.ts +40 -5
  29. package/src/plugin/plugin-loader.ts +4 -0
  30. package/src/providers/anthropic.ts +8 -2
  31. package/src/providers/openai-compat.ts +14 -2
  32. package/src/shared/arg-validation.ts +2 -1
  33. package/src/shared/package-info.ts +2 -2
  34. package/src/shared/types.ts +18 -0
  35. package/src/skills/loader.ts +86 -4
  36. package/src/tools/agent/workflow.ts +9 -2
  37. package/src/tools/exec/bash.ts +38 -11
  38. package/src/tools/exec/exit-worktree.ts +45 -4
  39. package/src/tools/file/read.ts +16 -2
  40. package/src/tools/network/web-fetch.ts +11 -3
  41. package/src/tools/network/web-search.ts +5 -1
  42. package/src/tools/scheduling/cron.ts +2 -1
  43. package/src/tools/scheduling/schedule-wakeup.ts +23 -8
  44. package/src/tools/validation.ts +11 -0
  45. package/src/ui/app.tsx +6 -5
  46. package/src/ui/commands.ts +17 -8
  47. package/src/workflow/primitives/agent.ts +34 -5
  48. package/src/workflow/primitives/verify.ts +36 -20
  49. package/src/workflow/runtime.ts +10 -2
@@ -1,4 +1,4 @@
1
- import { mkdirSync } from 'node:fs'
1
+ import { mkdirSync, openSync, readSync, closeSync, statSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
3
  import { createHash } from 'node:crypto'
4
4
  import type { Message, ToolUseContent, ToolResultContent, ToolResult } from '../shared/types'
@@ -150,6 +150,32 @@ function sleepSyncMs(ms: number): void {
150
150
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
151
151
  }
152
152
 
153
+ /**
154
+ * Does the log end on a complete line (or not exist yet)?
155
+ *
156
+ * Uses stat + a one-byte read instead of `readFileSync`: the repair gate runs
157
+ * on every save, and a session log can be large. Non-regular paths answer
158
+ * `true` here — `appendRegularFileSync` is the gate that refuses those, and
159
+ * opening a FIFO for repair would block.
160
+ */
161
+ function endsWithNewline(path: string): boolean {
162
+ try {
163
+ const st = statSync(path)
164
+ if (!st.isFile() || st.size === 0) return true
165
+ const fd = openSync(path, 'r')
166
+ try {
167
+ const last = Buffer.alloc(1)
168
+ return readSync(fd, last, 0, 1, st.size - 1) === 1 && last[0] === 0x0a
169
+ } finally {
170
+ closeSync(fd)
171
+ }
172
+ } catch {
173
+ // Missing (append creates it) or unreadable (append will refuse) — either
174
+ // way there is no partial line to close.
175
+ return true
176
+ }
177
+ }
178
+
153
179
  /** 补上的那条结果的正文:说明事情本身,并给出下一步,而不是只报一个状态。 */
154
180
  function interruptedCallNotice(): string {
155
181
  return (
@@ -244,6 +270,15 @@ export class SessionLog {
244
270
  // restrict to owner-only (dir 0700, file 0600).
245
271
  mkdirSync(LOG_DIR, { recursive: true, mode: 0o700 })
246
272
  const path = join(LOG_DIR, `${sanitizeSessionName(this.name)}.jsonl`)
273
+
274
+ // A writer killed mid-append can leave a partial line with no trailing
275
+ // newline. `open()` skips that line, but the next append would glue the new
276
+ // event onto it — corrupting both, and losing the first event after resume.
277
+ // Close the partial line before appending (it stays a skippable bad line).
278
+ if (this.buf.length > this.flushed && !endsWithNewline(path)) {
279
+ appendRegularFileSync(path, '\n', { mode: 0o600 })
280
+ }
281
+
247
282
  let wrote = 0
248
283
  for (const e of this.buf.slice(this.flushed)) {
249
284
  // FIFO/socket 路径上「写不进去」而不是**干等**(`appendFileSync` 会打开目标写)。
@@ -30,6 +30,7 @@ import { SkillsLoader } from '../skills/loader'
30
30
  import { RulesLoader } from '../core/rules-loader'
31
31
  import { HookEngine } from '../core/hooks'
32
32
  import { loadHookConfigs } from '../core/hooks-config'
33
+ import { isSafeMode } from '../core/safe-mode'
33
34
  import { loadSettingsJson } from '../config/loader'
34
35
  import { getWorkspaceTrust, warnProjectHooksSkipped } from '../core/workspace-trust'
35
36
  import { AgentRegistry } from '../agent/agent-registry'
@@ -68,8 +69,10 @@ function skillsFor(cwd: string, paths?: string[]): SkillsLoader {
68
69
  // 内置 skill 从包内解析(`import.meta.dirname`),与 cwd 无关;用户 skill 在
69
70
  // `~/.mipham/skills`。三者里只有外部路径随 cwd 变。
70
71
  loader.loadBuiltinFromPackage()
71
- loader.loadUserSkills()
72
- if (paths && paths.length > 0) loader.loadExternal(paths)
72
+ if (!isSafeMode()) {
73
+ loader.loadUserSkills()
74
+ if (paths && paths.length > 0) loader.loadExternal(paths)
75
+ }
73
76
  skillsCache.set(cwd, loader)
74
77
  return loader
75
78
  }
@@ -91,6 +94,10 @@ function hooksFor(cwd: string, skills: SkillsLoader): HookEngine {
91
94
  // 会话 cwd 必须显式传:daemon 一个进程服务多个会话,`process.cwd()` 是它自己被
92
95
  // 启动时所在的目录,不属于任何会话 —— hooks 会在那里跑,并且**被告知**它在那里。
93
96
  const engine = new HookEngine(cwd)
97
+ if (isSafeMode()) {
98
+ hookCache.set(cwd, engine)
99
+ return engine
100
+ }
94
101
  for (const skill of skills.list()) {
95
102
  for (const hook of skill.hooks ?? []) engine.register(hook)
96
103
  }
@@ -110,8 +117,10 @@ function agentsFor(cwd: string): AgentRegistry {
110
117
  const cached = agentCache.get(cwd)
111
118
  if (cached) return cached
112
119
  const registry = new AgentRegistry()
113
- registry.loadUserAgents()
114
- registry.loadProjectAgents(cwd)
120
+ if (!isSafeMode()) {
121
+ registry.loadUserAgents()
122
+ registry.loadProjectAgents(cwd)
123
+ }
115
124
  agentCache.set(cwd, registry)
116
125
  return registry
117
126
  }
@@ -322,6 +322,43 @@ export async function waitForDaemonExit(
322
322
  }
323
323
  }
324
324
 
325
+ /**
326
+ * Stop a daemon and confirm it is gone.
327
+ *
328
+ * SIGTERM, then wait; if the process is still there, SIGKILL and wait a short
329
+ * window more. Returns true only when `waitForExit` confirms the process
330
+ * disappeared — delivering a signal is a request, not a result.
331
+ */
332
+ export async function terminateDaemonProcess(
333
+ pid: number,
334
+ opts: {
335
+ timeoutMs?: number
336
+ forceTimeoutMs?: number
337
+ deps?: {
338
+ kill?: (pid: number, signal: NodeJS.Signals) => void
339
+ waitForExit?: (opts?: { timeoutMs?: number }) => Promise<boolean>
340
+ }
341
+ } = {},
342
+ ): Promise<boolean> {
343
+ const kill = opts.deps?.kill ?? ((p: number, signal: NodeJS.Signals) => process.kill(p, signal))
344
+ const wait = opts.deps?.waitForExit ?? ((o?: { timeoutMs?: number }) => waitForDaemonExit(o))
345
+
346
+ const waitOpts = opts.timeoutMs === undefined ? undefined : { timeoutMs: opts.timeoutMs }
347
+ try {
348
+ kill(pid, 'SIGTERM')
349
+ } catch {
350
+ // Already gone between the status probe and the signal.
351
+ }
352
+ if (await wait(waitOpts)) return true
353
+
354
+ try {
355
+ kill(pid, 'SIGKILL')
356
+ } catch {
357
+ // Exited between the wait and the kill.
358
+ }
359
+ return wait({ timeoutMs: opts.forceTimeoutMs ?? 2_000 })
360
+ }
361
+
325
362
  /**
326
363
  * The daemon process body, shared by the `__daemon` branch of the compiled
327
364
  * binary and by `bin/daemon.ts` (source mode). One implementation, two entry
@@ -38,6 +38,10 @@ import { createDingtalkApi } from './dingtalk/api.js'
38
38
  import type { DingtalkConfig } from './dingtalk/types.js'
39
39
  import { startHeartbeat } from './heartbeat'
40
40
  import { wireDaemonEngine } from './engine-capabilities'
41
+ import {
42
+ cancelAllSessionTimers,
43
+ unregisterWakeupHandler,
44
+ } from '../tools/scheduling/schedule-wakeup'
41
45
 
42
46
  interface ServerConfig {
43
47
  db: DaemonDatabase
@@ -559,8 +563,12 @@ export function createServer(config: ServerConfig): Server<WsData> {
559
563
  pool.stopWorker(sessionId).catch((err: unknown) => {
560
564
  logger.error('error stopping worker', { sessionId, error: err })
561
565
  })
562
- // Remove engine from cache
566
+ // Remove engine from cache. A closed session must not keep receiving
567
+ // wakeups: drop the handler (it holds the engine) and any timer still
568
+ // armed for it, plus the persisted intent.
563
569
  engineCache.delete(sessionId)
570
+ unregisterWakeupHandler(sessionId)
571
+ cancelAllSessionTimers(sessionId)
564
572
  sm.closeSession(sessionId)
565
573
  return json({ ok: true })
566
574
  }
@@ -952,6 +952,7 @@
952
952
  "tool_collision": "[mcp] Tool collision: \"{name}\" already registered. Skipping.",
953
953
  "missing_param": "Missing required parameter: \"{param}\"",
954
954
  "invalid_params": "Invalid parameters: {errors}",
955
+ "unparseable_args": "The arguments for this tool call were not valid JSON ({detail}). Nothing was executed. Re-issue the call with complete JSON — do not infer the parameters from the fragment.",
955
956
  "type_string": "\"{key}\" must be a string",
956
957
  "type_number": "\"{key}\" must be a number",
957
958
  "type_boolean": "\"{key}\" must be a boolean",
@@ -952,6 +952,7 @@
952
952
  "tool_collision": "[mcp] 工具冲突:\"{name}\" 已注册,跳过。",
953
953
  "missing_param": "缺少必需参数:\"{param}\"",
954
954
  "invalid_params": "参数无效:{errors}",
955
+ "unparseable_args": "这次工具调用的参数不是合法 JSON({detail}),没有执行任何操作。请带着完整的 JSON 重新发起调用 —— 不要从这段残片里猜参数。",
955
956
  "type_string": "\"{key}\" 必须是字符串",
956
957
  "type_number": "\"{key}\" 必须是数字",
957
958
  "type_boolean": "\"{key}\" 必须是布尔值",
package/src/index.tsx CHANGED
@@ -51,7 +51,14 @@ import { formatMcpConnectFailures, type McpConnectFailure } from './mcp/connect-
51
51
  import { AgentRegistry } from './agent/agent-registry'
52
52
  import { HookEngine } from './core/hooks'
53
53
  import { loadHookConfigs } from './core/hooks-config'
54
+ import { isSafeMode } from './core/safe-mode'
54
55
  import { ArtifactServer } from './artifacts/server'
56
+ import {
57
+ exitSession,
58
+ registerExitHandler,
59
+ withTimeout,
60
+ SESSION_END_HOOK_TIMEOUT_MS,
61
+ } from './core/session-exit'
55
62
  import { getMetrics } from './core/metrics'
56
63
  import { initTelemetry, enableTelemetryNow } from './telemetry/index'
57
64
  import { wasPrompted, markPrompted, isInteractive, setTelemetryEnabled } from './telemetry/consent'
@@ -513,12 +520,25 @@ export async function runApp(options: RunOptions): Promise<void> {
513
520
  )
514
521
  }
515
522
 
523
+ // `--safe-mode` (bin/mipham.ts sets MIPHAM_SAFE_MODE=1) skips everything
524
+ // supplied by the user, the project or plugins. Before this, the flag only
525
+ // set an env var that nothing read — the help text advertised a guard that
526
+ // did not exist.
527
+ const safeMode = isSafeMode()
528
+ if (safeMode) {
529
+ console.error(
530
+ '[mipham] safe mode: custom agents, skills, hooks and plugins are disabled (built-in skills remain).',
531
+ )
532
+ }
533
+
516
534
  // Load skills
517
535
  const skillsLoader = new SkillsLoader()
518
536
  skillsLoader.loadBuiltinFromPackage()
519
- skillsLoader.loadUserSkills()
520
- if (config.skills?.paths) {
521
- skillsLoader.loadExternal(config.skills.paths)
537
+ if (!safeMode) {
538
+ skillsLoader.loadUserSkills()
539
+ if (config.skills?.paths) {
540
+ skillsLoader.loadExternal(config.skills.paths)
541
+ }
522
542
  }
523
543
 
524
544
  // Initialize plugin manager
@@ -741,10 +761,12 @@ export async function runApp(options: RunOptions): Promise<void> {
741
761
  // CLI 是一次性进程,会话 cwd 就是 `process.cwd()`;写出来是为了与 daemon 那处
742
762
  // (`daemon/engine-capabilities.ts` 传会话 cwd)成对照,别让哪边看起来像漏了。
743
763
  const hookEngine = new HookEngine(process.cwd())
744
- for (const skill of skillsLoader.list()) {
745
- if (skill.hooks) {
746
- for (const hook of skill.hooks) {
747
- hookEngine.register(hook)
764
+ if (!safeMode) {
765
+ for (const skill of skillsLoader.list()) {
766
+ if (skill.hooks) {
767
+ for (const hook of skill.hooks) {
768
+ hookEngine.register(hook)
769
+ }
748
770
  }
749
771
  }
750
772
  }
@@ -757,8 +779,10 @@ export async function runApp(options: RunOptions): Promise<void> {
757
779
  // skip is announced, since silence would look the same as having passed.
758
780
  // `settingsJson` itself was read up top, next to the permission it also feeds.
759
781
  if (settingsJson.projectHooksSkipped) warnProjectHooksSkipped(process.cwd())
760
- for (const def of loadHookConfigs(settingsJson.hooks)) {
761
- hookEngine.register(def)
782
+ if (!safeMode) {
783
+ for (const def of loadHookConfigs(settingsJson.hooks)) {
784
+ hookEngine.register(def)
785
+ }
762
786
  }
763
787
 
764
788
  // Start artifact server (lazy — first artifact creation triggers listening)
@@ -830,18 +854,22 @@ export async function runApp(options: RunOptions): Promise<void> {
830
854
 
831
855
  // Initialize agent registry and load plugin agents/skills/MCP/hooks
832
856
  const agentRegistry = new AgentRegistry()
833
- agentRegistry.loadUserAgents()
834
- agentRegistry.loadProjectAgents(process.cwd())
857
+ if (!safeMode) {
858
+ agentRegistry.loadUserAgents()
859
+ agentRegistry.loadProjectAgents(process.cwd())
860
+ }
835
861
  engine.setAgentRegistry(agentRegistry)
836
862
 
837
- loadPlugins(
838
- pluginManager,
839
- agentRegistry,
840
- skillsLoader,
841
- hookEngine,
842
- McpClient.getInstance(),
843
- tools,
844
- )
863
+ if (!safeMode) {
864
+ loadPlugins(
865
+ pluginManager,
866
+ agentRegistry,
867
+ skillsLoader,
868
+ hookEngine,
869
+ McpClient.getInstance(),
870
+ tools,
871
+ )
872
+ }
845
873
 
846
874
  engine.setupContextSummarizer()
847
875
 
@@ -915,12 +943,17 @@ export async function runApp(options: RunOptions): Promise<void> {
915
943
  }
916
944
  }
917
945
 
918
- const saveAndExit = () => {
919
- saved = true
946
+ const shutdown = async (): Promise<void> => {
920
947
  clearInterval(heartbeatInterval)
921
948
  unregisterSession(sessionName)
922
- // P2-1: Trigger SessionEnd hooks before cleanup (best-effort)
923
- hookEngine.executeSessionEnd(sessionName).catch(() => {})
949
+ // SessionEnd hooks are asynchronous; process.exit() is not. Starting the
950
+ // hooks and exiting in the same tick meant they never ran — the await is
951
+ // the difference between "best effort" and "never". Bounded, because a
952
+ // hook waiting on an unreachable server must not hold the terminal open.
953
+ await withTimeout(
954
+ hookEngine.executeSessionEnd(sessionName).catch(() => undefined),
955
+ SESSION_END_HOOK_TIMEOUT_MS,
956
+ )
924
957
  artifactServer.stop()
925
958
  persistSession()
926
959
  // Finalize the session — write session summary + flush CRSI effectiveness
@@ -931,8 +964,15 @@ export async function runApp(options: RunOptions): Promise<void> {
931
964
  } catch {
932
965
  // ignore — CRSI closeout is non-critical
933
966
  }
967
+ saved = true
934
968
  getMetrics().activeSessions.dec()
935
- process.exit(0)
969
+ }
970
+ // Every user-initiated exit (`/exit`, `/quit`, the second Ctrl+C, signals)
971
+ // goes through this one handler, so none of them can skip SessionEnd.
972
+ registerExitHandler(shutdown)
973
+
974
+ const saveAndExit = () => {
975
+ void exitSession(0)
936
976
  }
937
977
 
938
978
  process.on('SIGINT', saveAndExit)
@@ -941,9 +981,10 @@ export async function runApp(options: RunOptions): Promise<void> {
941
981
  // a handler the session log is silently dropped on those paths.
942
982
  process.on('SIGHUP', saveAndExit)
943
983
 
944
- // Safety net: persist on exit for paths that bypass saveAndExit (e.g. /exit
945
- // and /quit call process.exit(0) directly). saveAndExit already persists;
946
- // guard on !saved to avoid double-writing.
984
+ // Safety net: persist on exit for paths that never reach `shutdown` — a
985
+ // daemon worker being killed, a crash, `process.exit()` called by code that
986
+ // does not know about this session. `shutdown` already persisted; guard on
987
+ // !saved to avoid double-writing.
947
988
  process.on('exit', () => {
948
989
  clearInterval(heartbeatInterval)
949
990
  unregisterSession(sessionName)
package/src/mcp/client.ts CHANGED
@@ -11,6 +11,7 @@ import { HttpTransport, McpHttpError } from './http-transport'
11
11
  import { McpProtocol } from './protocol'
12
12
  import { OAuthClient } from './oauth'
13
13
  import { TokenStore } from './token-store'
14
+ import { createAwakeTimer } from '../providers/fetch-utils'
14
15
  import { createT } from '../i18n-core/t'
15
16
  import enUS from '../i18n-core/locales/en-US.json'
16
17
  import zhCN from '../i18n-core/locales/zh-CN.json'
@@ -454,10 +455,22 @@ export class McpClient {
454
455
  }
455
456
  }
456
457
 
457
- /** Race the connect handshake against a timeout so a hung server fails fast. */
458
+ /**
459
+ * Race the connect handshake against a timeout so a hung server fails fast.
460
+ *
461
+ * The budget counts *awake* time (`createAwakeTimer`), not wall time: a laptop
462
+ * that sleeps mid-handshake would otherwise fire the whole budget the instant
463
+ * the lid opens, latch the connection as `error`, and — because a failed
464
+ * server registers no tools — never give `markIfTransportLost` a chance to
465
+ * reconnect. The server is fine; only the clock moved.
466
+ */
458
467
  private async withConnectTimeout<T>(name: string, fn: () => Promise<T>): Promise<T> {
459
468
  const timeoutMs = connectTimeoutMs()
460
- let timer: ReturnType<typeof setTimeout> | null = null
469
+ // Held in an object, not a `let`: the timer is armed inside the Promise
470
+ // executor, and assignments made there are invisible to control-flow
471
+ // narrowing — TS keeps the variable typed `null` and the cleanup call below
472
+ // is a type error rather than code.
473
+ const timer: { cancel?: () => void } = {}
461
474
  // Swallow a late rejection: if the timeout wins, transport.close() in the
462
475
  // caller's catch makes fn()'s pending request reject after we've moved on.
463
476
  const work = fn()
@@ -466,14 +479,13 @@ export class McpClient {
466
479
  return await Promise.race([
467
480
  work,
468
481
  new Promise<never>((_, reject) => {
469
- timer = setTimeout(
470
- () => reject(new Error(`MCP connect timed out for "${name}" after ${timeoutMs}ms`)),
471
- timeoutMs,
482
+ timer.cancel = createAwakeTimer(timeoutMs, () =>
483
+ reject(new Error(`MCP connect timed out for "${name}" after ${timeoutMs}ms`)),
472
484
  )
473
485
  }),
474
486
  ])
475
487
  } finally {
476
- if (timer) clearTimeout(timer)
488
+ timer.cancel?.()
477
489
  }
478
490
  }
479
491
 
@@ -493,11 +505,13 @@ export class McpClient {
493
505
  * nothing to wait for, and `callTool` will say so.
494
506
  */
495
507
  async waitUntilReady(name: string, timeoutMs: number = connectTimeoutMs()): Promise<boolean> {
496
- const deadline = Date.now() + timeoutMs
508
+ // Awake time, same as the handshake budget it mirrors: a sleep mid-wait must
509
+ // not spend the deadline the server never got to use.
510
+ const deadline = performance.now() + timeoutMs
497
511
  for (;;) {
498
512
  const conn = this.connections.get(name)
499
513
  if (!conn || conn.status !== 'connecting') return true
500
- if (Date.now() >= deadline) return false
514
+ if (performance.now() >= deadline) return false
501
515
  await new Promise((resolve) => setTimeout(resolve, CONNECT_POLL_MS))
502
516
  }
503
517
  }
@@ -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
  }
@@ -310,8 +310,14 @@ export class AnthropicProvider implements ProviderInstance {
310
310
  let parsedInput: Record<string, unknown> = {}
311
311
  try {
312
312
  parsedInput = JSON.parse(accumulatedToolInput)
313
- } catch {
314
- parsedInput = { _raw: accumulatedToolInput }
313
+ } catch (err) {
314
+ // Same tag as the OpenAI-compatible path: a bare fragment
315
+ // reaches the validator as "missing required parameter",
316
+ // which sends the model looking for the wrong mistake.
317
+ parsedInput = {
318
+ _parseError: `${err instanceof Error ? err.message : String(err)}; received ${accumulatedToolInput.length} characters`,
319
+ _raw: accumulatedToolInput,
320
+ }
315
321
  }
316
322
 
317
323
  yield {
@@ -33,6 +33,11 @@ export class OpenAICompatProvider implements ProviderInstance {
33
33
  stream: true,
34
34
  max_tokens: req.maxTokens || declaredMaxOutput || 8192,
35
35
  temperature: req.temperature,
36
+ // Without this the server never sends the final usage chunk, so callers
37
+ // that report token use (sub-agents, the metrics footer) record 0 for
38
+ // every OpenAI-compatible provider — a number that reads as "free" rather
39
+ // than "not measured".
40
+ stream_options: { include_usage: true },
36
41
  tools: req.tools?.map((t) => ({ type: 'function', function: t })),
37
42
  }
38
43
 
@@ -448,8 +453,15 @@ export class OpenAICompatProvider implements ProviderInstance {
448
453
  if (!raw) return {}
449
454
  try {
450
455
  return JSON.parse(raw)
451
- } catch {
452
- return { _raw: raw }
456
+ } catch (err) {
457
+ // Tag the failure instead of handing back a bare fragment: the tool's
458
+ // validator would then report "missing required parameter", and the model
459
+ // would spend its retry supplying a parameter it had already written
460
+ // rather than re-sending the JSON it truncated.
461
+ return {
462
+ _parseError: `${err instanceof Error ? err.message : String(err)}; received ${raw.length} characters`,
463
+ _raw: raw,
464
+ }
453
465
  }
454
466
  }
455
467
 
@@ -44,6 +44,7 @@ const KNOWN_FLAGS = [
44
44
  '--help',
45
45
  '-h',
46
46
  '--dump-config',
47
+ '--profile',
47
48
  '--safe-mode',
48
49
  '--resume',
49
50
  '--permission',
@@ -71,7 +72,7 @@ const KNOWN_FLAGS = [
71
72
  * actually wrong never mentioned, exit 1, no CLI. Their values are open (a provider may
72
73
  * be user-defined), so — unlike `--permission` — this module owns only their spelling.
73
74
  */
74
- const VALUE_FLAGS = ['--resume', '--permission', '--provider', '--model']
75
+ const VALUE_FLAGS = ['--resume', '--permission', '--provider', '--model', '--profile']
75
76
 
76
77
  /**
77
78
  * The first token that would be read as a command, skipping flags and the values
@@ -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.22' as const
12
+ export const PACKAGE_VERSION = '0.85.24' 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 = 4247 as const
93
+ export const TEST_COUNT = 4388 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