@posthog/agent 2.3.168 → 2.3.169

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.
@@ -509,7 +509,7 @@ var require_has_flag = __commonJS({
509
509
  var require_supports_color = __commonJS({
510
510
  "../../node_modules/supports-color/index.js"(exports2, module2) {
511
511
  "use strict";
512
- var os6 = require("os");
512
+ var os7 = require("os");
513
513
  var tty = require("tty");
514
514
  var hasFlag = require_has_flag();
515
515
  var { env } = process;
@@ -557,7 +557,7 @@ var require_supports_color = __commonJS({
557
557
  return min;
558
558
  }
559
559
  if (process.platform === "win32") {
560
- const osRelease = os6.release().split(".");
560
+ const osRelease = os7.release().split(".");
561
561
  if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
562
562
  return Number(osRelease[2]) >= 14931 ? 3 : 2;
563
563
  }
@@ -805,10 +805,10 @@ var require_src2 = __commonJS({
805
805
  var fs_1 = require("fs");
806
806
  var debug_1 = __importDefault(require_src());
807
807
  var log = debug_1.default("@kwsites/file-exists");
808
- function check(path12, isFile, isDirectory) {
809
- log(`checking %s`, path12);
808
+ function check(path13, isFile, isDirectory) {
809
+ log(`checking %s`, path13);
810
810
  try {
811
- const stat = fs_1.statSync(path12);
811
+ const stat = fs_1.statSync(path13);
812
812
  if (stat.isFile() && isFile) {
813
813
  log(`[OK] path represents a file`);
814
814
  return true;
@@ -828,8 +828,8 @@ var require_src2 = __commonJS({
828
828
  throw e;
829
829
  }
830
830
  }
831
- function exists2(path12, type = exports2.READABLE) {
832
- return check(path12, (type & exports2.FILE) > 0, (type & exports2.FOLDER) > 0);
831
+ function exists2(path13, type = exports2.READABLE) {
832
+ return check(path13, (type & exports2.FILE) > 0, (type & exports2.FOLDER) > 0);
833
833
  }
834
834
  exports2.exists = exists2;
835
835
  exports2.FILE = 1;
@@ -897,14 +897,14 @@ var import_commander = require("commander");
897
897
  var import_zod4 = require("zod");
898
898
 
899
899
  // src/server/agent-server.ts
900
- var import_sdk4 = require("@agentclientprotocol/sdk");
900
+ var import_sdk5 = require("@agentclientprotocol/sdk");
901
901
  var import_node_server = require("@hono/node-server");
902
902
  var import_hono = require("hono");
903
903
 
904
904
  // package.json
905
905
  var package_default = {
906
906
  name: "@posthog/agent",
907
- version: "2.3.168",
907
+ version: "2.3.169",
908
908
  repository: "https://github.com/PostHog/code",
909
909
  description: "TypeScript agent framework wrapping Claude Agent SDK with Git-based task execution for PostHog",
910
910
  exports: {
@@ -1066,64 +1066,7 @@ var POSTHOG_NOTIFICATIONS = {
1066
1066
  };
1067
1067
 
1068
1068
  // src/adapters/acp-connection.ts
1069
- var import_sdk3 = require("@agentclientprotocol/sdk");
1070
-
1071
- // src/gateway-models.ts
1072
- var DEFAULT_GATEWAY_MODEL = "claude-opus-4-6";
1073
- var BLOCKED_MODELS = /* @__PURE__ */ new Set(["gpt-5-mini", "openai/gpt-5-mini"]);
1074
- var CACHE_TTL = 10 * 60 * 1e3;
1075
- var gatewayModelsCache = null;
1076
- async function fetchGatewayModels(options) {
1077
- const gatewayUrl = options?.gatewayUrl ?? process.env.ANTHROPIC_BASE_URL;
1078
- if (!gatewayUrl) {
1079
- return [];
1080
- }
1081
- if (gatewayModelsCache && gatewayModelsCache.url === gatewayUrl && Date.now() < gatewayModelsCache.expiry) {
1082
- return gatewayModelsCache.models;
1083
- }
1084
- const modelsUrl = `${gatewayUrl}/v1/models`;
1085
- try {
1086
- const response = await fetch(modelsUrl);
1087
- if (!response.ok) {
1088
- return [];
1089
- }
1090
- const data = await response.json();
1091
- const models = (data.data ?? []).filter((m) => !BLOCKED_MODELS.has(m.id));
1092
- gatewayModelsCache = {
1093
- models,
1094
- expiry: Date.now() + CACHE_TTL,
1095
- url: gatewayUrl
1096
- };
1097
- return models;
1098
- } catch {
1099
- return [];
1100
- }
1101
- }
1102
- function isAnthropicModel(model) {
1103
- if (model.owned_by) {
1104
- return model.owned_by === "anthropic";
1105
- }
1106
- return model.id.startsWith("claude-") || model.id.startsWith("anthropic/");
1107
- }
1108
- var PROVIDER_PREFIXES = ["anthropic/", "openai/", "google-vertex/"];
1109
- function formatGatewayModelName(model) {
1110
- return formatModelId(model.id);
1111
- }
1112
- function formatModelId(modelId) {
1113
- let cleanId = modelId;
1114
- for (const prefix of PROVIDER_PREFIXES) {
1115
- if (cleanId.startsWith(prefix)) {
1116
- cleanId = cleanId.slice(prefix.length);
1117
- break;
1118
- }
1119
- }
1120
- cleanId = cleanId.replace(/(\d)-(\d)/g, "$1.$2");
1121
- const words = cleanId.split(/[-_]/).map((word) => {
1122
- if (word.match(/^[0-9.]+$/)) return word;
1123
- return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
1124
- });
1125
- return words.join(" ");
1126
- }
1069
+ var import_sdk4 = require("@agentclientprotocol/sdk");
1127
1070
 
1128
1071
  // src/utils/logger.ts
1129
1072
  var Logger = class _Logger {
@@ -1382,6 +1325,63 @@ function unreachable(value, logger) {
1382
1325
  logger.error(`Unexpected case: ${valueAsString}`);
1383
1326
  }
1384
1327
 
1328
+ // src/gateway-models.ts
1329
+ var DEFAULT_GATEWAY_MODEL = "claude-opus-4-6";
1330
+ var BLOCKED_MODELS = /* @__PURE__ */ new Set(["gpt-5-mini", "openai/gpt-5-mini"]);
1331
+ var CACHE_TTL = 10 * 60 * 1e3;
1332
+ var gatewayModelsCache = null;
1333
+ async function fetchGatewayModels(options) {
1334
+ const gatewayUrl = options?.gatewayUrl ?? process.env.ANTHROPIC_BASE_URL;
1335
+ if (!gatewayUrl) {
1336
+ return [];
1337
+ }
1338
+ if (gatewayModelsCache && gatewayModelsCache.url === gatewayUrl && Date.now() < gatewayModelsCache.expiry) {
1339
+ return gatewayModelsCache.models;
1340
+ }
1341
+ const modelsUrl = `${gatewayUrl}/v1/models`;
1342
+ try {
1343
+ const response = await fetch(modelsUrl);
1344
+ if (!response.ok) {
1345
+ return [];
1346
+ }
1347
+ const data = await response.json();
1348
+ const models = (data.data ?? []).filter((m) => !BLOCKED_MODELS.has(m.id));
1349
+ gatewayModelsCache = {
1350
+ models,
1351
+ expiry: Date.now() + CACHE_TTL,
1352
+ url: gatewayUrl
1353
+ };
1354
+ return models;
1355
+ } catch {
1356
+ return [];
1357
+ }
1358
+ }
1359
+ function isAnthropicModel(model) {
1360
+ if (model.owned_by) {
1361
+ return model.owned_by === "anthropic";
1362
+ }
1363
+ return model.id.startsWith("claude-") || model.id.startsWith("anthropic/");
1364
+ }
1365
+ var PROVIDER_PREFIXES = ["anthropic/", "openai/", "google-vertex/"];
1366
+ function formatGatewayModelName(model) {
1367
+ return formatModelId(model.id);
1368
+ }
1369
+ function formatModelId(modelId) {
1370
+ let cleanId = modelId;
1371
+ for (const prefix of PROVIDER_PREFIXES) {
1372
+ if (cleanId.startsWith(prefix)) {
1373
+ cleanId = cleanId.slice(prefix.length);
1374
+ break;
1375
+ }
1376
+ }
1377
+ cleanId = cleanId.replace(/(\d)-(\d)/g, "$1.$2");
1378
+ const words = cleanId.split(/[-_]/).map((word) => {
1379
+ if (word.match(/^[0-9.]+$/)) return word;
1380
+ return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
1381
+ });
1382
+ return words.join(" ");
1383
+ }
1384
+
1385
1385
  // src/adapters/base-acp-agent.ts
1386
1386
  var DEFAULT_CONTEXT_WINDOW = 2e5;
1387
1387
  var BaseAcpAgent = class {
@@ -1589,8 +1589,8 @@ var ToolContentBuilder = class {
1589
1589
  this.items.push({ type: "content", content: image(data, mimeType, uri) });
1590
1590
  return this;
1591
1591
  }
1592
- diff(path12, oldText, newText) {
1593
- this.items.push({ type: "diff", path: path12, oldText, newText });
1592
+ diff(path13, oldText, newText) {
1593
+ this.items.push({ type: "diff", path: path13, oldText, newText });
1594
1594
  return this;
1595
1595
  }
1596
1596
  build() {
@@ -5001,6 +5001,185 @@ var ClaudeAcpAgent = class extends BaseAcpAgent {
5001
5001
  }
5002
5002
  };
5003
5003
 
5004
+ // src/adapters/codex/codex-agent.ts
5005
+ var import_sdk3 = require("@agentclientprotocol/sdk");
5006
+
5007
+ // src/adapters/codex/codex-client.ts
5008
+ function createCodexClient(upstreamClient, logger, sessionState, callbacks) {
5009
+ const terminalHandles = /* @__PURE__ */ new Map();
5010
+ return {
5011
+ async requestPermission(params) {
5012
+ logger.debug("Relaying permission request to upstream", {
5013
+ sessionId: params.sessionId
5014
+ });
5015
+ return upstreamClient.requestPermission(params);
5016
+ },
5017
+ async sessionUpdate(params) {
5018
+ const update = params.update;
5019
+ if (update?.sessionUpdate === "usage_update") {
5020
+ const used = update.used;
5021
+ const size = update.size;
5022
+ if (used !== void 0) sessionState.contextUsed = used;
5023
+ if (size !== void 0) sessionState.contextSize = size;
5024
+ callbacks?.onUsageUpdate?.(update);
5025
+ }
5026
+ await upstreamClient.sessionUpdate(params);
5027
+ },
5028
+ async readTextFile(params) {
5029
+ return upstreamClient.readTextFile(params);
5030
+ },
5031
+ async writeTextFile(params) {
5032
+ return upstreamClient.writeTextFile(params);
5033
+ },
5034
+ async createTerminal(params) {
5035
+ const handle = await upstreamClient.createTerminal(params);
5036
+ terminalHandles.set(handle.id, handle);
5037
+ return { terminalId: handle.id };
5038
+ },
5039
+ async terminalOutput(params) {
5040
+ const handle = terminalHandles.get(params.terminalId);
5041
+ if (!handle) {
5042
+ return { output: "", truncated: false };
5043
+ }
5044
+ return handle.currentOutput();
5045
+ },
5046
+ async releaseTerminal(params) {
5047
+ const handle = terminalHandles.get(params.terminalId);
5048
+ if (handle) {
5049
+ terminalHandles.delete(params.terminalId);
5050
+ const result = await handle.release();
5051
+ return result ?? void 0;
5052
+ }
5053
+ },
5054
+ async waitForTerminalExit(params) {
5055
+ const handle = terminalHandles.get(params.terminalId);
5056
+ if (!handle) {
5057
+ return { exitCode: 1 };
5058
+ }
5059
+ return handle.waitForExit();
5060
+ },
5061
+ async killTerminal(params) {
5062
+ const handle = terminalHandles.get(params.terminalId);
5063
+ if (handle) {
5064
+ return handle.kill();
5065
+ }
5066
+ },
5067
+ async extMethod(method, params) {
5068
+ return upstreamClient.extMethod(method, params);
5069
+ },
5070
+ async extNotification(method, params) {
5071
+ return upstreamClient.extNotification(method, params);
5072
+ }
5073
+ };
5074
+ }
5075
+
5076
+ // src/adapters/codex/session-state.ts
5077
+ function createSessionState(sessionId, cwd, opts) {
5078
+ return {
5079
+ sessionId,
5080
+ cwd,
5081
+ modeId: opts?.modeId ?? "default",
5082
+ modelId: opts?.modelId,
5083
+ configOptions: [],
5084
+ accumulatedUsage: {
5085
+ inputTokens: 0,
5086
+ outputTokens: 0,
5087
+ cachedReadTokens: 0,
5088
+ cachedWriteTokens: 0
5089
+ },
5090
+ cancelled: false,
5091
+ taskRunId: opts?.taskRunId,
5092
+ taskId: opts?.taskId
5093
+ };
5094
+ }
5095
+ function resetUsage(state) {
5096
+ state.accumulatedUsage = {
5097
+ inputTokens: 0,
5098
+ outputTokens: 0,
5099
+ cachedReadTokens: 0,
5100
+ cachedWriteTokens: 0
5101
+ };
5102
+ }
5103
+
5104
+ // src/adapters/codex/settings.ts
5105
+ var fs5 = __toESM(require("fs"), 1);
5106
+ var os5 = __toESM(require("os"), 1);
5107
+ var path7 = __toESM(require("path"), 1);
5108
+ var CodexSettingsManager = class {
5109
+ cwd;
5110
+ settings = {};
5111
+ initialized = false;
5112
+ constructor(cwd) {
5113
+ this.cwd = cwd;
5114
+ }
5115
+ async initialize() {
5116
+ if (this.initialized) {
5117
+ return;
5118
+ }
5119
+ await this.loadSettings();
5120
+ this.initialized = true;
5121
+ }
5122
+ getConfigPath() {
5123
+ return path7.join(os5.homedir(), ".codex", "config.toml");
5124
+ }
5125
+ async loadSettings() {
5126
+ const configPath = this.getConfigPath();
5127
+ try {
5128
+ const content = await fs5.promises.readFile(configPath, "utf-8");
5129
+ this.settings = parseCodexToml(content, this.cwd);
5130
+ } catch {
5131
+ this.settings = {};
5132
+ }
5133
+ }
5134
+ getSettings() {
5135
+ return this.settings;
5136
+ }
5137
+ getCwd() {
5138
+ return this.cwd;
5139
+ }
5140
+ async setCwd(cwd) {
5141
+ if (this.cwd === cwd) {
5142
+ return;
5143
+ }
5144
+ this.dispose();
5145
+ this.cwd = cwd;
5146
+ this.initialized = false;
5147
+ await this.initialize();
5148
+ }
5149
+ dispose() {
5150
+ this.initialized = false;
5151
+ }
5152
+ };
5153
+ function parseCodexToml(content, cwd) {
5154
+ const settings = {};
5155
+ let currentSection = "";
5156
+ for (const line of content.split("\n")) {
5157
+ const trimmed2 = line.trim();
5158
+ if (!trimmed2 || trimmed2.startsWith("#")) continue;
5159
+ const sectionMatch = trimmed2.match(/^\[(.+)\]$/);
5160
+ if (sectionMatch) {
5161
+ currentSection = sectionMatch[1] ?? "";
5162
+ continue;
5163
+ }
5164
+ const kvMatch = trimmed2.match(/^(\w+)\s*=\s*(.+)$/);
5165
+ if (!kvMatch) continue;
5166
+ const key = kvMatch[1];
5167
+ let value = kvMatch[2]?.trim() ?? "";
5168
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
5169
+ value = value.slice(1, -1);
5170
+ }
5171
+ if (!currentSection) {
5172
+ if (key === "model") settings.model = value;
5173
+ if (key === "personality") settings.personality = value;
5174
+ if (key === "model_reasoning_effort")
5175
+ settings.modelReasoningEffort = value;
5176
+ } else if (currentSection === `projects."${cwd}"`) {
5177
+ if (key === "trust_level") settings.trustLevel = value;
5178
+ }
5179
+ }
5180
+ return settings;
5181
+ }
5182
+
5004
5183
  // src/adapters/codex/spawn.ts
5005
5184
  var import_node_child_process2 = require("child_process");
5006
5185
  var import_node_fs2 = require("fs");
@@ -5097,64 +5276,216 @@ function spawnCodexProcess(options) {
5097
5276
  };
5098
5277
  }
5099
5278
 
5100
- // src/adapters/acp-connection.ts
5101
- function isGroupedOptions(options) {
5102
- return options.length > 0 && "group" in options[0];
5103
- }
5104
- function formatOption(o) {
5105
- if (!o.value) return o;
5106
- return { ...o, name: formatModelId(o.value) };
5107
- }
5108
- function filterModelConfigOptions(msg, allowedModelIds) {
5109
- const payload = msg;
5110
- const configOptions = payload.result?.configOptions ?? payload.params?.update?.configOptions;
5111
- if (!configOptions) return null;
5112
- const filtered = configOptions.map((opt) => {
5113
- if (opt.category !== "model" || !opt.options) return opt;
5114
- const options = opt.options;
5115
- if (isGroupedOptions(options)) {
5116
- const filteredOptions2 = options.map((group) => ({
5117
- ...group,
5118
- options: (group.options ?? []).filter((o) => o?.value && allowedModelIds.has(o.value)).map(formatOption)
5119
- }));
5120
- const flat = filteredOptions2.flatMap((g) => g.options ?? []);
5121
- const currentAllowed2 = opt.currentValue && allowedModelIds.has(opt.currentValue);
5122
- const nextCurrent2 = currentAllowed2 || flat.length === 0 ? opt.currentValue : flat[0]?.value;
5123
- return {
5124
- ...opt,
5125
- currentValue: nextCurrent2,
5126
- options: filteredOptions2
5127
- };
5128
- }
5129
- const valueOptions = options;
5130
- const filteredOptions = valueOptions.filter((o) => o?.value && allowedModelIds.has(o.value)).map(formatOption);
5131
- const currentAllowed = opt.currentValue && allowedModelIds.has(opt.currentValue);
5132
- const nextCurrent = currentAllowed || filteredOptions.length === 0 ? opt.currentValue : filteredOptions[0]?.value;
5279
+ // src/adapters/codex/codex-agent.ts
5280
+ var CodexAcpAgent = class extends BaseAcpAgent {
5281
+ adapterName = "codex";
5282
+ codexProcess;
5283
+ codexConnection;
5284
+ sessionState;
5285
+ constructor(client, options) {
5286
+ super(client);
5287
+ this.logger = new Logger({ debug: true, prefix: "[CodexAcpAgent]" });
5288
+ this.codexProcess = spawnCodexProcess({
5289
+ ...options.codexProcessOptions,
5290
+ logger: this.logger,
5291
+ processCallbacks: options.processCallbacks
5292
+ });
5293
+ const codexReadable = nodeReadableToWebReadable(this.codexProcess.stdout);
5294
+ const codexWritable = nodeWritableToWebWritable(this.codexProcess.stdin);
5295
+ const codexStream = (0, import_sdk3.ndJsonStream)(codexWritable, codexReadable);
5296
+ const cwd = options.codexProcessOptions.cwd ?? process.cwd();
5297
+ const settingsManager = new CodexSettingsManager(cwd);
5298
+ const abortController = new AbortController();
5299
+ this.session = {
5300
+ abortController,
5301
+ settingsManager,
5302
+ notificationHistory: [],
5303
+ cancelled: false
5304
+ };
5305
+ this.codexConnection = new import_sdk3.ClientSideConnection(
5306
+ (_agent) => createCodexClient(
5307
+ this.client,
5308
+ this.logger,
5309
+ this.sessionState ?? {
5310
+ sessionId: "",
5311
+ cwd: "",
5312
+ modeId: "default",
5313
+ configOptions: [],
5314
+ accumulatedUsage: {
5315
+ inputTokens: 0,
5316
+ outputTokens: 0,
5317
+ cachedReadTokens: 0,
5318
+ cachedWriteTokens: 0
5319
+ },
5320
+ cancelled: false
5321
+ }
5322
+ ),
5323
+ codexStream
5324
+ );
5325
+ }
5326
+ async initialize(request) {
5327
+ await this.session.settingsManager.initialize();
5328
+ const response = await this.codexConnection.initialize(request);
5133
5329
  return {
5134
- ...opt,
5135
- currentValue: nextCurrent,
5136
- options: filteredOptions
5330
+ ...response,
5331
+ agentCapabilities: {
5332
+ ...response.agentCapabilities,
5333
+ sessionCapabilities: {
5334
+ ...response.agentCapabilities?.sessionCapabilities,
5335
+ resume: {},
5336
+ fork: {}
5337
+ },
5338
+ _meta: {
5339
+ posthog: {
5340
+ resumeSession: true
5341
+ }
5342
+ }
5343
+ },
5344
+ agentInfo: {
5345
+ name: package_default.name,
5346
+ title: "Codex Agent",
5347
+ version: package_default.version
5348
+ }
5137
5349
  };
5138
- });
5139
- if (payload.result?.configOptions) {
5140
- return { ...msg, result: { ...payload.result, configOptions: filtered } };
5141
5350
  }
5142
- if (payload.params?.update?.configOptions) {
5351
+ async newSession(params) {
5352
+ const meta = params._meta;
5353
+ const response = await this.codexConnection.newSession(params);
5354
+ this.sessionState = createSessionState(response.sessionId, params.cwd, {
5355
+ taskRunId: meta?.taskRunId,
5356
+ taskId: meta?.taskId ?? meta?.persistence?.taskId,
5357
+ modeId: response.modes?.currentModeId ?? "default",
5358
+ modelId: response.models?.currentModelId
5359
+ });
5360
+ this.sessionId = response.sessionId;
5361
+ this.sessionState.configOptions = response.configOptions ?? [];
5362
+ if (meta?.taskRunId) {
5363
+ await this.client.extNotification(POSTHOG_NOTIFICATIONS.SDK_SESSION, {
5364
+ taskRunId: meta.taskRunId,
5365
+ sessionId: response.sessionId,
5366
+ adapter: "codex"
5367
+ });
5368
+ }
5369
+ this.logger.info("Codex session created", {
5370
+ sessionId: response.sessionId,
5371
+ taskRunId: meta?.taskRunId
5372
+ });
5373
+ return response;
5374
+ }
5375
+ async loadSession(params) {
5376
+ const response = await this.codexConnection.loadSession(params);
5377
+ this.sessionState = createSessionState(params.sessionId, params.cwd);
5378
+ this.sessionId = params.sessionId;
5379
+ this.sessionState.configOptions = response.configOptions ?? [];
5380
+ return response;
5381
+ }
5382
+ async unstable_resumeSession(params) {
5383
+ const loadResponse = await this.codexConnection.loadSession({
5384
+ sessionId: params.sessionId,
5385
+ cwd: params.cwd,
5386
+ mcpServers: params.mcpServers ?? []
5387
+ });
5388
+ this.sessionState = createSessionState(params.sessionId, params.cwd);
5389
+ this.sessionId = params.sessionId;
5390
+ this.sessionState.configOptions = loadResponse.configOptions ?? [];
5391
+ const meta = params._meta;
5392
+ if (meta?.taskRunId) {
5393
+ await this.client.extNotification(POSTHOG_NOTIFICATIONS.SDK_SESSION, {
5394
+ taskRunId: meta.taskRunId,
5395
+ sessionId: params.sessionId,
5396
+ adapter: "codex"
5397
+ });
5398
+ }
5143
5399
  return {
5144
- ...msg,
5145
- params: {
5146
- ...payload.params,
5147
- update: { ...payload.params.update, configOptions: filtered }
5148
- }
5400
+ modes: loadResponse.modes,
5401
+ models: loadResponse.models,
5402
+ configOptions: loadResponse.configOptions
5149
5403
  };
5150
5404
  }
5151
- return null;
5152
- }
5153
- function extractReasoningEffort(configOptions) {
5154
- if (!configOptions) return void 0;
5155
- const option = configOptions.find((opt) => opt.id === "reasoning_effort");
5156
- return option?.currentValue ?? void 0;
5157
- }
5405
+ async unstable_forkSession(params) {
5406
+ const newResponse = await this.codexConnection.newSession({
5407
+ cwd: params.cwd,
5408
+ mcpServers: params.mcpServers ?? [],
5409
+ _meta: params._meta
5410
+ });
5411
+ this.sessionState = createSessionState(newResponse.sessionId, params.cwd);
5412
+ this.sessionId = newResponse.sessionId;
5413
+ this.sessionState.configOptions = newResponse.configOptions ?? [];
5414
+ return newResponse;
5415
+ }
5416
+ async listSessions(params) {
5417
+ return this.codexConnection.listSessions(params);
5418
+ }
5419
+ async unstable_listSessions(params) {
5420
+ return this.codexConnection.listSessions(params);
5421
+ }
5422
+ async prompt(params) {
5423
+ if (this.sessionState) {
5424
+ this.sessionState.cancelled = false;
5425
+ this.sessionState.interruptReason = void 0;
5426
+ resetUsage(this.sessionState);
5427
+ }
5428
+ const response = await this.codexConnection.prompt(params);
5429
+ if (this.sessionState?.taskRunId && response.usage) {
5430
+ await this.client.extNotification("_posthog/usage_update", {
5431
+ sessionId: params.sessionId,
5432
+ used: {
5433
+ inputTokens: response.usage.inputTokens ?? 0,
5434
+ outputTokens: response.usage.outputTokens ?? 0,
5435
+ cachedReadTokens: response.usage.cachedReadTokens ?? 0,
5436
+ cachedWriteTokens: response.usage.cachedWriteTokens ?? 0
5437
+ },
5438
+ cost: null
5439
+ });
5440
+ }
5441
+ return response;
5442
+ }
5443
+ async interrupt() {
5444
+ if (this.sessionState) {
5445
+ this.sessionState.cancelled = true;
5446
+ }
5447
+ await this.codexConnection.cancel({
5448
+ sessionId: this.sessionId
5449
+ });
5450
+ }
5451
+ async cancel(params) {
5452
+ if (this.sessionState) {
5453
+ this.sessionState.cancelled = true;
5454
+ const meta = params._meta;
5455
+ if (meta?.interruptReason) {
5456
+ this.sessionState.interruptReason = meta.interruptReason;
5457
+ }
5458
+ }
5459
+ await this.codexConnection.cancel(params);
5460
+ }
5461
+ async setSessionMode(params) {
5462
+ const response = await this.codexConnection.setSessionMode(params);
5463
+ if (this.sessionState) {
5464
+ this.sessionState.modeId = params.modeId;
5465
+ }
5466
+ return response ?? {};
5467
+ }
5468
+ async setSessionConfigOption(params) {
5469
+ const response = await this.codexConnection.setSessionConfigOption(params);
5470
+ if (this.sessionState && response.configOptions) {
5471
+ this.sessionState.configOptions = response.configOptions;
5472
+ }
5473
+ return response;
5474
+ }
5475
+ async authenticate(_params) {
5476
+ }
5477
+ async closeSession() {
5478
+ this.logger.info("Closing Codex session", { sessionId: this.sessionId });
5479
+ this.session.settingsManager.dispose();
5480
+ try {
5481
+ this.codexProcess.kill();
5482
+ } catch (err) {
5483
+ this.logger.warn("Failed to kill codex-acp process", { error: err });
5484
+ }
5485
+ }
5486
+ };
5487
+
5488
+ // src/adapters/acp-connection.ts
5158
5489
  function createAcpConnection(config = {}) {
5159
5490
  const adapterType = config.adapter ?? "claude";
5160
5491
  if (adapterType === "codex") {
@@ -5195,9 +5526,9 @@ function createClaudeConnection(config) {
5195
5526
  hasLogWriter: !!logWriter
5196
5527
  });
5197
5528
  }
5198
- const agentStream = (0, import_sdk3.ndJsonStream)(agentWritable, streams.agent.readable);
5529
+ const agentStream = (0, import_sdk4.ndJsonStream)(agentWritable, streams.agent.readable);
5199
5530
  let agent = null;
5200
- const agentConnection = new import_sdk3.AgentSideConnection((client) => {
5531
+ const agentConnection = new import_sdk4.AgentSideConnection((client) => {
5201
5532
  agent = new ClaudeAcpAgent(client, config.processCallbacks);
5202
5533
  logger.info(`Created ${agent.adapterName} agent`);
5203
5534
  return agent;
@@ -5227,214 +5558,63 @@ function createClaudeConnection(config) {
5227
5558
  function createCodexConnection(config) {
5228
5559
  const logger = config.logger?.child("CodexConnection") ?? new Logger({ debug: true, prefix: "[CodexConnection]" });
5229
5560
  const { logWriter } = config;
5230
- const allowedModelIds = config.allowedModelIds;
5231
- const codexProcess = spawnCodexProcess({
5232
- ...config.codexOptions,
5233
- logger,
5234
- processCallbacks: config.processCallbacks
5235
- });
5236
- let clientReadable = nodeReadableToWebReadable(codexProcess.stdout);
5237
- let clientWritable = nodeWritableToWebWritable(codexProcess.stdin);
5238
- let isLoadingSession = false;
5239
- let loadRequestId = null;
5240
- let newSessionRequestId = null;
5241
- let sdkSessionEmitted = false;
5242
- const reasoningEffortBySessionId = /* @__PURE__ */ new Map();
5243
- let injectedConfigId = 0;
5244
- const decoder = new TextDecoder();
5245
- const encoder = new TextEncoder();
5246
- let readBuffer = "";
5247
- const taskRunId = config.taskRunId;
5248
- const filteringReadable = clientReadable.pipeThrough(
5249
- new TransformStream({
5250
- transform(chunk, controller) {
5251
- readBuffer += decoder.decode(chunk, { stream: true });
5252
- const lines = readBuffer.split("\n");
5253
- readBuffer = lines.pop() ?? "";
5254
- const outputLines = [];
5255
- for (const line of lines) {
5256
- const trimmed2 = line.trim();
5257
- if (!trimmed2) {
5258
- outputLines.push(line);
5259
- continue;
5260
- }
5261
- let shouldFilter = false;
5262
- try {
5263
- const msg = JSON.parse(trimmed2);
5264
- const sessionId = msg?.params?.sessionId ?? msg?.result?.sessionId ?? null;
5265
- const configOptions = msg?.result?.configOptions ?? msg?.params?.update?.configOptions;
5266
- if (sessionId && configOptions) {
5267
- const effort = extractReasoningEffort(configOptions);
5268
- if (effort) {
5269
- reasoningEffortBySessionId.set(sessionId, effort);
5270
- }
5271
- }
5272
- if (!sdkSessionEmitted && newSessionRequestId !== null && msg.id === newSessionRequestId && "result" in msg) {
5273
- const sessionId2 = msg.result?.sessionId;
5274
- if (sessionId2 && taskRunId) {
5275
- const sdkSessionNotification = {
5276
- jsonrpc: "2.0",
5277
- method: POSTHOG_NOTIFICATIONS.SDK_SESSION,
5278
- params: {
5279
- taskRunId,
5280
- sessionId: sessionId2,
5281
- adapter: "codex"
5282
- }
5283
- };
5284
- outputLines.push(JSON.stringify(sdkSessionNotification));
5285
- sdkSessionEmitted = true;
5286
- }
5287
- newSessionRequestId = null;
5288
- }
5289
- if (isLoadingSession) {
5290
- if (msg.id === loadRequestId && "result" in msg) {
5291
- logger.debug("session/load complete, resuming stream");
5292
- isLoadingSession = false;
5293
- loadRequestId = null;
5294
- } else if (msg.method === "session/update") {
5295
- shouldFilter = true;
5296
- }
5297
- }
5298
- if (!shouldFilter && allowedModelIds && allowedModelIds.size > 0) {
5299
- const updated = filterModelConfigOptions(msg, allowedModelIds);
5300
- if (updated) {
5301
- outputLines.push(JSON.stringify(updated));
5302
- continue;
5303
- }
5304
- }
5305
- } catch {
5306
- }
5307
- if (!shouldFilter) {
5308
- outputLines.push(line);
5309
- const isChunkNoise = trimmed2.includes('"sessionUpdate":"agent_message_chunk"') || trimmed2.includes('"sessionUpdate":"agent_thought_chunk"');
5310
- if (!isChunkNoise) {
5311
- logger.debug("codex-acp stdout:", trimmed2);
5312
- }
5313
- }
5314
- }
5315
- if (outputLines.length > 0) {
5316
- const output = `${outputLines.join("\n")}
5317
- `;
5318
- controller.enqueue(encoder.encode(output));
5319
- }
5320
- },
5321
- flush(controller) {
5322
- if (readBuffer.trim()) {
5323
- controller.enqueue(encoder.encode(readBuffer));
5324
- }
5325
- }
5326
- })
5327
- );
5328
- clientReadable = filteringReadable;
5329
- const originalWritable = clientWritable;
5330
- clientWritable = new WritableStream({
5331
- write(chunk) {
5332
- const text2 = decoder.decode(chunk, { stream: true });
5333
- const trimmed2 = text2.trim();
5334
- logger.debug("codex-acp stdin:", trimmed2);
5335
- try {
5336
- const msg = JSON.parse(trimmed2);
5337
- if (msg.method === "session/set_config_option" && msg.params?.configId === "reasoning_effort" && msg.params?.sessionId && msg.params?.value) {
5338
- reasoningEffortBySessionId.set(
5339
- msg.params.sessionId,
5340
- msg.params.value
5341
- );
5342
- }
5343
- if (msg.method === "session/prompt" && msg.params?.sessionId) {
5344
- const effort = reasoningEffortBySessionId.get(msg.params.sessionId);
5345
- if (effort) {
5346
- const injection = {
5347
- jsonrpc: "2.0",
5348
- id: `reasoning_effort_${Date.now()}_${injectedConfigId++}`,
5349
- method: "session/set_config_option",
5350
- params: {
5351
- sessionId: msg.params.sessionId,
5352
- configId: "reasoning_effort",
5353
- value: effort
5354
- }
5355
- };
5356
- const injectionLine = `${JSON.stringify(injection)}
5357
- `;
5358
- const writer2 = originalWritable.getWriter();
5359
- return writer2.write(encoder.encode(injectionLine)).then(() => writer2.releaseLock()).then(() => {
5360
- const nextWriter = originalWritable.getWriter();
5361
- return nextWriter.write(chunk).finally(() => nextWriter.releaseLock());
5362
- });
5363
- }
5364
- }
5365
- if (msg.method === "session/new" && msg.id) {
5366
- logger.debug("session/new detected, tracking request ID");
5367
- newSessionRequestId = msg.id;
5368
- } else if (msg.method === "session/load" && msg.id) {
5369
- logger.debug("session/load detected, pausing stream updates");
5370
- isLoadingSession = true;
5371
- loadRequestId = msg.id;
5372
- }
5373
- } catch {
5374
- }
5375
- const writer = originalWritable.getWriter();
5376
- return writer.write(chunk).finally(() => writer.releaseLock());
5377
- },
5378
- close() {
5379
- const writer = originalWritable.getWriter();
5380
- return writer.close().finally(() => writer.releaseLock());
5381
- }
5382
- });
5383
- const shouldTapLogs = config.taskRunId && logWriter;
5384
- if (shouldTapLogs && config.taskRunId) {
5385
- const taskRunId2 = config.taskRunId;
5386
- if (!logWriter.isRegistered(taskRunId2)) {
5387
- logWriter.register(taskRunId2, {
5388
- taskId: config.taskId ?? taskRunId2,
5389
- runId: taskRunId2
5561
+ const streams = createBidirectionalStreams();
5562
+ let agentWritable = streams.agent.writable;
5563
+ let clientWritable = streams.client.writable;
5564
+ if (config.taskRunId && logWriter) {
5565
+ if (!logWriter.isRegistered(config.taskRunId)) {
5566
+ logWriter.register(config.taskRunId, {
5567
+ taskId: config.taskId ?? config.taskRunId,
5568
+ runId: config.taskRunId,
5569
+ deviceType: config.deviceType
5390
5570
  });
5391
5571
  }
5392
- clientWritable = createTappedWritableStream(clientWritable, {
5572
+ const taskRunId = config.taskRunId;
5573
+ agentWritable = createTappedWritableStream(streams.agent.writable, {
5393
5574
  onMessage: (line) => {
5394
- logWriter.appendRawLine(taskRunId2, line);
5575
+ logWriter.appendRawLine(taskRunId, line);
5576
+ },
5577
+ logger
5578
+ });
5579
+ clientWritable = createTappedWritableStream(streams.client.writable, {
5580
+ onMessage: (line) => {
5581
+ logWriter.appendRawLine(taskRunId, line);
5395
5582
  },
5396
5583
  logger
5397
5584
  });
5398
- const originalReadable = clientReadable;
5399
- const logDecoder = new TextDecoder();
5400
- let logBuffer = "";
5401
- clientReadable = originalReadable.pipeThrough(
5402
- new TransformStream({
5403
- transform(chunk, controller) {
5404
- logBuffer += logDecoder.decode(chunk, { stream: true });
5405
- const lines = logBuffer.split("\n");
5406
- logBuffer = lines.pop() ?? "";
5407
- for (const line of lines) {
5408
- if (line.trim()) {
5409
- logWriter.appendRawLine(taskRunId2, line);
5410
- }
5411
- }
5412
- controller.enqueue(chunk);
5413
- },
5414
- flush() {
5415
- if (logBuffer.trim()) {
5416
- logWriter.appendRawLine(taskRunId2, logBuffer);
5417
- }
5418
- }
5419
- })
5420
- );
5421
5585
  } else {
5422
5586
  logger.info("Tapped streams NOT enabled for Codex", {
5423
5587
  hasTaskRunId: !!config.taskRunId,
5424
5588
  hasLogWriter: !!logWriter
5425
5589
  });
5426
5590
  }
5591
+ const agentStream = (0, import_sdk4.ndJsonStream)(agentWritable, streams.agent.readable);
5592
+ let agent = null;
5593
+ const agentConnection = new import_sdk4.AgentSideConnection((client) => {
5594
+ agent = new CodexAcpAgent(client, {
5595
+ codexProcessOptions: config.codexOptions ?? {},
5596
+ processCallbacks: config.processCallbacks
5597
+ });
5598
+ logger.info(`Created ${agent.adapterName} agent`);
5599
+ return agent;
5600
+ }, agentStream);
5427
5601
  return {
5428
- agentConnection: void 0,
5602
+ agentConnection,
5429
5603
  clientStreams: {
5430
- readable: clientReadable,
5604
+ readable: streams.client.readable,
5431
5605
  writable: clientWritable
5432
5606
  },
5433
5607
  cleanup: async () => {
5434
5608
  logger.info("Cleaning up Codex connection");
5435
- codexProcess.kill();
5609
+ if (agent) {
5610
+ await agent.closeSession();
5611
+ }
5436
5612
  try {
5437
- await clientWritable.close();
5613
+ await streams.client.writable.close();
5614
+ } catch {
5615
+ }
5616
+ try {
5617
+ await streams.agent.writable.close();
5438
5618
  } catch {
5439
5619
  }
5440
5620
  }
@@ -5443,9 +5623,9 @@ function createCodexConnection(config) {
5443
5623
 
5444
5624
  // src/adapters/claude/session/jsonl-hydration.ts
5445
5625
  var import_node_crypto2 = require("crypto");
5446
- var fs5 = __toESM(require("fs/promises"), 1);
5447
- var os5 = __toESM(require("os"), 1);
5448
- var path7 = __toESM(require("path"), 1);
5626
+ var fs6 = __toESM(require("fs/promises"), 1);
5627
+ var os6 = __toESM(require("os"), 1);
5628
+ var path8 = __toESM(require("path"), 1);
5449
5629
  var CHARS_PER_TOKEN = 4;
5450
5630
  var DEFAULT_MAX_TOKENS = 15e4;
5451
5631
  function estimateTurnTokens(turn) {
@@ -5808,8 +5988,8 @@ var Saga = class {
5808
5988
  };
5809
5989
 
5810
5990
  // ../git/dist/queries.js
5811
- var fs7 = __toESM(require("fs/promises"), 1);
5812
- var path9 = __toESM(require("path"), 1);
5991
+ var fs8 = __toESM(require("fs/promises"), 1);
5992
+ var path10 = __toESM(require("path"), 1);
5813
5993
 
5814
5994
  // ../../node_modules/simple-git/dist/esm/index.js
5815
5995
  var import_node_buffer = require("buffer");
@@ -5848,8 +6028,8 @@ function pathspec(...paths) {
5848
6028
  cache.set(key, paths);
5849
6029
  return key;
5850
6030
  }
5851
- function isPathSpec(path12) {
5852
- return path12 instanceof String && cache.has(path12);
6031
+ function isPathSpec(path13) {
6032
+ return path13 instanceof String && cache.has(path13);
5853
6033
  }
5854
6034
  function toPaths(pathSpec) {
5855
6035
  return cache.get(pathSpec) || [];
@@ -5938,8 +6118,8 @@ function toLinesWithContent(input = "", trimmed2 = true, separator = "\n") {
5938
6118
  function forEachLineWithContent(input, callback) {
5939
6119
  return toLinesWithContent(input, true).map((line) => callback(line));
5940
6120
  }
5941
- function folderExists(path12) {
5942
- return (0, import_file_exists.exists)(path12, import_file_exists.FOLDER);
6121
+ function folderExists(path13) {
6122
+ return (0, import_file_exists.exists)(path13, import_file_exists.FOLDER);
5943
6123
  }
5944
6124
  function append(target, item) {
5945
6125
  if (Array.isArray(target)) {
@@ -6343,8 +6523,8 @@ function checkIsRepoRootTask() {
6343
6523
  commands,
6344
6524
  format: "utf-8",
6345
6525
  onError,
6346
- parser(path12) {
6347
- return /^\.(git)?$/.test(path12.trim());
6526
+ parser(path13) {
6527
+ return /^\.(git)?$/.test(path13.trim());
6348
6528
  }
6349
6529
  };
6350
6530
  }
@@ -6778,11 +6958,11 @@ function parseGrep(grep) {
6778
6958
  const paths = /* @__PURE__ */ new Set();
6779
6959
  const results = {};
6780
6960
  forEachLineWithContent(grep, (input) => {
6781
- const [path12, line, preview] = input.split(NULL);
6782
- paths.add(path12);
6783
- (results[path12] = results[path12] || []).push({
6961
+ const [path13, line, preview] = input.split(NULL);
6962
+ paths.add(path13);
6963
+ (results[path13] = results[path13] || []).push({
6784
6964
  line: asNumber(line),
6785
- path: path12,
6965
+ path: path13,
6786
6966
  preview
6787
6967
  });
6788
6968
  });
@@ -7547,14 +7727,14 @@ var init_hash_object = __esm({
7547
7727
  init_task();
7548
7728
  }
7549
7729
  });
7550
- function parseInit(bare, path12, text2) {
7730
+ function parseInit(bare, path13, text2) {
7551
7731
  const response = String(text2).trim();
7552
7732
  let result;
7553
7733
  if (result = initResponseRegex.exec(response)) {
7554
- return new InitSummary(bare, path12, false, result[1]);
7734
+ return new InitSummary(bare, path13, false, result[1]);
7555
7735
  }
7556
7736
  if (result = reInitResponseRegex.exec(response)) {
7557
- return new InitSummary(bare, path12, true, result[1]);
7737
+ return new InitSummary(bare, path13, true, result[1]);
7558
7738
  }
7559
7739
  let gitDir = "";
7560
7740
  const tokens = response.split(" ");
@@ -7565,7 +7745,7 @@ function parseInit(bare, path12, text2) {
7565
7745
  break;
7566
7746
  }
7567
7747
  }
7568
- return new InitSummary(bare, path12, /^re/i.test(response), gitDir);
7748
+ return new InitSummary(bare, path13, /^re/i.test(response), gitDir);
7569
7749
  }
7570
7750
  var InitSummary;
7571
7751
  var initResponseRegex;
@@ -7574,9 +7754,9 @@ var init_InitSummary = __esm({
7574
7754
  "src/lib/responses/InitSummary.ts"() {
7575
7755
  "use strict";
7576
7756
  InitSummary = class {
7577
- constructor(bare, path12, existing, gitDir) {
7757
+ constructor(bare, path13, existing, gitDir) {
7578
7758
  this.bare = bare;
7579
- this.path = path12;
7759
+ this.path = path13;
7580
7760
  this.existing = existing;
7581
7761
  this.gitDir = gitDir;
7582
7762
  }
@@ -7588,7 +7768,7 @@ var init_InitSummary = __esm({
7588
7768
  function hasBareCommand(command) {
7589
7769
  return command.includes(bareCommand);
7590
7770
  }
7591
- function initTask(bare = false, path12, customArgs) {
7771
+ function initTask(bare = false, path13, customArgs) {
7592
7772
  const commands = ["init", ...customArgs];
7593
7773
  if (bare && !hasBareCommand(commands)) {
7594
7774
  commands.splice(1, 0, bareCommand);
@@ -7597,7 +7777,7 @@ function initTask(bare = false, path12, customArgs) {
7597
7777
  commands,
7598
7778
  format: "utf-8",
7599
7779
  parser(text2) {
7600
- return parseInit(commands.includes("--bare"), path12, text2);
7780
+ return parseInit(commands.includes("--bare"), path13, text2);
7601
7781
  }
7602
7782
  };
7603
7783
  }
@@ -8413,12 +8593,12 @@ var init_FileStatusSummary = __esm({
8413
8593
  "use strict";
8414
8594
  fromPathRegex = /^(.+)\0(.+)$/;
8415
8595
  FileStatusSummary = class {
8416
- constructor(path12, index, working_dir) {
8417
- this.path = path12;
8596
+ constructor(path13, index, working_dir) {
8597
+ this.path = path13;
8418
8598
  this.index = index;
8419
8599
  this.working_dir = working_dir;
8420
8600
  if (index === "R" || working_dir === "R") {
8421
- const detail = fromPathRegex.exec(path12) || [null, path12, path12];
8601
+ const detail = fromPathRegex.exec(path13) || [null, path13, path13];
8422
8602
  this.from = detail[2] || "";
8423
8603
  this.path = detail[1] || "";
8424
8604
  }
@@ -8449,14 +8629,14 @@ function splitLine(result, lineStr) {
8449
8629
  default:
8450
8630
  return;
8451
8631
  }
8452
- function data(index, workingDir, path12) {
8632
+ function data(index, workingDir, path13) {
8453
8633
  const raw = `${index}${workingDir}`;
8454
8634
  const handler = parsers6.get(raw);
8455
8635
  if (handler) {
8456
- handler(result, path12);
8636
+ handler(result, path13);
8457
8637
  }
8458
8638
  if (raw !== "##" && raw !== "!!") {
8459
- result.files.push(new FileStatusSummary(path12, index, workingDir));
8639
+ result.files.push(new FileStatusSummary(path13, index, workingDir));
8460
8640
  }
8461
8641
  }
8462
8642
  }
@@ -8769,9 +8949,9 @@ var init_simple_git_api = __esm({
8769
8949
  next
8770
8950
  );
8771
8951
  }
8772
- hashObject(path12, write) {
8952
+ hashObject(path13, write) {
8773
8953
  return this._runTask(
8774
- hashObjectTask(path12, write === true),
8954
+ hashObjectTask(path13, write === true),
8775
8955
  trailingFunctionArgument(arguments)
8776
8956
  );
8777
8957
  }
@@ -9124,8 +9304,8 @@ var init_branch = __esm({
9124
9304
  }
9125
9305
  });
9126
9306
  function toPath(input) {
9127
- const path12 = input.trim().replace(/^["']|["']$/g, "");
9128
- return path12 && (0, import_node_path3.normalize)(path12);
9307
+ const path13 = input.trim().replace(/^["']|["']$/g, "");
9308
+ return path13 && (0, import_node_path3.normalize)(path13);
9129
9309
  }
9130
9310
  var parseCheckIgnore;
9131
9311
  var init_CheckIgnore = __esm({
@@ -9439,8 +9619,8 @@ __export(sub_module_exports, {
9439
9619
  subModuleTask: () => subModuleTask,
9440
9620
  updateSubModuleTask: () => updateSubModuleTask
9441
9621
  });
9442
- function addSubModuleTask(repo, path12) {
9443
- return subModuleTask(["add", repo, path12]);
9622
+ function addSubModuleTask(repo, path13) {
9623
+ return subModuleTask(["add", repo, path13]);
9444
9624
  }
9445
9625
  function initSubModuleTask(customArgs) {
9446
9626
  return subModuleTask(["init", ...customArgs]);
@@ -9770,8 +9950,8 @@ var require_git = __commonJS2({
9770
9950
  }
9771
9951
  return this._runTask(straightThroughStringTask2(command, this._trimmed), next);
9772
9952
  };
9773
- Git2.prototype.submoduleAdd = function(repo, path12, then) {
9774
- return this._runTask(addSubModuleTask2(repo, path12), trailingFunctionArgument2(arguments));
9953
+ Git2.prototype.submoduleAdd = function(repo, path13, then) {
9954
+ return this._runTask(addSubModuleTask2(repo, path13), trailingFunctionArgument2(arguments));
9775
9955
  };
9776
9956
  Git2.prototype.submoduleUpdate = function(args, then) {
9777
9957
  return this._runTask(
@@ -10583,8 +10763,8 @@ var import_node_path5 = require("path");
10583
10763
 
10584
10764
  // ../git/dist/sagas/tree.js
10585
10765
  var import_node_fs3 = require("fs");
10586
- var fs8 = __toESM(require("fs/promises"), 1);
10587
- var path10 = __toESM(require("path"), 1);
10766
+ var fs9 = __toESM(require("fs/promises"), 1);
10767
+ var path11 = __toESM(require("path"), 1);
10588
10768
  var tar = __toESM(require("tar"), 1);
10589
10769
 
10590
10770
  // ../git/dist/git-saga.js
@@ -10611,14 +10791,14 @@ var CaptureTreeSaga = class extends GitSaga {
10611
10791
  tempIndexPath = null;
10612
10792
  async executeGitOperations(input) {
10613
10793
  const { baseDir, lastTreeHash, archivePath, signal } = input;
10614
- const tmpDir = path10.join(baseDir, ".git", "posthog-code-tmp");
10794
+ const tmpDir = path11.join(baseDir, ".git", "posthog-code-tmp");
10615
10795
  await this.step({
10616
10796
  name: "create_tmp_dir",
10617
- execute: () => fs8.mkdir(tmpDir, { recursive: true }),
10797
+ execute: () => fs9.mkdir(tmpDir, { recursive: true }),
10618
10798
  rollback: async () => {
10619
10799
  }
10620
10800
  });
10621
- this.tempIndexPath = path10.join(tmpDir, `index-${Date.now()}`);
10801
+ this.tempIndexPath = path11.join(tmpDir, `index-${Date.now()}`);
10622
10802
  const tempIndexGit = this.git.env({
10623
10803
  ...process.env,
10624
10804
  GIT_INDEX_FILE: this.tempIndexPath
@@ -10628,7 +10808,7 @@ var CaptureTreeSaga = class extends GitSaga {
10628
10808
  execute: () => tempIndexGit.raw(["read-tree", "HEAD"]),
10629
10809
  rollback: async () => {
10630
10810
  if (this.tempIndexPath) {
10631
- await fs8.rm(this.tempIndexPath, { force: true }).catch(() => {
10811
+ await fs9.rm(this.tempIndexPath, { force: true }).catch(() => {
10632
10812
  });
10633
10813
  }
10634
10814
  }
@@ -10637,7 +10817,7 @@ var CaptureTreeSaga = class extends GitSaga {
10637
10817
  const treeHash = await this.readOnlyStep("write_tree", () => tempIndexGit.raw(["write-tree"]));
10638
10818
  if (lastTreeHash && treeHash === lastTreeHash) {
10639
10819
  this.log.debug("No changes since last capture", { treeHash });
10640
- await fs8.rm(this.tempIndexPath, { force: true }).catch(() => {
10820
+ await fs9.rm(this.tempIndexPath, { force: true }).catch(() => {
10641
10821
  });
10642
10822
  return { snapshot: null, changed: false };
10643
10823
  }
@@ -10649,7 +10829,7 @@ var CaptureTreeSaga = class extends GitSaga {
10649
10829
  }
10650
10830
  });
10651
10831
  const changes = await this.readOnlyStep("get_changes", () => this.getChanges(this.git, baseCommit, treeHash));
10652
- await fs8.rm(this.tempIndexPath, { force: true }).catch(() => {
10832
+ await fs9.rm(this.tempIndexPath, { force: true }).catch(() => {
10653
10833
  });
10654
10834
  const snapshot = {
10655
10835
  treeHash,
@@ -10673,15 +10853,15 @@ var CaptureTreeSaga = class extends GitSaga {
10673
10853
  if (filesToArchive.length === 0) {
10674
10854
  return void 0;
10675
10855
  }
10676
- const existingFiles = filesToArchive.filter((f) => (0, import_node_fs3.existsSync)(path10.join(baseDir, f)));
10856
+ const existingFiles = filesToArchive.filter((f) => (0, import_node_fs3.existsSync)(path11.join(baseDir, f)));
10677
10857
  if (existingFiles.length === 0) {
10678
10858
  return void 0;
10679
10859
  }
10680
10860
  await this.step({
10681
10861
  name: "create_archive",
10682
10862
  execute: async () => {
10683
- const archiveDir = path10.dirname(archivePath);
10684
- await fs8.mkdir(archiveDir, { recursive: true });
10863
+ const archiveDir = path11.dirname(archivePath);
10864
+ await fs9.mkdir(archiveDir, { recursive: true });
10685
10865
  await tar.create({
10686
10866
  gzip: true,
10687
10867
  file: archivePath,
@@ -10689,7 +10869,7 @@ var CaptureTreeSaga = class extends GitSaga {
10689
10869
  }, existingFiles);
10690
10870
  },
10691
10871
  rollback: async () => {
10692
- await fs8.rm(archivePath, { force: true }).catch(() => {
10872
+ await fs9.rm(archivePath, { force: true }).catch(() => {
10693
10873
  });
10694
10874
  }
10695
10875
  });
@@ -10789,9 +10969,9 @@ var ApplyTreeSaga = class extends GitSaga {
10789
10969
  const filesToExtract = changes.filter((c) => c.status !== "D").map((c) => c.path);
10790
10970
  await this.readOnlyStep("backup_existing_files", async () => {
10791
10971
  for (const filePath of filesToExtract) {
10792
- const fullPath = path10.join(baseDir, filePath);
10972
+ const fullPath = path11.join(baseDir, filePath);
10793
10973
  try {
10794
- const content = await fs8.readFile(fullPath);
10974
+ const content = await fs9.readFile(fullPath);
10795
10975
  this.fileBackups.set(filePath, content);
10796
10976
  } catch {
10797
10977
  }
@@ -10808,16 +10988,16 @@ var ApplyTreeSaga = class extends GitSaga {
10808
10988
  },
10809
10989
  rollback: async () => {
10810
10990
  for (const filePath of this.extractedFiles) {
10811
- const fullPath = path10.join(baseDir, filePath);
10991
+ const fullPath = path11.join(baseDir, filePath);
10812
10992
  const backup = this.fileBackups.get(filePath);
10813
10993
  if (backup) {
10814
- const dir = path10.dirname(fullPath);
10815
- await fs8.mkdir(dir, { recursive: true }).catch(() => {
10994
+ const dir = path11.dirname(fullPath);
10995
+ await fs9.mkdir(dir, { recursive: true }).catch(() => {
10816
10996
  });
10817
- await fs8.writeFile(fullPath, backup).catch(() => {
10997
+ await fs9.writeFile(fullPath, backup).catch(() => {
10818
10998
  });
10819
10999
  } else {
10820
- await fs8.rm(fullPath, { force: true }).catch(() => {
11000
+ await fs9.rm(fullPath, { force: true }).catch(() => {
10821
11001
  });
10822
11002
  }
10823
11003
  }
@@ -10825,10 +11005,10 @@ var ApplyTreeSaga = class extends GitSaga {
10825
11005
  });
10826
11006
  }
10827
11007
  for (const change of changes.filter((c) => c.status === "D")) {
10828
- const fullPath = path10.join(baseDir, change.path);
11008
+ const fullPath = path11.join(baseDir, change.path);
10829
11009
  const backupContent = await this.readOnlyStep(`backup_${change.path}`, async () => {
10830
11010
  try {
10831
- return await fs8.readFile(fullPath);
11011
+ return await fs9.readFile(fullPath);
10832
11012
  } catch {
10833
11013
  return null;
10834
11014
  }
@@ -10836,15 +11016,15 @@ var ApplyTreeSaga = class extends GitSaga {
10836
11016
  await this.step({
10837
11017
  name: `delete_${change.path}`,
10838
11018
  execute: async () => {
10839
- await fs8.rm(fullPath, { force: true });
11019
+ await fs9.rm(fullPath, { force: true });
10840
11020
  this.log.debug(`Deleted file: ${change.path}`);
10841
11021
  },
10842
11022
  rollback: async () => {
10843
11023
  if (backupContent) {
10844
- const dir = path10.dirname(fullPath);
10845
- await fs8.mkdir(dir, { recursive: true }).catch(() => {
11024
+ const dir = path11.dirname(fullPath);
11025
+ await fs9.mkdir(dir, { recursive: true }).catch(() => {
10846
11026
  });
10847
- await fs8.writeFile(fullPath, backupContent).catch(() => {
11027
+ await fs9.writeFile(fullPath, backupContent).catch(() => {
10848
11028
  });
10849
11029
  }
10850
11030
  }
@@ -12378,13 +12558,13 @@ You MUST NOT create a new branch, close the existing PR, or create a new PR.`
12378
12558
  onAcpMessage,
12379
12559
  this.logger
12380
12560
  );
12381
- const clientStream = (0, import_sdk4.ndJsonStream)(tappedWritable, tappedReadable);
12382
- const clientConnection = new import_sdk4.ClientSideConnection(
12561
+ const clientStream = (0, import_sdk5.ndJsonStream)(tappedWritable, tappedReadable);
12562
+ const clientConnection = new import_sdk5.ClientSideConnection(
12383
12563
  () => this.createCloudClient(payload),
12384
12564
  clientStream
12385
12565
  );
12386
12566
  await clientConnection.initialize({
12387
- protocolVersion: import_sdk4.PROTOCOL_VERSION,
12567
+ protocolVersion: import_sdk5.PROTOCOL_VERSION,
12388
12568
  clientCapabilities: {}
12389
12569
  });
12390
12570
  let preTaskRun = null;