@miphamai/cli 0.85.33 → 0.85.35
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.
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/agent/services.ts +21 -0
- package/src/agent/sub-agent.ts +129 -21
- package/src/commands/environment.ts +14 -11
- package/src/commands/project.ts +43 -12
- package/src/config/loader.ts +65 -35
- package/src/core/alignment-vocabulary.json +2 -2
- package/src/core/constitution-loader.ts +85 -24
- package/src/core/context.ts +22 -5
- package/src/core/engine.ts +62 -143
- package/src/core/hooks-config.ts +32 -0
- package/src/core/memory/memory-loader.ts +2 -2
- package/src/core/permission-rules.ts +67 -12
- package/src/core/session-log.ts +26 -7
- package/src/core/session-store.ts +4 -3
- package/src/core/tool-gate.ts +222 -0
- package/src/daemon/engine-capabilities.ts +124 -2
- package/src/daemon/remote-engine.ts +3 -0
- package/src/daemon/server.ts +13 -1
- package/src/i18n-core/locales/en-US.json +1 -0
- package/src/i18n-core/locales/zh-CN.json +1 -0
- package/src/mcp/client.ts +22 -2
- package/src/plugin/plugin-manager.ts +14 -0
- package/src/shared/package-info.ts +2 -2
- package/src/shared/types.ts +8 -0
- package/src/skills/fork-executor.ts +11 -1
- package/src/skills/marketplace.ts +44 -13
- package/src/skills/registry.ts +12 -1
- package/src/tools/agent/agent.ts +3 -0
- package/src/tools/agent/enter-plan.ts +22 -4
- package/src/tools/agent/exit-plan.ts +9 -1
- package/src/tools/agent/skill.ts +1 -0
- package/src/tools/agent/workflow.ts +1 -0
- package/src/tools/exec/git.ts +113 -69
- package/src/tools/index.ts +2 -2
- package/src/ui/app.tsx +15 -0
- package/src/ui/chat.tsx +7 -4
- package/src/ui/commands.ts +140 -20
- package/src/workflow/primitives/agent.ts +12 -1
- package/src/workflow/primitives/loop.ts +14 -0
- package/src/workflow/primitives/verify.ts +13 -1
- package/src/workflow/runtime.ts +1 -0
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.
|
|
12
|
+
export const PACKAGE_VERSION = '0.85.35' 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 =
|
|
93
|
+
export const TEST_COUNT = 4814 as const
|
package/src/shared/types.ts
CHANGED
|
@@ -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(
|
|
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<{
|
|
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
|
-
*
|
|
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
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
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).
|
|
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
|
-
|
|
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
|
|
package/src/skills/registry.ts
CHANGED
|
@@ -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
|
-
|
|
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 {
|
package/src/tools/agent/agent.ts
CHANGED
|
@@ -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
|
-
|
|
80
|
-
|
|
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
|
-
|
|
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
|
'',
|
package/src/tools/agent/skill.ts
CHANGED
|
@@ -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 {
|
package/src/tools/exec/git.ts
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import { resolve } from 'node:path'
|
|
2
|
-
import type { ToolDefinition } from '../../shared/index.ts'
|
|
2
|
+
import type { CredentialMaskingConfig, ToolDefinition } from '../../shared/index.ts'
|
|
3
|
+
import { DEFAULT_CREDENTIAL_MASKING_CONFIG } from '../../config/defaults'
|
|
3
4
|
import { findWorktreeMarker } from '../../core/paths.ts'
|
|
4
5
|
import { isWithin } from '../../security/path.ts'
|
|
6
|
+
import type { Service } from '../../vajra'
|
|
7
|
+
import { toolKey } from '../seam'
|
|
8
|
+
import { withValidation } from '../validation'
|
|
5
9
|
|
|
6
10
|
/** Generous enough for a clone or fetch, short enough to bound a hung git. */
|
|
7
11
|
const GIT_TIMEOUT_MS = 120_000
|
|
@@ -201,91 +205,131 @@ export function splitCommand(command: string): string[] {
|
|
|
201
205
|
return tokens
|
|
202
206
|
}
|
|
203
207
|
|
|
204
|
-
export
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
208
|
+
export function createGitTool(
|
|
209
|
+
credentialConfig: CredentialMaskingConfig = DEFAULT_CREDENTIAL_MASKING_CONFIG,
|
|
210
|
+
): ToolDefinition {
|
|
211
|
+
return {
|
|
212
|
+
name: 'Git',
|
|
213
|
+
description: 'Execute git commands. Dangerous operations (force push, hard reset) are blocked.',
|
|
214
|
+
category: 'exec',
|
|
215
|
+
permission: 'self',
|
|
216
|
+
parameters: {
|
|
217
|
+
type: 'object',
|
|
218
|
+
properties: {
|
|
219
|
+
command: {
|
|
220
|
+
type: 'string',
|
|
221
|
+
description: 'Git subcommand + args (e.g., "status", "log --oneline")',
|
|
222
|
+
},
|
|
215
223
|
},
|
|
224
|
+
required: ['command'],
|
|
216
225
|
},
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
226
|
+
async execute(params, ctx) {
|
|
227
|
+
const command = params.command as string
|
|
228
|
+
|
|
229
|
+
// P0-4: Regex-based word-boundary pattern matching
|
|
230
|
+
for (const { pattern, description } of DANGEROUS_GIT_PATTERNS) {
|
|
231
|
+
if (pattern.test(command)) {
|
|
232
|
+
return {
|
|
233
|
+
success: false,
|
|
234
|
+
content: '',
|
|
235
|
+
error: `Dangerous git command blocked: "${description}". Run manually if intended.`,
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
221
239
|
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
if (
|
|
240
|
+
// P0-4: Worktree isolation — block commands referencing outside paths
|
|
241
|
+
const worktreeErr = isOutsideWorktree(command, ctx.cwd)
|
|
242
|
+
if (worktreeErr) {
|
|
225
243
|
return {
|
|
226
244
|
success: false,
|
|
227
245
|
content: '',
|
|
228
|
-
error: `
|
|
246
|
+
error: `Worktree isolation: ${worktreeErr}. Blocked for safety.`,
|
|
229
247
|
}
|
|
230
248
|
}
|
|
231
|
-
}
|
|
232
249
|
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
250
|
+
// Git runs without an approval prompt (`permission: 'self'`), so an option
|
|
251
|
+
// that names a program to execute is a code-execution path Bash would have
|
|
252
|
+
// had to ask for. Checked on argv, which is what git is handed below.
|
|
253
|
+
const argv = splitCommand(command)
|
|
254
|
+
const execArg = findProgramExecutingArg(argv)
|
|
255
|
+
if (execArg) {
|
|
256
|
+
return {
|
|
257
|
+
success: false,
|
|
258
|
+
content: '',
|
|
259
|
+
error: `Dangerous git option blocked: "${execArg}" makes git run an arbitrary program. Run manually if intended.`,
|
|
260
|
+
}
|
|
240
261
|
}
|
|
241
|
-
}
|
|
242
262
|
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
263
|
+
try {
|
|
264
|
+
// The environment a git child gets is the same contract Bash's children
|
|
265
|
+
// get: sensitive variables are replaced by the sentinel, never handed
|
|
266
|
+
// over in the clear. This is not a cosmetic difference — `pre-commit`
|
|
267
|
+
// hooks, `filter.*` drivers and credential helpers are repository-
|
|
268
|
+
// supplied code, and the model can run any of them by asking for
|
|
269
|
+
// `git checkout` / `git commit` in a cloned repository.
|
|
270
|
+
let spawnEnv: Record<string, string | undefined> = process.env as Record<
|
|
271
|
+
string,
|
|
272
|
+
string | undefined
|
|
273
|
+
>
|
|
274
|
+
if (credentialConfig.enabled && credentialConfig.env_filter.enabled) {
|
|
275
|
+
const { filterEnv } = await import('../../core/credential-masker')
|
|
276
|
+
spawnEnv = filterEnv(spawnEnv, credentialConfig)
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const proc = Bun.spawn(['git', ...argv], {
|
|
280
|
+
cwd: ctx.cwd,
|
|
281
|
+
stdout: 'pipe',
|
|
282
|
+
stderr: 'pipe',
|
|
283
|
+
env: spawnEnv,
|
|
284
|
+
})
|
|
285
|
+
|
|
286
|
+
// Bounded like Bash: a git command that blocks on a pager, a credential
|
|
287
|
+
// prompt, or an unreachable remote would otherwise hang the turn forever.
|
|
288
|
+
const timer = setTimeout(() => proc.kill(), GIT_TIMEOUT_MS)
|
|
289
|
+
const output = await new Response(proc.stdout).text()
|
|
290
|
+
const exitCode = await proc.exited
|
|
291
|
+
clearTimeout(timer)
|
|
292
|
+
|
|
293
|
+
// Output scrubbing, for the same reason `Read`/`Grep`/`Bash` scrub:
|
|
294
|
+
// `git show HEAD:.env` returns a secret verbatim, and a masked read of
|
|
295
|
+
// the same file would not. One contract, every path.
|
|
296
|
+
const scrub = async (text: string): Promise<string> =>
|
|
297
|
+
credentialConfig.enabled && credentialConfig.output_scrubbing.enabled
|
|
298
|
+
? (await import('../../core/credential-masker')).maskOutput(text, credentialConfig)
|
|
299
|
+
: text
|
|
300
|
+
|
|
301
|
+
if (exitCode !== 0) {
|
|
302
|
+
const stderr = await new Response(proc.stderr).text()
|
|
303
|
+
return {
|
|
304
|
+
success: false,
|
|
305
|
+
content: '',
|
|
306
|
+
error: `Git error (exit ${exitCode}): ${(await scrub(stderr)).slice(0, 1000)}`,
|
|
307
|
+
}
|
|
308
|
+
}
|
|
255
309
|
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
})
|
|
262
|
-
|
|
263
|
-
// Bounded like Bash: a git command that blocks on a pager, a credential
|
|
264
|
-
// prompt, or an unreachable remote would otherwise hang the turn forever.
|
|
265
|
-
const timer = setTimeout(() => proc.kill(), GIT_TIMEOUT_MS)
|
|
266
|
-
const output = await new Response(proc.stdout).text()
|
|
267
|
-
const exitCode = await proc.exited
|
|
268
|
-
clearTimeout(timer)
|
|
269
|
-
|
|
270
|
-
if (exitCode !== 0) {
|
|
271
|
-
const stderr = await new Response(proc.stderr).text()
|
|
310
|
+
return {
|
|
311
|
+
success: true,
|
|
312
|
+
content: (await scrub(output)).slice(0, 50_000) || '(no output)',
|
|
313
|
+
}
|
|
314
|
+
} catch (err) {
|
|
272
315
|
return {
|
|
273
316
|
success: false,
|
|
274
317
|
content: '',
|
|
275
|
-
error: `Git
|
|
318
|
+
error: `Git execution failed: ${String(err)}`,
|
|
276
319
|
}
|
|
277
320
|
}
|
|
321
|
+
},
|
|
322
|
+
}
|
|
323
|
+
}
|
|
278
324
|
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
success: false,
|
|
286
|
-
content: '',
|
|
287
|
-
error: `Git execution failed: ${String(err)}`,
|
|
288
|
-
}
|
|
289
|
-
}
|
|
325
|
+
/** Registry entry with credential masking, handed in the same way as Bash's. */
|
|
326
|
+
export const gitToolService: Service = {
|
|
327
|
+
inject: ['credentials'],
|
|
328
|
+
apply(ctx) {
|
|
329
|
+
const credentialConfig = ctx.get<CredentialMaskingConfig>('credentials')
|
|
330
|
+
ctx.provide(toolKey('Git'), withValidation(createGitTool(credentialConfig)))
|
|
290
331
|
},
|
|
291
332
|
}
|
|
333
|
+
|
|
334
|
+
/** Unwrapped tool for callers that build a registry by hand (tests). */
|
|
335
|
+
export const gitTool: ToolDefinition = createGitTool()
|
package/src/tools/index.ts
CHANGED
|
@@ -8,7 +8,7 @@ import { editTool } from './file/edit'
|
|
|
8
8
|
import { globToolService } from './file/glob'
|
|
9
9
|
import { grepToolService } from './file/grep'
|
|
10
10
|
import { bashToolService } from './exec/bash'
|
|
11
|
-
import {
|
|
11
|
+
import { gitToolService } from './exec/git'
|
|
12
12
|
import { taskTool } from './exec/task'
|
|
13
13
|
import { enterWorktreeTool } from './exec/enter-worktree'
|
|
14
14
|
import { exitWorktreeTool } from './exec/exit-worktree'
|
|
@@ -58,7 +58,6 @@ export function createToolRegistry(
|
|
|
58
58
|
writeTool,
|
|
59
59
|
editTool,
|
|
60
60
|
// Exec tools
|
|
61
|
-
gitTool,
|
|
62
61
|
taskTool,
|
|
63
62
|
enterWorktreeTool,
|
|
64
63
|
exitWorktreeTool,
|
|
@@ -103,6 +102,7 @@ export function createToolRegistry(
|
|
|
103
102
|
// provider 的 apiKey、MCP server 的 env、inference hook 的 signing_secret。
|
|
104
103
|
ctx.mount(readToolService)
|
|
105
104
|
ctx.mount(bashToolService)
|
|
105
|
+
ctx.mount(gitToolService)
|
|
106
106
|
ctx.mount(grepToolService)
|
|
107
107
|
ctx.mount(globToolService)
|
|
108
108
|
ctx.mount(configToolService)
|
package/src/ui/app.tsx
CHANGED
|
@@ -1524,6 +1524,21 @@ export function App({
|
|
|
1524
1524
|
currentProvider={providerId}
|
|
1525
1525
|
currentModel={modelId}
|
|
1526
1526
|
onSelect={(newProvider, newModel) => {
|
|
1527
|
+
// 远程 attach:`switchProvider` 是 no-op,而页脚状态是本地的 ——
|
|
1528
|
+
// 照旧改会得到「页脚说 A、daemon 跑 B」。宁可不改,也要说清楚。
|
|
1529
|
+
if (engine.isRemote) {
|
|
1530
|
+
setPickerOpen(false)
|
|
1531
|
+
setMessages((prev) => [
|
|
1532
|
+
...prev,
|
|
1533
|
+
{
|
|
1534
|
+
role: 'system',
|
|
1535
|
+
content:
|
|
1536
|
+
`Model is chosen by the daemon in an attached session — ` +
|
|
1537
|
+
`${newProvider}/${newModel} was not applied.`,
|
|
1538
|
+
},
|
|
1539
|
+
])
|
|
1540
|
+
return
|
|
1541
|
+
}
|
|
1527
1542
|
engine.switchProvider(newProvider, newModel)
|
|
1528
1543
|
setProviderId(newProvider)
|
|
1529
1544
|
setModelId(newModel)
|
package/src/ui/chat.tsx
CHANGED
|
@@ -68,10 +68,13 @@ function capRenderedLines(text: string): string {
|
|
|
68
68
|
function displayCwd(): string {
|
|
69
69
|
const cwd = process.cwd()
|
|
70
70
|
const home = homedir()
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
71
|
+
const shown = home && cwd.startsWith(home) ? '~' + cwd.slice(home.length) : cwd
|
|
72
|
+
// A folder name can contain a newline or an escape sequence (they are just
|
|
73
|
+
// bytes on every filesystem this runs on). The header is one line and is
|
|
74
|
+
// written to the terminal verbatim, so the same inline strip the tool name
|
|
75
|
+
// gets applies here — otherwise the "header" can split into lines or carry a
|
|
76
|
+
// raw SGR the user cannot see.
|
|
77
|
+
return sanitizeInlineField(shown)
|
|
75
78
|
}
|
|
76
79
|
|
|
77
80
|
/** Map tool names to dot colors — Claude Code parity */
|