@koreanhole/opencodex 3.2.32 → 3.2.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@koreanhole/opencodex",
3
- "version": "3.2.32",
3
+ "version": "3.2.34",
4
4
  "description": "Full opencodex runtime with Cline 2.2.0+ JSON and Gemini CLI headless provider adapters",
5
5
  "type": "module",
6
6
  "main": "./bin/package-main.mjs",
@@ -3,7 +3,7 @@ import { writeFile } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
  import type { AdapterEvent, IncomingMeta, OcxParsedRequest } from "../../../types";
5
5
  import { buildCodingAgentToolCatalog, CodingAgentToolCatalogError } from "../../tool-catalog";
6
- import { buildConversationInput, buildSystemPrompt } from "../protocol";
6
+ import { buildConversationDelta, buildConversationInput, buildSystemPrompt } from "../protocol";
7
7
  import { whichFromPath, type WhichFn } from "../../coding-agent/profile";
8
8
  import { isStandaloneBinary } from "../../../lib/standalone";
9
9
  import type { CliAgentTurnDeps } from "../types";
@@ -18,7 +18,7 @@ import {
18
18
  type ClineSelection,
19
19
  type ClineStagedTurn,
20
20
  } from "./settings";
21
- import { resolveClineBinary } from "./binary";
21
+ import { clineBinaryFingerprintSync, resolveClineBinary } from "./binary";
22
22
  import { buildClineProbeEnv } from "./env";
23
23
  import {
24
24
  buildClineJsonArgs,
@@ -29,12 +29,28 @@ import {
29
29
  type ClineJsonCapabilities,
30
30
  type ClineJsonTurnInput,
31
31
  } from "./json";
32
+ import {
33
+ claimClineSessionKey,
34
+ clineSessionRootExists,
35
+ clineSessionWorkspace,
36
+ deleteClineSession,
37
+ findClineSessionByKeyHash,
38
+ findClineSessionByResponseId,
39
+ hashConversationKey,
40
+ hashMessages,
41
+ reclaimClineSessions,
42
+ releaseClineSessionKey,
43
+ saveClineSession,
44
+ type ClineSessionRecord,
45
+ } from "./session-store";
32
46
 
33
47
  export const CLINE_CLI_BASE_URL = "https://api.cline.bot";
34
48
  export const CLINE_CLI_MODEL_ID = "default";
35
49
  const CLINE_MCP_SERVER_NAME = "opencodex";
36
50
  const CLINE_MCP_SERVER_PATH = fileURLToPath(new URL("../mcp-server.ts", import.meta.url));
37
51
  const CLINE_JSON_PROMPT = "Follow the piped conversation and instructions.";
52
+ const CLINE_CONVERSATION_KEY_TAG = "key:";
53
+ const CLINE_RESPONSE_KEY_TAG = "response:";
38
54
 
39
55
  const CLINE_SYSTEM_PROMPT = [
40
56
  "You are a model backend used by an external coding client.",
@@ -142,6 +158,50 @@ function failure(error: unknown): Extract<AdapterEvent, { type: "error" }> {
142
158
  };
143
159
  }
144
160
 
161
+ /** Resolve the conversation identity in the same precedence the Gemini adapter uses. */
162
+ export async function resolveClineSession(
163
+ parsed: OcxParsedRequest,
164
+ incoming: IncomingMeta,
165
+ env: NodeJS.ProcessEnv = process.env,
166
+ ): Promise<{ keyHash?: string; prior?: ClineSessionRecord; source?: string }> {
167
+ if (parsed.previousResponseId) {
168
+ const prior = await findClineSessionByResponseId(parsed.previousResponseId, env);
169
+ if (prior) return { keyHash: prior.keyHash, prior, source: "previous_response_id" };
170
+ }
171
+ const cacheKey = parsed.promptCacheKey?.trim();
172
+ const headerKey = incoming.headers.get("x-opencodex-conversation")?.trim();
173
+ const clientKey = cacheKey || headerKey;
174
+ if (clientKey) {
175
+ const keyHash = hashConversationKey(CLINE_CONVERSATION_KEY_TAG + clientKey);
176
+ return {
177
+ keyHash,
178
+ prior: await findClineSessionByKeyHash(keyHash, env),
179
+ source: cacheKey ? "prompt_cache_key" : "header",
180
+ };
181
+ }
182
+ return parsed.responseId
183
+ ? { keyHash: hashConversationKey(CLINE_RESPONSE_KEY_TAG + parsed.responseId), source: "response_id" }
184
+ : {};
185
+ }
186
+
187
+ /** Build the resumed prompt from the new messages only; instructions still lead every turn. */
188
+ function buildClineDeltaPrompt(
189
+ parsed: OcxParsedRequest,
190
+ startIndex: number,
191
+ vendorNameByWire: ReadonlyMap<string, string>,
192
+ fixedSystem: string,
193
+ ): string | undefined {
194
+ const delta = buildConversationDelta(parsed, startIndex, { vendorNameByWire });
195
+ if (!delta.trim()) return undefined;
196
+ return [
197
+ "SYSTEM AND DEVELOPER INSTRUCTIONS:",
198
+ fixedSystem,
199
+ buildSystemPrompt(parsed),
200
+ "NEW CONVERSATION DELTA:",
201
+ delta,
202
+ ].filter(Boolean).join("\n\n");
203
+ }
204
+
145
205
  function mcpLaunch(): ClineMcpLaunch {
146
206
  return isStandaloneBinary()
147
207
  ? { kind: "entrypoint", entrypoint: "__cli-agent-mcp" }
@@ -203,7 +263,38 @@ export async function runClineTurn(
203
263
  wireName.startsWith("opencodex__") ? wireName : `opencodex__${wireName}`,
204
264
  ]));
