@miphamai/cli 0.85.8 → 0.85.9
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 +2 -2
- package/bin/mipham.ts +6 -4
- package/package.json +1 -1
- package/src/commands/project.ts +39 -7
- package/src/config/loader.ts +262 -71
- package/src/core/crsi-producer.ts +320 -29
- package/src/core/eval-harness.ts +13 -4
- package/src/core/instructions.ts +17 -5
- package/src/core/permission-config.ts +22 -0
- package/src/daemon/auth.ts +50 -3
- package/src/daemon/feishu/adapter.ts +57 -1
- package/src/daemon/server.ts +24 -12
- package/src/index.tsx +21 -1
- package/src/shared/package-info.ts +3 -3
- package/src/telemetry/consent.ts +18 -2
- package/src/tools/index.ts +5 -3
- package/src/tools/system/config.ts +119 -52
- package/src/ui/app.tsx +7 -1
- package/src/ui/commands.ts +49 -0
package/src/daemon/auth.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
// apps/cli/src/daemon/auth.ts
|
|
2
2
|
import { randomBytes, timingSafeEqual } from 'node:crypto'
|
|
3
|
-
import { readFileSync, existsSync, mkdirSync } from 'node:fs'
|
|
3
|
+
import { readFileSync, existsSync, mkdirSync, statSync, chmodSync } from 'node:fs'
|
|
4
4
|
import { atomicWriteFileSync } from '../shared/atomic-write'
|
|
5
|
+
import { isRegularFile } from '../shared/regular-file'
|
|
6
|
+
import { logger } from './logger'
|
|
5
7
|
import { dirname } from 'node:path'
|
|
6
8
|
|
|
7
9
|
/**
|
|
@@ -11,13 +13,58 @@ export function generateToken(): string {
|
|
|
11
13
|
return randomBytes(32).toString('hex')
|
|
12
14
|
}
|
|
13
15
|
|
|
16
|
+
/**
|
|
17
|
+
* Read the token file: type gate first, then pull a drifted mode back.
|
|
18
|
+
*
|
|
19
|
+
* The type gate is not defensive form. `readFileSync` on a FIFO with no writer
|
|
20
|
+
* blocks **synchronously** until one appears — timers and signal handlers cannot
|
|
21
|
+
* queue behind it, so at daemon startup it looks like nothing happening at all
|
|
22
|
+
* (measured: the process is still inside the call when the watchdog kills it, and
|
|
23
|
+
* had printed no error). A FIFO on this path is a signal something is wrong, so
|
|
24
|
+
* name the path and refuse rather than wait forever.
|
|
25
|
+
*
|
|
26
|
+
* The repair targets the 0o600 this module itself declares (both writers pass
|
|
27
|
+
* `mode: 0o600`), not the credential key's 0o400 — a drifted 0644 token is
|
|
28
|
+
* readable by every local user, and the bearer token it holds buys full control
|
|
29
|
+
* of the daemon. The read path is the only place that ever notices, so the repair
|
|
30
|
+
* lives here; and it says so, because the widened mode may have been set on
|
|
31
|
+
* purpose by someone who deserves to know it was taken back.
|
|
32
|
+
*
|
|
33
|
+
* Exported so that every reader of this file goes through it: `mipham attach`
|
|
34
|
+
* used to inline its own `existsSync + readFileSync` copy, and that copy had
|
|
35
|
+
* neither half of this gate. Caller's precondition: the path exists.
|
|
36
|
+
*/
|
|
37
|
+
export function readTokenFile(tokenPath: string): string {
|
|
38
|
+
if (!isRegularFile(tokenPath)) {
|
|
39
|
+
throw new Error(
|
|
40
|
+
`${tokenPath} is not a regular file — refusing to read the daemon token from it ` +
|
|
41
|
+
`(remove or replace it with a regular file).`,
|
|
42
|
+
)
|
|
43
|
+
}
|
|
44
|
+
const mode = statSync(tokenPath).mode & 0o777
|
|
45
|
+
if (mode !== 0o600) {
|
|
46
|
+
chmodSync(tokenPath, 0o600)
|
|
47
|
+
logger.warn('daemon token file was not 0600 — tightened', {
|
|
48
|
+
path: tokenPath,
|
|
49
|
+
from: mode.toString(8),
|
|
50
|
+
to: '600',
|
|
51
|
+
})
|
|
52
|
+
}
|
|
53
|
+
return readFileSync(tokenPath, 'utf-8').trim()
|
|
54
|
+
}
|
|
55
|
+
|
|
14
56
|
/**
|
|
15
57
|
* Load an existing token from disk, or create one if it doesn't exist.
|
|
16
58
|
* The token file is created with 0o600 permissions.
|
|
59
|
+
*
|
|
60
|
+
* A path that exists but is not a regular file throws (see `readTokenFile`) —
|
|
61
|
+
* it is never treated as "absent", because writing over it would destroy
|
|
62
|
+
* whatever occupies the path and mint a token that locks out every client
|
|
63
|
+
* already paired with the running one.
|
|
17
64
|
*/
|
|
18
65
|
export function loadOrCreateToken(tokenPath: string): string {
|
|
19
66
|
if (existsSync(tokenPath)) {
|
|
20
|
-
return
|
|
67
|
+
return readTokenFile(tokenPath)
|
|
21
68
|
}
|
|
22
69
|
|
|
23
70
|
const token = generateToken()
|
|
@@ -63,7 +110,7 @@ export function rotateToken(tokenPath: string): string {
|
|
|
63
110
|
*/
|
|
64
111
|
export function listTokens(tokenPath: string): string[] {
|
|
65
112
|
if (!existsSync(tokenPath)) return []
|
|
66
|
-
const token =
|
|
113
|
+
const token = readTokenFile(tokenPath)
|
|
67
114
|
return token ? [token] : []
|
|
68
115
|
}
|
|
69
116
|
|
|
@@ -20,6 +20,58 @@ export interface FeishuAdapter {
|
|
|
20
20
|
isAllowed(openId: string): boolean
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
+
/**
|
|
24
|
+
* 单次请求体上限。Feishu 事件体在 KB 量级,256 KiB 已是两个数量级的余量。
|
|
25
|
+
*
|
|
26
|
+
* 为什么必须在**解析之前**封顶:`handleEvent` 从前直接 `await request.json()`,
|
|
27
|
+
* 而签名校验发生在**解析之后** —— 于是拒绝的代价由被拒方转嫁给了守护进程:
|
|
28
|
+
* 未鉴权的调用方可以先让它吞下整个体(Bun 默认 `maxRequestBodySize` = 128 MB,
|
|
29
|
+
* 实测 127 MB 通过 / 140 MB 才 413),再拿到那句 400。限流(`server.ts`)管的是
|
|
30
|
+
* **频次**,这里管的是**单次成本**,两道各管一件事。
|
|
31
|
+
*/
|
|
32
|
+
const MAX_BODY_BYTES = 256 * 1024
|
|
33
|
+
|
|
34
|
+
type BoundedBody = { ok: true; text: string } | { ok: false }
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 读取请求体,超过 `MAX_BODY_BYTES` 即中止并返回 `ok: false`。
|
|
38
|
+
*
|
|
39
|
+
* 按**流式累计**封顶而非只看 `Content-Length`:声明可以缺席(chunked)也可以撒谎,
|
|
40
|
+
* 只有累计读数才是真判据;`Content-Length` 只用作廉价的第一道,免得把一个自报
|
|
41
|
+
* 超限的体读进来再发现。
|
|
42
|
+
*/
|
|
43
|
+
async function readBoundedBody(request: Request): Promise<BoundedBody> {
|
|
44
|
+
const declared = Number(request.headers.get('content-length'))
|
|
45
|
+
if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) return { ok: false }
|
|
46
|
+
|
|
47
|
+
const stream = request.body
|
|
48
|
+
if (!stream) return { ok: true, text: '' }
|
|
49
|
+
|
|
50
|
+
const reader = stream.getReader()
|
|
51
|
+
const chunks: Uint8Array[] = []
|
|
52
|
+
let total = 0
|
|
53
|
+
for (;;) {
|
|
54
|
+
const { done, value } = await reader.read()
|
|
55
|
+
if (done) break
|
|
56
|
+
total += value.byteLength
|
|
57
|
+
if (total > MAX_BODY_BYTES) {
|
|
58
|
+
await reader.cancel().catch(() => {
|
|
59
|
+
/* 中止流的失败不影响本次拒绝 */
|
|
60
|
+
})
|
|
61
|
+
return { ok: false }
|
|
62
|
+
}
|
|
63
|
+
chunks.push(value)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const buf = new Uint8Array(total)
|
|
67
|
+
let offset = 0
|
|
68
|
+
for (const chunk of chunks) {
|
|
69
|
+
buf.set(chunk, offset)
|
|
70
|
+
offset += chunk.byteLength
|
|
71
|
+
}
|
|
72
|
+
return { ok: true, text: new TextDecoder().decode(buf) }
|
|
73
|
+
}
|
|
74
|
+
|
|
23
75
|
export function createFeishuAdapter(config: FeishuConfig, deps: FeishuAdapterDeps): FeishuAdapter {
|
|
24
76
|
const api = createFeishuApi(config)
|
|
25
77
|
const allowed = new Set(config.allowedOpenIds)
|
|
@@ -47,9 +99,13 @@ export function createFeishuAdapter(config: FeishuConfig, deps: FeishuAdapterDep
|
|
|
47
99
|
return {
|
|
48
100
|
isAllowed: (openId) => allowed.has(openId),
|
|
49
101
|
async handleEvent(request: Request): Promise<Response> {
|
|
102
|
+
const bounded = await readBoundedBody(request)
|
|
103
|
+
if (!bounded.ok) {
|
|
104
|
+
return Response.json({ code: 1, msg: 'payload_too_large' }, { status: 413 })
|
|
105
|
+
}
|
|
50
106
|
let body: unknown = {}
|
|
51
107
|
try {
|
|
52
|
-
body =
|
|
108
|
+
body = JSON.parse(bounded.text)
|
|
53
109
|
} catch {
|
|
54
110
|
/* 非 JSON body 容忍 */
|
|
55
111
|
}
|
package/src/daemon/server.ts
CHANGED
|
@@ -428,19 +428,12 @@ export function createServer(config: ServerConfig): Server<WsData> {
|
|
|
428
428
|
const method = req.method
|
|
429
429
|
logger.info('request', { method, path })
|
|
430
430
|
|
|
431
|
-
// ── Feishu event callback(独立签名验证,不经过 daemon Bearer 鉴权)──
|
|
432
|
-
if (feishuAdapter && method === 'POST' && path === '/feishu/event') {
|
|
433
|
-
return await feishuAdapter.handleEvent(req)
|
|
434
|
-
}
|
|
435
|
-
|
|
436
|
-
// ── Origin gate ─────────────────────────────────
|
|
437
|
-
// Runs before the WebSocket upgrade below, which is what makes the
|
|
438
|
-
// upgrade path covered by it: browsers attach Origin to a WS handshake
|
|
439
|
-
// but never block the connection themselves.
|
|
440
|
-
const originError = originMiddleware(req)
|
|
441
|
-
if (originError) return originError
|
|
442
|
-
|
|
443
431
|
// ── Rate limiting (skip health endpoint) ──────────
|
|
432
|
+
// Ahead of every route below, the Feishu callback included: a signed
|
|
433
|
+
// caller is an authenticated caller, not an unmetered one. This block
|
|
434
|
+
// used to sit *after* the callback's early return, which left that one
|
|
435
|
+
// path uncounted (F3-1) — the signature gates whether a request is
|
|
436
|
+
// processed, never how many arrive.
|
|
444
437
|
if (path !== '/api/v1/health') {
|
|
445
438
|
const ip = server.requestIP(req)?.address || 'unknown'
|
|
446
439
|
const rl = rateLimiter.check(ip)
|
|
@@ -452,6 +445,25 @@ export function createServer(config: ServerConfig): Server<WsData> {
|
|
|
452
445
|
}
|
|
453
446
|
}
|
|
454
447
|
|
|
448
|
+
// ── Feishu event callback(独立签名验证,不经过 daemon Bearer 鉴权)──
|
|
449
|
+
// Deliberately above the origin gate and below the rate limiter. Its gate
|
|
450
|
+
// is the lark signature — parseFeishuEnv is fail-closed on encryptKey,
|
|
451
|
+
// precisely because the SDK's signature check returns true when that key
|
|
452
|
+
// is empty — and its caller is a server, not a browser page. So the two
|
|
453
|
+
// middlewares split: metering applies (above), Origin does not.
|
|
454
|
+
// Keep this branch below the rate-limit block; hoisting it back up
|
|
455
|
+
// re-opens F3-1.
|
|
456
|
+
if (feishuAdapter && method === 'POST' && path === '/feishu/event') {
|
|
457
|
+
return await feishuAdapter.handleEvent(req)
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
// ── Origin gate ─────────────────────────────────
|
|
461
|
+
// Runs before the WebSocket upgrade below, which is what makes the
|
|
462
|
+
// upgrade path covered by it: browsers attach Origin to a WS handshake
|
|
463
|
+
// but never block the connection themselves.
|
|
464
|
+
const originError = originMiddleware(req)
|
|
465
|
+
if (originError) return originError
|
|
466
|
+
|
|
455
467
|
// ── Auth check ──────────────────────────────────
|
|
456
468
|
const authError = authMiddleware(req, activeToken, server.requestIP(req)?.address)
|
|
457
469
|
if (authError) return addCorsHeaders(authError, req)
|
package/src/index.tsx
CHANGED
|
@@ -295,12 +295,17 @@ async function connectMcpServers(
|
|
|
295
295
|
const mcp = McpClient.getInstance()
|
|
296
296
|
// Wire runtime tool-list changes before connect so mid-connect updates land.
|
|
297
297
|
syncMcpToolsOnChange(mcp, tools)
|
|
298
|
+
let registeredServers = 0
|
|
299
|
+
let registeredTools = 0
|
|
298
300
|
const results = await Promise.allSettled(
|
|
299
301
|
mcpServers.map(async (server) => {
|
|
300
302
|
await mcp.connect(server)
|
|
301
303
|
const count = registerMcpServerTools(server.name, tools)
|
|
304
|
+
// Same `count > 0` test that used to gate the per-server line, so the total
|
|
305
|
+
// counts exactly the servers that would have spoken before.
|
|
302
306
|
if (count > 0) {
|
|
303
|
-
|
|
307
|
+
registeredServers++
|
|
308
|
+
registeredTools += count
|
|
304
309
|
}
|
|
305
310
|
}),
|
|
306
311
|
)
|
|
@@ -314,6 +319,12 @@ async function connectMcpServers(
|
|
|
314
319
|
console.error(`[mcp] Failed to connect "${name}": ${reason}`)
|
|
315
320
|
}
|
|
316
321
|
}
|
|
322
|
+
// One line for the batch, not one per server: with five configured servers this
|
|
323
|
+
// was five lines of scrollback before the TUI ever drew. The quiet path is the
|
|
324
|
+
// one with nothing to report — each failure still speaks for itself, above.
|
|
325
|
+
if (registeredServers > 0) {
|
|
326
|
+
console.log(`[mcp] ${registeredServers} server(s), ${registeredTools} tools registered`)
|
|
327
|
+
}
|
|
317
328
|
return failures
|
|
318
329
|
}
|
|
319
330
|
|
|
@@ -440,6 +451,15 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
440
451
|
` (a repository must not choose the approval gate — set it in ${settingsPathFor('user', process.cwd())})\n`,
|
|
441
452
|
)
|
|
442
453
|
}
|
|
454
|
+
// Same reason, same file, one key over: an allow rule is the approval gate for
|
|
455
|
+
// the tools it names, and without a configured `maxAllowedMode` there is
|
|
456
|
+
// nothing bounding how far it reaches.
|
|
457
|
+
if (settingsJson.projectAllowSkipped) {
|
|
458
|
+
process.stderr.write(
|
|
459
|
+
`⚠ Mipham Code: ignored permissions.allow from ${settingsPathFor('project', process.cwd())}\n` +
|
|
460
|
+
` (an allow rule widens the gate — move the rules to ${settingsPathFor('user', process.cwd())})\n`,
|
|
461
|
+
)
|
|
462
|
+
}
|
|
443
463
|
// Apply org-level permission restrictions (P0: bypassPermissions policy gap)
|
|
444
464
|
if (config.permissionRestrictions) {
|
|
445
465
|
permission.setRestrictions(config.permissionRestrictions)
|
|
@@ -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.9' 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 =
|
|
78
|
+
export const SLASH_COMMAND_COUNT = 138 as const
|
|
79
79
|
|
|
80
80
|
/** 内置提供商总数(真源:`DEFAULT_PROVIDERS.length`,`apps/cli/src/shared/constants.ts`) */
|
|
81
81
|
export const PROVIDER_COUNT = 12 as const
|
|
@@ -90,4 +90,4 @@ export const TOOL_COUNT = 31 as const
|
|
|
90
90
|
* —— `test/e2e/full-pipeline.test.ts` 在 Linux 上整文件 skip、在 macOS 上跑 ——
|
|
91
91
|
* 但**总数相同**(两边都把被 skip 的算进去)。
|
|
92
92
|
*/
|
|
93
|
-
export const TEST_COUNT =
|
|
93
|
+
export const TEST_COUNT = 3696 as const
|
package/src/telemetry/consent.ts
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto'
|
|
2
|
-
import {
|
|
2
|
+
import {
|
|
3
|
+
readSettingsDoc,
|
|
4
|
+
writeSettingsDoc,
|
|
5
|
+
settingsPathFor,
|
|
6
|
+
projectFilePath,
|
|
7
|
+
} from '../config/loader'
|
|
3
8
|
import { resolveEndpoint, type EndpointSource } from './endpoint'
|
|
4
9
|
import { miphamHome } from '../core/paths.ts'
|
|
5
10
|
|
|
@@ -134,6 +139,11 @@ export function readTelemetrySettings(
|
|
|
134
139
|
* persistent, deliberate act (the first-run prompt or `/telemetry on`) — env
|
|
135
140
|
* vars are inherited by child processes and end up in CI logs, so they must not
|
|
136
141
|
* be a channel for consent-by-proxy.
|
|
142
|
+
*
|
|
143
|
+
* **There is no tier 3 at all when running from `~`.** There the project path and
|
|
144
|
+
* the user path name the same file, so applying tier 3 would withhold the user's
|
|
145
|
+
* *own* consent. That case skips the read rather than re-labelling it — see
|
|
146
|
+
* `projectFilePath`.
|
|
137
147
|
*/
|
|
138
148
|
export function resolveTelemetry(
|
|
139
149
|
cwd: string = process.cwd(),
|
|
@@ -152,7 +162,13 @@ export function resolveTelemetry(
|
|
|
152
162
|
}
|
|
153
163
|
|
|
154
164
|
const user = readTelemetrySettings('user', cwd)
|
|
155
|
-
|
|
165
|
+
// Absent — not "read and hollowed out" — when the project scope *is* the user
|
|
166
|
+
// scope, i.e. the CLI is running from the home directory itself (see
|
|
167
|
+
// `projectFilePath`). Reading it anyway would file the user's own opt-in as a
|
|
168
|
+
// repository declaration: withheld here, and then named back to them in the
|
|
169
|
+
// warning as the very file to go set it in.
|
|
170
|
+
const project =
|
|
171
|
+
projectFilePath('settings.json', cwd) === null ? {} : readTelemetrySettings('project', cwd)
|
|
156
172
|
const { endpoint, source: endpointSource } = resolveEndpoint(user.endpoint, env)
|
|
157
173
|
const ignoredProjectKeys = declaredProjectKeys(project)
|
|
158
174
|
|
package/src/tools/index.ts
CHANGED
|
@@ -21,7 +21,7 @@ import { memoryTool } from './agent/memory'
|
|
|
21
21
|
import { workflowTool } from './agent/workflow'
|
|
22
22
|
import { webFetchTool } from './network/web-fetch'
|
|
23
23
|
import { webSearchTool } from './network/web-search'
|
|
24
|
-
import {
|
|
24
|
+
import { configToolService } from './system/config'
|
|
25
25
|
import { mcpTool } from './system/mcp'
|
|
26
26
|
import { toolSearchTool } from './system/tool-search'
|
|
27
27
|
import { artifactTool } from './artifact/artifact'
|
|
@@ -77,7 +77,6 @@ export function createToolRegistry(
|
|
|
77
77
|
webFetchTool,
|
|
78
78
|
webSearchTool,
|
|
79
79
|
// System tools
|
|
80
|
-
configTool,
|
|
81
80
|
mcpTool,
|
|
82
81
|
toolSearchTool,
|
|
83
82
|
// Artifact tools
|
|
@@ -93,11 +92,14 @@ export function createToolRegistry(
|
|
|
93
92
|
for (const tool of plainTools) {
|
|
94
93
|
ctx.mount(toolService(withValidation(tool)))
|
|
95
94
|
}
|
|
96
|
-
// 注入工具(credentials 依赖):read + bash + grep + glob
|
|
95
|
+
// 注入工具(credentials 依赖):read + bash + grep + glob + config
|
|
96
|
+
// Config 也在这条线上:它吐出来的正是 `config.yml` 本体,而那份文件里放着
|
|
97
|
+
// provider 的 apiKey、MCP server 的 env、inference hook 的 signing_secret。
|
|
97
98
|
ctx.mount(readToolService)
|
|
98
99
|
ctx.mount(bashToolService)
|
|
99
100
|
ctx.mount(grepToolService)
|
|
100
101
|
ctx.mount(globToolService)
|
|
102
|
+
ctx.mount(configToolService)
|
|
101
103
|
|
|
102
104
|
return collectTools(ctx)
|
|
103
105
|
}
|
|
@@ -2,72 +2,139 @@ import { readFileSync, existsSync, mkdirSync } from 'node:fs'
|
|
|
2
2
|
import { join } from 'node:path'
|
|
3
3
|
import { parse as parseYaml, stringify } from 'yaml'
|
|
4
4
|
import { atomicWriteFileSync } from '../../shared/atomic-write'
|
|
5
|
-
import
|
|
5
|
+
import { ENC_PREFIX, encryptApiKey, getCredentialKey } from '../../config/credential-crypto'
|
|
6
|
+
import { DEFAULT_CREDENTIAL_MASKING_CONFIG } from '../../config/defaults'
|
|
7
|
+
import { maskOutput } from '../../core/credential-masker'
|
|
8
|
+
import type { ToolDefinition, CredentialMaskingConfig } from '../../shared/index.ts'
|
|
9
|
+
import type { Service } from '../../vajra'
|
|
10
|
+
import { withValidation } from '../validation'
|
|
11
|
+
import { toolKey } from '../seam'
|
|
6
12
|
import { miphamHome } from '../../core/paths.ts'
|
|
7
13
|
|
|
8
14
|
const MIPHAM_HOME = miphamHome()
|
|
9
15
|
const USER_CONFIG = join(MIPHAM_HOME, 'config.yml')
|
|
10
16
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
17
|
+
/**
|
|
18
|
+
* 读路径的出口唯一:任何离开本工具的配置文本都过一遍现有的 `maskOutput`。
|
|
19
|
+
*
|
|
20
|
+
* `config.yml` 的用途之一就是放凭据(provider 的 `apiKey`、MCP server 的 env /
|
|
21
|
+
* headers、inference hook 的 `signing_secret`),而这份输出会进模型上下文、会话日志,
|
|
22
|
+
* 并随之后每一轮请求发往提供商 —— 与 Bash / Read / Grep / Glob 四条同一条通道,
|
|
23
|
+
* 于是也该用同一个函数擦洗。「什么算秘密」只有 `output_scrubbing` 那一处定义,
|
|
24
|
+
* 在这里重写一遍必然与它分叉(F1-2 的教训)。
|
|
25
|
+
*
|
|
26
|
+
* 默认值方向与那四条**相反**:无参构造时取默认掩码策略,而不是「没给就关掉」。
|
|
27
|
+
* 它们默认不遮是因为它们的输出是**别人的**文件与命令输出;本条吐出来的正是凭据
|
|
28
|
+
* 仓库本体,方向只能往「遮」那一侧倒。
|
|
29
|
+
*/
|
|
30
|
+
export function createConfigTool(
|
|
31
|
+
credentialConfig: CredentialMaskingConfig = DEFAULT_CREDENTIAL_MASKING_CONFIG,
|
|
32
|
+
): ToolDefinition {
|
|
33
|
+
return {
|
|
34
|
+
name: 'Config',
|
|
35
|
+
description: 'Read or update Mipham Code configuration.',
|
|
36
|
+
category: 'system',
|
|
37
|
+
permission: 'ask',
|
|
38
|
+
parameters: {
|
|
39
|
+
type: 'object',
|
|
40
|
+
properties: {
|
|
41
|
+
action: {
|
|
42
|
+
type: 'string',
|
|
43
|
+
enum: ['get', 'set', 'list'],
|
|
44
|
+
description: 'Action to perform',
|
|
45
|
+
},
|
|
46
|
+
key: { type: 'string', description: 'Config key (dot notation)' },
|
|
47
|
+
value: { type: 'string', description: 'Value to set' },
|
|
23
48
|
},
|
|
24
|
-
|
|
25
|
-
value: { type: 'string', description: 'Value to set' },
|
|
49
|
+
required: ['action'],
|
|
26
50
|
},
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
mkdirSync(MIPHAM_HOME, { recursive: true })
|
|
31
|
-
const action = params.action as string
|
|
51
|
+
async execute(params, _ctx) {
|
|
52
|
+
mkdirSync(MIPHAM_HOME, { recursive: true })
|
|
53
|
+
const action = params.action as string
|
|
32
54
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
55
|
+
let config: Record<string, unknown> = {}
|
|
56
|
+
if (existsSync(USER_CONFIG)) {
|
|
57
|
+
config = parseYaml(readFileSync(USER_CONFIG, 'utf-8')) as Record<string, unknown>
|
|
58
|
+
}
|
|
37
59
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
60
|
+
if (action === 'list') {
|
|
61
|
+
return {
|
|
62
|
+
success: true,
|
|
63
|
+
content: maskOutput(stringify(config) || '(empty config)', credentialConfig),
|
|
64
|
+
}
|
|
65
|
+
}
|
|
41
66
|
|
|
42
|
-
|
|
43
|
-
|
|
67
|
+
const key = params.key as string
|
|
68
|
+
if (!key) return { success: false, content: '', error: 'key is required for get/set' }
|
|
44
69
|
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
70
|
+
if (action === 'get') {
|
|
71
|
+
const value = key.split('.').reduce((obj: unknown, k) => {
|
|
72
|
+
if (obj && typeof obj === 'object') {
|
|
73
|
+
return (obj as Record<string, unknown>)[k]
|
|
74
|
+
}
|
|
75
|
+
return undefined
|
|
76
|
+
}, config)
|
|
77
|
+
// 键不存在时说清楚。原来 `JSON.stringify(undefined)` 返回的**不是字符串**而是
|
|
78
|
+
// `undefined` 本身(违反本字段的 `string` 类型);换成 YAML 之后同一情形会渲染
|
|
79
|
+
// 成 `{}` —— 一个**看着像空对象**的答案,比原来更糟。两种都是静默失败。
|
|
80
|
+
if (value === undefined) {
|
|
81
|
+
return { success: false, content: '', error: `Key not found: ${key}` }
|
|
49
82
|
}
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
83
|
+
// 擦洗按**名字**认(`apiKey` / `token` / `secret`…),而裸值的 JSON 里没有名字
|
|
84
|
+
// —— `get providers.0.apiKey` 会原样吐出密文、`get daemon.token` 会原样吐出
|
|
85
|
+
// 明文。改成 `key: value`(与 `list` 同一形状),同一个函数才看得见它。
|
|
86
|
+
return { success: true, content: maskOutput(stringify({ [key]: value }), credentialConfig) }
|
|
87
|
+
}
|
|
54
88
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
89
|
+
if (action === 'set') {
|
|
90
|
+
const keys = key.split('.')
|
|
91
|
+
let obj: Record<string, unknown> = config
|
|
92
|
+
for (let i = 0; i < keys.length - 1; i++) {
|
|
93
|
+
const k = keys[i]!
|
|
94
|
+
if (!obj[k]) obj[k] = {}
|
|
95
|
+
obj = obj[k] as Record<string, unknown>
|
|
96
|
+
}
|
|
97
|
+
const last = keys[keys.length - 1]!
|
|
98
|
+
let value = params.value
|
|
99
|
+
// provider 的 apiKey 是凭据,而**读**侧早已把 `enc:v1:` 当成它的 at-rest 形态
|
|
100
|
+
// (`loadConfig` → `decryptProviderApiKeys`、`getProviderApiKey`)。写侧却有两条路写
|
|
101
|
+
// **同一份**文件 —— `saveProviderApiKey`(加密)与这里(不加密)—— 于是「密钥在盘上
|
|
102
|
+
// 是密文」这条保证取决于用户从哪个写者进来,从这里进来的那份**静默降级**为明文。
|
|
103
|
+
// 这里复用 `encryptApiKey` 本身,而不是重写一遍它的判断:什么算秘密(空值与 env 模板
|
|
104
|
+
// 放行)只有一个定义,两份判断迟早分叉。调用侧只补它没有的那一条 —— 已加密的不再套
|
|
105
|
+
// 一层(套两层不报错,只会让读侧解出一段密文,报错还指向别处)。
|
|
106
|
+
if (
|
|
107
|
+
keys.length === 3 &&
|
|
108
|
+
keys[0] === 'providers' &&
|
|
109
|
+
last === 'apiKey' &&
|
|
110
|
+
typeof value === 'string' &&
|
|
111
|
+
!value.startsWith(ENC_PREFIX)
|
|
112
|
+
) {
|
|
113
|
+
value = encryptApiKey(value, getCredentialKey(MIPHAM_HOME))
|
|
114
|
+
}
|
|
115
|
+
obj[last] = value
|
|
116
|
+
// 原子写 + 0o600:这是整份 read-modify-write,裸 writeFileSync 原地截断 ——
|
|
117
|
+
// 崩在写中途就留下半截 YAML,而权限由 umask 决定(典型 0644),比同一份配置的
|
|
118
|
+
// 另一个写者 saveProviderApiKey(loader.ts,0600 原子写)更松。
|
|
119
|
+
atomicWriteFileSync(USER_CONFIG, stringify(config), { mode: 0o600 })
|
|
120
|
+
// 回显**落盘的那个值**的形态,不由路径猜:env 模板与空值走的是同一条路,却明文落盘,
|
|
121
|
+
// 按路径断言会把它说成「已加密」。密钥本身不回显 —— 它已经在写它的那次调用里了。
|
|
122
|
+
const atRest = typeof value === 'string' && value.startsWith(ENC_PREFIX)
|
|
123
|
+
return {
|
|
124
|
+
success: true,
|
|
125
|
+
content: atRest ? `Set ${key} (encrypted at rest)` : `Set ${key} = ${params.value}`,
|
|
126
|
+
}
|
|
62
127
|
}
|
|
63
|
-
obj[keys[keys.length - 1]!] = params.value
|
|
64
|
-
// 原子写 + 0o600:这是整份 read-modify-write,裸 writeFileSync 原地截断 ——
|
|
65
|
-
// 崩在写中途就留下半截 YAML,而权限由 umask 决定(典型 0644),比同一份配置的
|
|
66
|
-
// 另一个写者 saveProviderApiKey(loader.ts,0600 原子写)更松。
|
|
67
|
-
atomicWriteFileSync(USER_CONFIG, stringify(config), { mode: 0o600 })
|
|
68
|
-
return { success: true, content: `Set ${key} = ${params.value}` }
|
|
69
|
-
}
|
|
70
128
|
|
|
71
|
-
|
|
129
|
+
return { success: false, content: '', error: `Unknown action: ${action}` }
|
|
130
|
+
},
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export const configToolService: Service = {
|
|
135
|
+
inject: ['credentials'],
|
|
136
|
+
apply(ctx) {
|
|
137
|
+
const credentialConfig = ctx.get<CredentialMaskingConfig>('credentials')
|
|
138
|
+
ctx.provide(toolKey('Config'), withValidation(createConfigTool(credentialConfig)))
|
|
72
139
|
},
|
|
73
140
|
}
|
package/src/ui/app.tsx
CHANGED
|
@@ -276,9 +276,15 @@ export function App({
|
|
|
276
276
|
const [inputHistory, setInputHistory] = useState<string[]>([])
|
|
277
277
|
const [updateStatus, setUpdateStatus] = useState<UpdateStatus | null>(null)
|
|
278
278
|
// Current git branch — read once at mount (not a git repo → null).
|
|
279
|
+
// `stdio` 显式给:默认下 git 的 stderr 是继承的,「不是仓库」这个正常路径会把
|
|
280
|
+
// `fatal:` 漏到终端上(与 `core/instructions.ts` 的 `gitRoot` 同一件事)。
|
|
281
|
+
// stdout 仍须是管道,否则读到的永远是空串 —— 分支名直接消失,且不报错。
|
|
279
282
|
const [gitBranch] = useState<string | null>(() => {
|
|
280
283
|
try {
|
|
281
|
-
const b = execSync('git branch --show-current', {
|
|
284
|
+
const b = execSync('git branch --show-current', {
|
|
285
|
+
encoding: 'utf-8',
|
|
286
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
287
|
+
}).trim()
|
|
282
288
|
return b || null
|
|
283
289
|
} catch {
|
|
284
290
|
return null
|
package/src/ui/commands.ts
CHANGED
|
@@ -34,7 +34,11 @@ import {
|
|
|
34
34
|
appendProseProposal,
|
|
35
35
|
clearProseProposals,
|
|
36
36
|
loadAlwaysOnLessonsBlock,
|
|
37
|
+
buildResidentLessonReport,
|
|
38
|
+
extractCrsiLessonSummaries,
|
|
39
|
+
selectResidentLessons,
|
|
37
40
|
formatNetChange,
|
|
41
|
+
formatSeverityShift,
|
|
38
42
|
LESSONS_FILE,
|
|
39
43
|
MANAGED_RULES_FILE,
|
|
40
44
|
} from '../core/crsi-producer'
|
|
@@ -1162,10 +1166,15 @@ const crsiProposeCmd: CommandHandler = async (ctx, args) => {
|
|
|
1162
1166
|
return { content: `❌ 合并失败(phase: ${result.phase})。\n${result.error ?? ''}` }
|
|
1163
1167
|
}
|
|
1164
1168
|
|
|
1169
|
+
// 档位迁移:**只呈现、不判定**,与 ε 命中 / 代价 / 事前风险 / 净变化同一纪律
|
|
1170
|
+
//(见 crsi-producer.ts 的 formatSeverityShift)。落点在**人类真正做决定的那一刻** ——
|
|
1171
|
+
// 紧挨着它描述的那份 diff。恒打(含无变化):「这次没把一条非常驻的教训变成常驻」
|
|
1172
|
+
// 正是那条可证伪的基线读数,只打有变化的等于让读者看不见基线。
|
|
1165
1173
|
return {
|
|
1166
1174
|
content:
|
|
1167
1175
|
`✅ 已生成合并教训并跑过测试。审阅 diff:\n` +
|
|
1168
1176
|
renderGateNote(result) +
|
|
1177
|
+
`${formatSeverityShift(proposal.severityA, proposal.severityB, proposal.mergedSeverity)}\n` +
|
|
1169
1178
|
`\n${result.diff}\n\n` +
|
|
1170
1179
|
'/crsi modify --approve 合并 | /crsi modify --reject 丢弃',
|
|
1171
1180
|
}
|
|
@@ -1309,6 +1318,45 @@ const crsiProseClearCmd: CommandHandler = () => {
|
|
|
1309
1318
|
return { content: `已清空散文提议 ledger(移除 ${count} 条记录)。` }
|
|
1310
1319
|
}
|
|
1311
1320
|
|
|
1321
|
+
/**
|
|
1322
|
+
* `/crsi lessons` —— 常驻档名册(只读)。
|
|
1323
|
+
*
|
|
1324
|
+
* 这是 `selectResidentLessons` 唯一**给人看**的读者。另两个(系统提示、`--prose` 算子)
|
|
1325
|
+
* 的输出都只进模型的上下文;而常驻档的成本是**人**在付(每条 critical 随每次请求发出),
|
|
1326
|
+
* 能动手降档、缩短的也只有人。没有它,「这档涨得值不值」没有材料可查。
|
|
1327
|
+
*
|
|
1328
|
+
* 读的是**当前磁盘上的文件**(不是启动时那份快照):刚改完 `- 严重度:` 就该看到新名册。
|
|
1329
|
+
*/
|
|
1330
|
+
const crsiLessonsCmd: CommandHandler = async () => {
|
|
1331
|
+
// 目标文件按仓库根解析 —— 与 `/crsi propose` 同一口径(那里的 filePath 是仓库根相对)
|
|
1332
|
+
let root = process.cwd()
|
|
1333
|
+
try {
|
|
1334
|
+
root = execSync('git rev-parse --show-toplevel', {
|
|
1335
|
+
timeout: 5000,
|
|
1336
|
+
encoding: 'utf-8',
|
|
1337
|
+
}).trim()
|
|
1338
|
+
} catch {
|
|
1339
|
+
// 非 git 目录 → 回退 cwd
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
const { readFileSync, existsSync } = await import('node:fs')
|
|
1343
|
+
const { join } = await import('node:path')
|
|
1344
|
+
const lessonsPath = join(root, LESSONS_FILE)
|
|
1345
|
+
if (!existsSync(lessonsPath)) {
|
|
1346
|
+
return { content: `教训文件不存在:${lessonsPath}` }
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1349
|
+
let summaries
|
|
1350
|
+
try {
|
|
1351
|
+
summaries = extractCrsiLessonSummaries(readFileSync(lessonsPath, 'utf-8'))
|
|
1352
|
+
} catch (e) {
|
|
1353
|
+
return { content: `教训文件读取失败:${lessonsPath}\n${String(e)}` }
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1356
|
+
// 择点与两个已有读者同一个 ⇒ 名册报的就是这条会话真正会注入的那一份
|
|
1357
|
+
return { content: buildResidentLessonReport(selectResidentLessons(summaries), lessonsPath) }
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1312
1360
|
const crsiHealthCmd: CommandHandler = async (ctx) => {
|
|
1313
1361
|
const engine = ctx.engine.getRuleEngine()
|
|
1314
1362
|
const tracker = ctx.engine.getEffectivenessTracker()
|
|
@@ -5854,6 +5902,7 @@ registry.set('/crsi inventory', crsiInventoryCmd)
|
|
|
5854
5902
|
registry.set('/crsi modify', crsiModifyCmd)
|
|
5855
5903
|
registry.set('/crsi propose', crsiProposeCmd)
|
|
5856
5904
|
registry.set('/crsi prose-clear', crsiProseClearCmd)
|
|
5905
|
+
registry.set('/crsi lessons', crsiLessonsCmd)
|
|
5857
5906
|
registry.set('/crsi eval', crsiEvalCmd)
|
|
5858
5907
|
registry.set('/crsi bench', crsiBenchCmd)
|
|
5859
5908
|
registry.set('/crsi meta', crsiMetaCmd)
|