@miphamai/cli 0.85.25 → 0.85.26

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.
@@ -1,6 +1,11 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { existsSync, mkdirSync, readFileSync, unlinkSync } from 'node:fs'
3
+ import { dirname } from 'node:path'
1
4
  import type { ToolDefinition } from '../../shared/index.ts'
2
5
  import type { BackgroundAgentRegistry, BackgroundTask } from '../../agent/background-registry'
3
6
  import { hasSupportedEvidenceSince } from '../../core/working-memory'
7
+ import { atomicWriteFileSync } from '../../shared/atomic-write'
8
+ import { miphamHome } from '../../core/paths'
4
9
 
5
10
  export interface Task {
6
11
  id: string
@@ -19,12 +24,108 @@ export interface Task {
19
24
  outputError?: string
20
25
  }
21
26
 
22
- const tasks = new Map<string, Task>()
27
+ /**
28
+ * Task lists are **per session and on disk**.
29
+ *
30
+ * The list used to be one process-global Map with nothing behind it. That made a
31
+ * resumed conversation (`--resume` / `--continue` / `/resume`) start with no tasks
32
+ * at all — the work plan the user just watched being made simply vanished — while a
33
+ * `/clear` kept the *old* list alive in the same process. Both are the same defect
34
+ * seen from two sides: the store's lifetime was "this process", not "this session".
35
+ *
36
+ * Keyed by session id and cached per process (the daemon runs several sessions at
37
+ * once — a single global "current" map would leak one session's tasks into another).
38
+ * Readers without a session id (the TUI's goal panel, the memory tool) use the
39
+ * last session the tool touched, which **is** the session on screen.
40
+ */
41
+ const stores = new Map<string, Map<string, Task>>()
42
+ let activeSessionId = ''
23
43
  let taskCounter = 0
24
44
 
25
- /** Read accessor for the session task store — returns all non-deleted tasks. */
26
- export function getTasks(): Task[] {
27
- return Array.from(tasks.values()).filter((t) => t.status !== 'deleted')
45
+ function storePath(sessionId: string): string {
46
+ // Hashed: the id is operator input (`--resume <id>`), and a `../` must not walk
47
+ // out of the tasks directory.
48
+ const name = createHash('sha256').update(sessionId).digest('hex').slice(0, 32)
49
+ return miphamHome('tasks', `${name}.json`)
50
+ }
51
+
52
+ /** The session's map, loading it from disk the first time it is asked for. */
53
+ function storeFor(sessionId: string): Map<string, Task> {
54
+ activeSessionId = sessionId
55
+ const cached = stores.get(sessionId)
56
+ if (cached) return cached
57
+
58
+ const map = new Map<string, Task>()
59
+ const path = storePath(sessionId)
60
+ if (existsSync(path)) {
61
+ try {
62
+ const parsed = JSON.parse(readFileSync(path, 'utf-8')) as { tasks?: Task[] }
63
+ for (const t of parsed.tasks ?? []) {
64
+ if (!t || typeof t.id !== 'string') continue
65
+ // Dependency walks index these fields unconditionally.
66
+ map.set(t.id, { ...t, blocks: t.blocks ?? [], blockedBy: t.blockedBy ?? [] })
67
+ const n = Number(t.id)
68
+ if (Number.isFinite(n)) taskCounter = Math.max(taskCounter, n)
69
+ }
70
+ } catch {
71
+ // An unreadable store reads as empty — a corrupt file must not make the
72
+ // tool throw on a session that otherwise works.
73
+ }
74
+ }
75
+ stores.set(sessionId, map)
76
+ return map
77
+ }
78
+
79
+ /** Persist the session's map. A failed write must not fail the tool call. */
80
+ function saveStore(sessionId: string): void {
81
+ const map = stores.get(sessionId)
82
+ if (!map) return
83
+ try {
84
+ const path = storePath(sessionId)
85
+ mkdirSync(dirname(path), { recursive: true })
86
+ atomicWriteFileSync(path, `${JSON.stringify({ tasks: [...map.values()] }, null, 2)}\n`, {
87
+ mode: 0o600,
88
+ })
89
+ } catch {
90
+ /* the in-memory list is still correct for this process */
91
+ }
92
+ }
93
+
94
+ /** Make `sessionId` the one that session-less readers see, loading its tasks. */
95
+ export function setActiveTaskSession(sessionId: string): void {
96
+ if (!sessionId) return
97
+ storeFor(sessionId)
98
+ }
99
+
100
+ /** The map a reader means: the named session's, or the one on screen. */
101
+ function resolveStore(sessionId?: string): Map<string, Task> {
102
+ if (sessionId !== undefined) return storeFor(sessionId)
103
+ return stores.get(activeSessionId) ?? new Map()
104
+ }
105
+
106
+ /**
107
+ * Read accessor for a session's task store — returns all non-deleted tasks.
108
+ * Without an id: the session the Task tool last touched.
109
+ */
110
+ export function getTasks(sessionId?: string): Task[] {
111
+ return Array.from(resolveStore(sessionId).values()).filter((t) => t.status !== 'deleted')
112
+ }
113
+
114
+ /**
115
+ * Drop a session's task list — the store and the file behind it.
116
+ *
117
+ * `/clear` means "start this conversation over"; leaving the old plan in place is
118
+ * how a fresh context came back showing tasks nobody had asked for in it.
119
+ */
120
+ export function clearTasks(sessionId: string): void {
121
+ if (!sessionId) return
122
+ stores.delete(sessionId)
123
+ try {
124
+ const path = storePath(sessionId)
125
+ if (existsSync(path)) unlinkSync(path)
126
+ } catch {
127
+ /* a file we cannot remove is still not in this process's list */
128
+ }
28
129
  }
29
130
 
30
131
  function formatTask(t: Task): string {
@@ -95,8 +196,15 @@ function stopBackgroundTask(
95
196
  }
96
197
  }
97
198
 
98
- /** Check if a task is blocked — has unresolved dependencies. */
99
- function isBlocked(task: Task): boolean {
199
+ /**
200
+ * Check if a task is blocked — has unresolved dependencies.
201
+ *
202
+ * The map is passed in rather than read from a module global: dependencies only
203
+ * mean anything **within one session's list**, and resolving them against
204
+ * whichever session happened to be active would let one session's ids answer
205
+ * for another's.
206
+ */
207
+ function isBlocked(task: Task, tasks: Map<string, Task>): boolean {
100
208
  if (task.blockedBy.length === 0) return false
101
209
  return task.blockedBy.some((depId) => {
102
210
  const dep = tasks.get(depId)
@@ -105,7 +213,7 @@ function isBlocked(task: Task): boolean {
105
213
  }
106
214
 
107
215
  /** Get the list of blocking task IDs (unresolved dependencies). */
108
- function getBlockingIds(task: Task): string[] {
216
+ function getBlockingIds(task: Task, tasks: Map<string, Task>): string[] {
109
217
  return task.blockedBy.filter((depId) => {
110
218
  const dep = tasks.get(depId)
111
219
  return dep && dep.status !== 'completed' && dep.status !== 'deleted'
@@ -120,8 +228,9 @@ function getBlockingIds(task: Task): string[] {
120
228
  * both go through here. A second renderer for the panel would be the "two
121
229
  * paths, one wired" mistake this repo has already paid for once.
122
230
  */
123
- export function formatTaskList(): string {
124
- const all = getTasks()
231
+ export function formatTaskList(sessionId?: string): string {
232
+ const map = resolveStore(sessionId)
233
+ const all = Array.from(map.values()).filter((t) => t.status !== 'deleted')
125
234
  if (all.length === 0) return '(no tasks)'
126
235
 
127
236
  // Sort by availability: in_progress → pending(available) → pending(blocked) → completed
@@ -138,8 +247,8 @@ export function formatTaskList(): string {
138
247
  if (orderA !== orderB) return orderA - orderB
139
248
  // Within same status: available before blocked
140
249
  if (a.status === 'pending' && b.status === 'pending') {
141
- const aBlocked = isBlocked(a)
142
- const bBlocked = isBlocked(b)
250
+ const aBlocked = isBlocked(a, map)
251
+ const bBlocked = isBlocked(b, map)
143
252
  if (aBlocked !== bBlocked) return aBlocked ? 1 : -1
144
253
  }
145
254
  return 0
@@ -165,15 +274,15 @@ export function formatTaskList(): string {
165
274
  lines.push(`${statusInfo.emoji} ${currentStatus} (${count}):`)
166
275
  }
167
276
 
168
- const blocked = isBlocked(t)
277
+ const blocked = isBlocked(t, map)
169
278
  const prefix = blocked && t.status === 'pending' ? '🚫 ' : ' '
170
- const blockingNote = blocked ? ` 🚫 阻塞中 (等待: ${getBlockingIds(t).join(', ')})` : ''
279
+ const blockingNote = blocked ? ` 🚫 阻塞中 (等待: ${getBlockingIds(t, map).join(', ')})` : ''
171
280
  lines.push(`${prefix}${formatTask(t)}${blockingNote}`)
172
281
  }
173
282
 
174
283
  // Summary footer
175
- const available = all.filter((t) => t.status === 'pending' && !isBlocked(t)).length
176
- const blockedCount = all.filter((t) => t.status === 'pending' && isBlocked(t)).length
284
+ const available = all.filter((t) => t.status === 'pending' && !isBlocked(t, map)).length
285
+ const blockedCount = all.filter((t) => t.status === 'pending' && isBlocked(t, map)).length
177
286
  if (blockedCount > 0) {
178
287
  lines.push('')
179
288
  lines.push(
@@ -238,6 +347,15 @@ export const taskTool: ToolDefinition = {
238
347
 
239
348
  async execute(params, _ctx) {
240
349
  const action = params.action as string
350
+ // The list this call works on. A sub-agent reports to its parent's list —
351
+ // `sessionId` is the literal 'sub-agent' one level down, so keying off it
352
+ // alone would put every nested task, from every session, in one bucket that
353
+ // no session panel reads.
354
+ // `|| … || 'default'` rather than `??`: a context assembled without a
355
+ // session id (tests, embedders) must still get a working list, and hashing
356
+ // `undefined` would throw instead.
357
+ const sid = _ctx.parentSessionId || _ctx.sessionId || 'default'
358
+ const tasks = storeFor(sid)
241
359
 
242
360
  // ── CREATE ──
243
361
  if (action === 'create') {
@@ -269,15 +387,16 @@ export const taskTool: ToolDefinition = {
269
387
  }
270
388
 
271
389
  tasks.set(id, task)
272
- const blockedNote = isBlocked(task)
273
- ? ` (blocked — waiting on: ${getBlockingIds(task).join(', ')})`
390
+ saveStore(sid)
391
+ const blockedNote = isBlocked(task, tasks)
392
+ ? ` (blocked — waiting on: ${getBlockingIds(task, tasks).join(', ')})`
274
393
  : ''
275
394
  return { success: true, content: `Task #${id} created: ${subject}${blockedNote}` }
276
395
  }
277
396
 
278
397
  // ── LIST ──
279
398
  if (action === 'list') {
280
- return { success: true, content: formatTaskList() }
399
+ return { success: true, content: formatTaskList(sid) }
281
400
  }
282
401
 
283
402
  // ── GET ──
@@ -299,7 +418,7 @@ export const taskTool: ToolDefinition = {
299
418
  if (task.owner) lines.push(`Owner: ${task.owner}`)
300
419
  if (task.blocks.length) lines.push(`Blocks: ${task.blocks.join(', ')}`)
301
420
  if (task.blockedBy.length) {
302
- const blocking = getBlockingIds(task)
421
+ const blocking = getBlockingIds(task, tasks)
303
422
  if (blocking.length > 0) {
304
423
  lines.push(
305
424
  `Blocked by: ${task.blockedBy.join(', ')} (active blockers: ${blocking.join(', ')})`,
@@ -359,8 +478,9 @@ export const taskTool: ToolDefinition = {
359
478
  }
360
479
  }
361
480
 
362
- const blockedNote = isBlocked(task)
363
- ? ` (blocked — waiting on: ${getBlockingIds(task).join(', ')})`
481
+ saveStore(sid)
482
+ const blockedNote = isBlocked(task, tasks)
483
+ ? ` (blocked — waiting on: ${getBlockingIds(task, tasks).join(', ')})`
364
484
  : ''
365
485
  const unverifiedNote =
366
486
  task.status === 'completed' && task.completionEvidence === 'unverified'
@@ -379,6 +499,7 @@ export const taskTool: ToolDefinition = {
379
499
  const task = tasks.get(taskId)
380
500
  if (!task) return { success: false, content: '', error: `Task #${taskId} not found` }
381
501
  task.status = 'deleted'
502
+ saveStore(sid)
382
503
  return { success: true, content: `Task #${taskId} deleted.` }
383
504
  }
384
505
 
@@ -447,6 +568,7 @@ export const taskTool: ToolDefinition = {
447
568
  if (task.status === 'pending') {
448
569
  // Cancel a pending task
449
570
  task.status = 'deleted'
571
+ saveStore(sid)
450
572
  return { success: true, content: `Task #${taskId} cancelled (was pending).` }
451
573
  }
452
574
 
@@ -455,6 +577,7 @@ export const taskTool: ToolDefinition = {
455
577
  // the registry owns.
456
578
  task.status = 'failed'
457
579
  task.outputError = 'Task stopped by user.'
580
+ saveStore(sid)
458
581
 
459
582
  return { success: true, content: `Task #${taskId} stopped.` }
460
583
  }
@@ -250,10 +250,12 @@ export const webFetchTool: ToolDefinition = {
250
250
  return { success: false, content: '', error: validationError }
251
251
  }
252
252
 
253
+ // The timer spans the body read, not just the headers: a server that sends
254
+ // headers and then stalls mid-body would otherwise hang the tool forever —
255
+ // the abort signal is only consulted while `fetch` itself is running.
256
+ const controller = new AbortController()
257
+ const timer = setTimeout(() => controller.abort(), 30_000) // 30s timeout
253
258
  try {
254
- const controller = new AbortController()
255
- const timer = setTimeout(() => controller.abort(), 30_000) // 30s timeout
256
-
257
259
  // Manual redirect handling: follow same-host redirects one hop at a time,
258
260
  // validating the target BEFORE each request (closes the SSRF-via-redirect gap).
259
261
  let currentUrl = url
@@ -280,7 +282,6 @@ export const webFetchTool: ToolDefinition = {
280
282
  // SSRF defense: validate the redirect target BEFORE following
281
283
  const redirectError = await validateUrl(nextUrl)
282
284
  if (redirectError) {
283
- clearTimeout(timer)
284
285
  return {
285
286
  success: false,
286
287
  content: '',
@@ -290,7 +291,6 @@ export const webFetchTool: ToolDefinition = {
290
291
 
291
292
  // Cross-host redirects are returned to the caller (tool contract)
292
293
  if (new URL(nextUrl).hostname !== originalHost) {
293
- clearTimeout(timer)
294
294
  return {
295
295
  success: true,
296
296
  content: `Redirected to: ${nextUrl}\n\nFetch from this URL directly to retrieve content.`,
@@ -301,8 +301,6 @@ export const webFetchTool: ToolDefinition = {
301
301
  currentUrl = nextUrl
302
302
  }
303
303
 
304
- clearTimeout(timer)
305
-
306
304
  // Determine content type; only convert HTML to markdown
307
305
  const contentType = response.headers.get('content-type') || ''
308
306
  const isHtml = contentType.includes('text/html') || contentType.includes('application/xhtml')
@@ -352,6 +350,8 @@ export const webFetchTool: ToolDefinition = {
352
350
  ? 'Request timed out (30s)'
353
351
  : `Fetch failed: ${String(err)}. If direct network is blocked, retry via the web-access skill (CDP through the user's logged-in Chrome).`
354
352
  return { success: false, content: '', error: message }
353
+ } finally {
354
+ clearTimeout(timer)
355
355
  }
356
356
  },
357
357
  }
@@ -132,14 +132,15 @@ export const webSearchTool: ToolDefinition = {
132
132
  }
133
133
  }
134
134
 
135
+ // The timer spans the body read too: headers followed by a stalled body is
136
+ // the same hang as a request that never answers.
137
+ const controller = new AbortController()
138
+ const timer = setTimeout(() => controller.abort(), 15_000) // 15s timeout
135
139
  try {
136
140
  const url = new URL(BRAVE_API)
137
141
  url.searchParams.set('q', query)
138
142
  url.searchParams.set('count', String(MAX_RESULTS))
139
143
 
140
- const controller = new AbortController()
141
- const timer = setTimeout(() => controller.abort(), 15_000) // 15s timeout
142
-
143
144
  const response = await fetch(url.toString(), {
144
145
  headers: {
145
146
  Accept: 'application/json',
@@ -149,8 +150,6 @@ export const webSearchTool: ToolDefinition = {
149
150
  signal: controller.signal,
150
151
  })
151
152
 
152
- clearTimeout(timer)
153
-
154
153
  if (!response.ok) {
155
154
  const body = await response.text().catch(() => '')
156
155
  // 429 = rate limit, 401 = bad key
@@ -207,6 +206,8 @@ export const webSearchTool: ToolDefinition = {
207
206
  ? 'Search timed out (15s). Try a more specific query.'
208
207
  : `Search failed: ${String(err)}. If direct network is blocked, retry via the web-access skill (CDP through the user's logged-in Chrome).`
209
208
  return { success: false, content: '', error: message }
209
+ } finally {
210
+ clearTimeout(timer)
210
211
  }
211
212
  },
212
213
  }
@@ -119,7 +119,7 @@ import { listActiveAutoloops, formatLoopRows } from '../commands/autoloop-journa
119
119
  import { execSync } from 'node:child_process'
120
120
  import { MIPHAM_DIR, OLLAMA_PRESET_MODELS } from '../shared/constants'
121
121
  import { renameActiveSession } from '../agent/cross-session/discovery'
122
- import { formatTaskList } from '../tools/exec/task'
122
+ import { clearTasks, formatTaskList } from '../tools/exec/task'
123
123
 
124
124
  export interface CommandContext {
125
125
  engine: QueryEngine
@@ -340,6 +340,10 @@ const versionCmd: CommandHandler = (ctx) => {
340
340
 
341
341
  const clearCmd: CommandHandler = (ctx) => {
342
342
  ctx.engine.getContext().clear()
343
+ // The task list outlives the process now, so "start over" has to say so
344
+ // explicitly — otherwise the old plan comes back on resume and the panel keeps
345
+ // showing tasks from a conversation the user just discarded.
346
+ clearTasks(ctx.sessionId)
343
347
  const t = resolveT(ctx)
344
348
  return { content: t('commands.clear.confirmed'), clearMessages: true }
345
349
  }
@@ -3096,7 +3100,7 @@ const tasksCmd: CommandHandler = (ctx) => {
3096
3100
  // 却有历史时又会说「检测到 N 次任务操作」。面板自称 "Background tasks"、标题写
3097
3101
  // 「后台任务」、空态写「尚未跟踪任何任务」—— 全是登记表词汇,而登记表就在
3098
3102
  // 一步之外(`getTasks()`,`GoalProgress` 早就接了)。
3099
- const taskList = formatTaskList()
3103
+ const taskList = formatTaskList(ctx.sessionId)
3100
3104
  const hasTasks = taskList !== '(no tasks)'
3101
3105
 
3102
3106
  return {
@@ -3830,7 +3834,11 @@ const codeReviewCmd = gitDiffBridgeCmd({
3830
3834
  : maxFindings.value === 'default'
3831
3835
  ? ''
3832
3836
  : ` Report at most ${maxFindings.value} findings, most severe first.`
3833
- return `use the code-review skill to review all uncommitted changes. Check all 7 dimensions: correctness, security, performance, code quality, architecture & design, testing, and language-specific issues. Use effort level: ${getPreference('lastCodeReviewEffort', 'high')}.${cap}`
3837
+ // 档位放在**最前**:它是这一轮的工作量,后面那句「查哪七个维度」是它的宾语。
3838
+ // 写成句末时模型容易先按默认深度铺开、再拿档位去追认。`max` 另有一句上限:
3839
+ // 仓里存的可能是上一轮自己挑的,而不是用户这一轮要的 —— 只有**用户点名**才用。
3840
+ const effort = getPreference('lastCodeReviewEffort', 'high')
3841
+ return `Use effort level: ${effort} — settle this before you start; never pick max on your own, only when the user asked for it. Then use the code-review skill to review all uncommitted changes. Check all 7 dimensions: correctness, security, performance, code quality, architecture & design, testing, and language-specific issues.${cap}`
3834
3842
  },
3835
3843
  })
3836
3844