@miphamai/cli 0.85.24 → 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.
- package/README.md +3 -3
- package/bin/mipham.ts +34 -24
- package/package.json +1 -1
- package/src/agent/agent-context.ts +23 -3
- package/src/agent/sub-agent.ts +29 -15
- package/src/artifacts/server.ts +5 -1
- package/src/commands/git.ts +9 -1
- package/src/commands/project.ts +34 -17
- package/src/core/context-token.ts +55 -3
- package/src/core/context.ts +54 -42
- package/src/core/crsi-sandbox.ts +5 -1
- package/src/core/engine.ts +91 -10
- package/src/core/instructions.ts +130 -18
- package/src/core/permission-rule-ack.ts +67 -0
- package/src/core/permission-rules.ts +141 -25
- package/src/daemon/remote-engine.ts +11 -5
- package/src/daemon/schedule-manager.ts +32 -3
- package/src/daemon/server.ts +6 -0
- package/src/i18n-core/locales/en-US.json +1 -1
- package/src/i18n-core/locales/zh-CN.json +1 -1
- package/src/index.tsx +34 -4
- package/src/mcp/client.ts +37 -2
- package/src/mcp/http-transport.ts +20 -1
- package/src/mcp/protocol.ts +13 -5
- package/src/mcp/registry.ts +8 -3
- package/src/mcp/transport.ts +40 -3
- package/src/plugin/plugin-manager.ts +23 -2
- package/src/providers/anthropic.ts +3 -1
- package/src/providers/fetch-utils.ts +40 -6
- package/src/providers/openai-compat.ts +2 -1
- package/src/providers/registry.ts +23 -1
- package/src/shared/git-env.ts +18 -0
- package/src/shared/package-info.ts +3 -3
- package/src/shared/sanitize.ts +21 -0
- package/src/shared/types.ts +9 -0
- package/src/skills/loader.ts +14 -0
- package/src/tools/exec/bash.ts +168 -6
- package/src/tools/exec/enter-worktree.ts +26 -2
- package/src/tools/exec/task.ts +144 -21
- package/src/tools/network/web-fetch.ts +7 -7
- package/src/tools/network/web-search.ts +6 -5
- package/src/ui/app.tsx +22 -7
- package/src/ui/chat.tsx +3 -2
- package/src/ui/commands.ts +65 -5
- package/src/workflow/primitives/agent.ts +17 -1
|
@@ -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.26' as const
|
|
13
13
|
|
|
14
14
|
/** npm install 全局安装命令 */
|
|
15
15
|
export const NPM_INSTALL_COMMAND = `npm install -g ${PACKAGE_NAME}` as const
|
|
@@ -75,7 +75,7 @@ export const COMPANY_SHORT = '华安麦逄科技' as const
|
|
|
75
75
|
*/
|
|
76
76
|
|
|
77
77
|
/** Slash 命令总数(真源:`getCommandNames().length`,`apps/cli/src/ui/commands.ts`) */
|
|
78
|
-
export const SLASH_COMMAND_COUNT =
|
|
78
|
+
export const SLASH_COMMAND_COUNT = 138 as const
|
|
79
79
|
|
|
80
80
|
/** 内置提供商总数(真源:`DEFAULT_PROVIDERS.length`,`apps/cli/src/shared/constants.ts`) */
|
|
81
81
|
export const PROVIDER_COUNT = 12 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 = 4533 as const
|
package/src/shared/sanitize.ts
CHANGED
|
@@ -290,6 +290,27 @@ export function stripControlCharsForDisplay(input: string): string {
|
|
|
290
290
|
)
|
|
291
291
|
}
|
|
292
292
|
|
|
293
|
+
/**
|
|
294
|
+
* `String.prototype.slice` counted in UTF-16 code units, made **surrogate-safe**.
|
|
295
|
+
*
|
|
296
|
+
* A cut that lands between the two halves of a surrogate pair leaves a lone
|
|
297
|
+
* surrogate behind. When that string is serialized into a JSONL transcript,
|
|
298
|
+
* `JSON.stringify` emits it as a bare `\uD83D` escape and strict parsers reject
|
|
299
|
+
* the **whole line** (`jq`: "Invalid \uXXXX\uXXXX surrogate pair escape"). In a
|
|
300
|
+
* terminal it renders as U+FFFD.
|
|
301
|
+
*
|
|
302
|
+
* Back off one code unit when the last kept unit is a high surrogate, so the cut
|
|
303
|
+
* never splits a pair. A lone surrogate that was already in the input is left
|
|
304
|
+
* alone — this only removes *newly created* ones.
|
|
305
|
+
*/
|
|
306
|
+
export function safeSlice(text: string, max: number): string {
|
|
307
|
+
if (!Number.isFinite(max) || max >= text.length) return text
|
|
308
|
+
if (max <= 0) return ''
|
|
309
|
+
const last = text.charCodeAt(max - 1)
|
|
310
|
+
const end = last >= 0xd800 && last <= 0xdbff ? max - 1 : max
|
|
311
|
+
return text.slice(0, end)
|
|
312
|
+
}
|
|
313
|
+
|
|
293
314
|
/**
|
|
294
315
|
* Full command sanitization pipeline for permission checks.
|
|
295
316
|
* Applies in order:
|
package/src/shared/types.ts
CHANGED
|
@@ -661,6 +661,15 @@ export interface ToolContext {
|
|
|
661
661
|
* consume a background handle, so its default flips to synchronous.
|
|
662
662
|
*/
|
|
663
663
|
isSubAgent?: boolean
|
|
664
|
+
/**
|
|
665
|
+
* The session a sub-agent is running on behalf of.
|
|
666
|
+
*
|
|
667
|
+
* `sessionId` is the literal `'sub-agent'` one level down, so anything keyed by
|
|
668
|
+
* it would put every nested call — from every session — into one bucket. Set by
|
|
669
|
+
* `SubAgent.runExecution` from the caller's context; absent for the main
|
|
670
|
+
* session, where `sessionId` is already the answer.
|
|
671
|
+
*/
|
|
672
|
+
parentSessionId?: string
|
|
664
673
|
/**
|
|
665
674
|
* The agent's own name, when this call is being executed by a sub-agent.
|
|
666
675
|
*
|
package/src/skills/loader.ts
CHANGED
|
@@ -46,6 +46,8 @@ export function invalidSkillNameReason(name: string): string | null {
|
|
|
46
46
|
|
|
47
47
|
export class SkillsLoader implements Skills {
|
|
48
48
|
private skills = new Map<string, SkillDefinition>()
|
|
49
|
+
/** File each loaded skill came from — so a name collision can name both sides. */
|
|
50
|
+
private sources = new Map<string, string>()
|
|
49
51
|
|
|
50
52
|
loadBuiltin(basePath: string): void {
|
|
51
53
|
// Load standard skills (*.SKILL.md)
|
|
@@ -237,7 +239,19 @@ export class SkillsLoader implements Skills {
|
|
|
237
239
|
requiresBins: data['requires-bins'] as string[] | undefined,
|
|
238
240
|
}
|
|
239
241
|
|
|
242
|
+
// Two files declaring the same name is a silent last-one-wins race: the
|
|
243
|
+
// user edits the shadowed file, reloads, and sees no effect. Say which file
|
|
244
|
+
// won and which one it displaced. Re-loading the **same** path (what
|
|
245
|
+
// `/reload-skills` does, into this same loader) is not a collision.
|
|
246
|
+
const previousSource = this.sources.get(skill.name)
|
|
247
|
+
if (previousSource !== undefined && previousSource !== sourceName) {
|
|
248
|
+
process.stderr.write(
|
|
249
|
+
`⚠️ Skill "${skill.name}" from ${sourceName} replaces the one loaded from ` +
|
|
250
|
+
`${previousSource} — the later file wins; rename one of them.\n`,
|
|
251
|
+
)
|
|
252
|
+
}
|
|
240
253
|
this.skills.set(skill.name, skill)
|
|
254
|
+
this.sources.set(skill.name, sourceName)
|
|
241
255
|
} catch {
|
|
242
256
|
// skip unparseable
|
|
243
257
|
}
|
package/src/tools/exec/bash.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { sanitizeCommand } from '../../shared/sanitize.ts'
|
|
|
5
5
|
import { DANGEROUS_GIT_PATTERNS } from './git.ts'
|
|
6
6
|
import { isUncOrDevicePath, isWithin } from '../../security/path.ts'
|
|
7
7
|
import { findWorktreeMarker } from '../../core/paths.ts'
|
|
8
|
+
import { splitShellSegments, expandKnownPathVars } from '../../core/permission-rules'
|
|
8
9
|
import type { Service } from '../../vajra'
|
|
9
10
|
import { toolKey } from '../seam'
|
|
10
11
|
import { withValidation } from '../validation'
|
|
@@ -376,16 +377,177 @@ export function resolveWorktreeEscape(
|
|
|
376
377
|
worktreeRoot: string,
|
|
377
378
|
command: string,
|
|
378
379
|
): string | null {
|
|
379
|
-
const
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
380
|
+
for (const segment of splitShellSegments(command)) {
|
|
381
|
+
for (const target of changeDirectoryTargets(shellWords(segment))) {
|
|
382
|
+
// `resolve` does not expand `~` or `$HOME`: `cd ~` would otherwise be
|
|
383
|
+
// resolved as a directory literally named `~` under the worktree, i.e.
|
|
384
|
+
// "inside", while the shell lands in the home directory.
|
|
385
|
+
const resolved = resolve(cwd, expandKnownPathVars(target))
|
|
386
|
+
if (!isWithin(resolved, cwd) && !isWithin(resolved, worktreeRoot)) return target
|
|
387
|
+
}
|
|
385
388
|
}
|
|
386
389
|
return null
|
|
387
390
|
}
|
|
388
391
|
|
|
392
|
+
/** Shell structure that can precede the command word without being one. */
|
|
393
|
+
const LEADING_SHELL_PUNCT = new Set(['(', '{', '!', ')', '}'])
|
|
394
|
+
/** Keywords after which the *next* word is the command (`if cd /x; then`). */
|
|
395
|
+
const LEADING_SHELL_KEYWORDS = new Set([
|
|
396
|
+
'if',
|
|
397
|
+
'then',
|
|
398
|
+
'else',
|
|
399
|
+
'elif',
|
|
400
|
+
'while',
|
|
401
|
+
'until',
|
|
402
|
+
'do',
|
|
403
|
+
'for',
|
|
404
|
+
'time',
|
|
405
|
+
'coproc',
|
|
406
|
+
])
|
|
407
|
+
/** Wrappers that run a command of their own; the wrapped words are re-scanned. */
|
|
408
|
+
const WRAPPERS = new Set(['command', 'builtin'])
|
|
409
|
+
const LEADING_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/
|
|
410
|
+
const CD_COMMANDS = new Set(['cd', 'pushd'])
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* Quote-aware word split of one simple command, with the quotes removed.
|
|
414
|
+
*
|
|
415
|
+
* The previous implementation matched `\bcd\s+` against the raw text. A quoted
|
|
416
|
+
* **command word** (`'cd' /etc`, `"cd" /etc`, `\cd /etc`) is still the `cd`
|
|
417
|
+
* builtin to bash, but there is no word boundary followed by whitespace in
|
|
418
|
+
* that spelling, so the guard never saw it. Reconstructing the words first also
|
|
419
|
+
* lets `pushd` and `env -C` be recognized as what they are.
|
|
420
|
+
*
|
|
421
|
+
* Over-splitting is the safe direction here: a word that is not really a
|
|
422
|
+
* command word simply fails to match `cd`.
|
|
423
|
+
*/
|
|
424
|
+
function shellWords(segment: string): string[] {
|
|
425
|
+
const words: string[] = []
|
|
426
|
+
let cur = ''
|
|
427
|
+
let started = false
|
|
428
|
+
let quote: '"' | "'" | null = null
|
|
429
|
+
for (let i = 0; i < segment.length; i++) {
|
|
430
|
+
const ch = segment[i]!
|
|
431
|
+
if (quote === "'") {
|
|
432
|
+
if (ch === "'") quote = null
|
|
433
|
+
else cur += ch
|
|
434
|
+
continue
|
|
435
|
+
}
|
|
436
|
+
if (quote === '"') {
|
|
437
|
+
if (ch === '"') quote = null
|
|
438
|
+
else if (ch === '\\' && i + 1 < segment.length) cur += segment[++i]
|
|
439
|
+
else cur += ch
|
|
440
|
+
continue
|
|
441
|
+
}
|
|
442
|
+
if (ch === "'" || ch === '"') {
|
|
443
|
+
quote = ch
|
|
444
|
+
started = true
|
|
445
|
+
} else if (ch === '\\' && i + 1 < segment.length) {
|
|
446
|
+
cur += segment[++i]
|
|
447
|
+
started = true
|
|
448
|
+
} else if (/\s/.test(ch)) {
|
|
449
|
+
if (started) {
|
|
450
|
+
words.push(cur)
|
|
451
|
+
cur = ''
|
|
452
|
+
started = false
|
|
453
|
+
}
|
|
454
|
+
} else {
|
|
455
|
+
cur += ch
|
|
456
|
+
started = true
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
if (started) words.push(cur)
|
|
460
|
+
return words
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* Every directory this simple command changes the shell's cwd to.
|
|
465
|
+
*
|
|
466
|
+
* A bare `cd` goes to `$HOME`, which is outside any worktree — it is reported
|
|
467
|
+
* as the home directory rather than skipped. Re-scanning wrapped words is what
|
|
468
|
+
* catches `env A=1 -C /etc cd /tmp`: both directories are candidates, and
|
|
469
|
+
* either one leaving the worktree is enough to refuse the command.
|
|
470
|
+
*/
|
|
471
|
+
function changeDirectoryTargets(words: string[], depth = 0): string[] {
|
|
472
|
+
if (depth > 4) return []
|
|
473
|
+
const out: string[] = []
|
|
474
|
+
let i = 0
|
|
475
|
+
const skipNoise = (): void => {
|
|
476
|
+
for (;;) {
|
|
477
|
+
while (i < words.length && LEADING_ASSIGNMENT.test(words[i]!)) i++
|
|
478
|
+
const word = words[i]
|
|
479
|
+
if (word === undefined) return
|
|
480
|
+
if (LEADING_SHELL_PUNCT.has(word)) {
|
|
481
|
+
i++
|
|
482
|
+
continue
|
|
483
|
+
}
|
|
484
|
+
if (LEADING_SHELL_KEYWORDS.has(word)) {
|
|
485
|
+
i++
|
|
486
|
+
// A keyword's own flags (`time -p rm …`) are not the command word.
|
|
487
|
+
while (i < words.length && /^-[A-Za-z]+$/.test(words[i]!)) i++
|
|
488
|
+
continue
|
|
489
|
+
}
|
|
490
|
+
return
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
skipNoise()
|
|
495
|
+
const cmd = words[i]
|
|
496
|
+
if (cmd === undefined) return out
|
|
497
|
+
|
|
498
|
+
if (WRAPPERS.has(cmd)) {
|
|
499
|
+
return changeDirectoryTargets(words.slice(i + 1), depth + 1)
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
if (cmd === 'env') {
|
|
503
|
+
i++
|
|
504
|
+
while (i < words.length) {
|
|
505
|
+
const w = words[i]!
|
|
506
|
+
if (w === '-C' || w === '--chdir') {
|
|
507
|
+
const dir = words[i + 1]
|
|
508
|
+
if (dir !== undefined) out.push(dir)
|
|
509
|
+
i += 2
|
|
510
|
+
continue
|
|
511
|
+
}
|
|
512
|
+
if (w.startsWith('--chdir=')) {
|
|
513
|
+
out.push(w.slice('--chdir='.length))
|
|
514
|
+
i++
|
|
515
|
+
continue
|
|
516
|
+
}
|
|
517
|
+
if (w === '-u' || w === '--unset') {
|
|
518
|
+
i += 2 // takes an argument
|
|
519
|
+
continue
|
|
520
|
+
}
|
|
521
|
+
if (LEADING_ASSIGNMENT.test(w)) {
|
|
522
|
+
i++ // `env A=1 -C /etc cmd` — assignments may sit among the options
|
|
523
|
+
continue
|
|
524
|
+
}
|
|
525
|
+
if (w === '-S' || w === '--split-string' || w === '--') break
|
|
526
|
+
if (w.startsWith('-')) {
|
|
527
|
+
i++
|
|
528
|
+
continue
|
|
529
|
+
}
|
|
530
|
+
break
|
|
531
|
+
}
|
|
532
|
+
return out.concat(changeDirectoryTargets(words.slice(i), depth + 1))
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
if (!CD_COMMANDS.has(cmd)) return out
|
|
536
|
+
|
|
537
|
+
let j = i + 1
|
|
538
|
+
while (j < words.length && /^-[A-Za-z]+$/.test(words[j]!)) j++
|
|
539
|
+
if (words[j] === '--') j++
|
|
540
|
+
const target = words[j]
|
|
541
|
+
if (target === undefined) {
|
|
542
|
+
// `cd` / `pushd` alone: `cd` goes home. (`pushd` with no argument swaps the
|
|
543
|
+
// directory stack, which cannot leave the shell it is already in.)
|
|
544
|
+
if (cmd === 'cd') out.push('~')
|
|
545
|
+
} else {
|
|
546
|
+
out.push(target)
|
|
547
|
+
}
|
|
548
|
+
return out
|
|
549
|
+
}
|
|
550
|
+
|
|
389
551
|
export function createBashTool(credentialConfig?: CredentialMaskingConfig): ToolDefinition {
|
|
390
552
|
return {
|
|
391
553
|
name: 'Bash',
|
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import type { ToolDefinition } from '../../shared/index.ts'
|
|
2
|
+
import { internalGitEnv } from '../../shared/git-env'
|
|
2
3
|
import { listsWorktree, worktreeRoot } from '../../core/paths.ts'
|
|
3
4
|
|
|
5
|
+
/** Upper bound for `git worktree add` — a hung fetch must not hang the tool. */
|
|
6
|
+
const WORKTREE_ADD_TIMEOUT_MS = 60_000
|
|
7
|
+
|
|
4
8
|
export const enterWorktreeTool: ToolDefinition = {
|
|
5
9
|
name: 'EnterWorktree',
|
|
6
10
|
description:
|
|
@@ -78,6 +82,7 @@ export const enterWorktreeTool: ToolDefinition = {
|
|
|
78
82
|
cwd,
|
|
79
83
|
stdout: 'pipe',
|
|
80
84
|
stderr: 'pipe',
|
|
85
|
+
env: internalGitEnv(),
|
|
81
86
|
})
|
|
82
87
|
const gitCheckExit = await gitCheck.exited
|
|
83
88
|
if (gitCheckExit !== 0) {
|
|
@@ -93,6 +98,7 @@ export const enterWorktreeTool: ToolDefinition = {
|
|
|
93
98
|
cwd,
|
|
94
99
|
stdout: 'pipe',
|
|
95
100
|
stderr: 'pipe',
|
|
101
|
+
env: internalGitEnv(),
|
|
96
102
|
})
|
|
97
103
|
const existingWorktrees = await new Response(checkProc.stdout).text()
|
|
98
104
|
if (listsWorktree(existingWorktrees, worktreePath)) {
|
|
@@ -116,6 +122,7 @@ export const enterWorktreeTool: ToolDefinition = {
|
|
|
116
122
|
cwd,
|
|
117
123
|
stdout: 'pipe',
|
|
118
124
|
stderr: 'pipe',
|
|
125
|
+
env: internalGitEnv(),
|
|
119
126
|
})
|
|
120
127
|
const branch = (await new Response(branchProc.stdout).text()).trim()
|
|
121
128
|
resolvedBaseRef = branch || 'HEAD'
|
|
@@ -134,10 +141,27 @@ export const enterWorktreeTool: ToolDefinition = {
|
|
|
134
141
|
// nonsense, which is what a bad base ref should do.
|
|
135
142
|
const proc = Bun.spawn(
|
|
136
143
|
['git', 'worktree', 'add', '-b', branchName, worktreePath, '--', resolvedBaseRef],
|
|
137
|
-
{ cwd, stdout: 'pipe', stderr: 'pipe' },
|
|
144
|
+
{ cwd, stdout: 'pipe', stderr: 'pipe', env: internalGitEnv() },
|
|
138
145
|
)
|
|
139
146
|
const _stdout = await new Response(proc.stdout).text()
|
|
140
|
-
|
|
147
|
+
// A worktree that cannot be created (a promisor remote that is gone, a
|
|
148
|
+
// lock from a crashed run) otherwise hangs this tool with no answer at all.
|
|
149
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
150
|
+
const exitCode = await Promise.race([
|
|
151
|
+
proc.exited,
|
|
152
|
+
new Promise<number>((resolve) => {
|
|
153
|
+
timer = setTimeout(() => resolve(-1), WORKTREE_ADD_TIMEOUT_MS)
|
|
154
|
+
}),
|
|
155
|
+
])
|
|
156
|
+
clearTimeout(timer)
|
|
157
|
+
if (exitCode === -1) {
|
|
158
|
+
proc.kill()
|
|
159
|
+
return {
|
|
160
|
+
success: false,
|
|
161
|
+
content: '',
|
|
162
|
+
error: `git worktree add did not finish within ${WORKTREE_ADD_TIMEOUT_MS / 1000}s.`,
|
|
163
|
+
}
|
|
164
|
+
}
|
|
141
165
|
|
|
142
166
|
if (exitCode !== 0) {
|
|
143
167
|
const stderr = await new Response(proc.stderr).text()
|
package/src/tools/exec/task.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
26
|
-
|
|
27
|
-
|
|
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
|
-
/**
|
|
99
|
-
|
|
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
|
|
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
|
-
|
|
273
|
-
|
|
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
|
-
|
|
363
|
-
|
|
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
|
}
|