205
265
  const fixedSystem = systemPromptWithToolNames(catalog, !capabilities.toolCatalogJson);
206
- const actualPrompt = buildClinePrompt(parsed, vendorNameByWire, fixedSystem);
266
+ await reclaimClineSessions(sourceEnv).catch(() => undefined);
267
+ const fingerprint = clineBinaryFingerprintSync(binary);
268
+ const sessionMessages = parsed.context.messages.filter(message => message.role !== "developer");
269
+ const toolHash = catalog.tools.length > 0 ? hashConversationKey(JSON.stringify(catalog.tools)) : undefined;
270
+ const resolved = await resolveClineSession(parsed, incoming, sourceEnv);
271
+ const sessionKey = resolved.prior?.keyHash ?? resolved.keyHash;
272
+ const ownsKey = sessionKey ? claimClineSessionKey(sessionKey) : false;
273
+ let prior = ownsKey ? resolved.prior : undefined;
274
+ let reuse = false;
275
+ let deltaPrompt: string | undefined;
276
+ if (prior && capabilities.resumeFlag && prior.fingerprint === fingerprint && prior.modelId === requestedModel
277
+ && prior.toolHash === toolHash && clineSessionRootExists(prior, sourceEnv)) {
278
+ const prefix = sessionMessages.slice(0, prior.historyCount);
279
+ if (prefix.length === prior.historyCount && hashMessages(prefix) === prior.historyHash) {
280
+ let deltaStart = prior.historyCount;
281
+ while (deltaStart < sessionMessages.length && sessionMessages[deltaStart]!.role === "assistant") deltaStart++;
282
+ if (deltaStart < sessionMessages.length) {
283
+ deltaPrompt = buildClineDeltaPrompt(parsed, deltaStart, vendorNameByWire, fixedSystem);
284
+ reuse = Boolean(deltaPrompt);
285
+ }
286
+ }
287
+ }
288
+ if (prior && !reuse) {
289
+ await deleteClineSession(prior.keyHash, sourceEnv).catch(() => undefined);
290
+ prior = undefined;
291
+ }
292
+ const sessionRoot = ownsKey && sessionKey && capabilities.resumeFlag
293
+ ? (reuse && prior ? prior.workspace : clineSessionWorkspace(sessionKey, sourceEnv))
294
+ : undefined;
295
+ const actualPrompt = reuse && deltaPrompt
296
+ ? deltaPrompt
297
+ : buildClinePrompt(parsed, vendorNameByWire, fixedSystem);
207
298
  let args: string[];
208
299
  try {
209
300
  args = buildClineJsonArgs({
@@ -212,18 +303,23 @@ export async function runClineTurn(
212
303
  ...(selection ? { selection } : {}),
213
304
  systemPrompt: fixedSystem.replace(/\s+/g, " ").trim(),
214
305
  prompt: CLINE_JSON_PROMPT,
306
+ ...(reuse && prior ? { resumeSessionId: prior.vendorSessionId } : {}),
215
307
  });
216
308
  } catch (error) {
309
+ if (ownsKey && sessionKey && prior) await deleteClineSession(sessionKey, sourceEnv).catch(() => undefined);
310
+ if (ownsKey && sessionKey) releaseClineSessionKey(sessionKey);
217
311
  emit(failure(error));
218
312
  return;
219
313
  }
220
314
 
221
315
  let staged: ClineStagedTurn | undefined;
316
+ let saved = false;
222
317
  try {
223
318
  staged = await (deps.stageTurn ?? stageClineTurn)({
224
319
  providerSettingsPath,
225
320
  catalog: catalog.tools,
226
321
  ...(catalog.emittedNameMap.size > 0 ? { mcpLaunch: mcpLaunch() } : {}),
322
+ ...(sessionRoot ? { root: sessionRoot } : {}),
227
323
  });
228
324
  const env = buildClineChildEnv(staged, sourceEnv);
229
325
  if (capabilities.toolCatalogJson) {
@@ -273,6 +369,8 @@ export async function runClineTurn(
273
369
  return;
274
370
  }
275
371
 
372
+ let terminal: AdapterEvent | undefined;
373
+ let vendorSessionId: string | undefined;
276
374
  await (deps.runJson ?? runClineJsonTurn)({
277
375
  binary,
278
376
  args,
@@ -283,11 +381,40 @@ export async function runClineTurn(
283
381
  maxToolCalls: 16,
284
382
  requireToolCall: catalog.requireToolCall,
285
383
  incoming,
286
- }, emit, deps);
384
+ onVendorSession: sessionId => { vendorSessionId ??= sessionId; },
385
+ }, event => {
386
+ if ((event.type === "done" || event.type === "error" || event.type === "incomplete") && !terminal) terminal = event;
387
+ emit(event);
388
+ }, deps);
389
+ const reusable = terminal?.type === "done" && terminal.stopReason !== "tool_use";
390
+ const resumedVendorId = !reuse || !prior || vendorSessionId === prior.vendorSessionId;
391
+ if (ownsKey && sessionKey && vendorSessionId && capabilities.resumeFlag && reusable && resumedVendorId) {
392
+ try {
393
+ await saveClineSession({
394
+ keyHash: sessionKey,
395
+ vendorSessionId,
396
+ fingerprint,
397
+ modelId: requestedModel,
398
+ workspace: staged.root,
399
+ historyCount: sessionMessages.length,
400
+ historyHash: hashMessages(sessionMessages),
401
+ ...(toolHash ? { toolHash } : {}),
402
+ lastUsed: Date.now(),
403
+ turnCount: (resolved.prior?.turnCount ?? 0) + 1,
404
+ }, parsed.responseId, sourceEnv);
405
+ saved = true;
406
+ } catch {
407
+ await deleteClineSession(sessionKey, sourceEnv).catch(() => undefined);
408
+ }
409
+ }
287
410
  } catch (error) {
288
411
  emit(failure(error));
289
412
  } finally {
413
+ if (ownsKey && sessionKey && prior && !saved) {
414
+ await deleteClineSession(sessionKey, sourceEnv).catch(() => undefined);
415
+ }
290
416
  await staged?.cleanup();
417
+ if (ownsKey && sessionKey) releaseClineSessionKey(sessionKey);
291
418
  }
292
419
  }
