@miphamai/cli 0.85.22 → 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/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 +32 -2
- 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 +9 -1
- package/src/index.tsx +68 -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
|
@@ -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
|
|
@@ -559,8 +563,12 @@ export function createServer(config: ServerConfig): Server<WsData> {
|
|
|
559
563
|
pool.stopWorker(sessionId).catch((err: unknown) => {
|
|
560
564
|
logger.error('error stopping worker', { sessionId, error: err })
|
|
561
565
|
})
|
|
562
|
-
// 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.
|
|
563
569
|
engineCache.delete(sessionId)
|
|
570
|
+
unregisterWakeupHandler(sessionId)
|
|
571
|
+
cancelAllSessionTimers(sessionId)
|
|
564
572
|
sm.closeSession(sessionId)
|
|
565
573
|
return json({ ok: true })
|
|
566
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)
|
|
@@ -830,18 +854,22 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
830
854
|
|
|
831
855
|
// Initialize agent registry and load plugin agents/skills/MCP/hooks
|
|
832
856
|
const agentRegistry = new AgentRegistry()
|
|
833
|
-
|
|
834
|
-
|
|
857
|
+
if (!safeMode) {
|
|
858
|
+
agentRegistry.loadUserAgents()
|
|
859
|
+
agentRegistry.loadProjectAgents(process.cwd())
|
|
860
|
+
}
|
|
835
861
|
engine.setAgentRegistry(agentRegistry)
|
|
836
862
|
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
863
|
+
if (!safeMode) {
|
|
864
|
+
loadPlugins(
|
|
865
|
+
pluginManager,
|
|
866
|
+
agentRegistry,
|
|
867
|
+
skillsLoader,
|
|
868
|
+
hookEngine,
|
|
869
|
+
McpClient.getInstance(),
|
|
870
|
+
tools,
|
|
871
|
+
)
|
|
872
|
+
}
|
|
845
873
|
|
|
846
874
|
engine.setupContextSummarizer()
|
|
847
875
|
|
|
@@ -915,12 +943,17 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
915
943
|
}
|
|
916
944
|
}
|
|
917
945
|
|
|
918
|
-
const
|
|
919
|
-
saved = true
|
|
946
|
+
const shutdown = async (): Promise<void> => {
|
|
920
947
|
clearInterval(heartbeatInterval)
|
|
921
948
|
unregisterSession(sessionName)
|
|
922
|
-
//
|
|
923
|
-
|
|
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
|
+
)
|
|
924
957
|
artifactServer.stop()
|
|
925
958
|
persistSession()
|
|
926
959
|
// Finalize the session — write session summary + flush CRSI effectiveness
|
|
@@ -931,8 +964,15 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
931
964
|
} catch {
|
|
932
965
|
// ignore — CRSI closeout is non-critical
|
|
933
966
|
}
|
|
967
|
+
saved = true
|
|
934
968
|
getMetrics().activeSessions.dec()
|
|
935
|
-
|
|
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)
|
|
936
976
|
}
|
|
937
977
|
|
|
938
978
|
process.on('SIGINT', saveAndExit)
|
|
@@ -941,9 +981,10 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
941
981
|
// a handler the session log is silently dropped on those paths.
|
|
942
982
|
process.on('SIGHUP', saveAndExit)
|
|
943
983
|
|
|
944
|
-
// Safety net: persist on exit for paths that
|
|
945
|
-
//
|
|
946
|
-
//
|
|
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.
|
|
947
988
|
process.on('exit', () => {
|
|
948
989
|
clearInterval(heartbeatInterval)
|
|
949
990
|
unregisterSession(sessionName)
|
|
@@ -277,8 +277,15 @@ export class HttpTransport implements Transport {
|
|
|
277
277
|
...(params ? { params } : {}),
|
|
278
278
|
}
|
|
279
279
|
|
|
280
|
-
// Fire-and-forget: do not await the response.
|
|
281
|
-
|
|
280
|
+
// Fire-and-forget: do not await the response — but bound it. Without a
|
|
281
|
+
// signal the request inherits the platform fetch timeout (none, in Node),
|
|
282
|
+
// so a server that never answers pins a socket for the life of the process.
|
|
283
|
+
const url = this.url
|
|
284
|
+
const controller = new AbortController()
|
|
285
|
+
const timer = setTimeout(() => controller.abort(), this.requestTimeoutMs)
|
|
286
|
+
// A best-effort notification must not keep the process alive on exit.
|
|
287
|
+
timer.unref?.()
|
|
288
|
+
void this.fetchImpl(url, {
|
|
282
289
|
method: 'POST',
|
|
283
290
|
headers: {
|
|
284
291
|
'Content-Type': 'application/json',
|
|
@@ -287,9 +294,17 @@ export class HttpTransport implements Transport {
|
|
|
287
294
|
},
|
|
288
295
|
body: JSON.stringify(notification),
|
|
289
296
|
redirect: 'manual',
|
|
290
|
-
|
|
291
|
-
/* notifications are best-effort */
|
|
297
|
+
signal: controller.signal,
|
|
292
298
|
})
|
|
299
|
+
.then((res) => {
|
|
300
|
+
// Nobody reads this body; release it so an undrained keep-alive
|
|
301
|
+
// response cannot hold the socket open either.
|
|
302
|
+
void res.body?.cancel().catch(() => {})
|
|
303
|
+
})
|
|
304
|
+
.catch(() => {
|
|
305
|
+
/* notifications are best-effort */
|
|
306
|
+
})
|
|
307
|
+
.finally(() => clearTimeout(timer))
|
|
293
308
|
}
|
|
294
309
|
|
|
295
310
|
onNotification(handler: NotificationHandler): void {
|
package/src/mcp/registry.ts
CHANGED
|
@@ -48,6 +48,45 @@ function buildToolName(serverName: string, toolName: string): string {
|
|
|
48
48
|
return prefix + sanitizeName(toolName).slice(0, maxToolLen)
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
+
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
52
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Coerce a server-declared `inputSchema` into a shape every provider accepts.
|
|
57
|
+
*
|
|
58
|
+
* `inputSchema` comes from another process and is not validated against JSON
|
|
59
|
+
* Schema. Passing it through put the same malformed schema in front of the
|
|
60
|
+
* model on *every* turn, so one broken server could make the whole session
|
|
61
|
+
* unusable — not just the one tool. Only the top level is repaired: property
|
|
62
|
+
* schemas that are themselves objects are kept verbatim, so this narrows
|
|
63
|
+
* malformed input without rewriting a server's intent.
|
|
64
|
+
*/
|
|
65
|
+
export function sanitizeInputSchema(schema: unknown): {
|
|
66
|
+
properties: Record<string, unknown>
|
|
67
|
+
required?: string[]
|
|
68
|
+
} {
|
|
69
|
+
const root = isPlainObject(schema) ? schema : {}
|
|
70
|
+
const rawProperties = isPlainObject(root.properties) ? root.properties : {}
|
|
71
|
+
const properties: Record<string, unknown> = {}
|
|
72
|
+
for (const [name, property] of Object.entries(rawProperties)) {
|
|
73
|
+
if (isPlainObject(property)) properties[name] = property
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const required = Array.isArray(root.required)
|
|
77
|
+
? [
|
|
78
|
+
...new Set(
|
|
79
|
+
root.required.filter(
|
|
80
|
+
(name): name is string =>
|
|
81
|
+
typeof name === 'string' && Object.prototype.hasOwnProperty.call(properties, name),
|
|
82
|
+
),
|
|
83
|
+
),
|
|
84
|
+
]
|
|
85
|
+
: []
|
|
86
|
+
|
|
87
|
+
return required.length > 0 ? { properties, required } : { properties }
|
|
88
|
+
}
|
|
89
|
+
|
|
51
90
|
/**
|
|
52
91
|
* Convert an MCP server ToolDefinition into the main ToolDefinition format
|
|
53
92
|
* that can be registered in the central tool registry.
|
|
@@ -55,13 +94,9 @@ function buildToolName(serverName: string, toolName: string): string {
|
|
|
55
94
|
export function convertMcpTool(serverName: string, mcpTool: McpToolDefinition): ToolDefinition {
|
|
56
95
|
const toolName = buildToolName(serverName, mcpTool.name)
|
|
57
96
|
|
|
58
|
-
// Build parameters schema — pass through MCP inputSchema as-is
|
|
59
97
|
const parameters: Record<string, unknown> = {
|
|
60
98
|
type: 'object',
|
|
61
|
-
|
|
62
|
-
}
|
|
63
|
-
if (mcpTool.inputSchema.required) {
|
|
64
|
-
parameters.required = mcpTool.inputSchema.required
|
|
99
|
+
...sanitizeInputSchema(mcpTool.inputSchema),
|
|
65
100
|
}
|
|
66
101
|
|
|
67
102
|
return {
|
|
@@ -149,6 +149,10 @@ export function loadPlugins(
|
|
|
149
149
|
// its command, its health would be tracked under the bare event
|
|
150
150
|
// name, and the cleanup below would have nothing to scope to.
|
|
151
151
|
source: plugin.name,
|
|
152
|
+
// Same reason as `loadHookConfigs`: the engine's own failure
|
|
153
|
+
// paths read the definition, and an opted-open guard must stay
|
|
154
|
+
// open when its handler throws or it is auto-disabled.
|
|
155
|
+
failureMode: hookCfg.failureMode,
|
|
152
156
|
handler: async (ctx) => executeHook(hookCfg, ctx, plugin.name),
|
|
153
157
|
})
|
|
154
158
|
}
|
|
@@ -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.23' as const
|
|
13
13
|
|
|
14
14
|
/** npm install 全局安装命令 */
|
|
15
15
|
export const NPM_INSTALL_COMMAND = `npm install -g ${PACKAGE_NAME}` as const
|
|
@@ -90,4 +90,4 @@ export const TOOL_COUNT = 31 as const
|
|
|
90
90
|
* —— `test/e2e/full-pipeline.test.ts` 在 Linux 上整文件 skip、在 macOS 上跑 ——
|
|
91
91
|
* 但**总数相同**(两边都把被 skip 的算进去)。
|
|
92
92
|
*/
|
|
93
|
-
export const TEST_COUNT =
|
|
93
|
+
export const TEST_COUNT = 4342 as const
|
package/src/shared/types.ts
CHANGED
|
@@ -320,6 +320,18 @@ export interface HookConfig {
|
|
|
320
320
|
/** Command timeout in seconds (Claude Code default is 60). */
|
|
321
321
|
timeout?: number
|
|
322
322
|
continueOnBlock?: boolean
|
|
323
|
+
/**
|
|
324
|
+
* What a failure to *run* this hook means.
|
|
325
|
+
*
|
|
326
|
+
* Defaults to `'closed'` for `PreToolUse` and `'open'` for every other event.
|
|
327
|
+
* A guard exists to decide before the tool runs; if it cannot start, time out,
|
|
328
|
+
* or hand back an answer, there is no decision, and allowing the call turns a
|
|
329
|
+
* broken guard into a silent bypass. Other events observe something that
|
|
330
|
+
* already happened — there is nothing left to refuse — so their failures stay
|
|
331
|
+
* context. Set `'open'` on a `PreToolUse` hook to opt it back into the old
|
|
332
|
+
* behaviour.
|
|
333
|
+
*/
|
|
334
|
+
failureMode?: 'open' | 'closed'
|
|
323
335
|
}
|
|
324
336
|
|
|
325
337
|
export interface HookDefinition {
|
|
@@ -333,6 +345,12 @@ export interface HookDefinition {
|
|
|
333
345
|
* health is tracked per key, and removal has nothing to scope to.
|
|
334
346
|
*/
|
|
335
347
|
source?: string
|
|
348
|
+
/**
|
|
349
|
+
* Failure policy for this hook — see `HookConfig.failureMode`. Defaults to
|
|
350
|
+
* `'closed'` on `PreToolUse`, where a handler that throws is a guard that
|
|
351
|
+
* could not answer.
|
|
352
|
+
*/
|
|
353
|
+
failureMode?: 'open' | 'closed'
|
|
336
354
|
handler: (context: HookContext) => Promise<HookResult>
|
|
337
355
|
}
|
|
338
356
|
|
package/src/skills/loader.ts
CHANGED
|
@@ -26,6 +26,24 @@ export function parseFrontmatter(raw: string): FrontmatterResult {
|
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
+
/**
|
|
30
|
+
* Skill names are interpolated verbatim into the `<system-reminder>` block and
|
|
31
|
+
* used as the map key for the Skill tool. A name carrying control characters,
|
|
32
|
+
* bidirectional/format controls, line separators, exotic spaces or angle
|
|
33
|
+
* brackets can forge reminder lines or make the listing unreadable.
|
|
34
|
+
*
|
|
35
|
+
* Returns a short reason when the name is unusable, null when it is fine.
|
|
36
|
+
* Callers reject rather than strip: a name the author did not choose is worse
|
|
37
|
+
* than falling back to the path-derived name.
|
|
38
|
+
*/
|
|
39
|
+
export function invalidSkillNameReason(name: string): string | null {
|
|
40
|
+
if (!name.trim()) return 'empty name'
|
|
41
|
+
if (/[\p{Cc}\p{Cf}<>]/u.test(name)) return 'control, format or angle-bracket characters'
|
|
42
|
+
if (/[\p{Zl}\p{Zp}]/u.test(name)) return 'line/paragraph separators'
|
|
43
|
+
if (/[\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]/u.test(name)) return 'non-ASCII spacing'
|
|
44
|
+
return null
|
|
45
|
+
}
|
|
46
|
+
|
|
29
47
|
export class SkillsLoader implements Skills {
|
|
30
48
|
private skills = new Map<string, SkillDefinition>()
|
|
31
49
|
|
|
@@ -147,7 +165,33 @@ export class SkillsLoader implements Skills {
|
|
|
147
165
|
|
|
148
166
|
const rawDescription = (data.description as string) || ''
|
|
149
167
|
const rawBody = content.trim() || undefined
|
|
150
|
-
|
|
168
|
+
|
|
169
|
+
// Name gate (see `invalidSkillNameReason`). A declared name that fails is
|
|
170
|
+
// ignored in favour of the path-derived one; if that fails too the skill
|
|
171
|
+
// is skipped. Only a string counts — `name: 42` is a malformed declaration,
|
|
172
|
+
// not a name.
|
|
173
|
+
const declaredName = typeof data.name === 'string' ? data.name.trim() : ''
|
|
174
|
+
let skillName = ''
|
|
175
|
+
if (declaredName) {
|
|
176
|
+
const reason = invalidSkillNameReason(declaredName)
|
|
177
|
+
if (reason) {
|
|
178
|
+
process.stderr.write(
|
|
179
|
+
`⚠️ Skill at ${sourceName}: frontmatter name rejected (${reason}) — using the path-derived name.\n`,
|
|
180
|
+
)
|
|
181
|
+
} else {
|
|
182
|
+
skillName = declaredName
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
if (!skillName) {
|
|
186
|
+
skillName = this.nameFromPath(sourceName)
|
|
187
|
+
const reason = invalidSkillNameReason(skillName)
|
|
188
|
+
if (reason) {
|
|
189
|
+
process.stderr.write(
|
|
190
|
+
`⚠️ Skill at ${sourceName}: path-derived name rejected (${reason}) — skipped.\n`,
|
|
191
|
+
)
|
|
192
|
+
return
|
|
193
|
+
}
|
|
194
|
+
}
|
|
151
195
|
|
|
152
196
|
// ── Safety: check for command/MCP shadowing ──
|
|
153
197
|
const shadowCheck = checkSkillShadow(skillName, rawDescription)
|