zapagent 1.14.19 → 1.14.21
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 -1
- package/README.zh-CN.md +2 -2
- package/package.json +1 -1
- package/src/App.tsx +4 -1
- package/src/agent-factory.ts +6 -1
- package/src/cli-routing.ts +0 -14
- package/src/codex-auth-command.ts +44 -0
- package/src/codex-auth.ts +233 -0
- package/src/codex-provider.ts +37 -0
- package/src/commands/dispatcher.ts +7 -2
- package/src/config.ts +5 -3
- 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 +9 -17
- package/src/provider-catalog.ts +11 -0
- package/src/session.ts +8 -3
- package/src/ui/dialog-codex-login.tsx +44 -0
- package/src/ui/dialog-connect.tsx +12 -3
- package/src/ui/provider-directory.tsx +4 -2
- 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/core/providers/openai-responses.ts +64 -6
- package/zapsdk/debug/agent-logger.ts +4 -1
- package/zapsdk/mcp/manager.ts +75 -43
- package/zapsdk/skills/template.ts +5 -3
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)
|
|
@@ -26,6 +26,9 @@ Options:
|
|
|
26
26
|
--watch-no-open Print the Watch URL without opening a browser
|
|
27
27
|
--watch-linger <s> Keep the headless viewer available after a run (0..300)
|
|
28
28
|
--help-headless Show non-interactive (headless) mode flags
|
|
29
|
+
auth login codex Sign in to Codex with ChatGPT (--device-code for SSH)
|
|
30
|
+
auth logout codex Remove Zap's Codex credentials
|
|
31
|
+
auth status codex Show Zap's Codex login status
|
|
29
32
|
update [--yes] Check, confirm and install the latest version
|
|
30
33
|
acp Serve Agent Client Protocol v1 over stdio (no TUI)
|
|
31
34
|
workflow Inspect, wait for or cancel a persisted workflow (--db required)
|
|
@@ -62,6 +65,11 @@ if (args.includes("--version") || args.includes("-v")) {
|
|
|
62
65
|
process.exit(0)
|
|
63
66
|
}
|
|
64
67
|
|
|
68
|
+
if (args[0] === "auth") {
|
|
69
|
+
const { runCodexAuthCommand } = await import("./codex-auth-command.js")
|
|
70
|
+
process.exit(await runCodexAuthCommand(args.slice(1)))
|
|
71
|
+
}
|
|
72
|
+
|
|
65
73
|
if (args[0] === "update") {
|
|
66
74
|
const { runUpdateCommand } = await import("./update-cli.js")
|
|
67
75
|
process.exit(await runUpdateCommand(args.slice(1)))
|
|
@@ -168,22 +176,6 @@ if (devPort) {
|
|
|
168
176
|
// Ink graph below — no TTY ops, no stdin patch, no devtools (unless user
|
|
169
177
|
// explicitly set ZAPCODE_DEVTOOLS_PORT before invocation).
|
|
170
178
|
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
179
|
const { runHeadlessFromArgv } = await import("./headless/run.js")
|
|
188
180
|
const code = await runHeadlessFromArgv(args, watchOptions)
|
|
189
181
|
process.exit(code)
|
package/src/provider-catalog.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { listModels } from "../zapsdk/core/list-models.js"
|
|
|
2
2
|
import { getModelsDevProvider, suggestedModelsDevIds, type ModelsDevProvider } from "../zapsdk/core/models-dev.js"
|
|
3
3
|
import { resolveCatalogProviderId, upsertProvider, setActive, type AppConfig, type Provider, type ProviderModelMetadata } from "./config.js"
|
|
4
4
|
import { enrichProviderMetadata, mergeModelMetadata, modelsDevMetadata, pickModelMetadata } from "./provider-metadata.js"
|
|
5
|
+
import { discoverCodexModels } from "./codex-provider.js"
|
|
5
6
|
|
|
6
7
|
export type ModelSource = "saved" | "provider" | "models.dev" | "manual"
|
|
7
8
|
export interface CatalogRow { id: string; source: ModelSource; metadata?: ProviderModelMetadata }
|
|
@@ -27,6 +28,16 @@ export function associateModelMetadata(config: AppConfig, providerId: string, mo
|
|
|
27
28
|
|
|
28
29
|
/** Discovery is read-only: returning a model is not proof of inference access. */
|
|
29
30
|
export async function discoverProviderModels(provider: Provider, signal: AbortSignal): Promise<DiscoveredCatalog> {
|
|
31
|
+
if (provider.authMode === "codex-oauth") {
|
|
32
|
+
const rows = new Map<string, CatalogRow>(provider.models.map(id => [id, { id, source: "saved", metadata: provider.modelMetadata?.[id] }]))
|
|
33
|
+
try {
|
|
34
|
+
for (const row of await discoverCodexModels(signal)) rows.set(row.id, { ...row, source: "provider" })
|
|
35
|
+
return { rows: [...rows.values()] }
|
|
36
|
+
} catch (error) {
|
|
37
|
+
signal.throwIfAborted()
|
|
38
|
+
return { rows: [...rows.values()], error: error instanceof Error ? error.message : "Codex model discovery failed. Sign in again with /connect." }
|
|
39
|
+
}
|
|
40
|
+
}
|
|
30
41
|
const catalogId = resolveCatalogProviderId(provider)
|
|
31
42
|
const [live, catalog] = await Promise.allSettled([
|
|
32
43
|
listModels(provider.baseURL, provider.authMode === "none" ? "" : provider.apiKey, 6000, signal, provider.protocol),
|
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
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/** @jsxImportSource react */
|
|
2
|
+
import { useEffect, useRef, useState } from "react"
|
|
3
|
+
import { Text, useInput } from "ink"
|
|
4
|
+
import { openAuthBrowser, saveCodexCredentials, startCodexBrowserLogin, startCodexDeviceLogin } from "../codex-auth.js"
|
|
5
|
+
import { DialogFrame } from "./dialog-frame.js"
|
|
6
|
+
import { PickerDialog } from "./dialog-picker.js"
|
|
7
|
+
import { c } from "./theme.js"
|
|
8
|
+
|
|
9
|
+
export function CodexLoginDialog({ onSuccess, onCancel }: { onSuccess: () => void; onCancel: () => void }) {
|
|
10
|
+
const [method, setMethod] = useState<"browser" | "device" | null>(null)
|
|
11
|
+
const [details, setDetails] = useState<{ url: string; instructions: string } | null>(null)
|
|
12
|
+
const [error, setError] = useState("")
|
|
13
|
+
const callbacks = useRef({ onSuccess, onCancel })
|
|
14
|
+
callbacks.current = { onSuccess, onCancel }
|
|
15
|
+
useInput((_input, key) => { if (method && key.escape) setMethod(null) })
|
|
16
|
+
useEffect(() => {
|
|
17
|
+
if (!method) return
|
|
18
|
+
const controller = new AbortController()
|
|
19
|
+
setDetails(null); setError("")
|
|
20
|
+
void (async () => {
|
|
21
|
+
const login = method === "browser" ? await startCodexBrowserLogin({ signal: controller.signal }) : await startCodexDeviceLogin(controller.signal)
|
|
22
|
+
if (controller.signal.aborted) { login.cancel(); return }
|
|
23
|
+
setDetails({ url: login.url, instructions: login.instructions })
|
|
24
|
+
openAuthBrowser(login.url)
|
|
25
|
+
const credentials = await login.complete
|
|
26
|
+
if (controller.signal.aborted) return
|
|
27
|
+
await saveCodexCredentials(credentials, undefined, controller.signal)
|
|
28
|
+
if (controller.signal.aborted) return
|
|
29
|
+
callbacks.current.onSuccess()
|
|
30
|
+
})().catch(error => { if (!controller.signal.aborted) setError(error instanceof Error ? error.message : "Codex login failed.") })
|
|
31
|
+
return () => controller.abort()
|
|
32
|
+
}, [method])
|
|
33
|
+
if (!method) return <PickerDialog title="OpenAI Codex · sign in with ChatGPT"
|
|
34
|
+
options={[{ id: "browser", label: "Browser login", meta: "opens ChatGPT sign-in · local callback on port 1455" },
|
|
35
|
+
{ id: "device", label: "Device code", meta: "for SSH, headless hosts, or a busy callback port" }]}
|
|
36
|
+
onCancel={onCancel} onSelect={id => setMethod(id as "browser" | "device")} />
|
|
37
|
+
return <DialogFrame title="OpenAI Codex · sign in with ChatGPT" hint="esc back / cancel login">
|
|
38
|
+
{error ? <Text color={c.warning}>{error}</Text> : <>
|
|
39
|
+
<Text>{details?.instructions ?? "Starting Codex login…"}</Text>
|
|
40
|
+
{details && <Text color={c.accent}>{details.url}</Text>}
|
|
41
|
+
<Text color={c.text.faint}>If the browser did not open, open this URL manually. Waiting for authorization…</Text>
|
|
42
|
+
</>}
|
|
43
|
+
</DialogFrame>
|
|
44
|
+
}
|
|
@@ -12,12 +12,14 @@ import { commandInput, isReturnInput } from "./controlled-input.js"
|
|
|
12
12
|
import { c } from "./theme.js"
|
|
13
13
|
import { ModelDialog } from "./dialog-model.js"
|
|
14
14
|
import { ContextWindowDialog } from "./dialog-context-window.js"
|
|
15
|
+
import { CodexLoginDialog } from "./dialog-codex-login.js"
|
|
16
|
+
import { connectCodexProvider } from "../codex-provider.js"
|
|
15
17
|
|
|
16
18
|
interface Props { config: AppConfig; onSave: (next: AppConfig) => void; onCommit: (next: AppConfig) => void; onCancel: () => void }
|
|
17
19
|
type Draft = { name: string; baseURL: string; apiKey: string; protocol: ProviderProtocol;
|
|
18
20
|
authMode: "none" | "api-key"; catalogProviderId?: string; existing?: Provider;
|
|
19
21
|
contextWindow?: number; contextWindowMode?: ContextWindowMode }
|
|
20
|
-
type Step = "connections" | "preset" | "name" | "endpoint" | "protocol" | "auth" | "key" | "context" | "review"
|
|
22
|
+
type Step = "connections" | "preset" | "name" | "endpoint" | "protocol" | "auth" | "key" | "context" | "review" | "codex"
|
|
21
23
|
|
|
22
24
|
export function saveConnection(config: AppConfig, draft: Draft): AppConfig {
|
|
23
25
|
const existing = draft.existing
|
|
@@ -73,6 +75,7 @@ export function ConnectDialog({ config, onSave, onCommit, onCancel }: Props) {
|
|
|
73
75
|
if (cmd === "d" && provider) { setDeleting(true); return }
|
|
74
76
|
if (isReturnInput(input, key) || cmd === "e") {
|
|
75
77
|
if (!provider) { setStep("preset"); return }
|
|
78
|
+
if (provider.authMode === "codex-oauth") { setStep("codex"); return }
|
|
76
79
|
setDraft({ existing: provider, name: provider.name, baseURL: provider.baseURL,
|
|
77
80
|
apiKey: provider.apiKey, protocol: provider.protocol ?? "openai",
|
|
78
81
|
authMode: provider.authMode ?? (provider.apiKey ? "api-key" : "none"), catalogProviderId: provider.catalogProviderId })
|
|
@@ -90,7 +93,7 @@ export function ConnectDialog({ config, onSave, onCommit, onCancel }: Props) {
|
|
|
90
93
|
<Box flexDirection="column" marginTop={1}>
|
|
91
94
|
{config.providers.map((provider, i) => <Box key={provider.id} flexDirection="column">
|
|
92
95
|
<Text color={i === index ? c.accent : c.text.primary}>{`${i === index ? "›" : " "} ${provider.name || "Unnamed connection"}`}</Text>
|
|
93
|
-
<Text color={c.text.faint}>{` ${provider.protocol ?? "openai"} · ${provider.apiKey ? "API key stored" : "no key"} · ${provider.models.length} saved models`}</Text>
|
|
96
|
+
<Text color={c.text.faint}>{` ${provider.authMode === "codex-oauth" ? "Codex Responses · ChatGPT OAuth" : `${provider.protocol ?? "openai"} · ${provider.apiKey ? "API key stored" : "no key"}`} · ${provider.models.length} saved models`}</Text>
|
|
94
97
|
<Text color={c.text.faint}>{` ${provider.baseURL}`}</Text>
|
|
95
98
|
</Box>)}
|
|
96
99
|
<Text color={index === config.providers.length ? c.accent : c.text.primary}>{`${index === config.providers.length ? "›" : " "} + New connection`}</Text>
|
|
@@ -98,7 +101,13 @@ export function ConnectDialog({ config, onSave, onCommit, onCancel }: Props) {
|
|
|
98
101
|
{deleting && <Text color={c.warning}>Remove connection and its saved model preferences?</Text>}
|
|
99
102
|
</DialogFrame>
|
|
100
103
|
|
|
101
|
-
if (step === "
|
|
104
|
+
if (step === "codex") return <CodexLoginDialog onCancel={() => setStep("connections")} onSuccess={() => {
|
|
105
|
+
const result = connectCodexProvider(live.current.config)
|
|
106
|
+
onSave(result.config)
|
|
107
|
+
setModelTarget({ id: result.provider.id, setup: true })
|
|
108
|
+
}} />
|
|
109
|
+
|
|
110
|
+
if (step === "preset") return <ProviderDirectory onCodex={() => setStep("codex")}
|
|
102
111
|
onCancel={() => setStep("connections")} onSelect={provider => {
|
|
103
112
|
setDraft({ catalogProviderId: provider?.id, name: provider?.name ?? "", baseURL: provider?.api ?? "", apiKey: "",
|
|
104
113
|
protocol: provider?.protocol ?? "openai", authMode: "api-key" })
|
|
@@ -10,11 +10,11 @@ import { useTermWidth } from "./term-width.js"
|
|
|
10
10
|
import { truncateToWidth } from "./truncate.js"
|
|
11
11
|
import { c } from "./theme.js"
|
|
12
12
|
|
|
13
|
-
interface Props { onSelect: (provider: ModelsDevConnection | null) => void; onCancel: () => void; metadataOnly?: boolean }
|
|
13
|
+
interface Props { onSelect: (provider: ModelsDevConnection | null) => void; onCancel: () => void; metadataOnly?: boolean; onCodex?: () => void }
|
|
14
14
|
|
|
15
15
|
/** Public directory data supplies vendor names and endpoints; adapters only
|
|
16
16
|
* constrain which wire protocols the installed runtime actually supports. */
|
|
17
|
-
export function ProviderDirectory({ onSelect, onCancel, metadataOnly = false }: Props) {
|
|
17
|
+
export function ProviderDirectory({ onSelect, onCancel, metadataOnly = false, onCodex }: Props) {
|
|
18
18
|
const [providers, setProviders] = useState<ModelsDevConnection[]>([])
|
|
19
19
|
const [loading, setLoading] = useState(true)
|
|
20
20
|
const [error, setError] = useState("")
|
|
@@ -60,11 +60,13 @@ export function ProviderDirectory({ onSelect, onCancel, metadataOnly = false }:
|
|
|
60
60
|
maxRows={Math.max(3, Math.min(10, (process.stdout.rows ?? 24) - 15))}
|
|
61
61
|
hint="↑↓ select · enter configure · / search · r reload · esc back"
|
|
62
62
|
options={[...(!metadataOnly ? [{ id: "__custom", label: "Custom endpoint", meta: "configure manually" }] : []),
|
|
63
|
+
...(!metadataOnly && onCodex ? [{ id: "__codex", label: "OpenAI Codex (ChatGPT)", meta: "OAuth · sign in with ChatGPT" }] : []),
|
|
63
64
|
...visible.map(provider => ({ id: `catalog:${provider.id}`, label: truncateToWidth(provider.name, labelWidth),
|
|
64
65
|
meta: truncateToWidth(provider.protocol ? `${provider.protocol}${provider.api ? " · endpoint provided" : " · enter endpoint"}` : "unsupported adapter", width - labelWidth - 2),
|
|
65
66
|
disabled: !metadataOnly && !provider.protocol }))]}
|
|
66
67
|
onCancel={onCancel} onSelect={id => {
|
|
67
68
|
if (id === "__custom") onSelect(null)
|
|
69
|
+
else if (id === "__codex") onCodex?.()
|
|
68
70
|
else {
|
|
69
71
|
const provider = providers.find(item => item.id === id.slice("catalog:".length))
|
|
70
72
|
if (provider && (metadataOnly || provider.protocol)) onSelect(provider)
|
|
@@ -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);
|