293
420
 
@@ -10,7 +10,7 @@ export function resolveClineBinary(
10
10
  ): string | undefined {
11
11
  const explicit = env.CLINE_BIN_PATH?.trim();
12
12
  if (explicit && existsSync(explicit)) return explicit;
13
- const resolved = which("cline");
13
+ const resolved = which === whichFromPath ? whichFromPath("cline", { env }) : which("cline");
14
14
  if (!resolved) return undefined;
15
15
  const cached = join(dirname(resolved), ".cline");
16
16
  return existsSync(cached) ? cached : resolved;
@@ -13,6 +13,7 @@ import type { ClineSelection } from "./settings";
13
13
  import {
14
14
  classifyClineFailure,
15
15
  ClineStreamProtocolError,
16
+ clineVendorSessionId,
16
17
  createClineStreamState,
17
18
  mapClineMessage,
18
19
  } from "./stream";
@@ -46,6 +47,7 @@ export interface ClineJsonCapabilities {
46
47
  modelFlag?: "--model" | "--modelid";
47
48
  systemFlag?: "--system";
48
49
  autoApproveFlag?: "--auto-approve";
50
+ resumeFlag?: "--id" | "--taskId";
49
51
  }
50
52
 
51
53
  export interface ClineJsonTurnInput {
@@ -58,6 +60,8 @@ export interface ClineJsonTurnInput {
58
60
  maxToolCalls: number;
59
61
  requireToolCall: boolean;
60
62
  incoming: IncomingMeta;
63
+ /** First vendor session id reported by the turn; enables continuation storage. */
64
+ onVendorSession?: (sessionId: string) => void;
61
65
  }
62
66
 
63
67
  export interface ClineEnabledTool {
@@ -110,6 +114,11 @@ export function parseClineJsonHelp(
110
114
  : undefined;
111
115
  const systemFlag = optionPresent(text, "--system") ? "--system" as const : undefined;
112
116
  const autoApproveFlag = optionPresent(text, "--auto-approve") ? "--auto-approve" as const : undefined;
117
+ const resumeFlag = optionPresent(text, "--id")
118
+ ? "--id" as const
119
+ : optionPresent(text, "--taskId")
120
+ ? "--taskId" as const
121
+ : undefined;
113
122
  return {
114
123
  json,
115
124
  toolCatalogJson: false,
@@ -117,6 +126,7 @@ export function parseClineJsonHelp(
117
126
  ...(modelFlag ? { modelFlag } : {}),
118
127
  ...(systemFlag ? { systemFlag } : {}),
119
128
  ...(autoApproveFlag ? { autoApproveFlag } : {}),
129
+ ...(resumeFlag ? { resumeFlag } : {}),
120
130
  };
121
131
  }
122
132
 
@@ -257,6 +267,7 @@ export function buildClineJsonArgs(input: {
257
267
  selection?: ClineSelection;
258
268
  systemPrompt?: string;
259
269
  prompt: string;
270
+ resumeSessionId?: string;
260
271
  }): string[] {
261
272
  if (!input.capabilities.json) {
262
273
  throw new ClineJsonError("The installed Cline CLI does not advertise --json.", 400, "invalid_request_error", "cline_json_unsupported", false);
@@ -283,6 +294,9 @@ export function buildClineJsonArgs(input: {
283
294
  if (input.capabilities.autoApproveFlag) {
284
295
  args.push(input.capabilities.autoApproveFlag, "false");
285
296
  }
297
+ if (input.resumeSessionId && input.capabilities.resumeFlag) {
298
+ args.push(input.capabilities.resumeFlag, input.resumeSessionId);
299
+ }
286
300
  args.push(input.prompt);
287
301
  return args;
288
302
  }
@@ -408,6 +422,7 @@ export async function runClineJsonTurn(
408
422
  let aborted = false;
409
423
  let timedOut = false;
410
424
  let toolBatchStopped = false;
425
+ let reportedVendorSession = false;
411
426
  let spawnError: Error | undefined;
412
427
  let exitCode: number | null = null;
413
428
  let timeoutTimer: ReturnType<typeof setTimeout> | undefined;
@@ -551,6 +566,13 @@ export async function runClineJsonTurn(
551
566
  if (!child.stdout) throw new Error("Cline JSON process produced no stdout stream.");
552
567
  for await (const message of readJsonLines(child.stdout)) {
553
568
  if (terminalEmitted) break;
569
+ if (!reportedVendorSession) {
570
+ const vendorSession = clineVendorSessionId(message);
571
+ if (vendorSession) {
572
+ reportedVendorSession = true;
573
+ input.onVendorSession?.(vendorSession);
574
+ }
575
+ }
554
576
  let events: AdapterEvent[];
555
577
  try {
556
578
  events = mapClineMessage(message, state, {
@@ -612,6 +634,18 @@ export async function runClineJsonTurn(
612
634
  });
613
635
  } else if (exitCode !== null && exitCode !== 0) {
614
636
  deliver(classifyClineFailure(exitCode, stderr.join("")));
637
+ } else if (state.sawText || state.legacyText) {
638
+ if (!state.sawThinking && state.legacyThinking) {
639
+ state.sawThinking = true;
640
+ deliver({ type: "thinking_delta", thinking: state.legacyThinking });
641
+ }
642
+ if (!state.sawText && state.legacyText) {
643
+ state.sawText = true;
644
+ deliver({ type: "text_delta", text: state.legacyText });
645
+ }
646
+ deliver({ type: "done", stopReason: "stop", ...(state.usage ? { usage: state.usage } : {}) });
647
+ } else if (stderr.join("").trim()) {
648
+ deliver(classifyClineFailure(exitCode ?? 1, stderr.join("")));
615
649
  } else {
616
650
  deliver({
617
651
  type: "error",
@@ -0,0 +1,297 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync } from "node:fs";
3
+ import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
4
+ import { join, resolve, sep } from "node:path";
5
+ import { getConfigDir } from "../../../config";
6
+ import type { OcxMessage } from "../../../types";
7
+
8
+ export interface ClineSessionRecord {
9
+ keyHash: string;
10
+ vendorSessionId: string;
11
+ fingerprint: string;
12
+ modelId: string;
13
+ workspace: string;
14
+ historyCount: number;
15
+ historyHash: string;
16
+ toolHash?: string;
17
+ lastUsed: number;
18
+ turnCount: number;
19
+ }
20
+
21
+ interface SessionDocument {
22
+ version: 1;
23
+ sessions: Record<string, ClineSessionRecord>;
24
+ responses: Record<string, string>;
25
+ }
26
+
27
+ const DEFAULT_TTL_MS = 60 * 60 * 1000;
28
+ const DEFAULT_MAX_SESSIONS = 32;
29
+
30
+ const sessions = new Map<string, ClineSessionRecord>();
31
+ const responses = new Map<string, string>();
32
+ const inProgress = new Set<string>();
33
+ const deleted = new Set<string>();
34
+ let loadPromise: Promise<boolean> | undefined;
35
+ let persistChain: Promise<void> = Promise.resolve();
36
+
37
+ function sessionPath(env: NodeJS.ProcessEnv): string {
38
+ return join(getConfigDir(env), "cline", "sessions.json");
39
+ }
40
+
41
+ function sessionsRoot(env: NodeJS.ProcessEnv): string {
42
+ return join(getConfigDir(env), "cline", "sessions");
43
+ }
44
+
45
+ function positiveInt(value: unknown, fallback: number): number {
46
+ const parsed = typeof value === "string" ? Number(value) : value;
47
+ return typeof parsed === "number" && Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : fallback;
48
+ }
49
+
50
+ function ttlMs(env: NodeJS.ProcessEnv): number {
51
+ return positiveInt(env.OPENCODEX_CLINE_SESSION_TTL_MS, DEFAULT_TTL_MS);
52
+ }
53
+
54
+ function maxSessions(env: NodeJS.ProcessEnv): number {
55
+ return positiveInt(env.OPENCODEX_CLINE_SESSION_MAX, DEFAULT_MAX_SESSIONS);
56
+ }
57
+
58
+ function parseRecord(value: unknown): ClineSessionRecord | undefined {
59
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
60
+ const row = value as Record<string, unknown>;
61
+ const keyHash = typeof row.keyHash === "string" ? row.keyHash : undefined;
62
+ const vendorSessionId = typeof row.vendorSessionId === "string" ? row.vendorSessionId : undefined;
63
+ const fingerprint = typeof row.fingerprint === "string" ? row.fingerprint : undefined;
64
+ const modelId = typeof row.modelId === "string" ? row.modelId : undefined;
65
+ const workspace = typeof row.workspace === "string" ? row.workspace : undefined;
66
+ const historyHash = typeof row.historyHash === "string" ? row.historyHash : undefined;
67
+ const toolHash = typeof row.toolHash === "string" ? row.toolHash : undefined;
68
+ const historyCount = typeof row.historyCount === "number" && Number.isInteger(row.historyCount) && row.historyCount >= 0 ? row.historyCount : undefined;
69
+ const lastUsed = typeof row.lastUsed === "number" && Number.isFinite(row.lastUsed) && row.lastUsed >= 0 ? row.lastUsed : undefined;
70
+ const turnCount = typeof row.turnCount === "number" && Number.isInteger(row.turnCount) && row.turnCount >= 0 ? row.turnCount : undefined;
71
+ if (!keyHash || !vendorSessionId || !fingerprint || !modelId || !workspace || !historyHash || historyCount === undefined || lastUsed === undefined || turnCount === undefined) return undefined;
72
+ return { keyHash, vendorSessionId, fingerprint, modelId, workspace, historyCount, historyHash, ...(toolHash ? { toolHash } : {}), lastUsed, turnCount };
73
+ }
74
+
75
+ function parseDocument(text: string): SessionDocument | undefined {
76
+ let parsed: unknown;
77
+ try {
78
+ parsed = JSON.parse(text);
79
+ } catch {
80
+ return undefined;
81
+ }
82
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return undefined;
83
+ const document = parsed as Partial<SessionDocument>;
84
+ if (document.version !== 1) return undefined;
85
+ const sessionRows = document.sessions && typeof document.sessions === "object" ? document.sessions : {};
86
+ const responseRows = document.responses && typeof document.responses === "object" ? document.responses : {};
87
+ return { version: 1, sessions: sessionRows, responses: responseRows };
88
+ }
89
+
90
+ const UNREADABLE = "Cline session store cannot be read; leaving it untouched.";
91
+
92
+ async function readDocument(env: NodeJS.ProcessEnv): Promise<boolean> {
93
+ let text: string;
94
+ try {
95
+ text = await readFile(sessionPath(env), "utf8");
96
+ } catch (error) {
97
+ return (error as NodeJS.ErrnoException).code === "ENOENT";
98
+ }
99
+ const document = parseDocument(text);
100
+ if (!document) return false;
101
+ for (const [key, value] of Object.entries(document.sessions)) {
102
+ const record = parseRecord(value);
103
+ if (record) sessions.set(key, record);
104
+ }
105
+ for (const [responseId, keyHash] of Object.entries(document.responses)) {
106
+ if (typeof keyHash === "string") responses.set(responseId, keyHash);
107
+ }
108
+ return true;
109
+ }
110
+
111
+ /**
112
+ * Resolves false when the on-disk store exists but could not be read. The in-flight promise is
113
+ * shared so a concurrent caller sees the real records instead of an empty map.
114
+ */
115
+ function load(env: NodeJS.ProcessEnv): Promise<boolean> {
116
+ loadPromise ??= readDocument(env);
117
+ return loadPromise;
118
+ }
119
+
120
+ async function mergeFromDisk(env: NodeJS.ProcessEnv): Promise<void> {
121
+ let text: string;
122
+ try {
123
+ text = await readFile(sessionPath(env), "utf8");
124
+ } catch (error) {
125
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
126
+ throw new Error(UNREADABLE);
127
+ }
128
+ const document = parseDocument(text);
129
+ if (!document) throw new Error(UNREADABLE);
130
+ for (const [key, value] of Object.entries(document.sessions)) {
131
+ if (sessions.has(key) || deleted.has(key)) continue;
132
+ const record = parseRecord(value);
133
+ if (record) sessions.set(key, record);
134
+ }
135
+ for (const [responseId, keyHash] of Object.entries(document.responses)) {
136
+ if (typeof keyHash !== "string" || responses.has(responseId) || deleted.has(keyHash)) continue;
137
+ if (sessions.has(keyHash)) responses.set(responseId, keyHash);
138
+ }
139
+ }
140
+
141
+ function persist(env: NodeJS.ProcessEnv): Promise<void> {
142
+ const write = persistChain.then(() => writeDocument(env));
143
+ persistChain = write.catch(() => undefined);
144
+ return write;
145
+ }
146
+
147
+ // Records another ocx added since our load are merged so its writes survive ours.
148
+ // shortcut: no cross-process lock, so concurrent root sweeps still race; add one if shared roots appear.
149
+ async function writeDocument(env: NodeJS.ProcessEnv): Promise<void> {
150
+ const path = sessionPath(env);
151
+ await mkdir(join(getConfigDir(env), "cline"), { recursive: true, mode: 0o700 });
152
+ await mergeFromDisk(env);
153
+ const document: SessionDocument = {
154
+ version: 1,
155
+ sessions: Object.fromEntries(sessions),
156
+ responses: Object.fromEntries(responses),
157
+ };
158
+ const temporary = `${path}.${crypto.randomUUID()}.tmp`;
159
+ await writeFile(temporary, JSON.stringify(document, null, 2) + "\n", { encoding: "utf8", mode: 0o600 });
160
+ await rename(temporary, path);
161
+ deleted.clear();
162
+ }
163
+
164
+ /** A root is removable only when it resolves inside the Cline sessions directory. */
165
+ function safeWorkspace(workspace: string, env: NodeJS.ProcessEnv): boolean {
166
+ const resolved = resolve(workspace);
167
+ return resolved.startsWith(resolve(sessionsRoot(env)) + sep);
168
+ }
169
+
170
+ async function removeWorkspace(workspace: string, env: NodeJS.ProcessEnv): Promise<void> {
171
+ if (!safeWorkspace(workspace, env)) return;
172
+ await rm(workspace, { recursive: true, force: true }).catch(() => undefined);
173
+ }
174
+
175
+ export function hashConversationKey(value: string): string {
176
+ return createHash("sha256").update(value).digest("hex");
177
+ }
178
+
179
+ export function hashMessages(messages: readonly OcxMessage[]): string {
180
+ return createHash("sha256")
181
+ .update(JSON.stringify(messages, (key, value) => key === "timestamp" ? undefined : value))
182
+ .digest("hex");
183
+ }
184
+
185
+ export function clineSessionWorkspace(keyHash: string, env: NodeJS.ProcessEnv = process.env): string {
186
+ return join(sessionsRoot(env), keyHash);
187
+ }
188
+
189
+ /** One turn owns a key at a time; the claim is synchronous so concurrent turns cannot both win. */
190
+ export function claimClineSessionKey(keyHash: string): boolean {
191
+ if (inProgress.has(keyHash)) return false;
192
+ inProgress.add(keyHash);
193
+ return true;
194
+ }
195
+
196
+ export function releaseClineSessionKey(keyHash: string): void {
197
+ inProgress.delete(keyHash);
198
+ }
199
+
200
+ export async function findClineSessionByResponseId(
201
+ responseId: string,
202
+ env: NodeJS.ProcessEnv = process.env,
203
+ ): Promise<ClineSessionRecord | undefined> {
204
+ if (!(await load(env))) return undefined;
205
+ const keyHash = responses.get(responseId);
206
+ return keyHash ? sessions.get(keyHash) : undefined;
207
+ }
208
+
209
+ export async function findClineSessionByKeyHash(
210
+ keyHash: string,
211
+ env: NodeJS.ProcessEnv = process.env,
212
+ ): Promise<ClineSessionRecord | undefined> {
213
+ if (!(await load(env))) return undefined;
214
+ return sessions.get(keyHash);
215
+ }
216
+
217
+ export function clineSessionRootExists(record: ClineSessionRecord, env: NodeJS.ProcessEnv = process.env): boolean {
218
+ return safeWorkspace(record.workspace, env) && existsSync(record.workspace);
219
+ }
220
+
221
+ export async function saveClineSession(
222
+ record: ClineSessionRecord,
223
+ responseId: string | undefined,
224
+ env: NodeJS.ProcessEnv = process.env,
225
+ ): Promise<void> {
226
+ if (!(await load(env))) throw new Error(UNREADABLE);
227
+ sessions.set(record.keyHash, record);
228
+ const previousResponses = [...responses].filter(([, key]) => key === record.keyHash);
229
+ for (const [id] of previousResponses.slice(0, Math.max(0, previousResponses.length - 1))) {
230
+ responses.delete(id);
231
+ }
232
+ if (responseId) responses.set(responseId, record.keyHash);
233
+ const limit = maxSessions(env);
234
+ while (sessions.size > limit) {
235
+ const oldest = [...sessions.values()]
236
+ .filter(value => !inProgress.has(value.keyHash) && value.keyHash !== record.keyHash)
237
+ .sort((left, right) => left.lastUsed - right.lastUsed
238
+ || (left.keyHash < right.keyHash ? -1 : left.keyHash > right.keyHash ? 1 : 0))[0];
239
+ if (!oldest) break;
240
+ sessions.delete(oldest.keyHash);
241
+ deleted.add(oldest.keyHash);
242
+ for (const [id, mapped] of responses) if (mapped === oldest.keyHash) responses.delete(id);
243
+ await removeWorkspace(oldest.workspace, env);
244
+ }
245
+ await persist(env);
246
+ }
247
+
248
+ export async function deleteClineSession(
249
+ keyHash: string,
250
+ env: NodeJS.ProcessEnv = process.env,
251
+ ): Promise<void> {
252
+ if (!(await load(env))) return;
253
+ const record = sessions.get(keyHash);
254
+ sessions.delete(keyHash);
255
+ deleted.add(keyHash);
256
+ for (const [id, mapped] of responses) if (mapped === keyHash) responses.delete(id);
257
+ if (record) await removeWorkspace(record.workspace, env);
258
+ await persist(env);
259
+ }
260
+
261
+ export async function reclaimClineSessions(
262
+ env: NodeJS.ProcessEnv = process.env,
263
+ now: number = Date.now(),
264
+ ): Promise<void> {
265
+ if (!(await load(env))) return;
266
+ const window = ttlMs(env);
267
+ let changed = false;
268
+ for (const [key, record] of sessions) {
269
+ if (inProgress.has(key)) continue;
270
+ if (now - record.lastUsed < window) continue;
271
+ sessions.delete(key);
272
+ deleted.add(key);
273
+ for (const [id, mapped] of responses) if (mapped === key) responses.delete(id);
274
+ await removeWorkspace(record.workspace, env);
275
+ changed = true;
276
+ }
277
+ let orphans: string[] = [];
278
+ try {
279
+ orphans = await readdir(sessionsRoot(env));
280
+ } catch {
281
+ orphans = [];
282
+ }
283
+ for (const entry of orphans) {
284
+ if (sessions.has(entry) || inProgress.has(entry)) continue;
285
+ await rm(join(sessionsRoot(env), entry), { recursive: true, force: true }).catch(() => undefined);
286
+ }
287
+ if (changed) await persist(env);
288
+ }
289
+
290
+ export function resetClineSessionStoreForTests(): void {
291
+ sessions.clear();
292
+ responses.clear();
293
+ inProgress.clear();
294
+ deleted.clear();
295
+ loadPromise = undefined;
296
+ persistChain = Promise.resolve();
297
+ }
@@ -209,7 +209,8 @@ export function resolveClineProviderSettingsPath(env: Record<string, string | un
209
209
  if (dataDir) return join(dataDir, "settings", "providers.json");
210
210
  const clineDir = nonEmpty(env.CLINE_DIR);
211
211
  if (clineDir) return join(clineDir, "data", "settings", "providers.json");
212
- return join(homedir(), ".cline", "data", "settings", "providers.json");
212
+ const home = nonEmpty(env.HOME) ?? nonEmpty(env.USERPROFILE) ?? homedir();
213
+ return join(home, ".cline", "data", "settings", "providers.json");
213
214
  }
214
215
 
215
216
  function isLoopbackUrl(value: string): boolean {
@@ -418,6 +419,8 @@ async function linkClineSettings(input: {
418
419
  configDir: string;
419
420
  homeDir: string;
420
421
  providerSettingsPath?: string;
422
+ legacyGlobalStatePath?: string;
423
+ legacySecretsPath?: string;
421
424
  globalSettingsPath: string;
422
425
  mcpSettingsPath: string;
423
426
  }): Promise<void> {
@@ -434,6 +437,15 @@ async function linkClineSettings(input: {
434
437
  await linkClineFile(input.globalSettingsPath, join(target.dir, "global-settings.json"));
435
438
  await linkClineFile(input.mcpSettingsPath, join(target.dir, "cline_mcp_settings.json"));
436
439
  }
440
+ const legacyDirs = [input.dataDir, join(input.homeDir, ".cline", "data")];
441
+ for (const dir of legacyDirs) {
442
+ if (input.legacyGlobalStatePath) {
443
+ await linkClineFile(input.legacyGlobalStatePath, join(dir, "globalState.json"));
444
+ }
445
+ if (input.legacySecretsPath) {
446
+ await linkClineFile(input.legacySecretsPath, join(dir, "secrets.json"));
447
+ }
448
+ }
437
449
  }
438
450
 
439
451
  /** Stage all Cline paths the proxy controls; the vendor provider store remains the auth source. */
@@ -441,8 +453,11 @@ export async function stageClineTurn(options: {
441
453
  providerSettingsPath: string;
442
454
  catalog: readonly Record<string, unknown>[];
443
455
  mcpLaunch?: ClineMcpLaunch;
456
+ /** Persistent conversation root. When set, per-turn state is recreated and vendor data survives. */
457
+ root?: string;
444
458
  }): Promise<ClineStagedTurn> {
445
- const root = await mkdtemp(join(tmpdir(), "ocx-cline-cli-"));
459
+ const persistent = Boolean(options.root);
460
+ const root = options.root ?? await mkdtemp(join(tmpdir(), "ocx-cline-cli-"));
446
461
  const configDir = join(root, "config");
447
462
  const dataDir = join(root, "data");
448
463
  const homeDir = join(root, "home");
@@ -454,11 +469,27 @@ export async function stageClineTurn(options: {
454
469
  const providerSettingsPath = join(homeDir, ".cline", "data", "settings", "providers.json");
455
470
  const catalogPath = join(root, "tool-catalog.json");
456
471
 
472
+ const recreatedPaths = [
473
+ configDir,
474
+ homeDir,
475
+ hooksDir,
476
+ logDir,
477
+ join(dataDir, "settings"),
478
+ join(dataDir, "globalState.json"),
479
+ join(dataDir, "secrets.json"),
480
+ catalogPath,
481
+ ];
482
+ const perTurnPaths = [...recreatedPaths, join(root, "prompt.txt")];
457
483
  const cleanup = async (): Promise<void> => {
458
- await rm(root, { recursive: true, force: true }).catch(() => undefined);
484
+ const targets = persistent ? perTurnPaths : [root];
485
+ await Promise.all(targets.map(path => rm(path, { recursive: true, force: true }).catch(() => undefined)));
459
486
  };
460
487
 
461
488
  try {
489
+ if (persistent) {
490
+ await mkdir(root, { recursive: true, mode: 0o700 });
491
+ await Promise.all(recreatedPaths.map(path => rm(path, { recursive: true, force: true }).catch(() => undefined)));
492
+ }
462
493
  await Promise.all([
463
494
  mkdir(configDir, { recursive: true, mode: 0o700 }),
464
495
  mkdir(dirname(globalSettingsPath), { recursive: true, mode: 0o700 }),
@@ -483,6 +514,8 @@ export async function stageClineTurn(options: {
483
514
  configDir,
484
515
  homeDir,
485
516
  ...(copiedProviderStore ? { providerSettingsPath } : {}),
517
+ legacyGlobalStatePath: legacyState.globalStatePath,
518
+ ...(legacyState.secretsPath ? { legacySecretsPath: legacyState.secretsPath } : {}),
486
519
  globalSettingsPath,
487
520
  mcpSettingsPath,
488
521
  });
@@ -542,11 +575,23 @@ export async function mergeClineDisabledTools(
542
575
  }
543
576
 
544
577
  export function buildClineChildEnv(staged: ClineStagedTurn, sourceEnv: NodeJS.ProcessEnv = process.env): Record<string, string> {
545
- const env = baseScopedEnv();
546
- env.HOME = staged.homeDir;
547
- env.USERPROFILE = staged.homeDir;
548
- env.XDG_CONFIG_HOME = join(staged.homeDir, ".config");
549
- env.XDG_CACHE_HOME = join(staged.homeDir, ".cache");
578
+ const env = baseScopedEnv(sourceEnv);
579
+ const realHome = nonEmpty(sourceEnv.HOME) ?? nonEmpty(sourceEnv.USERPROFILE) ?? homedir();
580
+ if (realHome) {
581
+ env.HOME = realHome;
582
+ env.USERPROFILE = realHome;
583
+ }
584
+ for (const key of [
585
+ "XDG_CONFIG_HOME",
586
+ "XDG_CACHE_HOME",
587
+ "XDG_DATA_HOME",
588
+ "XDG_RUNTIME_DIR",
589
+ "DBUS_SESSION_BUS_ADDRESS",
590
+ "GNOME_KEYRING_CONTROL",
591
+ ]) {
592
+ const value = nonEmpty(sourceEnv[key]);
593
+ if (value) env[key] = value;
594
+ }
550
595
  const user = sourceEnv.USER ?? sourceEnv.LOGNAME;
551
596
  if (user) env.USER = user;
552
597
  if (sourceEnv.LOGNAME) env.LOGNAME = sourceEnv.LOGNAME;
@@ -30,6 +30,17 @@ export function createClineStreamState(): CliAgentStreamState {
30
30
  };
31
31
  }
32
32
 
33
+ /** Read the vendor session id from either stream generation without changing event mapping. */
34
+ export function clineVendorSessionId(message: Record<string, unknown>): string | undefined {
35
+ const type = asString(message.type);
36
+ const value = type === "run_start"
37
+ ? message.sessionId
38
+ : type === "task_started"
39
+ ? message.taskId
40
+ : undefined;
41
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
42
+ }
43
+
33
44
  /** Map a validated Cline tool intent into events owned by Codex. */
34
45
  export function mapClineToolIntent(
35
46
  vendorName: string,
@@ -68,7 +79,7 @@ function safeMessage(value: unknown): string {
68
79
  }
69
80
 
70
81
  function classifyError(message: string): { status: number; errorType: string; code: string; retryable: boolean } {
71
- if (/not logged in|please (?:run )?\/?login|sign in|authentication (?:failed|required)|unauthorized|invalid (?:api )?key/i.test(message)) {
82
+ if (/not logged in|please (?:run )?\/?login|sign in|authentication (?:failed|required)|unauthorized|invalid (?:api )?key|interactive auth|auth setup/i.test(message)) {
72
83
  return { status: 401, errorType: "authentication_error", code: "cline_cli_not_logged_in", retryable: false };
73
84
  }
74
85
  if (/rate limit|too many requests|quota|credit|usage limit|daily limit/i.test(message)) {
@@ -173,7 +184,7 @@ function mapLegacyMessage(
173
184
  if (status === "error") {
174
185
  return legacyError(safeMessage(message.message ?? text ?? "Cline reported an error."), state);
175
186
  }
176
- if (status === "success") return legacyDone(state, text);
187
+ if (status === "success" || status === "completed") return legacyDone(state, text);
177
188
  return [];
178
189
  }
179
190
  if (type === "say") {
@@ -242,6 +253,23 @@ function mapAgentEvent(
242
253
  return [];
243
254
  }
244
255
 
256
+ if (type === "content_update") {
257
+ const contentType = asString(event.contentType);
258
+ if (contentType === "text") {
259
+ const text = asString(event.text) ?? asString(event.delta);
260
+ if (!text) return [];
261
+ state.sawText = true;
262
+ return [{ type: "text_delta", text }];
263
+ }
264
+ if (contentType === "reasoning") {
265
+ const thinking = asString(event.reasoning) ?? asString(event.text) ?? asString(event.delta);
266
+ if (!thinking) return [];
267
+ state.sawThinking = true;
268
+ return [{ type: "thinking_delta", thinking }];
269
+ }
270
+ return [];
271
+ }
272
+
245
273
  if (type === "content_end") {
246
274
  const contentType = asString(event.contentType);
247
275
  if (contentType === "text" && !state.sawText) {
@@ -315,7 +343,7 @@ export function mapClineMessage(
315
343
  const usage = usageFrom(message.usage) ?? state.usage;
316
344
  if (usage) state.usage = usage;
317
345
  const finishReason = asString(message.finishReason);
318
- if (finishReason && finishReason !== "completed" && finishReason !== "stop") {
346
+ if (finishReason && finishReason !== "completed" && finishReason !== "stop" && finishReason !== "end_turn") {
319
347
  const messageText = safeMessage(message.text ?? `Cline finished with ${finishReason}.`);
320
348
  state.terminal = true;
321
349
  return [{ type: "error", message: messageText, ...classifyError(messageText) }];
@@ -355,8 +383,25 @@ export function mapClineMessage(
355
383
  return [];
356
384
  }
357
385
 
386
+ function extractStderrErrorMessage(stderr: string): string | undefined {
387
+ for (const line of stderr.split(/\r?\n/)) {
388
+ const trimmed = line.trim();
389
+ if (!trimmed.startsWith("{")) continue;
390
+ try {
391
+ const record = asRecord(JSON.parse(trimmed));
392
+ if (!record) continue;
393
+ const candidate = asString(asRecord(record.error)?.message)
394
+ ?? (record.type === "error" || typeof record.message === "string" ? asString(record.message) : undefined);
395
+ if (candidate?.trim()) return candidate.trim();
396
+ } catch {
397
+ // Ignore non-JSON stderr diagnostic lines.
398
+ }
399
+ }
400
+ return undefined;
401
+ }
402
+
358
403
  /** Convert a nonzero process exit into a stable terminal error. */
359
404
  export function classifyClineFailure(exitCode: number, stderr: string): Extract<AdapterEvent, { type: "error" }> {
360
- const detail = safeMessage(stderr.trim() || `Cline exited with code ${exitCode}.`);
405
+ const detail = safeMessage(extractStderrErrorMessage(stderr) ?? (stderr.trim() || `Cline exited with code ${exitCode}.`));
361
406
  return { type: "error", message: detail, ...classifyError(detail) };
362
407
  }
@@ -9,7 +9,7 @@ export function resolveGeminiBinary(
9
9
  ): string | undefined {
10
10
  const explicit = env.GEMINI_BIN_PATH?.trim();
11
11
  if (explicit && existsSync(explicit)) return explicit;
12
- return which("gemini");
12
+ return which === whichFromPath ? whichFromPath("gemini", { env }) : which("gemini");
13
13
  }
14
14
 
15
15
  export function geminiBinaryFingerprintSync(binary: string): string {