@miphamai/cli 0.85.17 → 0.85.19

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.
Files changed (40) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/src/agent/sub-agent.ts +11 -0
  4. package/src/agent/types.ts +8 -0
  5. package/src/agent-view/agent-view-manager.ts +50 -0
  6. package/src/config/defaults.ts +6 -1
  7. package/src/core/credential-masker/output-scrub.ts +8 -1
  8. package/src/core/engine.ts +88 -9
  9. package/src/core/instructions.ts +97 -2
  10. package/src/core/permission-rules.ts +52 -4
  11. package/src/core/permission.ts +6 -2
  12. package/src/core/session-log.ts +10 -0
  13. package/src/daemon/channel-message.ts +8 -1
  14. package/src/daemon/session-worker.ts +17 -2
  15. package/src/i18n-core/locales/en-US.json +4 -2
  16. package/src/i18n-core/locales/zh-CN.json +4 -2
  17. package/src/index.tsx +22 -1
  18. package/src/mcp/client.ts +20 -1
  19. package/src/mcp/http-transport.ts +48 -3
  20. package/src/mcp/instructions.ts +25 -1
  21. package/src/mcp/protocol.ts +69 -2
  22. package/src/providers/anthropic.ts +47 -12
  23. package/src/providers/fetch-utils.ts +72 -4
  24. package/src/providers/openai-compat.ts +13 -10
  25. package/src/shared/package-info.ts +2 -2
  26. package/src/shared/types.ts +12 -0
  27. package/src/skills/loader.ts +13 -2
  28. package/src/skills/sanitizer.ts +16 -8
  29. package/src/tools/agent/agent.ts +24 -0
  30. package/src/tools/agent/skill.ts +13 -0
  31. package/src/tools/artifact/artifact.ts +9 -9
  32. package/src/tools/exec/bash.ts +10 -0
  33. package/src/tools/file/grep.ts +11 -2
  34. package/src/tools/file/read.ts +21 -0
  35. package/src/tools/network/web-fetch.ts +87 -22
  36. package/src/tools/scheduling/schedule-wakeup.ts +156 -32
  37. package/src/ui/app.tsx +47 -6
  38. package/src/ui/chat.tsx +15 -1
  39. package/src/ui/input.tsx +25 -1
  40. package/src/workflow/primitives/agent.ts +1 -0
@@ -245,8 +245,19 @@ export class SkillsLoader implements Skills {
245
245
  }
246
246
 
247
247
  private nameFromPath(path: string): string {
248
- const base = path.split('/').pop() || ''
249
- return base.replace(/\.(SKILL|mipham-skill)\.md$/i, '')
248
+ const parts = path.split('/').filter(Boolean)
249
+ const base = parts.pop() ?? ''
250
+ // `foo.SKILL.md` / `foo.mipham-skill.md` — the file name carries the skill.
251
+ const stem = base.replace(/\.md$/i, '').replace(/\.(SKILL|mipham-skill)$/i, '')
252
+ if (stem && stem !== 'SKILL' && stem !== 'mipham-skill') return stem
253
+ // Directory layout (`skills/<name>/SKILL.md`, the Claude-plugin shape). Every
254
+ // one of these files is literally named `SKILL.md`, so the file name names
255
+ // nothing — they all collide on one key and the last loaded silently wins.
256
+ // The folder is the name. Skip the `skills` bucket itself so a flat
257
+ // `skills/SKILL.md` falls through to the plugin directory above it.
258
+ let dir = parts.pop()
259
+ while (dir === 'skills') dir = parts.pop()
260
+ return dir || base
250
261
  }
251
262
  }
252
263
 
