@miphamai/cli 0.85.44 → 0.85.46

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.
@@ -513,7 +513,12 @@
513
513
  "skills_unavailable": " (技能信息不可用)",
514
514
  "audit_section": "── CLAUDE.md 审计 ──",
515
515
  "audit_clean": " ✓ 未发现可从代码推断的冗余章节",
516
- "audit_found": "将上述章节加入 `prompt-exclude` frontmatter,可停止发送给模型、节省 token。"
516
+ "audit_found": "将上述章节加入 `prompt-exclude` frontmatter,可停止发送给模型、节省 token。",
517
+ "api_section": "── API ──",
518
+ "api_target": " {provider}({model})",
519
+ "api_not_tested": " ⚪ 未测试 — {reason}",
520
+ "api_reachable": " 🟢 可连接 — {detail}",
521
+ "api_unreachable": " 🔴 不可连接 — {detail}"
517
522
  },
518
523
  "skillDoctor": {
519
524
  "title": "── 技能体检 ──",
package/src/mcp/oauth.ts CHANGED
@@ -256,10 +256,27 @@ export class OAuthClient {
256
256
  const fresh = await this.executePkceFlow(config)
257
257
  return fresh.accessToken
258
258
  }
259
- const data = (await response.json()) as {
260
- access_token: string
259
+ let data: {
260
+ access_token?: unknown
261
261
  refresh_token?: string
262
262
  expires_in?: number
263
+ error?: unknown
264
+ }
265
+ try {
266
+ data = (await response.json()) as typeof data
267
+ } catch {
268
+ // A non-JSON body on a 2xx is not a token either.
269
+ data = {}
270
+ }
271
+ // Some providers (Slack is the documented one) answer a dead refresh token
272
+ // with HTTP 200 and `{"error":"invalid_grant"}`. Checking `response.ok`
273
+ // alone saved that object as a token, and every later call failed until the
274
+ // user cleared credentials by hand (CC 2.1.74-007). A refresh is only
275
+ // successful if it actually returned an access token.
276
+ if (typeof data.access_token !== 'string' || data.access_token === '') {
277
+ this.store.delete(serverName)
278
+ const fresh = await this.executePkceFlow(config)
279
+ return fresh.accessToken
263
280
  }
264
281
  this.store.save(serverName, {
265
282
  accessToken: data.access_token,
@@ -29,6 +29,9 @@ const t = createT(bundles['en-US'] || (enUS as TranslationMap), enUS as Translat
29
29
  */
30
30
  export const MCP_SUPPORTED_VERSIONS: readonly string[] = ['2024-11-05']
31
31
 
32
+ /** Upper bound on paged list reads, so a server that always returns a cursor cannot loop forever. */
33
+ const MAX_LIST_PAGES = 100
34
+
32
35
  /**
33
36
  * The revision to offer in `initialize`.
34
37
  *
@@ -130,16 +133,39 @@ export class McpProtocol {
130
133
  return result
131
134
  }
132
135
 
133
- async listTools(): Promise<ToolDefinition[]> {
134
- const result = (await this.transport.sendRequest('tools/list')) as {
135
- tools?: ToolDefinition[]
136
+ /**
137
+ * Read every page of a paged MCP list method.
138
+ *
139
+ * Servers cap a page (commonly 100 entries) and return `nextCursor` for the
140
+ * rest. Sending a single request and dropping the cursor silently hid every
141
+ * tool past page 1 — the server looked healthy and half its tools did not
142
+ * exist (CC 2.1.144-019). The page cap only bounds a server that keeps
143
+ * answering with a fresh cursor; it does not change normal pagination.
144
+ */
145
+ private async listAllPages<T>(method: string, key: string): Promise<T[]> {
146
+ const out: T[] = []
147
+ let cursor: string | undefined
148
+ for (let page = 0; page < MAX_LIST_PAGES; page++) {
149
+ const result = (await this.transport.sendRequest(
150
+ method,
151
+ cursor ? { cursor } : undefined,
152
+ )) as Record<string, unknown> | null
153
+ const items = result?.[key]
154
+ if (Array.isArray(items)) out.push(...(items as T[]))
155
+ const next = result?.nextCursor
156
+ if (typeof next !== 'string' || next === '' || next === cursor) break
157
+ cursor = next
136
158
  }
159
+ return out
160
+ }
161
+
162
+ async listTools(): Promise<ToolDefinition[]> {
163
+ const tools = await this.listAllPages<ToolDefinition>('tools/list', 'tools')
137
164
  // A server (or the host embedding it) may put a `null` or a nameless entry
138
165
  // in `tools`. That shape used to reach `connection.tools.map(t => t.name)`,
139
166
  // throw a TypeError from a background async, and — with our crash handler
140
167
  // installed — take the whole CLI down over one malformed server. Drop
141
168
  // entries that cannot be addressed instead of trusting the payload.
142
- const tools = Array.isArray(result?.tools) ? result.tools : []
143
169
  return tools.filter(
144
170
  (tool): tool is ToolDefinition =>
145
171
  !!tool &&
@@ -169,10 +195,7 @@ export class McpProtocol {
169
195
  if (!this.serverCapabilities.resources) {
170
196
  return []
171
197
  }
172
- const result = (await this.transport.sendRequest('resources/list')) as {
173
- resources: ResourceDefinition[]
174
- }
175
- return result.resources || []
198
+ return this.listAllPages<ResourceDefinition>('resources/list', 'resources')
176
199
  }
177
200
 
178
201
  async readResource(uri: string): Promise<ResourceReadResult> {
@@ -90,6 +90,25 @@ function killProcessTree(proc: ChildProcess): void {
90
90
  }
91
91
  }
92
92
 
93
+ /**
94
+ * The request id a response line answers, if any.
95
+ *
96
+ * Our requests carry **numeric** ids, but a server is free to stringify them on
97
+ * the way back (`"id": "7"`). That response used to match nothing, so the
98
+ * request stayed pending until the full request timeout — a malformed reply
99
+ * that reads as a slow server. Numeric-string ids are the one spelling we can
100
+ * map back safely; anything else (a non-numeric string, `null`, an object) names
101
+ * a request we never sent and must not settle someone else's promise.
102
+ */
103
+ function matchResponseId(value: unknown): number | null {
104
+ if (typeof value === 'number' && Number.isInteger(value)) return value
105
+ if (typeof value === 'string' && /^\d+$/.test(value)) {
106
+ const id = Number(value)
107
+ return Number.isSafeInteger(id) ? id : null
108
+ }
109
+ return null
110
+ }
111
+
93
112
  /** Every descendant of `root`, parents before children. */
94
113
  function descendantPids(root: number): number[] {
95
114
  let listing: string
@@ -146,6 +165,10 @@ const SENSITIVE_ENV_PATTERNS = [
146
165
  /^GCLOUD_/, // GCP credentials
147
166
  /^AZURE_/, // Azure credentials
148
167
  /^DOCKER_/, // DOCKER_TOKEN, DOCKER_PASSWORD
168
+ // OTLP endpoint headers carry an ingestion token, and the endpoint itself is
169
+ // the operator's telemetry destination. A subprocess inheriting `OTEL_*`
170
+ // exports its own spans to it (CC 2.1.128-006).
171
+ /^OTEL_/,
149
172
  ]
150
173
 
151
174
  /**
@@ -232,12 +255,13 @@ export class StdioTransport implements Transport {
232
255
  const msg = JSON.parse(trimmed)
233
256
 
234
257
  // Check if it's a response (has id and result/error)
235
- if (typeof msg.id === 'number' && ('result' in msg || 'error' in msg)) {
236
- const response = msg as JsonRpcResponse
237
- const entry = this.pending.get(response.id)
258
+ const responseId = matchResponseId(msg.id)
259
+ if (responseId !== null && ('result' in msg || 'error' in msg)) {
260
+ const entry = this.pending.get(responseId)
238
261
  if (entry) {
239
262
  clearTimeout(entry.timer)
240
- this.pending.delete(response.id)
263
+ this.pending.delete(responseId)
264
+ const response = msg as JsonRpcResponse
241
265
  if (response.error) {
242
266
  entry.reject(
243
267
  new Error(`MCP error ${response.error.code}: ${response.error.message}`),
@@ -5,7 +5,8 @@ import type {
5
5
  StreamChunk,
6
6
  ContentBlock,
7
7
  } from '../shared/index.ts'
8
- import type { ProviderInstance, ChatRequest } from './registry'
8
+ import type { ProviderInstance, ChatRequest, ConnectivityProbe } from './registry'
9
+ import { UNNAMED_TOOL_CALL } from '../shared/constants'
9
10
  import {
10
11
  fetchWithRetry,
11
12
  streamIdleTimeoutMs,
@@ -326,7 +327,12 @@ export class AnthropicProvider implements ProviderInstance {
326
327
  // tool_calls 落在同一个响应体里)。**这是有意的不对称,不是漏做**:
327
328
  // 要在这里丢弃,就得把 `tool_use` 缓冲到 `message_stop` 再发 ——
328
329
  // 那是一次行为变更,不属本次范围。
329
- if (currentToolId && currentToolName && accumulatedToolInput) {
330
+ // A named call needs accumulated input (the old shape). A *nameless*
331
+ // block is malformed on its own, so it is emitted regardless of
332
+ // whether any input arrived: dropping it left the turn as a silent
333
+ // short answer with nothing for the model to correct (331-038).
334
+ const nameless = !!currentToolId && !currentToolName
335
+ if ((currentToolId && currentToolName && accumulatedToolInput) || nameless) {
330
336
  // A replayed block carries the id it was first sent with, so the
331
337
  // id is what tells a second call apart from the same call twice.
332
338
  if (!emittedToolIds.has(currentToolId)) {
@@ -334,7 +340,7 @@ export class AnthropicProvider implements ProviderInstance {
334
340
 
335
341
  let parsedInput: Record<string, unknown> = {}
336
342
  try {
337
- parsedInput = JSON.parse(accumulatedToolInput)
343
+ parsedInput = accumulatedToolInput ? JSON.parse(accumulatedToolInput) : {}
338
344
  } catch (err) {
339
345
  // Same tag as the OpenAI-compatible path: a bare fragment
340
346
  // reaches the validator as "missing required parameter",
@@ -350,7 +356,7 @@ export class AnthropicProvider implements ProviderInstance {
350
356
  toolUse: {
351
357
  type: 'tool_use',
352
358
  id: currentToolId,
353
- name: currentToolName,
359
+ name: currentToolName || UNNAMED_TOOL_CALL,
354
360
  input: parsedInput,
355
361
  },
356
362
  }
@@ -446,6 +452,44 @@ export class AnthropicProvider implements ProviderInstance {
446
452
  return apiKey.length > 0 && apiKey.startsWith('sk-ant-')
447
453
  }
448
454
 
455
+ /**
456
+ * Detailed reachability for `/doctor` (331-003).
457
+ *
458
+ * `healthCheck` above only inspects the key's shape — it never touches the
459
+ * network, so the "reachable" it backs is really "configured". This probe
460
+ * asks the API: any HTTP answer (200, 401, 404) proves the endpoint is there,
461
+ * and the status tells the user which problem they have.
462
+ */
463
+ async probeConnectivity(): Promise<ConnectivityProbe> {
464
+ const apiKey = this.resolveApiKey(this.config.apiKey)
465
+ if (!apiKey) return { tested: false, ok: false, detail: 'no API key configured' }
466
+ const url = `${this.baseUrl}/models`
467
+ try {
468
+ const res = await fetchWithRetry(
469
+ url,
470
+ {
471
+ headers: {
472
+ 'x-api-key': apiKey,
473
+ 'anthropic-version': '2023-06-01',
474
+ },
475
+ },
476
+ { timeout: 5000, maxRetries: 0 },
477
+ )
478
+ try {
479
+ await res.body?.cancel()
480
+ } catch {
481
+ /* body already gone */
482
+ }
483
+ return { tested: true, ok: true, detail: `HTTP ${res.status} from ${url}` }
484
+ } catch (err) {
485
+ return {
486
+ tested: true,
487
+ ok: false,
488
+ detail: `${err instanceof Error ? err.message : String(err)} (${url})`,
489
+ }
490
+ }
491
+ }
492
+
449
493
  /**
450
494
  * Mark the stable conversation prefix for prompt caching. The breakpoint is
451
495
  * placed on the last block of the second-to-last message, leaving only the
@@ -1,6 +1,6 @@
1
1
  import { execSync } from 'node:child_process'
2
2
  import type { ProviderConfig, ModelInfo, Message, StreamChunk } from '../shared/index.ts'
3
- import type { ProviderInstance, ChatRequest } from './registry'
3
+ import type { ProviderInstance, ChatRequest, ConnectivityProbe } from './registry'
4
4
  import {
5
5
  fetchWithRetry,
6
6
  streamIdleTimeoutMs,
@@ -8,7 +8,7 @@ import {
8
8
  createAwakeTimer,
9
9
  readErrorBody,
10
10
  } from './fetch-utils'
11
- import { OLLAMA_PRESET_MODELS } from '../shared/constants'
11
+ import { OLLAMA_PRESET_MODELS, UNNAMED_TOOL_CALL } from '../shared/constants'
12
12
  import { toWellFormed } from '../shared/sanitize'
13
13
 
14
14
  /**
@@ -160,14 +160,17 @@ export class OpenAICompatProvider implements ProviderInstance {
160
160
  const data = trimmed.slice(6)
161
161
  if (data === '[DONE]') {
162
162
  // Emit any pending tool calls before stopping
163
- for (const [, tc] of pendingToolCalls) {
164
- if (!tc.name) continue // drop malformed tool call (missing name)
163
+ for (const [idx, tc] of pendingToolCalls) {
164
+ // A nameless call is still a call the model wrote. Dropping it made
165
+ // the turn end as a short answer with no explanation; the synthetic
166
+ // name reaches the engine's unknown-tool path, which returns an
167
+ // error result the model can act on (331-038).
165
168
  yield {
166
169
  type: 'tool_use',
167
170
  toolUse: {
168
171
  type: 'tool_use',
169
- id: tc.id || `call_${Date.now()}`,
170
- name: tc.name,
172
+ id: tc.id || `call_${Date.now()}_${idx}`,
173
+ name: tc.name || UNNAMED_TOOL_CALL,
171
174
  input: this.safeParseJson(tc.arguments),
172
175
  },
173
176
  }
@@ -242,14 +245,15 @@ export class OpenAICompatProvider implements ProviderInstance {
242
245
 
243
246
  if (choice.finish_reason === 'tool_calls') {
244
247
  // Emit fully accumulated tool calls
245
- for (const [, tc] of pendingToolCalls) {
246
- if (!tc.name) continue // drop malformed tool call (missing name)
248
+ for (const [idx, tc] of pendingToolCalls) {
249
+ // Same treatment as the `[DONE]` path above: a nameless call gets
250
+ // the synthetic name instead of being dropped on the floor.
247
251
  yield {
248
252
  type: 'tool_use',
249
253
  toolUse: {
250
254
  type: 'tool_use',
251
- id: tc.id || `call_${Date.now()}`,
252
- name: tc.name,
255
+ id: tc.id || `call_${Date.now()}_${idx}`,
256
+ name: tc.name || UNNAMED_TOOL_CALL,
253
257
  input: this.safeParseJson(tc.arguments),
254
258
  },
255
259
  }
@@ -340,16 +344,9 @@ export class OpenAICompatProvider implements ProviderInstance {
340
344
 
341
345
  async healthCheck(): Promise<boolean> {
342
346
  try {
343
- const rawBase = (this.config as any).baseUrl || (this.config as any).baseURL
344
- const baseUrl =
345
- this.resolveEnvTemplate(
346
- rawBase?.replace(/\/+$/, '') || '',
347
- 'OpenAI-compatible provider: baseUrl',
348
- ) || 'https://api.openai.com/v1'
349
- const apiKey = this.resolveApiKey(this.config.apiKey)
350
- // 5s timeout so a down endpoint doesn't hang health checks (v2.1.229 alignment)
347
+ const { url, apiKey } = this.modelsEndpoint()
351
348
  const res = await fetchWithRetry(
352
- `${baseUrl}/models`,
349
+ url,
353
350
  { headers: { Authorization: `Bearer ${apiKey}` } },
354
351
  { timeout: 5000, maxRetries: 0 },
355
352
  )
@@ -359,6 +356,48 @@ export class OpenAICompatProvider implements ProviderInstance {
359
356
  }
360
357
  }
361
358
 
359
+ /**
360
+ * Detailed reachability for `/doctor`. Unlike `healthCheck`, any HTTP answer
361
+ * counts as reachable: a 401 from a live endpoint means "the endpoint is
362
+ * here and refused this key", which is a different problem from "nothing
363
+ * answered".
364
+ */
365
+ async probeConnectivity(): Promise<ConnectivityProbe> {
366
+ const { url, apiKey } = this.modelsEndpoint()
367
+ if (!apiKey) return { tested: false, ok: false, detail: 'no API key configured' }
368
+ try {
369
+ // 5s timeout so a down endpoint doesn't hang the doctor screen.
370
+ const res = await fetchWithRetry(
371
+ url,
372
+ { headers: { Authorization: `Bearer ${apiKey}` } },
373
+ { timeout: 5000, maxRetries: 0 },
374
+ )
375
+ try {
376
+ await res.body?.cancel()
377
+ } catch {
378
+ /* body already gone */
379
+ }
380
+ return { tested: true, ok: true, detail: `HTTP ${res.status} from ${url}` }
381
+ } catch (err) {
382
+ return {
383
+ tested: true,
384
+ ok: false,
385
+ detail: `${err instanceof Error ? err.message : String(err)} (${url})`,
386
+ }
387
+ }
388
+ }
389
+
390
+ /** `/models` on the configured base — the one endpoint both checks share. */
391
+ private modelsEndpoint(): { url: string; apiKey: string } {
392
+ const rawBase = (this.config as any).baseUrl || (this.config as any).baseURL
393
+ const baseUrl =
394
+ this.resolveEnvTemplate(
395
+ rawBase?.replace(/\/+$/, '') || '',
396
+ 'OpenAI-compatible provider: baseUrl',
397
+ ) || 'https://api.openai.com/v1'
398
+ return { url: `${baseUrl}/models`, apiKey: this.resolveApiKey(this.config.apiKey) }
399
+ }
400
+
362
401
  private convertMessages(messages: Message[], systemPrompt?: string): Record<string, unknown>[] {
363
402
  const result: Record<string, unknown>[] = []
364
403
 
@@ -43,11 +43,27 @@ export function resolveClassifierModel(
43
43
  return choice
44
44
  }
45
45
 
46
+ /**
47
+ * Detail behind a reachability check, for `/doctor` (331-003).
48
+ *
49
+ * `healthCheck` answers a boolean the status line consumes; it cannot say *what*
50
+ * happened. This shape can: `tested: false` means the check was skipped and
51
+ * `detail` is the reason (no key, no endpoint), never a silent "unreachable".
52
+ */
53
+ export interface ConnectivityProbe {
54
+ tested: boolean
55
+ /** Reachability, not authentication: any HTTP response means the endpoint answered. */
56
+ ok: boolean
57
+ detail: string
58
+ }
59
+
46
60
  export interface ProviderInstance {
47
61
  config: ProviderConfig
48
62
  chat(req: ChatRequest): AsyncGenerator<StreamChunk>
49
63
  listModels(): Promise<ModelInfo[]>
50
64
  healthCheck(): Promise<boolean>
65
+ /** Optional detailed probe; `healthCheck` remains the only required contract. */
66
+ probeConnectivity?(): Promise<ConnectivityProbe>
51
67
  }
52
68
 
53
69
  export interface ChatRequest {
@@ -164,6 +180,31 @@ export class ProviderRegistry implements Llm {
164
180
  }
165
181
  }
166
182
 
183
+ /**
184
+ * Detailed reachability for `/doctor`. Falls back to the boolean health check
185
+ * when a provider has no probe, and says so — "reachable" with no detail is
186
+ * still information; "unreachable" invented from a missing method is not.
187
+ */
188
+ async probeConnectivity(id: string): Promise<ConnectivityProbe | undefined> {
189
+ const provider = this.providers.get(id)
190
+ if (!provider) return undefined
191
+ if (provider.probeConnectivity) {
192
+ try {
193
+ return await provider.probeConnectivity()
194
+ } catch (err) {
195
+ return {
196
+ tested: true,
197
+ ok: false,
198
+ detail: err instanceof Error ? err.message : String(err),
199
+ }
200
+ }
201
+ }
202
+ const ok = await this.healthStatus(id)
203
+ return ok === undefined
204
+ ? undefined
205
+ : { tested: false, ok, detail: 'this provider has no detailed probe' }
206
+ }
207
+
167
208
  /**
168
209
  * Health of all registered providers, checked concurrently.
169
210
  * Returns a Map of provider id → reachable boolean.
@@ -1,6 +1,17 @@
1
1
  import type { ProviderConfig, ModelInfo } from './types'
2
2
  import miphamModelsSnapshot from './mipham-models.json' with { type: 'json' }
3
3
 
4
+ /**
5
+ * Synthetic tool name for a provider response that carried a tool call with no
6
+ * name (a custom endpoint, or a malformed stream).
7
+ *
8
+ * Dropping such a call silently left the turn looking like a short answer: the
9
+ * model wrote a call, nothing dispatched, and the user got no explanation. Give
10
+ * it a name so the ordinary "Unknown tool" path hands the model an error result
11
+ * it can correct on the next round — the turn continues instead of vanishing.
12
+ */
13
+ export const UNNAMED_TOOL_CALL = '(tool call without a name)'
14
+
4
15
  // Build MiphamAI provider from synced model definitions.
5
16
  // Source of truth: Engine GET /v1/mipham-models → packages/shared/src/mipham-models.json
6
17
  // Run `bun run scripts/sync-mipham-models.ts` to update from Engine.
@@ -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.44' as const
12
+ export const PACKAGE_VERSION = '0.85.46' 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 = 140 as const
78
+ export const SLASH_COMMAND_COUNT = 141 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 = 5171 as const
93
+ export const TEST_COUNT = 5228 as const
@@ -311,6 +311,23 @@ export function safeSlice(text: string, max: number): string {
311
311
  return text.slice(0, end)
312
312
  }
313
313
 
314
+ /**
315
+ * `safeSlice` for **display only** — appends `…` when it actually cut something.
316
+ *
317
+ * A bare `safeSlice` at a render site leaves a long tool result looking like the
318
+ * whole output: the reader has no way to tell "the tool said this" from "the
319
+ * tool said more and we stopped". Never use this where the string is stored or
320
+ * sent (session JSONL, tool arguments, prompts) — the ellipsis would become part
321
+ * of the data. `safeSlice` remains the right call there.
322
+ */
323
+ export function safeSliceWithEllipsis(text: string, max: number): string {
324
+ const clipped = safeSlice(text, max)
325
+ // `max <= 0` means "show nothing", not "show an ellipsis" — and an empty input
326
+ // cannot have been cut.
327
+ if (max <= 0 || clipped === text) return clipped
328
+ return `${clipped}…`
329
+ }
330
+
314
331
  /**
315
332
  * Replace lone UTF-16 surrogates with U+FFFD, leaving valid pairs untouched.
316
333
  *
@@ -706,6 +706,15 @@ export interface ToolContext {
706
706
  * consume a background handle, so its default flips to synchronous.
707
707
  */
708
708
  isSubAgent?: boolean
709
+ /**
710
+ * How many `Agent` calls deep this tool context is (main loop = 0 / absent).
711
+ *
712
+ * A sub-agent's tool set includes `Agent`, so nesting is reachable from the
713
+ * model. The Agent tool refuses past `MAX_AGENT_DEPTH`; this field is what it
714
+ * counts. Incremented by `SubAgent.runExecution` when it builds its children's
715
+ * context, so a foreground chain is bounded exactly like a background one.
716
+ */
717
+ agentDepth?: number
709
718
  /**
710
719
  * The session a sub-agent is running on behalf of.
711
720
  *
@@ -20,10 +20,49 @@ export function parseFrontmatter(raw: string): FrontmatterResult {
20
20
  if (!match) {
21
21
  return { data: {}, content: src }
22
22
  }
23
- return {
24
- data: parseYaml(match[1] || '') as Record<string, unknown>,
25
- content: match[2] || '',
23
+ // A plain scalar containing ": " (`description: Fix: a bug`) is invalid YAML:
24
+ // the parser sees a second mapping colon. Strict parsing threw, the per-file
25
+ // catch swallowed it, and the skill disappeared with no message. Frontmatter
26
+ // is hand-written, so recover the top-level scalar keys line by line instead
27
+ // of losing the whole file.
28
+ let data: Record<string, unknown>
29
+ try {
30
+ const parsed = parseYaml(match[1] || '')
31
+ data =
32
+ parsed && typeof parsed === 'object' && !Array.isArray(parsed)
33
+ ? (parsed as Record<string, unknown>)
34
+ : {}
35
+ } catch {
36
+ data = parseLooseFrontmatter(match[1] || '')
26
37
  }
38
+ return { data, content: match[2] || '' }
39
+ }
40
+
41
+ /**
42
+ * Last-resort reader for frontmatter that strict YAML rejects.
43
+ *
44
+ * Only top-level `key: scalar` pairs are recovered — nested maps and block
45
+ * lists are lost. That is already better than dropping the skill, and it is
46
+ * limited to files that would otherwise fail entirely.
47
+ */
48
+ function parseLooseFrontmatter(text: string): Record<string, unknown> {
49
+ const out: Record<string, unknown> = {}
50
+ for (const line of text.split('\n')) {
51
+ const m = line.match(/^([A-Za-z0-9_-]+):\s*(.*)$/)
52
+ if (!m) continue
53
+ let value = m[2]!.trim()
54
+ if (!value) continue
55
+ // Block scalars / flow collections are not recoverable this way.
56
+ if (/^[|>[{&*!]/.test(value)) continue
57
+ if (
58
+ (value.startsWith('"') && value.endsWith('"') && value.length >= 2) ||
59
+ (value.startsWith("'") && value.endsWith("'") && value.length >= 2)
60
+ ) {
61
+ value = value.slice(1, -1)
62
+ }
63
+ out[m[1]!] = value
64
+ }
65
+ return out
27
66
  }
28
67
 
29
68
  /**
@@ -195,7 +234,30 @@ export class SkillsLoader implements Skills {
195
234
  try {
196
235
  const { data, content } = parseFrontmatter(raw)
197
236
 
198
- const rawDescription = (data.description as string) || ''
237
+ // `description: [a, b]` (a YAML list) is a legal frontmatter value but not
238
+ // a string. Casting it and letting `sanitizeSkillDescription` call
239
+ // `.replace` on it threw inside the per-file try/catch, which swallowed the
240
+ // error — the skill vanished with no message. Only a string counts; say so
241
+ // instead of dropping it silently.
242
+ // `description: 3000` is a bare number; coerce it rather than dropping what
243
+ // the author wrote (CC 2.1.47-028). A list/object cannot be a description.
244
+ const descriptionValue = data.description
245
+ const rawDescription =
246
+ typeof descriptionValue === 'string'
247
+ ? descriptionValue
248
+ : typeof descriptionValue === 'number' || typeof descriptionValue === 'boolean'
249
+ ? String(descriptionValue)
250
+ : ''
251
+ if (
252
+ descriptionValue !== undefined &&
253
+ typeof descriptionValue !== 'string' &&
254
+ typeof descriptionValue !== 'number' &&
255
+ typeof descriptionValue !== 'boolean'
256
+ ) {
257
+ process.stderr.write(
258
+ `⚠️ Skill at ${sourceName}: frontmatter description is not a string — ignored.\n`,
259
+ )
260
+ }
199
261
  const rawBody = content.trim() || undefined
200
262
 
201
263
  // Name gate (see `invalidSkillNameReason`). A declared name that fails is
@@ -282,8 +344,14 @@ export class SkillsLoader implements Skills {
282
344
  }
283
345
  this.skills.set(skill.name, skill)
284
346
  this.sources.set(skill.name, sourceName)
285
- } catch {
286
- // skip unparseable
347
+ } catch (err) {
348
+ // Never drop a skill silently: to the user a skill that vanished and a
349
+ // skill that was never installed look identical, and the frontmatter is
350
+ // hand-written (CC 2.1.69-068 / 2.1.47-028).
351
+ const detail = err instanceof Error ? err.message : String(err)
352
+ process.stderr.write(
353
+ `⚠️ Skill at ${sourceName}: could not be loaded — skipped (${detail.split('\n')[0]})\n`,
354
+ )
287
355
  }
288
356
  }
289
357
 
@@ -24,6 +24,9 @@ const VALID_EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max']
24
24
  * honoured, in both directions: that is a request, not a default chosen on the
25
25
  * caller's behalf.
26
26
  */
27
+ /** Deepest nesting of `Agent` calls (CC parity: 5). */
28
+ export const MAX_AGENT_DEPTH = 5
29
+
27
30
  export function resolveRunInBackground(
28
31
  runInBackground: boolean | undefined,
29
32
  agentDef?: { background?: boolean },
@@ -85,6 +88,21 @@ export const agentTool: ToolDefinition = {
85
88
  const prompt = params.prompt as string
86
89
  const agentType = (params.subagent_type as SubAgentType) || 'general'
87
90
 
91
+ // A sub-agent's tool set includes `Agent`, so a model can nest calls. Without
92
+ // a depth bound one run could spawn children that spawn children until the
93
+ // token budget or the process dies (CC 2.1.181-019). Background sub-agents
94
+ // already had a limit; this applies the same one to foreground runs.
95
+ const depth = ctx.agentDepth ?? 0
96
+ if (depth >= MAX_AGENT_DEPTH) {
97
+ return {
98
+ success: false,
99
+ content: '',
100
+ error:
101
+ `Sub-agent nesting limit reached (${MAX_AGENT_DEPTH} levels). ` +
102
+ "Finish this level's work directly instead of spawning another agent.",
103
+ }
104
+ }
105
+
88
106
  if (!VALID_TYPES.includes(agentType)) {
89
107
  return {
90
108
  success: false,