zapagent 1.14.8 → 1.14.10

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.8",
3
+ "version": "1.14.10",
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",
@@ -22,7 +22,7 @@ export interface ExecutionEnvironment {
22
22
  capacity?: ExecutionCapacityFacts
23
23
  // No prompt, model, retry, budget or completion policy is accepted here.
24
24
  commandOptions: Pick<ExecuteCommandOptions,
25
- "disableBackgroundTasks" | "restrictedNetwork" | "preserveEnvironment" | "allowUnsandboxed" | "sandboxNetwork" | "sandboxExcludedCommands">
25
+ "disableBackgroundTasks" | "restrictedNetwork" | "preserveEnvironment" | "allowUnsandboxed" | "sandboxNetwork" | "sandboxExcludedCommands" | "sandboxGitIntegration">
26
26
  }
27
27
 
28
28
  export type ExecutionBackend = "local" | "vm"
@@ -123,6 +123,7 @@ export function createExecutionEnvironment(
123
123
  const local = new DefaultExecutionBroker({
124
124
  services: serviceOwner,
125
125
  sandbox: createPlatformSandbox({
126
+ rootWorkspaceGitWrites: true,
126
127
  workspaceStateRoot: resident || installation || cloud ? undefined : join(getAppDataDir(), "sandbox", "workspaces"),
127
128
  // Trusted outer mounts/egress are enforcement details, not Agent policy.
128
129
  trustedWritablePaths: resident ? ["/nix"] : (installation || cloud ? [] : hostPackageWriteRoots()),
@@ -148,6 +149,7 @@ export function createExecutionEnvironment(
148
149
  vm: cloud ? createZapVmCloudExecutionBroker(cloud) : undefined,
149
150
  }),
150
151
  commandOptions: {
152
+ sandboxGitIntegration: hostSandboxed && sandboxMode !== "disabled" && local.sandboxStatus().available,
151
153
  // These transports cannot retain a detached child beyond its lease.
152
154
  // Other backends defer to the user's env setting instead of overriding it.
153
155
  disableBackgroundTasks: cloud !== undefined || resident ? true : undefined,
@@ -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
+ }
@@ -24,6 +24,8 @@ export interface ExecuteCommandOptions {
24
24
  * launch an interpreter; the execution broker owns that decision. */
25
25
  executionShell?: string;
26
26
  sandboxTemporaryDirectory?: ExecutionEnvironmentFacts["sandboxTemporaryDirectory"];
27
+ /** Host advertises its scoped, sandboxed root Git adapter. */
28
+ sandboxGitIntegration?: boolean;
27
29
  /** Inject a shared TaskStore to enable the `run_in_background:true`
28
30
  * flag. When omitted (or when `ZAPCODE_DISABLE_BACKGROUND_TASKS=1` is
29
31
  * set), background fields are stripped from the schema entirely — the
@@ -243,6 +245,9 @@ export function executeCommandTool(options: ExecuteCommandOptions = {}): Tool {
243
245
  "Exit 0 reports final shell status only. Inspect stderr for warnings or masked failures; do not auto-replay side effects. Chain dependencies with &&. Pipelines report the last stage: check stages or use supported pipefail. Use check_steps for independent checks; each uses a fresh shell and stops on nonzero.",
244
246
  "cwd selects the starting directory, not a narrower workspace. For external inputs/outputs declare read_paths/write_paths (relative to cwd); these need file authorization. A prior Read alone does not grant Bash access. Sandboxed .git/.zapcode remain read-only.",
245
247
  );
248
+ if (options.sandboxGitIntegration) {
249
+ promptLines.push("For root-repository Git writes, use standalone Bash calls: git add <paths>, git commit -m <message>, git stash push/pop, git rebase <ref>. The Host runs supported commands using trusted Git inside the OS sandbox. Do not combine them with &&, cd, redirects, -c/-C or interactive options. Arbitrary shell writes to .git remain blocked; unsupported or executable Git config retains the normal approval path.");
250
+ }
246
251
  if (options.sandboxTemporaryDirectory) {
247
252
  promptLines.push(
248
253
  `Local sandbox: expand ${options.sandboxTemporaryDirectory.environmentVariables.join(", ")} for a private writable scratch directory; avoid hard-coded /tmp or disposable project files.`,
@@ -0,0 +1,106 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, realpathSync, statSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { integrationGitWriteRoots } from "./workspace-runtime.js";
5
+
6
+ /** Deliberately smaller than shell syntax: never evaluate substitutions, chains,
7
+ * redirections or environment assignments with elevated Git metadata access. */
8
+ export function rootGitArguments(command: string): string[] | undefined {
9
+ if (/[\r\n$`\0]/.test(command)) return;
10
+ const words: string[] = [];
11
+ let word = "", quote = "", active = false;
12
+ for (let i = 0; i < command.length; i++) {
13
+ const ch = command[i]!;
14
+ if (quote) {
15
+ if (ch === quote) quote = "";
16
+ else if (ch === "\\" && quote === '"') {
17
+ const next = command[++i]; if (next === undefined || !['"', "\\"].includes(next)) return;
18
+ word += next;
19
+ } else word += ch;
20
+ } else if (ch === "'" || ch === '"') { quote = ch; active = true; }
21
+ else if (/\s/.test(ch)) { if (active) { words.push(word); word = ""; active = false; } }
22
+ else if (/[;&|<>()[\]{}*?!#\\]/.test(ch)) return;
23
+ else { word += ch; active = true; }
24
+ }
25
+ if (quote) return;
26
+ if (active) words.push(word);
27
+ if (words.shift() !== "git") return;
28
+ const op = words.shift();
29
+ if (!op || !["add", "commit", "stash", "rebase"].includes(op)) return;
30
+ const flags: Record<string, Set<string>> = {
31
+ add: new Set(["-A", "--all", "-u", "--update", "-f", "--force", "-v", "--verbose"]),
32
+ commit: new Set(["-a", "--all", "--amend", "--no-edit", "--allow-empty", "-q", "--quiet", "-v", "--verbose"]),
33
+ stash: new Set(["-u", "--include-untracked", "-a", "--all", "-k", "--keep-index", "-q", "--quiet", "--index"]),
34
+ rebase: new Set(["--onto", "--root", "--autostash", "--no-autostash", "-q", "--quiet", "-v", "--verbose"]),
35
+ };
36
+ let paths = false;
37
+ for (let i = 0; i < words.length; i++) {
38
+ const word = words[i]!;
39
+ if (word === "--" && op !== "rebase") { paths = true; continue; }
40
+ if (paths) continue;
41
+ if ((op === "commit" || op === "stash") && ["-m", "--message", ...(op === "commit" ? ["-am", "-ma", "-qm"] : [])].includes(word)) {
42
+ if (words[++i] === undefined) return;
43
+ continue;
44
+ }
45
+ if (word.startsWith("-")) { if (!flags[op]!.has(word)) return; }
46
+ else if (op === "rebase" && !/^[A-Za-z0-9_][A-Za-z0-9_./~^@{}-]*$/.test(word)) return;
47
+ }
48
+ if (op === "stash" && words[0] && !words[0].startsWith("-") && !["push", "pop", "apply", "drop", "list"].includes(words[0])) return;
49
+ // Never permit commit to enter an editor or rebase to consume an existing
50
+ // todo containing exec instructions. Fresh non-interactive rebase only.
51
+ if (op === "commit" && !words.some(word => ["-m", "--message", "-am", "-ma", "-qm", "--no-edit"].includes(word))) return;
52
+ if (op === "rebase" && !words.length) return;
53
+ return [op, ...words];
54
+ }
55
+
56
+ export function trustedGitExecutable(): string {
57
+ let path = process.platform === "win32" ? join(process.env.ProgramFiles ?? "C:\\Program Files", "Git", "cmd", "git.exe") : "/usr/bin/git";
58
+ if (process.platform === "darwin") path = execFileSync("/usr/bin/xcrun", ["--find", "git"], { encoding: "utf8", timeout: 3000, stdio: ["ignore", "pipe", "ignore"] }).trim();
59
+ path = realpathSync(path);
60
+ const file = statSync(path);
61
+ if (!file.isFile() || (process.platform !== "win32" && (file.uid !== 0 || (file.mode & 0o022)))) throw new Error("Git integration requires a trusted system Git executable");
62
+ return path;
63
+ }
64
+
65
+ export function rootGitEnvironment(): NodeJS.ProcessEnv {
66
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^GIT_/i.test(key)));
67
+ const empty = process.platform === "win32" ? "NUL" : "/dev/null";
68
+ return { ...env, GIT_CONFIG_GLOBAL: empty, GIT_CONFIG_SYSTEM: empty, GIT_CONFIG_NOSYSTEM: "1", GIT_TERMINAL_PROMPT: "0" };
69
+ }
70
+
71
+ /** No Git helper may execute arbitrary code while Git metadata is writable.
72
+ * Fail back to the ordinary sandbox for unsupported/executable repository config. */
73
+ export function prepareRootGit(command: string, workspace: string, cwd: string): { executable: string; args: string[]; environment: NodeJS.ProcessEnv } | undefined {
74
+ const args = rootGitArguments(command);
75
+ if (!args) return;
76
+ const roots = integrationGitWriteRoots(workspace);
77
+ if (!roots.length) return;
78
+ const metadata = roots[0]!;
79
+ if (["rebase-merge", "rebase-apply", "sequencer"].some(name => existsSync(join(metadata, name)))) return;
80
+ // Nested repositories are not implicitly the authorized root repository.
81
+ const executable = trustedGitExecutable();
82
+ const environment = rootGitEnvironment();
83
+ const top = execFileSync(executable, ["rev-parse", "--show-toplevel"], { cwd, env: environment, encoding: "utf8", timeout: 3000, stdio: ["ignore", "pipe", "ignore"] }).trim();
84
+ if (realpathSync(top) !== realpathSync(workspace)) return;
85
+ const keys = execFileSync(executable, ["config", "--local", "--no-includes", "--null", "--name-only", "--list"], { cwd, env: environment, encoding: "utf8", timeout: 3000, maxBuffer: 64 * 1024, stdio: ["ignore", "pipe", "ignore"] }).split("\0").filter(Boolean);
86
+ const safe = /^(?:core\.(?:repositoryformatversion|filemode|bare|logallrefupdates|ignorecase|precomposeunicode|quotepath|autocrlf|safecrlf|symlinks|abbrev|hookspath|fsmonitor|editor)|user\.(?:name|email)|remote\..+\.(?:url|fetch|pushurl|glab-resolved-head)|branch\..+\.(?:remote|merge|rebase|vscode-merge-base)|commit\.gpgsign|tag\.gpgsign|extensions\.objectformat)$/i;
87
+ if (keys.some(key => !safe.test(key))) return;
88
+ // Preserve identity without loading executable global config into the Git
89
+ // sandbox. Git config queries do not execute hooks, aliases or helpers.
90
+ for (const field of ["name", "email"] as const) {
91
+ let fallback: string | undefined;
92
+ if (!keys.some(key => key.toLowerCase() === `user.${field}`)) {
93
+ const host = { ...environment };
94
+ delete host.GIT_CONFIG_GLOBAL;
95
+ try { fallback = execFileSync(executable, ["config", "--global", "--null", "--get", `user.${field}`], { cwd, env: host, encoding: "utf8", timeout: 3000, maxBuffer: 8192, stdio: ["ignore", "pipe", "ignore"] }).replace(/\0$/, ""); }
96
+ catch { /* Git reports a missing identity normally if none is configured. */ }
97
+ }
98
+ for (const role of ["AUTHOR", "COMMITTER"]) {
99
+ const key = `GIT_${role}_${field.toUpperCase()}`;
100
+ const value = process.env[key] ?? fallback;
101
+ if (value !== undefined) environment[key] = value;
102
+ }
103
+ }
104
+ const empty = process.platform === "win32" ? "NUL" : "/dev/null";
105
+ return { executable, environment, args: ["--no-pager", "-c", `core.hooksPath=${empty}`, "-c", "core.fsmonitor=false", "-c", "commit.gpgsign=false", "-c", "tag.gpgsign=false", "-c", "core.editor=false", "-c", "sequence.editor=false", "-c", "submodule.recurse=false", "-c", "rebase.backend=apply", ...args] };
106
+ }
@@ -1,3 +1,4 @@
1
+ import { prepareRootGit } from "./root-git.js";
1
2
  import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, rmdirSync, writeFileSync } from "node:fs";
2
3
  import { homedir, tmpdir } from "node:os";
3
4
  import { delimiter, dirname, join, resolve } from "node:path";
@@ -10,7 +11,7 @@ import type {
10
11
  } from "./types.js";
11
12
  import { WINDOWS_APPCONTAINER_HELPER } from "./windows-appcontainer.js";
12
13
  import { localExecutionShell } from "./shell.js";
13
- import { linkedWorktreeReadRoots, privateGitWriteRoot, macToolShimPath, workspaceRuntimeDirectory, workspaceRuntimeEnvironment, workspaceRuntimeTemporaryDirectory } from "./workspace-runtime.js";
14
+ import { linkedWorktreeReadRoots, privateGitWriteRoot, integrationGitWriteRoots, macToolShimPath, workspaceRuntimeDirectory, workspaceRuntimeEnvironment, workspaceRuntimeTemporaryDirectory } from "./workspace-runtime.js";
14
15
  import { NODE_PROXY_PRELOAD } from "./node-proxy-preload.generated.js";
15
16
  import { ExecutionBoundaryError, operationFailure } from "./failure.js";
16
17
 
@@ -23,6 +24,9 @@ export interface PlatformSandboxOptions {
23
24
  /** Host-owned, workspace-scoped home/cache/scratch. Omitted for strict,
24
25
  * stateless SDK sandboxes and remote runtimes. */
25
26
  workspaceStateRoot?: string;
27
+ /** Trusted Host opt-in for strictly parsed single Git commands in an authorized root workspace.
28
+ * Never applies to readonly/shared or isolated child workspaces. */
29
+ rootWorkspaceGitWrites?: boolean;
26
30
  /** Embedder-owned paths that stay writable inside the process sandbox.
27
31
  * These are not derived from model/tool grants and must only be supplied by
28
32
  * a trusted runtime boundary such as a per-Computer persistent tool store. */
@@ -63,6 +67,7 @@ abstract class CommandWrappingSandbox implements OsSandbox {
63
67
  trustedEnvironmentNames: string[] = [],
64
68
  networkProxy?: NetworkProxy | (() => NetworkProxy | undefined),
65
69
  workspaceStateRoot?: string,
70
+ private readonly rootWorkspaceGitWrites = false,
66
71
  ) {
67
72
  this.networkProxy = networkProxy;
68
73
  this.workspaceStateRoot = workspaceStateRoot;
@@ -86,7 +91,7 @@ abstract class CommandWrappingSandbox implements OsSandbox {
86
91
  },
87
92
  ): { executable: string; args: string[]; release?: () => void };
88
93
 
89
- createContext(input: Parameters<OsSandbox["createContext"]>[0]): SandboxExecutionContext {
94
+ createContext(input: Parameters<OsSandbox["createContext"]>[0], gitOperation = false): SandboxExecutionContext {
90
95
  const status = this.status();
91
96
  if (!status.available || status.provider === "none") {
92
97
  throw new Error(status.reason ?? "OS sandbox is unavailable");
@@ -95,10 +100,14 @@ abstract class CommandWrappingSandbox implements OsSandbox {
95
100
  ? workspaceRuntimeDirectory(this.workspaceStateRoot, input.workspace.root) : undefined;
96
101
  const runtimeTemp = runtimeDirectory ? workspaceRuntimeTemporaryDirectory(runtimeDirectory) : undefined;
97
102
  const privateGit = privateGitWriteRoot(input.workspace);
103
+ const rootGit = gitOperation && this.rootWorkspaceGitWrites && input.workspace.mode === "root"
104
+ && input.grant.filesystem?.write.some(path => canonicalPath(resolve(input.workspace.root, path)) === canonicalPath(input.workspace.root))
105
+ ? integrationGitWriteRoots(input.workspace.root) : [];
98
106
  const writablePaths = [...new Set([
99
107
  ...(input.grant.filesystem?.write ?? []),
100
108
  ...this.trustedWritablePaths,
101
109
  ...(privateGit ? [privateGit] : []),
110
+ ...rootGit,
102
111
  ...(runtimeDirectory ? [runtimeDirectory] : []),
103
112
  ...(runtimeTemp ? [runtimeTemp] : []),
104
113
  ].map((path) => canonicalPath(resolve(input.workspace.root, path))))];
@@ -114,7 +123,7 @@ abstract class CommandWrappingSandbox implements OsSandbox {
114
123
  && input.grant.filesystem?.write.some(path => canonicalPath(path) === canonicalPath(join(input.workspace.root, ".git")));
115
124
  const protectedPaths = [".git", ".zapcode"]
116
125
  .map((name) => canonicalPath(resolve(input.workspace.root, name)))
117
- .filter((path) => path !== privateGit && !(integrationGit && path === canonicalPath(join(input.workspace.root, ".git"))));
126
+ .filter((path) => path !== privateGit && !rootGit.includes(path) && !(integrationGit && path === canonicalPath(join(input.workspace.root, ".git"))));
118
127
  const provider = status.provider;
119
128
  const prepare = (
120
129
  executable: string,
@@ -184,6 +193,20 @@ abstract class CommandWrappingSandbox implements OsSandbox {
184
193
  networkAllowed,
185
194
  prepareCommand: prepare,
186
195
  prepareShell: (command, options) => {
196
+ if (!gitOperation && this.rootWorkspaceGitWrites && input.workspace.mode === "root"
197
+ && input.grant.filesystem?.write.some(path => canonicalPath(resolve(input.workspace.root, path)) === canonicalPath(input.workspace.root))) {
198
+ let git: ReturnType<typeof prepareRootGit>;
199
+ try { git = prepareRootGit(command, input.workspace.root, options.cwd); } catch { /* Unsupported repository: retain normal sandbox protection. */ }
200
+ if (git) {
201
+ const prepared = this.createContext(input, true).prepareCommand(git.executable, git.args, { ...options, environment: {} });
202
+ // Remove inherited GIT_* overrides after normal sandbox environment
203
+ // construction; untrusted tool environment cannot redirect Git.
204
+ if (process.platform !== "win32") prepared.env.PATH = `${dirname(git.executable)}:/usr/bin:/bin:/usr/sbin:/sbin`;
205
+ for (const key of Object.keys(prepared.env)) if (/^GIT_/i.test(key)) delete prepared.env[key];
206
+ for (const [key, value] of Object.entries(git.environment)) if (/^GIT_/i.test(key)) prepared.env[key] = value;
207
+ return prepared;
208
+ }
209
+ }
187
210
  const { executable, argsPrefix } = localExecutionShell();
188
211
  return prepare(executable, [...argsPrefix, command], options);
189
212
  },
@@ -196,7 +219,7 @@ class MacOsSeatbeltSandbox extends CommandWrappingSandbox {
196
219
  protected override readonly enforcesNetworkProxy = true;
197
220
 
198
221
  constructor(options: PlatformSandboxOptions) {
199
- super(options.tempRoot, options.trustedWritablePaths, options.trustedEnvironmentNames, options.networkProxy, options.workspaceStateRoot);
222
+ super(options.tempRoot, options.trustedWritablePaths, options.trustedEnvironmentNames, options.networkProxy, options.workspaceStateRoot, options.rootWorkspaceGitWrites);
200
223
  this.executable = options.sandboxExecPath ?? "/usr/bin/sandbox-exec";
201
224
  }
202
225
 
@@ -264,7 +287,7 @@ class LinuxBubblewrapSandbox extends CommandWrappingSandbox {
264
287
  private readonly executable: string;
265
288
 
266
289
  constructor(options: PlatformSandboxOptions) {
267
- super(options.tempRoot, options.trustedWritablePaths, options.trustedEnvironmentNames, undefined, options.workspaceStateRoot);
290
+ super(options.tempRoot, options.trustedWritablePaths, options.trustedEnvironmentNames, undefined, options.workspaceStateRoot, options.rootWorkspaceGitWrites);
268
291
  this.executable = options.bwrapPath ?? findOnPath("bwrap") ?? "bwrap";
269
292
  }
270
293
 
@@ -366,7 +389,7 @@ class WindowsHelperSandbox extends CommandWrappingSandbox {
366
389
  private readonly trace: boolean;
367
390
 
368
391
  constructor(options: PlatformSandboxOptions) {
369
- super(options.tempRoot, options.trustedWritablePaths, options.trustedEnvironmentNames, undefined, options.workspaceStateRoot);
392
+ super(options.tempRoot, options.trustedWritablePaths, options.trustedEnvironmentNames, undefined, options.workspaceStateRoot, options.rootWorkspaceGitWrites);
370
393
  this.executable = options.windowsHelperPath
371
394
  ?? join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
372
395
  this.trace = options.trace === true;
@@ -97,14 +97,14 @@ export class DefaultToolPolicyEngine implements ToolPolicyEngine {
97
97
  if (permission === "confirm") {
98
98
  return {
99
99
  decision: "ask",
100
- request: { call: request.call, effects: request.effects, proposedGrant: grant },
100
+ request: { call: request.call, effects: request.effects, proposedGrant: grant, grantTtlMs: this.grantTtlMs },
101
101
  reason: "tool requires confirmation",
102
102
  };
103
103
  }
104
104
  if (request.effects.confidence === "unknown" && this.askOnUnknownEffects) {
105
105
  return {
106
106
  decision: "ask",
107
- request: { call: request.call, effects: request.effects, proposedGrant: grant },
107
+ request: { call: request.call, effects: request.effects, proposedGrant: grant, grantTtlMs: this.grantTtlMs },
108
108
  reason: "tool effects are unknown",
109
109
  };
110
110
  }
@@ -52,6 +52,9 @@ export interface ApprovalRequest {
52
52
  call: ResolvedToolCall;
53
53
  effects: ToolEffects;
54
54
  proposedGrant: CapabilityGrant;
55
+ /** Host policy opt-in: start this grant lifetime after approval completes.
56
+ * Omitted custom policies retain their absolute proposedGrant expiry. */
57
+ grantTtlMs?: number;
55
58
  }
56
59
 
57
60
  export interface PolicyRequest {
@@ -803,9 +803,18 @@ export class ToolExecutor {
803
803
  failure: operationFailure("APPROVAL_REQUIRED", "approval", context?.toolCallId),
804
804
  };
805
805
  }
806
- return this.requestApproval(tool, name, parsedArgs, effects, signal, context).then((result) => (
807
- result === true ? authorized() : result
808
- ));
806
+ return this.requestApproval(tool, name, parsedArgs, effects, signal, context).then((result) => {
807
+ if (result !== true) return result;
808
+ const authorization = authorized();
809
+ const ttl = policy.request.grantTtlMs;
810
+ // Human/approval-queue wait consumes no execution authority lifetime.
811
+ // Only a policy that explicitly supplies a duration may activate a fresh
812
+ // expiry. Absolute custom-policy expiries and task deadlines stay intact.
813
+ if (typeof ttl === "number" && Number.isFinite(ttl) && ttl > 0) {
814
+ authorization.grant = { ...grant, expiresAt: Date.now() + ttl };
815
+ }
816
+ return authorization;
817
+ });
809
818
  }
810
819
 
811
820
  private async requestApproval(