zapagent 1.14.7 → 1.14.9

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 CHANGED
@@ -72,6 +72,10 @@ On first use, enter `/connect` and follow the setup prompts to connect your mode
72
72
 
73
73
  You need your own model service account and API key; usage is billed by your provider. [Connection guide](docs/usage.md#getting-started).
74
74
 
75
+ Update from your terminal with `zap update` (or `zap update --yes` for unattended installation).
76
+
77
+ The interactive CLI checks for updates in the background without delaying startup. When an update is available, run `/update` and press `y` to download, verify, install and restart with your saved session. Automatic installation supports global npm installs and standalone macOS/Linux binaries; other installations show instructions for their package manager. Set `ZAP_DISABLE_UPDATE_CHECK=1` to disable checks. CI and non-interactive modes do not check.
78
+
75
79
  <details>
76
80
  <summary>Other installation options and advanced setup: Bun, binaries, source, API protocols</summary>
77
81
 
package/README.zh-CN.md CHANGED
@@ -72,6 +72,10 @@ zap --watch
72
72
 
73
73
  需要你自己的模型服务账号和 API Key,调用费用由模型服务商收取。[连接指南](docs/usage.md#getting-started)。
74
74
 
75
+ 在终端执行 `zap update` 检查并确认更新;脚本中可用 `zap update --yes` 跳过交互确认。
76
+
77
+ 启动后会在后台检查新版本,不阻塞使用。发现新版时输入 `/update`,按 `y` 确认后才下载、校验、安装并重启,恢复已保存的会话。支持 npm 全局安装和 macOS/Linux 独立程序;其他安装方式按提示使用原包管理器更新。设置 `ZAP_DISABLE_UPDATE_CHECK=1` 可关闭后台检查,CI 和非交互模式不检查。
78
+
75
79
  <details>
76
80
  <summary>其他安装方式与高级配置:Bun、二进制、源码、API 协议</summary>
77
81
 
package/npm/cli.cjs CHANGED
@@ -4,7 +4,7 @@ const { constants } = require("node:os");
4
4
  const { ensureBinary } = require("./install.cjs");
5
5
  (async () => {
6
6
  const binary = await ensureBinary();
7
- const child = spawn(binary, process.argv.slice(2), { stdio: "inherit", env: process.env });
7
+ const child = spawn(binary, process.argv.slice(2), { stdio: "inherit", env: { ...process.env, ZAPAGENT_NPM_LAUNCHER: __filename, ZAPAGENT_NPM_RUNTIME: process.execPath } });
8
8
  const forward = signal => { if (!child.killed) child.kill(signal); };
9
9
  const handlers = Object.fromEntries(["SIGINT", "SIGTERM", "SIGHUP"].map(signal => [signal, () => forward(signal)]));
10
10
  for (const [signal, handler] of Object.entries(handlers)) process.on(signal, handler);
@@ -0,0 +1,8 @@
1
+ export interface BinaryOptions {
2
+ version?: string
3
+ platform?: string
4
+ arch?: string
5
+ env?: Record<string, string | undefined>
6
+ fetch?: typeof fetch
7
+ }
8
+ export function ensureBinary(options?: BinaryOptions): Promise<string>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zapagent",
3
- "version": "1.14.7",
3
+ "version": "1.14.9",
4
4
  "packageManager": "bun@1.3.14",
5
5
  "author": "",
6
6
  "main": "src/index.tsx",
package/src/App.tsx CHANGED
@@ -1,4 +1,7 @@
1
1
  /** @jsxImportSource react */
2
+ import { restoreAfterUpdate } from "./update-lifecycle.js"
3
+ import { UpdateDialog } from "./ui/dialog-update.js"
4
+ import { requestUpdateRestart } from "./self-update.js"
2
5
  // Ink-based App, orchestrator only — every non-trivial subsystem lives in
3
6
  // src/hooks/* or src/commands/*. The monolithic ~2200-line predecessor was
4
7
  // broken up in the App→hooks refactor (commit 30f1544).
@@ -33,6 +36,8 @@ import { cwdShort, configPath, getCurrentSessionId, getSessionPersistenceStatus,
33
36
  import { useLogs } from "./hooks/useLogs.js"
34
37
  import { useAgentRunner } from "./hooks/useAgentRunner.js"
35
38
  import { useToasts } from "./hooks/useToasts.js"
39
+ import { useUpdateCheck } from "./hooks/useUpdateCheck.js"
40
+ import { UpdateNotice } from "./ui/UpdateNotice.js"
36
41
  import { autoMemory, appLogger, agentLogger, conversation, tokenAccounting } from "./singletons.js"
37
42
  import { CheckpointManager } from "../zapsdk/checkpoint/index.js"
38
43
  import { type Todo, type TodoStore } from "../zapsdk/index.js"
@@ -112,7 +117,7 @@ import { ConnectDialog } from "./ui/dialog-connect.js"
112
117
  import { ModeDialog, EffortDialog } from "./ui/dialog-config.js"
113
118
  import { ModelDialog } from "./ui/dialog-model.js"
114
119
  import { StatusDialog } from "./ui/dialog-status.js"
115
- import { commitSessionForDialog, replaceConversationMessages, SessionsDialog } from "./ui/dialog-sessions.js"
120
+ import { loadSessionForDialog, type DialogSessionRestore, commitSessionForDialog, replaceConversationMessages, SessionsDialog } from "./ui/dialog-sessions.js"
116
121
  import { MemDialog } from "./ui/dialog-mem.js"
117
122
  import { PermissionsDialog } from "./ui/dialog-permissions.js"
118
123
  import { RewindDialog, rewindDraft } from "./ui/dialog-rewind.js"
@@ -346,7 +351,7 @@ export function App() {
346
351
  // Only one modal can be open at a time; the prompt is hidden behind it
347
352
  // (Ink keyboard input routes to the dialog because it mounts a useInput
348
353
  // hook of its own).
349
- const [dialog, setDialog] = useState<DialogId>(null)
354
+ const [dialog, setDialog] = useState<DialogId>(() => process.env.ZAPAGENT_RESTORE_SESSION ? "restoring" : null)
350
355
  // ZAPCODE_DIAG=1: log dialog open/close transitions so latest.log shows
351
356
  // exactly when /model entered + how long before the user dismissed.
352
357
  useEffect(() => {
@@ -441,6 +446,7 @@ export function App() {
441
446
 
442
447
  // ── Toasts ──
443
448
  const { toasts, addToast } = useToasts()
449
+ const availableUpdate = useUpdateCheck()
444
450
 
445
451
  // ── Pending images attached to next user turn ──
446
452
  const [pendingImages, setPendingImages] = useState<import("./queue/inputQueue.js").PendingImage[]>([])
@@ -798,7 +804,7 @@ export function App() {
798
804
  // Pending delivery is busy for UI/controls, but must not block the
799
805
  // dispatcher effect that starts that very delivery.
800
806
  isRunning: isAgentRunning,
801
- paused: dialog === "rewind",
807
+ paused: dialog === "rewind" || dialog === "update" || dialog === "restoring",
802
808
  inputQueue,
803
809
  systemInboxSize,
804
810
  followUpMode: config.followUpMode ?? "queue",
@@ -944,6 +950,117 @@ export function App() {
944
950
  // surrounding context must stay visible.
945
951
  const inModal = dialog !== null && process.env.ZAPCODE_MODAL_TAKEOVER === "1"
946
952
 
953
+ const restoreSession = (loaded: DialogSessionRestore) => {
954
+ const { logs: restored, messages, loadedSessionId, metadata } = loaded
955
+ appLogger.info("session_restore_begin", {
956
+ sessionId: loadedSessionId,
957
+ restoredLogs: restored.length,
958
+ messagesToAdd: messages.length,
959
+ })
960
+ // All fallible file reads and transcript conversion completed in
961
+ // the dialog's prepare phase. Commit conversation + durable writer
962
+ // together; a writer failure restores the previous conversation.
963
+ const restoredActiveSessionId = commitSessionForDialog(loaded, conversation)
964
+ restoreQueueDraft()
965
+ bindQueue(loadedSessionId)
966
+ // Recalibrate the current next-prompt estimate from the LAST API
967
+ // truth persisted with this session. Recovering provider overhead
968
+ // via `total - localEstimateAtTime` avoids a fresh process showing
969
+ // a number 10-30k below what the API would receive next.
970
+ const persistedHistory = metadata.usages
971
+ const persisted = persistedHistory.at(-1) ?? null
972
+ const activeCacheScope = makePromptCacheScope(
973
+ config.active.providerId,
974
+ config.active.model,
975
+ )
976
+ const persistedMatchesActiveModel = !!persisted && (
977
+ !persisted.cacheScope || samePromptCacheScope(persisted.cacheScope, activeCacheScope)
978
+ )
979
+ if (persisted && persistedMatchesActiveModel) {
980
+ const restoredUsage = resolveRestoredUsageContext(
981
+ persisted,
982
+ conversation.estimatedTokens,
983
+ tokenAccounting.promptOverhead,
984
+ )
985
+ tokenAccounting.promptOverhead = restoredUsage.promptOverhead
986
+ setContextTokens(
987
+ restoredUsage.contextTokens,
988
+ "restored",
989
+ persisted.total > 0 ? persisted.total : null,
990
+ )
991
+ resetRunDiagnostics(
992
+ persistedUsageToRunnerUsage(persisted),
993
+ persisted.contextDiagnostics,
994
+ persistedHistory.map(persistedUsageToRunnerUsage),
995
+ persistedHistory.flatMap((usage) => usage.contextDiagnostics ? [usage.contextDiagnostics] : []),
996
+ persisted.promptCacheDiagnostics,
997
+ )
998
+ } else {
999
+ const restoredUsage = resolveUnmeasuredUsageContext(conversation.estimatedTokens)
1000
+ tokenAccounting.promptOverhead = restoredUsage.promptOverhead
1001
+ setContextTokens(restoredUsage.contextTokens, "pending", null)
1002
+ if (persisted) {
1003
+ resetRunDiagnostics(
1004
+ persistedUsageToRunnerUsage(persisted),
1005
+ persisted.contextDiagnostics,
1006
+ persistedHistory.map(persistedUsageToRunnerUsage),
1007
+ persistedHistory.flatMap((usage) => usage.contextDiagnostics ? [usage.contextDiagnostics] : []),
1008
+ persisted.promptCacheDiagnostics,
1009
+ )
1010
+ } else {
1011
+ resetRunDiagnostics()
1012
+ }
1013
+ }
1014
+ setLogs(restored)
1015
+ restoreMemoryQueryHistoryFromLogs(restored)
1016
+ appLogger.info("session_restore_state_set", {
1017
+ convEstimatedTokens: conversation.estimatedTokens,
1018
+ convMessageCount: conversation.getMessages().length,
1019
+ persistedUsage: persisted,
1020
+ promptOverhead: tokenAccounting.promptOverhead,
1021
+ firstMsgRole: messages[0]?.role,
1022
+ firstMsgPreview: messages[0]?.content?.slice(0, 60),
1023
+ lastMsgRole: messages[messages.length - 1]?.role,
1024
+ lastMsgPreview: messages[messages.length - 1]?.content?.slice(0, 60),
1025
+ })
1026
+ // Rebind checkpoint to the durable fork and hydrate from the same
1027
+ // validated source bundle that was copied into the fork.
1028
+ try {
1029
+ checkpoint.setSessionId(restoredActiveSessionId)
1030
+ checkpoint.hydrateFromJsonl(metadata.checkpointJournal, { remapToCurrentSession: true })
1031
+ } catch (err) {
1032
+ addLog("error", `checkpoint hydrate failed: ${err instanceof Error ? err.message : String(err)}`)
1033
+ }
1034
+ // `parseTodoUpdates` is tail-wins per key. The exact validated map
1035
+ // was also persisted into the durable fork during commit.
1036
+ try {
1037
+ const todoMap = metadata.todos
1038
+ const main = todoMap.get("main") as Todo[] | undefined
1039
+ todosRef.current = main ?? []
1040
+ setTodos(main ?? [])
1041
+ subagentTodosRef.current.clear()
1042
+ for (const [key, list] of todoMap) {
1043
+ if (key === "main") continue
1044
+ subagentTodosRef.current.set(key, list as Todo[])
1045
+ }
1046
+ } catch (err) {
1047
+ addLog("error", `todo restore failed: ${err instanceof Error ? err.message : String(err)}`)
1048
+ }
1049
+ bumpTranscript()
1050
+ appLogger.info("session_restore_end", { sessionId: loadedSessionId })
1051
+ closeDialog()
1052
+
1053
+ }
1054
+ useEffect(() => {
1055
+ const id = process.env.ZAPAGENT_RESTORE_SESSION
1056
+ delete process.env.ZAPAGENT_RESTORE_SESSION
1057
+ if (id) void restoreAfterUpdate({
1058
+ load: () => loadSessionForDialog(id), commit: restoreSession,
1059
+ failed: () => addToast("Could not restore the previous session. Open /sessions to recover it.", { variant: "error" }),
1060
+ finished: () => setDialog(null),
1061
+ })
1062
+ }, [])
1063
+
947
1064
  return (
948
1065
  <TermWidthContext.Provider value={termWidth}>
949
1066
  <ConversationSurface>
@@ -976,6 +1093,7 @@ export function App() {
976
1093
  />
977
1094
 
978
1095
  <ToastContainer toasts={toasts} />
1096
+ <UpdateNotice version={availableUpdate} />
979
1097
 
980
1098
  <TokenWarning contextBudget={contextBudget} />
981
1099
 
@@ -1049,6 +1167,12 @@ export function App() {
1049
1167
  * FilePalette already work). Prompt above stays visible but
1050
1168
  * defocused while the dialog owns the keyboard (see focused= prop
1051
1169
  * above). */}
1170
+ {dialog === "restoring" && <Text>Restoring saved session…</Text>}
1171
+ {dialog === "update" && <UpdateDialog version={availableUpdate} busy={isRunning} sessionId={getCurrentSessionId()} beforeInstall={() => {
1172
+ readCurrentSessionLogs()
1173
+ const persistence = getSessionPersistenceStatus()
1174
+ if (persistence.pendingWrites || persistence.lastFailure) throw new Error("Save the current session successfully before updating.")
1175
+ }} onCancel={closeDialog} onRestart={request => { readCurrentSessionLogs(); requestUpdateRestart(request); exit() }} />}
1052
1176
  {dialog === "connect" && <ConnectDialog config={config} onSave={updateConfig} onCommit={commitConfig} onCancel={closeDialog} />}
1053
1177
  {dialog === "model" && <ModelDialog config={config} onCommit={commitConfig} onCancel={closeDialog} />}
1054
1178
  {dialog === "mode" && <ModeDialog config={config} onCommit={commitConfig} onCancel={closeDialog} />}
@@ -1080,106 +1204,7 @@ export function App() {
1080
1204
  )}
1081
1205
  {dialog === "sessions" && (
1082
1206
  <SessionsDialog
1083
- onLoad={(loaded) => {
1084
- const { logs: restored, messages, loadedSessionId, metadata } = loaded
1085
- appLogger.info("session_restore_begin", {
1086
- sessionId: loadedSessionId,
1087
- restoredLogs: restored.length,
1088
- messagesToAdd: messages.length,
1089
- })
1090
- // All fallible file reads and transcript conversion completed in
1091
- // the dialog's prepare phase. Commit conversation + durable writer
1092
- // together; a writer failure restores the previous conversation.
1093
- const restoredActiveSessionId = commitSessionForDialog(loaded, conversation)
1094
- restoreQueueDraft()
1095
- bindQueue(loadedSessionId)
1096
- // Recalibrate the current next-prompt estimate from the LAST API
1097
- // truth persisted with this session. Recovering provider overhead
1098
- // via `total - localEstimateAtTime` avoids a fresh process showing
1099
- // a number 10-30k below what the API would receive next.
1100
- const persistedHistory = metadata.usages
1101
- const persisted = persistedHistory.at(-1) ?? null
1102
- const activeCacheScope = makePromptCacheScope(
1103
- config.active.providerId,
1104
- config.active.model,
1105
- )
1106
- const persistedMatchesActiveModel = !!persisted && (
1107
- !persisted.cacheScope || samePromptCacheScope(persisted.cacheScope, activeCacheScope)
1108
- )
1109
- if (persisted && persistedMatchesActiveModel) {
1110
- const restoredUsage = resolveRestoredUsageContext(
1111
- persisted,
1112
- conversation.estimatedTokens,
1113
- tokenAccounting.promptOverhead,
1114
- )
1115
- tokenAccounting.promptOverhead = restoredUsage.promptOverhead
1116
- setContextTokens(
1117
- restoredUsage.contextTokens,
1118
- "restored",
1119
- persisted.total > 0 ? persisted.total : null,
1120
- )
1121
- resetRunDiagnostics(
1122
- persistedUsageToRunnerUsage(persisted),
1123
- persisted.contextDiagnostics,
1124
- persistedHistory.map(persistedUsageToRunnerUsage),
1125
- persistedHistory.flatMap((usage) => usage.contextDiagnostics ? [usage.contextDiagnostics] : []),
1126
- persisted.promptCacheDiagnostics,
1127
- )
1128
- } else {
1129
- const restoredUsage = resolveUnmeasuredUsageContext(conversation.estimatedTokens)
1130
- tokenAccounting.promptOverhead = restoredUsage.promptOverhead
1131
- setContextTokens(restoredUsage.contextTokens, "pending", null)
1132
- if (persisted) {
1133
- resetRunDiagnostics(
1134
- persistedUsageToRunnerUsage(persisted),
1135
- persisted.contextDiagnostics,
1136
- persistedHistory.map(persistedUsageToRunnerUsage),
1137
- persistedHistory.flatMap((usage) => usage.contextDiagnostics ? [usage.contextDiagnostics] : []),
1138
- persisted.promptCacheDiagnostics,
1139
- )
1140
- } else {
1141
- resetRunDiagnostics()
1142
- }
1143
- }
1144
- setLogs(restored)
1145
- restoreMemoryQueryHistoryFromLogs(restored)
1146
- appLogger.info("session_restore_state_set", {
1147
- convEstimatedTokens: conversation.estimatedTokens,
1148
- convMessageCount: conversation.getMessages().length,
1149
- persistedUsage: persisted,
1150
- promptOverhead: tokenAccounting.promptOverhead,
1151
- firstMsgRole: messages[0]?.role,
1152
- firstMsgPreview: messages[0]?.content?.slice(0, 60),
1153
- lastMsgRole: messages[messages.length - 1]?.role,
1154
- lastMsgPreview: messages[messages.length - 1]?.content?.slice(0, 60),
1155
- })
1156
- // Rebind checkpoint to the durable fork and hydrate from the same
1157
- // validated source bundle that was copied into the fork.
1158
- try {
1159
- checkpoint.setSessionId(restoredActiveSessionId)
1160
- checkpoint.hydrateFromJsonl(metadata.checkpointJournal, { remapToCurrentSession: true })
1161
- } catch (err) {
1162
- addLog("error", `checkpoint hydrate failed: ${err instanceof Error ? err.message : String(err)}`)
1163
- }
1164
- // `parseTodoUpdates` is tail-wins per key. The exact validated map
1165
- // was also persisted into the durable fork during commit.
1166
- try {
1167
- const todoMap = metadata.todos
1168
- const main = todoMap.get("main") as Todo[] | undefined
1169
- todosRef.current = main ?? []
1170
- setTodos(main ?? [])
1171
- subagentTodosRef.current.clear()
1172
- for (const [key, list] of todoMap) {
1173
- if (key === "main") continue
1174
- subagentTodosRef.current.set(key, list as Todo[])
1175
- }
1176
- } catch (err) {
1177
- addLog("error", `todo restore failed: ${err instanceof Error ? err.message : String(err)}`)
1178
- }
1179
- bumpTranscript()
1180
- appLogger.info("session_restore_end", { sessionId: loadedSessionId })
1181
- closeDialog()
1182
- }}
1207
+ onLoad={restoreSession}
1183
1208
  onCancel={closeDialog}
1184
1209
  />
1185
1210
  )}
@@ -80,6 +80,8 @@ type RestorableUserEntry = {
80
80
  }
81
81
 
82
82
  export type DialogId =
83
+ | "restoring"
84
+ | "update"
83
85
  | "connect"
84
86
  | "model"
85
87
  | "mode"
@@ -372,6 +374,7 @@ export function dispatchSlashCommand(
372
374
  return true
373
375
  }
374
376
 
377
+ case "open_update": deps.setDialog("update"); return true
375
378
  case "open_connect": deps.setDialog("connect"); return true
376
379
  case "open_model_picker":deps.setDialog("model"); return true
377
380
  case "open_mode_picker": deps.setDialog("mode"); return true
package/src/commands.ts CHANGED
@@ -11,6 +11,7 @@ export interface CommandResult {
11
11
  | "copy"
12
12
  | "copy_input"
13
13
  | "compact_session"
14
+ | "open_update"
14
15
  | "open_connect"
15
16
  | "open_model_picker"
16
17
  | "set_model"
@@ -80,6 +81,7 @@ export function parseCommand(input: string): CommandResult | null {
80
81
  const rest = match[2] ?? ""
81
82
 
82
83
  switch (cmd) {
84
+ case "update": return { type: "open_update" }
83
85
  case "help":
84
86
  return {
85
87
  type: "output",
@@ -87,6 +89,7 @@ export function parseCommand(input: string): CommandResult | null {
87
89
  "⚡ zapAgent Commands:",
88
90
  "",
89
91
  " Built-in:",
92
+ " /update — Confirm download, installation and restart",
90
93
  " /review [path] — Review code for bugs & security",
91
94
  " /commit — Stage changes and create a commit",
92
95
  " /init — Analyze project and generate AGENTS.md",
@@ -354,7 +354,7 @@ export function useKeyboardShortcuts(opts: UseKeyboardShortcutsOptions): void {
354
354
  opts.addToast("Press Ctrl+C again to exit")
355
355
  lastCtrlCRef.current = now
356
356
  }
357
- if (key.ctrl && rawInput === "l") {
357
+ if (key.ctrl && rawInput === "l" && opts.dialog !== "update" && opts.dialog !== "restoring") {
358
358
  // Same as /clear — let App's onClearScreen own the full reset.
359
359
  opts.onClearScreen()
360
360
  }
@@ -0,0 +1,15 @@
1
+ import { useEffect, useState } from "react"
2
+ import { join } from "node:path"
3
+ import { getAppDataDir } from "../../zapsdk/utils/platform.js"
4
+ import { shouldCheckForUpdates, startUpdateCheck } from "../update-check.js"
5
+ import { VERSION } from "../version.js"
6
+
7
+ export function useUpdateCheck(): string | null {
8
+ const [version, setVersion] = useState<string | null>(null)
9
+ useEffect(() => {
10
+ if (!shouldCheckForUpdates()) return
11
+ return startUpdateCheck({ currentVersion: VERSION,
12
+ cachePath: join(getAppDataDir(), "cache", "update-check.json") }, setVersion)
13
+ }, [])
14
+ return version
15
+ }
package/src/index.tsx CHANGED
@@ -26,6 +26,7 @@ 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
+ update [--yes] Check, confirm and install the latest version
29
30
  acp Serve Agent Client Protocol v1 over stdio (no TUI)
30
31
  workflow Inspect, wait for or cancel a persisted workflow (--db required)
31
32
 
@@ -61,6 +62,11 @@ if (args.includes("--version") || args.includes("-v")) {
61
62
  process.exit(0)
62
63
  }
63
64
 
65
+ if (args[0] === "update") {
66
+ const { runUpdateCommand } = await import("./update-cli.js")
67
+ process.exit(await runUpdateCommand(args.slice(1)))
68
+ }
69
+
64
70
  let watchOptions: import("./watch/args.js").WatchOptions;
65
71
  try {
66
72
  const parsed = parseWatchArgs(args);
@@ -386,6 +392,32 @@ if (process.stdout.isTTY) {
386
392
  // app-side hooks. macOS Cmd-C / pbpaste continue to work as expected.
387
393
 
388
394
  await inst.waitUntilExit()
395
+ const restart = (await import("./self-update.js")).takeUpdateRestart()
396
+ if (restart) {
397
+ await (await import("./update-lifecycle.js")).prepareUpdateRestart({
398
+ stopWatch: (await import("./watch/integration.js")).stopWatch,
399
+ stopHost: stopHostProtocolServer,
400
+ stopRuntime: (await import("./singletons.js")).stopRuntimeForRestart,
401
+ })
402
+ // Ink has restored the terminal before the replacement process inherits it.
403
+ const restartEnv = { ...process.env, ZAPAGENT_RESTORE_SESSION: restart.sessionId }
404
+ if (process.platform !== "win32" && typeof process.execve === "function") {
405
+ // Replace this process rather than accumulating old runtimes after updates.
406
+ try { process.execve(restart.command, [restart.command, ...restart.args], restartEnv) }
407
+ catch { /* Unsupported runtime/host: use the portable foreground fallback. */ }
408
+ }
409
+ const child = spawn(restart.command, restart.args, { stdio: "inherit", env: restartEnv })
410
+ const forward = (signal: NodeJS.Signals) => { child.kill(signal) }
411
+ const onInterrupt = () => forward("SIGINT")
412
+ const onTerminate = () => forward("SIGTERM")
413
+ process.on("SIGINT", onInterrupt)
414
+ process.on("SIGTERM", onTerminate)
415
+ const code = await new Promise<number>(resolve => {
416
+ child.once("error", error => { console.error(`Restart failed: ${error.message}. Run zap again and use /sessions.`); resolve(1) })
417
+ child.once("exit", code => resolve(code ?? 1))
418
+ })
419
+ process.exit(code)
420
+ }
389
421
  await (await import("./watch/integration.js")).stopWatch()
390
422
  await stopHostProtocolServer()
391
423
  process.exit(0)
@@ -0,0 +1,106 @@
1
+ import { spawn } from "node:child_process"
2
+ import { access, chmod, copyFile, readFile, realpath, rename, rm } from "node:fs/promises"
3
+ import { constants } from "node:fs"
4
+ import { delimiter, dirname, join, resolve } from "node:path"
5
+ import { isNewerRelease } from "./update-check.js"
6
+ import { VERSION } from "./version.js"
7
+ // Reuse the release downloader: versioned cache, SHA-256 verification, atomic writes.
8
+ import { ensureBinary } from "../npm/install.cjs"
9
+
10
+ export interface UpdatePlan {
11
+ version: string
12
+ kind: "npm" | "binary"
13
+ destination: string
14
+ runtime?: string
15
+ npmCLI?: string
16
+ prefix?: string
17
+ }
18
+ export interface RestartRequest { command: string; args: string[]; sessionId: string }
19
+ let restartRequest: RestartRequest | null = null
20
+ export function requestUpdateRestart(request: RestartRequest): void { restartRequest = request }
21
+ export function takeUpdateRestart(): RestartRequest | null {
22
+ const result = restartRequest
23
+ restartRequest = null
24
+ return result
25
+ }
26
+
27
+ async function findNpmCLI(runtime: string): Promise<string> {
28
+ const candidates = [join(dirname(runtime), "node_modules/npm/bin/npm-cli.js"),
29
+ join(dirname(runtime), "../lib/node_modules/npm/bin/npm-cli.js")]
30
+ for (const dir of (process.env.PATH ?? "").split(delimiter)) {
31
+ try {
32
+ const executable = await realpath(join(dir, process.platform === "win32" ? "npm.cmd" : "npm"))
33
+ if (executable.endsWith("npm-cli.js")) candidates.push(executable)
34
+ candidates.push(join(dirname(executable), "node_modules/npm/bin/npm-cli.js"))
35
+ } catch { /* Try the next PATH entry. */ }
36
+ }
37
+ for (const candidate of candidates) {
38
+ try { await access(candidate); return resolve(candidate) } catch { /* Not this installation. */ }
39
+ }
40
+ throw new Error("npm was not found. Install npm or update zapagent using your package manager.")
41
+ }
42
+
43
+ export async function planSelfUpdate(version: string): Promise<UpdatePlan> {
44
+ if (!isNewerRelease(version, VERSION)) throw new Error("Invalid or non-newer release version")
45
+ const launcher = process.env.ZAPAGENT_NPM_LAUNCHER
46
+ const runtime = process.env.ZAPAGENT_NPM_RUNTIME
47
+ if (launcher && runtime) {
48
+ const root = dirname(launcher)
49
+ const pkg = JSON.parse(await readFile(join(root, "../package.json"), "utf8"))
50
+ if (pkg.name !== "zapagent" || pkg.version !== VERSION) throw new Error("Unrecognized npm installation")
51
+ const packageRoot = dirname(root)
52
+ const modules = dirname(packageRoot)
53
+ // Global npm layout only. Local project dependencies and Bun/Homebrew installs
54
+ // belong to their package manager and must not be silently rewritten.
55
+ if (dirname(modules).endsWith(`${process.platform === "win32" ? "\\" : "/"}lib`)) {
56
+ const prefix = dirname(dirname(modules))
57
+ return { version, kind: "npm", destination: launcher, runtime, prefix, npmCLI: await findNpmCLI(runtime) }
58
+ }
59
+ if (process.platform === "win32" && modules.toLowerCase() === join(process.env.APPDATA ?? "", "npm", "node_modules").toLowerCase()) {
60
+ return { version, kind: "npm", destination: launcher, runtime, prefix: dirname(modules), npmCLI: await findNpmCLI(runtime) }
61
+ }
62
+ throw new Error("Use your package manager to update this local or Bun-managed installation.")
63
+ }
64
+ const destination = await realpath(process.execPath)
65
+ if (!process.versions.bun || /(?:^|[/\\])bun(?:\.exe)?$/.test(destination)) throw new Error("Source builds must be updated from Git.")
66
+ if (process.platform === "win32") throw new Error("For automatic updates on Windows, install with npm install -g zapagent.")
67
+ if (destination.includes("/Cellar/") || destination.includes("/nix/store/")) throw new Error("Update this installation using its package manager.")
68
+ await access(dirname(destination), constants.W_OK)
69
+ return { version, kind: "binary", destination }
70
+ }
71
+
72
+ export async function runUpdateProcess(command: string, args: string[]): Promise<void> {
73
+ await new Promise<void>((resolvePromise, reject) => {
74
+ const child = spawn(command, args, { stdio: ["ignore", "ignore", "pipe"], windowsHide: true })
75
+ // Consume output without exposing registry credentials or disturbing the TUI.
76
+ child.stderr?.resume()
77
+ const timer = setTimeout(() => { child.kill(); reject(new Error("Update command timed out. Current session is still running.")) }, 300_000)
78
+ child.once("error", error => { clearTimeout(timer); reject(error) })
79
+ child.once("exit", (code, signal) => { clearTimeout(timer); code === 0 ? resolvePromise() : reject(new Error(`Update command failed (${signal ?? code}). Current session is still running.`)) })
80
+ })
81
+ }
82
+
83
+ export async function installSelfUpdate(
84
+ plan: UpdatePlan,
85
+ sessionId: string,
86
+ deps = { download: ensureBinary, run: runUpdateProcess },
87
+ ): Promise<RestartRequest> {
88
+ if (!isNewerRelease(plan.version, VERSION)) throw new Error("Invalid update version")
89
+ // Download and verify before modifying the installation. No network work is
90
+ // performed by planSelfUpdate; this function is called only after confirmation.
91
+ const binary: string = await deps.download({ version: plan.version })
92
+ if (plan.kind === "npm") {
93
+ if (!plan.runtime || !plan.npmCLI || !plan.prefix) throw new Error("Incomplete npm update plan")
94
+ await deps.run(plan.runtime, [plan.npmCLI, "install", "--global", "--prefix", plan.prefix, `zapagent@${plan.version}`, "--no-audit", "--no-fund"])
95
+ const pkg = JSON.parse(await readFile(join(dirname(plan.destination), "../package.json"), "utf8"))
96
+ if (pkg.version !== plan.version) throw new Error("npm did not install the requested version")
97
+ return { command: binary, args: process.argv.slice(2), sessionId }
98
+ }
99
+ const pending = `${plan.destination}.${process.pid}.update`
100
+ try {
101
+ await copyFile(binary, pending, constants.COPYFILE_EXCL)
102
+ await chmod(pending, 0o755)
103
+ await rename(pending, plan.destination)
104
+ } finally { await rm(pending, { force: true }) }
105
+ return { command: plan.destination, args: process.argv.slice(2), sessionId }
106
+ }
package/src/singletons.ts CHANGED
@@ -153,8 +153,16 @@ function _shutdown(): void {
153
153
  try { cronHandle.stop() } catch {}
154
154
  }
155
155
  process.on("exit", _shutdown)
156
- process.on("SIGINT", () => { _shutdown(); process.exit(130) })
157
- process.on("SIGTERM", () => { _shutdown(); process.exit(143) })
156
+ const shutdownOnInterrupt = () => { _shutdown(); process.exit(130) }
157
+ const shutdownOnTerminate = () => { _shutdown(); process.exit(143) }
158
+ process.on("SIGINT", shutdownOnInterrupt)
159
+ process.on("SIGTERM", shutdownOnTerminate)
160
+
161
+ export function stopRuntimeForRestart(): void {
162
+ _shutdown()
163
+ process.removeListener("SIGINT", shutdownOnInterrupt)
164
+ process.removeListener("SIGTERM", shutdownOnTerminate)
165
+ }
158
166
 
159
167
  // ─── Delegate-agent provider probe + event bridge ───
160
168
  // Probe PATH for `claude` / `codex` once at startup so per-turn agent factory
@@ -0,0 +1,11 @@
1
+ /** @jsxImportSource react */
2
+ import { Box, Text } from "ink"
3
+ import { c } from "./theme.js"
4
+ import { VERSION } from "../version.js"
5
+
6
+ export function UpdateNotice({ version }: { version: string | null }) {
7
+ if (!version) return null
8
+ return <Box paddingX={1}><Text color={c.info}>
9
+ {`Update available: v${VERSION} → v${version} · /update to download, install and restart`}
10
+ </Text></Box>
11
+ }
@@ -0,0 +1,44 @@
1
+ /** @jsxImportSource react */
2
+ import { useEffect, useRef, useState } from "react"
3
+ import { Text, useInput } from "ink"
4
+ import { DialogFrame } from "./dialog-frame.js"
5
+ import { installSelfUpdate, planSelfUpdate, type RestartRequest, type UpdatePlan } from "../self-update.js"
6
+
7
+ export function UpdateDialog({ version, busy, sessionId, beforeInstall, onRestart, onCancel }: {
8
+ version: string | null; busy: boolean; sessionId: string
9
+ beforeInstall: () => void
10
+ onRestart: (request: RestartRequest) => void; onCancel: () => void
11
+ }) {
12
+ const [plan, setPlan] = useState<UpdatePlan | null>(null)
13
+ const [message, setMessage] = useState("Checking installation…")
14
+ const [installing, setInstalling] = useState(false)
15
+ const started = useRef(false)
16
+ useEffect(() => {
17
+ let active = true
18
+ if (!version) { setMessage("No newer version is available yet."); return }
19
+ if (busy) { setMessage("Wait for the current task and queued messages to finish before updating."); return }
20
+ void planSelfUpdate(version).then(result => {
21
+ if (active) { setPlan(result); setMessage(`Install v${version} and restart? Your saved session will be restored.`) }
22
+ }, error => { if (active) setMessage(error instanceof Error ? error.message : "Could not prepare update") })
23
+ return () => { active = false }
24
+ }, [version, busy])
25
+ useInput((input, key) => {
26
+ if (started.current) return
27
+ if (key.escape || input === "n") { onCancel(); return }
28
+ // Enter does not approve: a deliberate 'y' prevents a trailing slash-command
29
+ // Return event from accidentally confirming installation.
30
+ if (input !== "y" || !plan || busy) return
31
+ started.current = true
32
+ setInstalling(true)
33
+ setMessage(`Downloading and installing v${plan.version}…`)
34
+ void Promise.resolve().then(() => { beforeInstall(); return installSelfUpdate(plan, sessionId) }).then(onRestart).catch(error => {
35
+ started.current = false
36
+ setInstalling(false)
37
+ setPlan(null)
38
+ setMessage(`Update failed: ${error instanceof Error ? error.message : "unknown error"}. Close this dialog to continue.`)
39
+ })
40
+ })
41
+ return <DialogFrame title="Update zapAgent" hint={installing ? "Please wait — restart follows successful installation" : "y download, install and restart · esc/n later"}>
42
+ <Text>{message}</Text>
43
+ </DialogFrame>
44
+ }
@@ -17,6 +17,7 @@ export interface SlashEntry {
17
17
  }
18
18
 
19
19
  export const BUILTIN_COMMANDS: SlashEntry[] = [
20
+ { name: "/update", desc: "Download, install and restart after confirmation" },
20
21
  { name: "/help", desc: "Show command reference" },
21
22
  { name: "/connect", desc: "Set up provider & API key" },
22
23
  { name: "/model", desc: "Show or switch model" },
@@ -0,0 +1,129 @@
1
+ import { randomUUID } from "node:crypto"
2
+ import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises"
3
+ import { dirname, join } from "node:path"
4
+
5
+ const REGISTRY_URL = "https://registry.npmjs.org/-/package/zapagent/dist-tags"
6
+ const SUCCESS_TTL = 24 * 60 * 60 * 1000
7
+ const FAILURE_TTL = 15 * 60 * 1000
8
+ const MAX_BYTES = 16 * 1024
9
+
10
+ interface Cache { checkedAt: number; latest: string | null; failed: boolean }
11
+ export function shouldCheckForUpdates(env: NodeJS.ProcessEnv = process.env): boolean {
12
+ return !env.CI && env.ZAP_DISABLE_UPDATE_CHECK !== "1"
13
+ }
14
+ export interface UpdateCheckOptions {
15
+ currentVersion: string
16
+ cachePath: string
17
+ signal?: AbortSignal
18
+ fetch?: typeof fetch
19
+ now?: () => number
20
+ timeoutMs?: number
21
+ }
22
+
23
+ function stableVersion(value: unknown): value is string {
24
+ return typeof value === "string" && value.length <= 64
25
+ && /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value)
26
+ }
27
+
28
+ export function isNewerRelease(latest: string, current: string): boolean {
29
+ if (!stableVersion(latest)) return false
30
+ const parsed = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.exec(current)
31
+ if (!parsed) return false
32
+ const next = latest.split(".").map(BigInt)
33
+ for (let i = 0; i < 3; i++) {
34
+ const installed = BigInt(parsed[i + 1]!)
35
+ if (next[i]! !== installed) return next[i]! > installed
36
+ }
37
+ return Boolean(parsed[4])
38
+ }
39
+
40
+ async function readCache(path: string, now: number): Promise<Cache | undefined> {
41
+ try {
42
+ const text = await readFile(path, "utf8")
43
+ if (text.length > MAX_BYTES) return
44
+ const value = JSON.parse(text) as Cache
45
+ if (!value || !Number.isFinite(value.checkedAt) || value.checkedAt < 0 || value.checkedAt > now
46
+ || typeof value.failed !== "boolean" || (value.latest !== null && !stableVersion(value.latest))) return
47
+ return value
48
+ } catch { return }
49
+ }
50
+
51
+ async function writeCache(path: string, value: Cache): Promise<void> {
52
+ const temporary = join(dirname(path), `.update-${randomUUID()}.tmp`)
53
+ try {
54
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 })
55
+ await writeFile(temporary, JSON.stringify(value), { mode: 0o600, flag: "wx" })
56
+ await rename(temporary, path)
57
+ } catch { /* Read-only/unavailable storage must not affect the CLI. */ }
58
+ finally { await unlink(temporary).catch(() => {}) }
59
+ }
60
+
61
+ export async function fetchLatestRelease(options: UpdateCheckOptions): Promise<string> {
62
+ const controller = new AbortController()
63
+ let timer: ReturnType<typeof setTimeout> | undefined
64
+ let onAbort: (() => void) | undefined
65
+ try {
66
+ return await Promise.race([
67
+ (async () => {
68
+ const response = await (options.fetch ?? fetch)(REGISTRY_URL, {
69
+ signal: controller.signal, redirect: "error", headers: { Accept: "application/json" },
70
+ })
71
+ if (!response.ok || !response.body) throw new Error("Update metadata unavailable")
72
+ const reader = response.body.getReader()
73
+ let size = 0, text = ""
74
+ const decoder = new TextDecoder()
75
+ try {
76
+ while (true) {
77
+ const { done, value } = await reader.read()
78
+ if (done) break
79
+ size += value.byteLength
80
+ if (size > MAX_BYTES) throw new Error("Update metadata too large")
81
+ text += decoder.decode(value, { stream: true })
82
+ }
83
+ text += decoder.decode()
84
+ } finally { await reader.cancel().catch(() => {}) }
85
+ const latest: unknown = JSON.parse(text)?.latest
86
+ if (!stableVersion(latest)) throw new Error("Invalid stable release")
87
+ return latest
88
+ })(),
89
+ new Promise<never>((_, reject) => {
90
+ onAbort = () => { controller.abort(); reject(new Error("Update check cancelled")) }
91
+ options.signal?.addEventListener("abort", onAbort, { once: true })
92
+ if (options.signal?.aborted) return onAbort()
93
+ timer = setTimeout(() => { controller.abort(); reject(new Error("Update check timed out")) }, options.timeoutMs ?? 3000)
94
+ timer.unref?.()
95
+ }),
96
+ ])
97
+ } finally {
98
+ if (timer) clearTimeout(timer)
99
+ if (onAbort) options.signal?.removeEventListener("abort", onAbort)
100
+ controller.abort()
101
+ }
102
+ }
103
+
104
+ /** Background-only, best effort. Never logs or throws into startup/protocol output. */
105
+ export async function checkForUpdate(options: UpdateCheckOptions): Promise<string | null> {
106
+ try {
107
+ if (options.signal?.aborted) return null
108
+ const now = options.now ?? Date.now
109
+ const cached = await readCache(options.cachePath, now())
110
+ if (options.signal?.aborted) return null
111
+ let latest = cached?.latest ?? null
112
+ if (!cached || now() - cached.checkedAt >= (cached.failed ? FAILURE_TTL : SUCCESS_TTL)) {
113
+ let failed = false
114
+ try { latest = await fetchLatestRelease(options) } catch { failed = true }
115
+ if (options.signal?.aborted) return null
116
+ await writeCache(options.cachePath, { checkedAt: now(), latest, failed })
117
+ }
118
+ return latest && isNewerRelease(latest, options.currentVersion) ? latest : null
119
+ } catch { return null }
120
+ }
121
+
122
+ /** Returns immediately; unmount cancels requests and suppresses late notices. */
123
+ export function startUpdateCheck(options: Omit<UpdateCheckOptions, "signal">, notify: (version: string) => void): () => void {
124
+ const controller = new AbortController()
125
+ void checkForUpdate({ ...options, signal: controller.signal }).then(version => {
126
+ if (version && !controller.signal.aborted) notify(version)
127
+ }).catch(() => {})
128
+ return () => controller.abort()
129
+ }
@@ -0,0 +1,54 @@
1
+ import { createInterface } from "node:readline/promises"
2
+ import { fetchLatestRelease, isNewerRelease } from "./update-check.js"
3
+ import { installSelfUpdate, planSelfUpdate } from "./self-update.js"
4
+ import { VERSION } from "./version.js"
5
+
6
+ interface UpdateCommandDeps {
7
+ latest: () => Promise<string>
8
+ confirm: (question: string) => Promise<boolean>
9
+ plan: typeof planSelfUpdate
10
+ install: typeof installSelfUpdate
11
+ write: (message: string) => void
12
+ }
13
+
14
+ export async function runUpdateCommand(args: string[], overrides: Partial<UpdateCommandDeps> = {}): Promise<number> {
15
+ const deps: UpdateCommandDeps = {
16
+ latest: () => fetchLatestRelease({ currentVersion: VERSION, cachePath: "" }),
17
+ confirm: async question => {
18
+ if (!process.stdin.isTTY) throw new Error("Confirmation requires a terminal. Use zap update --yes for unattended installation.")
19
+ const input = createInterface({ input: process.stdin, output: process.stdout })
20
+ try { return /^(?:y|yes)$/i.test((await input.question(question)).trim()) }
21
+ finally { input.close() }
22
+ },
23
+ plan: planSelfUpdate, install: installSelfUpdate,
24
+ write: message => { process.stdout.write(`${message}\n`) },
25
+ ...overrides,
26
+ }
27
+ if (args.some(arg => arg !== "--yes" && arg !== "-y")) {
28
+ deps.write("Usage: zap update [--yes|-y]")
29
+ return 2
30
+ }
31
+ try {
32
+ deps.write("Checking for zapAgent updates…")
33
+ const version = await deps.latest()
34
+ if (!isNewerRelease(version, VERSION)) {
35
+ deps.write(`zapAgent v${VERSION} is up to date.`)
36
+ return 0
37
+ }
38
+ const plan = await deps.plan(version)
39
+ deps.write(`Update available: v${VERSION} → v${version}`)
40
+ if (!args.includes("--yes") && !args.includes("-y") && !await deps.confirm("Download and install? [y/N] ")) {
41
+ deps.write("Update cancelled.")
42
+ return 0
43
+ }
44
+ deps.write(`Downloading and installing v${version}…`)
45
+ await deps.install(plan, "")
46
+ // This short-lived command owns no TUI/session to restart. Future zap
47
+ // invocations use the updated launcher/binary; an existing TUI is untouched.
48
+ deps.write(`Installed zapAgent v${version}. Run zap to start.`)
49
+ return 0
50
+ } catch (error) {
51
+ deps.write(`Update failed: ${error instanceof Error ? error.message : "unknown error"}`)
52
+ return 1
53
+ }
54
+ }
@@ -0,0 +1,22 @@
1
+ /** Keep the composer and queue paused until both preparation and commit finish. */
2
+ export async function restoreAfterUpdate<T>(options: {
3
+ load: () => Promise<T>
4
+ commit: (loaded: T) => void
5
+ failed: () => void
6
+ finished: () => void
7
+ }): Promise<void> {
8
+ try { options.commit(await options.load()) }
9
+ catch { options.failed() }
10
+ finally { options.finished() }
11
+ }
12
+
13
+ /** Cleanup must complete before a replacement TUI inherits the terminal. */
14
+ export async function prepareUpdateRestart(options: {
15
+ stopWatch: () => Promise<void>
16
+ stopHost: () => Promise<void>
17
+ stopRuntime: () => void
18
+ }): Promise<void> {
19
+ await options.stopWatch()
20
+ await options.stopHost()
21
+ options.stopRuntime()
22
+ }
@@ -8,6 +8,7 @@ export interface ParserCtx {
8
8
  stepCounter: { value: number };
9
9
  textBlockId: string | null;
10
10
  finalText: string;
11
+ error?: string;
11
12
  startedEmitted: boolean;
12
13
  finishedEmitted: boolean;
13
14
  /** Captured from the first event that carries it:
@@ -326,6 +327,9 @@ export function parseCodexLine(line: string, ctx: ParserCtx): AgentEvent[] {
326
327
  case "turn.failed":
327
328
  case "thread.failed":
328
329
  case "error": {
330
+ const detail = o.error as { message?: unknown } | undefined;
331
+ const message = detail?.message ?? o.message;
332
+ if (typeof message === "string") ctx.error = message;
329
333
  const ev = emitFinished(ctx, "codex", false);
330
334
  if (ev) out.push(ev);
331
335
  return out;
@@ -1,10 +1,10 @@
1
1
  import { z } from "zod";
2
2
  import { currentRuntimeObservation, observeRuntime } from "../runtime/observation.js";
3
- import { existsSync, mkdirSync, lstatSync } from "node:fs";
3
+ import { existsSync, mkdirSync, lstatSync, symlinkSync, realpathSync } from "node:fs";
4
4
  import { createHash } from "node:crypto";
5
5
  import { execFileSync } from "node:child_process";
6
6
  import { homedir } from "node:os";
7
- import { join } from "node:path";
7
+ import { join, resolve } from "node:path";
8
8
  import type { Tool, ToolResult } from "../tools/types.js";
9
9
  import type { AgentEventHandler } from "../agent/events.js";
10
10
  import type { DetectedProvider } from "./delegate-detect.js";
@@ -19,6 +19,7 @@ import {
19
19
  diffSnapshots,
20
20
  formatChangeSummary,
21
21
  } from "./delegate-changes.js";
22
+ import { integrationGitWriteRoots } from "../execution/workspace-runtime.js";
22
23
  import { resolveToolPath, resolveToolPathCanonical } from "./filesystem.js";
23
24
  import { createLocalProcessBroker, terminateProcessTreeWithGrace } from "../execution/process.js";
24
25
 
@@ -52,11 +53,12 @@ export function buildCliArgs(
52
53
  args.push("-p", task);
53
54
  return args;
54
55
  }
55
- // codex
56
+ // Codex must preserve the broker environment: login profiles reset PATH and
57
+ // bypass the sandbox toolchain shims (notably Apple git/xcrun).
56
58
  if (resumeId) {
57
- return ["exec", "resume", "--dangerously-bypass-approvals-and-sandbox", "--json", resumeId, task];
59
+ return ["exec", "resume", "--dangerously-bypass-approvals-and-sandbox", "--config", "allow_login_shell=false", "--json", resumeId, task];
58
60
  }
59
- return ["exec", "--dangerously-bypass-approvals-and-sandbox", "--json", task];
61
+ return ["exec", "--dangerously-bypass-approvals-and-sandbox", "--config", "allow_login_shell=false", "--json", task];
60
62
  }
61
63
 
62
64
  function buildDescription(providers: DetectedProvider[]): string {
@@ -75,6 +77,7 @@ function buildDescription(providers: DetectedProvider[]): string {
75
77
  claudeBlurb,
76
78
  codexBlurb,
77
79
  "Returns a final report, git change summary, and resumable session id.",
80
+ "Sandbox temp is per-call; save reusable files in cwd.",
78
81
  ].filter(Boolean).join(" ");
79
82
  }
80
83
 
@@ -110,10 +113,11 @@ export function delegateAgentTool(opts: DelegateAgentOptions): Tool | null {
110
113
  opts.defaultCwd ?? context.cwd,
111
114
  );
112
115
  const provider = String(args.provider) as "claude" | "codex";
113
- const keychain = provider === "claude" ? macKeychainPaths() : undefined;
116
+ const keychain = macKeychainPaths();
114
117
  return {
115
118
  filesystem: [
116
119
  { kind: "filesystem", operation: "read", paths: [cwd] },
120
+ ...integrationGitWriteRoots(cwd).map(path => ({ kind: "filesystem" as const, operation: "modify" as const, paths: [path] })),
117
121
  ...delegateCredentialPaths(provider).map((path) => ({
118
122
  kind: "filesystem" as const,
119
123
  operation: "read" as const,
@@ -124,8 +128,8 @@ export function delegateAgentTool(opts: DelegateAgentOptions): Tool | null {
124
128
  { kind: "filesystem" as const, operation: "modify" as const, paths: [keychain.lock] },
125
129
  ] : []),
126
130
  { kind: "filesystem", operation: "modify", paths: [cwd] },
127
- ...(provider === "claude" ? [{ kind: "filesystem" as const, operation: "modify" as const,
128
- paths: [claudeStateDirectory(cwd, opts.stateDir)] }] : []),
131
+ { kind: "filesystem" as const, operation: "modify" as const,
132
+ paths: [delegateStateDirectory(provider, cwd, opts.stateDir)] },
129
133
  ],
130
134
  network: [{ kind: "network", operation: "connect", destinations: ["*"], methods: [] }],
131
135
  process: [{
@@ -181,22 +185,34 @@ export function delegateAgentTool(opts: DelegateAgentOptions): Tool | null {
181
185
  // Cancellation may arrive while the asynchronous workspace snapshot runs.
182
186
  if (signal?.aborted) return { success: false, output: "", error: "aborted" };
183
187
 
184
- let environment: Record<string, string> | undefined;
185
- if (provider === "claude") {
186
- const stateDir = claudeStateDirectory(resolveToolPathCanonical(cwd, cwd), opts.stateDir);
188
+ let environment: Record<string, string>;
189
+ {
190
+ const stateDir = delegateStateDirectory(provider, resolveToolPathCanonical(cwd, cwd), opts.stateDir);
187
191
  mkdirSync(stateDir, { recursive: true, mode: 0o700 });
188
192
  const state = lstatSync(stateDir);
189
- if (!state.isDirectory() || (state.mode & 0o077) !== 0) {
190
- return { success: false, output: "", error: "Claude delegate state must be a private directory (0700)." };
193
+ if (!state.isDirectory() || state.isSymbolicLink() || (state.mode & 0o077) !== 0) {
194
+ return { success: false, output: "", error: "Delegate state must be a private directory (0700)." };
191
195
  }
192
- environment = {
196
+ environment = provider === "claude" ? {
193
197
  CLAUDE_CONFIG_DIR: stateDir,
194
198
  // Keep the login/keychain namespace, but never make host settings or
195
199
  // credentials writable. Session/debug/cache writes use private state.
196
200
  // Empty selects Claude's default credential/keychain namespace;
197
201
  // a nonempty path hashes into a different, unauthenticated namespace.
198
202
  CLAUDE_SECURESTORAGE_CONFIG_DIR: "",
199
- };
203
+ } : { CODEX_HOME: stateDir };
204
+ if (provider === "codex") {
205
+ const host = codexHome();
206
+ for (const name of ["auth.json", "config.toml"]) {
207
+ const source = join(host, name), target = join(stateDir, name);
208
+ if (existsSync(source)) {
209
+ try { lstatSync(target); } catch (error) {
210
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
211
+ symlinkSync(realpathSync(source), target);
212
+ }
213
+ }
214
+ }
215
+ }
200
216
  }
201
217
 
202
218
  observeExternal("starting");
@@ -204,6 +220,9 @@ export function delegateAgentTool(opts: DelegateAgentOptions): Tool | null {
204
220
  try { child = processBroker.spawnCommand(detected.bin, cliArgs, {
205
221
  cwd,
206
222
  hostHome: true,
223
+ networkDomains: provider === "claude"
224
+ ? ["api.anthropic.com", "console.anthropic.com", "claude.ai", "*.claude.ai"]
225
+ : ["chatgpt.com", "*.chatgpt.com", "api.openai.com", "auth.openai.com", "*.oaiusercontent.com"],
207
226
  environment,
208
227
  temporaryDirectoryEnvironment: provider === "claude" ? ["CLAUDE_CODE_TMPDIR"] : undefined,
209
228
  preserveEnvironment: provider === "claude"
@@ -314,6 +333,7 @@ export function delegateAgentTool(opts: DelegateAgentOptions): Tool | null {
314
333
  // main agent has no way to learn what id to pass back next call.
315
334
  const sessionLine = ctx.sessionId
316
335
  ? `\n\n_Session resumable: pass \`resume_session_id="${ctx.sessionId}"\` (provider="${provider}") in your next delegate_agent call to continue this session._`
336
+ + (processBroker.sandboxedSpawnCount > 0 ? "\n_Sandbox temporary files were cleaned up at CLI exit; session resume does not restore TMPDIR files. Save reusable artifacts in cwd._" : "")
317
337
  : "";
318
338
 
319
339
  if (aborted) {
@@ -331,7 +351,7 @@ export function delegateAgentTool(opts: DelegateAgentOptions): Tool | null {
331
351
  return {
332
352
  success: false,
333
353
  output: "",
334
- error: `${provider} exited with code ${exitInfo.code}. stderr (last ${STDERR_TAIL_BYTES}B):\n${stderrTail}`,
354
+ error: `${provider} exited with code ${exitInfo.code}. ${ctx.error ? `${ctx.error}\n` : ""}stderr (last ${STDERR_TAIL_BYTES}B):\n${stderrTail}`,
335
355
  meta,
336
356
  };
337
357
  }
@@ -362,10 +382,23 @@ export function delegateAgentTool(opts: DelegateAgentOptions): Tool | null {
362
382
  };
363
383
  }
364
384
 
365
- function claudeStateDirectory(cwd: string, stateDir?: string): string {
385
+ function delegateStateDirectory(provider: "claude" | "codex", cwd: string, stateDir?: string): string {
366
386
  const root = stateDir ?? join(process.env.ZAPCODE_DATA_DIR || join(homedir(), ".zapcode"), "delegates");
367
- const workspaceId = createHash("sha256").update(cwd).digest("hex").slice(0, 24);
368
- return resolveToolPathCanonical(join(root, "claude", workspaceId), process.cwd());
387
+ const workspaceId = createHash("sha256").update(resolveToolPathCanonical(cwd, cwd)).digest("hex").slice(0, 24);
388
+ const target = resolve(root, provider, workspaceId);
389
+ // Do not canonicalize an existing state symlink into a new host write grant.
390
+ for (const path of [resolve(root), resolve(root, provider), target]) {
391
+ try {
392
+ const stat = lstatSync(path);
393
+ if (!stat.isDirectory() || stat.isSymbolicLink()
394
+ || (process.getuid && (stat.uid !== process.getuid() || (stat.mode & 0o077) !== 0))) {
395
+ throw new Error("Delegate state must be a private directory (0700).");
396
+ }
397
+ } catch (error) {
398
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
399
+ }
400
+ }
401
+ return resolveToolPathCanonical(target, process.cwd());
369
402
  }
370
403
 
371
404
  /** Security.framework reads its per-user MDS cache and locks mds.lock even
@@ -385,6 +418,8 @@ function delegateCredentialPaths(provider: "claude" | "codex"): string[] {
385
418
  const home = homedir();
386
419
  const candidates = provider === "claude"
387
420
  ? [join(home, ".claude"), join(home, ".claude.json"), join(home, ".config", "claude")]
388
- : [join(home, ".codex"), join(home, ".config", "codex")];
421
+ : [codexHome(), join(home, ".config", "codex")];
389
422
  return candidates.filter(existsSync);
390
423
  }
424
+
425
+ function codexHome(): string { return process.env.CODEX_HOME || join(homedir(), ".codex"); }
@@ -202,7 +202,12 @@ export class DefaultExecutionBroker implements ExecutionBroker {
202
202
  if (signal?.aborted) return reject("aborted", "CANCELLED");
203
203
  sandbox = needsProcessSandbox && !unsandboxed && sandboxStatus.available
204
204
  ? this.sandbox.createContext({ executionId: request.executionId,
205
- workspace: request.workspace, effects: request.effects, grant: request.grant })
205
+ workspace: request.workspace, effects: request.effects, grant: request.grant,
206
+ externalCliIntegration: request.tool.definition.name === "delegate_agent"
207
+ && request.tool.definition.executionLocation === "host"
208
+ && request.workspace.mode !== "shared-readonly"
209
+ && request.effects.workspace.mode === "root-integration"
210
+ && request.effects.process.some(effect => effect.commandClass === "external-cli") })
206
211
  : undefined;
207
212
  processBroker = needsProcessSandbox
208
213
  ? this.processBrokerFactory?.({ request, sandbox, signal: executionAbort.signal, limits })
@@ -92,6 +92,19 @@ export class NetworkProxy {
92
92
  * Concurrent commands must never inherit one another's denial evidence. */
93
93
  fork(): NetworkProxy { return new NetworkProxy(this.policy); }
94
94
 
95
+ /** Only trusted adapters may extend a command-owned listener. */
96
+ private readonly additionalDomains = new Set<string>();
97
+ allowDomains(domains: string[]): void {
98
+ for (const domain of domains) {
99
+ if (/^(?:\*\.)?[a-z0-9][a-z0-9.-]*$/i.test(domain)) this.additionalDomains.add(domain);
100
+ }
101
+ }
102
+
103
+ decideHost(host: string): ReturnType<typeof decideHost> {
104
+ const policy = this.policy();
105
+ return decideHost({ ...policy, allowedDomains: [...policy.allowedDomains, ...this.additionalDomains] }, host);
106
+ }
107
+
95
108
  close(): void {
96
109
  this.server.close();
97
110
  for (const socket of this.sockets) socket.destroy();
@@ -142,7 +155,7 @@ export class NetworkProxy {
142
155
  const headers = lines.slice(1).filter((line) => !/^(proxy-connection|connection|proxy-authorization):/i.test(line));
143
156
  forwardHead = [`${method} ${url.pathname}${url.search} HTTP/1.1`, ...headers, "Connection: close"].join("\r\n") + "\r\n\r\n";
144
157
  }
145
- const decision = decideHost(this.policy(), host);
158
+ const decision = this.decideHost(host);
146
159
  if (!decision.allowed) {
147
160
  const key = normalizeHost(host);
148
161
  if (!this.blocked.has(key)) this.blocked.set(key, decision.reason);
@@ -110,9 +110,11 @@ abstract class CommandWrappingSandbox implements OsSandbox {
110
110
  dirname(canonicalPath(process.execPath)),
111
111
  ].map((path) => canonicalPath(resolve(input.workspace.root, path))))];
112
112
  const networkAllowed = (input.grant.network?.destinations.length ?? 0) > 0;
113
+ const integrationGit = input.externalCliIntegration
114
+ && input.grant.filesystem?.write.some(path => canonicalPath(path) === canonicalPath(join(input.workspace.root, ".git")));
113
115
  const protectedPaths = [".git", ".zapcode"]
114
116
  .map((name) => canonicalPath(resolve(input.workspace.root, name)))
115
- .filter((path) => path !== privateGit);
117
+ .filter((path) => path !== privateGit && !(integrationGit && path === canonicalPath(join(input.workspace.root, ".git"))));
116
118
  const provider = status.provider;
117
119
  const prepare = (
118
120
  executable: string,
@@ -133,6 +135,7 @@ abstract class CommandWrappingSandbox implements OsSandbox {
133
135
  operationFailure("BACKEND_UNAVAILABLE", "backend", input.executionId));
134
136
  }
135
137
  }
138
+ if (input.externalCliIntegration) proxy?.allowDomains(options.networkDomains ?? []);
136
139
  wrapped = this.wrap(executable, args, {
137
140
  cwd: canonicalPath(resolve(options.cwd)),
138
141
  readablePaths: [...new Set([
@@ -523,6 +526,9 @@ function sandboxEnvironment(
523
526
  Object.assign(env, options.environment);
524
527
  for (const key of options.temporaryDirectoryEnvironment ?? []) env[key] = tempDir;
525
528
  env.HOME = options.hostHome ? homedir() : tempDir;
529
+ // Authenticated CLIs use explicit credential paths, not implicit host XDG
530
+ // settings (Git otherwise probes ~/.config/git/ignore outside its grant).
531
+ if (options.hostHome) env.XDG_CONFIG_HOME = join(tempDir, "config");
526
532
  env.TMPDIR = tempDir;
527
533
  env.TMP = tempDir;
528
534
  env.TEMP = tempDir;
@@ -534,6 +540,8 @@ function sandboxEnvironment(
534
540
  : [join(env.HOME!, ".local", "bin"), join(env.HOME!, ".cargo", "bin"), join(env.HOME!, ".bun", "bin")];
535
541
  env.PATH = [...bins, ...(env.PATH ? [env.PATH] : [])].join(delimiter);
536
542
  }
543
+ // zsh uses TMPPREFIX rather than TMPDIR for heredoc temporary files.
544
+ env.TMPPREFIX = join(env.TMPDIR!, "zsh");
537
545
  env.GIT_CONFIG_GLOBAL = "/dev/null";
538
546
  if (proxyUrl) {
539
547
  for (const name of ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"]) env[name] = proxyUrl;
@@ -45,6 +45,8 @@ export interface SandboxCommandOptions {
45
45
  environment?: Record<string, string>;
46
46
  /** Adapter-specific aliases for the broker's private per-command temp dir. */
47
47
  temporaryDirectoryEnvironment?: string[];
48
+ /** Trusted adapter endpoints, scoped to this command; explicit host denials still win. */
49
+ networkDomains?: string[];
48
50
  }
49
51
 
50
52
  export interface SandboxExecutionContext {
@@ -90,6 +92,8 @@ export interface OsSandbox {
90
92
  status(): SandboxStatus;
91
93
  createContext(input: {
92
94
  executionId: string;
95
+ /** Broker-authorized external CLI integration, never derived from shell arguments. */
96
+ externalCliIntegration?: boolean;
93
97
  workspace: WorkspaceIdentity;
94
98
  effects: ToolEffects;
95
99
  grant: CapabilityGrant;
@@ -146,3 +146,20 @@ export function workspaceRuntimeEnvironment(root: string, temp: string): Record<
146
146
  }
147
147
  return env;
148
148
  }
149
+
150
+ /** Explicit Git integration roots for an approved external CLI. Never follow
151
+ * arbitrary .git pointers; linked worktrees must pass the reciprocal checks. */
152
+ export function integrationGitWriteRoots(workspace: string): string[] {
153
+ const root = realpathSync(workspace);
154
+ const entry = join(root, ".git");
155
+ try {
156
+ const stat = lstatSync(entry);
157
+ if (stat.isDirectory() && !stat.isSymbolicLink()) return [entry];
158
+ const [gitDir, common] = linkedWorktreeReadRoots(root);
159
+ if (!gitDir || !common) return [];
160
+ return [gitDir, ...["objects", "refs", "logs"].map(name => join(common, name)).filter(path => {
161
+ try { const stat = lstatSync(path); return stat.isDirectory() && !stat.isSymbolicLink() && realpathSync(path) === path; }
162
+ catch { return false; }
163
+ })];
164
+ } catch { return []; }
165
+ }