@miphamai/cli 0.85.32 → 0.85.34

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 (53) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/src/agent/services.ts +21 -0
  4. package/src/agent/sub-agent.ts +129 -21
  5. package/src/commands/environment.ts +14 -11
  6. package/src/commands/project.ts +43 -12
  7. package/src/config/loader.ts +65 -35
  8. package/src/core/alignment-vocabulary.json +2 -2
  9. package/src/core/constitution-loader.ts +85 -24
  10. package/src/core/credential-masker/env-filter.ts +37 -0
  11. package/src/core/engine.ts +59 -140
  12. package/src/core/permission-rules.ts +163 -14
  13. package/src/core/permission.ts +14 -1
  14. package/src/core/session-log.ts +11 -0
  15. package/src/core/session-store.ts +4 -3
  16. package/src/core/tool-gate.ts +222 -0
  17. package/src/core/workspace-trust.ts +50 -17
  18. package/src/daemon/remote-engine.ts +3 -0
  19. package/src/i18n-core/locales/en-US.json +1 -0
  20. package/src/i18n-core/locales/zh-CN.json +1 -0
  21. package/src/index.tsx +6 -0
  22. package/src/mcp/client.ts +22 -2
  23. package/src/mcp/protocol.ts +16 -2
  24. package/src/plugin/plugin-manager.ts +29 -3
  25. package/src/providers/fetch-utils.ts +49 -0
  26. package/src/providers/openai-compat.ts +28 -2
  27. package/src/shared/git-env.ts +37 -13
  28. package/src/shared/package-info.ts +2 -2
  29. package/src/shared/sanitize.ts +17 -0
  30. package/src/shared/types.ts +8 -0
  31. package/src/skills/fork-executor.ts +11 -1
  32. package/src/skills/marketplace.ts +44 -13
  33. package/src/skills/registry.ts +12 -1
  34. package/src/tools/agent/agent.ts +3 -0
  35. package/src/tools/agent/enter-plan.ts +22 -4
  36. package/src/tools/agent/exit-plan.ts +9 -1
  37. package/src/tools/agent/skill.ts +1 -0
  38. package/src/tools/agent/workflow.ts +1 -0
  39. package/src/tools/computer/browser.ts +13 -0
  40. package/src/tools/exec/git.ts +113 -69
  41. package/src/tools/file/edit.ts +19 -3
  42. package/src/tools/file/grep.ts +5 -1
  43. package/src/tools/file/write.ts +18 -1
  44. package/src/tools/index.ts +2 -2
  45. package/src/tools/network/web-fetch.ts +12 -0
  46. package/src/tools/system/tool-search.ts +35 -3
  47. package/src/ui/app.tsx +105 -4
  48. package/src/ui/chat.tsx +21 -7
  49. package/src/ui/commands.ts +127 -18
  50. package/src/workflow/primitives/agent.ts +12 -1
  51. package/src/workflow/primitives/loop.ts +14 -0
  52. package/src/workflow/primitives/verify.ts +13 -1
  53. package/src/workflow/runtime.ts +1 -0
package/src/index.tsx CHANGED
@@ -879,6 +879,12 @@ export async function runApp(options: RunOptions): Promise<void> {
879
879
  process.stderr.write(`⚠ Mipham Code: ${msg}\n`)
880
880
  }
881
881
 
882
+ // Valid-but-doesn't-mean-what-it-says: a `*` in a variable's value in an
883
+ // allow rule (`Bash(PORT=* npm run dev)`) grants every value.
884
+ for (const msg of engine.getPermission().getRuleWarnings()) {
885
+ process.stderr.write(`⚠ Mipham Code: ${msg}\n`)
886
+ }
887
+
882
888
  // Same warning channel for malformed restrictions (P1) — a typo'd
883
889
  // `forbiddenModes`/`maxAllowedMode` used to leave the policy silently inert.