@@ -71,11 +71,19 @@ const SOURCE_TAGS: Record<string, string> = {
71
71
  /**
72
72
  * Sanitize a skill body (markdown instructions) for safe execution.
73
73
  *
74
- * Security measures:
75
- * - `! command` patterns → escaped to `! command` (prevents AI from treating as shell command)
76
- * - `@file` references → prefixed with safety note
77
- * - Trailing backticks that could break markdown fences → escaped
78
- * - Excessively long lines → truncated
74
+ * Three transformations, each of which also pushes a warning:
75
+ * - a line starting with `!command` → `! command`. The inserted character is a
76
+ * **plain space**, which is what breaks the exact `!`-prefixed shape a session
77
+ * treats as a shell command. Deliberately *not* a zero-width space: U+200B is on
78
+ * the dangerous-invisible strip list in `shared/sanitize.ts`, so a ZWSP written
79
+ * here would be removed further down the pipe and the neutralization would undo
80
+ * itself.
81
+ * - `@file.ext` references → `@ file.ext` (a space after the `@` stops expansion)
82
+ * - an odd number of ``` fences → a closing fence is appended
83
+ *
84
+ * Detection is **line-scoped**: `!` must open its line, and the lookahead must find a
85
+ * non-space on that same line — hence `[^\S\n]*` rather than `\s*`, which would reach
86
+ * across the newline and report the next line's first word as a command.
79
87
  */
80
88
  export function sanitizeSkillBody(body: string): SanitizeResult {
81
89
  const warnings: string[] = []
@@ -84,15 +92,15 @@ export function sanitizeSkillBody(body: string): SanitizeResult {
84
92
 
85
93
  // ── 1. Detect and warn about `!` shell command patterns ──
86
94
  // Pattern: line starting with `!` (Bash command marker in some AI contexts)
87
- const bangCommandRegex = /^!\s*(\S+)/gm
95
+ const bangCommandRegex = /^![^\S\n]*(\S+)/gm
88
96
  let bangMatch: RegExpExecArray | null
89
97
  const bangCommands: string[] = []
90
98
  while ((bangMatch = bangCommandRegex.exec(text)) !== null) {
91
99
  bangCommands.push(bangMatch[1] || '')
92
100
  }
93
101
  if (bangCommands.length > 0) {
94
- // Escape `!` → `! ` (zero-width space after bang to neutralize)
95
- text = text.replace(/^!(?=\s*\S)/gm, '! ')
102
+ // Escape `!` → `! ` (a plain space — see the docblock for why not a zero-width one)
103
+ text = text.replace(/^!(?=[^\S\n]*\S)/gm, '! ')
96
104
  modified = true
97
105
  warnings.push(
98
106
  `Skill body contained ${bangCommands.length} shell-command-like patterns (${bangCommands.slice(0, 3).join(', ')}${bangCommands.length > 3 ? '...' : ''}). Escaped to prevent unintended command execution.`,
@@ -5,6 +5,9 @@ import { getBackgroundAgentRegistry } from '../../agent/background-registry'
5
5
 
6
6
  const VALID_TYPES: SubAgentType[] = ['general', 'explore', 'plan', 'code-review']
7
7
 
8
+ /** Same domain as the session-level `/effort` command (`ui/commands.ts`). */
9
+ const VALID_EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max']
10
+
8
11
  /**
9
12
  * Resolve whether a sub-agent should run in the background.
10
13
  *
@@ -64,6 +67,14 @@ export const agentTool: ToolDefinition = {
64
67
  description:
65
68
  'When false, execute synchronously and return the result directly. Default: true (background).',
66
69
  },
70
+ effort: {
71
+ type: 'string',
72
+ enum: ['low', 'medium', 'high', 'xhigh', 'max'],
73
+ description:
74
+ 'Reasoning effort for this sub-agent, same levels as /effort. Higher levels get a longer ' +
75
+ 'streaming idle budget so a long thinking pass is not mistaken for a stalled connection. ' +
76
+ 'Omit to inherit the provider default.',
77
+ },
67
78
  },
68
79
  required: ['description', 'prompt'],
69
80
  },
@@ -80,6 +91,18 @@ export const agentTool: ToolDefinition = {
80
91
  }
81
92
  }
82
93
 
94
+ // Reject rather than pass through: an unrecognized level silently lands on
95
+ // the 1× timeout, i.e. it behaves exactly like omitting the parameter while
96
+ // reading as though it took effect.
97
+ const effort = params.effort as string | undefined
98
+ if (effort !== undefined && !VALID_EFFORTS.includes(effort)) {
99
+ return {
100
+ success: false,
101
+ content: '',
102
+ error: `Invalid effort "${effort}". Valid levels: ${VALID_EFFORTS.join(', ')}`,
103
+ }
104
+ }
105
+
83
106
  const registry = ctx.registry
84
107
  const toolRegistry = ctx.toolRegistry
85
108
  if (!registry || !toolRegistry) {
@@ -112,6 +135,7 @@ export const agentTool: ToolDefinition = {
112
135
  type: agentType,
113
136
  agentDef,
114
137
  runInBackground,
138
+ effort,
115
139
  // Hand the caller's services down: the sub-agent keeps running the same
116
140
  // skills/agents/artifacts, and only the fields it owns are overridden.
117
141
  toolContext: ctx,
@@ -39,6 +39,19 @@ export const skillTool: ToolDefinition = {
39
39
  }
40
40
  }
41
41
 
42
+ // A skill marked `disable-model-invocation` is reserved for the user to run
43
+ // by hand. The broadcast filter (loader.buildSystemReminder) keeps it out of
44
+ // the ambient list, but that is not a gate: the model can still name it —
45
+ // from a compaction summary, a file, or its own memory — and land here. The
46
+ // reservation only holds if it is enforced at the point of use.
47
+ if (skill.disableModelInvocation) {
48
+ return {
49
+ success: false,
50
+ content: '',
51
+ error: `Skill "${skillName}" is reserved for user invocation (disable-model-invocation: true) and cannot be run through the Skill tool. Ask the user to run it.`,
52
+ }
53
+ }
54
+
42
55
  // Extract executable assets (scripts/references) if this skill bundles them.
43
56
  // No-op for every skill that has no entry in BUNDLED_SKILL_ASSETS.
44
57
  // A write failure (EACCES/ENOSPC) must not abort invocation: the skill body
@@ -62,7 +62,11 @@ export const artifactTool: ToolDefinition = {
62
62
  // directory are one and the same; computing it here is what made the URL a
63
63
  // guaranteed 404 before.
64
64
  const baseDir = artifactsRoot(ctx.cwd)
65
- const sessionDir = join(baseDir, ctx.sessionId)
65
+ // Not always `ctx.sessionId`: a sub-agent's session id is the literal
66
+ // `'sub-agent'`, shared by every sub-agent in every session (see
67
+ // `ToolContext.artifactSessionId`).
68
+ const sessionId = ctx.artifactSessionId ?? ctx.sessionId
69
+ const sessionDir = join(baseDir, sessionId)
66
70
  mkdirSync(sessionDir, { recursive: true })
67
71
 
68
72
  const ext = type === 'svg' ? '.svg' : '.html'
@@ -82,9 +86,7 @@ export const artifactTool: ToolDefinition = {
82
86
  const isUpdate = existsSync(filepath)
83
87
  if (isUpdate) {
84
88
  const manifest = readManifest(baseDir)
85
- const existing = manifest.artifacts.find(
86
- (a) => a.name === name && a.sessionId === ctx.sessionId,
87
- )
89
+ const existing = manifest.artifacts.find((a) => a.name === name && a.sessionId === sessionId)
88
90
  if (existing) {
89
91
  archivedVersion = archiveVersion(baseDir, existing)
90
92
  }
@@ -94,13 +96,11 @@ export const artifactTool: ToolDefinition = {
94
96
  writeFileSync(filepath, content, 'utf-8')
95
97
 
96
98
  // Build URL and manifest entry
97
- const url = port
98
- ? `http://localhost:${port}/${ctx.sessionId}/${filename}`
99
- : `file://${filepath}`
99
+ const url = port ? `http://localhost:${port}/${sessionId}/${filename}` : `file://${filepath}`
100
100
 
101
101
  // Preserve existing version count
102
102
  const manifestPre = readManifest(baseDir)
103
- const prev = manifestPre.artifacts.find((a) => a.name === name && a.sessionId === ctx.sessionId)
103
+ const prev = manifestPre.artifacts.find((a) => a.name === name && a.sessionId === sessionId)
104
104
  const versionCount = prev?.versionCount || (isUpdate ? 1 : undefined)
105
105
 
106
106
  const { quarantined } = addToManifest(
@@ -112,7 +112,7 @@ export const artifactTool: ToolDefinition = {
112
112
  size,
113
113
  type: type as 'html' | 'svg',
114
114
  createdAt: new Date().toISOString(),
115
- sessionId: ctx.sessionId,
115
+ sessionId,
116
116
  versions: prev?.versions,
117
117
  versionCount,
118
118
  },
@@ -32,6 +32,16 @@ const BLOCKED_PATTERNS = [
32
32
  // `rm -rf .` and its path spellings `./` and `../` delete the working directory;
33
33
  // `./build` and `../vendor` name an entry inside it and stay allowed.
34
34
  /\brm\s+-(?:rf|fr)\s+['"]?\.\.?(?:\/)?(?=["'\s;&|>]|$)/,
35
+ // The home directory under another name is still the home directory. `$HOME`
36
+ // expands to the same tree as `~`; on Windows `C:\Users\<name>` *is* the profile
37
+ // directory, long or in its 8.3 short form (`C:\Users\GUOHUA~1`). Guarding only
38
+ // the literal spellings above leaves each of these a one-word bypass.
39
+ /\brm\s+-(?:rf|fr)\s+['"]?\$\{?HOME\}?(?:["'\s/]|$)/,
40
+ /\brm\s+-(?:rf|fr)\s+['"]?[A-Za-z]:[\\/](?=["'\s;&|>]|$)/,
41
+ /\brm\s+-(?:rf|fr)\s+['"]?[A-Za-z]:[\\/]Users[\\/][^\\/\s"']+[\\/]?(?=["'\s;&|>]|$)/i,
42
+ // cmd.exe spells the same directories with percent signs; in scope whenever a
43
+ // command hands off to cmd (`cmd /c …`).
44
+ /\brm\s+-(?:rf|fr)\s+['"]?%(?:USERPROFILE|HOMEPATH|HOMEDRIVE)%/i,
35
45
  // Filesystem manipulation
36
46
  /\bmkfs\./,
37
47
  /\bdd\s+if=/,
@@ -94,19 +94,28 @@ export function createGrepTool(credentialConfig?: CredentialMaskingConfig): Tool
94
94
  properties: {
95
95
  pattern: { type: 'string', description: 'Regex pattern to search for' },
96
96
  path: { type: 'string', description: 'Directory or file to search in' },
97
+ file_path: {
98
+ type: 'string',
99
+ description:
100
+ 'Alias for "path" — accepted so a caller that names the search root the way Read/Write/Edit do still lands where it meant to.',
101
+ },
97
102
  include: { type: 'string', description: 'File pattern to include (e.g., "*.ts")' },
98
103
  },
99
104
  required: ['pattern'],
100
105
  },
101
106
  async execute(params, ctx) {
102
107
  const pattern = params.pattern as string
103
- const searchPath = resolveSafe(ctx.cwd, (params.path as string) || '.')
108
+ // `file_path` is the alias callers reach for (Read/Write/Edit all use it).
109
+ // Without it the value is dropped and the search silently falls back to `cwd`
110
+ // — answering a question about the wrong tree without saying so.
111
+ const explicitPath = (params.path as string) || (params.file_path as string) || undefined
112
+ const searchPath = resolveSafe(ctx.cwd, explicitPath || '.')
104
113
  const include = params.include as string | undefined
105
114
 
106
115
  // Scope guard: a top-level search root (home or filesystem root) scans an
107
116
  // enormous tree and stalls the find fallback for minutes. Fail fast and
108
117
  // ask for a project-scoped path instead of silently scanning everything.
109
- if (!params.path && isTopLevelScope(searchPath)) {
118
+ if (!explicitPath && isTopLevelScope(searchPath)) {
110
119
  return {
111
120
  success: false,
112
121
  content: '',
@@ -193,6 +193,27 @@ export function createReadTool(credentialConfig?: CredentialMaskingConfig): Tool
193
193
  result = formatLines(lines, offset)
194
194
  }
195
195
 
196
+ // ── Binary sniff ──
197
+ // A NUL byte is the tell `file(1)` and git both use for "this is not
198
+ // text". Without this, a PNG/zip/object file is decoded as UTF-8 with
199
+ // replacement characters and handed to the model as garbled "text" it
200
+ // will then reason about — a silently wrong answer, not an error.
201
+ //
202
+ // The check is on the string actually being returned, not on the head of
203
+ // the file: a *sparse* text file (a log preallocated with `truncate`, a
204
+ // hole in the middle) is real text where it was written, and reading its
205
+ // opening lines is exactly what a caller asking for line 1–3 wants. Only
206
+ // the bytes that would reach the model have to be text.
207
+ if (result.includes('\0')) {
208
+ return {
209
+ success: false,
210
+ content: '',
211
+ error:
212
+ `Not a text file (the requested window contains NUL bytes): ${filePath}. ` +
213
+ `Use a shell tool (e.g. \`file\`, \`xxd\`) to inspect binary content.`,
214
+ }
215
+ }
216
+
196
217
  // ── Read tracking: mark file as read for Write tool safety ──
197
218
  ctx.readFiles?.add(filePath)
198
219
  return { success: true, content: result }
@@ -4,25 +4,37 @@ import { validateUrl } from '../../security/url'
4
4
 
5
5
  // ── In-memory cache (15-min TTL per URL) ──
6
6
 
7
+ /** Most characters returned in one call. Past this the caller pages with `offset`. */
8
+ const MAX_RETURN_CHARS = 100_000
9
+
7
10
  interface CacheEntry {
8
11
  content: string
9
12
  timestamp: number
13
+ /** Is `content` the whole page, or only its first `MAX_RETURN_CHARS`? */
14
+ complete: boolean
10
15
  }
11
16
 
12
17
  const CACHE_TTL = 15 * 60 * 1000 // 15 minutes
13
18
  const cache = new Map<string, CacheEntry>()
14
19
 
15
- function getCached(url: string): string | undefined {
20
+ /**
21
+ * `complete` says whether `content` is the whole page or only its first
22
+ * `MAX_RETURN_CHARS`. A caller asking past the end of an incomplete entry has to
23
+ * re-fetch: answering from the cache would report "no more content" for a page
24
+ * that has plenty, which is the same wrong answer a silently truncated read gave.
25
+ */
26
+ function getCached(url: string, needFrom: number): CacheEntry | undefined {
16
27
  const entry = cache.get(url)
17
28
  if (!entry) return undefined
18
29
  if (Date.now() - entry.timestamp > CACHE_TTL) {
19
30
  cache.delete(url)
20
31
  return undefined
21
32
  }
22
- return entry.content
33
+ if (!entry.complete && needFrom >= entry.content.length) return undefined
34
+ return entry
23
35
  }
24
36
 
25
- function setCache(url: string, content: string): void {
37
+ function setCache(url: string, content: string, complete: boolean): void {
26
38
  // Evict oldest entries if cache grows too large (max 200 URLs)
27
39
  if (cache.size >= 200) {
28
40
  const oldest = [...cache.entries()].sort((a, b) => a[1].timestamp - b[1].timestamp)
@@ -30,7 +42,7 @@ function setCache(url: string, content: string): void {
30
42
  cache.delete(oldest[i]![0])
31
43
  }
32
44
  }
33
- cache.set(url, { content, timestamp: Date.now() })
45
+ cache.set(url, { content, timestamp: Date.now(), complete })
34
46
  }
35
47
 
36
48
  // ── HTTP→HTTPS upgrade ──
@@ -142,6 +154,54 @@ function resolveUrl(href: string, baseUrl: string): string {
142
154
  }
143
155
  }
144
156
 
157
+ // ── Result rendering ──
158
+
159
+ /**
160
+ * Render the requested window of `full`, with the header and a notice saying how
161
+ * much of the page is *not* in this answer and which `offset` continues it.
162
+ *
163
+ * The notice is the point. A bare `... (truncated)` is indistinguishable from
164
+ * "this was the whole page", so the caller reports a partial read as a complete
165
+ * one; and without an `offset` to pass, everything past the first window was
166
+ * permanently unreachable rather than merely unread.
167
+ */
168
+ function withOffsetNotice(
169
+ full: string,
170
+ offset: number,
171
+ prompt: string,
172
+ url: string,
173
+ complete: boolean,
174
+ ): string {
175
+ const header = prompt
176
+ ? `── WebFetch: ${url} ──\nPrompt: ${prompt}\n\n`
177
+ : `── WebFetch: ${url} ──\n\n`
178
+
179
+ if (offset >= full.length) {
180
+ return (
181
+ header +
182
+ `... (offset ${offset} is past the end: this page has ` +
183
+ `${complete ? full.length : `at least ${full.length}`} characters)`
184
+ )
185
+ }
186
+
187
+ const window = full.slice(offset, offset + MAX_RETURN_CHARS)
188
+ const end = offset + window.length
189
+
190
+ // Whole page, asked for from the start — nothing to qualify.
191
+ if (complete && offset === 0 && end === full.length) return header + window
192
+
193
+ const total = complete ? `${full.length}` : `at least ${full.length}`
194
+ const remaining = complete ? full.length - end : undefined
195
+ const notice =
196
+ remaining === undefined
197
+ ? `\n\n... (characters ${offset}–${end - 1} of ${total}; call again with offset=${end} for more)`
198
+ : remaining > 0
199
+ ? `\n\n... (characters ${offset}–${end - 1} of ${total}; ${remaining} unread — call again with offset=${end} for the next part)`
200
+ : `\n\n... (characters ${offset}–${end - 1} of ${total}; end of page)`
201
+
202
+ return header + window + notice
203
+ }
204
+
145
205
  // ── Tool Definition ──
146
206
 
147
207
  export const webFetchTool: ToolDefinition = {
@@ -157,7 +217,12 @@ export const webFetchTool: ToolDefinition = {
157
217
  prompt: {
158
218
  type: 'string',
159
219
  description:
160
- 'What to extract from the page (e.g., "find the API docs for authentication"). The tool returns the full page; the prompt helps focus extraction.',
220
+ 'What to extract from the page (e.g., "find the API docs for authentication"). The tool returns the page content — truncated past 100,000 characters, with the omitted count stated — and the prompt helps focus extraction.',
221
+ },
222
+ offset: {
223
+ type: 'integer',
224
+ description:
225
+ 'Character offset to start reading from (default 0). A long page is returned 100,000 characters at a time; the truncation notice names the offset to pass next.',
161
226
  },
162
227
  },
163
228
  required: ['url'],
@@ -165,15 +230,17 @@ export const webFetchTool: ToolDefinition = {
165
230
  async execute(params, _ctx) {
166
231
  const rawUrl = params.url as string
167
232
  const prompt = (params.prompt as string) || ''
233
+ const offset = Math.max(0, Number(params.offset) || 0)
168
234
  const url = upgradeToHttps(rawUrl)
169
235
 
170
- // Check cache
171
- const cached = getCached(url)
236
+ // Check cache — an incomplete entry (first 100k only) cannot answer a
237
+ // request that starts past what it holds.
238
+ const cached = getCached(url, offset)
172
239
  if (cached) {
173
240
  return {
174
241
  success: true,
175
- content: cached,
176
- metadata: { cached: true, url },
242
+ content: withOffsetNotice(cached.content, offset, prompt, url, cached.complete),
243
+ metadata: { cached: true, url, offset },
177
244
  }
178
245
  }
179
246
 
@@ -259,20 +326,18 @@ export const webFetchTool: ToolDefinition = {
259
326
  content = await response.text()
260
327
  }
261
328
 
262
- // Truncate to 100K characters
263
- if (content.length > 100_000) {
264
- content = content.slice(0, 100_000) + '\n\n... (truncated)'
265
- }
266
-
267
- // Cache the result
268
- setCache(url, content)
329
+ // Cache the first window. The cache stays the size it always was (one
330
+ // `MAX_RETURN_CHARS` per URL) — `complete` is what lets a later `offset`
331
+ // tell "this is the whole page" apart from "this is the first slice of it",
332
+ // and re-fetch when it needs more.
333
+ const complete = content.length <= MAX_RETURN_CHARS
334
+ setCache(url, content.slice(0, MAX_RETURN_CHARS), complete)
269
335
 
270
- // Include prompt context if provided
271
- const header = prompt
272
- ? `── WebFetch: ${url} ──\nPrompt: ${prompt}\n\n`
273
- : `── WebFetch: ${url} ──\n\n`
274
-
275
- return { success: true, content: header + content, metadata: { url, size: content.length } }
336
+ return {
337
+ success: true,
338
+ content: withOffsetNotice(content, offset, prompt, url, complete),
339
+ metadata: { url, offset, totalSize: content.length },
340
+ }
276
341
  } catch (err) {
277
342
  const message =
278
343
  err instanceof Error && err.name === 'AbortError'
@@ -1,4 +1,9 @@
1
+ import { mkdirSync, readFileSync, unlinkSync, readdirSync, existsSync } from 'node:fs'
2
+ import { createHash } from 'node:crypto'
3
+ import { join } from 'node:path'
1
4
  import type { ToolDefinition } from '../../shared/index.ts'
5
+ import { atomicWriteFileSync } from '../../shared/atomic-write'
6
+ import { miphamHome } from '../../core/paths.ts'
2
7
 
3
8
  /**
4
9
  * Active wakeup timers — in-memory, per-session.
@@ -6,6 +11,18 @@ import type { ToolDefinition } from '../../shared/index.ts'
6
11
  */
7
12
  const activeTimers = new Map<string, ReturnType<typeof setTimeout>>()
8
13
 
14
+ /**
15
+ * Where pending wakeups are written — one file per session.
16
+ *
17
+ * A `setTimeout` cannot fire into a process that is not running, and here that is
18
+ * not hypothetical: the daemon recycles an idle worker after 30 minutes
19
+ * (`daemon/worker-pool.ts`) while a wakeup may be up to 3600s out. So the *intent*
20
+ * is written here and the timer is rebuilt from it on the next start — a wakeup
21
+ * still in the future is restored exactly, and one that came due while we were gone
22
+ * is handed back to the model instead of vanishing (`resumeWakeups`).
23
+ */
24
+ const WAKEUP_DIR = miphamHome('wakeups')
25
+
9
26
  let wakeupHandler: ((sessionId: string, prompt: string, noop?: boolean) => void) | null = null
10
27
 
11
28
  /** 引擎在启动时注入——timer 到期后回调,把 loop prompt 交回引擎 re-invoke。 */
@@ -15,6 +32,130 @@ export function registerWakeupHandler(
15
32
  wakeupHandler = fn
16
33
  }
17
34
 
35
+ /** One session's pending wakeup, as written to disk. */
36
+ export interface PersistedWakeup {
37
+ sessionId: string
38
+ prompt: string
39
+ noop: boolean
40
+ reason: string
41
+ /** When the timer was due (ISO). */
42
+ firesAt: string
43
+ }
44
+
45
+ /**
46
+ * File name for a session's slot. Hashed, not used literally: the session id is
47
+ * whatever `--resume <id>` was given, i.e. operator input, and a `../` in it must
48
+ * not walk out of this directory.
49
+ */
50
+ function wakeupPath(sessionId: string): string {
51
+ const name = createHash('sha256').update(sessionId).digest('hex').slice(0, 32)
52
+ return join(WAKEUP_DIR, `${name}.json`)
53
+ }
54
+
55
+ function persistWakeup(entry: PersistedWakeup): void {
56
+ if (!existsSync(WAKEUP_DIR)) mkdirSync(WAKEUP_DIR, { recursive: true })
57
+ atomicWriteFileSync(wakeupPath(entry.sessionId), JSON.stringify(entry, null, 2), { mode: 0o644 })
58
+ }
59
+
60
+ function clearPersistedWakeup(sessionId: string): void {
61
+ const path = wakeupPath(sessionId)
62
+ try {
63
+ if (existsSync(path)) unlinkSync(path)
64
+ } catch {
65
+ /* a file we cannot remove does not resurrect a timer we already cancelled */
66
+ }
67
+ }
68
+
69
+ /** Every wakeup left on disk, across all sessions. Unreadable files are skipped. */
70
+ export function readPersistedWakeups(): PersistedWakeup[] {
71
+ let files: string[]
72
+ try {
73
+ files = readdirSync(WAKEUP_DIR)
74
+ } catch {
75
+ return []
76
+ }
77
+ const out: PersistedWakeup[] = []
78
+ for (const file of files) {
79
+ if (!file.endsWith('.json')) continue
80
+ try {
81
+ const parsed = JSON.parse(readFileSync(join(WAKEUP_DIR, file), 'utf-8')) as PersistedWakeup
82
+ if (parsed?.sessionId && parsed.firesAt) out.push(parsed)
83
+ } catch {
84
+ /* skip corrupt files */
85
+ }
86
+ }
87
+ return out
88
+ }
89
+
90
+ /**
91
+ * Arm the session's wakeup timer, replacing whatever timer it already had — one
92
+ * active wakeup per session, enforced here so every arming path (the tool, the
93
+ * restart path) obeys it rather than each remembering to cancel first.
94
+ */
95
+ function armTimer(sessionId: string, prompt: string, noop: boolean, delayMs: number): void {
96
+ cancelSessionTimers(sessionId)
97
+ const timerKey = `${sessionId}:wakeup`
98
+ const timeoutId = setTimeout(() => {
99
+ activeTimers.delete(timerKey)
100
+ clearPersistedWakeup(sessionId)
101
+ wakeupHandler?.(sessionId, prompt, noop)
102
+ }, delayMs)
103
+ activeTimers.set(timerKey, timeoutId)
104
+ }
105
+
106
+ /** Drop this session's timers (in memory only — the store is the caller's business). */
107
+ function cancelSessionTimers(sessionId: string): number {
108
+ let count = 0
109
+ for (const [key, timer] of activeTimers) {
110
+ if (key.startsWith(sessionId + ':')) {
111
+ clearTimeout(timer)
112
+ activeTimers.delete(key)
113
+ count++
114
+ }
115
+ }
116
+ return count
117
+ }
118
+
119
+ /** A wakeup that came due while no process was running. */
120
+ export interface LostWakeup {
121
+ prompt: string
122
+ reason: string
123
+ firesAt: string
124
+ }
125
+
126
+ /**
127
+ * Rebuild this session's pending wakeup after a restart. Returns the ones that
128
+ * came due while we were gone, and re-arms the rest.
129
+ *
130
+ * A due-while-down wakeup is **returned, not fired**. The delay the model picked
131
+ * measured from when it picked it: re-running that prompt blind hours later is not
132
+ * the loop iteration that was asked for. The caller hands it back to the model,
133
+ * which is the only party that can reschedule or stop. What must never happen is
134
+ * the silent drop — the model believing a wakeup is pending while nothing is armed
135
+ * and nothing is on disk.
136
+ */
137
+ export function resumeWakeups(opts: { sessionId: string; now?: Date }): LostWakeup[] {
138
+ const now = (opts.now ?? new Date()).getTime()
139
+ const lost: LostWakeup[] = []
140
+
141
+ for (const entry of readPersistedWakeups()) {
142
+ if (entry.sessionId !== opts.sessionId) continue
143
+ const due = new Date(entry.firesAt).getTime()
144
+ if (!Number.isFinite(due)) {
145
+ clearPersistedWakeup(entry.sessionId)
146
+ continue
147
+ }
148
+ if (due <= now) {
149
+ clearPersistedWakeup(entry.sessionId)
150
+ lost.push({ prompt: entry.prompt, reason: entry.reason, firesAt: entry.firesAt })
151
+ continue
152
+ }
153
+ armTimer(entry.sessionId, entry.prompt, entry.noop, due - now)
154
+ }
155
+
156
+ return lost
157
+ }
158
+
18
159
  export const scheduleWakeupTool: ToolDefinition = {
19
160
  name: 'ScheduleWakeup',
20
161
  description:
@@ -53,14 +194,7 @@ export const scheduleWakeupTool: ToolDefinition = {
53
194
 
54
195
  // ── Stop — cancel all timers for this session ──
55
196
  if (params.stop === true) {
56
- let cancelled = 0
57
- for (const [key, timer] of activeTimers) {
58
- if (key.startsWith(sessionId + ':')) {
59
- clearTimeout(timer)
60
- activeTimers.delete(key)
61
- cancelled++
62
- }
63
- }
197
+ const cancelled = cancelAllSessionTimers(sessionId)
64
198
  return {
65
199
  success: true,
66
200
  content: `Loop ended. ${cancelled} pending wakeup(s) cancelled.`,
@@ -89,21 +223,17 @@ export const scheduleWakeupTool: ToolDefinition = {
89
223
  }
90
224
  }
91
225
 
92
- // Cancel any previous timer for this session (one active wakeup per session)
93
- for (const [key, timer] of activeTimers) {
94
- if (key.startsWith(sessionId + ':')) {
95
- clearTimeout(timer)
96
- activeTimers.delete(key)
97
- }
98
- }
99
-
100
- const timerKey = `${sessionId}:wakeup`
101
- const timeoutId = setTimeout(() => {
102
- activeTimers.delete(timerKey)
103
- wakeupHandler?.(sessionId, prompt, noop)
104
- }, delaySeconds * 1000)
105
-
106
- activeTimers.set(timerKey, timeoutId)
226
+ // Cancel any previous timer for this session (one active wakeup per session).
227
+ // Write the intent *before* arming: a wakeup that exists only in memory is the
228
+ // one that disappears when the process does.
229
+ persistWakeup({
230
+ sessionId,
231
+ prompt,
232
+ noop,
233
+ reason,
234
+ firesAt: new Date(Date.now() + delaySeconds * 1000).toISOString(),
235
+ })
236
+ armTimer(sessionId, prompt, noop, delaySeconds * 1000)
107
237
 
108
238
  const mins = Math.floor(delaySeconds / 60)
109
239
  const secs = delaySeconds % 60
@@ -118,15 +248,9 @@ export const scheduleWakeupTool: ToolDefinition = {
118
248
  },
119
249
  }
120
250
 
121
- /** Cancel all timers for a session. Called on session cleanup. */
251
+ /** Cancel all timers for a session and forget its pending wakeup. Session cleanup. */
122
252
  export function cancelAllSessionTimers(sessionId: string): number {
123
- let count = 0
124
- for (const [key, timer] of activeTimers) {
125
- if (key.startsWith(sessionId + ':')) {
126
- clearTimeout(timer)
127
- activeTimers.delete(key)
128
- count++
129
- }
130
- }
253
+ const count = cancelSessionTimers(sessionId)
254
+ clearPersistedWakeup(sessionId)
131
255
  return count
132
256
  }