@miphamai/cli 0.85.21 → 0.85.23
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/bin/mipham.ts +19 -11
- package/package.json +1 -1
- package/src/agent/agent-context.ts +19 -6
- package/src/commands/project.ts +9 -3
- package/src/config/loader.ts +41 -0
- package/src/core/cron-poller.ts +74 -6
- package/src/core/engine.ts +20 -2
- package/src/core/hooks-config.ts +4 -0
- package/src/core/hooks-executor.ts +96 -28
- package/src/core/hooks.ts +38 -2
- package/src/core/permission-rules.ts +61 -5
- package/src/core/permission.ts +54 -6
- package/src/core/safe-mode.ts +11 -0
- package/src/core/session-exit.ts +73 -0
- package/src/core/session-log.ts +36 -1
- package/src/daemon/engine-capabilities.ts +13 -4
- package/src/daemon/launch.ts +37 -0
- package/src/daemon/server.ts +15 -1
- package/src/index.tsx +75 -27
- package/src/mcp/http-transport.ts +19 -4
- package/src/mcp/registry.ts +40 -5
- package/src/plugin/plugin-loader.ts +4 -0
- package/src/shared/package-info.ts +2 -2
- package/src/shared/types.ts +18 -0
- package/src/skills/loader.ts +45 -1
- package/src/tools/exec/exit-worktree.ts +45 -4
- package/src/tools/file/read.ts +16 -2
- package/src/tools/scheduling/cron.ts +2 -1
- package/src/tools/scheduling/schedule-wakeup.ts +20 -6
- package/src/ui/app.tsx +6 -5
- package/src/ui/commands.ts +10 -3
|
@@ -786,9 +786,21 @@ export function wildcardMatch(pattern: string, input: string): boolean {
|
|
|
786
786
|
* 能否匹配任何东西 —— `Bash(zzz *)` 合法、装得上、只是不会命中,那是用户自己的
|
|
787
787
|
* 选择,不是配置错误。
|
|
788
788
|
*
|
|
789
|
+
* `knownTools` —— 注册表里实际存在的工具名集合(可选)。给了它,裸名分支才会判
|
|
790
|
+
* **存在性**:裸名的匹配是大小写敏感的 `pattern === tool.name`,所以 `bash` / `bahs`
|
|
791
|
+
* 与 `Bash(ls) x` 是同一类**静默空防护**(语法合法、装得上、永远不命中,而用户以为
|
|
792
|
+
* 配了保护)。不给它则只判结构(拿不到注册表的调用点不凭空给存在性判决)。
|
|
793
|
+
*
|
|
794
|
+
* **`mcp__` 前缀一律放行**:MCP 服务器是后台异步连接的(`connectMcpServers`),
|
|
795
|
+
* 规则加载那一刻它们的工具还没进注册表 —— 按当时的注册表判,会把每条 mcp 规则
|
|
796
|
+
* 都误报成「未知工具」。
|
|
797
|
+
*
|
|
789
798
|
* Returns null when the pattern is valid, or a reason string when malformed.
|
|
790
799
|
*/
|
|
791
|
-
export function validateRulePattern(
|
|
800
|
+
export function validateRulePattern(
|
|
801
|
+
pattern: string,
|
|
802
|
+
knownTools?: ReadonlySet<string>,
|
|
803
|
+
): string | null {
|
|
792
804
|
if (!pattern.trim()) return 'rule pattern is empty'
|
|
793
805
|
|
|
794
806
|
if (pattern.includes('(')) {
|
|
@@ -809,17 +821,61 @@ export function validateRulePattern(pattern: string): string | null {
|
|
|
809
821
|
return null
|
|
810
822
|
}
|
|
811
823
|
|
|
824
|
+
// Whole-server MCP rules (`mcp__server`, `mcp__server__*`) are valid and are
|
|
825
|
+
// compiled as a prefix match — see `mcpServerPrefix`. Before this they either
|
|
826
|
+
// failed `^\w+$` (the wildcard form, warned as invalid) or compiled to an
|
|
827
|
+
// exact regex that could never equal `mcp__server__tool` (silent dead rule).
|
|
828
|
+
if (mcpServerPrefix(pattern)) return null
|
|
829
|
+
|
|
812
830
|
// No parenthesis → must be a plain tool name (matched via `pattern === tool.name`).
|
|
813
831
|
if (!/^\w+$/.test(pattern)) return 'not a single tool name'
|
|
832
|
+
if (knownTools && !pattern.startsWith('mcp__')) {
|
|
833
|
+
if (knownTools.has(pattern)) return null
|
|
834
|
+
// 大小写错的名字有唯一的正确写法,把它带出来 —— 拒绝消息的价值就在于照抄能用。
|
|
835
|
+
// 只在**全名大小写相等**时给建议:那是个恒等改写,不可能指错工具。更远的东西
|
|
836
|
+
// (`bahs` → `Bash`)不猜,猜错会把用户引到另一个工具上。
|
|
837
|
+
const exact = [...knownTools].find((t) => t.toLowerCase() === pattern.toLowerCase())
|
|
838
|
+
return exact
|
|
839
|
+
? `unknown tool "${pattern}" — tool names are case-sensitive; did you mean "${exact}"?`
|
|
840
|
+
: `unknown tool "${pattern}"`
|
|
841
|
+
}
|
|
814
842
|
return null
|
|
815
843
|
}
|
|
816
844
|
|
|
817
|
-
/**
|
|
818
|
-
|
|
819
|
-
|
|
845
|
+
/**
|
|
846
|
+
* Recognize an **MCP whole-server** rule and return its tool-name prefix.
|
|
847
|
+
*
|
|
848
|
+
* `mcp__server` and `mcp__server__*` both mean "every tool on that server".
|
|
849
|
+
* Full tool names (`mcp__server__tool`) are not whole-server rules and return
|
|
850
|
+
* null — they stay exact matches. Server names are lowercased because
|
|
851
|
+
* `sanitizeName` (mcp/registry.ts) lowercases them when building tool names;
|
|
852
|
+
* without this, `mcp__MyServer` would compile to a rule that can never match.
|
|
853
|
+
*/
|
|
854
|
+
export function mcpServerPrefix(pattern: string): string | null {
|
|
855
|
+
const base = pattern.endsWith('__*') ? pattern.slice(0, -3) : pattern
|
|
856
|
+
if (!base.startsWith('mcp__')) return null
|
|
857
|
+
const server = base.slice('mcp__'.length)
|
|
858
|
+
// A second `__` means this is a full tool name, not a whole-server rule.
|
|
859
|
+
if (!server || server.includes('__')) return null
|
|
860
|
+
// Same charset `sanitizeName` leaves intact (it maps everything else to `_`).
|
|
861
|
+
if (!/^[A-Za-z0-9-]+$/.test(server)) return null
|
|
862
|
+
return `mcp__${server.toLowerCase()}__`
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
/**
|
|
866
|
+
* Compile a rule pattern string into a PermissionRuleEntry.
|
|
867
|
+
*/
|
|
868
|
+
export function compileRule(
|
|
869
|
+
pattern: string,
|
|
870
|
+
level: 'allow' | 'deny' | 'ask',
|
|
871
|
+
knownTools?: ReadonlySet<string>,
|
|
872
|
+
): PermissionRuleEntry {
|
|
873
|
+
const invalid = validateRulePattern(pattern, knownTools)
|
|
874
|
+
const serverPrefix = mcpServerPrefix(pattern)
|
|
875
|
+
const source = serverPrefix ? `${serverPrefix}*` : pattern
|
|
820
876
|
const regexStr =
|
|
821
877
|
'^' +
|
|
822
|
-
|
|
878
|
+
source
|
|
823
879
|
.replace(/[.+^${}()|[\]\\*?]/g, '\\$&')
|
|
824
880
|
.replace(/:/g, '[:\\s]')
|
|
825
881
|
.replace(/\\\*/g, '.*')
|
package/src/core/permission.ts
CHANGED
|
@@ -229,6 +229,13 @@ export class PermissionSystem {
|
|
|
229
229
|
*/
|
|
230
230
|
private classifier: PermissionClassifier | undefined = undefined
|
|
231
231
|
|
|
232
|
+
/**
|
|
233
|
+
* Tool names the registry holds, for judging a plain-name rule's existence (see
|
|
234
|
+
* `setKnownTools`). Absent is a legal state: a system nobody told about the
|
|
235
|
+
* registry judges structure only, which is the behavior every caller had before.
|
|
236
|
+
*/
|
|
237
|
+
private knownTools: ReadonlySet<string> | undefined = undefined
|
|
238
|
+
|
|
232
239
|
// ── Org-level restrictions (P0 security) ──
|
|
233
240
|
private restrictions: PermissionRestrictions | undefined = undefined
|
|
234
241
|
|
|
@@ -267,6 +274,35 @@ export class PermissionSystem {
|
|
|
267
274
|
this.invalidateCache()
|
|
268
275
|
}
|
|
269
276
|
|
|
277
|
+
/**
|
|
278
|
+
* Hand in the tool names the registry actually holds, so a plain-name rule can be
|
|
279
|
+
* judged on **existence** and not just on structure. Plain names match by
|
|
280
|
+
* `pattern === tool.name` (case-sensitive), so `bash` / `bahs` load fine and match
|
|
281
|
+
* nothing — the same silent-dead-rule class as `Bash(ls) x`, and the one that
|
|
282
|
+
* reached a user's settings.json as `allow: ["bash", "bahs"]`.
|
|
283
|
+
*
|
|
284
|
+
* Must be called **before** the rules it should judge: the verdict is stamped onto
|
|
285
|
+
* each entry at compile time (`compileRule`), which is also what `getInvalidRules`
|
|
286
|
+
* reads back. `mcp__`-prefixed names are exempt inside `validateRulePattern`.
|
|
287
|
+
*
|
|
288
|
+
* Like `setClassifier`, this seam lives on the permission system rather than the
|
|
289
|
+
* engine — an engine-side setter would be a new engine capability the daemon would
|
|
290
|
+
* have to match (`test/integrity/daemon-capability-parity.test.ts`).
|
|
291
|
+
*/
|
|
292
|
+
setKnownTools(names: Iterable<string>): void {
|
|
293
|
+
this.knownTools = new Set(names)
|
|
294
|
+
this.invalidateCache()
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* The set plain-name rules are validated against, or `undefined` when nobody
|
|
299
|
+
* handed one in. Public so the `/permissions` command judges a rule against
|
|
300
|
+
* **the same set this system will match it against** instead of a second copy.
|
|
301
|
+
*/
|
|
302
|
+
getKnownTools(): ReadonlySet<string> | undefined {
|
|
303
|
+
return this.knownTools
|
|
304
|
+
}
|
|
305
|
+
|
|
270
306
|
/** Whether an `auto`-mode classifier is attached. For diagnostics, not decisions. */
|
|
271
307
|
hasClassifier(): boolean {
|
|
272
308
|
return this.classifier !== undefined
|
|
@@ -370,6 +406,14 @@ export class PermissionSystem {
|
|
|
370
406
|
subPerm.setRestrictions(this.restrictions)
|
|
371
407
|
}
|
|
372
408
|
|
|
409
|
+
// The tool set travels too, and before the rules below: the deny rules are
|
|
410
|
+
// re-added through the same compile path, so without it a rule the parent had
|
|
411
|
+
// flagged would come back as "structurally valid" and its warning would vanish
|
|
412
|
+
// by travelling — a rule silently degrading one hop down.
|
|
413
|
+
if (this.knownTools) {
|
|
414
|
+
subPerm.setKnownTools(this.knownTools)
|
|
415
|
+
}
|
|
416
|
+
|
|
373
417
|
// Propagate deny rules (org safety policies must always apply)
|
|
374
418
|
for (const denyEntry of this.denyRules) {
|
|
375
419
|
subPerm.deny(denyEntry.pattern)
|
|
@@ -460,17 +504,17 @@ export class PermissionSystem {
|
|
|
460
504
|
// ── Rule management ──
|
|
461
505
|
|
|
462
506
|
allow(rule: string): void {
|
|
463
|
-
this.allowRules.push(compileRule(rule, 'allow'))
|
|
507
|
+
this.allowRules.push(compileRule(rule, 'allow', this.knownTools))
|
|
464
508
|
this.invalidateCache()
|
|
465
509
|
}
|
|
466
510
|
|
|
467
511
|
deny(rule: string): void {
|
|
468
|
-
this.denyRules.push(compileRule(rule, 'deny'))
|
|
512
|
+
this.denyRules.push(compileRule(rule, 'deny', this.knownTools))
|
|
469
513
|
this.invalidateCache()
|
|
470
514
|
}
|
|
471
515
|
|
|
472
516
|
ask(rule: string): void {
|
|
473
|
-
this.askRules.push(compileRule(rule, 'ask'))
|
|
517
|
+
this.askRules.push(compileRule(rule, 'ask', this.knownTools))
|
|
474
518
|
this.invalidateCache()
|
|
475
519
|
}
|
|
476
520
|
|
|
@@ -501,10 +545,10 @@ export class PermissionSystem {
|
|
|
501
545
|
this.askRules = []
|
|
502
546
|
|
|
503
547
|
for (const rule of config.allow) {
|
|
504
|
-
this.allowRules.push(compileRule(rule, 'allow'))
|
|
548
|
+
this.allowRules.push(compileRule(rule, 'allow', this.knownTools))
|
|
505
549
|
}
|
|
506
550
|
for (const rule of config.deny) {
|
|
507
|
-
this.denyRules.push(compileRule(rule, 'deny'))
|
|
551
|
+
this.denyRules.push(compileRule(rule, 'deny', this.knownTools))
|
|
508
552
|
}
|
|
509
553
|
|
|
510
554
|
this.invalidateCache()
|
|
@@ -1049,7 +1093,11 @@ export class PermissionSystem {
|
|
|
1049
1093
|
} else {
|
|
1050
1094
|
const rule = toolNameOrRule
|
|
1051
1095
|
if (rule.pattern) {
|
|
1052
|
-
const entry = compileRule(
|
|
1096
|
+
const entry = compileRule(
|
|
1097
|
+
rule.pattern,
|
|
1098
|
+
rule.level === 'bypass' ? 'allow' : 'ask',
|
|
1099
|
+
this.knownTools,
|
|
1100
|
+
)
|
|
1053
1101
|
if (rule.level === 'bypass') this.allowRules.push(entry)
|
|
1054
1102
|
else this.askRules.push(entry)
|
|
1055
1103
|
} else {
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `--safe-mode` gate.
|
|
3
|
+
*
|
|
4
|
+
* Read at call time, not at import time: `bin/mipham.ts` sets
|
|
5
|
+
* `MIPHAM_SAFE_MODE=1` while parsing argv, which happens after the module
|
|
6
|
+
* graph is evaluated. Only the exact value `1` enables it — an inherited
|
|
7
|
+
* empty string or `0` must not silently disable the user's customizations.
|
|
8
|
+
*/
|
|
9
|
+
export function isSafeMode(): boolean {
|
|
10
|
+
return process.env.MIPHAM_SAFE_MODE === '1'
|
|
11
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one way out of a session.
|
|
3
|
+
*
|
|
4
|
+
* `SessionEnd` hooks are asynchronous, while `process.exit()` is immediate. The
|
|
5
|
+
* exit path used to start the hooks and call `process.exit()` in the same tick,
|
|
6
|
+
* so a hook registered for SessionEnd could never finish — and `/exit`, `/quit`
|
|
7
|
+
* and the second Ctrl+C left through `process.exit()` directly, never starting
|
|
8
|
+
* them at all. Every user-initiated exit now goes through `exitSession()`, which
|
|
9
|
+
* runs the registered shutdown callback once and then exits.
|
|
10
|
+
*
|
|
11
|
+
* The callback owns its own bounds (a session must not hang on exit); this module
|
|
12
|
+
* only guarantees ordering and that a broken callback cannot trap the user.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
let handler: (() => void | Promise<void>) | null = null
|
|
16
|
+
let exitPromise: Promise<void> | null = null
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* SessionEnd is best-effort: a hook that is slow, hung, or waiting on a server
|
|
20
|
+
* that never answers must not hold the terminal open. The caller uses this as
|
|
21
|
+
* the upper bound for the hook phase.
|
|
22
|
+
*/
|
|
23
|
+
export const SESSION_END_HOOK_TIMEOUT_MS = 1_500
|
|
24
|
+
|
|
25
|
+
export function registerExitHandler(fn: () => void | Promise<void>): void {
|
|
26
|
+
handler = fn
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Test hook — the process-global handler otherwise leaks between test files. */
|
|
30
|
+
export function resetExitHandler(): void {
|
|
31
|
+
handler = null
|
|
32
|
+
exitPromise = null
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Run `promise`, giving up after `ms`. Used to bound SessionEnd hooks without
|
|
37
|
+
* cancelling the work they may still be doing in the background.
|
|
38
|
+
*/
|
|
39
|
+
export async function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T | undefined> {
|
|
40
|
+
let timer: unknown
|
|
41
|
+
try {
|
|
42
|
+
return await Promise.race([
|
|
43
|
+
promise,
|
|
44
|
+
new Promise<undefined>((resolve) => {
|
|
45
|
+
timer = setTimeout(resolve, ms)
|
|
46
|
+
// A pending timeout must not keep a test process (or a stuck session)
|
|
47
|
+
// alive by itself. Bun's timer is a number; Node's has `unref`.
|
|
48
|
+
;(timer as { unref?: () => void }).unref?.()
|
|
49
|
+
}),
|
|
50
|
+
])
|
|
51
|
+
} finally {
|
|
52
|
+
if (timer !== undefined) clearTimeout(timer as ReturnType<typeof setTimeout>)
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Run the registered shutdown callback (once, across every caller) and exit.
|
|
58
|
+
*
|
|
59
|
+
* Concurrent or repeated calls — a signal arriving while `/exit` is already
|
|
60
|
+
* shutting down — await the same work and share the same exit.
|
|
61
|
+
*/
|
|
62
|
+
export function exitSession(code = 0): Promise<never> {
|
|
63
|
+
if (!exitPromise) {
|
|
64
|
+
exitPromise = Promise.resolve()
|
|
65
|
+
.then(() => handler?.())
|
|
66
|
+
.then(() => undefined)
|
|
67
|
+
.catch(() => {
|
|
68
|
+
// Shutdown is best effort. A callback that throws must not leave the
|
|
69
|
+
// user with a session they cannot close.
|
|
70
|
+
})
|
|
71
|
+
}
|
|
72
|
+
return exitPromise.then(() => process.exit(code))
|
|
73
|
+
}
|
package/src/core/session-log.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { mkdirSync } from 'node:fs'
|
|
1
|
+
import { mkdirSync, openSync, readSync, closeSync, statSync } from 'node:fs'
|
|
2
2
|
import { join } from 'node:path'
|
|
3
3
|
import { createHash } from 'node:crypto'
|
|
4
4
|
import type { Message, ToolUseContent, ToolResultContent, ToolResult } from '../shared/types'
|
|
@@ -150,6 +150,32 @@ function sleepSyncMs(ms: number): void {
|
|
|
150
150
|
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
|
|
151
151
|
}
|
|
152
152
|
|
|
153
|
+
/**
|
|
154
|
+
* Does the log end on a complete line (or not exist yet)?
|
|
155
|
+
*
|
|
156
|
+
* Uses stat + a one-byte read instead of `readFileSync`: the repair gate runs
|
|
157
|
+
* on every save, and a session log can be large. Non-regular paths answer
|
|
158
|
+
* `true` here — `appendRegularFileSync` is the gate that refuses those, and
|
|
159
|
+
* opening a FIFO for repair would block.
|
|
160
|
+
*/
|
|
161
|
+
function endsWithNewline(path: string): boolean {
|
|
162
|
+
try {
|
|
163
|
+
const st = statSync(path)
|
|
164
|
+
if (!st.isFile() || st.size === 0) return true
|
|
165
|
+
const fd = openSync(path, 'r')
|
|
166
|
+
try {
|
|
167
|
+
const last = Buffer.alloc(1)
|
|
168
|
+
return readSync(fd, last, 0, 1, st.size - 1) === 1 && last[0] === 0x0a
|
|
169
|
+
} finally {
|
|
170
|
+
closeSync(fd)
|
|
171
|
+
}
|
|
172
|
+
} catch {
|
|
173
|
+
// Missing (append creates it) or unreadable (append will refuse) — either
|
|
174
|
+
// way there is no partial line to close.
|
|
175
|
+
return true
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
153
179
|
/** 补上的那条结果的正文:说明事情本身,并给出下一步,而不是只报一个状态。 */
|
|
154
180
|
function interruptedCallNotice(): string {
|
|
155
181
|
return (
|
|
@@ -244,6 +270,15 @@ export class SessionLog {
|
|
|
244
270
|
// restrict to owner-only (dir 0700, file 0600).
|
|
245
271
|
mkdirSync(LOG_DIR, { recursive: true, mode: 0o700 })
|
|
246
272
|
const path = join(LOG_DIR, `${sanitizeSessionName(this.name)}.jsonl`)
|
|
273
|
+
|
|
274
|
+
// A writer killed mid-append can leave a partial line with no trailing
|
|
275
|
+
// newline. `open()` skips that line, but the next append would glue the new
|
|
276
|
+
// event onto it — corrupting both, and losing the first event after resume.
|
|
277
|
+
// Close the partial line before appending (it stays a skippable bad line).
|
|
278
|
+
if (this.buf.length > this.flushed && !endsWithNewline(path)) {
|
|
279
|
+
appendRegularFileSync(path, '\n', { mode: 0o600 })
|
|
280
|
+
}
|
|
281
|
+
|
|
247
282
|
let wrote = 0
|
|
248
283
|
for (const e of this.buf.slice(this.flushed)) {
|
|
249
284
|
// FIFO/socket 路径上「写不进去」而不是**干等**(`appendFileSync` 会打开目标写)。
|
|
@@ -30,6 +30,7 @@ import { SkillsLoader } from '../skills/loader'
|
|
|
30
30
|
import { RulesLoader } from '../core/rules-loader'
|
|
31
31
|
import { HookEngine } from '../core/hooks'
|
|
32
32
|
import { loadHookConfigs } from '../core/hooks-config'
|
|
33
|
+
import { isSafeMode } from '../core/safe-mode'
|
|
33
34
|
import { loadSettingsJson } from '../config/loader'
|
|
34
35
|
import { getWorkspaceTrust, warnProjectHooksSkipped } from '../core/workspace-trust'
|
|
35
36
|
import { AgentRegistry } from '../agent/agent-registry'
|
|
@@ -68,8 +69,10 @@ function skillsFor(cwd: string, paths?: string[]): SkillsLoader {
|
|
|
68
69
|
// 内置 skill 从包内解析(`import.meta.dirname`),与 cwd 无关;用户 skill 在
|
|
69
70
|
// `~/.mipham/skills`。三者里只有外部路径随 cwd 变。
|
|
70
71
|
loader.loadBuiltinFromPackage()
|
|
71
|
-
|
|
72
|
-
|
|
72
|
+
if (!isSafeMode()) {
|
|
73
|
+
loader.loadUserSkills()
|
|
74
|
+
if (paths && paths.length > 0) loader.loadExternal(paths)
|
|
75
|
+
}
|
|
73
76
|
skillsCache.set(cwd, loader)
|
|
74
77
|
return loader
|
|
75
78
|
}
|
|
@@ -91,6 +94,10 @@ function hooksFor(cwd: string, skills: SkillsLoader): HookEngine {
|
|
|
91
94
|
// 会话 cwd 必须显式传:daemon 一个进程服务多个会话,`process.cwd()` 是它自己被
|
|
92
95
|
// 启动时所在的目录,不属于任何会话 —— hooks 会在那里跑,并且**被告知**它在那里。
|
|
93
96
|
const engine = new HookEngine(cwd)
|
|
97
|
+
if (isSafeMode()) {
|
|
98
|
+
hookCache.set(cwd, engine)
|
|
99
|
+
return engine
|
|
100
|
+
}
|
|
94
101
|
for (const skill of skills.list()) {
|
|
95
102
|
for (const hook of skill.hooks ?? []) engine.register(hook)
|
|
96
103
|
}
|
|
@@ -110,8 +117,10 @@ function agentsFor(cwd: string): AgentRegistry {
|
|
|
110
117
|
const cached = agentCache.get(cwd)
|
|
111
118
|
if (cached) return cached
|
|
112
119
|
const registry = new AgentRegistry()
|
|
113
|
-
|
|
114
|
-
|
|
120
|
+
if (!isSafeMode()) {
|
|
121
|
+
registry.loadUserAgents()
|
|
122
|
+
registry.loadProjectAgents(cwd)
|
|
123
|
+
}
|
|
115
124
|
agentCache.set(cwd, registry)
|
|
116
125
|
return registry
|
|
117
126
|
}
|
package/src/daemon/launch.ts
CHANGED
|
@@ -322,6 +322,43 @@ export async function waitForDaemonExit(
|
|
|
322
322
|
}
|
|
323
323
|
}
|
|
324
324
|
|
|
325
|
+
/**
|
|
326
|
+
* Stop a daemon and confirm it is gone.
|
|
327
|
+
*
|
|
328
|
+
* SIGTERM, then wait; if the process is still there, SIGKILL and wait a short
|
|
329
|
+
* window more. Returns true only when `waitForExit` confirms the process
|
|
330
|
+
* disappeared — delivering a signal is a request, not a result.
|
|
331
|
+
*/
|
|
332
|
+
export async function terminateDaemonProcess(
|
|
333
|
+
pid: number,
|
|
334
|
+
opts: {
|
|
335
|
+
timeoutMs?: number
|
|
336
|
+
forceTimeoutMs?: number
|
|
337
|
+
deps?: {
|
|
338
|
+
kill?: (pid: number, signal: NodeJS.Signals) => void
|
|
339
|
+
waitForExit?: (opts?: { timeoutMs?: number }) => Promise<boolean>
|
|
340
|
+
}
|
|
341
|
+
} = {},
|
|
342
|
+
): Promise<boolean> {
|
|
343
|
+
const kill = opts.deps?.kill ?? ((p: number, signal: NodeJS.Signals) => process.kill(p, signal))
|
|
344
|
+
const wait = opts.deps?.waitForExit ?? ((o?: { timeoutMs?: number }) => waitForDaemonExit(o))
|
|
345
|
+
|
|
346
|
+
const waitOpts = opts.timeoutMs === undefined ? undefined : { timeoutMs: opts.timeoutMs }
|
|
347
|
+
try {
|
|
348
|
+
kill(pid, 'SIGTERM')
|
|
349
|
+
} catch {
|
|
350
|
+
// Already gone between the status probe and the signal.
|
|
351
|
+
}
|
|
352
|
+
if (await wait(waitOpts)) return true
|
|
353
|
+
|
|
354
|
+
try {
|
|
355
|
+
kill(pid, 'SIGKILL')
|
|
356
|
+
} catch {
|
|
357
|
+
// Exited between the wait and the kill.
|
|
358
|
+
}
|
|
359
|
+
return wait({ timeoutMs: opts.forceTimeoutMs ?? 2_000 })
|
|
360
|
+
}
|
|
361
|
+
|
|
325
362
|
/**
|
|
326
363
|
* The daemon process body, shared by the `__daemon` branch of the compiled
|
|
327
364
|
* binary and by `bin/daemon.ts` (source mode). One implementation, two entry
|
package/src/daemon/server.ts
CHANGED
|
@@ -38,6 +38,10 @@ import { createDingtalkApi } from './dingtalk/api.js'
|
|
|
38
38
|
import type { DingtalkConfig } from './dingtalk/types.js'
|
|
39
39
|
import { startHeartbeat } from './heartbeat'
|
|
40
40
|
import { wireDaemonEngine } from './engine-capabilities'
|
|
41
|
+
import {
|
|
42
|
+
cancelAllSessionTimers,
|
|
43
|
+
unregisterWakeupHandler,
|
|
44
|
+
} from '../tools/scheduling/schedule-wakeup'
|
|
41
45
|
|
|
42
46
|
interface ServerConfig {
|
|
43
47
|
db: DaemonDatabase
|
|
@@ -111,9 +115,14 @@ function resolveDaemonPermission(): PermissionMode {
|
|
|
111
115
|
export function buildDaemonPermission(
|
|
112
116
|
restrictions?: PermissionRestrictions,
|
|
113
117
|
rules?: { allow?: string[]; deny?: string[] },
|
|
118
|
+
tools?: Iterable<string>,
|
|
114
119
|
): PermissionSystem {
|
|
115
120
|
const permission = new PermissionSystem(resolveDaemonPermission())
|
|
116
121
|
if (restrictions) permission.setRestrictions(restrictions)
|
|
122
|
+
// Before the rules, like the CLI entry: the verdict is stamped at compile time.
|
|
123
|
+
// Without it a `permissionRules` typo in `config.yml` stays a silent dead rule in
|
|
124
|
+
// the daemon — the same failure, one wiring site over.
|
|
125
|
+
if (tools) permission.setKnownTools(tools)
|
|
117
126
|
if (rules) {
|
|
118
127
|
for (const rule of rules.allow ?? []) permission.allow(rule)
|
|
119
128
|
for (const rule of rules.deny ?? []) permission.deny(rule)
|
|
@@ -269,6 +278,7 @@ export function createServer(config: ServerConfig): Server<WsData> {
|
|
|
269
278
|
const permission = buildDaemonPermission(
|
|
270
279
|
daemonConfig.permissionRestrictions,
|
|
271
280
|
daemonConfig.permissionRules,
|
|
281
|
+
sharedTools.keys(),
|
|
272
282
|
)
|
|
273
283
|
// After `setRestrictions` (inside the builder) so this goes through the same clamp the
|
|
274
284
|
// first engine did — see `sessionModes`. Absent entry ⇒ env mode, unchanged.
|
|
@@ -553,8 +563,12 @@ export function createServer(config: ServerConfig): Server<WsData> {
|
|
|
553
563
|
pool.stopWorker(sessionId).catch((err: unknown) => {
|
|
554
564
|
logger.error('error stopping worker', { sessionId, error: err })
|
|
555
565
|
})
|
|
556
|
-
// Remove engine from cache
|
|
566
|
+
// Remove engine from cache. A closed session must not keep receiving
|
|
567
|
+
// wakeups: drop the handler (it holds the engine) and any timer still
|
|
568
|
+
// armed for it, plus the persisted intent.
|
|
557
569
|
engineCache.delete(sessionId)
|
|
570
|
+
unregisterWakeupHandler(sessionId)
|
|
571
|
+
cancelAllSessionTimers(sessionId)
|
|
558
572
|
sm.closeSession(sessionId)
|
|
559
573
|
return json({ ok: true })
|
|
560
574
|
}
|
package/src/index.tsx
CHANGED
|
@@ -51,7 +51,14 @@ import { formatMcpConnectFailures, type McpConnectFailure } from './mcp/connect-
|
|
|
51
51
|
import { AgentRegistry } from './agent/agent-registry'
|
|
52
52
|
import { HookEngine } from './core/hooks'
|
|
53
53
|
import { loadHookConfigs } from './core/hooks-config'
|
|
54
|
+
import { isSafeMode } from './core/safe-mode'
|
|
54
55
|
import { ArtifactServer } from './artifacts/server'
|
|
56
|
+
import {
|
|
57
|
+
exitSession,
|
|
58
|
+
registerExitHandler,
|
|
59
|
+
withTimeout,
|
|
60
|
+
SESSION_END_HOOK_TIMEOUT_MS,
|
|
61
|
+
} from './core/session-exit'
|
|
55
62
|
import { getMetrics } from './core/metrics'
|
|
56
63
|
import { initTelemetry, enableTelemetryNow } from './telemetry/index'
|
|
57
64
|
import { wasPrompted, markPrompted, isInteractive, setTelemetryEnabled } from './telemetry/consent'
|
|
@@ -513,12 +520,25 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
513
520
|
)
|
|
514
521
|
}
|
|
515
522
|
|
|
523
|
+
// `--safe-mode` (bin/mipham.ts sets MIPHAM_SAFE_MODE=1) skips everything
|
|
524
|
+
// supplied by the user, the project or plugins. Before this, the flag only
|
|
525
|
+
// set an env var that nothing read — the help text advertised a guard that
|
|
526
|
+
// did not exist.
|
|
527
|
+
const safeMode = isSafeMode()
|
|
528
|
+
if (safeMode) {
|
|
529
|
+
console.error(
|
|
530
|
+
'[mipham] safe mode: custom agents, skills, hooks and plugins are disabled (built-in skills remain).',
|
|
531
|
+
)
|
|
532
|
+
}
|
|
533
|
+
|
|
516
534
|
// Load skills
|
|
517
535
|
const skillsLoader = new SkillsLoader()
|
|
518
536
|
skillsLoader.loadBuiltinFromPackage()
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
537
|
+
if (!safeMode) {
|
|
538
|
+
skillsLoader.loadUserSkills()
|
|
539
|
+
if (config.skills?.paths) {
|
|
540
|
+
skillsLoader.loadExternal(config.skills.paths)
|
|
541
|
+
}
|
|
522
542
|
}
|
|
523
543
|
|
|
524
544
|
// Initialize plugin manager
|
|
@@ -741,10 +761,12 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
741
761
|
// CLI 是一次性进程,会话 cwd 就是 `process.cwd()`;写出来是为了与 daemon 那处
|
|
742
762
|
// (`daemon/engine-capabilities.ts` 传会话 cwd)成对照,别让哪边看起来像漏了。
|
|
743
763
|
const hookEngine = new HookEngine(process.cwd())
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
764
|
+
if (!safeMode) {
|
|
765
|
+
for (const skill of skillsLoader.list()) {
|
|
766
|
+
if (skill.hooks) {
|
|
767
|
+
for (const hook of skill.hooks) {
|
|
768
|
+
hookEngine.register(hook)
|
|
769
|
+
}
|
|
748
770
|
}
|
|
749
771
|
}
|
|
750
772
|
}
|
|
@@ -757,8 +779,10 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
757
779
|
// skip is announced, since silence would look the same as having passed.
|
|
758
780
|
// `settingsJson` itself was read up top, next to the permission it also feeds.
|
|
759
781
|
if (settingsJson.projectHooksSkipped) warnProjectHooksSkipped(process.cwd())
|
|
760
|
-
|
|
761
|
-
|
|
782
|
+
if (!safeMode) {
|
|
783
|
+
for (const def of loadHookConfigs(settingsJson.hooks)) {
|
|
784
|
+
hookEngine.register(def)
|
|
785
|
+
}
|
|
762
786
|
}
|
|
763
787
|
|
|
764
788
|
// Start artifact server (lazy — first artifact creation triggers listening)
|
|
@@ -791,6 +815,13 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
791
815
|
// `config.permission` / `permissionRestrictions` are applied up top, on the instance
|
|
792
816
|
// handed to `new QueryEngine(...)` — the same one whose mode the system prompt reads.
|
|
793
817
|
|
|
818
|
+
// Hand the registry's tool names to the permission system **before** any rule is
|
|
819
|
+
// loaded, so a plain-name rule is judged on existence and not only on structure
|
|
820
|
+
// (`bash` / `bahs` are structurally fine and match nothing — see `setKnownTools`).
|
|
821
|
+
// `mcp__` names are exempt inside `validateRulePattern`: those servers are still
|
|
822
|
+
// connecting in the background at this point.
|
|
823
|
+
engine.getPermission().setKnownTools(tools.keys())
|
|
824
|
+
|
|
794
825
|
// Apply user-defined permission rules (allow/deny) — wire the rule system into runtime
|
|
795
826
|
if (config.permissionRules) {
|
|
796
827
|
for (const rule of config.permissionRules.allow ?? []) engine.getPermission().allow(rule)
|
|
@@ -823,18 +854,22 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
823
854
|
|
|
824
855
|
// Initialize agent registry and load plugin agents/skills/MCP/hooks
|
|
825
856
|
const agentRegistry = new AgentRegistry()
|
|
826
|
-
|
|
827
|
-
|
|
857
|
+
if (!safeMode) {
|
|
858
|
+
agentRegistry.loadUserAgents()
|
|
859
|
+
agentRegistry.loadProjectAgents(process.cwd())
|
|
860
|
+
}
|
|
828
861
|
engine.setAgentRegistry(agentRegistry)
|
|
829
862
|
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
863
|
+
if (!safeMode) {
|
|
864
|
+
loadPlugins(
|
|
865
|
+
pluginManager,
|
|
866
|
+
agentRegistry,
|
|
867
|
+
skillsLoader,
|
|
868
|
+
hookEngine,
|
|
869
|
+
McpClient.getInstance(),
|
|
870
|
+
tools,
|
|
871
|
+
)
|
|
872
|
+
}
|
|
838
873
|
|
|
839
874
|
engine.setupContextSummarizer()
|
|
840
875
|
|
|
@@ -908,12 +943,17 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
908
943
|
}
|
|
909
944
|
}
|
|
910
945
|
|
|
911
|
-
const
|
|
912
|
-
saved = true
|
|
946
|
+
const shutdown = async (): Promise<void> => {
|
|
913
947
|
clearInterval(heartbeatInterval)
|
|
914
948
|
unregisterSession(sessionName)
|
|
915
|
-
//
|
|
916
|
-
|
|
949
|
+
// SessionEnd hooks are asynchronous; process.exit() is not. Starting the
|
|
950
|
+
// hooks and exiting in the same tick meant they never ran — the await is
|
|
951
|
+
// the difference between "best effort" and "never". Bounded, because a
|
|
952
|
+
// hook waiting on an unreachable server must not hold the terminal open.
|
|
953
|
+
await withTimeout(
|
|
954
|
+
hookEngine.executeSessionEnd(sessionName).catch(() => undefined),
|
|
955
|
+
SESSION_END_HOOK_TIMEOUT_MS,
|
|
956
|
+
)
|
|
917
957
|
artifactServer.stop()
|
|
918
958
|
persistSession()
|
|
919
959
|
// Finalize the session — write session summary + flush CRSI effectiveness
|
|
@@ -924,8 +964,15 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
924
964
|
} catch {
|
|
925
965
|
// ignore — CRSI closeout is non-critical
|
|
926
966
|
}
|
|
967
|
+
saved = true
|
|
927
968
|
getMetrics().activeSessions.dec()
|
|
928
|
-
|
|
969
|
+
}
|
|
970
|
+
// Every user-initiated exit (`/exit`, `/quit`, the second Ctrl+C, signals)
|
|
971
|
+
// goes through this one handler, so none of them can skip SessionEnd.
|
|
972
|
+
registerExitHandler(shutdown)
|
|
973
|
+
|
|
974
|
+
const saveAndExit = () => {
|
|
975
|
+
void exitSession(0)
|
|
929
976
|
}
|
|
930
977
|
|
|
931
978
|
process.on('SIGINT', saveAndExit)
|
|
@@ -934,9 +981,10 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
934
981
|
// a handler the session log is silently dropped on those paths.
|
|
935
982
|
process.on('SIGHUP', saveAndExit)
|
|
936
983
|
|
|
937
|
-
// Safety net: persist on exit for paths that
|
|
938
|
-
//
|
|
939
|
-
//
|
|
984
|
+
// Safety net: persist on exit for paths that never reach `shutdown` — a
|
|
985
|
+
// daemon worker being killed, a crash, `process.exit()` called by code that
|
|
986
|
+
// does not know about this session. `shutdown` already persisted; guard on
|
|
987
|
+
// !saved to avoid double-writing.
|
|
940
988
|
process.on('exit', () => {
|
|
941
989
|
clearInterval(heartbeatInterval)
|
|
942
990
|
unregisterSession(sessionName)
|