@miphamai/cli 0.85.8 → 0.85.10
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 +341 -29
- package/src/core/engine.ts +54 -0
- package/src/core/eval-harness.ts +13 -4
- package/src/core/instructions.ts +35 -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 +27 -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/core/instructions.ts
CHANGED
|
@@ -9,7 +9,8 @@ import {
|
|
|
9
9
|
extractCrsiLessonSummaries,
|
|
10
10
|
buildCrsiLessonsBlock,
|
|
11
11
|
buildCrsiLessonsPointer,
|
|
12
|
-
|
|
12
|
+
buildLessonRevisitNudge,
|
|
13
|
+
selectResidentLessons,
|
|
13
14
|
type CrsiLessonSummary,
|
|
14
15
|
} from './crsi-producer'
|
|
15
16
|
import { miphamHome } from './paths.ts'
|
|
@@ -62,13 +63,21 @@ export function parsePromptExclude(value: unknown): string[] {
|
|
|
62
63
|
return []
|
|
63
64
|
}
|
|
64
65
|
|
|
65
|
-
/**
|
|
66
|
+
/**
|
|
67
|
+
* 定位仓库根(git rev-parse --show-toplevel),非 git 目录回退 cwd。
|
|
68
|
+
*
|
|
69
|
+
* `stdio` 必须显式给:默认下子进程的 stderr 是**继承**的,于是「不是 git 仓库」这个
|
|
70
|
+
* **正常路径**会把 git 的 `fatal: not a git repository` 直接漏到终端上(从 `~` 启动
|
|
71
|
+
* 就能看见)。但 stdout 仍须是管道 —— 换成 `'ignore'`(`commands.ts` 里那种 stdout
|
|
72
|
+
* 不用的形状)会让这里永远拿到空串、永远回退 cwd,**连在仓库里都失效**。
|
|
73
|
+
*/
|
|
66
74
|
export function gitRoot(cwd: string): string {
|
|
67
75
|
try {
|
|
68
76
|
return execSync('git rev-parse --show-toplevel', {
|
|
69
77
|
cwd,
|
|
70
78
|
timeout: 5000,
|
|
71
79
|
encoding: 'utf-8',
|
|
80
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
72
81
|
}).trim()
|
|
73
82
|
} catch {
|
|
74
83
|
return cwd
|
|
@@ -457,18 +466,39 @@ Never omit it or present the work as purely human-authored.`)
|
|
|
457
466
|
* 分档:`critical` 常驻全文,`warning` 移出常驻块、只留一行指针指向文件。
|
|
458
467
|
* 指针保证移出去的那些仍有真实召回入口,不是被无声丢弃 —— 这正是不分档
|
|
459
468
|
* 与「删掉 warning」的区别。
|
|
469
|
+
*
|
|
470
|
+
* 常驻档还受 `RESIDENT_LESSONS_BUDGET` 约束,超出的 critical 与 warning 同样
|
|
471
|
+
* 落进指针(并在指针里被点名)—— 择点走 `selectResidentLessons`,与
|
|
472
|
+
* `loadAlwaysOnLessonsBlock` 是同一个。
|
|
460
473
|
*/
|
|
461
474
|
private crsiLessonsText(): string {
|
|
462
475
|
if (!this.lessonsPath) return ''
|
|
463
|
-
const
|
|
476
|
+
const selection = selectResidentLessons(this.crsiLessonSummaries)
|
|
464
477
|
return [
|
|
465
|
-
buildCrsiLessonsBlock(
|
|
466
|
-
buildCrsiLessonsPointer(
|
|
478
|
+
buildCrsiLessonsBlock(selection.resident),
|
|
479
|
+
buildCrsiLessonsPointer(selection, this.lessonsPath),
|
|
467
480
|
]
|
|
468
481
|
.filter(Boolean)
|
|
469
482
|
.join('\n\n')
|
|
470
483
|
}
|
|
471
484
|
|
|
485
|
+
/**
|
|
486
|
+
* 事件型召回扳机 —— {@link crsiLessonsText} 的姊妹件,走**同一个择点**、同一份
|
|
487
|
+
* `lessonsPath`,因此不可能与系统提示里那条指针漂移(一处说「有 33 条未常驻」、
|
|
488
|
+
* 另一处说「没有」是最坏的形状:两声哨,读者不知道信哪个)。
|
|
489
|
+
*
|
|
490
|
+
* 与 `crsiLessonsText` 的分工:那份进**系统提示**,一次生成、随每次请求发出;
|
|
491
|
+
* 这份在**工具失败**那一刻注入,只在事件上说话。没有未常驻教训时返回空串 ——
|
|
492
|
+
* 与指针同一条件,故不会出现「扳机响了但没有指针」。
|
|
493
|
+
*/
|
|
494
|
+
crsiLessonNudgeText(): string {
|
|
495
|
+
if (!this.lessonsPath) return ''
|
|
496
|
+
return buildLessonRevisitNudge(
|
|
497
|
+
selectResidentLessons(this.crsiLessonSummaries),
|
|
498
|
+
this.lessonsPath,
|
|
499
|
+
)
|
|
500
|
+
}
|
|
501
|
+
|
|
472
502
|
/**
|
|
473
503
|
* Loader-shaped alias of {@link buildPermissionBlock}(模块级那个才是实现)。
|
|
474
504
|
* 保留它是因为**已有**的调用点都握着一个装载器:`index.tsx` 的接线行与
|
|
@@ -310,6 +310,28 @@ export function clampMode(
|
|
|
310
310
|
return allowed[0] ?? 'default'
|
|
311
311
|
}
|
|
312
312
|
|
|
313
|
+
/**
|
|
314
|
+
* 从**仓库带来的** `forbiddenModes` 里挑出会造成「放宽」的条目 —— 判据是 `clampMode` 的回落。
|
|
315
|
+
*
|
|
316
|
+
* `forbiddenModes` 名义上只收窄(禁掉一档),但它有一个出口:`clampMode` 从被请求的档
|
|
317
|
+
* **向下**找落点,若「该档及其以下」全被禁就走到了底,此时回落到 `allowed[0]` ——
|
|
318
|
+
* 而那是**更宽**的一档。禁掉层级最窄的那一档(`PERMISSION_MODE_HIERARCHY[0]`)正好
|
|
319
|
+
* 制造这个情形:请求 `plan` 会拿到 `default`/`acceptEdits`/`auto`。
|
|
320
|
+
*
|
|
321
|
+
* 为什么「保住最窄那一档」就够了:任何请求档 D 向下走,最窄档 ≤ D 且被允许,
|
|
322
|
+
* 所以永远找得到落点、永远进不了那条回落分支。这是**充分**条件;而且对当前两张表
|
|
323
|
+
* (`PERMISSION_MODE_HIERARCHY` × `ALL_MODES`)它也是**必要**的 —— 穷举 32 个子集 ×
|
|
324
|
+
* 5 个请求档共 160 格,会改宽的 27 格全部且仅仅落在含 `plan` 的那 16 个子集里。
|
|
325
|
+
* 机制由 `config/loader.ts` 的「仓库带来的限制不得改宽」区间不变量实测钉住。
|
|
326
|
+
*
|
|
327
|
+
* 收的是**原始条目**(可能是别名或大小写变体):归一化只有一张表(`MODE_ALIASES`)且就在
|
|
328
|
+
* 本文件 —— 在这里复用 `normalizeModeName`,不另写判据。否则 `Plan` 会从闸门缝里滑过去,
|
|
329
|
+
* 随后被 `normalizeRestrictions` 归一成 `plan`,闸门就成了摆设。
|
|
330
|
+
*/
|
|
331
|
+
export function wideningForbiddenEntries(entries: readonly unknown[]): unknown[] {
|
|
332
|
+
return entries.filter((entry) => normalizeModeName(entry) === STRICTEST_MODE)
|
|
333
|
+
}
|
|
334
|
+
|
|
313
335
|
export function nextMode(
|
|
314
336
|
current: PermissionMode,
|
|
315
337
|
restrictions?: PermissionRestrictions,
|
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)
|
|
@@ -726,6 +746,12 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
726
746
|
// matching file. Loaded once at startup; setRulesLoader performs the load.
|
|
727
747
|
engine.setRulesLoader(new RulesLoader(process.cwd()))
|
|
728
748
|
|
|
749
|
+
// CRSI lessons recall nudge: the instruction loader is where the *pointer* to the
|
|
750
|
+
// non-resident lessons comes from, so the nudge reads its emptiness condition from
|
|
751
|
+
// the same selection rather than guessing at a path. Same loader instance that
|
|
752
|
+
// builds the system prompt above — no second copy of the lessons state.
|
|
753
|
+
engine.setInstructions(instructions)
|
|
754
|
+
|
|
729
755
|
// Wire inference hooks (DLP) configuration
|
|
730
756
|
const inferenceHookConfig = loadInferenceHookConfig()
|
|
731
757
|
engine.setInferenceHookConfig(inferenceHookConfig)
|
|
@@ -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.10' 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 = 3714 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
|
}
|