@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
@@ -247,38 +247,145 @@ const LEADING_ASSIGNMENT_RE = /^[A-Za-z_][A-Za-z0-9_]*=/
247
247
  * 不剥尾随符号(`rm -rf x )` 里的 `)`):`wildcardMatch` 的 `*` 已经吃掉它。
248
248
  */
249
249
  export function stripLeadingShellNoise(segment: string): string {
250
- let tokens = segment.trim().split(/\s+/).filter(Boolean)
250
+ const n = segment.length
251
+ let i = 0
251
252
  let stripped = false
252
- let skipFlags = false
253
- for (;;) {
254
- const head = tokens[0]
255
- if (!head) break
256
- if (skipFlags && /^--?[A-Za-z]/.test(head)) {
257
- tokens = tokens.slice(1)
258
- stripped = true
259
- continue
253
+ const skipSpace = (): void => {
254
+ while (i < n && /\s/.test(segment[i]!)) i++
255
+ }
256
+
257
+ /**
258
+ * Consume one `NAME=value`, returning the index just past the value.
259
+ *
260
+ * Splitting on whitespace was the bug: `X="a b" rm …` became the tokens
261
+ * `['X="a', 'b"', 'rm', …]`, so stripping the first "assignment" left
262
+ * `b" rm …` — and the real command vanished from every gate that reads this
263
+ * normalized form (parameterized deny rules, dangerous `rm`, world-writable
264
+ * `chmod`). Values therefore have to be scanned with shell quoting rules,
265
+ * not tokenized by spaces.
266
+ */
267
+ const consumeAssignment = (start: number): number | null => {
268
+ const m = LEADING_ASSIGNMENT_RE.exec(segment.slice(start))
269
+ if (!m) return null
270
+ let j = start + m[0].length
271
+ while (j < n) {
272
+ const c = segment[j]!
273
+ if (/\s/.test(c)) break
274
+ if (c === '\\') {
275
+ j += 2
276
+ continue
277
+ }
278
+ if (c === "'") {
279
+ j++
280
+ while (j < n && segment[j] !== "'") j++
281
+ if (j < n) j++
282
+ continue
283
+ }
284
+ if (c === '"') {
285
+ j++
286
+ while (j < n) {
287
+ if (segment[j] === '\\') {
288
+ j += 2
289
+ continue
290
+ }
291
+ if (segment[j] === '"') {
292
+ j++
293
+ break
294
+ }
295
+ j++
296
+ }
297
+ continue
298
+ }
299
+ if (c === '`') {
300
+ j++
301
+ while (j < n && segment[j] !== '`') {
302
+ if (segment[j] === '\\') j++
303
+ j++
304
+ }
305
+ if (j < n) j++
306
+ continue
307
+ }
308
+ if (c === '$' && segment[j + 1] === '(') {
309
+ j += 2
310
+ let depth = 1
311
+ while (j < n && depth > 0) {
312
+ if (segment[j] === '(') depth++
313
+ else if (segment[j] === ')') depth--
314
+ j++
315
+ }
316
+ continue
317
+ }
318
+ if (c === '$' && segment[j + 1] === '{') {
319
+ j += 2
320
+ while (j < n && segment[j] !== '}') j++
321
+ if (j < n) j++
322
+ continue
323
+ }
324
+ if (c === '(') {
325
+ // Array assignment (`arr=(a b) cmd`): the whole parenthesized list is
326
+ // the value, spaces included.
327
+ let depth = 0
328
+ while (j < n) {
329
+ if (segment[j] === '(') depth++
330
+ else if (segment[j] === ')') {
331
+ depth--
332
+ if (depth === 0) {
333
+ j++
334
+ break
335
+ }
336
+ }
337
+ j++
338
+ }
339
+ continue
340
+ }
341
+ j++
260
342
  }
261
- skipFlags = false
262
- const bare = head.replace(/^[({!]+/, '') // `(!` 这类连写
263
- if (bare !== head) {
264
- tokens = bare ? [bare, ...tokens.slice(1)] : tokens.slice(1)
343
+ return j
344
+ }
345
+
346
+ for (;;) {
347
+ skipSpace()
348
+ if (i >= n) break
349
+ const c = segment[i]!
350
+
351
+ // Grouping / negation punctuation. Consume runs (`(!` / `((`).
352
+ if (LEADING_SHELL_PUNCT.has(c)) {
353
+ i++
265
354
  stripped = true
266
355
  continue
267
356
  }
268
- if (LEADING_SHELL_PUNCT.has(head) || LEADING_ASSIGNMENT_RE.test(head)) {
269
- tokens = tokens.slice(1)
270
- stripped = true
271
- continue
357
+
358
+ const word = /^[A-Za-z_][A-Za-z0-9_]*/.exec(segment.slice(i))?.[0]
359
+ if (word) {
360
+ const after = i + word.length
361
+ const atBoundary = after === n || /\s/.test(segment[after]!)
362
+ if (LEADING_SHELL_KEYWORDS.has(word) && atBoundary) {
363
+ i = after
364
+ stripped = true
365
+ // `time -p rm …` — the keyword's own bare flags are not the command.
366
+ for (;;) {
367
+ skipSpace()
368
+ if (i < n && segment[i] === '-' && /[A-Za-z]/.test(segment[i + 1] ?? '')) {
369
+ while (i < n && !/\s/.test(segment[i]!)) i++
370
+ continue
371
+ }
372
+ break
373
+ }
374
+ continue
375
+ }
272
376
  }
273
- if (LEADING_SHELL_KEYWORDS.has(head)) {
274
- tokens = tokens.slice(1)
377
+
378
+ const assignmentEnd = consumeAssignment(i)
379
+ if (assignmentEnd !== null) {
380
+ i = assignmentEnd
275
381
  stripped = true
276
- skipFlags = true // `time -p rm …` —— 关键字自己的裸 flag 不是命令
277
382
  continue
278
383
  }
384
+
279
385
  break
280
386
  }
281
- return stripped ? tokens.join(' ') : segment
387
+
388
+ return stripped ? segment.slice(i).trim() : segment
282
389
  }
283
390
 
284
391
  function uniq(items: string[]): string[] {
@@ -325,14 +432,19 @@ export function extractBashFileAccess(command: string): BashFileAccess {
325
432
  const read: string[] = []
326
433
  const write: string[] = []
327
434
 
328
- // 1. Redirect targets. Handles `> file` and `>file`, optional fd prefix
329
- // (`2>`, `&>`). Heredocs (`<<`) and fd-dup targets (`2>&1`) are skipped —
330
- // their "target" is a delimiter or file descriptor, not a path.
331
- const redirectRe = /(?:^|[\s;|&])([0-9]*&?)?(>>|<<|<|>)\s*([^\s;|&<>]+)/g
435
+ // 1. Redirect targets. Handles `> file`, `>file`, and the same operators
436
+ // right after a substitution/subshell (`(echo x)>file`, `x=$(date)>file`).
437
+ // Requiring a separator before the operator (the old shape) missed every
438
+ // no-space form, so `Edit(path)`/`Write(path)` deny rules were bypassable
439
+ // with `echo hi>path`. Heredocs (`<<`) and fd-dup targets (`2>&1`) are
440
+ // skipped — their "target" is a delimiter or file descriptor, not a path.
441
+ const redirectRe = /([0-9]*&?)?(>>|<<|<|>)\s*([^\s;|&<>]+)/g
332
442
  let m: RegExpExecArray | null
333
443
  while ((m = redirectRe.exec(command)) !== null) {
334
444
  const op = m[2]!
335
445
  if (op === '<<') continue // heredoc delimiter
446
+ // Process substitution `<(...)` / `>(...)` is not a redirect to a file.
447
+ if (m[3]!.startsWith('(')) continue
336
448
  const target = stripQuotes(m[3]!)
337
449
  if (op === '<') read.push(target)
338
450
  else write.push(target)
@@ -526,6 +638,10 @@ function scanReaderWriterCommands(
526
638
  // `sed -i` / `perl -i` read AND write their file args.
527
639
  const inPlace = args.some((a) => a === '-i' || a.startsWith('--in-place'))
528
640
  for (const arg of args) {
641
+ // Redirection operators are syntax, not paths: `cat < /etc/hosts`
642
+ // already contributed `/etc/hosts` in the redirect pass. Keeping the
643
+ // bare `<` here made it look like a read target of its own.
644
+ if (/^[0-9]*[<>]{1,2}&?[0-9-]*$/.test(arg)) continue
529
645
  if (arg.startsWith('-')) {
530
646
  // `--include=*secret*` / `--file=.env`: the option VALUE is a path the
531
647
  // reader opens, but the `-` guard used to drop the whole token, so a
@@ -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/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
  }
@@ -345,11 +345,32 @@ export class PluginManager {
345
345
  // plugin command instead of starting empty.
346
346
  this.plugins = Array.isArray(parsed) ? (parsed as InstalledPlugin[]) : []
347
347
  if (!Array.isArray(parsed)) {
348
- this.loadWarning = `Plugin state file is not a list; starting empty (${this.statePath})`
348
+ this.quarantineState('Plugin state file is not a list;')
349
349
  }
350
350
  } catch (err) {
351
351
  this.plugins = []
352
- this.loadWarning = `Could not read plugin state (${this.statePath}): ${String(err)}`
352
+ this.quarantineState(`Could not read plugin state (${this.statePath}): ${String(err)}.`)
353
+ }
354
+ }
355
+
356
+ /**
357
+ * Move an unusable `state.json` aside before continuing with an empty list.
358
+ *
359
+ * Warning alone is not enough: the next `saveState` persists `[]` over the
360
+ * same path, so a file we could not read becomes a file whose records are
361
+ * gone. Renaming keeps the bytes for hand recovery — and if the rename fails
362
+ * the warning says so, because that is exactly the case where the next save
363
+ * destroys the only copy.
364
+ */
365
+ private quarantineState(reason: string): void {
366
+ const backup = `${this.statePath}.corrupt-${Date.now()}`
367
+ try {
368
+ renameSync(this.statePath, backup)
369
+ this.loadWarning = `${reason} Moved to ${backup}; starting with an empty plugin list.`
370
+ } catch (err) {
371
+ this.loadWarning =
372
+ `${reason} Could not move it aside (${String(err)}); starting with an empty ` +
373
+ `plugin list — the next change overwrites ${this.statePath}.`
353
374
  }
354
375
  }
355
376
 
@@ -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
 
@@ -8,6 +8,9 @@ import { getMetrics } from '../core/metrics'
8
8
  * active. Exported so the permission classifier and `self-critique` pick the
9
9
  * same model — two private copies of this heuristic would drift apart silently.
10
10
  */
11
+ /** Tier shorthands an agent definition may use instead of a concrete model id. */
12
+ const MODEL_TIER_ALIASES = new Set(['haiku', 'sonnet', 'opus'])
13
+
11
14
  export function pickFastestModel(registry: ProviderRegistry): string {
12
15
  const models = registry.listModels?.() ?? []
13
16
  const flash = models.find(
@@ -120,12 +123,31 @@ export class ProviderRegistry implements Llm {
120
123
  return provider.config.models.filter((m) => m.status === 'active')
121
124
  }
122
125
 
126
+ /**
127
+ * `haiku` / `sonnet` / `opus` are **tiers, not ids** — agent definitions
128
+ * (`AgentDefinition.model`) and `--model` spell them that way to mean "the
129
+ * current model of this tier". An exact id always wins, so a provider that
130
+ * really ships a model with that name is unaffected. Otherwise the tier is
131
+ * resolved against the **active provider only**: returning another provider's
132
+ * model would pair an id with a provider that cannot serve it, since the
133
+ * caller passes the resolved id back to the active provider's `chat()`.
134
+ *
135
+ * Within the tier the **last listed** active model wins — provider configs
136
+ * enumerate a family in ascending version order (`…-sonnet-4-6` before
137
+ * `…-sonnet-5`).
138
+ */
123
139
  findModel(modelId: string): ModelInfo | undefined {
124
140
  for (const provider of this.providers.values()) {
125
141
  const model = provider.config.models.find((m) => m.id === modelId)
126
142
  if (model) return model
127
143
  }
128
- return undefined
144
+ if (!MODEL_TIER_ALIASES.has(modelId)) return undefined
145
+ const active = this.providers.get(this.activeProviderId)
146
+ if (!active) return undefined
147
+ const tier = active.config.models.filter(
148
+ (m) => m.status === 'active' && m.id.toLowerCase().includes(`-${modelId}-`),
149
+ )
150
+ return tier.at(-1)
129
151
  }
130
152
 
131
153
  /**
@@ -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
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Environment for git commands **this program runs on its own behalf** (creating
3
+ * a worktree, reading the branch, …) — as opposed to commands the model asked to
4
+ * run in the user's shell.
5
+ *
6
+ * `GIT_NO_REPLACE_OBJECTS=1` makes git ignore `refs/replace/*`. A replace ref
7
+ * rewrites what a commit *appears to be*: `git replace <a> <b>` makes every
8
+ * reader of `<a>` see `<b>`'s tree, so a checkout / `worktree add` produced from
9
+ * that view contains different files than the real object graph. These are local
10
+ * refs that any process in the repository can write, and this program derives no
11
+ * correctness from replaying them — the isolation boundary (`enter-worktree`,
12
+ * workflow agents, `/fork`, the CRSI sandbox) has to be built from true history.
13
+ * `git` itself still accepts the env var as an escape hatch, so nothing here
14
+ * breaks a repository that genuinely relies on replacements in a user's shell.
15
+ */
16
+ export function internalGitEnv(): NodeJS.ProcessEnv {
17
+ return { ...process.env, GIT_NO_REPLACE_OBJECTS: '1' }
18
+ }
@@ -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.23' as const
12
+ export const PACKAGE_VERSION = '0.85.25' as const
13
13
 
14
14
  /** npm install 全局安装命令 */
15
15
  export const NPM_INSTALL_COMMAND = `npm install -g ${PACKAGE_NAME}` as const
@@ -75,7 +75,7 @@ export const COMPANY_SHORT = '华安麦逄科技' as const
75
75
  */
76
76
 
77
77
  /** Slash 命令总数(真源:`getCommandNames().length`,`apps/cli/src/ui/commands.ts`) */
78
- export const SLASH_COMMAND_COUNT = 137 as const
78
+ export const SLASH_COMMAND_COUNT = 138 as const
79
79
 
80
80
  /** 内置提供商总数(真源:`DEFAULT_PROVIDERS.length`,`apps/cli/src/shared/constants.ts`) */
81
81
  export const PROVIDER_COUNT = 12 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 = 4342 as const
93
+ export const TEST_COUNT = 4477 as const
@@ -290,6 +290,27 @@ export function stripControlCharsForDisplay(input: string): string {
290
290
  )
291
291
  }
292
292
 
293
+ /**
294
+ * `String.prototype.slice` counted in UTF-16 code units, made **surrogate-safe**.
295
+ *
296
+ * A cut that lands between the two halves of a surrogate pair leaves a lone
297
+ * surrogate behind. When that string is serialized into a JSONL transcript,
298
+ * `JSON.stringify` emits it as a bare `\uD83D` escape and strict parsers reject
299
+ * the **whole line** (`jq`: "Invalid \uXXXX\uXXXX surrogate pair escape"). In a
300
+ * terminal it renders as U+FFFD.
301
+ *
302
+ * Back off one code unit when the last kept unit is a high surrogate, so the cut
303
+ * never splits a pair. A lone surrogate that was already in the input is left
304
+ * alone — this only removes *newly created* ones.
305
+ */
306
+ export function safeSlice(text: string, max: number): string {
307
+ if (!Number.isFinite(max) || max >= text.length) return text
308
+ if (max <= 0) return ''
309
+ const last = text.charCodeAt(max - 1)
310
+ const end = last >= 0xd800 && last <= 0xdbff ? max - 1 : max
311
+ return text.slice(0, end)
312
+ }
313
+
293
314
  /**
294
315
  * Full command sanitization pipeline for permission checks.
295
316
  * Applies in order:
@@ -46,6 +46,8 @@ export function invalidSkillNameReason(name: string): string | null {
46
46
 
47
47
  export class SkillsLoader implements Skills {
48
48
  private skills = new Map<string, SkillDefinition>()
49
+ /** File each loaded skill came from — so a name collision can name both sides. */
50
+ private sources = new Map<string, string>()
49
51
 
50
52
  loadBuiltin(basePath: string): void {
51
53
  // Load standard skills (*.SKILL.md)
@@ -227,7 +229,7 @@ export class SkillsLoader implements Skills {
227
229
  type,
228
230
  body,
229
231
  tools: data.tools as SkillDefinition['tools'],
230
- hooks: data.hooks as SkillDefinition['hooks'],
232
+ hooks: parseSkillHooks(data.hooks, skillName),
231
233
  prompts: data.prompts as SkillDefinition['prompts'],
232
234
  // NEW: frontmatter fields for fork/auto-trigger support
233
235
  context: data.context as string | undefined,
@@ -237,7 +239,19 @@ export class SkillsLoader implements Skills {
237
239
  requiresBins: data['requires-bins'] as string[] | undefined,
238
240
  }
239
241
 
242
+ // Two files declaring the same name is a silent last-one-wins race: the
243
+ // user edits the shadowed file, reloads, and sees no effect. Say which file
244
+ // won and which one it displaced. Re-loading the **same** path (what
245
+ // `/reload-skills` does, into this same loader) is not a collision.
246
+ const previousSource = this.sources.get(skill.name)
247
+ if (previousSource !== undefined && previousSource !== sourceName) {
248
+ process.stderr.write(
249
+ `⚠️ Skill "${skill.name}" from ${sourceName} replaces the one loaded from ` +
250
+ `${previousSource} — the later file wins; rename one of them.\n`,
251
+ )
252
+ }
240
253
  this.skills.set(skill.name, skill)
254
+ this.sources.set(skill.name, sourceName)
241
255
  } catch {
242
256
  // skip unparseable
243
257
  }
@@ -305,10 +319,48 @@ export class SkillsLoader implements Skills {
305
319
  }
306
320
  }
307
321
 
322
+ /**
323
+ * 只接受**真带 handler** 的技能钩子。
324
+ *
325
+ * YAML 里没有闭包,所以技能 frontmatter 写的 `hooks:` 到这一步只是数据,`handler`
326
+ * 恒为 `undefined`(`as` 断言把类型骗过去了)。原样注册的后果不是「钩子不生效」,
327
+ * 是**每一个工具调用都被拒**:`runHooks` 调 `undefined(ctx)` 抛 TypeError,而
328
+ * PreToolUse 的守卫是 fail-closed —— 引擎把它读成「守卫答不出来」,于是整场会话
329
+ * 的每一次工具调用都返回拒绝。插件路径交进来的钩子带真 handler,照常放行。
330
+ */
331
+ function parseSkillHooks(raw: unknown, skillName: string): SkillDefinition['hooks'] {
332
+ if (!Array.isArray(raw)) return undefined
333
+
334
+ const accepted: SkillDefinition['hooks'] = []
335
+ for (const entry of raw) {
336
+ const handler = (entry as { handler?: unknown } | null)?.handler
337
+ if (typeof handler === 'function') {
338
+ accepted.push({
339
+ ...(entry as object),
340
+ source: skillName,
341
+ } as NonNullable<SkillDefinition['hooks']>[number])
342
+ continue
343
+ }
344
+ process.stderr.write(
345
+ `⚠️ Skill "${skillName}": a hook entry has no handler (frontmatter cannot carry ` +
346
+ `functions) — ignored. Declare the hook in settings.json instead.\n`,
347
+ )
348
+ }
349
+ return accepted.length > 0 ? accepted : undefined
350
+ }
351
+
308
352
  const COMPACT_DESC_MAX_CHARS = 80
309
353
 
310
- /** Compact reminder: collapse a description to a single short line. */
311
- function truncateSkillDescription(desc: string): string {
354
+ /**
355
+ * Collapse a description to a single short line.
356
+ *
357
+ * Used both by the compact system reminder and by the human-facing `/skills`
358
+ * listing: skill descriptions are written for the *model* and are often
359
+ * several paragraphs of instructions. Pasting that into a terminal listing
360
+ * turns three skills into a screenful; the first line + an ellipsis is the
361
+ * honest short form (there is no separate short-description field to read).
362
+ */
363
+ export function truncateSkillDescription(desc: string): string {
312
364
  const firstLine = desc.split('\n')[0]?.trim() ?? ''
313
365
  return firstLine.length > COMPACT_DESC_MAX_CHARS
314
366
  ? firstLine.slice(0, COMPACT_DESC_MAX_CHARS) + '…'
@@ -93,11 +93,18 @@ export const workflowTool: ToolDefinition = {
93
93
  }
94
94
  }
95
95
 
96
- // Build a minimal engine-like interface for runWorkflow
96
+ // Build a minimal engine-like interface for runWorkflow.
97
+ //
98
+ // `runWorkflow` reads four accessors, not two: without `getPermission` /
99
+ // `getLlm` this stub made every Workflow call throw `engine.getPermission is
100
+ // not a function` before the script even started. The cast hid it — the
101
+ // object was asserted to be a QueryEngine, and nothing exercised the call.
97
102
  const engineStub = {
98
103
  getRegistry: () => ctx.registry!,
99
104
  getTools: () => ctx.toolRegistry!,
100
- } as QueryEngine
105
+ getPermission: () => ctx.permissionSystem,
106
+ getLlm: () => ctx.llm,
107
+ } as unknown as QueryEngine
101
108
 
102
109
  try {
103
110
  const { runId, result, cacheHits, cacheMisses } = await runWorkflow(