884
890
  for (const msg of engine.getPermission().getInvalidRestrictions()) {
package/src/mcp/client.ts CHANGED
@@ -171,6 +171,16 @@ export class McpClient {
171
171
  private reconnecting = new Set<string>()
172
172
  /** Set by `closeAll` so a teardown is never undone by an in-flight reconnect. */
173
173
  private closing = false
174
+ /**
175
+ * Per-server teardown, same guarantee as `closing` but for one name.
176
+ *
177
+ * `disconnect()` deletes the connection, but a reconnect loop already asleep
178
+ * in its backoff holds the old config and would call `connect()` again on the
179
+ * next tick — the server comes back after the user (or a plugin reload)
180
+ * removed it. An explicit `connect()` clears the mark, so `/mcp connect` and
181
+ * a fresh plugin load still work.
182
+ */
183
+ private tornDown = new Set<string>()
174
184
 
175
185
  private get tokenStore(): TokenStore {
176
186
  if (!this._tokenStore) this._tokenStore = new TokenStore()
@@ -332,7 +342,7 @@ export class McpClient {
332
342
  const maxAttempts = 10
333
343
 
334
344
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
335
- if (this.closing) return
345
+ if (this.closing || this.tornDown.has(name)) return
336
346
  try {
337
347
  try {
338
348
  await connection.transport.close()
@@ -380,7 +390,7 @@ export class McpClient {
380
390
  * unhandled rejection.
381
391
  */
382
392
  private scheduleAutoReconnect(name: string): void {
383
- if (!this.autoReconnect || this.closing) return
393
+ if (!this.autoReconnect || this.closing || this.tornDown.has(name)) return
384
394
  if (this.reconnecting.has(name)) return
385
395
  this.reconnecting.add(name)
386
396
  void this.reconnect(name)
@@ -420,6 +430,12 @@ export class McpClient {
420
430
  }
421
431
 
422
432
  async connect(config: McpServerConfig): Promise<void> {
433
+ // An explicit attempt — startup, `/mcp connect`, a plugin load — is what
434
+ // makes a previously torn-down name eligible again. The reconnect loop's
435
+ // own checks happen per attempt, before this call, so clearing here does
436
+ // not undo a teardown that lands mid-backoff.
437
+ this.tornDown.delete(config.name)
438
+
423
439
  // Skip if already connected
424
440
  const existing = this.connections.get(config.name)
425
441
  if (existing?.status === 'connected') return
@@ -596,6 +612,10 @@ export class McpClient {
596
612
  * so the caller can unregister them from the central tool registry.
597
613
  */
598
614
  disconnect(name: string): string[] {
615
+ // Marked before the lookup: a server between reconnect attempts has no
616
+ // entry in `connections`, and that is exactly the state in which an
617
+ // unmarked teardown gets undone by the sleeping loop.
618
+ this.tornDown.add(name)
599
619
  const conn = this.connections.get(name)
600
620
  if (!conn) return []
601
621
 
@@ -131,8 +131,22 @@ export class McpProtocol {
131
131
  }
132
132
 
133
133
  async listTools(): Promise<ToolDefinition[]> {
134
- const result = (await this.transport.sendRequest('tools/list')) as { tools: ToolDefinition[] }
135
- return result.tools || []
134
+ const result = (await this.transport.sendRequest('tools/list')) as {
135
+ tools?: ToolDefinition[]
136
+ }
137
+ // A server (or the host embedding it) may put a `null` or a nameless entry
138
+ // in `tools`. That shape used to reach `connection.tools.map(t => t.name)`,
139
+ // throw a TypeError from a background async, and — with our crash handler
140
+ // installed — take the whole CLI down over one malformed server. Drop
141
+ // entries that cannot be addressed instead of trusting the payload.
142
+ const tools = Array.isArray(result?.tools) ? result.tools : []
143
+ return tools.filter(
144
+ (tool): tool is ToolDefinition =>
145
+ !!tool &&
146
+ typeof tool === 'object' &&
147
+ typeof (tool as { name?: unknown }).name === 'string' &&
148
+ (tool as { name: string }).name.length > 0,
149
+ )
136
150
  }
137
151
 
138
152
  async callTool(
@@ -8,13 +8,25 @@ import {
8
8
  renameSync,
9
9
  } from 'node:fs'
10
10
  import { join } from 'node:path'
11
- import { execFileSync } from 'node:child_process'
11
+ import { spawnSync } from 'node:child_process'
12
12
  import { validatePlugin } from './plugin-validator'
13
13
  import { atomicWriteFileSync } from '../shared/atomic-write'
14
14
  import { miphamHome } from '../core/paths.ts'
15
15
 
16
16
  const PLUGIN_DIR = miphamHome('plugins')
17
17
 
18
+ /**
19
+ * Shown with every successful install.
20
+ *
21
+ * A plugin is not a passive configuration file: its hooks, MCP servers and
22
+ * skills run as this user, with the same file and shell access. The install
23
+ * receipt is the last moment before that becomes true, and it is the only
24
+ * place the operator is guaranteed to look — a warning in documentation is
25
+ * read by people who already know.
26
+ */
27
+ const PLUGIN_TRUST_NOTE =
28
+ 'Plugins can run code on this computer, with access to your files and shell — install only from sources you trust.'
29
+
18
30
  /**
19
31
  * Render validation warnings for the install result.
20
32
  *
@@ -95,6 +107,7 @@ export class PluginManager {
95
107
  success: true,
96
108
  message:
97
109
  `Plugin "${validation.manifest.name}" v${validation.manifest.version} installed` +
110
+ `\n${PLUGIN_TRUST_NOTE}` +
98
111
  (similarWarning ? `\n⚠ ${similarWarning}` : '') +
99
112
  warningsBlock(validation.warnings),
100
113
  }
@@ -143,7 +156,7 @@ export class PluginManager {
143
156
  // preinstall/install/postinstall hooks as the current user — arbitrary
144
157
  // code execution from any npm package, reachable via `/install-plugin`.
145
158
  // A plugin only needs to *be* files on disk; it never needs a build step
146
- // of its own to be loaded from here. `execFileSync` (argv array, no
159
+ // of its own to be loaded from here. `spawnSync` (argv array, no
147
160
  // shell) keeps the command line independent of packageName, so package
148
161
  // name validation is not the only thing standing between us and a shell.
149
162
  //
@@ -155,7 +168,12 @@ export class PluginManager {
155
168
  // resolver. The value is the npm default already declared in this repo's
156
169
  // registry chain (`src/shared/update.ts`), not a new literal. The flag is
157
170
  // honoured over npm config because command-line flags outrank it.
158
- execFileSync(
171
+ // `spawnSync`, not `execFileSync`: the latter returns stdout only, so
172
+ // whatever npm wrote to stderr on a *successful* install (deprecation
173
+ // notices, funding warnings — the messages that explain what the user got)
174
+ // was discarded. Non-zero exit keeps the old failure shape: the stderr is
175
+ // the error message.
176
+ const npm = spawnSync(
159
177
  'npm',
160
178
  [
161
179
  'install',
@@ -173,6 +191,12 @@ export class PluginManager {
173
191
  timeout: 60_000,
174
192
  },
175
193
  )
194
+ if (npm.error) throw npm.error
195
+ if (npm.status !== 0) {
196
+ const detail = (npm.stderr || npm.stdout || '').trim()
197
+ throw new Error(detail || `npm exited with status ${npm.status}`)
198
+ }
199
+ const npmNote = (npm.stderr || '').trim()
176
200
 
177
201
  // npm installs the package into <stagingDir>/node_modules/<packageName>/ —
178
202
  // validate there, then flatten it to the plugin dir root so its layout
@@ -215,6 +239,8 @@ export class PluginManager {
215
239
  success: true,
216
240
  message:
217
241
  `Plugin "${manifestName}" installed from npm` +
242
+ `\n${PLUGIN_TRUST_NOTE}` +
243
+ (npmNote ? `\n${npmNote}` : '') +
218
244
  (similarWarning ? `\n⚠ ${similarWarning}` : '') +
219
245
  warningsBlock(validation.warnings),
220
246
  }
@@ -73,8 +73,44 @@ export function retryDelayMs(
73
73
  return Math.min(Math.max(requested, RETRY_AFTER_MIN_MS), RETRY_AFTER_MAX_MS)
74
74
  }
75
75
 
76
+ /**
77
+ * TLS failures a retry cannot fix.
78
+ *
79
+ * A certificate that has expired, or names another host, fails identically on
80
+ * every attempt — re-sending only delays the explanation the first handshake
81
+ * already gave. Matched on the `code` of the thrown error *and its `cause`
82
+ * chain*: Node's undici throws a bare `TypeError: fetch failed` and hides the
83
+ * OpenSSL verdict one level down, so a check that only looked at the top-level
84
+ * error would classify every certificate failure as transient.
85
+ */
86
+ const NON_RETRYABLE_TLS_CODES = new Set([
87
+ 'DEPTH_ZERO_SELF_SIGNED_CERT',
88
+ 'SELF_SIGNED_CERT_IN_CHAIN',
89
+ 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
90
+ 'UNABLE_TO_GET_ISSUER_CERT',
91
+ 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',
92
+ 'ERR_TLS_CERT_ALTNAME_INVALID',
93
+ ])
94
+
95
+ /** The certificate verdict anywhere in `err`'s cause chain, if there is one. */
96
+ function tlsCertCode(err: unknown): string | undefined {
97
+ let cur: unknown = err
98
+ for (let depth = 0; cur && depth < 4; depth++) {
99
+ const code = (cur as { code?: unknown }).code
100
+ if (
101
+ typeof code === 'string' &&
102
+ (code.startsWith('CERT_') || NON_RETRYABLE_TLS_CODES.has(code))
103
+ ) {
104
+ return code
105
+ }
106
+ cur = (cur as { cause?: unknown }).cause
107
+ }
108
+ return undefined
109
+ }
110
+
76
111
  function isRetryableError(err: unknown): boolean {
77
112
  if (err instanceof DOMException && err.name === 'AbortError') return false
113
+ if (tlsCertCode(err) !== undefined) return false
78
114
  return true
79
115
  }
80
116
 
@@ -238,6 +274,19 @@ export async function fetchWithRetry(
238
274
  `API Error: No response from API (timed out after ${Math.round(timeout / 1000)}s)`,
239
275
  )
240
276
  }
277
+ const certCode = tlsCertCode(err)
278
+ if (certCode) {
279
+ let host = url
280
+ try {
281
+ host = new URL(url).host
282
+ } catch {
283
+ /* keep the raw URL in the message */
284
+ }
285
+ throw new Error(
286
+ `API Error: TLS certificate rejected (${certCode}) for ${host}. ` +
287
+ 'The certificate is what it is — check the endpoint or the provider base URL.',
288
+ )
289
+ }
241
290
  throw err
242
291
  }
243
292
  await sleep(baseDelay * Math.pow(2, attempt))
@@ -9,6 +9,32 @@ import {
9
9
  readErrorBody,
10
10
  } from './fetch-utils'
11
11
  import { OLLAMA_PRESET_MODELS } from '../shared/constants'
12
+ import { toWellFormed } from '../shared/sanitize'
13
+
14
+ /**
15
+ * `JSON.stringify` a tool call's input with lone surrogates made well-formed.
16
+ *
17
+ * Tool arguments are re-sent with every later request, so one broken half of an
18
+ * emoji in a parameter name fails every turn after it — strict JSON parsers
19
+ * reject the bare `\uD800` escape `JSON.stringify` produces for it. Repaired at
20
+ * the point of serialization rather than at ingest: the value still reaches the
21
+ * tool as the model wrote it, and the transcript on disk keeps what happened.
22
+ */
23
+ export function serializeToolArguments(input: unknown): string {
24
+ const walk = (value: unknown): unknown => {
25
+ if (typeof value === 'string') return toWellFormed(value)
26
+ if (Array.isArray(value)) return value.map(walk)
27
+ if (value && typeof value === 'object') {
28
+ const out: Record<string, unknown> = {}
29
+ for (const [key, v] of Object.entries(value as Record<string, unknown>)) {
30
+ out[toWellFormed(key)] = walk(v)
31
+ }
32
+ return out
33
+ }
34
+ return value
35
+ }
36
+ return JSON.stringify(walk(input))
37
+ }
12
38
 
13
39
  export class OpenAICompatProvider implements ProviderInstance {
14
40
  constructor(public config: ProviderConfig) {}
@@ -371,7 +397,7 @@ export class OpenAICompatProvider implements ProviderInstance {
371
397
  type: 'function',
372
398
  function: {
373
399
  name: tu.name,
374
- arguments: JSON.stringify(tu.input),
400
+ arguments: serializeToolArguments(tu.input),
375
401
  },
376
402
  })),
377
403
  // DeepSeek V4 thinking mode: every assistant message needs reasoning_content
@@ -413,7 +439,7 @@ export class OpenAICompatProvider implements ProviderInstance {
413
439
  type: 'function',
414
440
  function: {
415
441
  name: tu.name,
416
- arguments: JSON.stringify(tu.input),
442
+ arguments: serializeToolArguments(tu.input),
417
443
  },
418
444
  })),
419
445
  // DeepSeek V4 thinking mode: every assistant message needs reasoning_content
@@ -1,18 +1,42 @@
1
+ import { DEFAULT_CREDENTIAL_MASKING_CONFIG } from '../config/defaults'
2
+ import { stripEnv } from '../core/credential-masker/env-filter'
3
+
1
4
  /**
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
+ * Environment for processes **this program runs on its own behalf** (creating a
6
+ * worktree, reading the branch, searching with ripgrep, …) — as opposed to
7
+ * commands the model asked to run in the user's shell.
5
8
  *
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.
9
+ * Two things are true of these children:
10
+ *
11
+ * 1. **They never need the user's credentials.** A provider API key or token in
12
+ * their environment is not used by them — but it *is* readable by whatever
13
+ * they run: a git credential helper, a `pre-commit` hook, a `.git/config`
14
+ * `filter.*` driver. The keys are ours to keep, so they are stripped rather
15
+ * than handed down (the model's shell keeps the masking contract instead —
16
+ * see `filterEnv`).
17
+ * 2. **They derive no correctness from replace refs.** `GIT_NO_REPLACE_OBJECTS=1`
18
+ * makes git ignore `refs/replace/*`. A replace ref rewrites what a commit
19
+ * *appears to be*: `git replace <a> <b>` makes every reader of `<a>` see
20
+ * `<b>`'s tree, so a checkout / `worktree add` produced from that view
21
+ * contains different files than the real object graph. These are local refs
22
+ * that any process in the repository can write, and this program derives no
23
+ * correctness from replaying them — the isolation boundary (`enter-worktree`,
24
+ * workflow agents, `/fork`, the CRSI sandbox) has to be built from true
25
+ * history. `git` itself still accepts the env var as an escape hatch, so
26
+ * nothing here breaks a repository that genuinely relies on replacements in
27
+ * a user's shell.
28
+ */
29
+ export function internalProcessEnv(): NodeJS.ProcessEnv {
30
+ return stripEnv(
31
+ process.env as Record<string, string | undefined>,
32
+ DEFAULT_CREDENTIAL_MASKING_CONFIG,
33
+ )
34
+ }
35
+
36
+ /**
37
+ * `internalProcessEnv()` plus the git-specific replace-ref guard. Kept as a
38
+ * separate name because the reason for the guard is git's, not the credentials'.
15
39
  */
16
40
  export function internalGitEnv(): NodeJS.ProcessEnv {
17
- return { ...process.env, GIT_NO_REPLACE_OBJECTS: '1' }
41
+ return { ...internalProcessEnv(), GIT_NO_REPLACE_OBJECTS: '1' }
18
42
  }
@@ -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.32' as const
12
+ export const PACKAGE_VERSION = '0.85.34' 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 = 4662 as const
93
+ export const TEST_COUNT = 4807 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
+ * Replace lone UTF-16 surrogates with U+FFFD, leaving valid pairs untouched.
316
+ *
317
+ * `JSON.stringify` emits a lone surrogate as a bare `\uD83D` escape (well-formed
318
+ * stringify does not repair it — it only guarantees *deterministic* output). That
319
+ * escape is what strict JSON parsers reject, so one broken half of an emoji
320
+ * picked up from a tool call would be re-sent with every later request and fail
321
+ * the whole turn. A surrogate that already lost its partner cannot be recovered;
322
+ * the replacement character at least serializes.
323
+ */
324
+ export function toWellFormed(text: string): string {
325
+ return text.replace(
326
+ /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,
327
+ '�',
328
+ )
329
+ }
330
+
314
331
  /**
315
332
  * Full command sanitization pipeline for permission checks.
316
333
  * Applies in order:
@@ -637,6 +637,14 @@ export interface ToolContext {
637
637
  backgroundAgentRegistry?: import('../agent/background-registry').BackgroundAgentRegistry
638
638
  permissionSystem?: import('../core/permission').PermissionSystem
639
639
  ruleEngine?: import('../core/rule-engine').ExperienceRuleEngine
640
+ /**
641
+ * Everything a sub-agent must run the same gates as the main loop.
642
+ *
643
+ * Populated by `Engine.executeTool`; absent when a tool context is built by
644
+ * hand (tests, daemon stubs). Absent must never mean "run without gates" —
645
+ * `SubAgent` falls back to its own hook engine for the legacy paths.
646
+ */
647
+ subAgentServices?: import('../agent/services').SubAgentServices
640
648
  llm?: import('../providers/llm').Llm
641
649
  /** Files read this session — used by Write tool to check read-before-write */
642
650
  readFiles?: Set<string>
@@ -4,6 +4,7 @@ import type { Llm } from '../providers/llm'
4
4
  import type { ToolDefinition, SkillDefinition } from '../shared/index.ts'
5
5
  import type { AgentDefinition } from '../agent/types'
6
6
  import type { PermissionSystem } from '../core/permission'
7
+ import type { SubAgentServices } from '../agent/services'
7
8
  import { sanitizeSkillDescription } from './sanitizer.js'
8
9
 
9
10
  /**
@@ -22,6 +23,7 @@ export async function executeForkedSkill(
22
23
  toolRegistry: Map<string, ToolDefinition>,
23
24
  permissionSystem?: PermissionSystem,
24
25
  llm?: Llm,
26
+ services?: SubAgentServices,
25
27
  ): Promise<string> {
26
28
  const agentDef: AgentDefinition = {
27
29
  name: `skill:${skill.name}`,
@@ -34,7 +36,15 @@ export async function executeForkedSkill(
34
36
  source: 'builtin',
35
37
  }
36
38
 
37
- const sub = new SubAgent(registry, toolRegistry, permissionSystem, undefined, undefined, llm)
39
+ const sub = new SubAgent(
40
+ registry,
41
+ toolRegistry,
42
+ permissionSystem,
43
+ undefined,
44
+ undefined,
45
+ llm,
46
+ services,
47
+ )
38
48
  const prompt = args
39
49
  ? `Execute the "${skill.name}" skill with arguments: ${args}`
40
50
  : `Execute the "${skill.name}" skill.`
@@ -120,28 +120,38 @@ export interface DiscoveredSkill {
120
120
 
121
121
  /** Minimal fetch shape (ok/json/text) so discovery is testable without real network. */
122
122
  export interface FetchLike {
123
- (url: string): Promise<{ ok: boolean; json: () => Promise<unknown>; text: () => Promise<string> }>
123
+ (url: string): Promise<{
124
+ ok: boolean
125
+ status?: number
126
+ json: () => Promise<unknown>
127
+ text: () => Promise<string>
128
+ }>
124
129
  }
125
130
 
126
131
  /**
127
132
  * List every `SKILL.md` blob path in a repository via the GitHub trees API.
128
- * Returns [] on any failure (network, rate-limit, non-2xx).
133
+ *
134
+ * **Throws** when the listing could not be obtained (network error, rate limit,
135
+ * non-2xx, malformed JSON). Returning `[]` for those — as this did — made "the
136
+ * repo has no skills" and "we never reached GitHub" the same value, so an
137
+ * offline machine or a rate-limited API surfaced to the user as
138
+ * `Skill "x" not found`. An empty array now means exactly one thing: the tree
139
+ * answered, and it contains no `SKILL.md`.
129
140
  */
130
141
  export async function listSkillPaths(
131
142
  source: MarketplaceSource,
132
143
  fetchFn: FetchLike,
133
144
  ): Promise<string[]> {
134
145
  const url = `https://api.github.com/repos/${source.owner}/${source.repo}/git/trees/HEAD?recursive=1`
135
- try {
136
- const res = await fetchFn(url)
137
- if (!res.ok) return []
138
- const data = (await res.json()) as { tree?: Array<{ path?: string; type?: string }> }
139
- return (data.tree ?? [])
140
- .filter((e) => e.type === 'blob' && e.path?.endsWith('SKILL.md'))
141
- .map((e) => e.path!)
142
- } catch {
143
- return []
146
+ const res = await fetchFn(url)
147
+ if (!res.ok) {
148
+ const status = typeof res.status === 'number' ? ` ${res.status}` : ''
149
+ throw new Error(`GitHub API${status} for ${source.owner}/${source.repo}`)
144
150
  }
151
+ const data = (await res.json()) as { tree?: Array<{ path?: string; type?: string }> }
152
+ return (data.tree ?? [])
153
+ .filter((e) => e.type === 'blob' && e.path?.endsWith('SKILL.md'))
154
+ .map((e) => e.path!)
145
155
  }
146
156
 
147
157
  /**
@@ -178,7 +188,12 @@ export interface FoundSkill {
178
188
 
179
189
  /**
180
190
  * Search every marketplace source for a skill by name (first match wins, in
181
- * source order). Returns null when no source exposes it.
191
+ * source order).
192
+ *
193
+ * Returns null **only** when every source answered and none exposes the skill.
194
+ * If some source could not be searched and the skill was not found in the ones
195
+ * that did answer, this throws — otherwise a network failure reads as
196
+ * "not found", which sends the user looking for a skill that may well exist.
182
197
  */
183
198
  export async function findSkillInMarketplaces(
184
199
  skillName: string,
@@ -186,8 +201,17 @@ export async function findSkillInMarketplaces(
186
201
  fetchFn: FetchLike,
187
202
  download: (url: string) => Promise<string>,
188
203
  ): Promise<FoundSkill | null> {
204
+ const failures: string[] = []
189
205
  for (const source of sources) {
190
- const skills = await discoverSkills(source, fetchFn, download)
206
+ let skills: DiscoveredSkill[]
207
+ try {
208
+ skills = await discoverSkills(source, fetchFn, download)
209
+ } catch (err) {
210
+ failures.push(
211
+ `${source.owner}/${source.repo}: ${err instanceof Error ? err.message : String(err)}`,
212
+ )
213
+ continue
214
+ }
191
215
  const found = skills.find((s) => s.name === skillName)
192
216
  if (found) {
193
217
  return {
@@ -199,6 +223,13 @@ export async function findSkillInMarketplaces(
199
223
  }
200
224
  }
201
225
  }
226
+ if (failures.length > 0) {
227
+ throw new Error(
228
+ `could not search ${failures.length} of ${sources.length} marketplace source(s) ` +
229
+ `(${failures.join('; ')}); "${skillName}" was not found in the sources that answered, ` +
230
+ `but it may exist in the ones that did not`,
231
+ )
232
+ }
202
233
  return null
203
234
  }
204
235
 
@@ -212,7 +212,18 @@ async function installFromMarketplace(
212
212
  (p) => (existsSync(p) ? readFileSync(p, 'utf-8') : null),
213
213
  (m) => console.error(`⚠ ${m}`),
214
214
  )
215
- const found = await findSkillInMarketplaces(skillName, sources, globalThis.fetch, downloadFile)
215
+ let found: Awaited<ReturnType<typeof findSkillInMarketplaces>>
216
+ try {
217
+ found = await findSkillInMarketplaces(skillName, sources, globalThis.fetch, downloadFile)
218
+ } catch (err) {
219
+ // 查不成 ≠ 不存在。把「没能搜索」渲染成 `Skill "x" not found` 会让用户
220
+ // 去一个根本可能有的技能上白找 —— 网络断、限流、GitHub 500 都走这条。
221
+ return {
222
+ success: false,
223
+ name: skillName,
224
+ message: `Could not search the marketplaces for "${skillName}": ${err instanceof Error ? err.message : String(err)}`,
225
+ }
226
+ }
216
227
 
217
228
  if (!found) {
218
229
  return {
@@ -130,6 +130,9 @@ export const agentTool: ToolDefinition = {
130
130
  undefined,
131
131
  ctx.ruleEngine,
132
132
  ctx.llm,
133
+ // Hooks, gates and DLP travel with the context the engine built. Without
134
+ // this the child ran the same tools under a strictly weaker gate set.
135
+ ctx.subAgentServices,
133
136
  )
134
137
  const result = await sub.execute(prompt, description, {
135
138
  type: agentType,
@@ -26,6 +26,15 @@ export const enterPlanModeTool: ToolDefinition = {
26
26
  async execute(params, ctx) {
27
27
  const description = (params.description as string) || 'Implementation Plan'
28
28
 
29
+ // 这个工具的正文一直在说「Plan mode is READ-ONLY:其他工具都要确认」,
30
+ // 可它从前**只写了一个 markdown 模板**,从未动过权限模式 —— 于是工具返回
31
+ // 「已进入计划模式」,闸门还停在进这一轮之前的档位(比如 acceptEdits:
32
+ // 写文件不问)。广告的能力没有落点,模型据此以为自己在只读档里。
33
+ const before = ctx.permissionSystem?.getMode()
34
+ ctx.permissionSystem?.setMode('plan')
35
+ const live = ctx.permissionSystem?.getMode() ?? before
36
+ const switched = live === 'plan'
37
+
29
38
  // Create plan file
30
39
  const planDir = join(ctx.cwd, MIPHAM_DIR, 'plans')
31
40
  mkdirSync(planDir, { recursive: true })
@@ -69,16 +78,25 @@ export const enterPlanModeTool: ToolDefinition = {
69
78
 
70
79
  writeFileSync(filepath, content, 'utf-8')
71
80
 
81
+ const modeLine = switched
82
+ ? 'Plan mode is READ-ONLY:'
83
+ : `⚠️ Plan mode was NOT applied — the live permission mode is "${live ?? 'unknown'}"` +
84
+ ' (organisation policy may forbid "plan"). Treat every write as refused until' +
85
+ ' the user moves the mode, and say so rather than assuming read-only.'
86
+
87
+ const readOnlyLines = switched
88
+ ? [' ✅ Read, Grep, Glob — auto-approved', ' ⚠️ All other tools — require confirmation']
89
+ : []
90
+
72
91
  return {
73
92
  success: true,
74
93
  content: [
75
- '── Plan Mode Activated ──',
94
+ switched ? '── Plan Mode Activated ──' : '── Plan File Created (mode unchanged) ──',
76
95
  '',
77
96
  `Plan file: ${filepath}`,
78
97
  '',
79
- 'Plan mode is READ-ONLY:',
80
- ' ✅ Read, Grep, Glob — auto-approved',
81
- ' ⚠️ All other tools — require confirmation',
98
+ modeLine,
99
+ ...readOnlyLines,
82
100
  '',
83
101
  'Design your approach, explore the codebase, then:',
84
102
  ' • Use ExitPlanMode to submit your plan for user review',
@@ -74,12 +74,20 @@ export const exitPlanModeTool: ToolDefinition = {
74
74
  ? `⚠️ Plan file not readable (${planFile}): ${readError}`
75
75
  : '⚠️ No plan file found — present the plan from your own context.'
76
76
 
77
+ // 这一行曾经写「✓ Exiting plan mode.」,可这套工具链从不动权限模式:
78
+ // 进入时没进、退出时也没退。现在 EnterPlanMode 真的会切到 plan,
79
+ // 于是「已退出」更是一句假话 —— 档位要等用户批准(`/approve` 或 Shift+Tab)
80
+ // 才会变。说清楚当前档位,别让模型以为自己已经能在写模式下动手。
81
+ const mode = ctx.permissionSystem?.getMode()
82
+
77
83
  return {
78
84
  success: true,
79
85
  content: [
80
86
  '── Plan Ready for Review ──',
81
87
  '',
82
- '✓ Exiting plan mode.',
88
+ mode === 'plan'
89
+ ? 'Plan mode: still active (read-only). The switch to acceptEdits happens on approval.'
90
+ : `Permission mode right now: ${mode ?? 'unknown'}.`,
83
91
  planStatus,
84
92
  planFile ? `Plan file: ${planFile}` : '',
85
93
  '',
@@ -94,6 +94,7 @@ export const skillTool: ToolDefinition = {
94
94
  ctx.toolRegistry || new Map(),
95
95
  ctx.permissionSystem,
96
96
  ctx.llm,
97
+ ctx.subAgentServices,
97
98
  )
98
99
  // Return to AI as internal context
99
100
  recordSkillUsage(skillName)
@@ -104,6 +104,7 @@ export const workflowTool: ToolDefinition = {
104
104
  getTools: () => ctx.toolRegistry!,
105
105
  getPermission: () => ctx.permissionSystem,
106
106
  getLlm: () => ctx.llm,
107
+ getSubAgentServices: () => ctx.subAgentServices,
107
108
  } as unknown as QueryEngine
108
109
 
109
110
  try {