zapagent 1.14.27 → 1.14.29

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.
@@ -1,44 +1,40 @@
1
1
  /** @jsxImportSource react */
2
2
  import { useEffect, useRef, useState } from "react"
3
+ import { stripVTControlCharacters } from "node:util"
3
4
  import { Text, useInput } from "ink"
4
- import { openAuthBrowser, saveCodexCredentials, startCodexBrowserLogin, startCodexDeviceLogin } from "../codex-auth.js"
5
+ import { runCodexAuth } from "../codex-auth.js"
5
6
  import { DialogFrame } from "./dialog-frame.js"
6
7
  import { PickerDialog } from "./dialog-picker.js"
7
8
  import { c } from "./theme.js"
8
9
 
9
10
  export function CodexLoginDialog({ onSuccess, onCancel }: { onSuccess: () => void; onCancel: () => void }) {
10
- const [method, setMethod] = useState<"browser" | "device" | null>(null)
11
- const [details, setDetails] = useState<{ url: string; instructions: string } | null>(null)
11
+ const [method, setMethod] = useState<"browser" | "device" | "existing" | null>(null)
12
+ const [details, setDetails] = useState("")
12
13
  const [error, setError] = useState("")
13
- const callbacks = useRef({ onSuccess, onCancel })
14
- callbacks.current = { onSuccess, onCancel }
14
+ const callbacks = useRef(onSuccess)
15
+ callbacks.current = onSuccess
15
16
  useInput((_input, key) => { if (method && key.escape) setMethod(null) })
16
17
  useEffect(() => {
17
18
  if (!method) return
18
19
  const controller = new AbortController()
19
- setDetails(null); setError("")
20
+ setDetails(""); setError("")
20
21
  void (async () => {
21
- const login = method === "browser" ? await startCodexBrowserLogin({ signal: controller.signal }) : await startCodexDeviceLogin(controller.signal)
22
- if (controller.signal.aborted) { login.cancel(); return }
23
- setDetails({ url: login.url, instructions: login.instructions })
24
- openAuthBrowser(login.url)
25
- const credentials = await login.complete
22
+ const status = await runCodexAuth(method === "existing" ? "status" : "login", { device: method === "device", signal: controller.signal,
23
+ onOutput: text => { if (!controller.signal.aborted) setDetails(previous => (previous + text).slice(-8192)) } })
26
24
  if (controller.signal.aborted) return
27
- await saveCodexCredentials(credentials, undefined, controller.signal)
28
- if (controller.signal.aborted) return
29
- callbacks.current.onSuccess()
25
+ if (status !== 0) throw new Error("Codex login did not complete. Run codex login to retry.")
26
+ callbacks.current()
30
27
  })().catch(error => { if (!controller.signal.aborted) setError(error instanceof Error ? error.message : "Codex login failed.") })
31
28
  return () => controller.abort()
32
29
  }, [method])
33
30
  if (!method) return <PickerDialog title="OpenAI Codex · sign in with ChatGPT"
34
- options={[{ id: "browser", label: "Browser login", meta: "opens ChatGPT sign-in · local callback on port 1455" },
31
+ options={[{ id: "existing", label: "Use existing Codex login", meta: "checks the local CLI session" },
32
+ { id: "browser", label: "Browser login", meta: "opens ChatGPT sign-in · local callback on port 1455" },
35
33
  { id: "device", label: "Device code", meta: "for SSH, headless hosts, or a busy callback port" }]}
36
- onCancel={onCancel} onSelect={id => setMethod(id as "browser" | "device")} />
34
+ onCancel={onCancel} onSelect={id => setMethod(id as "browser" | "device" | "existing")} />
37
35
  return <DialogFrame title="OpenAI Codex · sign in with ChatGPT" hint="esc back / cancel login">
38
36
  {error ? <Text color={c.warning}>{error}</Text> : <>
39
- <Text>{details?.instructions ?? "Starting Codex login…"}</Text>
40
- {details && <Text color={c.accent}>{details.url}</Text>}
41
- <Text color={c.text.faint}>If the browser did not open, open this URL manually. Waiting for authorization…</Text>
37
+ <Text>{stripVTControlCharacters(details) || "Starting the official Codex login…"}</Text>
42
38
  </>}
43
39
  </DialogFrame>
44
40
  }
@@ -7,7 +7,7 @@ import { modelReasoningFor } from "../../zapsdk/core/reasoning-effort.js"
7
7
  import { useEffect, useState } from "react"
8
8
  import { discoverCodexModels } from "../codex-provider.js"
9
9
  import {
10
- effortModel,
10
+ agentManagingModel, effortModel,
11
11
  upsertProvider,
12
12
  getActiveProvider,
13
13
  getEffort,
@@ -53,6 +53,8 @@ export function ModeDialog({ config, onCommit, onCancel }: DialogProps) {
53
53
  // ── Effort picker ────────────────────────────────────────────────────────
54
54
  export function EffortDialog({ config, onCommit, onCancel }: DialogProps) {
55
55
  const provider = getActiveProvider(config)
56
+ const agent = agentManagingModel(config)
57
+ if (agent) return <PickerDialog title="Reasoning effort" options={[{ id: "agent", label: `Managed by ${agent}`, disabled: true }]} onCancel={onCancel} onSelect={onCancel} />
56
58
  // A changed connection remounts the fetch and picker, including its cursor.
57
59
  return <ModelEffortDialog key={provider ? `${provider.id}:${effortModel(config, provider)}` : "none"}
58
60
  config={config} onCommit={onCommit} onCancel={onCancel} />
@@ -2,7 +2,7 @@
2
2
  import { useRef, useState } from "react"
3
3
  import { Box, Text, useInput } from "ink"
4
4
  import { randomUUID } from "node:crypto"
5
- import { buildConnectedProvider, inferLegacyContextWindowMode, presetForConnection, removeProvider, upsertProvider,
5
+ import { conversationAgentId, buildConnectedProvider, inferLegacyContextWindowMode, presetForConnection, removeProvider, upsertProvider,
6
6
  type AppConfig, type ContextWindowMode, type Provider, type ProviderProtocol } from "../config.js"
7
7
  import { ProviderDirectory } from "./provider-directory.js"
8
8
  import { DialogFrame } from "./dialog-frame.js"
@@ -15,7 +15,7 @@ import { ContextWindowDialog } from "./dialog-context-window.js"
15
15
  import { CodexLoginDialog } from "./dialog-codex-login.js"
16
16
  import { connectCodexProvider } from "../codex-provider.js"
17
17
 
18
- interface Props { config: AppConfig; onSave: (next: AppConfig) => void; onCommit: (next: AppConfig) => void; onCancel: () => void }
18
+ interface Props { onAgentSelected?: (message: string) => void; config: AppConfig; onSave: (next: AppConfig) => void; onCommit: (next: AppConfig) => void; onCancel: () => void }
19
19
  type Draft = { name: string; baseURL: string; apiKey: string; protocol: ProviderProtocol;
20
20
  authMode: "none" | "api-key"; catalogProviderId?: string; existing?: Provider;
21
21
  contextWindow?: number; contextWindowMode?: ContextWindowMode }
@@ -46,7 +46,7 @@ export function saveConnection(config: AppConfig, draft: Draft): AppConfig {
46
46
  }
47
47
 
48
48
  /** Persist the connection first, then guide new connections through model selection. */
49
- export function ConnectDialog({ config, onSave, onCommit, onCancel }: Props) {
49
+ export function ConnectDialog({ onAgentSelected, config, onSave, onCommit, onCancel }: Props) {
50
50
  const [step, setStep] = useState<Step>("connections")
51
51
  const [index, setIndex] = useState(0)
52
52
  const [deleting, setDeleting] = useState(false)
@@ -91,9 +91,10 @@ export function ConnectDialog({ config, onSave, onCommit, onCancel }: Props) {
91
91
  hint={deleting ? "d confirm removal · esc cancel" : "↑↓ navigate · enter/e edit · m models · d remove · esc close"}>
92
92
  <Text color={c.text.faint}>Add a connection, then choose its model. Press m to manage models for an existing connection.</Text>
93
93
  <Box flexDirection="column" marginTop={1}>
94
+ {conversationAgentId(config) === "claude-code" && <Text color={c.accent}>Claude Code · active local CLI</Text>}
94
95
  {config.providers.map((provider, i) => <Box key={provider.id} flexDirection="column">
95
96
  <Text color={i === index ? c.accent : c.text.primary}>{`${i === index ? "›" : " "} ${provider.name || "Unnamed connection"}`}</Text>
96
- <Text color={c.text.faint}>{` ${provider.authMode === "codex-oauth" ? "Codex Responses · ChatGPT OAuth" : `${provider.protocol ?? "openai"} · ${provider.apiKey ? "API key stored" : "no key"}`} · ${provider.models.length} saved models`}</Text>
97
+ <Text color={c.text.faint}>{` ${provider.authMode === "codex-oauth" ? "Official Codex agent · local CLI login" : `${provider.protocol ?? "openai"} · ${provider.apiKey ? "API key stored" : "no key"}`} · ${provider.models.length} saved models`}</Text>
97
98
  <Text color={c.text.faint}>{` ${provider.baseURL}`}</Text>
98
99
  </Box>)}
99
100
  <Text color={index === config.providers.length ? c.accent : c.text.primary}>{`${index === config.providers.length ? "›" : " "} + New connection`}</Text>
@@ -107,7 +108,10 @@ export function ConnectDialog({ config, onSave, onCommit, onCancel }: Props) {
107
108
  setModelTarget({ id: result.provider.id, setup: true })
108
109
  }} />
109
110
 
110
- if (step === "preset") return <ProviderDirectory onCodex={() => setStep("codex")}
111
+ if (step === "preset") return <ProviderDirectory onCodex={() => setStep("codex")} onClaude={() => {
112
+ onCommit({ ...config, activeAgent: undefined, subscriptionAgent: "claude-code" })
113
+ onAgentSelected?.("agent → Claude Code")
114
+ }}
111
115
  onCancel={() => setStep("connections")} onSelect={provider => {
112
116
  setDraft({ catalogProviderId: provider?.id, name: provider?.name ?? "", baseURL: provider?.api ?? "", apiKey: "",
113
117
  protocol: provider?.protocol ?? "openai", authMode: "api-key" })
@@ -1,7 +1,7 @@
1
1
  /** @jsxImportSource react */
2
2
  import { useEffect, useRef, useState } from "react"
3
3
  import { Box, Text, useInput } from "ink"
4
- import { inferLegacyContextWindowMode, resolveProviderContextWindow, upsertProvider, type AppConfig } from "../config.js"
4
+ import { agentManagingModel, inferLegacyContextWindowMode, resolveProviderContextWindow, upsertProvider, type AppConfig } from "../config.js"
5
5
  import { associateModelMetadata, describeCatalogRow, selectCatalogModel } from "../provider-catalog.js"
6
6
  import { configuredModelRows, discoverConfiguredModels, modelCatalogKey, savedConnectionCatalogs, type ConnectionCatalog, type ConnectionModelRow } from "../model-catalog.js"
7
7
  import { DialogFrame } from "./dialog-frame.js"
@@ -96,8 +96,11 @@ export function ModelDialog({ config, initialProviderId, setup = false, onSave,
96
96
  }
97
97
  })
98
98
 
99
+ const agent = agentManagingModel(config)
100
+ const agentModel = agent === "claude-code" ? "Claude Code · model selected by local CLI" : agent ? `${agent} · model selected by agent` : undefined
99
101
  if (!provider) return <DialogFrame title="Models · /model" hint="esc close">
100
- <Text>No connection configured. Use /connect to create one first.</Text>
102
+ {agentModel && <Text>Current: {agentModel}</Text>}
103
+ <Text>No provider models configured. Use /connect to add a model provider.</Text>
101
104
  </DialogFrame>
102
105
  if (phase === "metadata" && target && targetProvider) return <ModelMetadataDialog modelId={target.id}
103
106
  onCancel={() => setPhase("models")} onSelect={metadata => {
@@ -141,7 +144,7 @@ export function ModelDialog({ config, initialProviderId, setup = false, onSave,
141
144
  return <DialogFrame title={`${setup ? "Choose a model" : "Models"} · ${providerFilter === null ? "All connections" : provider.name || provider.baseURL}`}
142
145
  hint={setup ? "↑↓ navigate · enter select and finish · m metadata · c context · / filter · t manual · esc choose later" : "↑↓ navigate · enter select · / search · p filter connections · m metadata · c context · r refresh · t manual · esc close"}>
143
146
  {setup && <Text color={c.accent}>Connection saved. Choose a model to use it, or press esc to choose later with /model.</Text>}
144
- <Text color={c.text.faint}>{truncateToWidth(`Current: ${config.active.model || "none"} · ${activeProvider?.name || "none"}`, width)}</Text>
147
+ <Text color={c.text.faint}>{truncateToWidth(`Current: ${agentModel ?? `${config.active.model || "none"} · ${activeProvider?.name || "none"}`}`, width)}</Text>
145
148
  <Text color={c.text.faint}>{truncateToWidth(`${shown.length} models · ${scopedCatalogs.length} connections${loading ? ` · ${loading} discovering…` : ""}${failed ? ` · ${failed} discovery unavailable` : ""}${query ? ` · filter: ${query}` : ""}`, width)}</Text>
146
149
  <Text color={c.text.faint}>{truncateToWidth((provider.contextWindowMode ?? inferLegacyContextWindowMode(provider)) === "manual"
147
150
  ? `${provider.name}: manual context ${provider.contextWindow.toLocaleString("en-US")} tokens · c to change`
@@ -149,7 +152,7 @@ export function ModelDialog({ config, initialProviderId, setup = false, onSave,
149
152
  {error && <Text color={c.warning}>{truncateToWidth(`${provider.name}: ${error}`, width)}</Text>}
150
153
  <Box flexDirection="column" marginTop={1}>
151
154
  {shown.slice(start, start + count).map((row, i) => <Box key={modelCatalogKey(row.provider.id, row.id)} flexDirection="column">
152
- <Text color={start + i === selectedIndex ? c.accent : c.text.primary} bold={start + i === selectedIndex}>{truncateToWidth(`${start + i === selectedIndex ? "›" : " "} ${row.id}${row.provider.id === config.active.providerId && row.id === config.active.model ? " (current)" : ""}`, width)}</Text>
155
+ <Text color={start + i === selectedIndex ? c.accent : c.text.primary} bold={start + i === selectedIndex}>{truncateToWidth(`${start + i === selectedIndex ? "›" : " "} ${row.id}${!agent && row.provider.id === config.active.providerId && row.id === config.active.model ? " (current)" : ""}`, width)}</Text>
153
156
  <Text color={c.text.faint}>{truncateToWidth(` ${row.provider.name || row.provider.id} · ${row.provider.baseURL}`, width)}</Text>
154
157
  <Text color={c.text.faint}>{truncateToWidth(` ${describeCatalogRow(row)}`, width)}</Text>
155
158
  </Box>)}
@@ -10,11 +10,11 @@ import { useTermWidth } from "./term-width.js"
10
10
  import { truncateToWidth } from "./truncate.js"
11
11
  import { c } from "./theme.js"
12
12
 
13
- interface Props { onSelect: (provider: ModelsDevConnection | null) => void; onCancel: () => void; metadataOnly?: boolean; onCodex?: () => void }
13
+ interface Props { onSelect: (provider: ModelsDevConnection | null) => void; onCancel: () => void; metadataOnly?: boolean; onCodex?: () => void; onClaude?: () => void }
14
14
 
15
15
  /** Public directory data supplies vendor names and endpoints; adapters only
16
16
  * constrain which wire protocols the installed runtime actually supports. */
17
- export function ProviderDirectory({ onSelect, onCancel, metadataOnly = false, onCodex }: Props) {
17
+ export function ProviderDirectory({ onSelect, onCancel, metadataOnly = false, onCodex, onClaude }: Props) {
18
18
  const [providers, setProviders] = useState<ModelsDevConnection[]>([])
19
19
  const [loading, setLoading] = useState(true)
20
20
  const [error, setError] = useState("")
@@ -60,13 +60,15 @@ export function ProviderDirectory({ onSelect, onCancel, metadataOnly = false, on
60
60
  maxRows={Math.max(3, Math.min(10, (process.stdout.rows ?? 24) - 15))}
61
61
  hint="↑↓ select · enter configure · / search · r reload · esc back"
62
62
  options={[...(!metadataOnly ? [{ id: "__custom", label: "Custom endpoint", meta: "configure manually" }] : []),
63
- ...(!metadataOnly && onCodex ? [{ id: "__codex", label: "OpenAI Codex (ChatGPT)", meta: "OAuth · sign in with ChatGPT" }] : []),
63
+ ...(!metadataOnly && onCodex ? [{ id: "__codex", label: "OpenAI Codex (ChatGPT)", meta: "official agent · sign in with Codex CLI" }] : []),
64
+ ...(!metadataOnly && onClaude ? [{ id: "__claude", label: "Claude Code", meta: "official agent · sign in with claude auth login" }] : []),
64
65
  ...visible.map(provider => ({ id: `catalog:${provider.id}`, label: truncateToWidth(provider.name, labelWidth),
65
66
  meta: truncateToWidth(provider.protocol ? `${provider.protocol}${provider.api ? " · endpoint provided" : " · enter endpoint"}` : "unsupported adapter", width - labelWidth - 2),
66
67
  disabled: !metadataOnly && !provider.protocol }))]}
67
68
  onCancel={onCancel} onSelect={id => {
68
69
  if (id === "__custom") onSelect(null)
69
70
  else if (id === "__codex") onCodex?.()
71
+ else if (id === "__claude") onClaude?.()
70
72
  else {
71
73
  const provider = providers.find(item => item.id === id.slice("catalog:".length))
72
74
  if (provider && (metadataOnly || provider.protocol)) onSelect(provider)
@@ -179,8 +179,14 @@ export function contentText(block: ContentBlock | undefined | null): string {
179
179
  /** Usage from a prompt response or `_meta`, in zap's shape. */
180
180
  export function acpUsage(usage: Usage | null | undefined): TokenUsage | undefined {
181
181
  if (!usage) return undefined;
182
+ // Some ACP agents include cached tokens in inputTokens. Codex ACP reports
183
+ // disjoint fresh/read/write counts, whose sum reconciles with totalTokens.
184
+ const cached = (usage.cachedReadTokens ?? 0) + (usage.cachedWriteTokens ?? 0);
185
+ const sum = usage.inputTokens + cached + usage.outputTokens;
186
+ const disjoint = usage.inputTokens < cached || usage.totalTokens === sum
187
+ || usage.totalTokens === sum + (usage.thoughtTokens ?? 0);
182
188
  return {
183
- inputTokens: Math.max(0, usage.inputTokens - (usage.cachedReadTokens ?? 0)),
189
+ inputTokens: disjoint ? usage.inputTokens : Math.max(0, usage.inputTokens - cached),
184
190
  outputTokens: usage.outputTokens,
185
191
  cacheReadInputTokens: usage.cachedReadTokens ?? undefined,
186
192
  cacheCreationInputTokens: usage.cachedWriteTokens ?? undefined,
@@ -1,5 +1,5 @@
1
1
  import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
2
- import { dirname, isAbsolute, join, sep } from "node:path";
2
+ import { dirname, isAbsolute, join, resolve, sep } from "node:path";
3
3
  import { RequestError, type PermissionOption, type RequestPermissionRequest, type RequestPermissionResponse } from "@agentclientprotocol/sdk";
4
4
  import type { ApprovalCallback, ApprovalContext, ApprovalResponse } from "../tools/executor.js";
5
5
  import { resolveToolPathCanonical } from "../builtin-tools/filesystem.js";
@@ -45,7 +45,17 @@ export class AcpWorkspace {
45
45
  }
46
46
 
47
47
  contains(path: string): boolean { return within(path, this.root); }
48
- isProtected(path: string): boolean { return this.protectedRoots.some(root => within(path, root)); }
48
+ isProtected(path: string): boolean {
49
+ // Reserve control-directory spellings even when a new path has no
50
+ // on-disk casing for realpath to recover on macOS or Windows.
51
+ const fold = process.platform === "win32" || process.platform === "darwin";
52
+ return this.protectedRoots.some(root => fold ? within(path.toLowerCase(), root.toLowerCase()) : within(path, root));
53
+ }
54
+
55
+ protectsWrite(path: string): boolean {
56
+ const absolute = resolve(this.root, path);
57
+ return this.isProtected(absolute) || this.isProtected(this.resolve(absolute));
58
+ }
49
59
  }
50
60
 
51
61
  function within(path: string, root: string): boolean {
@@ -86,7 +96,11 @@ export function createAcpHostHandlers(policy: AcpHostPolicy): AcpHostHandlers {
86
96
  // must be answered "cancelled", not rejected.
87
97
  const live = signalFor(signal);
88
98
  if (live.aborted) return { outcome: { outcome: "cancelled" } };
89
- const response = await approve(permissionTarget(policy.agentId, request, workspace), live);
99
+ const diffs = tool.content?.flatMap(item => item.type === "diff" ? [item.path] : []) ?? [];
100
+ const mutation = tool.kind === "edit" || tool.kind === "delete" || tool.kind === "move";
101
+ const paths = mutation ? [...diffs, ...(tool.locations ?? []).map(location => location.path)] : diffs;
102
+ const response = paths.some(path => workspace.protectsWrite(path))
103
+ ? false : await approve(permissionTarget(policy.agentId, request, workspace), live);
90
104
  if (live.aborted) return { outcome: { outcome: "cancelled" } };
91
105
  const allowed = response === true;
92
106
  decisions.push({ title, kind: tool.kind ?? undefined, allowed });
@@ -116,7 +130,7 @@ export function createAcpHostHandlers(policy: AcpHostPolicy): AcpHostHandlers {
116
130
 
117
131
  async writeTextFile(request, signal) {
118
132
  const path = workspace.resolve(request.path);
119
- if (workspace.isProtected(path)) {
133
+ if (workspace.isProtected(request.path) || workspace.isProtected(path)) {
120
134
  throw RequestError.internalError(undefined, "denied by zap: .git and .zapcode are protected and cannot be written");
121
135
  }
122
136
  const target: ApprovalTarget = workspace.contains(path)
@@ -84,6 +84,7 @@ export class AcpAgentSession {
84
84
  }
85
85
  const mode = options.mode ?? spec.mode;
86
86
  if (mode) await session.attempt(`mode ${mode}`, () => connection.setMode(session.sessionId, mode));
87
+ if (spec.requireSettings && session.warnings.length) throw new Error(session.warnings.join("; "));
87
88
  return session;
88
89
  } catch (error) {
89
90
  await connection.close();
@@ -26,6 +26,8 @@ export interface AcpAgentSpec {
26
26
  model?: string;
27
27
  /** Session mode to select after session/new (`session/set_mode`). */
28
28
  mode?: string;
29
+ /** Reject the session if a requested mode, model or config option is refused. */
30
+ requireSettings?: boolean;
29
31
  /** Session config options to apply after session/new
30
32
  * (`session/set_config_option`), e.g. `{ thought_level: "high" }`. */
31
33
  config?: Record<string, string>;
@@ -516,6 +516,7 @@ export class LoopAgent {
516
516
  private storageSessionId: string;
517
517
  private storageProjectCwd: string;
518
518
  private sessionId: string;
519
+ private readonly providerSessionId: string;
519
520
  private onRunStart?: LoopAgentOptions["onRunStart"];
520
521
  private onRunEnd?: (ctx: { turnStartIndex: number; sessionId: string }) => Promise<void>;
521
522
  // onRetry surfaces a system log via the observation event bus so the
@@ -601,6 +602,7 @@ export class LoopAgent {
601
602
  this.storageSessionId = options.storageSessionId ?? randomUUID();
602
603
  this.storageProjectCwd = options.storageProjectCwd ?? process.cwd();
603
604
  this.sessionId = options.sessionId ?? "default";
605
+ this.providerSessionId = options.sessionId ?? this.storageSessionId;
604
606
  this.onRunStart = options.onRunStart;
605
607
  this.onRunEnd = options.onRunEnd;
606
608
  this.contextWindow = nonNegativeInteger(options.contextWindow);
@@ -2270,7 +2272,7 @@ export class LoopAgent {
2270
2272
  private providerCallOptions(step: number, maxOutputTokens: number | undefined, signal?: AbortSignal): LLMCallOptions {
2271
2273
  const requestId = nextContentId("request");
2272
2274
  let observedAttempt: number | undefined;
2273
- const options: LLMCallOptions = { maxOutputTokens, signal,
2275
+ const options: LLMCallOptions = { maxOutputTokens, signal, sessionId: this.providerSessionId,
2274
2276
  deadline: signal ? this.providerDeadlines.get(signal) : undefined, onRequestEvent: request => {
2275
2277
  if (request.cacheShape && observedAttempt !== request.attempt) {
2276
2278
  observedAttempt = request.attempt;
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import type { LLMProvider } from "../core/llm.js";
2
3
  import type { Message, TokenUsage } from "../core/types.js";
3
4
  import {
@@ -52,7 +53,8 @@ export class SingleCallAgent {
52
53
 
53
54
  // First LLM call
54
55
  const tools = this.registry.definitions();
55
- const response = await this.provider.call(messages, tools);
56
+ const options = { sessionId: this.sessionId ?? randomUUID() };
57
+ const response = await this.provider.call(messages, tools, options);
56
58
  accumulateTokenUsage(totalUsage, response.usage);
57
59
 
58
60
  // If no tool calls, return directly
@@ -82,7 +84,7 @@ export class SingleCallAgent {
82
84
  }
83
85
 
84
86
  // Second LLM call with tool results
85
- const finalResponse = await this.provider.call(messages, tools);
87
+ const finalResponse = await this.provider.call(messages, tools, options);
86
88
  accumulateTokenUsage(totalUsage, finalResponse.usage);
87
89
 
88
90
  return { text: finalResponse.text, toolResults, totalUsage };
@@ -68,6 +68,8 @@ export interface LLMCallOptions {
68
68
  onRequestEvent?: (event: ProviderRequestEvent) => void;
69
69
  /** RetryProvider supplies this metadata to each adapter attempt. */
70
70
  requestAttempt?: { attempt: number; maxAttempts: number };
71
+ /** Conversation identity for providers with session-scoped prompt cache routing. */
72
+ sessionId?: string;
71
73
  /** Host-local logical request identity, shared by retry attempts. */
72
74
  requestId?: string;
73
75
  }
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto";
1
2
  import OpenAI from "openai";
2
3
  import type { Response as APIResponse, ResponseInputItem, ResponseCreateParams } from "openai/resources/responses/responses";
3
4
  import type { LLMProvider, LLMCallOptions } from "../llm.js";
@@ -41,7 +42,7 @@ export class OpenAIResponsesProvider implements LLMProvider {
41
42
  setVisionSupported(supported: boolean): void { this.formatter.setVisionSupported(supported); }
42
43
  getImageTokenContext(options?: LLMCallOptions) { return this.formatter.getImageTokenContext(options); }
43
44
 
44
- private async requestClient(request: ProviderRequest): Promise<OpenAI> {
45
+ private async requestClient(request: ProviderRequest, sessionAffinity?: string): Promise<OpenAI> {
45
46
  const codex = this.options.codex;
46
47
  if (!codex) return this.client;
47
48
  const credentials = await request.wait(codex.getCredentials(request.signal));
@@ -49,6 +50,7 @@ export class OpenAIResponsesProvider implements LLMProvider {
49
50
  // OAuth tokens are never sent to a user-configurable endpoint/client.
50
51
  return new OpenAI({ baseURL: CODEX_RESPONSES_BASE_URL, apiKey: credentials.accessToken, maxRetries: 0,
51
52
  fetch: codex.fetch, defaultHeaders: { originator: "zap",
53
+ ...(sessionAffinity ? { "session-id": sessionAffinity } : {}),
52
54
  ...(credentials.accountId ? { "ChatGPT-Account-ID": credentials.accountId } : {}) } });
53
55
  }
54
56
 
@@ -121,7 +123,7 @@ export class OpenAIResponsesProvider implements LLMProvider {
121
123
  model: opts?.model ?? this.options.model,
122
124
  max_output_tokens: opts?.maxOutputTokens ?? this.options.maxTokens ?? 4096,
123
125
  ...extra,
124
- input: this.serializeMessages(messages),
126
+ input: [],
125
127
  tools: tools?.length ? [...tools].sort((a, b) => a.name.localeCompare(b.name)).map(tool => ({
126
128
  type: "function", name: tool.name, description: tool.description, strict: false,
127
129
  parameters: canonicalizeJsonSchema(tool.rawSchema ?? zodToJsonSchema(tool.parameters)),
@@ -142,13 +144,19 @@ export class OpenAIResponsesProvider implements LLMProvider {
142
144
  else delete body.reasoning;
143
145
  let leadingSystemEnd = 0;
144
146
  while (messages[leadingSystemEnd]?.role === "system") leadingSystemEnd++;
145
- body.instructions = messages.slice(0, leadingSystemEnd).map(message => stripBoundary(message.content)).join("\n\n");
146
- body.input = this.serializeMessages(messages.slice(leadingSystemEnd));
147
+ // GPT-6.2 renders top-level instructions after the cacheable input.
148
+ const instructions = messages.slice(0, leadingSystemEnd).map(message => stripBoundary(message.content)).join("\n\n");
149
+ const input = this.serializeMessages(messages.slice(leadingSystemEnd));
150
+ if (instructions) input.unshift({ role: "developer", content: instructions });
151
+ body.input = input;
152
+ body.instructions = "";
147
153
  // Codex requires SSE and rejects generation controls accepted by the API.
148
154
  delete body.max_output_tokens;
149
155
  delete body.temperature;
150
156
  delete body.top_p;
151
157
  body.stream = true;
158
+ } else {
159
+ body.input = this.serializeMessages(messages);
152
160
  }
153
161
  return body;
154
162
  }
@@ -183,12 +191,18 @@ export class OpenAIResponsesProvider implements LLMProvider {
183
191
  }
184
192
  const usage = response.usage;
185
193
  const cached = usage?.input_tokens_details?.cached_tokens;
194
+ const written = usage?.input_tokens_details?.cache_write_tokens;
186
195
  return {
187
196
  type: toolCalls.length ? "tool_call" : "text", text,
188
197
  toolCalls: toolCalls.length ? toolCalls : undefined,
189
198
  finishReason: truncated ? "length" : toolCalls.length ? "tool_calls" : "stop",
190
- usage: { inputTokens: Math.max(0, (usage?.input_tokens ?? 0) - (cached ?? 0)), outputTokens: usage?.output_tokens ?? 0,
191
- providerUsageReported: !!usage, ...(cached !== undefined ? { cacheReadInputTokens: cached } : {}) },
199
+ usage: {
200
+ inputTokens: Math.max(0, (usage?.input_tokens ?? 0) - (cached ?? 0) - (written ?? 0)),
201
+ outputTokens: usage?.output_tokens ?? 0,
202
+ providerUsageReported: !!usage,
203
+ ...(cached !== undefined ? { cacheReadInputTokens: cached } : {}),
204
+ ...(written !== undefined ? { cacheCreationInputTokens: written } : {}),
205
+ },
192
206
  raw: layout.length ? { openaiResponses: { items: layout } } : undefined,
193
207
  };
194
208
  }
@@ -237,8 +251,12 @@ export class OpenAIResponsesProvider implements LLMProvider {
237
251
 
238
252
  private async *streamResponse(messages: Message[], tools: ToolDefinition[] | undefined, opts: LLMCallOptions | undefined, request: ProviderRequest): AsyncIterable<LLMChunk> {
239
253
  const body = this.body(messages, tools, opts, true);
254
+ // Derive both routing fields from the same header-safe conversation identity.
255
+ const sessionAffinity = this.options.codex && opts?.sessionId
256
+ ? createHash("sha256").update(opts.sessionId).digest("hex") : undefined;
257
+ if (sessionAffinity && body.prompt_cache_key === undefined) body.prompt_cache_key = sessionAffinity;
240
258
  request.measureBody(body, this.options.maxRequestBytes, `responses:${this.options.codex ? CODEX_RESPONSES_BASE_URL : this.options.baseURL ?? this.options.client?.baseURL ?? "default"}`);
241
- const client = await this.requestClient(request);
259
+ const client = await this.requestClient(request, sessionAffinity);
242
260
  const stream = await request.wait(client.responses.create({ ...body, stream: true }, { signal: request.signal, maxRetries: 0 }));
243
261
  request.responseReceived();
244
262
  let emittedText = "";
@@ -1,4 +1,5 @@
1
- import { spawn, type ChildProcess } from "node:child_process";
1
+ import { join } from "node:path";
2
+ import { spawnSync, spawn, type ChildProcess } from "node:child_process";
2
3
  import { localExecutionShell } from "./shell.js";
3
4
  import { readProcessTable, snapshotDescendants } from "./process-tree.js";
4
5
  import type {
@@ -135,7 +136,13 @@ export function terminateProcessTree(
135
136
  let delivered = false;
136
137
  const killChild = () => child.exitCode === null && child.signalCode === null && child.kill(signal);
137
138
  try {
138
- if (process.platform === "win32" || !child.pid) delivered = killChild();
139
+ if (process.platform === "win32" && (signal === "SIGTERM" || signal === "SIGKILL") && child.pid && child.exitCode === null && child.signalCode === null) {
140
+ const systemRoot = process.env.SystemRoot ?? "C:\\Windows";
141
+ const result = spawnSync(join(systemRoot, "System32", "taskkill.exe"), ["/PID", String(child.pid), "/T", "/F"], {
142
+ stdio: "ignore", windowsHide: true, timeout: 3000,
143
+ });
144
+ delivered = result.status === 0 || killChild();
145
+ } else if (!child.pid || process.platform === "win32") delivered = killChild();
139
146
  // The group can outlive its leader and keep stdout/stderr open. A leader's
140
147
  // exit must not suppress escalation to surviving descendants.
141
148
  else delivered = process.kill(-child.pid, signal);