@miphamai/cli 0.85.22 → 0.85.24
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 +40 -13
- package/package.json +1 -1
- package/src/agent/agent-context.ts +19 -6
- package/src/agent/agent-registry.ts +42 -2
- package/src/agent/message-router.ts +30 -0
- package/src/agent/sub-agent.ts +17 -0
- package/src/config/loader.ts +41 -0
- package/src/core/context-microcompact.ts +1 -1
- package/src/core/context.ts +167 -10
- package/src/core/cron-poller.ts +74 -6
- package/src/core/engine.ts +34 -7
- package/src/core/hooks-config.ts +4 -0
- package/src/core/hooks-executor.ts +96 -28
- package/src/core/hooks.ts +49 -3
- 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/i18n-core/locales/en-US.json +1 -0
- package/src/i18n-core/locales/zh-CN.json +1 -0
- package/src/index.tsx +68 -27
- package/src/mcp/client.ts +22 -8
- 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/providers/anthropic.ts +8 -2
- package/src/providers/openai-compat.ts +14 -2
- package/src/shared/arg-validation.ts +2 -1
- package/src/shared/package-info.ts +2 -2
- package/src/shared/types.ts +18 -0
- package/src/skills/loader.ts +86 -4
- package/src/tools/agent/workflow.ts +9 -2
- package/src/tools/exec/bash.ts +38 -11
- package/src/tools/exec/exit-worktree.ts +45 -4
- package/src/tools/file/read.ts +16 -2
- package/src/tools/network/web-fetch.ts +11 -3
- package/src/tools/network/web-search.ts +5 -1
- package/src/tools/scheduling/cron.ts +2 -1
- package/src/tools/scheduling/schedule-wakeup.ts +23 -8
- package/src/tools/validation.ts +11 -0
- package/src/ui/app.tsx +6 -5
- package/src/ui/commands.ts +17 -8
- package/src/workflow/primitives/agent.ts +34 -5
- package/src/workflow/primitives/verify.ts +36 -20
- package/src/workflow/runtime.ts +10 -2
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)
|
|
@@ -183,7 +227,7 @@ export class SkillsLoader implements Skills {
|
|
|
183
227
|
type,
|
|
184
228
|
body,
|
|
185
229
|
tools: data.tools as SkillDefinition['tools'],
|
|
186
|
-
hooks: data.hooks
|
|
230
|
+
hooks: parseSkillHooks(data.hooks, skillName),
|
|
187
231
|
prompts: data.prompts as SkillDefinition['prompts'],
|
|
188
232
|
// NEW: frontmatter fields for fork/auto-trigger support
|
|
189
233
|
context: data.context as string | undefined,
|
|
@@ -261,10 +305,48 @@ export class SkillsLoader implements Skills {
|
|
|
261
305
|
}
|
|
262
306
|
}
|
|
263
307
|
|
|
308
|
+
/**
|
|
309
|
+
* 只接受**真带 handler** 的技能钩子。
|
|
310
|
+
*
|
|
311
|
+
* YAML 里没有闭包,所以技能 frontmatter 写的 `hooks:` 到这一步只是数据,`handler`
|
|
312
|
+
* 恒为 `undefined`(`as` 断言把类型骗过去了)。原样注册的后果不是「钩子不生效」,
|
|
313
|
+
* 是**每一个工具调用都被拒**:`runHooks` 调 `undefined(ctx)` 抛 TypeError,而
|
|
314
|
+
* PreToolUse 的守卫是 fail-closed —— 引擎把它读成「守卫答不出来」,于是整场会话
|
|
315
|
+
* 的每一次工具调用都返回拒绝。插件路径交进来的钩子带真 handler,照常放行。
|
|
316
|
+
*/
|
|
317
|
+
function parseSkillHooks(raw: unknown, skillName: string): SkillDefinition['hooks'] {
|
|
318
|
+
if (!Array.isArray(raw)) return undefined
|
|
319
|
+
|
|
320
|
+
const accepted: SkillDefinition['hooks'] = []
|
|
321
|
+
for (const entry of raw) {
|
|
322
|
+
const handler = (entry as { handler?: unknown } | null)?.handler
|
|
323
|
+
if (typeof handler === 'function') {
|
|
324
|
+
accepted.push({
|
|
325
|
+
...(entry as object),
|
|
326
|
+
source: skillName,
|
|
327
|
+
} as NonNullable<SkillDefinition['hooks']>[number])
|
|
328
|
+
continue
|
|
329
|
+
}
|
|
330
|
+
process.stderr.write(
|
|
331
|
+
`⚠️ Skill "${skillName}": a hook entry has no handler (frontmatter cannot carry ` +
|
|
332
|
+
`functions) — ignored. Declare the hook in settings.json instead.\n`,
|
|
333
|
+
)
|
|
334
|
+
}
|
|
335
|
+
return accepted.length > 0 ? accepted : undefined
|
|
336
|
+
}
|
|
337
|
+
|
|
264
338
|
const COMPACT_DESC_MAX_CHARS = 80
|
|
265
339
|
|
|
266
|
-
/**
|
|
267
|
-
|
|
340
|
+
/**
|
|
341
|
+
* Collapse a description to a single short line.
|
|
342
|
+
*
|
|
343
|
+
* Used both by the compact system reminder and by the human-facing `/skills`
|
|
344
|
+
* listing: skill descriptions are written for the *model* and are often
|
|
345
|
+
* several paragraphs of instructions. Pasting that into a terminal listing
|
|
346
|
+
* turns three skills into a screenful; the first line + an ellipsis is the
|
|
347
|
+
* honest short form (there is no separate short-description field to read).
|
|
348
|
+
*/
|
|
349
|
+
export function truncateSkillDescription(desc: string): string {
|
|
268
350
|
const firstLine = desc.split('\n')[0]?.trim() ?? ''
|
|
269
351
|
return firstLine.length > COMPACT_DESC_MAX_CHARS
|
|
270
352
|
? firstLine.slice(0, COMPACT_DESC_MAX_CHARS) + '…'
|
|
@@ -93,11 +93,18 @@ export const workflowTool: ToolDefinition = {
|
|
|
93
93
|
}
|
|
94
94
|
}
|
|
95
95
|
|
|
96
|
-
// Build a minimal engine-like interface for runWorkflow
|
|
96
|
+
// Build a minimal engine-like interface for runWorkflow.
|
|
97
|
+
//
|
|
98
|
+
// `runWorkflow` reads four accessors, not two: without `getPermission` /
|
|
99
|
+
// `getLlm` this stub made every Workflow call throw `engine.getPermission is
|
|
100
|
+
// not a function` before the script even started. The cast hid it — the
|
|
101
|
+
// object was asserted to be a QueryEngine, and nothing exercised the call.
|
|
97
102
|
const engineStub = {
|
|
98
103
|
getRegistry: () => ctx.registry!,
|
|
99
104
|
getTools: () => ctx.toolRegistry!,
|
|
100
|
-
|
|
105
|
+
getPermission: () => ctx.permissionSystem,
|
|
106
|
+
getLlm: () => ctx.llm,
|
|
107
|
+
} as unknown as QueryEngine
|
|
101
108
|
|
|
102
109
|
try {
|
|
103
110
|
const { runId, result, cacheHits, cacheMisses } = await runWorkflow(
|
package/src/tools/exec/bash.ts
CHANGED
|
@@ -16,32 +16,53 @@ import { withValidation } from '../validation'
|
|
|
16
16
|
// target being the last thing on the line, so `rm -rf /*` was refused while
|
|
17
17
|
// `rm -rf /* > log`, `rm -rf /* foo` and `rm -rf /*; echo x` — the same
|
|
18
18
|
// deletion — were not.
|
|
19
|
+
// Any spelling of the recursive flag: `-rf`, `-fr`, `-r`, `-R`, `--recursive`.
|
|
20
|
+
// Another flag may sit on either side (`-f -r`, `-i -r -v`), because the shell
|
|
21
|
+
// does not care about flag order or which letters share a cluster.
|
|
22
|
+
//
|
|
23
|
+
// Matching only `-rf`/`-fr` made the refusal a spelling test rather than a
|
|
24
|
+
// behaviour test: `rm -r /Volumes` deletes exactly what `rm -rf /Volumes` does
|
|
25
|
+
// and passed. Every guard below needs the same fragment, so it is written once.
|
|
26
|
+
const RM_OTHER_FLAGS = String.raw`(?:-[A-Za-z]+|--[a-z][a-z-]*)`
|
|
27
|
+
const RM_RECURSIVE = String.raw`(?:-[A-Za-z]*[rR][A-Za-z]*|--recursive)`
|
|
28
|
+
const RM_LEAD = String.raw`\brm\s+(?:${RM_OTHER_FLAGS}\s+)*${RM_RECURSIVE}(?:\s+${RM_OTHER_FLAGS})*\s+`
|
|
29
|
+
|
|
30
|
+
/** `rm` with the recursive flag in any spelling, followed by `target`. */
|
|
31
|
+
function rmRecursiveOn(target: string, flags = ''): RegExp {
|
|
32
|
+
return new RegExp(RM_LEAD + target, flags)
|
|
33
|
+
}
|
|
34
|
+
|
|
19
35
|
const BLOCKED_PATTERNS = [
|
|
20
36
|
// Recursive root deletion without preserve-root safeguard.
|
|
21
37
|
// The operand may be quoted: `rm -rf '/'` reaches the same path as `rm -rf /`, so
|
|
22
38
|
// the quote belongs to the *delimiter* class, not to the path — `['"]?` opens the
|
|
23
39
|
// operand and the lookahead accepts the closing quote.
|
|
24
|
-
|
|
25
|
-
|
|
40
|
+
rmRecursiveOn(String.raw`['"]?\/(?=["'\s]|$)`),
|
|
41
|
+
rmRecursiveOn(String.raw`['"]?\/\*(?=["'\s;&|>]|$)`),
|
|
26
42
|
/\bsudo\s+rm\s+.*\//,
|
|
27
43
|
// rm -rf on home directory or any absolute path (relative dirs like node_modules stay allowed)
|
|
28
|
-
|
|
29
|
-
|
|
44
|
+
rmRecursiveOn(String.raw`['"]?~(?:["'\s\/]|$)`),
|
|
45
|
+
rmRecursiveOn(String.raw`['"]?\/(?![\s*])`),
|
|
30
46
|
// rm -rf on dangerous cwd globs
|
|
31
|
-
|
|
47
|
+
rmRecursiveOn(String.raw`['"]?\*(?=["'\s;&|>]|$)`),
|
|
32
48
|
// `rm -rf .` and its path spellings `./` and `../` delete the working directory;
|
|
33
49
|
// `./build` and `../vendor` name an entry inside it and stay allowed.
|
|
34
|
-
|
|
50
|
+
rmRecursiveOn(String.raw`['"]?\.\.?(?:\/)?(?=["'\s;&|>]|$)`),
|
|
35
51
|
// The home directory under another name is still the home directory. `$HOME`
|
|
36
52
|
// expands to the same tree as `~`; on Windows `C:\Users\<name>` *is* the profile
|
|
37
53
|
// directory, long or in its 8.3 short form (`C:\Users\GUOHUA~1`). Guarding only
|
|
38
54
|
// the literal spellings above leaves each of these a one-word bypass.
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
55
|
+
rmRecursiveOn(String.raw`['"]?\$\{?HOME\}?(?:["'\s/]|$)`),
|
|
56
|
+
rmRecursiveOn(String.raw`['"]?[A-Za-z]:[\\/](?=["'\s;&|>]|$)`),
|
|
57
|
+
// `C:\Users` itself is the parent of every profile on the drive — the drive's
|
|
58
|
+
// equivalent of `/home`, so the profile name is optional rather than required.
|
|
59
|
+
rmRecursiveOn(
|
|
60
|
+
String.raw`['"]?[A-Za-z]:[\\/]Users(?:[\\/](?:[^\\/\s"']+(?:[\\/])?)?)?(?=["'\s;&|>]|$)`,
|
|
61
|
+
'i',
|
|
62
|
+
),
|
|
42
63
|
// cmd.exe spells the same directories with percent signs; in scope whenever a
|
|
43
64
|
// command hands off to cmd (`cmd /c …`).
|
|
44
|
-
|
|
65
|
+
rmRecursiveOn(String.raw`['"]?%(?:USERPROFILE|HOMEPATH|HOMEDRIVE)%`, 'i'),
|
|
45
66
|
// Filesystem manipulation
|
|
46
67
|
/\bmkfs\./,
|
|
47
68
|
/\bdd\s+if=/,
|
|
@@ -531,6 +552,10 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
|
|
|
531
552
|
)
|
|
532
553
|
.join('\n')
|
|
533
554
|
}
|
|
555
|
+
// A full disk is the one failure whose raw form (`ENOSPC … /some/path`)
|
|
556
|
+
// reads like a *path* problem, so the model starts checking permissions
|
|
557
|
+
// on a path that is fine. Say what happened instead.
|
|
558
|
+
const diskFull = /ENOSPC|No space left on device/i.test(stderr)
|
|
534
559
|
return {
|
|
535
560
|
success: false,
|
|
536
561
|
content: errorContent,
|
|
@@ -538,7 +563,9 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
|
|
|
538
563
|
? `Command cancelled (SIGKILL to its process group)`
|
|
539
564
|
: timedOut
|
|
540
565
|
? `Command timed out after ${timeout}ms (killed): ${stderr.slice(0, 1_000)}`
|
|
541
|
-
:
|
|
566
|
+
: diskFull
|
|
567
|
+
? `The disk is full (ENOSPC) — the command could not finish, and anything it had written may be partial: ${stderr.slice(0, 1_000)}`
|
|
568
|
+
: `Exit code ${exitCode}: ${stderr.slice(0, 1_000)}`,
|
|
542
569
|
}
|
|
543
570
|
}
|
|
544
571
|
|
|
@@ -128,6 +128,42 @@ export const exitWorktreeTool: ToolDefinition = {
|
|
|
128
128
|
// Branch detection is best-effort
|
|
129
129
|
}
|
|
130
130
|
|
|
131
|
+
// Unmerged-commit guard. `status --porcelain` above only sees the working
|
|
132
|
+
// tree: a clean worktree whose branch holds commits that exist nowhere
|
|
133
|
+
// else passes it, and `git worktree remove` succeeds too — then the
|
|
134
|
+
// `git branch -D` below silently destroys those commits. Ask git what the
|
|
135
|
+
// branch has that HEAD and every remote do not.
|
|
136
|
+
let branchSafeToDelete = true
|
|
137
|
+
if (!discardChanges && branchName && branchName !== 'HEAD') {
|
|
138
|
+
try {
|
|
139
|
+
const countProc = Bun.spawn(
|
|
140
|
+
['git', 'rev-list', '--count', branchName, '--not', 'HEAD', '--remotes'],
|
|
141
|
+
{ cwd, stdout: 'pipe', stderr: 'pipe' },
|
|
142
|
+
)
|
|
143
|
+
const countText = (await new Response(countProc.stdout).text()).trim()
|
|
144
|
+
const countExit = await countProc.exited
|
|
145
|
+
if (countExit !== 0) {
|
|
146
|
+
// Can't prove it is safe ⇒ keep the branch (never delete blind).
|
|
147
|
+
branchSafeToDelete = false
|
|
148
|
+
} else {
|
|
149
|
+
const unmerged = Number.parseInt(countText, 10)
|
|
150
|
+
if (Number.isFinite(unmerged) && unmerged > 0) {
|
|
151
|
+
return {
|
|
152
|
+
success: false,
|
|
153
|
+
content: '',
|
|
154
|
+
error:
|
|
155
|
+
`Branch "${branchName}" has ${unmerged} commit(s) not on HEAD or any remote:\n\n` +
|
|
156
|
+
`Removing the worktree would delete them (git branch -D).\n\n` +
|
|
157
|
+
`Set discard_changes: true to force removal and discard these commits.\n` +
|
|
158
|
+
`Or merge/push the branch first, then retry.`,
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
} catch {
|
|
163
|
+
branchSafeToDelete = false
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
131
167
|
// Remove the worktree
|
|
132
168
|
const removeArgs = discardChanges
|
|
133
169
|
? ['git', 'worktree', 'remove', '--force', worktreePath]
|
|
@@ -149,27 +185,32 @@ export const exitWorktreeTool: ToolDefinition = {
|
|
|
149
185
|
}
|
|
150
186
|
}
|
|
151
187
|
|
|
152
|
-
// Clean up the branch if we have its name
|
|
153
|
-
|
|
188
|
+
// Clean up the branch if we have its name and proved it is safe to delete
|
|
189
|
+
let branchDeleted = false
|
|
190
|
+
if (branchSafeToDelete && branchName && branchName !== 'HEAD') {
|
|
154
191
|
try {
|
|
155
192
|
const branchProc = Bun.spawn(['git', 'branch', '-D', branchName], {
|
|
156
193
|
cwd,
|
|
157
194
|
stdout: 'pipe',
|
|
158
195
|
stderr: 'pipe',
|
|
159
196
|
})
|
|
160
|
-
await branchProc.exited
|
|
197
|
+
branchDeleted = (await branchProc.exited) === 0
|
|
161
198
|
// Best-effort — branch cleanup failure is not fatal
|
|
162
199
|
} catch {
|
|
163
200
|
// Ignore branch cleanup failures
|
|
164
201
|
}
|
|
165
202
|
}
|
|
166
203
|
|
|
204
|
+
const branchLine = branchName
|
|
205
|
+
? `Branch: ${branchName} (${branchDeleted ? 'deleted' : 'kept — could not prove it is safe to delete'})\n`
|
|
206
|
+
: ''
|
|
207
|
+
|
|
167
208
|
return {
|
|
168
209
|
success: true,
|
|
169
210
|
content:
|
|
170
211
|
`── Worktree Removed ──\n\n` +
|
|
171
212
|
`Path: ${worktreePath}\n` +
|
|
172
|
-
|
|
213
|
+
branchLine +
|
|
173
214
|
`\nThe worktree has been removed.`,
|
|
174
215
|
}
|
|
175
216
|
} catch (err) {
|
package/src/tools/file/read.ts
CHANGED
|
@@ -157,9 +157,12 @@ export function createReadTool(credentialConfig?: CredentialMaskingConfig): Tool
|
|
|
157
157
|
|
|
158
158
|
// O_NOFOLLOW: fail closed if the path was swapped to a symlink after
|
|
159
159
|
// resolveSafe (TOCTOU) — never follow it to read outside the workspace.
|
|
160
|
+
// O_NONBLOCK: opening a FIFO blocks until a writer appears, and no timer
|
|
161
|
+
// or signal handler can run inside a synchronous open — without this a
|
|
162
|
+
// `read` of a socket/FIFO would hang the CLI forever.
|
|
160
163
|
let fd: number
|
|
161
164
|
try {
|
|
162
|
-
fd = openNoFollow(filePath, constants.O_RDONLY)
|
|
165
|
+
fd = openNoFollow(filePath, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0))
|
|
163
166
|
} catch (err) {
|
|
164
167
|
if (isSymlinkLoop(err)) {
|
|
165
168
|
return { success: false, content: '', error: `Path is a symbolic link: ${filePath}` }
|
|
@@ -171,9 +174,20 @@ export function createReadTool(credentialConfig?: CredentialMaskingConfig): Tool
|
|
|
171
174
|
}
|
|
172
175
|
|
|
173
176
|
try {
|
|
174
|
-
|
|
177
|
+
const stat = fstatSync(fd)
|
|
178
|
+
if (stat.isDirectory()) {
|
|
175
179
|
return { success: false, content: '', error: `Path is a directory: ${filePath}` }
|
|
176
180
|
}
|
|
181
|
+
// FIFOs, sockets and device nodes are not files this tool can read a
|
|
182
|
+
// window out of; O_NONBLOCK got us past the open, so refuse here
|
|
183
|
+
// instead of blocking on the first read (or streaming /dev/zero).
|
|
184
|
+
if (!stat.isFile()) {
|
|
185
|
+
return {
|
|
186
|
+
success: false,
|
|
187
|
+
content: '',
|
|
188
|
+
error: `Path is not a regular file (FIFO, socket or device): ${filePath}`,
|
|
189
|
+
}
|
|
190
|
+
}
|
|
177
191
|
|
|
178
192
|
const offset = (params.offset as number) || 0
|
|
179
193
|
const limit = (params.limit as number) || DEFAULT_LIMIT
|
|
@@ -307,11 +307,19 @@ export const webFetchTool: ToolDefinition = {
|
|
|
307
307
|
const contentType = response.headers.get('content-type') || ''
|
|
308
308
|
const isHtml = contentType.includes('text/html') || contentType.includes('application/xhtml')
|
|
309
309
|
|
|
310
|
+
// A 4xx/5xx is a statement about the site, not a failure of the tool:
|
|
311
|
+
// hand the status and whatever body it returned to the model as a normal
|
|
312
|
+
// result, so it can re-aim the request instead of treating the fetch as
|
|
313
|
+
// broken. Deliberately not cached — a 404 today may be a 200 tomorrow.
|
|
310
314
|
if (!response.ok) {
|
|
315
|
+
const body = await response.text().catch(() => '')
|
|
316
|
+
const text = isHtml ? htmlToMarkdown(body, response.url || url) : body
|
|
311
317
|
return {
|
|
312
|
-
success:
|
|
313
|
-
content:
|
|
314
|
-
|
|
318
|
+
success: true,
|
|
319
|
+
content:
|
|
320
|
+
`HTTP ${response.status}: ${response.statusText}` +
|
|
321
|
+
(text ? `\n\n${text.slice(0, MAX_RETURN_CHARS)}` : ''),
|
|
322
|
+
metadata: { url, status: response.status },
|
|
315
323
|
}
|
|
316
324
|
}
|
|
317
325
|
|
|
@@ -158,8 +158,12 @@ export const webSearchTool: ToolDefinition = {
|
|
|
158
158
|
return {
|
|
159
159
|
success: false,
|
|
160
160
|
content: '',
|
|
161
|
+
// 说清楚「绕不过去」:不写这一句,模型最常见的下一步是改用 WebFetch
|
|
162
|
+
// 或浏览器去同一个站点再问一遍 —— 那既不会恢复配额,又是另一份预算。
|
|
161
163
|
error:
|
|
162
|
-
'Brave Search API rate limit reached (2,000/month on free tier).
|
|
164
|
+
'Brave Search API rate limit reached (2,000/month on free tier). ' +
|
|
165
|
+
'Do not route around it with WebFetch or a browser — the quota is spent ' +
|
|
166
|
+
'either way. Tell the user and wait for it to reset.',
|
|
163
167
|
}
|
|
164
168
|
}
|
|
165
169
|
if (response.status === 401) {
|
|
@@ -34,7 +34,8 @@ export interface CronJob {
|
|
|
34
34
|
sessionId?: string
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
-
|
|
37
|
+
/** Location of a job's JSON file. Also the base name its claim directory uses. */
|
|
38
|
+
export function jobPath(id: string): string {
|
|
38
39
|
return join(CRON_DIR, `${id}.json`)
|
|
39
40
|
}
|
|
40
41
|
|
|
@@ -23,13 +23,27 @@ const activeTimers = new Map<string, ReturnType<typeof setTimeout>>()
|
|
|
23
23
|
*/
|
|
24
24
|
const WAKEUP_DIR = miphamHome('wakeups')
|
|
25
25
|
|
|
26
|
-
|
|
26
|
+
type WakeupHandler = (sessionId: string, prompt: string, noop?: boolean) => void
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Handlers keyed by session — **not** a single slot.
|
|
30
|
+
*
|
|
31
|
+
* The daemon keeps one engine per session in the same process, and every engine
|
|
32
|
+
* construction used to overwrite the previous handler. A wakeup armed for session
|
|
33
|
+
* A then fired into whichever engine was built last, handing the loop prompt to a
|
|
34
|
+
* different conversation. The key is the session the timer was armed for, so a
|
|
35
|
+
* wakeup can only reach its own engine.
|
|
36
|
+
*/
|
|
37
|
+
const wakeupHandlers = new Map<string, WakeupHandler>()
|
|
27
38
|
|
|
28
39
|
/** 引擎在启动时注入——timer 到期后回调,把 loop prompt 交回引擎 re-invoke。 */
|
|
29
|
-
export function registerWakeupHandler(
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
40
|
+
export function registerWakeupHandler(sessionId: string, fn: WakeupHandler): void {
|
|
41
|
+
wakeupHandlers.set(sessionId, fn)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Drop a session's handler. Call this when the engine that owns it goes away. */
|
|
45
|
+
export function unregisterWakeupHandler(sessionId: string): void {
|
|
46
|
+
wakeupHandlers.delete(sessionId)
|
|
33
47
|
}
|
|
34
48
|
|
|
35
49
|
/** One session's pending wakeup, as written to disk. */
|
|
@@ -98,7 +112,7 @@ function armTimer(sessionId: string, prompt: string, noop: boolean, delayMs: num
|
|
|
98
112
|
const timeoutId = setTimeout(() => {
|
|
99
113
|
activeTimers.delete(timerKey)
|
|
100
114
|
clearPersistedWakeup(sessionId)
|
|
101
|
-
|
|
115
|
+
wakeupHandlers.get(sessionId)?.(sessionId, prompt, noop)
|
|
102
116
|
}, delayMs)
|
|
103
117
|
activeTimers.set(timerKey, timeoutId)
|
|
104
118
|
}
|
|
@@ -159,7 +173,7 @@ export function resumeWakeups(opts: { sessionId: string; now?: Date }): LostWake
|
|
|
159
173
|
export const scheduleWakeupTool: ToolDefinition = {
|
|
160
174
|
name: 'ScheduleWakeup',
|
|
161
175
|
description:
|
|
162
|
-
'Schedule when to resume work in /loop dynamic mode — the user invoked /loop without an interval, asking you to self-pace iterations of a specific task. Do NOT schedule a short-interval wakeup to poll for background work you started — when harness-tracked work finishes, you are re-invoked automatically. The runtime clamps to [60, 3600].',
|
|
176
|
+
'Schedule when to resume work in /loop dynamic mode — the user invoked /loop without an interval, asking you to self-pace iterations of a specific task. Do NOT schedule a short-interval wakeup to poll for background work you started — when harness-tracked work finishes, you are re-invoked automatically. The runtime clamps to [60, 3600]. Pick the delay by cache window, not by round minutes: sleeping past 300s means the next turn re-reads the conversation uncached. Use 60–270s while actively watching something nothing else will notify you about, 1200–1800s for idle waits. Avoid exactly 300s (pays the cache miss without buying a long wait), and do NOT pick 3600 — that fires just after the 1-hour prompt cache expires, so the full re-read buys nothing; 3300 or less lands inside the window.',
|
|
163
177
|
category: 'scheduling',
|
|
164
178
|
permission: 'self',
|
|
165
179
|
parameters: {
|
|
@@ -167,7 +181,8 @@ export const scheduleWakeupTool: ToolDefinition = {
|
|
|
167
181
|
properties: {
|
|
168
182
|
delaySeconds: {
|
|
169
183
|
type: 'number',
|
|
170
|
-
description:
|
|
184
|
+
description:
|
|
185
|
+
'Seconds from now to wake up. Clamped to [60, 3600] by the runtime; prefer 3300 or less so the next turn stays inside the prompt-cache window.',
|
|
171
186
|
},
|
|
172
187
|
reason: {
|
|
173
188
|
type: 'string',
|
package/src/tools/validation.ts
CHANGED
|
@@ -76,6 +76,17 @@ export function withValidation(tool: ToolDefinition): ToolDefinition {
|
|
|
76
76
|
return {
|
|
77
77
|
...tool,
|
|
78
78
|
async execute(params, ctx): Promise<ToolResult> {
|
|
79
|
+
// 参数不是合法 JSON 时,providers 交回的是 `{ _parseError, _raw }` 而不是
|
|
80
|
+
// `{}`。照常校验的话,模型会读到「缺少必需参数 url」—— 一个它明明写过的
|
|
81
|
+
// 参数,于是它去补参数,而不是去补那半个 JSON。先把这个事实说清楚。
|
|
82
|
+
if (typeof params._parseError === 'string') {
|
|
83
|
+
return {
|
|
84
|
+
success: false,
|
|
85
|
+
content: '',
|
|
86
|
+
error: t('errors.unparseable_args', { detail: params._parseError }),
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
79
90
|
const cleanParams = sanitizeParams(params)
|
|
80
91
|
const errors = validateParams(schema, cleanParams)
|
|
81
92
|
if (errors.length > 0) {
|
package/src/ui/app.tsx
CHANGED
|
@@ -66,6 +66,7 @@ import { recordLoopTurn, readAutoloopJournal } from '../commands/autoloop-journa
|
|
|
66
66
|
import { cancelAllSessionTimers, resumeWakeups } from '../tools/scheduling/schedule-wakeup.js'
|
|
67
67
|
import type { LostWakeup } from '../tools/scheduling/schedule-wakeup.js'
|
|
68
68
|
import { startCronPoller } from '../core/cron-poller'
|
|
69
|
+
import { exitSession } from '../core/session-exit'
|
|
69
70
|
|
|
70
71
|
interface AppProps {
|
|
71
72
|
engine: QueryEngine | RemoteEngine
|
|
@@ -1075,7 +1076,7 @@ export function App({
|
|
|
1075
1076
|
if (result.nextProvider) setProviderId(result.nextProvider)
|
|
1076
1077
|
if (result.nextModel) setModelId(result.nextModel)
|
|
1077
1078
|
}
|
|
1078
|
-
if (result.exit)
|
|
1079
|
+
if (result.exit) void exitSession(0)
|
|
1079
1080
|
return
|
|
1080
1081
|
}
|
|
1081
1082
|
|
|
@@ -1087,7 +1088,7 @@ export function App({
|
|
|
1087
1088
|
|
|
1088
1089
|
// /quit and /exit are special
|
|
1089
1090
|
if (command === '/exit' || command === '/quit') {
|
|
1090
|
-
|
|
1091
|
+
void exitSession(0)
|
|
1091
1092
|
}
|
|
1092
1093
|
|
|
1093
1094
|
// /focus toggle
|
|
@@ -1125,13 +1126,13 @@ export function App({
|
|
|
1125
1126
|
})
|
|
1126
1127
|
if (result.needsApiKey) {
|
|
1127
1128
|
// Don't process nextProvider/model when waiting for API key
|
|
1128
|
-
if (result.exit)
|
|
1129
|
+
if (result.exit) void exitSession(0)
|
|
1129
1130
|
return
|
|
1130
1131
|
}
|
|
1131
1132
|
if (result.clearMessages) setMessages([])
|
|
1132
1133
|
if (result.nextProvider) setProviderId(result.nextProvider)
|
|
1133
1134
|
if (result.nextModel) setModelId(result.nextModel)
|
|
1134
|
-
if (result.exit)
|
|
1135
|
+
if (result.exit) void exitSession(0)
|
|
1135
1136
|
if (result.clearMessages || (result.forwardedMessages?.length ?? 0) > 0) {
|
|
1136
1137
|
// The conversation this session is looking at just changed (/clear,
|
|
1137
1138
|
// /resume) — the read-before-write record belongs to the old one.
|
|
@@ -1276,7 +1277,7 @@ export function App({
|
|
|
1276
1277
|
return
|
|
1277
1278
|
}
|
|
1278
1279
|
if (ctrlC.isArmed()) {
|
|
1279
|
-
|
|
1280
|
+
void exitSession(0)
|
|
1280
1281
|
}
|
|
1281
1282
|
ctrlC.arm()
|
|
1282
1283
|
return
|
package/src/ui/commands.ts
CHANGED
|
@@ -8,7 +8,7 @@ import type { QueryEngine } from '../core/engine'
|
|
|
8
8
|
import type { MiphamConfig } from '../shared/index.ts'
|
|
9
9
|
import { formatContextWindow } from '../shared/format'
|
|
10
10
|
import { sanitizeInlineField } from '../shared/sanitize'
|
|
11
|
-
import type
|
|
11
|
+
import { truncateSkillDescription, type SkillsLoader } from '../skills/loader'
|
|
12
12
|
import { loadSkillUsage } from '../skills/usage'
|
|
13
13
|
import type { PluginManager } from '../plugin/plugin-manager'
|
|
14
14
|
import type { Message } from '../shared/types.js'
|
|
@@ -677,10 +677,11 @@ const skillsCmd: CommandHandler = (ctx) => {
|
|
|
677
677
|
|
|
678
678
|
const lines: string[] = [
|
|
679
679
|
`── Standard Skills (${counts.standard}) ──`,
|
|
680
|
-
|
|
680
|
+
// 描述是写给模型的(常是好几段指令),不是终端里的一行摘要。
|
|
681
|
+
...standard.map((s) => ` ${s.name.padEnd(28)} ${truncateSkillDescription(s.description)}`),
|
|
681
682
|
'',
|
|
682
683
|
`── Mipham Exclusive (${counts.mipham}) ──`,
|
|
683
|
-
...mipham.map((s) => ` ${s.name.padEnd(20)} ${s.description}`),
|
|
684
|
+
...mipham.map((s) => ` ${s.name.padEnd(20)} ${truncateSkillDescription(s.description)}`),
|
|
684
685
|
'',
|
|
685
686
|
t('commands.skills.loaded', { count: String(counts.total) }),
|
|
686
687
|
]
|
|
@@ -2460,7 +2461,14 @@ const usageCmd: CommandHandler = (ctx) => {
|
|
|
2460
2461
|
const estTokens = c.getEstimatedTokens()
|
|
2461
2462
|
const msgs = c.getMessages()
|
|
2462
2463
|
const maxTokens = c.getMaxTokens()
|
|
2463
|
-
|
|
2464
|
+
// Guard the ratio before formatting: an unknown/zero window makes it NaN or
|
|
2465
|
+
// Infinity, and a NaN `pct` later reaches `'░'.repeat(20 - …)` as a negative
|
|
2466
|
+
// or non-integer count — a RangeError that kills the whole `/usage` command.
|
|
2467
|
+
const maxTokensShown = Number.isFinite(maxTokens) && maxTokens > 0 ? maxTokens : 0
|
|
2468
|
+
const rawPct = maxTokensShown > 0 ? (estTokens / maxTokensShown) * 100 : 0
|
|
2469
|
+
const pctNum = Number.isFinite(rawPct) ? Math.min(100, Math.max(0, rawPct)) : 0
|
|
2470
|
+
const pct = pctNum.toFixed(1)
|
|
2471
|
+
const filledCells = Math.min(20, Math.max(0, Math.ceil(pctNum / 5)))
|
|
2464
2472
|
|
|
2465
2473
|
const tracker = ctx.engine.getUsageTracker()
|
|
2466
2474
|
const summary = tracker.getSummary()
|
|
@@ -2501,12 +2509,12 @@ const usageCmd: CommandHandler = (ctx) => {
|
|
|
2501
2509
|
content: stripIndent`
|
|
2502
2510
|
${t('commands.usage.title')}
|
|
2503
2511
|
${apiLine}
|
|
2504
|
-
${t('commands.usage.context_line', { est: estTokens.toLocaleString(), max:
|
|
2512
|
+
${t('commands.usage.context_line', { est: estTokens.toLocaleString(), max: maxTokensShown.toLocaleString(), pct })}
|
|
2505
2513
|
${t('commands.usage.messages_line', { count: String(msgs.length) })}
|
|
2506
2514
|
${t('commands.usage.provider_line', { provider: ctx.providerId })}
|
|
2507
2515
|
${t('commands.usage.model_line', { model: ctx.modelId })}
|
|
2508
2516
|
|
|
2509
|
-
${'█'.repeat(
|
|
2517
|
+
${'█'.repeat(filledCells)}${'░'.repeat(20 - filledCells)} ${pct}%
|
|
2510
2518
|
${toolSection}${loopSection}
|
|
2511
2519
|
|
|
2512
2520
|
${t('commands.usage.hint')}
|
|
@@ -2527,7 +2535,7 @@ const reloadSkillsCmd: CommandHandler = (ctx) => {
|
|
|
2527
2535
|
}
|
|
2528
2536
|
const skills = ctx.skillsLoader.list()
|
|
2529
2537
|
return {
|
|
2530
|
-
content: `${t('commands.reload_skills.confirmed', { count: String(skills.length) })}\n\n${skills.map((s) => ` ${s.name.padEnd(28)} ${s.type.padEnd(10)} ${s.description}`).join('\n')}`,
|
|
2538
|
+
content: `${t('commands.reload_skills.confirmed', { count: String(skills.length) })}\n\n${skills.map((s) => ` ${s.name.padEnd(28)} ${s.type.padEnd(10)} ${truncateSkillDescription(s.description)}`).join('\n')}`,
|
|
2531
2539
|
}
|
|
2532
2540
|
} catch (err) {
|
|
2533
2541
|
return { content: t('commands.reload_skills.failed', { error: String(err) }) }
|
|
@@ -3223,7 +3231,8 @@ const loopCmd: CommandHandler = async (ctx, args) => {
|
|
|
3223
3231
|
`You are in an autonomous loop. Each iteration:\n` +
|
|
3224
3232
|
`1. Make progress on the task above\n` +
|
|
3225
3233
|
`2. When you need to wait (e.g., for a deploy, CI, external event), call ScheduleWakeup with:\n` +
|
|
3226
|
-
` - delaySeconds: your best estimate of how long to wait (60-3600
|
|
3234
|
+
` - delaySeconds: your best estimate of how long to wait (60-3600; prefer ≤3300\n` +
|
|
3235
|
+
` so the wake-up stays inside the prompt-cache window)\n` +
|
|
3227
3236
|
` - reason: one sentence explaining why\n` +
|
|
3228
3237
|
` - prompt: include this full autonomous loop ID: ${sessionId}\n` +
|
|
3229
3238
|
`3. When the task is COMPLETE, call ScheduleWakeup with stop:true\n` +
|
|
@@ -222,22 +222,51 @@ export async function workflowAgent(
|
|
|
222
222
|
/* best-effort */
|
|
223
223
|
}
|
|
224
224
|
|
|
225
|
-
// Remove worktree and branch
|
|
225
|
+
// Remove worktree and branch.
|
|
226
|
+
//
|
|
227
|
+
// Every step here used to be fire-and-forget: a `worktree remove` that
|
|
228
|
+
// failed left the registration behind, the `branch -D` then failed too
|
|
229
|
+
// ("used by worktree at …"), and the run reported clean either way. So
|
|
230
|
+
// check both exits and say what is left — an unchanged agent worktree
|
|
231
|
+
// that nobody removes is state the next run has to trip over.
|
|
232
|
+
const leftovers: string[] = []
|
|
226
233
|
try {
|
|
227
234
|
const rmProc = Bun.spawn(['git', 'worktree', 'remove', '--force', worktreePath], {
|
|
228
235
|
stdout: 'pipe',
|
|
229
236
|
stderr: 'pipe',
|
|
230
237
|
})
|
|
231
|
-
await rmProc.exited
|
|
238
|
+
let removed = (await rmProc.exited) === 0
|
|
239
|
+
if (!removed) {
|
|
240
|
+
// A worktree whose directory is already gone leaves only a stale
|
|
241
|
+
// registration; prune clears it so the branch delete can proceed.
|
|
242
|
+
const pruneProc = Bun.spawn(['git', 'worktree', 'prune'], {
|
|
243
|
+
stdout: 'pipe',
|
|
244
|
+
stderr: 'pipe',
|
|
245
|
+
})
|
|
246
|
+
await pruneProc.exited
|
|
247
|
+
const retry = Bun.spawn(['git', 'worktree', 'remove', '--force', worktreePath], {
|
|
248
|
+
stdout: 'pipe',
|
|
249
|
+
stderr: 'pipe',
|
|
250
|
+
})
|
|
251
|
+
removed = (await retry.exited) === 0
|
|
252
|
+
}
|
|
253
|
+
if (!removed) leftovers.push(`worktree ${worktreePath}`)
|
|
254
|
+
|
|
232
255
|
if (worktreeBranch) {
|
|
233
256
|
const brProc = Bun.spawn(['git', 'branch', '-D', worktreeBranch], {
|
|
234
257
|
stdout: 'pipe',
|
|
235
258
|
stderr: 'pipe',
|
|
236
259
|
})
|
|
237
|
-
await brProc.exited
|
|
260
|
+
if ((await brProc.exited) !== 0) leftovers.push(`branch ${worktreeBranch}`)
|
|
238
261
|
}
|
|
239
|
-
} catch {
|
|
240
|
-
|
|
262
|
+
} catch (err) {
|
|
263
|
+
leftovers.push(`${worktreePath} (${err instanceof Error ? err.message : String(err)})`)
|
|
264
|
+
}
|
|
265
|
+
if (leftovers.length > 0) {
|
|
266
|
+
process.stderr.write(
|
|
267
|
+
`⚠️ workflow: could not clean up ${leftovers.join(' and ')} — ` +
|
|
268
|
+
`the run finished, but this state needs manual removal.\n`,
|
|
269
|
+
)
|
|
241
270
|
}
|
|
242
271
|
}
|
|
243
272
|
}
|