zapagent 1.14.19 → 1.14.20
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/package.json +1 -1
- package/src/App.tsx +4 -1
- package/src/cli-routing.ts +0 -14
- package/src/commands/dispatcher.ts +7 -2
- package/src/goal-view.ts +2 -2
- package/src/headless/run.ts +9 -0
- package/src/headless/runHeadless.ts +1 -1
- package/src/hooks/useAskUser.ts +11 -9
- package/src/hooks/usePendingInteraction.ts +37 -0
- package/src/hooks/usePlanMode.ts +26 -30
- package/src/imageStore.ts +72 -16
- package/src/index.tsx +1 -17
- package/src/session.ts +8 -3
- package/zapsdk/builtin-tools/ask-user.ts +3 -3
- package/zapsdk/builtin-tools/edit.ts +6 -1
- package/zapsdk/builtin-tools/http.ts +24 -2
- package/zapsdk/builtin-tools/multi-edit.ts +7 -1
- package/zapsdk/builtin-tools/plan-mode.ts +3 -3
- package/zapsdk/checkpoint/index.ts +4 -1
- package/zapsdk/context/reactive-compact.ts +15 -0
- package/zapsdk/coordinator/coordinator.ts +13 -4
- package/zapsdk/core/providers/openai-compatible.ts +1 -0
- package/zapsdk/debug/agent-logger.ts +4 -1
- package/zapsdk/mcp/manager.ts +75 -43
- package/zapsdk/skills/template.ts +5 -3
package/package.json
CHANGED
package/src/App.tsx
CHANGED
|
@@ -525,7 +525,10 @@ export function App() {
|
|
|
525
525
|
// any history entry) and ~/.zapcode/image-cache/ (SVG/URL caches older
|
|
526
526
|
// than CACHE_TTL). Runs once after first render so it doesn't block
|
|
527
527
|
// startup.
|
|
528
|
-
useEffect(() => {
|
|
528
|
+
useEffect(() => {
|
|
529
|
+
const pruned = pruneImageStorage()
|
|
530
|
+
if (pruned.skipped) appLogger.warn("image_prune_skipped", { reason: pruned.skipped })
|
|
531
|
+
}, [])
|
|
529
532
|
|
|
530
533
|
// ── Track journal index at the start of each turn (for checkpoint slicing) ──
|
|
531
534
|
const turnStartLogIndexRef = useRef(0)
|
package/src/cli-routing.ts
CHANGED
|
@@ -31,20 +31,6 @@ export function devtoolsPortFromArgs(argv: readonly string[]): string | null {
|
|
|
31
31
|
return maybePort && /^\d+$/.test(maybePort) ? maybePort : "9229"
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
-
export type HeadlessCwdArg =
|
|
35
|
-
| { ok: true; cwd?: string }
|
|
36
|
-
| { ok: false; message: string }
|
|
37
|
-
|
|
38
|
-
export function headlessCwdFromArgs(argv: readonly string[]): HeadlessCwdArg {
|
|
39
|
-
const cwdIdx = argv.findIndex(a => a === "--cwd")
|
|
40
|
-
if (cwdIdx < 0) return { ok: true }
|
|
41
|
-
const value = argv[cwdIdx + 1]
|
|
42
|
-
if (value === undefined || (value.startsWith("-") && !/^-?\d/.test(value))) {
|
|
43
|
-
return { ok: false, message: "--cwd requires a value" }
|
|
44
|
-
}
|
|
45
|
-
return { ok: true, cwd: value }
|
|
46
|
-
}
|
|
47
|
-
|
|
48
34
|
function isValueFlag(flag: string): boolean {
|
|
49
35
|
return flag === "--cwd" ||
|
|
50
36
|
flag === "--public-checks" ||
|
|
@@ -369,8 +369,13 @@ export function dispatchSlashCommand(
|
|
|
369
369
|
// session linger in memory under the old id (harmless — listSnapshots
|
|
370
370
|
// filters by the current id and won't surface them), but newly
|
|
371
371
|
// committed snapshots all label + persist under the new id.
|
|
372
|
+
try {
|
|
373
|
+
startNewSession()
|
|
374
|
+
} catch (error) {
|
|
375
|
+
deps.addToast(`Could not start a new session: ${error instanceof Error ? error.message : String(error)}. Retry /new after storage recovers.`, { variant: "error" })
|
|
376
|
+
return true
|
|
377
|
+
}
|
|
372
378
|
wipeTerminalScrollback()
|
|
373
|
-
startNewSession()
|
|
374
379
|
resetConversationState()
|
|
375
380
|
deps.checkpointRef.current.setSessionId(getCurrentSessionId())
|
|
376
381
|
deps.bumpTranscript()
|
|
@@ -828,7 +833,7 @@ export function dispatchSlashCommand(
|
|
|
828
833
|
const params = skill.parameters ?? []
|
|
829
834
|
let prompt = skill.systemPrompt
|
|
830
835
|
if (params.length === 1 && params[0])
|
|
831
|
-
prompt = prompt.replaceAll(`{{${params[0].name}}}`, tail)
|
|
836
|
+
prompt = prompt.replaceAll(`{{${params[0].name}}}`, () => tail)
|
|
832
837
|
const displayTail = displayCommand?.type === "run_skill" && displayCommand.skill === skillName
|
|
833
838
|
? runSkillTailFromRawCommand(meta.displayText ?? "", skillName) ?? (displayCommand.skillInput ?? "").trim()
|
|
834
839
|
: undefined
|
package/src/goal-view.ts
CHANGED
|
@@ -45,9 +45,9 @@ export function goalObjectiveText(objective: string): string {
|
|
|
45
45
|
export function goalActionText(goal: GoalView, attached: boolean, todos: readonly Todo[] = [], activeTool = ""): string {
|
|
46
46
|
if (goal.status === "completed") return goal.accepted ? "目标已完成,验收通过" : "目标已完成"
|
|
47
47
|
if (goal.status === "cancelled") return "目标已取消"
|
|
48
|
-
if (goal.status === "failed") return
|
|
48
|
+
if (goal.status === "failed") return `/goal status ${goal.id} · 目标执行失败`
|
|
49
49
|
if (goal.status === "paused") return goal.stopReason === "DEADLINE_EXCEEDED" ? "已达到你设置的时间限制" : "已暂停,进度已保留"
|
|
50
|
-
if (goal.status === "blocked") return
|
|
50
|
+
if (goal.status === "blocked") return `/goal status ${goal.id} · 目标暂时无法继续`
|
|
51
51
|
if (goal.status === "awaiting_acceptance") return "等待补充信息或确认"
|
|
52
52
|
if (goal.status === "budget_limited") return "已达到你设置的用量限制"
|
|
53
53
|
if (goal.status === "ready_for_delivery") return goal.accepted ? "验收通过,等待交付授权" : "等待交付授权"
|
package/src/headless/run.ts
CHANGED
|
@@ -7,6 +7,15 @@ import { parseHeadlessArgs, readStdinIfPiped, HEADLESS_HELP } from "./args.js"
|
|
|
7
7
|
const EXIT_BAD_ARGS = 2
|
|
8
8
|
|
|
9
9
|
async function runParsedHeadless(args: import("./args.js").HeadlessArgs, watch?: import("../watch/args.js").WatchOptions): Promise<number> {
|
|
10
|
+
// Apply the fully parsed value exactly once, before importing singletons
|
|
11
|
+
// through Watch/runtime. Repeated --cwd follows the parser's last-value rule.
|
|
12
|
+
if (args.cwd) {
|
|
13
|
+
try { process.chdir(args.cwd) }
|
|
14
|
+
catch (err) {
|
|
15
|
+
process.stderr.write(`bad --cwd: ${err instanceof Error ? err.message : String(err)}\n`)
|
|
16
|
+
return EXIT_BAD_ARGS
|
|
17
|
+
}
|
|
18
|
+
}
|
|
10
19
|
const viewer = watch?.enabled ? await import("../watch/integration.js") : undefined
|
|
11
20
|
if (viewer) {
|
|
12
21
|
try { await viewer.startWatch(watch!) }
|
|
@@ -331,7 +331,7 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
|
|
|
331
331
|
}
|
|
332
332
|
|
|
333
333
|
// ── Determine working directory ──────────────────────────────────────
|
|
334
|
-
// NOTE: actual `process.chdir(args.cwd)` happens earlier in
|
|
334
|
+
// NOTE: actual `process.chdir(args.cwd)` happens earlier in headless/run.ts,
|
|
335
335
|
// *before* singletons.ts loads, so autoMemory / mdStore / permissionManager
|
|
336
336
|
// all get constructed with the user-requested cwd. By the time we get
|
|
337
337
|
// here, process.cwd() already reflects --cwd. We just use it.
|
package/src/hooks/useAskUser.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import { useMemo
|
|
1
|
+
import { useMemo } from "react"
|
|
2
2
|
import type { AskUserAnswer, AskUserCallbacks, AskUserQuestion } from "../../zapsdk/index.js"
|
|
3
3
|
|
|
4
|
+
import { usePendingInteraction } from "./usePendingInteraction.js"
|
|
5
|
+
|
|
4
6
|
export interface PendingQuestions {
|
|
5
7
|
questions: AskUserQuestion[]
|
|
6
8
|
/** null = the user dismissed the questions. */
|
|
@@ -17,14 +19,14 @@ export interface UseAskUserResult {
|
|
|
17
19
|
/** One question set at a time: the tool executor runs `ask_user_question`
|
|
18
20
|
* exclusively, so a second `ask` can only arrive after the first resolved. */
|
|
19
21
|
export function useAskUser(): UseAskUserResult {
|
|
20
|
-
const
|
|
22
|
+
const { pending, request } = usePendingInteraction<AskUserQuestion[], AskUserAnswer[] | null>()
|
|
21
23
|
const askUserCallbacks = useMemo<AskUserCallbacks>(() => ({
|
|
22
|
-
ask: (questions) =>
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
24
|
+
ask: (questions, signal) => request(questions, null, signal),
|
|
25
|
+
}), [request])
|
|
26
|
+
// Keep identity stable across renders; App effects depend on this value.
|
|
27
|
+
const pendingQuestions = useMemo(
|
|
28
|
+
() => pending ? { questions: pending.value, resolve: pending.resolve } : null,
|
|
29
|
+
[pending],
|
|
30
|
+
)
|
|
29
31
|
return { askUserCallbacks, pendingQuestions }
|
|
30
32
|
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { useCallback, useEffect, useRef, useState } from "react"
|
|
2
|
+
|
|
3
|
+
/** A single, cancellable UI interaction. Old resolvers cannot settle a newer
|
|
4
|
+
* request; unmount settles the waiter without updating an unmounted view. */
|
|
5
|
+
export function usePendingInteraction<Value, Answer>() {
|
|
6
|
+
const [pending, setPending] = useState<{ value: Value; resolve: (answer: Answer) => void } | null>(null)
|
|
7
|
+
const cancelRef = useRef<(() => void) | null>(null)
|
|
8
|
+
const mounted = useRef(true)
|
|
9
|
+
|
|
10
|
+
useEffect(() => {
|
|
11
|
+
mounted.current = true
|
|
12
|
+
return () => {
|
|
13
|
+
mounted.current = false
|
|
14
|
+
cancelRef.current?.()
|
|
15
|
+
}
|
|
16
|
+
}, [])
|
|
17
|
+
|
|
18
|
+
const request = useCallback((value: Value, cancelled: Answer, signal?: AbortSignal): Promise<Answer> => {
|
|
19
|
+
if (!mounted.current || signal?.aborted) return Promise.resolve(cancelled)
|
|
20
|
+
cancelRef.current?.()
|
|
21
|
+
return new Promise((resolve) => {
|
|
22
|
+
const settle = (answer: Answer) => {
|
|
23
|
+
if (cancelRef.current !== cancel) return
|
|
24
|
+
cancelRef.current = null
|
|
25
|
+
signal?.removeEventListener("abort", cancel)
|
|
26
|
+
if (mounted.current) setPending(null)
|
|
27
|
+
resolve(answer)
|
|
28
|
+
}
|
|
29
|
+
const cancel = () => settle(cancelled)
|
|
30
|
+
cancelRef.current = cancel
|
|
31
|
+
signal?.addEventListener("abort", cancel, { once: true })
|
|
32
|
+
setPending({ value, resolve: settle })
|
|
33
|
+
})
|
|
34
|
+
}, [])
|
|
35
|
+
|
|
36
|
+
return { pending, request }
|
|
37
|
+
}
|
package/src/hooks/usePlanMode.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
import { useMemo, useRef
|
|
1
|
+
import { useMemo, useRef } from "react"
|
|
2
2
|
import { saveAppConfig, type AppConfig, type PermissionMode } from "../config.js"
|
|
3
3
|
import { configPath } from "../session.js"
|
|
4
4
|
import type { PlanModeCallbacks } from "../../zapsdk/index.js"
|
|
5
5
|
import type { PlanChoice } from "../ui/dialog-plan-approval.js"
|
|
6
6
|
|
|
7
|
+
import { usePendingInteraction } from "./usePendingInteraction.js"
|
|
8
|
+
|
|
7
9
|
interface PendingPlan {
|
|
8
10
|
plan: string
|
|
9
11
|
resolve: (choice: PlanChoice) => void
|
|
@@ -37,7 +39,7 @@ export interface UsePlanModeResult {
|
|
|
37
39
|
*/
|
|
38
40
|
export function usePlanMode(opts: UsePlanModeOptions): UsePlanModeResult {
|
|
39
41
|
const { configRef, setConfig } = opts
|
|
40
|
-
const
|
|
42
|
+
const { pending, request } = usePendingInteraction<string, PlanChoice>()
|
|
41
43
|
const prevModeBeforePlanRef = useRef<PermissionMode | null>(null)
|
|
42
44
|
|
|
43
45
|
const planCallbacks = useMemo<PlanModeCallbacks>(() => ({
|
|
@@ -53,34 +55,28 @@ export function usePlanMode(opts: UsePlanModeOptions): UsePlanModeResult {
|
|
|
53
55
|
saveAppConfig(configPath, next)
|
|
54
56
|
},
|
|
55
57
|
isActive: () => configRef.current.permissionMode === "plan",
|
|
56
|
-
requestExit: (plan
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
},
|
|
79
|
-
})
|
|
80
|
-
}),
|
|
81
|
-
// configRef + setConfig are refs/stable callbacks — empty deps is correct.
|
|
82
|
-
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
83
|
-
}), [])
|
|
58
|
+
requestExit: async (plan, signal) => {
|
|
59
|
+
const choice = await request(plan, { kind: "reject", reason: "Plan interaction cancelled" }, signal)
|
|
60
|
+
if (signal?.aborted) return { approved: false, reason: "Plan interaction cancelled" }
|
|
61
|
+
if (choice.kind === "approve") {
|
|
62
|
+
const restored = prevModeBeforePlanRef.current ?? "default"
|
|
63
|
+
prevModeBeforePlanRef.current = null
|
|
64
|
+
const next = { ...configRef.current, permissionMode: restored }
|
|
65
|
+
setConfig(next)
|
|
66
|
+
saveAppConfig(configPath, next)
|
|
67
|
+
return { approved: true }
|
|
68
|
+
}
|
|
69
|
+
// Rejection/cancellation keeps plan mode and its original snapshot so
|
|
70
|
+
// a later, live approval still restores the user's previous mode.
|
|
71
|
+
return { approved: false, reason: choice.reason }
|
|
72
|
+
},
|
|
73
|
+
}), [configRef, setConfig, request])
|
|
74
|
+
|
|
75
|
+
// Keep identity stable across renders; App effects depend on this value.
|
|
76
|
+
const pendingPlan = useMemo(
|
|
77
|
+
() => pending ? { plan: pending.value, resolve: pending.resolve } : null,
|
|
78
|
+
[pending],
|
|
79
|
+
)
|
|
84
80
|
|
|
85
81
|
return { planCallbacks, pendingPlan }
|
|
86
82
|
}
|
package/src/imageStore.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* Filenames are timestamps (`paste-<ts>.png`).
|
|
6
6
|
* ONE source of truth — once deleted, the
|
|
7
7
|
* image is unrecoverable. Strict policy:
|
|
8
|
-
* keep
|
|
8
|
+
* keep history and pending-queue references.
|
|
9
9
|
*
|
|
10
10
|
* ~/.zapcode/image-cache/ SVG raster outputs + URL downloads.
|
|
11
11
|
* Filenames are content-hash. If a hash gets
|
|
@@ -28,6 +28,7 @@ import {
|
|
|
28
28
|
closeSync,
|
|
29
29
|
existsSync,
|
|
30
30
|
openSync,
|
|
31
|
+
lstatSync,
|
|
31
32
|
readdirSync,
|
|
32
33
|
readFileSync,
|
|
33
34
|
readSync,
|
|
@@ -36,7 +37,7 @@ import {
|
|
|
36
37
|
} from "node:fs"
|
|
37
38
|
import type { Dirent } from "node:fs"
|
|
38
39
|
import { createHash } from "node:crypto"
|
|
39
|
-
import { basename, join } from "node:path"
|
|
40
|
+
import { basename, join, resolve } from "node:path"
|
|
40
41
|
import { StringDecoder } from "node:string_decoder"
|
|
41
42
|
import { getAppDataDir } from "../zapsdk/utils/platform.js"
|
|
42
43
|
|
|
@@ -55,23 +56,24 @@ const SESSION_REF_SCAN_CARRY_CHARS = 64 * 1024
|
|
|
55
56
|
const PLACEHOLDER_ID_RE = /^[1-9]\d*$/
|
|
56
57
|
const CONTENT_ADDRESSED_SIDECAR_RE = /^[a-f0-9]{64}\.txt$/
|
|
57
58
|
|
|
58
|
-
/** Internal struct returned for caller-side logging.
|
|
59
|
-
|
|
59
|
+
/** Internal struct returned for caller-side logging. `skipped` explains a
|
|
60
|
+
* pass that stopped early and may have kept garbage. */
|
|
61
|
+
export type PruneResult = { deleted: number; bytesFreed: number; skipped?: string }
|
|
60
62
|
|
|
61
63
|
// ─── image-paste/ — strict, history-driven prune ────────────────────
|
|
62
64
|
|
|
63
65
|
/**
|
|
64
66
|
* Walk ~/.zapcode/image-paste/ and remove every file that is NOT
|
|
65
|
-
* referenced by
|
|
66
|
-
*
|
|
67
|
-
*
|
|
67
|
+
* referenced by history.jsonl or a durable pending-message journal. History
|
|
68
|
+
* is capped at 200 entries (see prompt.tsx MAX_HISTORY); queue ownership lasts
|
|
69
|
+
* until an entry is accepted or removed, independent of history rollover.
|
|
68
70
|
*
|
|
69
71
|
* Reads history.jsonl directly off disk rather than going through
|
|
70
72
|
* prompt.tsx's in-memory `history` array, both to avoid cross-module
|
|
71
73
|
* state coupling and so this works even if prompt.tsx hasn't been
|
|
72
74
|
* imported yet (it has, but the decoupling is cleaner).
|
|
73
75
|
*/
|
|
74
|
-
export function pruneOrphanedPasteImages(): PruneResult {
|
|
76
|
+
export function pruneOrphanedPasteImages(pendingQueueRefs?: ReadonlySet<string>): PruneResult {
|
|
75
77
|
const result: PruneResult = { deleted: 0, bytesFreed: 0 }
|
|
76
78
|
try {
|
|
77
79
|
const dataDir = getAppDataDir()
|
|
@@ -79,11 +81,12 @@ export function pruneOrphanedPasteImages(): PruneResult {
|
|
|
79
81
|
if (!existsSync(pasteDir)) return result
|
|
80
82
|
|
|
81
83
|
const referenced = collectReferencedPaths(join(dataDir, "history.jsonl"), "imageRefs")
|
|
84
|
+
for (const path of pendingQueueRefs ?? collectPendingQueueImagePaths(dataDir)) referenced.add(path)
|
|
82
85
|
|
|
83
86
|
for (const entry of readdirSync(pasteDir, { withFileTypes: true })) {
|
|
84
87
|
if (!entry.isFile()) continue
|
|
85
88
|
const fp = join(pasteDir, entry.name)
|
|
86
|
-
if (referenced.has(fp)) continue
|
|
89
|
+
if (referenced.has(fp) || referenced.has(resolve(fp))) continue
|
|
87
90
|
try {
|
|
88
91
|
const sz = statSync(fp).size
|
|
89
92
|
unlinkSync(fp)
|
|
@@ -91,10 +94,48 @@ export function pruneOrphanedPasteImages(): PruneResult {
|
|
|
91
94
|
result.bytesFreed += sz
|
|
92
95
|
} catch { /* file already gone or no perm — skip */ }
|
|
93
96
|
}
|
|
94
|
-
} catch {
|
|
97
|
+
} catch (err) { result.skipped = describePruneError(err) } // never block boot
|
|
95
98
|
return result
|
|
96
99
|
}
|
|
97
100
|
|
|
101
|
+
/** Pending queues keep file references, not image bytes. Scan only the known
|
|
102
|
+
* projects/<project>/follow-ups/*.json layout, without following symlinks or
|
|
103
|
+
* opening referenced image paths. Accepted/removed entries no longer own files.
|
|
104
|
+
* Let unreadable or malformed journals abort this prune pass: an incomplete
|
|
105
|
+
* live set must not authorize deletion of potentially recoverable attachments. */
|
|
106
|
+
function collectPendingQueueImagePaths(dataDir: string): Set<string> {
|
|
107
|
+
const referenced = new Set<string>()
|
|
108
|
+
const projects = join(dataDir, "projects")
|
|
109
|
+
if (!existsSync(projects) || !lstatSync(projects).isDirectory()) return referenced
|
|
110
|
+
for (const project of readdirSync(projects, { withFileTypes: true })) {
|
|
111
|
+
if (!project.isDirectory()) continue
|
|
112
|
+
const projectDir = join(projects, project.name)
|
|
113
|
+
const queueDir = readdirSync(projectDir, { withFileTypes: true })
|
|
114
|
+
.find(entry => entry.name === "follow-ups" && entry.isDirectory())
|
|
115
|
+
if (!queueDir) continue
|
|
116
|
+
const directory = join(projectDir, queueDir.name)
|
|
117
|
+
for (const file of readdirSync(directory, { withFileTypes: true })) {
|
|
118
|
+
if (!file.isFile() || !file.name.endsWith(".json")) continue
|
|
119
|
+
const saved = JSON.parse(readFileSync(join(directory, file.name), "utf8"))
|
|
120
|
+
if (saved?.version !== 1 || !Array.isArray(saved.entries)) {
|
|
121
|
+
throw new Error("Invalid pending-message store")
|
|
122
|
+
}
|
|
123
|
+
for (const entry of saved.entries) {
|
|
124
|
+
if (entry?.state === "accepted") continue
|
|
125
|
+
if (!entry || typeof entry !== "object" ||
|
|
126
|
+
(entry.images !== undefined && !Array.isArray(entry.images))) {
|
|
127
|
+
throw new Error("Invalid pending-message entry")
|
|
128
|
+
}
|
|
129
|
+
for (const image of entry.images ?? []) {
|
|
130
|
+
const path = image?.content?.filePath
|
|
131
|
+
if (typeof path === "string" && path) referenced.add(resolve(path))
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return referenced
|
|
137
|
+
}
|
|
138
|
+
|
|
98
139
|
export function pruneOrphanedPasteHistoryText(): PruneResult {
|
|
99
140
|
const result: PruneResult = { deleted: 0, bytesFreed: 0 }
|
|
100
141
|
try {
|
|
@@ -269,27 +310,29 @@ function readHistoryTail(historyPath: string): string {
|
|
|
269
310
|
* Walk ~/.zapcode/image-cache/ and remove any file whose mtime is
|
|
270
311
|
* older than CACHE_TTL_MS. Safe because filenames are content-hashes:
|
|
271
312
|
* the SVG/URL producer (zapsdk/utils/image.ts) regenerates on miss.
|
|
272
|
-
*
|
|
313
|
+
* Pending queues still need their cached files for recovery without fetching
|
|
314
|
+
* or rasterizing their original sources, so retain those references.
|
|
273
315
|
*/
|
|
274
|
-
export function pruneStaleImageCache(): PruneResult {
|
|
316
|
+
export function pruneStaleImageCache(pendingQueueRefs?: ReadonlySet<string>): PruneResult {
|
|
275
317
|
const result: PruneResult = { deleted: 0, bytesFreed: 0 }
|
|
276
318
|
try {
|
|
277
319
|
const cacheDir = join(getAppDataDir(), "image-cache")
|
|
278
320
|
if (!existsSync(cacheDir)) return result
|
|
279
321
|
|
|
322
|
+
const referenced = pendingQueueRefs ?? collectPendingQueueImagePaths(getAppDataDir())
|
|
280
323
|
const cutoff = Date.now() - CACHE_TTL_MS
|
|
281
324
|
for (const entry of readdirSync(cacheDir, { withFileTypes: true })) {
|
|
282
325
|
if (!entry.isFile()) continue
|
|
283
326
|
const fp = join(cacheDir, entry.name)
|
|
284
327
|
try {
|
|
285
328
|
const st = statSync(fp)
|
|
286
|
-
if (st.mtimeMs >= cutoff) continue
|
|
329
|
+
if (st.mtimeMs >= cutoff || referenced.has(resolve(fp))) continue
|
|
287
330
|
unlinkSync(fp)
|
|
288
331
|
result.deleted += 1
|
|
289
332
|
result.bytesFreed += st.size
|
|
290
333
|
} catch { /* skip */ }
|
|
291
334
|
}
|
|
292
|
-
} catch {
|
|
335
|
+
} catch (err) { result.skipped = describePruneError(err) }
|
|
293
336
|
return result
|
|
294
337
|
}
|
|
295
338
|
|
|
@@ -300,11 +343,24 @@ export function pruneStaleImageCache(): PruneResult {
|
|
|
300
343
|
* Returns combined stats for optional debug logging.
|
|
301
344
|
*/
|
|
302
345
|
export function pruneImageStorage(): PruneResult {
|
|
303
|
-
|
|
304
|
-
|
|
346
|
+
// Both image stores honor the same queue ownership; scan the journals once.
|
|
347
|
+
// An unreadable journal skips both passes rather than risk deleting its files.
|
|
348
|
+
let queued: Set<string> | undefined
|
|
349
|
+
let queueError: string | undefined
|
|
350
|
+
try { queued = collectPendingQueueImagePaths(getAppDataDir()) }
|
|
351
|
+
catch (err) { queueError = `pending-message journals unreadable: ${describePruneError(err)}` }
|
|
352
|
+
const none: PruneResult = { deleted: 0, bytesFreed: 0 }
|
|
353
|
+
const a = queued ? pruneOrphanedPasteImages(queued) : none
|
|
354
|
+
const b = queued ? pruneStaleImageCache(queued) : none
|
|
305
355
|
const c = pruneOrphanedPasteHistoryText()
|
|
356
|
+
const skipped = [queueError, a.skipped, b.skipped].filter((reason): reason is string => !!reason)
|
|
306
357
|
return {
|
|
307
358
|
deleted: a.deleted + b.deleted + c.deleted,
|
|
308
359
|
bytesFreed: a.bytesFreed + b.bytesFreed + c.bytesFreed,
|
|
360
|
+
...(skipped.length ? { skipped: skipped.join("; ") } : {}),
|
|
309
361
|
}
|
|
310
362
|
}
|
|
363
|
+
|
|
364
|
+
function describePruneError(err: unknown): string {
|
|
365
|
+
return err instanceof Error ? err.message : String(err)
|
|
366
|
+
}
|
package/src/index.tsx
CHANGED
|
@@ -6,7 +6,7 @@ import { spawn } from "node:child_process"
|
|
|
6
6
|
import { parseWatchArgs } from "./watch/args.js";
|
|
7
7
|
import { VERSION } from "./version.js"
|
|
8
8
|
import { loadDotEnvFile } from "./dotenv.js"
|
|
9
|
-
import { devtoolsPortFromArgs,
|
|
9
|
+
import { devtoolsPortFromArgs, isHeadlessInvocation } from "./cli-routing.js"
|
|
10
10
|
|
|
11
11
|
// --help / --version before anything else (no TUI needed)
|
|
12
12
|
let args = process.argv.slice(2)
|
|
@@ -168,22 +168,6 @@ if (devPort) {
|
|
|
168
168
|
// Ink graph below — no TTY ops, no stdin patch, no devtools (unless user
|
|
169
169
|
// explicitly set ZAPCODE_DEVTOOLS_PORT before invocation).
|
|
170
170
|
if (isHeadless) {
|
|
171
|
-
// --cwd must be applied BEFORE singletons.ts is imported. singletons
|
|
172
|
-
// constructs autoMemory + mdStore against process.cwd() at module load,
|
|
173
|
-
// so a later process.chdir() leaves memory pointed at the original dir
|
|
174
|
-
// (silent split between tools-see-new-cwd / memory-sees-old-cwd).
|
|
175
|
-
const cwdArg = headlessCwdFromArgs(args)
|
|
176
|
-
if (!cwdArg.ok) {
|
|
177
|
-
process.stderr.write(`${cwdArg.message}\n`)
|
|
178
|
-
process.exit(2)
|
|
179
|
-
}
|
|
180
|
-
if (cwdArg.cwd) {
|
|
181
|
-
try { process.chdir(cwdArg.cwd) }
|
|
182
|
-
catch (err) {
|
|
183
|
-
process.stderr.write(`bad --cwd: ${err instanceof Error ? err.message : String(err)}\n`)
|
|
184
|
-
process.exit(2)
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
171
|
const { runHeadlessFromArgv } = await import("./headless/run.js")
|
|
188
172
|
const code = await runHeadlessFromArgv(args, watchOptions)
|
|
189
173
|
process.exit(code)
|
package/src/session.ts
CHANGED
|
@@ -644,12 +644,13 @@ class SessionWriter {
|
|
|
644
644
|
if (!this.materialized && this.buffer.length === 0) return
|
|
645
645
|
// Write last-prompt metadata (CCB compatible tail entry)
|
|
646
646
|
if (this.firstUserMsg) {
|
|
647
|
-
const entry = {
|
|
647
|
+
const entry = JSON.stringify({
|
|
648
648
|
type: "last-prompt",
|
|
649
649
|
lastPrompt: this.firstUserMsg.slice(0, 200),
|
|
650
650
|
sessionId: this.sessionId,
|
|
651
|
-
}
|
|
652
|
-
this.
|
|
651
|
+
})
|
|
652
|
+
// A failed finalize leaves this row buffered; retrying must not stack copies.
|
|
653
|
+
if (this.buffer[this.buffer.length - 1] !== entry) this.buffer.push(entry)
|
|
653
654
|
}
|
|
654
655
|
this.flushSync()
|
|
655
656
|
}
|
|
@@ -751,6 +752,10 @@ export function replaceLog(logIndex: number, type: string, text: string, tool?:
|
|
|
751
752
|
|
|
752
753
|
export function startNewSession(): void {
|
|
753
754
|
currentWriter.finalize()
|
|
755
|
+
// Keep the old writer and its exit handler available to retry failed writes.
|
|
756
|
+
if (currentWriter.getPendingWriteCount() > 0) {
|
|
757
|
+
throw new Error("cannot start a new session while current session writes are pending")
|
|
758
|
+
}
|
|
754
759
|
currentWriter.dispose()
|
|
755
760
|
currentWriter = new SessionWriter()
|
|
756
761
|
journalLogIndex = 0
|
|
@@ -20,7 +20,7 @@ export interface AskUserAnswer {
|
|
|
20
20
|
/** The app layer owns the UI. Resolve with the answers, or null when the user
|
|
21
21
|
* dismissed the question without answering. */
|
|
22
22
|
export interface AskUserCallbacks {
|
|
23
|
-
ask(questions: AskUserQuestion[]): Promise<AskUserAnswer[] | null>;
|
|
23
|
+
ask(questions: AskUserQuestion[], signal?: AbortSignal): Promise<AskUserAnswer[] | null>;
|
|
24
24
|
}
|
|
25
25
|
|
|
26
26
|
export interface AskUserToolOptions {
|
|
@@ -63,7 +63,7 @@ export function askUserQuestionTool(options: AskUserToolOptions): Tool {
|
|
|
63
63
|
// The user may take as long as they like.
|
|
64
64
|
timeoutMs: 24 * 60 * 60 * 1000,
|
|
65
65
|
},
|
|
66
|
-
handler: async (args,
|
|
66
|
+
handler: async (args, signal, context) => {
|
|
67
67
|
const questions = args.questions as AskUserQuestion[];
|
|
68
68
|
const observation = currentRuntimeObservation();
|
|
69
69
|
const publish = (phase: "requested" | "settled") => {
|
|
@@ -72,7 +72,7 @@ export function askUserQuestionTool(options: AskUserToolOptions): Tool {
|
|
|
72
72
|
};
|
|
73
73
|
publish("requested");
|
|
74
74
|
let answers: AskUserAnswer[] | null;
|
|
75
|
-
try { answers = await options.callbacks.ask(questions); }
|
|
75
|
+
try { answers = await options.callbacks.ask(questions, signal); }
|
|
76
76
|
finally { publish("settled"); }
|
|
77
77
|
if (!answers) {
|
|
78
78
|
return {
|
|
@@ -24,7 +24,7 @@ export function editFileTool(options: EditFileOptions = {}): Tool {
|
|
|
24
24
|
"**Do not use edit_file to rewrite an entire file**: when `new_string` (or `old_string`) would be more than ~50 lines, prefer an intentional full replacement with `write_file` instead.",
|
|
25
25
|
parameters: z.object({
|
|
26
26
|
path: z.string().describe("Path to the file to edit"),
|
|
27
|
-
old_string: z.string().describe("The exact string to find and replace"),
|
|
27
|
+
old_string: z.string().min(1).describe("The exact string to find and replace"),
|
|
28
28
|
new_string: z.string().describe("The replacement string"),
|
|
29
29
|
replace_all: z.boolean().optional().describe("Replace all occurrences (default: false, requires unique match)"),
|
|
30
30
|
skip_syntax_check: z.boolean().optional().describe("Skip the pre-write syntax check (TS/JS/JSON only). Use only when the validator gives a known false positive — e.g. an intentional intermediate state, an exotic JSX form, or a fragment that will be valid after a follow-up edit."),
|
|
@@ -43,6 +43,11 @@ export function editFileTool(options: EditFileOptions = {}): Tool {
|
|
|
43
43
|
const replaceAll = (args.replace_all as boolean) ?? false;
|
|
44
44
|
const skipSyntaxCheck = (args.skip_syntax_check as boolean) ?? false;
|
|
45
45
|
|
|
46
|
+
// Direct SDK handlers can bypass parameter-schema validation.
|
|
47
|
+
if (oldString.length === 0) {
|
|
48
|
+
return { success: false, output: "", error: "old_string must not be empty." };
|
|
49
|
+
}
|
|
50
|
+
|
|
46
51
|
if (!(await isToolPathWriteAllowed(filePath, options, context))) {
|
|
47
52
|
return {
|
|
48
53
|
success: false,
|
|
@@ -162,8 +162,9 @@ async function fetchWithValidatedRedirects(
|
|
|
162
162
|
options: HttpRuntimeOptions,
|
|
163
163
|
): Promise<{ response: Response; finalUrl: URL }> {
|
|
164
164
|
let current = await assertSafePublicHttpUrl(rawUrl, options.resolveHostname);
|
|
165
|
+
let request = { ...init };
|
|
165
166
|
for (let redirect = 0; redirect <= options.maxRedirects; redirect++) {
|
|
166
|
-
const response = await fetch(current, { ...
|
|
167
|
+
const response = await fetch(current, { ...request, redirect: "manual" });
|
|
167
168
|
if (![301, 302, 303, 307, 308].includes(response.status)) {
|
|
168
169
|
return { response, finalUrl: current };
|
|
169
170
|
}
|
|
@@ -172,7 +173,28 @@ async function fetchWithValidatedRedirects(
|
|
|
172
173
|
if (redirect === options.maxRedirects) {
|
|
173
174
|
throw new Error(`Too many redirects (>${options.maxRedirects})`);
|
|
174
175
|
}
|
|
175
|
-
|
|
176
|
+
const method = (request.method ?? "GET").toUpperCase();
|
|
177
|
+
if (((response.status === 301 || response.status === 302) && method === "POST") ||
|
|
178
|
+
(response.status === 303 && method !== "GET" && method !== "HEAD")) {
|
|
179
|
+
// Fetch redirect semantics: a retrieval must not replay the original body.
|
|
180
|
+
// Also drop an explicitly supplied body length now that the body is empty.
|
|
181
|
+
const headers = new Headers(request.headers);
|
|
182
|
+
for (const name of ["Content-Encoding", "Content-Language", "Content-Location", "Content-Type", "Content-Length"]) {
|
|
183
|
+
headers.delete(name);
|
|
184
|
+
}
|
|
185
|
+
request = { ...request, method: "GET", body: null, headers };
|
|
186
|
+
}
|
|
187
|
+
const next = await assertSafePublicHttpUrl(new URL(location, current).toString(), options.resolveHostname);
|
|
188
|
+
if (next.origin !== current.origin) {
|
|
189
|
+
// Fetch drops Authorization on cross-origin redirects; never hand caller
|
|
190
|
+
// credentials to a host the caller did not name. Not restored on return.
|
|
191
|
+
const headers = new Headers(request.headers);
|
|
192
|
+
for (const name of ["Authorization", "Proxy-Authorization", "Cookie"]) {
|
|
193
|
+
headers.delete(name);
|
|
194
|
+
}
|
|
195
|
+
request = { ...request, headers };
|
|
196
|
+
}
|
|
197
|
+
current = next;
|
|
176
198
|
}
|
|
177
199
|
throw new Error("Redirect validation failed");
|
|
178
200
|
}
|
|
@@ -19,7 +19,7 @@ export interface MultiEditOptions {
|
|
|
19
19
|
// buffer produced by edits 0..N-1, which is what lets the model chain rewrites
|
|
20
20
|
// like (A→B, B→C) in a single call.
|
|
21
21
|
const editSchema = z.object({
|
|
22
|
-
old_string: z.string().describe("Exact string to find and replace"),
|
|
22
|
+
old_string: z.string().min(1).describe("Exact string to find and replace"),
|
|
23
23
|
new_string: z.string().describe("Replacement string"),
|
|
24
24
|
replace_all: z.boolean().optional().describe("Replace all occurrences (default: false)"),
|
|
25
25
|
});
|
|
@@ -48,6 +48,12 @@ export function multiEditTool(options: MultiEditOptions = {}): Tool {
|
|
|
48
48
|
const edits = args.edits as Array<{ old_string: string; new_string: string; replace_all?: boolean }>;
|
|
49
49
|
const skipSyntaxCheck = (args.skip_syntax_check as boolean) ?? false;
|
|
50
50
|
|
|
51
|
+
// Direct SDK handlers can bypass parameter-schema validation.
|
|
52
|
+
const emptyEdit = edits.findIndex(edit => edit.old_string.length === 0);
|
|
53
|
+
if (emptyEdit >= 0) {
|
|
54
|
+
return { success: false, output: "", error: `Edit #${emptyEdit + 1} failed: old_string must not be empty.` };
|
|
55
|
+
}
|
|
56
|
+
|
|
51
57
|
if (!(await isToolPathWriteAllowed(filePath, options, context))) {
|
|
52
58
|
return {
|
|
53
59
|
success: false,
|
|
@@ -14,7 +14,7 @@ export interface PlanModeCallbacks {
|
|
|
14
14
|
* `approved: true` (mode switched back to default + the caller can
|
|
15
15
|
* continue with implementation) or `approved: false` (mode stays `plan`;
|
|
16
16
|
* the caller should revise and re-present). */
|
|
17
|
-
requestExit(plan: string): Promise<{ approved: boolean; reason?: string }>;
|
|
17
|
+
requestExit(plan: string, signal?: AbortSignal): Promise<{ approved: boolean; reason?: string }>;
|
|
18
18
|
/** True iff currently in plan mode. Used by the tools to reject
|
|
19
19
|
* `exit_plan_mode` when already outside plan mode, and to no-op
|
|
20
20
|
* `enter_plan_mode` when already inside. */
|
|
@@ -99,7 +99,7 @@ export function exitPlanModeTool(options: PlanModeToolsOptions): Tool {
|
|
|
99
99
|
confidence: "declared",
|
|
100
100
|
}),
|
|
101
101
|
},
|
|
102
|
-
handler: async (args) => {
|
|
102
|
+
handler: async (args, signal) => {
|
|
103
103
|
if (!options.callbacks.isActive()) {
|
|
104
104
|
return {
|
|
105
105
|
success: false,
|
|
@@ -109,7 +109,7 @@ export function exitPlanModeTool(options: PlanModeToolsOptions): Tool {
|
|
|
109
109
|
};
|
|
110
110
|
}
|
|
111
111
|
const plan = args.plan as string;
|
|
112
|
-
const { approved, reason } = await options.callbacks.requestExit(plan);
|
|
112
|
+
const { approved, reason } = await options.callbacks.requestExit(plan, signal);
|
|
113
113
|
if (approved) {
|
|
114
114
|
return {
|
|
115
115
|
success: true,
|
|
@@ -388,8 +388,11 @@ export class CheckpointManager {
|
|
|
388
388
|
}
|
|
389
389
|
}
|
|
390
390
|
}
|
|
391
|
+
// UI positions belong to the source process's rendered transcript.
|
|
392
|
+
// Restoring merges streaming rows, so a fork must map its durable
|
|
393
|
+
// journal boundary instead. Do this after archive substitution too.
|
|
391
394
|
const snap = remap
|
|
392
|
-
? { ...persisted, sessionId: this.sessionId }
|
|
395
|
+
? { ...persisted, sessionId: this.sessionId, uiLogIndex: undefined }
|
|
393
396
|
: persisted;
|
|
394
397
|
const safeSnap = this.sanitizeSnapshot(snap);
|
|
395
398
|
if (safeSnap && !this.isExpired(safeSnap)) this.snaps.hydrateOne(safeSnap);
|
|
@@ -182,6 +182,21 @@ export class ReactiveCompact {
|
|
|
182
182
|
// caused by the tail message itself, so preserve its head/tail and retry.
|
|
183
183
|
this.compactOversizedMessages(result, protectedMessages);
|
|
184
184
|
|
|
185
|
+
// Multimodal providers send text blocks instead of `content`. Keep mirrored
|
|
186
|
+
// text in sync after both reducers; independent blocks are not disposable.
|
|
187
|
+
messages.forEach((original, index) => {
|
|
188
|
+
const candidate = result[index]!;
|
|
189
|
+
if (original.role !== "user" || !original.contentBlocks?.length
|
|
190
|
+
|| original.content === candidate.content) return;
|
|
191
|
+
const textBlocks = original.contentBlocks.filter(block => block.type === "text");
|
|
192
|
+
if (textBlocks.length !== 1 || textBlocks[0]!.text !== original.content) {
|
|
193
|
+
result[index] = original;
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
result[index] = { ...candidate, contentBlocks: original.contentBlocks.map(block =>
|
|
197
|
+
block.type === "text" ? { ...block, text: candidate.content } : block) };
|
|
198
|
+
});
|
|
199
|
+
|
|
185
200
|
// Step 3: If still overflowing, drop middle messages.
|
|
186
201
|
// Keep: leading system messages, last 6 messages, drop the middle. Trigger whenever
|
|
187
202
|
// at least one old non-system message can be replaced; context overflows can
|
|
@@ -611,10 +611,18 @@ export class AgentCoordinator {
|
|
|
611
611
|
}
|
|
612
612
|
|
|
613
613
|
private async waitForMessage(runId: string): Promise<AgentMailboxMessage> {
|
|
614
|
-
const available = await this.drainMailbox(runId);
|
|
615
|
-
if (available[0]) return available[0];
|
|
616
614
|
const control = this.controls.get(runId);
|
|
617
615
|
if (!control) throw new Error(`Unknown Agent run: ${runId}`);
|
|
616
|
+
control.controller.signal.throwIfAborted();
|
|
617
|
+
// Claim only the returned message, before yielding to another receiver.
|
|
618
|
+
const available = this.current().messages.find((message) =>
|
|
619
|
+
message.toRunId === runId && message.consumedAt === undefined
|
|
620
|
+
);
|
|
621
|
+
if (available) {
|
|
622
|
+
available.consumedAt = this.clock();
|
|
623
|
+
await this.persist();
|
|
624
|
+
return structuredClone(available);
|
|
625
|
+
}
|
|
618
626
|
return new Promise((resolve, reject) => {
|
|
619
627
|
const deliver = (message: AgentMailboxMessage) => {
|
|
620
628
|
control.controller.signal.removeEventListener("abort", abort);
|
|
@@ -625,13 +633,14 @@ export class AgentCoordinator {
|
|
|
625
633
|
if (index >= 0) control.messageWaiters.splice(index, 1);
|
|
626
634
|
reject(control.controller.signal.reason ?? new Error("Agent cancelled"));
|
|
627
635
|
};
|
|
628
|
-
|
|
629
|
-
else control.controller.signal.addEventListener("abort", abort, { once: true });
|
|
636
|
+
control.controller.signal.addEventListener("abort", abort, { once: true });
|
|
630
637
|
control.messageWaiters.push(deliver);
|
|
631
638
|
});
|
|
632
639
|
}
|
|
633
640
|
|
|
634
641
|
private deliverMessage(message: AgentMailboxMessage): void {
|
|
642
|
+
// A receiver may have claimed this message while send() persisted it.
|
|
643
|
+
if (message.consumedAt !== undefined) return;
|
|
635
644
|
const control = this.controls.get(message.toRunId);
|
|
636
645
|
const waiter = control?.messageWaiters.shift();
|
|
637
646
|
if (!waiter) return;
|
|
@@ -164,7 +164,7 @@ export class AgentLogger {
|
|
|
164
164
|
|
|
165
165
|
type UsageLogInput = Pick<
|
|
166
166
|
TokenUsage,
|
|
167
|
-
"inputTokens" | "providerUsageReported" | "cacheReadInputTokens" | "cacheCreationInputTokens"
|
|
167
|
+
"inputTokens" | "providerUsageReported" | "usageIncomplete" | "cacheReadInputTokens" | "cacheCreationInputTokens"
|
|
168
168
|
>;
|
|
169
169
|
|
|
170
170
|
export function formatUsageLogFields(usage: UsageLogInput): Record<string, unknown> {
|
|
@@ -173,6 +173,9 @@ export function formatUsageLogFields(usage: UsageLogInput): Record<string, unkno
|
|
|
173
173
|
const cacheCreationReported = typeof usage.cacheCreationInputTokens === "number";
|
|
174
174
|
return {
|
|
175
175
|
inputTokens: usage.inputTokens,
|
|
176
|
+
...(typeof usage.usageIncomplete === "boolean"
|
|
177
|
+
? { usageIncomplete: usage.usageIncomplete }
|
|
178
|
+
: {}),
|
|
176
179
|
...(typeof usage.providerUsageReported === "boolean"
|
|
177
180
|
? { providerUsageReported: usage.providerUsageReported }
|
|
178
181
|
: {}),
|
package/zapsdk/mcp/manager.ts
CHANGED
|
@@ -330,7 +330,7 @@ export class MCPManager {
|
|
|
330
330
|
clearTimeout(s.reconnectTimer);
|
|
331
331
|
s.reconnectTimer = undefined;
|
|
332
332
|
}
|
|
333
|
-
|
|
333
|
+
// connect() owns invalidation and disposal, including overlapping reconnects.
|
|
334
334
|
// Clear terminal-error so scheduleReconnect's attempt counter starts
|
|
335
335
|
// fresh — the user explicitly asked to retry.
|
|
336
336
|
s.reconnectAttempts = 0;
|
|
@@ -380,10 +380,9 @@ export class MCPManager {
|
|
|
380
380
|
if (!s) return;
|
|
381
381
|
if (s.reconnectTimer) clearTimeout(s.reconnectTimer);
|
|
382
382
|
this.servers.delete(name);
|
|
383
|
-
|
|
384
|
-
try { await s.client.close(); } catch { /* ignore */ }
|
|
385
|
-
}
|
|
383
|
+
const disposed = this.disposeClient(s); // invalidate pending startup before yielding
|
|
386
384
|
this.setStatus(s, "disconnected");
|
|
385
|
+
await disposed;
|
|
387
386
|
}
|
|
388
387
|
|
|
389
388
|
/** Tear down everything. Best-effort, parallel; safe to call at unmount. */
|
|
@@ -436,26 +435,27 @@ export class MCPManager {
|
|
|
436
435
|
}
|
|
437
436
|
|
|
438
437
|
private async connect(s: ManagedServer): Promise<void> {
|
|
439
|
-
|
|
440
|
-
//
|
|
441
|
-
//
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
const generation = ++s.generation;
|
|
438
|
+
if (this.servers.get(s.config.name) !== s) return;
|
|
439
|
+
// Invalidate first, even when transport creation has not yet returned.
|
|
440
|
+
// Each continuation owns only this generation, never a newer reconnect.
|
|
441
|
+
const disposed = this.disposeClient(s);
|
|
442
|
+
const generation = s.generation;
|
|
443
|
+
const current = () => this.isCurrent(s, generation);
|
|
444
|
+
await disposed;
|
|
445
|
+
if (!current()) return;
|
|
450
446
|
this.setStatus(s, "connecting");
|
|
451
447
|
|
|
452
448
|
let transport: Transport;
|
|
453
449
|
try {
|
|
454
450
|
const built = await createTransport(s.config);
|
|
455
451
|
transport = built.transport;
|
|
452
|
+
if (!current()) {
|
|
453
|
+
try { await transport.close(); } catch { /* never attached to a client */ }
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
456
|
s.authProvider = built.authProvider;
|
|
457
457
|
} catch (err) {
|
|
458
|
-
this.markError(s, err);
|
|
458
|
+
if (current()) this.markError(s, err);
|
|
459
459
|
return;
|
|
460
460
|
}
|
|
461
461
|
|
|
@@ -465,15 +465,15 @@ export class MCPManager {
|
|
|
465
465
|
advertiseSampling,
|
|
466
466
|
advertiseRoots,
|
|
467
467
|
onToolsChanged: () => {
|
|
468
|
-
if (
|
|
468
|
+
if (!current()) return;
|
|
469
469
|
void this.refreshTools(s).catch(() => { /* ignore */ });
|
|
470
470
|
},
|
|
471
471
|
onResourcesChanged: () => {
|
|
472
|
-
if (
|
|
472
|
+
if (!current()) return;
|
|
473
473
|
void this.refreshResources(s).catch(() => { /* ignore */ });
|
|
474
474
|
},
|
|
475
475
|
onPromptsChanged: () => {
|
|
476
|
-
if (
|
|
476
|
+
if (!current()) return;
|
|
477
477
|
void this.refreshPrompts(s).catch(() => { /* ignore */ });
|
|
478
478
|
},
|
|
479
479
|
});
|
|
@@ -501,7 +501,7 @@ export class MCPManager {
|
|
|
501
501
|
}
|
|
502
502
|
// notifications/message → log event
|
|
503
503
|
client.setNotificationHandler(LoggingMessageNotificationSchema, async (notif) => {
|
|
504
|
-
if (
|
|
504
|
+
if (!current()) return;
|
|
505
505
|
const p = notif.params;
|
|
506
506
|
this.emit({
|
|
507
507
|
type: "log",
|
|
@@ -515,7 +515,7 @@ export class MCPManager {
|
|
|
515
515
|
// useMCPSubsystem hook). UI integration can be deepened later but the
|
|
516
516
|
// shape is stable enough for status-line widgets to consume.
|
|
517
517
|
client.setNotificationHandler(ProgressNotificationSchema, async (notif) => {
|
|
518
|
-
if (
|
|
518
|
+
if (!current()) return;
|
|
519
519
|
const p = notif.params;
|
|
520
520
|
this.emit({
|
|
521
521
|
type: "log",
|
|
@@ -530,17 +530,25 @@ export class MCPManager {
|
|
|
530
530
|
// from previous generations so a stale onclose can't trigger a reconnect
|
|
531
531
|
// while a fresh connect is already in progress.
|
|
532
532
|
transport.onclose = () => {
|
|
533
|
-
if (
|
|
533
|
+
if (!current()) return;
|
|
534
534
|
if (s.status === "disconnected") return; // intentional stop
|
|
535
535
|
s.lastError = "transport closed";
|
|
536
536
|
this.setStatus(s, "degraded");
|
|
537
537
|
this.scheduleReconnect(s);
|
|
538
538
|
};
|
|
539
539
|
transport.onerror = (err) => {
|
|
540
|
-
if (
|
|
540
|
+
if (!current()) return;
|
|
541
541
|
s.lastError = err instanceof Error ? err.message : String(err);
|
|
542
542
|
};
|
|
543
543
|
|
|
544
|
+
const retire = async () => {
|
|
545
|
+
if (!current()) return undefined;
|
|
546
|
+
const disposal = this.disposeClient(s);
|
|
547
|
+
const retiredGeneration = s.generation;
|
|
548
|
+
await disposal;
|
|
549
|
+
return retiredGeneration;
|
|
550
|
+
};
|
|
551
|
+
|
|
544
552
|
const connectTimeout = s.config.connectTimeoutMs ?? DEFAULTS.connectTimeoutMs;
|
|
545
553
|
try {
|
|
546
554
|
await withTimeout(
|
|
@@ -553,17 +561,21 @@ export class MCPManager {
|
|
|
553
561
|
// We do NOT auto-trigger the browser flow on every connect — that
|
|
554
562
|
// would race on app startup and pop a window without user intent.
|
|
555
563
|
if (err instanceof UnauthorizedError) {
|
|
556
|
-
await
|
|
564
|
+
const retiredGeneration = await retire();
|
|
565
|
+
if (retiredGeneration === undefined || !this.isCurrent(s, retiredGeneration)) return;
|
|
557
566
|
s.lastError = "authorization required";
|
|
558
567
|
this.setStatus(s, "needs_auth");
|
|
559
568
|
return;
|
|
560
569
|
}
|
|
561
|
-
await
|
|
570
|
+
const retiredGeneration = await retire();
|
|
571
|
+
if (retiredGeneration === undefined || !this.isCurrent(s, retiredGeneration)) return;
|
|
562
572
|
this.markError(s, err);
|
|
563
573
|
this.scheduleReconnect(s);
|
|
564
574
|
return;
|
|
565
575
|
}
|
|
566
576
|
|
|
577
|
+
if (!current()) return;
|
|
578
|
+
|
|
567
579
|
// Capture server capabilities for UI display + feature gating.
|
|
568
580
|
const caps = (client.getServerCapabilities?.() ?? {}) as MCPServerCapabilities;
|
|
569
581
|
s.capabilities = caps;
|
|
@@ -576,28 +588,33 @@ export class MCPManager {
|
|
|
576
588
|
try {
|
|
577
589
|
if (caps.tools) await this.refreshTools(s);
|
|
578
590
|
} catch (err) {
|
|
579
|
-
await
|
|
591
|
+
const retiredGeneration = await retire();
|
|
592
|
+
if (retiredGeneration === undefined || !this.isCurrent(s, retiredGeneration)) return;
|
|
580
593
|
this.markError(s, err);
|
|
581
594
|
this.scheduleReconnect(s);
|
|
582
595
|
return;
|
|
583
596
|
}
|
|
597
|
+
if (!current()) return;
|
|
584
598
|
await Promise.allSettled([
|
|
585
599
|
caps.resources ? this.refreshResources(s) : Promise.resolve(),
|
|
586
600
|
caps.prompts ? this.refreshPrompts(s) : Promise.resolve(),
|
|
587
601
|
]);
|
|
588
602
|
|
|
603
|
+
if (!current()) return;
|
|
604
|
+
|
|
589
605
|
// Re-subscribe to anything that was subscribed before the reconnect,
|
|
590
606
|
// and route resources/updated notifications back to event-bus consumers.
|
|
591
607
|
if (caps.resources?.subscribe) {
|
|
592
608
|
client.setNotificationHandler(
|
|
593
609
|
ResourceUpdatedNotificationSchema,
|
|
594
610
|
async (notif) => {
|
|
595
|
-
if (
|
|
611
|
+
if (!current()) return;
|
|
596
612
|
this.emit({ type: "resource_updated", server: s.config.name, uri: notif.params.uri });
|
|
597
613
|
},
|
|
598
614
|
);
|
|
599
615
|
for (const uri of s.subscriptions) {
|
|
600
616
|
try { await client.subscribeResource({ uri }); } catch { /* ignore */ }
|
|
617
|
+
if (!current()) return;
|
|
601
618
|
}
|
|
602
619
|
}
|
|
603
620
|
|
|
@@ -607,13 +624,16 @@ export class MCPManager {
|
|
|
607
624
|
try { await client.setLoggingLevel(s.config.loggingLevel); } catch { /* ignore */ }
|
|
608
625
|
}
|
|
609
626
|
|
|
627
|
+
if (!current()) return;
|
|
610
628
|
s.reconnectAttempts = 0;
|
|
611
629
|
s.connectedAt = new Date().toISOString();
|
|
612
630
|
this.setStatus(s, "ready");
|
|
613
631
|
}
|
|
614
632
|
|
|
615
633
|
private async refreshTools(s: ManagedServer): Promise<void> {
|
|
616
|
-
|
|
634
|
+
const client = s.client;
|
|
635
|
+
const generation = s.generation;
|
|
636
|
+
if (!client || !this.isCurrent(s, generation)) return;
|
|
617
637
|
const collected: MCPListedTool[] = [];
|
|
618
638
|
let cursor: string | undefined;
|
|
619
639
|
// Pagination loop. Most servers return everything in one shot; we still
|
|
@@ -624,10 +644,11 @@ export class MCPManager {
|
|
|
624
644
|
// behaviour of fetchResources / fetchPrompts so the connect path stays
|
|
625
645
|
// symmetric across primitives.
|
|
626
646
|
for (let i = 0; i < 32; i++) {
|
|
627
|
-
let res: Awaited<ReturnType<typeof
|
|
647
|
+
let res: Awaited<ReturnType<typeof client.listTools>>;
|
|
628
648
|
try {
|
|
629
|
-
res = await
|
|
649
|
+
res = await client.listTools(cursor ? { cursor } : undefined);
|
|
630
650
|
} catch (err) {
|
|
651
|
+
if (!this.isCurrent(s, generation)) return;
|
|
631
652
|
const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
|
|
632
653
|
if (msg.includes("-32601") || msg.includes("not found") || msg.includes("not supported")) {
|
|
633
654
|
s.tools = [];
|
|
@@ -636,6 +657,7 @@ export class MCPManager {
|
|
|
636
657
|
}
|
|
637
658
|
throw err;
|
|
638
659
|
}
|
|
660
|
+
if (!this.isCurrent(s, generation)) return;
|
|
639
661
|
for (const t of res.tools ?? []) collected.push(t as MCPListedTool);
|
|
640
662
|
cursor = res.nextCursor;
|
|
641
663
|
if (!cursor) break;
|
|
@@ -645,7 +667,7 @@ export class MCPManager {
|
|
|
645
667
|
for (const t of collected) {
|
|
646
668
|
try {
|
|
647
669
|
bridged.push(bridgeMCPTool(
|
|
648
|
-
|
|
670
|
+
client,
|
|
649
671
|
s.config,
|
|
650
672
|
t,
|
|
651
673
|
{ projectCwd: this.projectCwd },
|
|
@@ -673,23 +695,34 @@ export class MCPManager {
|
|
|
673
695
|
}
|
|
674
696
|
|
|
675
697
|
private async refreshResources(s: ManagedServer): Promise<void> {
|
|
676
|
-
|
|
677
|
-
const
|
|
698
|
+
const client = s.client;
|
|
699
|
+
const generation = s.generation;
|
|
700
|
+
if (!client || !this.isCurrent(s, generation)) return;
|
|
701
|
+
const { resources, templates } = await fetchResources(client, s.config);
|
|
702
|
+
if (!this.isCurrent(s, generation)) return;
|
|
678
703
|
s.resources = resources;
|
|
679
704
|
s.resourceTemplates = templates;
|
|
680
705
|
this.emit({ type: "resources_changed", server: s.config.name });
|
|
681
706
|
}
|
|
682
707
|
|
|
683
708
|
private async refreshPrompts(s: ManagedServer): Promise<void> {
|
|
684
|
-
|
|
685
|
-
|
|
709
|
+
const client = s.client;
|
|
710
|
+
const generation = s.generation;
|
|
711
|
+
if (!client || !this.isCurrent(s, generation)) return;
|
|
712
|
+
const prompts = await fetchPrompts(client, s.config);
|
|
713
|
+
if (!this.isCurrent(s, generation)) return;
|
|
714
|
+
s.prompts = prompts;
|
|
686
715
|
this.emit({ type: "prompts_changed", server: s.config.name });
|
|
687
716
|
}
|
|
688
717
|
|
|
689
718
|
// ── Reconnect / error helpers ──────────────────────────────────────────
|
|
690
719
|
|
|
720
|
+
private isCurrent(s: ManagedServer, generation: number): boolean {
|
|
721
|
+
return this.servers.get(s.config.name) === s && s.generation === generation;
|
|
722
|
+
}
|
|
723
|
+
|
|
691
724
|
private scheduleReconnect(s: ManagedServer): void {
|
|
692
|
-
if (s.status === "disconnected") return;
|
|
725
|
+
if (this.servers.get(s.config.name) !== s || s.status === "disconnected") return;
|
|
693
726
|
if (s.reconnectAttempts >= DEFAULTS.maxReconnectAttempts) {
|
|
694
727
|
this.setStatus(s, "error");
|
|
695
728
|
return;
|
|
@@ -698,8 +731,9 @@ export class MCPManager {
|
|
|
698
731
|
const delay = delays[Math.min(s.reconnectAttempts, delays.length - 1)]!;
|
|
699
732
|
s.reconnectAttempts++;
|
|
700
733
|
if (s.reconnectTimer) clearTimeout(s.reconnectTimer);
|
|
734
|
+
const generation = s.generation;
|
|
701
735
|
s.reconnectTimer = setTimeout(() => {
|
|
702
|
-
if (!this.
|
|
736
|
+
if (!this.isCurrent(s, generation)) return; // stopped or replaced while waiting
|
|
703
737
|
void this.connect(s);
|
|
704
738
|
}, delay);
|
|
705
739
|
}
|
|
@@ -729,14 +763,12 @@ export class MCPManager {
|
|
|
729
763
|
const transport = s.transport;
|
|
730
764
|
s.client = null;
|
|
731
765
|
s.transport = null;
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
// trip the reconnect loop.
|
|
735
|
-
transport.onclose = undefined;
|
|
736
|
-
transport.onerror = undefined;
|
|
737
|
-
}
|
|
766
|
+
// Keep the SDK's transport callbacks intact so close rejects pending
|
|
767
|
+
// requests. Our callbacks already ignore this invalidated generation.
|
|
738
768
|
if (client) {
|
|
739
769
|
try { await client.close(); } catch { /* swallow — server may already be gone */ }
|
|
770
|
+
} else if (transport) {
|
|
771
|
+
try { await transport.close(); } catch { /* half-initialized transport */ }
|
|
740
772
|
}
|
|
741
773
|
}
|
|
742
774
|
|
|
@@ -22,13 +22,15 @@ export function applySkillTemplate(
|
|
|
22
22
|
let body = skill.systemPrompt;
|
|
23
23
|
const provided = new Set(Object.keys(params));
|
|
24
24
|
|
|
25
|
+
// Callback replacements keep literal dollar tokens out of replacement-string syntax.
|
|
25
26
|
for (const [k, v] of Object.entries(params)) {
|
|
26
|
-
body = body.replaceAll(`{{${k}}}`, v);
|
|
27
|
+
body = body.replaceAll(`{{${k}}}`, () => v);
|
|
27
28
|
}
|
|
28
29
|
|
|
29
30
|
for (const p of skill.parameters ?? []) {
|
|
30
|
-
|
|
31
|
-
|
|
31
|
+
const defaultValue = p.default;
|
|
32
|
+
if (!provided.has(p.name) && defaultValue !== undefined) {
|
|
33
|
+
body = body.replaceAll(`{{${p.name}}}`, () => defaultValue);
|
|
32
34
|
}
|
|
33
35
|
}
|
|
34
36
|
|