@miphamai/cli 0.85.33 → 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.
@@ -0,0 +1,222 @@
1
+ import type { HookEngine } from './hooks'
2
+ import type { ExperienceRuleEngine } from './rule-engine'
3
+ import type { PreFlightChecker } from './preflight-checker'
4
+ import type { ConstitutionLoader } from './constitution-loader'
5
+ import type { SelfCritique } from './self-critique'
6
+ import type { ProviderRegistry } from '../providers/registry'
7
+ import type { Llm } from '../providers/llm'
8
+ import { getMetrics } from './metrics'
9
+ import { createT } from '../i18n-core/t'
10
+ import enUS from '../i18n-core/locales/en-US.json'
11
+ import type { TranslationMap } from '../i18n-core/types'
12
+
13
+ const t = createT(enUS as TranslationMap, enUS as TranslationMap)
14
+
15
+ /**
16
+ * Everything the pre-execution chain needs, resolved lazily.
17
+ *
18
+ * The chain was written inline in `Engine.executeTool`; `SubAgent` runs its own
19
+ * tool loop and called none of it, so a `Write` carrying an `apiKey = "sk-…"`
20
+ * was blocked in the main loop and executed verbatim one level down. This module
21
+ * is the single definition both loops call — duplicating the chain in the
22
+ * sub-agent would let the two drift again, which is the defect being fixed.
23
+ *
24
+ * The three constructors are getters, not instances: the engine creates them
25
+ * lazily on first use and that laziness is deliberate (`PreFlightChecker` builds
26
+ * the error-signature DB, `ConstitutionLoader` reads the vocabulary).
27
+ */
28
+ export interface ToolGateDeps {
29
+ hookEngine?: HookEngine
30
+ ruleEngine?: ExperienceRuleEngine
31
+ preflight?: () => PreFlightChecker
32
+ constitution?: () => ConstitutionLoader
33
+ selfCritique?: () => SelfCritique
34
+ /** `crsi.preToolHook !== false` — read once by the caller, same as the engine. */
35
+ crsiPreToolHook: boolean
36
+ registry: ProviderRegistry
37
+ llm?: Llm
38
+ }
39
+
40
+ export type ToolGateOutcome =
41
+ | { ok: false; content: string; error: string; notRun?: boolean }
42
+ | { ok: true; params: Record<string, unknown>; warnings: string[] }
43
+
44
+ /**
45
+ * The text a principle's `audit_pattern` is matched against.
46
+ *
47
+ * Not `JSON.stringify(params)`. Patterns are written against source text —
48
+ * `apiKey = "sk-…"` — while JSON spells that value `apiKey = \"sk-…\"`, so the
49
+ * quote class `['"]` never met the escaped quote and **the most idiomatic
50
+ * spelling was the one that could not match**. Rendering each parameter as
51
+ * `name=value` (strings verbatim) removes the escaping question entirely and
52
+ * also lets the key carry the signal (`{ apiKey: '…' }` → `apiKey=…`).
53
+ */
54
+ export function toolAuditSurface(params: Record<string, unknown>): string {
55
+ return Object.entries(params)
56
+ .map(([key, value]) => `${key}=${typeof value === 'string' ? value : JSON.stringify(value)}`)
57
+ .join('\n')
58
+ }
59
+
60
+ /**
61
+ * Run every pre-execution gate for one tool call, in the engine's order:
62
+ * PreToolUse hook → CRSI rules → SIS preflight → constitution → self-critique.
63
+ *
64
+ * `params` is returned by reference when nothing rewrote it; callers use that
65
+ * identity (`effectiveParams !== params`) to decide whether the permission gate
66
+ * has to rule again on what will actually run.
67
+ */
68
+ export async function runPreToolGate(
69
+ name: string,
70
+ params: Record<string, unknown>,
71
+ deps: ToolGateDeps,
72
+ sessionId: string,
73
+ ): Promise<ToolGateOutcome> {
74
+ let effectiveParams = params
75
+ const warnings: string[] = []
76
+
77
+ // ── PreToolUse hook ──
78
+ if (deps.hookEngine) {
79
+ const preResult = await deps.hookEngine.executePreToolUse(name, params, sessionId)
80
+ if (!preResult.allowed) {
81
+ return {
82
+ ok: false,
83
+ content: '',
84
+ error: preResult.reason || t('errors.tool_blocked', { name }),
85
+ notRun: true,
86
+ }
87
+ }
88
+
89
+ // `permissionDecision` narrows only — never widens. `ask` stops the call here
90
+ // (this CLI has no interactive approval prompt; `ask` is a hard refusal, the
91
+ // same as the `default` mode's ask path). `allow` is deliberately **not**
92
+ // honoured: a hook can come from the repository's own settings, so letting it
93
+ // auto-approve is the same defect as a project-supplied agent definition that
94
+ // grants itself `bypassPermissions` — the criterion is the *direction*, not the
95
+ // key name. `defer` (and an absent decision) means "no override", which is
96
+ // exactly what happens when we do nothing.
97
+ if (preResult.permissionDecision === 'ask' || preResult.permissionDecision === 'deny') {
98
+ return {
99
+ ok: false,
100
+ content: '',
101
+ error: preResult.reason || t('errors.tool_hook_ask', { name }),
102
+ notRun: true,
103
+ }
104
+ }
105
+
106
+ if (preResult.modifiedInput) {
107
+ effectiveParams = { ...params, ...preResult.modifiedInput }
108
+ }
109
+
110
+ // A hook's `additionalContext` is how every non-blocking hook speaks — the
111
+ // exit-1 stderr, a spawn failure, an unreachable `mcp_tool` server (see
112
+ // `core/hooks-executor.ts`). This path used to read only `allowed` /
113
+ // `modifiedInput`, so all of it was produced and then dropped. The warnings
114
+ // channel already reaches the model: it is prepended to the tool result.
115
+ // A non-`[rule:…]` line is ignored by the effectiveness tracker, so pushing
116
+ // prose here is safe.
117
+ if (preResult.additionalContext) {
118
+ warnings.push(preResult.additionalContext)
119
+ }
120
+ }
121
+
122
+ // ── CRSI RuleEngine intercept ──
123
+ if (deps.crsiPreToolHook !== false && deps.ruleEngine) {
124
+ const ruleResult = deps.ruleEngine.intercept(name, effectiveParams)
125
+ if (Object.keys(ruleResult.modified).length > 0) {
126
+ getMetrics().crsiRuleApplications.inc()
127
+ effectiveParams = ruleResult.modified
128
+ }
129
+ if (ruleResult.warnings.length > 0) {
130
+ // Append, do not replace: this array may already hold a PreToolUse hook's
131
+ // `additionalContext`. Every other writer below uses the spread form for the
132
+ // same reason — assignment here would silently drop whichever was written
133
+ // first ("two writers, one list").
134
+ warnings.push(...ruleResult.warnings)
135
+ }
136
+ }
137
+
138
+ // ── SIS PreFlightChecker — known error pattern interception ──
139
+ if (deps.preflight) {
140
+ const preflight = deps.preflight().check(name, effectiveParams)
141
+ if (preflight.action === 'block') {
142
+ getMetrics().sisInterceptions.inc()
143
+ return {
144
+ ok: false,
145
+ content: preflight.warning || 'SIS 免疫系统拦截了此操作',
146
+ error: preflight.warning || 'SIS 免疫系统拦截了此操作',
147
+ }
148
+ }
149
+ if (preflight.action === 'fix' && preflight.modifiedParams) {
150
+ getMetrics().sisInterceptions.inc()
151
+ effectiveParams = preflight.modifiedParams
152
+ if (preflight.warning) {
153
+ warnings.push(preflight.warning)
154
+ }
155
+ }
156
+ if (preflight.action === 'warn' && preflight.warning) {
157
+ warnings.push(preflight.warning)
158
+ }
159
+ }
160
+
161
+ // ── Mipham Constitution — constitutional principle enforcement ──
162
+ // Block-level violations (enforce: block) halt execution immediately.
163
+ // Warn-level violations (enforce: warn) are appended to the warnings.
164
+ if (deps.constitution) {
165
+ const principles = deps.constitution().getPrinciplesForTool(name)
166
+ for (const principle of principles) {
167
+ if (principle.enforce === 'block') {
168
+ // Audit: check if the tool params match a violation pattern
169
+ if (principle.audit_pattern) {
170
+ try {
171
+ const regex = new RegExp(principle.audit_pattern, 'i')
172
+ if (regex.test(toolAuditSurface(effectiveParams))) {
173
+ return {
174
+ ok: false,
175
+ content: `🚫 Constitution violation blocked: **${principle.id}** — ${principle.text}`,
176
+ error: `Constitutional principle "${principle.id}" blocked this operation.`,
177
+ }
178
+ }
179
+ } catch {
180
+ // Invalid regex — skip this principle
181
+ }
182
+ }
183
+ }
184
+ if (principle.enforce === 'warn') {
185
+ warnings.push(`⚖️ Constitution: ${principle.id} — ${principle.text}`)
186
+ }
187
+ }
188
+ }
189
+
190
+ // ── Self-Critique Hook — RLAIF-style tool-call safety verification ──
191
+ // Uses a fast model to critique the tool call before execution.
192
+ // Fail-open: if the critique times out or errors, the tool still executes.
193
+ if (deps.selfCritique) {
194
+ const selfCritique = deps.selfCritique()
195
+ if (selfCritique.getConfig().enabled) {
196
+ const critiqueResult = await selfCritique.critique(
197
+ name,
198
+ effectiveParams,
199
+ deps.registry,
200
+ deps.llm,
201
+ )
202
+ if (critiqueResult) {
203
+ if (critiqueResult.score < selfCritique.getConfig().threshold) {
204
+ // Score too low — block with explanation
205
+ if (!critiqueResult.safe) {
206
+ return {
207
+ ok: false,
208
+ content: `🔍 Self-Critique blocked: ${critiqueResult.reasoning}`,
209
+ error: `Self-Critique safety check failed (score: ${(critiqueResult.score * 100).toFixed(0)}%). ${critiqueResult.correction || ''}`,
210
+ }
211
+ }
212
+ // Score low but safe — warn but allow
213
+ warnings.push(
214
+ `🔍 Self-Critique: ${critiqueResult.reasoning}${critiqueResult.correction ? ` — Suggestion: ${critiqueResult.correction}` : ''}`,
215
+ )
216
+ }
217
+ }
218
+ }
219
+ }
220
+
221
+ return { ok: true, params: effectiveParams, warnings }
222
+ }
@@ -45,6 +45,9 @@ export interface RemoteEngineOptions {
45
45
  * consumes from the local engine.
46
46
  */
47
47
  export class RemoteEngine {
48
+ /** Attach mode: provider/model are the daemon's choice, not this process's. */
49
+ readonly isRemote = true
50
+
48
51
  private sessionId: string
49
52
  private port: number
50
53
  private token: string
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
 
@@ -15,6 +15,18 @@ 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
  }
@@ -226,6 +239,7 @@ export class PluginManager {
226
239
  success: true,
227
240
  message:
228
241
  `Plugin "${manifestName}" installed from npm` +
242
+ `\n${PLUGIN_TRUST_NOTE}` +
229
243
  (npmNote ? `\n${npmNote}` : '') +
230
244
  (similarWarning ? `\n⚠ ${similarWarning}` : '') +
231
245
  warningsBlock(validation.warnings),
@@ -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.33' 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 = 4706 as const
93
+ export const TEST_COUNT = 4807 as const
@@ -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 {