replicas-engine 0.1.1725 → 0.1.1730

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/dist/src/index.js CHANGED
@@ -90,12 +90,12 @@ import {
90
90
  import {
91
91
  getManagedPiMcpServers,
92
92
  managedMcpServerProcess
93
- } from "./chunk-UDR2HT74.js";
93
+ } from "./chunk-OW37FXFJ.js";
94
94
  import {
95
95
  evaluateCommandProtection,
96
96
  extractToolCommand,
97
97
  reportCommandProtectionBlock
98
- } from "./chunk-EZWCNWX2.js";
98
+ } from "./chunk-LIX74B2Y.js";
99
99
  import {
100
100
  ACCOUNT_RATE_LIMITS_UPDATED_METHOD,
101
101
  AGENT_MESSAGE_DELTA_METHOD,
@@ -117,27 +117,35 @@ import {
117
117
  TURN_STARTED_METHOD,
118
118
  dispatchAspNotification,
119
119
  fetchOpencodeModelVariants,
120
+ geminiSelectOption,
120
121
  getOpenCodeGoModel,
121
122
  getOpencodeProvider,
122
123
  hasOpencodeCredentials,
124
+ initializeGeminiAcp,
123
125
  initializeMuse,
124
126
  museTurnStartParams,
125
127
  opencodeConfig,
126
128
  opencodeModelRef,
127
129
  opencodeThinkingVariant,
128
130
  recoverCompletedTurn,
131
+ selectGeminiModel,
132
+ spawnGeminiAcp,
129
133
  spawnMuseMsp,
134
+ startGeminiSession,
130
135
  startMuseSession,
136
+ thinkingVariant,
131
137
  uuidV7
132
- } from "./chunk-4YQ4UWFY.js";
138
+ } from "./chunk-VHY4DMEA.js";
133
139
  import {
140
+ GEMINI_AUTH_PATH,
141
+ GEMINI_CLI_PATH,
134
142
  MUSE_AUTH_PATH,
135
143
  OPENCODE_AUTH_PATH,
136
144
  PI_AUTH_PATH
137
- } from "./chunk-7ZDAVYTV.js";
145
+ } from "./chunk-XCFPXSY4.js";
138
146
  import {
139
147
  publishedPullRequestUrls
140
- } from "./chunk-ESENYL7M.js";
148
+ } from "./chunk-ITJRSUSN.js";
141
149
  import {
142
150
  ACCOUNT_RATE_LIMITS_READ_METHOD,
143
151
  AsyncLock,
@@ -202,6 +210,7 @@ import {
202
210
  recordExhaustedCredential,
203
211
  recordFallbackModel,
204
212
  refreshDelayMs,
213
+ refreshRevocation,
205
214
  rememberSecret,
206
215
  removeCredentialFileLines,
207
216
  removeTempImageFiles,
@@ -214,13 +223,14 @@ import {
214
223
  timestampFromSeconds,
215
224
  transcriptSecrets,
216
225
  upsertCredentialFileLines,
226
+ withdrawAgentLogin,
217
227
  writeSecureCredentialFile
218
- } from "./chunk-3SJP6X3P.js";
228
+ } from "./chunk-KBE3MXTD.js";
219
229
  import {
220
230
  SUBAGENT_MCP_TOOL_TIMEOUT_MS,
221
231
  engineScriptProcess,
222
232
  subagentMcpProcessConfig
223
- } from "./chunk-DHAQM6LA.js";
233
+ } from "./chunk-2HQP6MMR.js";
224
234
  import {
225
235
  ENGINE_ENV,
226
236
  UNQUOTED_PATHS_CONFIG,
@@ -231,18 +241,18 @@ import {
231
241
  resolveDiffBase,
232
242
  setAgentCredentialSnapshot,
233
243
  setLinearSessionId
234
- } from "./chunk-ZYRAETMX.js";
244
+ } from "./chunk-BUJZF6CI.js";
235
245
  import {
236
246
  AspRequestTimeoutError,
237
247
  AspResponseError,
238
248
  buildCodexAgentEnv,
239
249
  getCodexModelProvider
240
- } from "./chunk-LIXZEE44.js";
250
+ } from "./chunk-PIZ63O3B.js";
241
251
  import {
242
252
  SUBPROCESS_MAX_BUFFER,
243
253
  execAsync,
244
254
  execFileAsync
245
- } from "./chunk-APCSKPLU.js";
255
+ } from "./chunk-O2BDFDEA.js";
246
256
  import {
247
257
  isRecord
248
258
  } from "./chunk-UZSNFLDQ.js";
@@ -285,6 +295,7 @@ import {
285
295
  DEFAULT_ASTER_MODEL,
286
296
  DEFAULT_CLAUDE_MODEL,
287
297
  DEFAULT_CURSOR_MODEL,
298
+ DEFAULT_GEMINI_MODEL,
288
299
  DEFAULT_MUSE_MODEL,
289
300
  DEFAULT_OLLAMA_MODEL,
290
301
  DEFAULT_OPENCODE_GO_MODEL,
@@ -452,6 +463,7 @@ import {
452
463
  isAgentChatMcpActivityRecord,
453
464
  isAgentChatSkillActivityRecord,
454
465
  isAgentChatTurnActivityRecord,
466
+ isAuthenticationErrorText,
455
467
  isCanvasTextKind,
456
468
  isChatMessageSender,
457
469
  isClaudeAuthErrorText,
@@ -503,6 +515,7 @@ import {
503
515
  parseProxyRouteCheck,
504
516
  parseReplicasConfigString,
505
517
  percentage,
518
+ providerContextUsage,
506
519
  proxyRouteCheckScript,
507
520
  raceWithTimeout,
508
521
  readChatHistoryAppended,
@@ -522,6 +535,7 @@ import {
522
535
  sendChatMessageRequestSchema,
523
536
  sendChatMessageResponseSchema,
524
537
  serializeCanvasContentResponse,
538
+ serializeGeminiAuthFile,
525
539
  serializeMuseAuthFile,
526
540
  shellQuotePosix,
527
541
  shouldRefreshPullRequests,
@@ -542,7 +556,7 @@ import {
542
556
  workspaceTokenRequestSchema,
543
557
  workspaceTokenResponseSchema,
544
558
  wrapInTag
545
- } from "./chunk-YNHFXBHT.js";
559
+ } from "./chunk-J6MIIMDU.js";
546
560
  import {
547
561
  __commonJS,
548
562
  __export,
@@ -679,7 +693,7 @@ var require_lib = __commonJS({
679
693
  "../node_modules/.bun/which@5.0.0/node_modules/which/lib/index.js"(exports, module) {
680
694
  "use strict";
681
695
  var { isexe, sync: isexeSync } = require_index_min();
682
- var { join: join38, delimiter: delimiter3, sep: sep2, posix } = __require("path");
696
+ var { join: join39, delimiter: delimiter3, sep: sep2, posix } = __require("path");
683
697
  var isWindows = process.platform === "win32";
684
698
  var rSlash = new RegExp(`[${posix.sep}${sep2 === posix.sep ? "" : sep2}]`.replace(/(\\)/g, "\\$1"));
685
699
  var rRel = new RegExp(`^\\.${rSlash.source}`);
@@ -708,7 +722,7 @@ var require_lib = __commonJS({
708
722
  var getPathPart = (raw, cmd) => {
709
723
  const pathPart = /^".*"$/.test(raw) ? raw.slice(1, -1) : raw;
710
724
  const prefix = !pathPart && rRel.test(cmd) ? cmd.slice(0, 2) : "";
711
- return prefix + join38(pathPart, cmd);
725
+ return prefix + join39(pathPart, cmd);
712
726
  };
713
727
  var which = async (cmd, opt = {}) => {
714
728
  const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
@@ -9291,7 +9305,13 @@ var ClaudeTokenManager = class extends BaseRefreshManager {
9291
9305
  }
9292
9306
  async requestAndApplyCredentials(generation, request) {
9293
9307
  console.log("[ClaudeTokenManager] Refreshing Claude credentials...");
9294
- const data = await requestClaudeCredentials(request);
9308
+ const data = await requestClaudeCredentials(request).catch(async (error) => {
9309
+ const revocation = refreshRevocation(error);
9310
+ if (revocation) await this.applyCredentialUpdate(generation, async () => {
9311
+ await withdrawAgentLogin("claude", revocation);
9312
+ });
9313
+ throw error;
9314
+ });
9295
9315
  await this.applyCredentialUpdate(generation, () => this.applyCredentialsResponse(data));
9296
9316
  console.log(`[ClaudeTokenManager] Credentials refreshed (method=${data.type})`);
9297
9317
  }
@@ -9961,6 +9981,8 @@ function detectAgentAuthMethod(provider) {
9961
9981
  return detectCodexAuthMethod();
9962
9982
  case AGENT.CURSOR:
9963
9983
  return ENGINE_ENV.CURSOR_API_KEY ? "api_key" : "none";
9984
+ case AGENT.GEMINI:
9985
+ return existsSync(GEMINI_AUTH_PATH) ? "oauth" : "none";
9964
9986
  case AGENT.MUSE:
9965
9987
  if (!existsSync(MUSE_AUTH_PATH)) return "none";
9966
9988
  if (ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS.muse?.method === "api_key") return "api_key";
@@ -10101,6 +10123,7 @@ var EnvironmentDetailsService = class {
10101
10123
  details.supportsMidTurnSteering = true;
10102
10124
  details.supportsClaudeMidTurnSteering = true;
10103
10125
  details.supportsCursorMidTurnSteering = true;
10126
+ details.supportsPiMidTurnSteering = true;
10104
10127
  details.supportsSendNow = true;
10105
10128
  details.supportsClaudeGoals = true;
10106
10129
  details.supportsGoalUpdates = true;
@@ -10120,6 +10143,7 @@ var EnvironmentDetailsService = class {
10120
10143
  details.claudeAuthMethod = detectAgentAuthMethod(AGENT.CLAUDE);
10121
10144
  details.codexAuthMethod = detectAgentAuthMethod(AGENT.CODEX);
10122
10145
  details.cursorAuthMethod = detectAgentAuthMethod(AGENT.CURSOR);
10146
+ details.geminiAuthMethod = existsSync2(GEMINI_CLI_PATH) ? detectAgentAuthMethod(AGENT.GEMINI) : void 0;
10123
10147
  details.museAuthMethod = detectAgentAuthMethod(AGENT.MUSE);
10124
10148
  details.opencodeAuthMethod = detectAgentAuthMethod(AGENT.OPENCODE);
10125
10149
  details.piAuthMethod = detectAgentAuthMethod(AGENT.PI);
@@ -11128,14 +11152,14 @@ function localControlComputers() {
11128
11152
  }
11129
11153
 
11130
11154
  // src/services/chat/chat-service.ts
11131
- import { appendFile as appendFile4, copyFile as copyFile2, mkdir as mkdir15, readFile as readFile17, rename as rename3, rm as rm7 } from "fs/promises";
11132
- import { join as join30 } from "path";
11155
+ import { appendFile as appendFile4, copyFile as copyFile2, mkdir as mkdir15, readFile as readFile18, rename as rename3, rm as rm7 } from "fs/promises";
11156
+ import { join as join31 } from "path";
11133
11157
  import { randomUUID as randomUUID9 } from "crypto";
11134
11158
  import { z as z4 } from "zod";
11135
11159
 
11136
11160
  // ../shared/src/persisted-query-hashes.ts
11137
11161
  var PERSISTED_QUERY_HASHES = {
11138
- workspaceChats: "15f7a29e"
11162
+ workspaceChats: "79cb548c"
11139
11163
  };
11140
11164
 
11141
11165
  // ../shared/src/workspace-chat.ts
@@ -11357,6 +11381,7 @@ function insertChronologically(existing, additions) {
11357
11381
  }
11358
11382
  function canSteerMessage(provider, request) {
11359
11383
  if (provider === "cursor") return !request.images?.length;
11384
+ if (provider === "pi") return !request.message.trimStart().startsWith("/");
11360
11385
  if (provider !== "claude" && provider !== "codex") return false;
11361
11386
  return !getGoalCommand(request.message, request.goalMode) && !(provider === "codex" && isCompactCommand(request.message));
11362
11387
  }
@@ -11391,7 +11416,10 @@ var MuseTokenManager = class extends BaseRefreshManager {
11391
11416
  };
11392
11417
  const response = await monolithRequest("/v1/engine/muse/refresh-credentials", { body: request, signal: AbortSignal.timeout(12e4) });
11393
11418
  if (!response.ok) {
11394
- throw new Error(`Credentials refresh failed: ${response.status} ${await response.text()}`);
11419
+ const error = new Error(`Credentials refresh failed: ${response.status} ${await response.text()}`);
11420
+ const revocation = refreshRevocation(error);
11421
+ if (revocation) await withdrawAgentLogin("muse", revocation);
11422
+ throw error;
11395
11423
  }
11396
11424
  const data = await response.json();
11397
11425
  await writeSecureCredentialFile(MUSE_AUTH_PATH, serializeMuseAuthFile(data), { ensureParentDir: true });
@@ -11403,22 +11431,58 @@ var MuseTokenManager = class extends BaseRefreshManager {
11403
11431
  };
11404
11432
  var museTokenManager = new MuseTokenManager();
11405
11433
 
11406
- // src/managers/opencode-token-manager.ts
11407
- var OPENCODE_AUTH_ENV_KEYS = [...ollamaAuthEnvKeys("opencode"), ...openAICompatibleAuthEnvKeys("opencode")];
11408
- var OpencodeTokenManager = class extends BaseRefreshManager {
11434
+ // src/managers/gemini-token-manager.ts
11435
+ var GeminiTokenManager = class extends BaseRefreshManager {
11409
11436
  constructor() {
11410
- super("OpencodeTokenManager");
11437
+ super("GeminiTokenManager");
11411
11438
  }
11412
11439
  doRefresh() {
11413
11440
  return Promise.resolve();
11414
11441
  }
11415
- async fetchFreshCredentials(failureReason, failureKind = "exhausted", failedCredential = ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS.opencode, allowedMethods, resetsAt) {
11416
- const failedMethod = AGENT_CREDENTIAL_METHODS_IN_ORDER.opencode.find(({ method }) => method === failedCredential?.method)?.method;
11442
+ async fetchFreshCredentials(failureReason, failureKind = "exhausted", failedCredential = ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS.gemini, allowedMethods) {
11443
+ return this.swapCredentials({
11444
+ provider: "gemini",
11445
+ failureKind,
11446
+ allowedMethods,
11447
+ refresh: async (exclusions) => {
11448
+ const request = {
11449
+ failedMethod: CREDENTIAL_METHOD.GEMINI_OAUTH,
11450
+ ...failedCredential ? { failedCredential } : {},
11451
+ failureReason,
11452
+ failureKind,
11453
+ ...exclusions
11454
+ };
11455
+ const response = await monolithRequest("/v1/engine/gemini/refresh-credentials", { body: request, signal: AbortSignal.timeout(12e4) });
11456
+ if (!response.ok) {
11457
+ throw new Error(`Credentials refresh failed: ${response.status} ${await response.text()}`);
11458
+ }
11459
+ const data = await response.json();
11460
+ await writeSecureCredentialFile(GEMINI_AUTH_PATH, serializeGeminiAuthFile(data), { ensureParentDir: true });
11461
+ setAgentCredentialSnapshot("gemini", data);
11462
+ },
11463
+ keepRefreshing: () => false
11464
+ });
11465
+ }
11466
+ };
11467
+ var geminiTokenManager = new GeminiTokenManager();
11468
+
11469
+ // src/managers/api-key-token-manager.ts
11470
+ var ApiKeyTokenManager = class extends BaseRefreshManager {
11471
+ constructor(agent) {
11472
+ super(`${getProviderDisplayName(agent)}TokenManager`);
11473
+ this.agent = agent;
11474
+ }
11475
+ agent;
11476
+ doRefresh() {
11477
+ return Promise.resolve();
11478
+ }
11479
+ async fetchFreshCredentials(failureReason, failureKind = "exhausted", failedCredential = ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS[this.agent], allowedMethods, resetsAt) {
11480
+ const failedMethod = AGENT_CREDENTIAL_METHODS_IN_ORDER[this.agent].find(({ method }) => method === failedCredential?.method)?.method;
11417
11481
  if (!failedMethod || allowedMethods && !allowedMethods.includes(failedMethod)) {
11418
- return createErrorResult({ message: "OpenCode only switches between keys of the same provider", code: "no_credentials" });
11482
+ return createErrorResult({ message: `${getProviderDisplayName(this.agent)} only switches between keys of the same provider`, code: "no_credentials" });
11419
11483
  }
11420
11484
  return this.swapCredentials({
11421
- provider: "opencode",
11485
+ provider: this.agent,
11422
11486
  failureKind,
11423
11487
  allowedMethods: [failedMethod],
11424
11488
  refresh: async (exclusions) => {
@@ -11430,31 +11494,38 @@ var OpencodeTokenManager = class extends BaseRefreshManager {
11430
11494
  ...resetsAt ? { resetsAt } : {},
11431
11495
  ...exclusions
11432
11496
  };
11433
- const response = await monolithRequest("/v1/engine/opencode/refresh-credentials", { body: request, signal: AbortSignal.timeout(12e4) });
11497
+ const response = await monolithRequest(`/v1/engine/${this.agent}/refresh-credentials`, { body: request, signal: AbortSignal.timeout(12e4) });
11434
11498
  if (!response.ok) {
11435
- throw new Error(`Credentials refresh failed: ${response.status} ${await response.text()}`);
11499
+ const error = new Error(`Credentials refresh failed: ${response.status} ${await response.text()}`);
11500
+ const revocation = refreshRevocation(error);
11501
+ if (revocation) await withdrawAgentLogin(this.agent, revocation);
11502
+ throw error;
11436
11503
  }
11437
11504
  const data = await response.json();
11438
11505
  for (const file of data.auth.files ?? []) {
11439
11506
  await writeSecureCredentialFile(file.path, file.contents, { ensureParentDir: true });
11440
11507
  }
11441
- for (const key of OPENCODE_AUTH_ENV_KEYS) delete process.env[key];
11508
+ for (const key of [...ollamaAuthEnvKeys(this.agent), ...openAICompatibleAuthEnvKeys(this.agent)]) delete process.env[key];
11442
11509
  Object.assign(process.env, data.auth.env);
11443
- setAgentCredentialSnapshot("opencode", data);
11510
+ setAgentCredentialSnapshot(this.agent, data);
11444
11511
  },
11445
11512
  keepRefreshing: () => false
11446
11513
  });
11447
11514
  }
11448
11515
  };
11449
- var opencodeTokenManager = new OpencodeTokenManager();
11516
+ var opencodeTokenManager = new ApiKeyTokenManager("opencode");
11517
+ var piTokenManager = new ApiKeyTokenManager("pi");
11450
11518
 
11451
11519
  // src/managers/auth-fallback.ts
11452
11520
  var SWAPPABLE_AGENTS = {
11453
11521
  claude: claudeTokenManager,
11454
11522
  codex: codexTokenManager,
11523
+ gemini: geminiTokenManager,
11455
11524
  muse: museTokenManager,
11456
- opencode: opencodeTokenManager
11525
+ opencode: opencodeTokenManager,
11526
+ pi: piTokenManager
11457
11527
  };
11528
+ var SWITCHED_CREDENTIAL_PROMPT = "Your previous turn stopped at a usage limit or a rejected credential. Continue from where you left off: first check what is already done, and do not repeat commands, edits, or messages you already completed.";
11458
11529
  var QUOTA_STOP_NEXT_STEP = {
11459
11530
  failed: "The next credential in the fallback chain could not be used. Check it in Settings \u2192 Fallbacks and try again.",
11460
11531
  not_configured: "Nothing further is configured in the fallback chain. Add a credential or harness in Settings \u2192 Fallbacks, or try again once the limit resets.",
@@ -12732,6 +12803,28 @@ function convertOpencodePart(part, linearSessionId) {
12732
12803
  }
12733
12804
  return null;
12734
12805
  }
12806
+ function convertPiEvent(event, linearSessionId) {
12807
+ if (event.type === "message_end" && event.message.role === "assistant") {
12808
+ const { content } = event.message;
12809
+ const text = content.flatMap((block) => block.type === "text" ? [block.text] : []).join("\n").trim();
12810
+ const body = text || content.flatMap((block) => block.type === "thinking" ? [block.thinking] : []).join("\n").trim();
12811
+ return body ? { linearSessionId, content: { type: "thought", body } } : null;
12812
+ }
12813
+ if (event.type === "tool_execution_start" || event.type === "tool_execution_end") {
12814
+ const output = event.type === "tool_execution_end" && isRecord2(event.result) ? extractToolResultText(event.result.content) : "";
12815
+ const result = event.type !== "tool_execution_end" ? void 0 : event.isError ? `Error: ${output || "Tool failed"}` : output || "Done";
12816
+ return {
12817
+ linearSessionId,
12818
+ content: {
12819
+ type: "action",
12820
+ action: toolAction(event.toolName),
12821
+ parameter: event.type === "tool_execution_start" ? summarizeInput(event.args) : "",
12822
+ ...result ? { result } : {}
12823
+ }
12824
+ };
12825
+ }
12826
+ return null;
12827
+ }
12735
12828
  function mapTodoStatus(status) {
12736
12829
  if (status === "in_progress") {
12737
12830
  return "inProgress";
@@ -17007,32 +17100,45 @@ function getPostToolPrHookPath() {
17007
17100
  if (!postToolHookPath) throw new Error("Replicas post-tool PR hook executable is missing.");
17008
17101
  return postToolHookPath;
17009
17102
  }
17010
- async function ensureCursorCommandProtectionHook() {
17011
- const path8 = join13(ENGINE_ENV.HOME_DIR, ".cursor", "hooks.json");
17103
+ async function updateHooksFile(path8, label, update) {
17012
17104
  let config = {};
17013
17105
  try {
17014
17106
  const content = await readFile8(path8, "utf8");
17015
17107
  const parsed = content.trim() ? JSON.parse(content) : {};
17016
- if (!isRecord(parsed)) throw new Error("Invalid Cursor hooks configuration.");
17108
+ if (!isRecord(parsed)) throw new Error(`Invalid ${label} hooks configuration.`);
17017
17109
  config = parsed;
17018
17110
  } catch (error) {
17019
17111
  if (!(error && typeof error === "object" && "code" in error && error.code === "ENOENT")) throw error;
17020
17112
  }
17021
- const hooks = isRecord(config.hooks) ? config.hooks : {};
17022
- const existing = Array.isArray(hooks.preToolUse) ? hooks.preToolUse : [];
17023
- hooks.preToolUse = [
17024
- ...existing.filter((entry) => !isRecord(entry) || typeof entry.command !== "string" || !entry.command.includes("command-protection-hook")),
17025
- { command: shellCommand(hookPath, "cursor") }
17026
- ];
17027
- const existingPost = Array.isArray(hooks.postToolUse) ? hooks.postToolUse : [];
17028
- hooks.postToolUse = [
17029
- ...existingPost.filter((entry) => !isRecord(entry) || typeof entry.command !== "string" || !entry.command.includes("post-tool-pr-hook")),
17030
- { command: shellCommand(postToolHookPath) }
17031
- ];
17032
17113
  await mkdir9(dirname4(path8), { recursive: true });
17033
- await atomicWriteFile(path8, `${JSON.stringify({ ...config, version: 1, hooks }, null, 2)}
17114
+ await atomicWriteFile(path8, `${JSON.stringify(update(config), null, 2)}
17034
17115
  `);
17035
17116
  }
17117
+ async function ensureCursorCommandProtectionHook() {
17118
+ await updateHooksFile(join13(ENGINE_ENV.HOME_DIR, ".cursor", "hooks.json"), "Cursor", (config) => {
17119
+ const hooks = isRecord(config.hooks) ? config.hooks : {};
17120
+ const existing = Array.isArray(hooks.preToolUse) ? hooks.preToolUse : [];
17121
+ hooks.preToolUse = [
17122
+ ...existing.filter((entry) => !isRecord(entry) || typeof entry.command !== "string" || !entry.command.includes("command-protection-hook")),
17123
+ { command: shellCommand(hookPath, "cursor") }
17124
+ ];
17125
+ const existingPost = Array.isArray(hooks.postToolUse) ? hooks.postToolUse : [];
17126
+ hooks.postToolUse = [
17127
+ ...existingPost.filter((entry) => !isRecord(entry) || typeof entry.command !== "string" || !entry.command.includes("post-tool-pr-hook")),
17128
+ { command: shellCommand(postToolHookPath) }
17129
+ ];
17130
+ return { ...config, version: 1, hooks };
17131
+ });
17132
+ }
17133
+ async function ensureGeminiCommandProtectionHook() {
17134
+ await updateHooksFile(join13(ENGINE_ENV.HOME_DIR, ".gemini", "config", "hooks.json"), "Antigravity", (config) => ({
17135
+ ...config,
17136
+ "replicas-command-protection": {
17137
+ PreToolUse: [{ matcher: "", hooks: [{ type: "command", command: shellCommand(hookPath, "gemini"), timeout: 60 }] }],
17138
+ PostToolUse: [{ matcher: "run_command", hooks: [{ type: "command", command: shellCommand(postToolHookPath) }] }]
17139
+ }
17140
+ }));
17141
+ }
17036
17142
 
17037
17143
  // src/managers/cursor-run-recovery.ts
17038
17144
  import { Agent as CursorAgent, AgentBusyError } from "@cursor/sdk";
@@ -17730,16 +17836,7 @@ ${typeof pending.subject.command === "string" ? pending.subject.command : JSON.s
17730
17836
  } else if (frame.method === "session/contextUsage") {
17731
17837
  const used = typeof frame.params.usedTokens === "number" ? frame.params.usedTokens : 0;
17732
17838
  const size = typeof frame.params.windowTokens === "number" ? frame.params.windowTokens : 0;
17733
- this.recordContextUsage({
17734
- provider: "muse",
17735
- source: "provider_usage",
17736
- model: DEFAULT_MUSE_MODEL,
17737
- totalTokens: used,
17738
- maxTokens: size,
17739
- percentage: size > 0 ? used / size * 100 : 0,
17740
- categories: [],
17741
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
17742
- });
17839
+ this.recordContextUsage(providerContextUsage({ provider: "muse", model: DEFAULT_MUSE_MODEL, totalTokens: used, maxTokens: size }));
17743
17840
  } else if (frame.method === "userInput/requested" && typeof frame.params.userInputId === "string") {
17744
17841
  const questions = Array.isArray(frame.params.questions) ? frame.params.questions.filter(isPendingQuestion) : [];
17745
17842
  this.pendingInput = {
@@ -17998,10 +18095,349 @@ ${pending}
17998
18095
  }
17999
18096
  };
18000
18097
 
18098
+ // src/services/installed-skill-service.ts
18099
+ import { readFile as readFile10, readdir as readdir6 } from "fs/promises";
18100
+ import { join as join15 } from "path";
18101
+ var installedSkillsByHome = /* @__PURE__ */ new Map();
18102
+ function isNotFoundError2(error) {
18103
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
18104
+ }
18105
+ async function loadInstalledSkills(homeDir) {
18106
+ const skillsDir = join15(homeDir, ".agents/skills");
18107
+ let entries;
18108
+ try {
18109
+ entries = await readdir6(skillsDir, { withFileTypes: true });
18110
+ } catch (error) {
18111
+ if (!isNotFoundError2(error)) console.warn("[InstalledSkills] Failed to list installed skills:", error);
18112
+ return [];
18113
+ }
18114
+ const skills = await Promise.all(entries.filter((entry) => entry.isDirectory() || entry.isSymbolicLink()).map(async (entry) => {
18115
+ try {
18116
+ const metadata = parseFrontmatter(await readFile10(join15(skillsDir, entry.name, "SKILL.md"), "utf8"));
18117
+ return metadata.name && metadata.description ? metadata : null;
18118
+ } catch (error) {
18119
+ if (!isNotFoundError2(error)) console.warn(`[InstalledSkills] Failed to read ${entry.name}:`, error);
18120
+ return null;
18121
+ }
18122
+ }));
18123
+ return skills.filter((skill) => skill !== null);
18124
+ }
18125
+ async function getInstalledSkillsAsSlashCommands(homeDir, provider) {
18126
+ let installedSkills = installedSkillsByHome.get(homeDir);
18127
+ if (!installedSkills) {
18128
+ installedSkills = loadInstalledSkills(homeDir);
18129
+ installedSkillsByHome.set(homeDir, installedSkills);
18130
+ }
18131
+ return (await installedSkills).flatMap(({ name, description }) => {
18132
+ const command = createProviderSlashCommand(provider, name, description);
18133
+ return command ? [command] : [];
18134
+ });
18135
+ }
18136
+
18137
+ // src/managers/gemini-manager.ts
18138
+ var GeminiQuotaError = class extends Error {
18139
+ };
18140
+ var GEMINI_LOGIN_REJECTED = /invalid_grant|not logged into Antigravity|Authentication required|UNAUTHENTICATED|Please log out \(\/logout\) and log back in/i;
18141
+ var GeminiManager = class extends CodingAgentManager {
18142
+ process = null;
18143
+ client = null;
18144
+ session = null;
18145
+ sessionId;
18146
+ systemPrompt = null;
18147
+ activePrompt = null;
18148
+ turnError = null;
18149
+ pendingQuestions = /* @__PURE__ */ new Map();
18150
+ slashCommands = [];
18151
+ constructor(options) {
18152
+ super({ ...options, provider: "gemini" });
18153
+ this.sessionId = options.initialSessionId;
18154
+ this.initializeManager(this.processMessageInternal.bind(this));
18155
+ }
18156
+ async initialize() {
18157
+ await ensureGeminiCommandProtectionHook();
18158
+ }
18159
+ /** Antigravity appends instructions to its system prompt only when a session starts, so changed ones restart it on the same conversation. */
18160
+ async start(instructions) {
18161
+ if (this.session && this.client && this.systemPrompt === instructions) return this.session;
18162
+ this.stopProcess();
18163
+ const { child, client } = spawnGeminiAcp(this.workingDirectory, this.originChatId ? { REPLICAS_CHAT_ID: this.originChatId } : void 0);
18164
+ this.process = child;
18165
+ this.client = client;
18166
+ client.on("notification", (frame) => this.handleNotification(frame));
18167
+ client.on("serverRequest", (frame) => this.handleServerRequest(frame));
18168
+ child.stderr.on("data", (chunk) => console.error("[gemini ACP]", chunk.toString().trimEnd()));
18169
+ child.on("error", (error) => this.handleProcessExit(child, error));
18170
+ child.on("exit", (code, signal) => this.handleProcessExit(child, new Error(`Antigravity exited with code ${code ?? signal}`)));
18171
+ await initializeGeminiAcp(client, 0);
18172
+ let session = null;
18173
+ if (this.sessionId) {
18174
+ session = await startGeminiSession(client, { cwd: this.workingDirectory, resumeSessionId: this.sessionId, systemPrompt: instructions }, 0).catch(() => null);
18175
+ }
18176
+ if (!session) {
18177
+ session = await startGeminiSession(client, { cwd: this.workingDirectory, systemPrompt: instructions }, 0);
18178
+ this.sessionId = session.sessionId;
18179
+ await this.onSaveSessionId(session.sessionId);
18180
+ }
18181
+ this.session = session;
18182
+ this.systemPrompt = instructions;
18183
+ return session;
18184
+ }
18185
+ request(method, params) {
18186
+ if (!this.client) return Promise.reject(new Error("Antigravity is not running."));
18187
+ return this.client.request(method, params, { timeoutMs: 0 });
18188
+ }
18189
+ handleProcessExit(child, error) {
18190
+ if (this.process !== child) return;
18191
+ const midTurn = (this.client?.pendingRequestCount ?? 0) > 0;
18192
+ this.process = null;
18193
+ this.session = null;
18194
+ this.client?.dispose(error);
18195
+ this.client = null;
18196
+ this.abortPendingQuestions();
18197
+ if (midTurn) this.turnError = error.message;
18198
+ }
18199
+ stopProcess() {
18200
+ const process10 = this.process;
18201
+ this.process = null;
18202
+ this.session = null;
18203
+ this.client?.dispose();
18204
+ this.client = null;
18205
+ this.abortPendingQuestions();
18206
+ process10?.kill("SIGTERM");
18207
+ }
18208
+ handleNotification(frame) {
18209
+ if (!isRecord2(frame) || frame.method !== "session/update" || !isRecord2(frame.params) || !isRecord2(frame.params.update)) return;
18210
+ if (frame.params.sessionId !== this.sessionId) return;
18211
+ const update = frame.params.update;
18212
+ const kind = update.sessionUpdate;
18213
+ if (kind === "available_commands_update" && Array.isArray(update.availableCommands)) {
18214
+ this.slashCommands = update.availableCommands.flatMap((command) => {
18215
+ if (!isRecord2(command) || typeof command.name !== "string") return [];
18216
+ const parsed = createProviderSlashCommand(
18217
+ "gemini",
18218
+ command.name,
18219
+ typeof command.description === "string" ? command.description : void 0,
18220
+ isRecord2(command.input) && typeof command.input.hint === "string" ? command.input.hint : void 0
18221
+ );
18222
+ return parsed ? [parsed] : [];
18223
+ });
18224
+ return;
18225
+ }
18226
+ if (kind === "config_option_update" && Array.isArray(update.configOptions)) {
18227
+ if (this.session) this.session.configOptions = update.configOptions;
18228
+ return;
18229
+ }
18230
+ if (kind === "usage_update" && typeof update.used === "number" && typeof update.size === "number") {
18231
+ this.recordContextUsage(providerContextUsage({
18232
+ provider: "gemini",
18233
+ model: this.session ? geminiSelectOption(this.session.configOptions, "model")?.currentValue ?? null : null,
18234
+ totalTokens: update.used,
18235
+ maxTokens: update.size
18236
+ }));
18237
+ return;
18238
+ }
18239
+ if (kind === "current_mode_update" || kind === "session_info_update") return;
18240
+ this.recordHistoryEvent(kind === "agent_message_chunk" || kind === "agent_thought_chunk" ? "gemini-chunk" : "gemini-session-update", { update });
18241
+ }
18242
+ handleServerRequest(frame) {
18243
+ const client = this.client;
18244
+ if (!client || !isRecord2(frame) || typeof frame.id !== "string" && typeof frame.id !== "number") return;
18245
+ if (frame.method !== "session/request_permission" || !isRecord2(frame.params) || !isRecord2(frame.params.toolCall) || !Array.isArray(frame.params.options)) {
18246
+ client.reject(frame.id, -32601, "Unsupported request");
18247
+ return;
18248
+ }
18249
+ const toolCall = frame.params.toolCall;
18250
+ const options = frame.params.options.flatMap((option2) => isRecord2(option2) && typeof option2.optionId === "string" ? [{ id: option2.optionId, label: typeof option2.name === "string" && option2.name ? option2.name : option2.optionId, kind: option2.kind }] : []);
18251
+ const toolCallId = typeof toolCall.toolCallId === "string" ? toolCall.toolCallId : String(frame.id);
18252
+ if (toolCallId.startsWith("interaction_")) {
18253
+ const requestId = `gemini-question:${toolCallId}`;
18254
+ this.pendingQuestions.set(requestId, { requestId: frame.id, toolCallId, optionIds: options.map((option2) => option2.id) });
18255
+ this.recordHistoryEvent("gemini-session-update", { update: { ...toolCall, sessionUpdate: "tool_call", status: "pending" } });
18256
+ this.recordHistoryEvent("replicas-tool-input-request", {
18257
+ requestId,
18258
+ toolUseId: toolCallId,
18259
+ toolName: "AskUserQuestion",
18260
+ questions: [{
18261
+ id: "question",
18262
+ prompt: typeof toolCall.title === "string" && toolCall.title ? toolCall.title : "Choose an option.",
18263
+ multiSelect: false,
18264
+ options: options.map(({ id, label }) => ({ id, label }))
18265
+ }],
18266
+ parent_tool_use_id: null
18267
+ });
18268
+ return;
18269
+ }
18270
+ const option = ["allow_always", "allow_once"].flatMap((kind) => options.filter((candidate) => candidate.kind === kind))[0];
18271
+ client.respond(frame.id, { outcome: option ? { outcome: "selected", optionId: option.id } : { outcome: "cancelled" } });
18272
+ }
18273
+ resolveQuestion(requestId, selectionId, selectionSummary) {
18274
+ const pending = this.pendingQuestions.get(requestId);
18275
+ if (!pending) return void 0;
18276
+ this.pendingQuestions.delete(requestId);
18277
+ this.recordHistoryEvent("replicas-tool-input-resolved", {
18278
+ requestId,
18279
+ toolUseId: pending.toolCallId,
18280
+ toolName: "AskUserQuestion",
18281
+ selectionId,
18282
+ ...selectionSummary ? { selectionSummary } : {},
18283
+ parent_tool_use_id: null
18284
+ });
18285
+ return pending;
18286
+ }
18287
+ abortPendingQuestions() {
18288
+ for (const requestId of [...this.pendingQuestions.keys()]) {
18289
+ const pending = this.resolveQuestion(requestId, "aborted");
18290
+ if (pending) this.client?.respond(pending.requestId, { outcome: { outcome: "cancelled" } });
18291
+ }
18292
+ }
18293
+ async respondToToolInput(requestId, selectionId) {
18294
+ const pending = this.pendingQuestions.get(requestId);
18295
+ if (!pending || !this.client) return false;
18296
+ if (selectionId === "declined") {
18297
+ this.resolveQuestion(requestId, "declined");
18298
+ this.client.respond(pending.requestId, { outcome: { outcome: "cancelled" } });
18299
+ return true;
18300
+ }
18301
+ const answer = toolInputAnswer(JSON.parse(selectionId), "question");
18302
+ const optionId = answer.options.find((id) => pending.optionIds.includes(id));
18303
+ if (!optionId) return false;
18304
+ this.resolveQuestion(requestId, selectionId);
18305
+ this.client.respond(pending.requestId, { outcome: { outcome: "selected", optionId } });
18306
+ return true;
18307
+ }
18308
+ isAwaitingInput() {
18309
+ return this.pendingQuestions.size > 0;
18310
+ }
18311
+ async createPrompt(request) {
18312
+ const prompt = [{ type: "text", text: request.message }];
18313
+ for (const image of await normalizeImages(request.images ?? [])) {
18314
+ if (image.label) prompt.push({ type: "text", text: image.label });
18315
+ prompt.push({ type: "image", mimeType: image.source.media_type, data: image.source.data });
18316
+ }
18317
+ return prompt;
18318
+ }
18319
+ async steerRequest(request) {
18320
+ if (!this.activePrompt || !this.sessionId) return false;
18321
+ const prompt = await this.createPrompt(request);
18322
+ const running = this.activePrompt;
18323
+ if (!running) return false;
18324
+ const steer = this.request("session/prompt", { sessionId: this.sessionId, prompt });
18325
+ steer.catch(() => {
18326
+ });
18327
+ this.activePrompt = steer;
18328
+ const accepted = await Promise.race([running.then(() => true, () => true), steer.then(() => true, () => false)]);
18329
+ if (!accepted) {
18330
+ if (this.activePrompt === steer) this.activePrompt = running;
18331
+ return false;
18332
+ }
18333
+ const read = this.markSteerRead(request.id);
18334
+ if (read) this.recordUserMessageHistoryEvent(read);
18335
+ return true;
18336
+ }
18337
+ async processMessageInternal(request, signal) {
18338
+ let userMessageRecorded = false;
18339
+ const dispatch = async (request2) => {
18340
+ const session = await this.start(this.buildCombinedInstructions(request2.customInstructions));
18341
+ const client = this.client;
18342
+ if (!client) throw new Error("Antigravity failed to start.");
18343
+ if (!userMessageRecorded) {
18344
+ this.recordUserMessageHistoryEvent(request2);
18345
+ userMessageRecorded = true;
18346
+ }
18347
+ await selectGeminiModel(client, session, request2.model ?? DEFAULT_GEMINI_MODEL, 0);
18348
+ const thinking = geminiSelectOption(session.configOptions, "thought_level");
18349
+ const thinkingValue = thinking ? thinkingVariant(new Set(thinking.values), request2.thinkingLevel) : void 0;
18350
+ if (thinking && thinkingValue && thinkingValue !== thinking.currentValue) {
18351
+ const result = await this.request("session/set_config_option", { sessionId: session.sessionId, configId: thinking.id, value: thinkingValue });
18352
+ if (isRecord2(result) && Array.isArray(result.configOptions)) session.configOptions = result.configOptions;
18353
+ }
18354
+ const prompt = await this.createPrompt(request2);
18355
+ if (signal.aborted) return;
18356
+ this.turnError = null;
18357
+ let response;
18358
+ try {
18359
+ this.activePrompt = this.request("session/prompt", { sessionId: session.sessionId, prompt });
18360
+ for (let pending = this.activePrompt; ; pending = this.activePrompt) {
18361
+ response = await pending;
18362
+ if (pending === this.activePrompt) break;
18363
+ }
18364
+ } catch (error) {
18365
+ this.turnError = (error instanceof Error ? error.message : String(error)).replace(/^ASP request failed for session\/prompt: (?:-?\d+ )?/, "");
18366
+ }
18367
+ if (this.turnError) {
18368
+ if (detectAgentQuotaLimit(this.turnError)) throw new GeminiQuotaError(this.turnError);
18369
+ throw new Error(this.turnError);
18370
+ }
18371
+ if (isRecord2(response) && isRecord2(response.usage)) this.onUsageUpdate(response.usage, (/* @__PURE__ */ new Date()).toISOString());
18372
+ this.recordHistoryEvent("gemini-turn-complete", { stopReason: isRecord2(response) ? response.stopReason : void 0 });
18373
+ };
18374
+ let current = request;
18375
+ let afterLimit = false;
18376
+ const failedLogins = [];
18377
+ try {
18378
+ for (; ; ) {
18379
+ try {
18380
+ await dispatch(current);
18381
+ return;
18382
+ } catch (error) {
18383
+ if (signal.aborted) return;
18384
+ const message = error instanceof Error ? error.message : String(error);
18385
+ const quotaKind = error instanceof GeminiQuotaError ? detectAgentQuotaLimit(message) ?? "rate_limit" : null;
18386
+ if (!quotaKind && !GEMINI_LOGIN_REJECTED.test(message)) {
18387
+ this.recordHistoryEvent("gemini-error", { message });
18388
+ throw error;
18389
+ }
18390
+ const attempted = ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS.gemini;
18391
+ const repeated = !!attempted && failedLogins.some((failed) => isSameCredential(failed, attempted));
18392
+ if (attempted) failedLogins.push(attempted);
18393
+ const fallback = repeated ? { outcome: "unavailable" } : await this.fallBackCredential(quotaKind ?? "auth_failed", message, attempted, void 0, afterLimit);
18394
+ if (fallback.outcome === "switched") {
18395
+ afterLimit ||= !!quotaKind;
18396
+ if (fallback.model) current = { ...current, model: fallback.model };
18397
+ this.stopProcess();
18398
+ continue;
18399
+ }
18400
+ this.recordHistoryEvent("gemini-error", { message });
18401
+ if (fallback.outcome === "fork") {
18402
+ this.emitQuotaExhausted({ provider: "gemini", reason: quotaKind ?? "auth_failed", detail: message, forkTo: fallback.target });
18403
+ return;
18404
+ }
18405
+ if (quotaKind) return;
18406
+ throw error;
18407
+ }
18408
+ }
18409
+ } finally {
18410
+ this.activePrompt = null;
18411
+ this.turnError = null;
18412
+ this.abortPendingQuestions();
18413
+ try {
18414
+ await this.historyFile.flush();
18415
+ } finally {
18416
+ await this.onTurnComplete();
18417
+ }
18418
+ }
18419
+ }
18420
+ async interruptActiveTurn() {
18421
+ this.abortPendingQuestions();
18422
+ if (!this.activePrompt) this.stopProcess();
18423
+ else if (this.client && this.sessionId) this.client.notify("session/cancel", { sessionId: this.sessionId });
18424
+ }
18425
+ async getHistory(page2 = {}) {
18426
+ await this.historyFile.flush();
18427
+ return { thread_id: this.sessionId, ...await this.historyFile.loadEventsPage(page2), goal: null };
18428
+ }
18429
+ async listSlashCommands() {
18430
+ return mergeSlashCommands(this.slashCommands, await getInstalledSkillsAsSlashCommands(ENGINE_ENV.HOME_DIR, "gemini"));
18431
+ }
18432
+ dispose() {
18433
+ this.stopProcess();
18434
+ }
18435
+ };
18436
+
18001
18437
  // src/managers/opencode-manager.ts
18002
18438
  import { existsSync as existsSync8 } from "fs";
18003
- import { copyFile, mkdir as mkdir10, readFile as readFile10, rm as rm4 } from "fs/promises";
18004
- import { delimiter, dirname as dirname5, join as join15 } from "path";
18439
+ import { copyFile, mkdir as mkdir10, readFile as readFile11, rm as rm4 } from "fs/promises";
18440
+ import { delimiter, dirname as dirname5, join as join16 } from "path";
18005
18441
  import { randomBytes as randomBytes2 } from "crypto";
18006
18442
  import { fileURLToPath as fileURLToPath2 } from "url";
18007
18443
  import { Agent } from "undici";
@@ -18029,16 +18465,15 @@ async function getAllowedOpenRouterModels() {
18029
18465
 
18030
18466
  // src/managers/opencode-manager.ts
18031
18467
  var OPENCODE_SHIM_DIR = dirname5(fileURLToPath2(new URL("../../scripts/opencode", import.meta.url)));
18032
- var OPENCODE_COMMAND_PROTECTION_PLUGIN_SOURCE = join15(OPENCODE_SHIM_DIR, "opencode-command-protection-plugin.ts");
18033
- var OPENCODE_COMMAND_PROTECTION_PLUGIN_PATH = join15(ENGINE_ENV.HOME_DIR, ".config", "opencode", "plugins", "replicas-command-protection.ts");
18034
- var OPENCODE_LEGACY_COMMAND_PROTECTION_PLUGIN_PATH = join15(ENGINE_ENV.HOME_DIR, ".config", "opencode", "plugins", "replicas-command-protection.mjs");
18035
- var OPENCODE_CONFIG_PATH = join15(ENGINE_ENV.HOME_DIR, ".config", "opencode", "opencode.json");
18468
+ var OPENCODE_COMMAND_PROTECTION_PLUGIN_SOURCE = join16(OPENCODE_SHIM_DIR, "opencode-command-protection-plugin.ts");
18469
+ var OPENCODE_COMMAND_PROTECTION_PLUGIN_PATH = join16(ENGINE_ENV.HOME_DIR, ".config", "opencode", "plugins", "replicas-command-protection.ts");
18470
+ var OPENCODE_LEGACY_COMMAND_PROTECTION_PLUGIN_PATH = join16(ENGINE_ENV.HOME_DIR, ".config", "opencode", "plugins", "replicas-command-protection.mjs");
18471
+ var OPENCODE_CONFIG_PATH = join16(ENGINE_ENV.HOME_DIR, ".config", "opencode", "opencode.json");
18036
18472
  var OPENCODE_SERVER_STARTUP_TIMEOUT_MS = 3e4;
18037
18473
  var OPENCODE_SLASH_COMMANDS_CACHE_MS = 3e4;
18038
18474
  var OPENCODE_HEARTBEAT_TIMEOUT_MS = 6e4;
18039
18475
  var OPENCODE_ABORT_TIMEOUT_MS = 5e3;
18040
18476
  var OPENCODE_SERVER_GONE = "exited or dropped its connection";
18041
- var OPENCODE_SWITCHED_CREDENTIAL_PROMPT = "Your previous turn stopped at a usage limit. Continue from where you left off: first check what is already done, and do not repeat commands, edits, or messages you already completed.";
18042
18477
  async function getDefaultOpencodeModel(provider) {
18043
18478
  const ollama = readOllamaAuthEnv("opencode", process.env);
18044
18479
  if (provider === "ollama" && ollama) {
@@ -18100,7 +18535,7 @@ function isOpencodeMcpEntry(value) {
18100
18535
  async function readProvisionedOpencodeMcpConfig() {
18101
18536
  let raw;
18102
18537
  try {
18103
- raw = await readFile10(OPENCODE_CONFIG_PATH, "utf8");
18538
+ raw = await readFile11(OPENCODE_CONFIG_PATH, "utf8");
18104
18539
  } catch (error) {
18105
18540
  if (isRecord(error) && error.code === "ENOENT") return void 0;
18106
18541
  console.error("[OpencodeManager] Failed to read Opencode config:", error);
@@ -18378,6 +18813,9 @@ var OpencodeManager = class extends CodingAgentManager {
18378
18813
  finishUpdate();
18379
18814
  }
18380
18815
  }
18816
+ dispose() {
18817
+ this.stopServer();
18818
+ }
18381
18819
  stopServer() {
18382
18820
  this.eventAbortController?.abort();
18383
18821
  this.server?.close();
@@ -18486,7 +18924,7 @@ var OpencodeManager = class extends CodingAgentManager {
18486
18924
  question: Boolean(request.enableInteractiveTools),
18487
18925
  ...this.subagentMcpParentChatId() ? { task: false } : {}
18488
18926
  },
18489
- parts: [{ type: "text", text: retry ? OPENCODE_SWITCHED_CREDENTIAL_PROMPT : request.message }]
18927
+ parts: [{ type: "text", text: retry ? SWITCHED_CREDENTIAL_PROMPT : request.message }]
18490
18928
  }, { signal: controller.signal, throwOnError: true });
18491
18929
  this.recordHistoryEvent("opencode-message.updated", { info: result.data.info });
18492
18930
  for (const part of result.data.parts) this.recordOpencodePart(part);
@@ -18733,7 +19171,7 @@ var OpencodeManager = class extends CodingAgentManager {
18733
19171
  };
18734
19172
 
18735
19173
  // src/managers/pi-manager.ts
18736
- import { join as join22 } from "path";
19174
+ import { join as join23 } from "path";
18737
19175
  import {
18738
19176
  createAgentSession,
18739
19177
  ModelRegistry,
@@ -41558,7 +41996,7 @@ async function probeMcpEndpoint(url3) {
41558
41996
 
41559
41997
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+f2da34192be1730e/node_modules/pi-mcp-adapter/npx-resolver.ts
41560
41998
  import { existsSync as existsSync9, readFileSync as readFileSync2, realpathSync, readdirSync as readdirSync2, statSync, writeFileSync as writeFileSync3, renameSync, mkdirSync as mkdirSync3, openSync as openSync2, readSync as readSync2, closeSync as closeSync2, unlinkSync } from "fs";
41561
- import { join as join16, dirname as dirname6, extname as extname2, resolve as resolve2, sep } from "path";
41999
+ import { join as join17, dirname as dirname6, extname as extname2, resolve as resolve2, sep } from "path";
41562
42000
 
41563
42001
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+f2da34192be1730e/node_modules/pi-mcp-adapter/abort.ts
41564
42002
  function throwIfAborted(signal) {
@@ -41715,7 +42153,7 @@ function resolveFromNpmCache(packageSpec, binName) {
41715
42153
  const { packageName, exactVersion } = parsedSpec;
41716
42154
  const packageDir = findCachedPackageDir(cacheDir, packageName, exactVersion);
41717
42155
  if (!packageDir) return null;
41718
- const packageJsonPath = join16(packageDir, "package.json");
42156
+ const packageJsonPath = join17(packageDir, "package.json");
41719
42157
  if (!existsSync9(packageJsonPath)) return null;
41720
42158
  let pkg = null;
41721
42159
  try {
@@ -41749,7 +42187,7 @@ function resolveFromNpmCache(packageSpec, binName) {
41749
42187
  }
41750
42188
  if (!binRel) return null;
41751
42189
  const nodeModulesDir = findNodeModulesDir(packageDir);
41752
- const binLink = chosenBinName ? join16(nodeModulesDir, ".bin", chosenBinName) : null;
42190
+ const binLink = chosenBinName ? join17(nodeModulesDir, ".bin", chosenBinName) : null;
41753
42191
  let resolvedBin = binLink && existsSync9(binLink) ? safeRealpath(binLink) : "";
41754
42192
  if (!resolvedBin) {
41755
42193
  resolvedBin = resolve2(packageDir, binRel);
@@ -41851,17 +42289,17 @@ function defaultBinName(packageName) {
41851
42289
  return packageName;
41852
42290
  }
41853
42291
  function findCachedPackageDir(cacheDir, packageName, exactVersion) {
41854
- const npxDir = join16(cacheDir, "_npx");
42292
+ const npxDir = join17(cacheDir, "_npx");
41855
42293
  if (!existsSync9(npxDir)) return null;
41856
42294
  const packagePathParts = packageName.startsWith("@") ? packageName.split("/") : [packageName];
41857
42295
  const candidates = readdirSync2(npxDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => {
41858
- const full = join16(npxDir, entry.name);
42296
+ const full = join17(npxDir, entry.name);
41859
42297
  const mtime = safeStatMtime(full);
41860
42298
  return { name: entry.name, mtime };
41861
42299
  }).sort((a, b) => b.mtime - a.mtime);
41862
42300
  for (const entry of candidates) {
41863
- const pkgDir = join16(npxDir, entry.name, "node_modules", ...packagePathParts);
41864
- const packageJsonPath = join16(pkgDir, "package.json");
42301
+ const pkgDir = join17(npxDir, entry.name, "node_modules", ...packagePathParts);
42302
+ const packageJsonPath = join17(pkgDir, "package.json");
41865
42303
  if (!existsSync9(packageJsonPath)) continue;
41866
42304
  if (exactVersion) {
41867
42305
  try {
@@ -41881,7 +42319,7 @@ function findNodeModulesDir(packageDir) {
41881
42319
  if (idx >= 0) {
41882
42320
  return parts.slice(0, idx + 1).join(sep);
41883
42321
  }
41884
- return join16(packageDir, "..");
42322
+ return join17(packageDir, "..");
41885
42323
  }
41886
42324
  function detectJsBinary(binPath) {
41887
42325
  const ext = extname2(binPath).toLowerCase();
@@ -42073,7 +42511,7 @@ import { spawnSync } from "child_process";
42073
42511
  import { createHash as createHash3 } from "crypto";
42074
42512
  import { createRequire } from "module";
42075
42513
  import { readFileSync as readFileSync3, existsSync as existsSync10, rmSync as rmSync2 } from "fs";
42076
- import { dirname as dirname7, join as join17 } from "path";
42514
+ import { dirname as dirname7, join as join18 } from "path";
42077
42515
  import { fileURLToPath as fileURLToPath3 } from "url";
42078
42516
  var require2 = createRequire(import.meta.url);
42079
42517
  var AUTH_SECRET_SERVICE = "pi-mcp-adapter.oauth";
@@ -42229,7 +42667,7 @@ function loadKeyringNativeBindingFallback(keyringRequire, platform4, arch3) {
42229
42667
  for (const target of targets) {
42230
42668
  try {
42231
42669
  const packageJsonPath = keyringRequire.resolve(`${target.packageName}/package.json`);
42232
- return keyringRequire(join17(dirname7(packageJsonPath), target.bindingFile));
42670
+ return keyringRequire(join18(dirname7(packageJsonPath), target.bindingFile));
42233
42671
  } catch (error) {
42234
42672
  lastError = error;
42235
42673
  }
@@ -42334,7 +42772,7 @@ function getServerDir(serverName, options) {
42334
42772
  throw new Error(`Invalid MCP server name: ${JSON.stringify(serverName)}`);
42335
42773
  }
42336
42774
  const storageKey = getAuthEntryAccount(serverName);
42337
- return join17(getAuthBaseDir(options), storageKey);
42775
+ return join18(getAuthBaseDir(options), storageKey);
42338
42776
  }
42339
42777
  function getAuthEntryAccount(serverName) {
42340
42778
  if (typeof serverName !== "string") {
@@ -42343,7 +42781,7 @@ function getAuthEntryAccount(serverName) {
42343
42781
  return `sha256-${createHash3("sha256").update(serverName, "utf8").digest("hex")}`;
42344
42782
  }
42345
42783
  function getAuthEntryFilePath(serverName, options) {
42346
- return join17(getServerDir(serverName, options), "tokens.json");
42784
+ return join18(getServerDir(serverName, options), "tokens.json");
42347
42785
  }
42348
42786
  function parseJsonPayload(serverName, payload, source) {
42349
42787
  try {
@@ -44946,7 +45384,7 @@ async function shutdownOAuth(runtime = legacyRuntime) {
44946
45384
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+f2da34192be1730e/node_modules/pi-mcp-adapter/mcp-bearer-store.ts
44947
45385
  import { createHash as createHash4 } from "crypto";
44948
45386
  import { createRequire as createRequire2 } from "module";
44949
- import { dirname as dirname8, join as join18 } from "path";
45387
+ import { dirname as dirname8, join as join19 } from "path";
44950
45388
  var require3 = createRequire2(import.meta.url);
44951
45389
  var BEARER_SECRET_SERVICE = "pi-mcp-adapter.bearer";
44952
45390
  var TEST_AUTH_STORE_ENV2 = "PI_MCP_ADAPTER_TEST_AUTH_STORE";
@@ -45048,7 +45486,7 @@ function loadKeyringNativeBindingFallback2(keyringRequire, platform4, arch3) {
45048
45486
  for (const target of targets) {
45049
45487
  try {
45050
45488
  const packageJsonPath = keyringRequire.resolve(`${target.packageName}/package.json`);
45051
- return keyringRequire(join18(dirname8(packageJsonPath), target.bindingFile));
45489
+ return keyringRequire(join19(dirname8(packageJsonPath), target.bindingFile));
45052
45490
  } catch (error) {
45053
45491
  lastError = error;
45054
45492
  }
@@ -49515,7 +49953,7 @@ async function openMcpAuthPanel(state, pi, ctx, configOverridePath) {
49515
49953
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+f2da34192be1730e/node_modules/pi-mcp-adapter/tool-registrar.ts
49516
49954
  import { mkdtempSync, rmSync as rmSync3, writeFileSync as writeFileSync5 } from "fs";
49517
49955
  import { tmpdir } from "os";
49518
- import { join as join19 } from "path";
49956
+ import { join as join20 } from "path";
49519
49957
  var MAX_BINARY_RESOURCE_BYTES = 10 * 1024 * 1024;
49520
49958
  var MAX_SESSION_RESOURCE_BYTES = 100 * 1024 * 1024;
49521
49959
  var MAX_SESSION_RESOURCE_FILES = 1e4;
@@ -49622,11 +50060,11 @@ function materializeBinaryResource(resource, scope) {
49622
50060
  return omitBinaryResource(resource, "session resource limit reached");
49623
50061
  }
49624
50062
  try {
49625
- session.directory ??= mkdtempSync(join19(tmpdir(), "pi-mcp-resource-"));
50063
+ session.directory ??= mkdtempSync(join20(tmpdir(), "pi-mcp-resource-"));
49626
50064
  } catch {
49627
50065
  return omitBinaryResource(resource, "could not be saved");
49628
50066
  }
49629
- const filePath = join19(session.directory, `resource-${++session.sequence}.bin`);
50067
+ const filePath = join20(session.directory, `resource-${++session.sequence}.bin`);
49630
50068
  session.bytes += decodedBytes;
49631
50069
  session.files += 1;
49632
50070
  try {
@@ -49719,7 +50157,7 @@ function stringifyStructuredContent(value) {
49719
50157
  import { randomBytes as randomBytes3 } from "crypto";
49720
50158
  import { mkdtemp, rm as rm5, writeFile as writeFile7 } from "fs/promises";
49721
50159
  import { tmpdir as tmpdir2 } from "os";
49722
- import { dirname as dirname11, join as join20 } from "path";
50160
+ import { dirname as dirname11, join as join21 } from "path";
49723
50161
  var DEFAULT_MCP_OUTPUT_MAX_BYTES = 50 * 1024;
49724
50162
  var DEFAULT_MCP_OUTPUT_MAX_LINES = 2e3;
49725
50163
  var DEFAULT_MCP_DETAILS_MAX_BYTES = 16 * 1024;
@@ -50027,8 +50465,8 @@ function serializedObjectEntryBytes(key, value, hasPrevious) {
50027
50465
  }
50028
50466
  async function saveArtifact(kind, text) {
50029
50467
  try {
50030
- const dir = await mkdtemp(join20(tmpdir2(), "pi-mcp-output-"));
50031
- const path8 = join20(dir, `${kind}-${randomBytes3(4).toString("hex")}.txt`);
50468
+ const dir = await mkdtemp(join21(tmpdir2(), "pi-mcp-output-"));
50469
+ const path8 = join21(dir, `${kind}-${randomBytes3(4).toString("hex")}.txt`);
50032
50470
  await writeFile7(path8, text, { encoding: "utf8", mode: 384 });
50033
50471
  return { path: path8 };
50034
50472
  } catch (error) {
@@ -51675,7 +52113,7 @@ function sendText(res, status, text) {
51675
52113
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+f2da34192be1730e/node_modules/pi-mcp-adapter/glimpse-ui.ts
51676
52114
  import { existsSync as existsSync13 } from "fs";
51677
52115
  import { execFileSync as execFileSync2 } from "child_process";
51678
- import { join as join21, dirname as dirname12 } from "path";
52116
+ import { join as join22, dirname as dirname12 } from "path";
51679
52117
  import { platform as platform2 } from "os";
51680
52118
  import { createRequire as createRequire3 } from "module";
51681
52119
  var glimpseAvailable = null;
@@ -51697,20 +52135,20 @@ function getGlimpseBinaryPath() {
51697
52135
  try {
51698
52136
  const require6 = createRequire3(import.meta.url);
51699
52137
  const glimpseuiPath = require6.resolve("glimpseui");
51700
- const binaryPath = join21(dirname12(glimpseuiPath), "glimpse");
52138
+ const binaryPath = join22(dirname12(glimpseuiPath), "glimpse");
51701
52139
  if (existsSync13(binaryPath)) return binaryPath;
51702
52140
  } catch {
51703
52141
  }
51704
52142
  try {
51705
52143
  const globalRoot = execFileSync2("npm", ["root", "-g"], { encoding: "utf-8" }).trim();
51706
- const binaryPath = join21(globalRoot, "glimpseui", "src", "glimpse");
52144
+ const binaryPath = join22(globalRoot, "glimpseui", "src", "glimpse");
51707
52145
  if (existsSync13(binaryPath)) return binaryPath;
51708
52146
  } catch {
51709
52147
  }
51710
52148
  return null;
51711
52149
  }
51712
52150
  async function openGlimpseWindow(html, options) {
51713
- const modulePath = resolvedBinaryPath ? join21(dirname12(resolvedBinaryPath), "glimpse.mjs") : "glimpseui";
52151
+ const modulePath = resolvedBinaryPath ? join22(dirname12(resolvedBinaryPath), "glimpse.mjs") : "glimpseui";
51714
52152
  const glimpse = await import(modulePath);
51715
52153
  let active = true;
51716
52154
  const win = glimpse.open(html, {
@@ -59607,16 +60045,30 @@ var PiManager = class extends CodingAgentManager {
59607
60045
  activeSessionFile = null;
59608
60046
  sessionSubagentMcpParentChatId;
59609
60047
  sessionInstructions;
60048
+ sessionCredential;
59610
60049
  providerId = "openrouter";
59611
60050
  providerApiKey = null;
59612
60051
  modelRuntime = null;
60052
+ linearForwarder = null;
60053
+ // Held until the turn ends: a call Pi retried or Replicas moved to another credential is not the turn's failure.
60054
+ failedCall = null;
60055
+ steers = [];
59613
60056
  constructor(options) {
59614
60057
  super(options);
59615
60058
  this.initializeManager(this.processMessageInternal.bind(this));
59616
60059
  }
59617
60060
  async interruptActiveTurn() {
60061
+ this.session?.clearQueue();
59618
60062
  await this.session?.abort();
59619
60063
  }
60064
+ async steerRequest(request) {
60065
+ if (!this.session?.isStreaming || !canSteerMessage("pi", request)) return false;
60066
+ const images = await this.toPiImages(request);
60067
+ if (!this.session?.isStreaming || this.isSteerWithdrawn(request)) return false;
60068
+ this.steers.push(request);
60069
+ await this.session.steer(request.message, images);
60070
+ return true;
60071
+ }
59620
60072
  async getHistory(page2 = {}) {
59621
60073
  await this.historyFile.flush();
59622
60074
  const history = await this.historyFile.loadEventsPage(page2);
@@ -59638,6 +60090,8 @@ var PiManager = class extends CodingAgentManager {
59638
60090
  this.unsubscribe = null;
59639
60091
  const session = this.session;
59640
60092
  this.session = null;
60093
+ this.modelRuntime = null;
60094
+ this.providerApiKey = null;
59641
60095
  if (session) {
59642
60096
  await session.extensionRunner.emit({ type: "session_shutdown", reason: "quit" }).catch(() => {
59643
60097
  });
@@ -59648,7 +60102,7 @@ var PiManager = class extends CodingAgentManager {
59648
60102
  const subagentMcpParentChatId = this.subagentMcpParentChatId();
59649
60103
  const instructions = this.buildCombinedInstructions(request.customInstructions) ?? "";
59650
60104
  let retainedModel;
59651
- if (this.session && (this.sessionSubagentMcpParentChatId !== subagentMcpParentChatId || this.sessionInstructions !== instructions)) {
60105
+ if (this.session && (this.sessionSubagentMcpParentChatId !== subagentMcpParentChatId || this.sessionInstructions !== instructions || this.sessionCredential !== ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS.pi)) {
59652
60106
  retainedModel = this.session.model?.id;
59653
60107
  await this.dispose();
59654
60108
  }
@@ -59673,6 +60127,7 @@ var PiManager = class extends CodingAgentManager {
59673
60127
  return this.session;
59674
60128
  }
59675
60129
  const modelRuntime = await this.getModelRuntime();
60130
+ const credential = ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS.pi;
59676
60131
  const credentialResult = await getPiProviderCredentials();
59677
60132
  if (!credentialResult.ok) throw new Error("OpenCode Go, Aster, OpenRouter, or OpenAI-compatible credentials are not configured for Pi.");
59678
60133
  const credentials = credentialResult.data;
@@ -59780,7 +60235,7 @@ var PiManager = class extends CodingAgentManager {
59780
60235
  }
59781
60236
  const resourceLoader = new DefaultResourceLoader({
59782
60237
  cwd: this.workingDirectory,
59783
- agentDir: join22(ENGINE_ENV.HOME_DIR, ".pi", "agent"),
60238
+ agentDir: join23(ENGINE_ENV.HOME_DIR, ".pi", "agent"),
59784
60239
  extensionFactories,
59785
60240
  appendSystemPrompt: [instructions]
59786
60241
  });
@@ -59795,12 +60250,14 @@ var PiManager = class extends CodingAgentManager {
59795
60250
  this.session = result.session;
59796
60251
  this.sessionSubagentMcpParentChatId = subagentMcpParentChatId;
59797
60252
  this.sessionInstructions = instructions;
60253
+ this.sessionCredential = credential;
59798
60254
  if (request.thinkingLevel) {
59799
60255
  this.session.setThinkingLevel(piThinkingLevel(request.thinkingLevel));
59800
60256
  }
59801
60257
  this.activeSessionFile = sessionManager.getSessionFile() ?? null;
59802
60258
  await this.onSaveSessionId(this.activeSessionFile);
59803
60259
  this.unsubscribe = this.session.subscribe((event) => this.handleEvent(event));
60260
+ await this.session.bindExtensions({});
59804
60261
  return this.session;
59805
60262
  }
59806
60263
  async getModelRuntime() {
@@ -59808,29 +60265,97 @@ var PiManager = class extends CodingAgentManager {
59808
60265
  return this.modelRuntime;
59809
60266
  }
59810
60267
  handleEvent(event) {
60268
+ if (event.type === "agent_start") void this.deliverEarlySteers();
60269
+ if (event.type === "message_start" && event.message.role === "user" && Array.isArray(event.message.content)) {
60270
+ const [first] = event.message.content;
60271
+ const index = first?.type === "text" ? this.steers.findIndex(({ message }) => message === first.text) : -1;
60272
+ if (index !== -1) {
60273
+ const steer = this.markSteerRead(this.steers.splice(index, 1)[0].id);
60274
+ if (steer) this.recordUserMessageHistoryEvent(steer);
60275
+ }
60276
+ }
59811
60277
  if (event.type === "message_end") this.onUsageUpdate(event, (/* @__PURE__ */ new Date()).toISOString());
59812
- const payload = eventPayload(event);
59813
- this.recordHistoryEvent(`pi-${event.type}`, payload);
60278
+ const usage = event.type === "message_end" && event.message.role === "assistant" ? this.session?.getContextUsage() : void 0;
60279
+ if (usage?.tokens != null) {
60280
+ this.recordContextUsage(providerContextUsage({
60281
+ provider: "pi",
60282
+ model: this.session?.model?.id ?? null,
60283
+ totalTokens: usage.tokens,
60284
+ maxTokens: usage.contextWindow,
60285
+ compactsAutomatically: this.session?.autoCompactionEnabled
60286
+ }));
60287
+ }
60288
+ if (event.type === "message_end" && event.message.role === "assistant") {
60289
+ this.failedCall = event.message.stopReason === "error" ? event : null;
60290
+ if (this.failedCall) return;
60291
+ }
60292
+ this.recordHistoryEvent(`pi-${event.type}`, eventPayload(event));
60293
+ const linearSessionId = this.linearSessionId;
60294
+ if (linearSessionId) this.linearForwarder?.sendEvent(convertPiEvent(event, linearSessionId));
59814
60295
  }
59815
60296
  recordUserMessage(session, request) {
59816
60297
  const skillName = explicitSkillName(session, request.message);
59817
60298
  this.recordUserMessageHistoryEvent(request, skillName ? { skillName } : {}, this.turnBeganAt);
59818
60299
  }
60300
+ async toPiImages(request) {
60301
+ if (!request.images?.length) return void 0;
60302
+ return (await normalizeImages(request.images)).map((image) => ({
60303
+ type: "image",
60304
+ data: image.source.data,
60305
+ mimeType: image.source.media_type
60306
+ }));
60307
+ }
59819
60308
  async processMessageInternal(request, signal) {
60309
+ this.linearForwarder = new LinearEventForwarder(() => this.linearSessionId);
59820
60310
  try {
59821
- const session = await this.ensureSession(request);
59822
- const images = request.images && request.images.length > 0 ? (await normalizeImages(request.images)).map((image) => ({
59823
- type: "image",
59824
- data: image.source.data,
59825
- mimeType: image.source.media_type
59826
- })) : void 0;
60311
+ let session = await this.ensureSession(request);
60312
+ const images = await this.toPiImages(request);
59827
60313
  if (!this.deliver(signal)) return;
59828
60314
  this.recordUserMessage(session, request);
59829
- await session.prompt(request.message, images ? { images } : void 0);
60315
+ let retry = false;
60316
+ let limit;
60317
+ while (true) {
60318
+ const attempted = this.sessionCredential;
60319
+ const thrown = await session.prompt(retry ? SWITCHED_CREDENTIAL_PROMPT : request.message, images && !retry ? { images } : void 0).then(() => null, (error) => error);
60320
+ const failedCall = this.failedCall;
60321
+ this.failedCall = null;
60322
+ const detail = thrown ? thrown instanceof Error ? thrown.message : String(thrown) : failedCall?.message.role === "assistant" ? failedCall.message.errorMessage ?? "Pi run failed" : null;
60323
+ if (detail === null) break;
60324
+ const quota = detectAgentQuotaLimit(detail);
60325
+ const authFailed = !quota && isAuthenticationErrorText(detail, [/\b401\b/]);
60326
+ const fallback = !signal.aborted && (quota || authFailed) ? await this.fallBackCredential(quota ?? "auth_failed", detail, attempted, void 0, !!limit) : null;
60327
+ limit ??= quota ?? void 0;
60328
+ if (fallback?.outcome === "switched") {
60329
+ if (signal.aborted) break;
60330
+ const model = fallback.model ?? session.model?.id;
60331
+ await this.dispose();
60332
+ session = await this.ensureSession({ ...request, ...model ? { model } : {} });
60333
+ if (signal.aborted) break;
60334
+ retry = true;
60335
+ continue;
60336
+ }
60337
+ const notice = fallback && limit ? describeQuotaExhaustion("pi", limit, attempted, fallback) : authFailed ? describeLoginFailure("pi", attempted, void 0, false) : null;
60338
+ if (notice) this.recordHistoryEvent("pi-error", { message: notice });
60339
+ else if (failedCall) this.recordHistoryEvent("pi-message_end", eventPayload(failedCall));
60340
+ if (fallback && limit) {
60341
+ this.emitQuotaExhausted({
60342
+ provider: "pi",
60343
+ reason: limit,
60344
+ detail,
60345
+ ...fallback.outcome === "fork" ? { forkTo: fallback.target } : {}
60346
+ });
60347
+ }
60348
+ if (thrown && !notice) throw thrown;
60349
+ break;
60350
+ }
60351
+ this.linearForwarder.flushThoughtAsResponse();
59830
60352
  } catch (error) {
59831
60353
  this.recordHistoryEvent("pi-error", { message: error instanceof Error ? error.message : String(error) });
59832
60354
  throw error;
59833
60355
  } finally {
60356
+ this.linearForwarder = null;
60357
+ this.session?.clearQueue();
60358
+ this.steers = [];
59834
60359
  await this.historyFile.flush();
59835
60360
  await this.onTurnComplete();
59836
60361
  }
@@ -59838,10 +60363,10 @@ var PiManager = class extends CodingAgentManager {
59838
60363
  };
59839
60364
 
59840
60365
  // src/services/chat/chat-commands.ts
59841
- import { mkdir as mkdir12, readFile as readFile11, rm as rm6 } from "fs/promises";
59842
- import { join as join23 } from "path";
60366
+ import { mkdir as mkdir12, readFile as readFile12, rm as rm6 } from "fs/promises";
60367
+ import { join as join24 } from "path";
59843
60368
  import { z as z3 } from "zod";
59844
- var CHAT_COMMANDS_DIR = join23(ENGINE_DIR, "chat-commands");
60369
+ var CHAT_COMMANDS_DIR = join24(ENGINE_DIR, "chat-commands");
59845
60370
  var ACCEPTED_RETENTION_MS = 8 * 24 * 60 * 6e4;
59846
60371
  var MAX_REMOVED_MESSAGE_IDS = 6e3;
59847
60372
  var queuedMessageSchema = sendChatMessageRequestSchema.extend({ id: z3.string(), queuedAt: z3.string() });
@@ -59870,7 +60395,7 @@ var ChatCommands = class _ChatCommands {
59870
60395
  state;
59871
60396
  writing = Promise.resolve();
59872
60397
  static async load(chatId) {
59873
- const content = await readFile11(join23(CHAT_COMMANDS_DIR, `${chatId}.json`), "utf-8").catch((error) => {
60398
+ const content = await readFile12(join24(CHAT_COMMANDS_DIR, `${chatId}.json`), "utf-8").catch((error) => {
59874
60399
  if (error.code === "ENOENT") return null;
59875
60400
  throw error;
59876
60401
  });
@@ -59900,13 +60425,13 @@ var ChatCommands = class _ChatCommands {
59900
60425
  this.writing = this.writing.catch(() => {
59901
60426
  }).then(async () => {
59902
60427
  await mkdir12(CHAT_COMMANDS_DIR, { recursive: true, mode: 448 });
59903
- await atomicWriteFile(join23(CHAT_COMMANDS_DIR, `${this.chatId}.json`), data, { mode: 384, flush: true });
60428
+ await atomicWriteFile(join24(CHAT_COMMANDS_DIR, `${this.chatId}.json`), data, { mode: 384, flush: true });
59904
60429
  });
59905
60430
  return this.writing;
59906
60431
  }
59907
60432
  remove() {
59908
60433
  this.writing = this.writing.catch(() => {
59909
- }).then(() => rm6(join23(CHAT_COMMANDS_DIR, `${this.chatId}.json`), { force: true }));
60434
+ }).then(() => rm6(join24(CHAT_COMMANDS_DIR, `${this.chatId}.json`), { force: true }));
59910
60435
  return this.writing;
59911
60436
  }
59912
60437
  };
@@ -59926,13 +60451,13 @@ async function uploadAnalytics(endpoint, body) {
59926
60451
  import {
59927
60452
  appendFile as appendFile3,
59928
60453
  mkdir as mkdir13,
59929
- readFile as readFile12,
59930
- readdir as readdir6,
60454
+ readFile as readFile13,
60455
+ readdir as readdir7,
59931
60456
  rename as rename2,
59932
60457
  unlink
59933
60458
  } from "fs/promises";
59934
60459
  import { existsSync as existsSync14, readFileSync as readFileSync5, readdirSync as readdirSync3 } from "fs";
59935
- import { join as join24 } from "path";
60460
+ import { join as join25 } from "path";
59936
60461
  var MAX_FAILED_RECORDS = 500;
59937
60462
  var FLUSH_DEBOUNCE_MS = 15e3;
59938
60463
  var MAX_UPLOADED_SEGMENTS = 50;
@@ -59944,7 +60469,7 @@ var AnalyticsRecordBuffer = class {
59944
60469
  options.storageName,
59945
60470
  ...options.legacyStorageNames ?? []
59946
60471
  ];
59947
- this.liveFile = join24(ENGINE_DIR, `${options.storageName}.jsonl`);
60472
+ this.liveFile = join25(ENGINE_DIR, `${options.storageName}.jsonl`);
59948
60473
  this.segmentFilePatterns = this.storageNames.map(
59949
60474
  (storageName) => new RegExp(`^${storageName}\\.(\\d+)\\.jsonl$`)
59950
60475
  );
@@ -59982,7 +60507,7 @@ var AnalyticsRecordBuffer = class {
59982
60507
  if (!existsSync14(ENGINE_DIR)) return [];
59983
60508
  return readdirSync3(ENGINE_DIR, { withFileTypes: true }).filter((entry) => entry.isFile() && this.storageNames.some(
59984
60509
  (storageName) => entry.name === `${storageName}.jsonl` || entry.name.startsWith(`${storageName}.`) && (entry.name.endsWith(".jsonl") || entry.name.endsWith(`.jsonl${UPLOADED_SUFFIX}`))
59985
- )).map(({ name }) => name).sort().flatMap((name) => this.parseRecords(readFileSync5(join24(ENGINE_DIR, name), "utf-8"))).map((record3) => {
60510
+ )).map(({ name }) => name).sort().flatMap((name) => this.parseRecords(readFileSync5(join25(ENGINE_DIR, name), "utf-8"))).map((record3) => {
59986
60511
  const recordId = this.options.getRecordId?.(record3);
59987
60512
  if (recordId) this.recordIds.add(recordId);
59988
60513
  return record3;
@@ -60017,18 +60542,18 @@ var AnalyticsRecordBuffer = class {
60017
60542
  }
60018
60543
  for (const storageName of this.storageNames) {
60019
60544
  await rename2(
60020
- join24(ENGINE_DIR, `${storageName}.jsonl`),
60021
- join24(ENGINE_DIR, `${storageName}.${Date.now()}.jsonl`)
60545
+ join25(ENGINE_DIR, `${storageName}.jsonl`),
60546
+ join25(ENGINE_DIR, `${storageName}.${Date.now()}.jsonl`)
60022
60547
  ).catch(() => {
60023
60548
  });
60024
60549
  }
60025
- const entries = await readdir6(ENGINE_DIR).catch(() => []);
60550
+ const entries = await readdir7(ENGINE_DIR).catch(() => []);
60026
60551
  let flushed = 0;
60027
60552
  let failed = 0;
60028
60553
  for (const entry of entries) {
60029
60554
  if (!this.segmentFilePatterns.some((pattern) => pattern.test(entry))) continue;
60030
60555
  try {
60031
- await this.uploadSegment(join24(ENGINE_DIR, entry));
60556
+ await this.uploadSegment(join25(ENGINE_DIR, entry));
60032
60557
  flushed++;
60033
60558
  } catch (error) {
60034
60559
  failed++;
@@ -60057,14 +60582,14 @@ var AnalyticsRecordBuffer = class {
60057
60582
  (storageName) => entry.startsWith(`${storageName}.`)
60058
60583
  ) && entry.endsWith(UPLOADED_SUFFIX)).sort();
60059
60584
  for (const entry of uploaded.slice(0, -MAX_UPLOADED_SEGMENTS)) {
60060
- await unlink(join24(ENGINE_DIR, entry)).catch(() => {
60585
+ await unlink(join25(ENGINE_DIR, entry)).catch(() => {
60061
60586
  });
60062
60587
  }
60063
60588
  }
60064
60589
  return { flushed, failed };
60065
60590
  }
60066
60591
  async uploadSegment(filePath) {
60067
- const records = this.parseRecords(await readFile12(filePath, "utf-8"));
60592
+ const records = this.parseRecords(await readFile13(filePath, "utf-8"));
60068
60593
  if (records.length > 0) await this.options.upload(records);
60069
60594
  await rename2(filePath, `${filePath}${UPLOADED_SUFFIX}`).catch(() => {
60070
60595
  });
@@ -60082,7 +60607,7 @@ var AnalyticsRecordBuffer = class {
60082
60607
  };
60083
60608
 
60084
60609
  // src/analytics/agent/activity/skill-mcp-call-extractor.ts
60085
- var NON_MCP_SERVERS = /* @__PURE__ */ new Set(["claude", "cursor", "muse", "opencode", "pi", "custom", "dynamic"]);
60610
+ var NON_MCP_SERVERS = /* @__PURE__ */ new Set(["claude", "cursor", "gemini", "muse", "opencode", "pi", "custom", "dynamic"]);
60086
60611
  function mcpNameFromToolCall(message) {
60087
60612
  const parsedName = parseMcpToolName(message.tool);
60088
60613
  if (parsedName) return parsedName.server;
@@ -60643,6 +61168,21 @@ var CursorTokenUsageService = class {
60643
61168
  }
60644
61169
  };
60645
61170
 
61171
+ // src/analytics/token-usage/gemini/index.ts
61172
+ var GeminiTokenUsageService = class {
61173
+ record(event) {
61174
+ return recordParsedTokenUsage(event, AGENT.GEMINI, (usage) => {
61175
+ if (!isRecord2(usage) || typeof usage.inputTokens !== "number" || typeof usage.outputTokens !== "number") return void 0;
61176
+ return {
61177
+ inputTokens: usage.inputTokens,
61178
+ outputTokens: usage.outputTokens + (typeof usage.thoughtTokens === "number" ? usage.thoughtTokens : 0),
61179
+ cacheReadInputTokens: typeof usage.cachedReadTokens === "number" ? usage.cachedReadTokens : 0,
61180
+ cacheWriteInputTokens: typeof usage.cachedWriteTokens === "number" ? usage.cachedWriteTokens : 0
61181
+ };
61182
+ });
61183
+ }
61184
+ };
61185
+
60646
61186
  // src/analytics/token-usage/muse/index.ts
60647
61187
  var MuseTokenUsageService = class {
60648
61188
  record(event) {
@@ -60720,6 +61260,8 @@ function createAgentTokenUsageService(harness) {
60720
61260
  return new CodexTokenUsageService();
60721
61261
  case AGENT.CURSOR:
60722
61262
  return new CursorTokenUsageService();
61263
+ case AGENT.GEMINI:
61264
+ return new GeminiTokenUsageService();
60723
61265
  case AGENT.MUSE:
60724
61266
  return new MuseTokenUsageService();
60725
61267
  case AGENT.OPENCODE:
@@ -60885,9 +61427,9 @@ var KeepAliveService = class _KeepAliveService {
60885
61427
  var keepAliveService = new KeepAliveService();
60886
61428
 
60887
61429
  // src/services/canvas-service.ts
60888
- import { readdir as readdir7, readFile as readFile14, stat as stat3 } from "fs/promises";
61430
+ import { readdir as readdir8, readFile as readFile15, stat as stat3 } from "fs/promises";
60889
61431
  import { homedir as homedir7 } from "os";
60890
- import { join as join25 } from "path";
61432
+ import { join as join26 } from "path";
60891
61433
 
60892
61434
  // src/utils/contained-file.ts
60893
61435
  import { realpath, stat as stat2 } from "fs/promises";
@@ -60913,9 +61455,9 @@ function fileRevision(content) {
60913
61455
  }
60914
61456
 
60915
61457
  // src/utils/revisioned-text-file.ts
60916
- import { readFile as readFile13 } from "fs/promises";
61458
+ import { readFile as readFile14 } from "fs/promises";
60917
61459
  async function writeRevisionedTextFile(filePath, content, expectedRevision) {
60918
- const current = await readFile13(filePath, "utf8");
61460
+ const current = await readFile14(filePath, "utf8");
60919
61461
  const revision = fileRevision(current);
60920
61462
  if (revision !== expectedRevision) {
60921
61463
  return {
@@ -60929,15 +61471,15 @@ async function writeRevisionedTextFile(filePath, content, expectedRevision) {
60929
61471
 
60930
61472
  // src/services/canvas-service.ts
60931
61473
  var GLOBAL_CANVAS_DIRECTORIES = [
60932
- join25(homedir7(), ".claude", "plans"),
60933
- join25(process.env.XDG_DATA_HOME ?? join25(homedir7(), ".local", "share"), "opencode", "plans"),
60934
- join25(homedir7(), ".replicas", "canvas")
61474
+ join26(homedir7(), ".claude", "plans"),
61475
+ join26(process.env.XDG_DATA_HOME ?? join26(homedir7(), ".local", "share"), "opencode", "plans"),
61476
+ join26(homedir7(), ".replicas", "canvas")
60935
61477
  ];
60936
61478
  async function canvasDirectories(repositories) {
60937
61479
  repositories ??= await gitService.listRepositories().catch(() => []);
60938
61480
  return [
60939
61481
  ...GLOBAL_CANVAS_DIRECTORIES,
60940
- ...repositories.map((repository) => join25(repository.path, ".opencode", "plans"))
61482
+ ...repositories.map((repository) => join26(repository.path, ".opencode", "plans"))
60941
61483
  ];
60942
61484
  }
60943
61485
  var CanvasService = class {
@@ -60955,14 +61497,14 @@ var CanvasService = class {
60955
61497
  if (!current) continue;
60956
61498
  let entries;
60957
61499
  try {
60958
- entries = await readdir7(current.directory, { withFileTypes: true });
61500
+ entries = await readdir8(current.directory, { withFileTypes: true });
60959
61501
  } catch {
60960
61502
  continue;
60961
61503
  }
60962
61504
  for (const entry of entries) {
60963
61505
  if (entry.name.startsWith(".")) continue;
60964
61506
  const filename = current.relativePath ? `${current.relativePath}/${entry.name}` : entry.name;
60965
- const filePath = join25(current.directory, entry.name);
61507
+ const filePath = join26(current.directory, entry.name);
60966
61508
  if (entry.isDirectory()) {
60967
61509
  pending.push({ directory: filePath, relativePath: filename });
60968
61510
  continue;
@@ -60986,7 +61528,7 @@ var CanvasService = class {
60986
61528
  const safe = sanitizeCanvasFilename(filename);
60987
61529
  if (!safe) return null;
60988
61530
  for (const directory of await this.directories()) {
60989
- const path8 = join25(directory, safe);
61531
+ const path8 = join26(directory, safe);
60990
61532
  const stats = await stat3(path8).catch(() => null);
60991
61533
  if (stats?.isFile()) {
60992
61534
  return {
@@ -61005,7 +61547,7 @@ var CanvasService = class {
61005
61547
  if (!item) return null;
61006
61548
  const { path: path8, ...file } = item;
61007
61549
  if (file.sizeBytes > maxBytes) return { ...file, tooLarge: true };
61008
- const bytes = await readFile14(path8).catch(() => null);
61550
+ const bytes = await readFile15(path8).catch(() => null);
61009
61551
  return bytes ? { ...file, bytes } : null;
61010
61552
  }
61011
61553
  async getItem(filename) {
@@ -61145,15 +61687,15 @@ async function reconcileCanvasItems(filenames) {
61145
61687
 
61146
61688
  // src/services/upload-chat-transcripts.ts
61147
61689
  import { createHash as createHash8 } from "crypto";
61148
- import { readFile as readFile15, readdir as readdir8 } from "fs/promises";
61690
+ import { readFile as readFile16, readdir as readdir9 } from "fs/promises";
61149
61691
  import { Readable } from "stream";
61150
- import { basename as basename3, join as join27 } from "path";
61692
+ import { basename as basename3, join as join28 } from "path";
61151
61693
 
61152
61694
  // src/services/chat/chat-senders.ts
61153
- import { join as join26 } from "path";
61154
- var CHAT_SENDERS_DIR = join26(ENGINE_DIR, "chat-senders");
61695
+ import { join as join27 } from "path";
61696
+ var CHAT_SENDERS_DIR = join27(ENGINE_DIR, "chat-senders");
61155
61697
  function chatMessageSendersFilePath(chatId) {
61156
- return join26(CHAT_SENDERS_DIR, `${chatId}.jsonl`);
61698
+ return join27(CHAT_SENDERS_DIR, `${chatId}.jsonl`);
61157
61699
  }
61158
61700
  function parseChatMessageSendersJsonl(content) {
61159
61701
  return content.split("\n").flatMap((line) => {
@@ -61229,7 +61771,7 @@ async function flushAllChatTranscripts(chatsById = /* @__PURE__ */ new Map(), ca
61229
61771
  for (const dir of HISTORY_DIRS) {
61230
61772
  let entries;
61231
61773
  try {
61232
- entries = await readdir8(dir);
61774
+ entries = await readdir9(dir);
61233
61775
  } catch {
61234
61776
  continue;
61235
61777
  }
@@ -61239,7 +61781,7 @@ async function flushAllChatTranscripts(chatsById = /* @__PURE__ */ new Map(), ca
61239
61781
  const chat = chatsById.get(chatId);
61240
61782
  if (!shouldFlushChatTranscript(dir, chat, chatsById, Boolean(capture))) continue;
61241
61783
  tasks.push(
61242
- uploadChatTranscript(chatId, join27(dir, entry), chat, capture).then(async (artifact) => {
61784
+ uploadChatTranscript(chatId, join28(dir, entry), chat, capture).then(async (artifact) => {
61243
61785
  flushed++;
61244
61786
  if (artifact && capture) revisions.push(artifact);
61245
61787
  await onUploaded?.(chatId, artifact).catch((err) => {
@@ -61308,7 +61850,7 @@ async function uploadOpenedTranscript(chatId, opened, historyVersion, chat, capt
61308
61850
  } : {};
61309
61851
  try {
61310
61852
  metadata.senders = parseChatMessageSendersJsonl(
61311
- await readFile15(chatMessageSendersFilePath(chatId), "utf-8")
61853
+ await readFile16(chatMessageSendersFilePath(chatId), "utf-8")
61312
61854
  );
61313
61855
  } catch (error) {
61314
61856
  if (!(error && typeof error === "object" && "code" in error && error.code === "ENOENT")) throw error;
@@ -61397,8 +61939,8 @@ async function flushRepoState() {
61397
61939
 
61398
61940
  // src/services/upload-engine-logs.ts
61399
61941
  import { createReadStream } from "fs";
61400
- import { readdir as readdir9, stat as stat4 } from "fs/promises";
61401
- import { join as join28 } from "path";
61942
+ import { readdir as readdir10, stat as stat4 } from "fs/promises";
61943
+ import { join as join29 } from "path";
61402
61944
  var MAX_ENGINE_LOG_FLUSH_SESSIONS = 10;
61403
61945
  var MAX_ENGINE_LOG_FLUSH_BYTES = 5 * 1024 * 1024;
61404
61946
  var ENGINE_LOG_FLUSH_TIMEOUT_MS = 2e4;
@@ -61408,7 +61950,7 @@ async function flushAllEngineLogs() {
61408
61950
  let failed = 0;
61409
61951
  const deadline = Date.now() + ENGINE_LOG_FLUSH_TIMEOUT_MS;
61410
61952
  await runBeforeDeadline((signal) => engineLogger.flush(signal), deadline);
61411
- const files = await runBeforeDeadline(() => readdir9(LOG_DIR), deadline).catch(() => []);
61953
+ const files = await runBeforeDeadline(() => readdir10(LOG_DIR), deadline).catch(() => []);
61412
61954
  const currentFilename = engineLogger.sessionId ? `${engineLogger.sessionId}.log` : null;
61413
61955
  const filenames = files.filter((filename) => {
61414
61956
  if (!filename.endsWith(".log")) return false;
@@ -61427,7 +61969,7 @@ async function flushAllEngineLogs() {
61427
61969
  const candidates = (await Promise.all(filenames.slice(0, MAX_ENGINE_LOG_FLUSH_SESSIONS).map(async (filename) => {
61428
61970
  try {
61429
61971
  const sessionId = filename.slice(0, -".log".length);
61430
- const filePath = join28(LOG_DIR, filename);
61972
+ const filePath = join29(LOG_DIR, filename);
61431
61973
  const fileStat = await runBeforeDeadline(() => stat4(filePath), deadline);
61432
61974
  if (!fileStat.isFile()) {
61433
61975
  skipped++;
@@ -61524,9 +62066,9 @@ async function uploadEngineLog(input, timeoutMs) {
61524
62066
 
61525
62067
  // src/services/chat/fork-handoff.ts
61526
62068
  import { createHash as createHash9 } from "crypto";
61527
- import { mkdir as mkdir14, readFile as readFile16, writeFile as writeFile8 } from "fs/promises";
62069
+ import { mkdir as mkdir14, readFile as readFile17, writeFile as writeFile8 } from "fs/promises";
61528
62070
  import { homedir as homedir8 } from "os";
61529
- import { join as join29 } from "path";
62071
+ import { join as join30 } from "path";
61530
62072
  var EXCERPT_MAX_CHARS = 24e3;
61531
62073
  var CONVERSATION_UPDATE_MAX_CHARS = 8e3;
61532
62074
  var PULL_REQUEST_DECISIONS_MAX_CHARS = 4e3;
@@ -61589,7 +62131,7 @@ ${text}` : null;
61589
62131
  }
61590
62132
  async function buildForkHandoff(input) {
61591
62133
  const sources = await Promise.all(input.segments.map(async (segment, index) => {
61592
- const rawHistoryPath = join29(HISTORY_DIR_BY_PROVIDER[segment.provider], `${segment.chatId}.jsonl`);
62134
+ const rawHistoryPath = join30(HISTORY_DIR_BY_PROVIDER[segment.provider], `${segment.chatId}.jsonl`);
61593
62135
  const { content, truncated: truncated2 } = await readHistoryTail(rawHistoryPath, MAX_SANITIZED_SOURCE_BYTES, segment.openHistory);
61594
62136
  const last = index === input.segments.length - 1;
61595
62137
  const blocks2 = canonicalizeChatTranscriptBlocks(content, segment.provider, segment.senders, last ? input.beforeMessageId : void 0).filter((block) => !block.startsWith("## Agent reasoning"));
@@ -61603,9 +62145,9 @@ async function buildForkHandoff(input) {
61603
62145
  const start = blocks.findLastIndex((block) => block.startsWith("## User") && ++turns === input.turnLimit);
61604
62146
  blocks = blocks.slice(Math.max(0, start));
61605
62147
  }
61606
- const forkDir = join29(FORKS_DIR, input.targetChatId);
62148
+ const forkDir = join30(FORKS_DIR, input.targetChatId);
61607
62149
  await mkdir14(forkDir, { recursive: true });
61608
- const transcriptPath = join29(forkDir, input.transcriptName ?? "source-transcript.md");
62150
+ const transcriptPath = join30(forkDir, input.transcriptName ?? "source-transcript.md");
61609
62151
  const rawHistoryPaths = sources.map((source) => source.rawHistoryPath);
61610
62152
  const header = sourceTruncated ? `_This file was generated from only the most recent ${MAX_SANITIZED_SOURCE_BYTES / 1024 / 1024} MB of ${sources.length > 1 ? "each part of " : ""}the source chat.${fullHistory ? ` The complete raw event ${sources.length > 1 ? `logs are, oldest first: ${rawHistoryPaths.join(", ")}` : `log is at ${rawHistoryPaths[0]}`}; grep ${sources.length > 1 ? "them" : "it"} for anything earlier.` : ""}_
61611
62153
 
@@ -61624,7 +62166,7 @@ async function buildForkHandoff(input) {
61624
62166
  };
61625
62167
  }
61626
62168
  async function readPullRequestDecisions(notesPath) {
61627
- const notes = await readFile16(notesPath.replace(/^~(?=\/)/, homedir8()), "utf-8").catch(() => "");
62169
+ const notes = await readFile17(notesPath.replace(/^~(?=\/)/, homedir8()), "utf-8").catch(() => "");
61628
62170
  const decisions = /^## Decisions[^\n]*\n([\s\S]*?)(?=^## |(?![\s\S]))/m.exec(notes)?.[1].trim();
61629
62171
  if (!decisions) return null;
61630
62172
  const body = decisions.length > PULL_REQUEST_DECISIONS_MAX_CHARS ? `${decisions.slice(0, PULL_REQUEST_DECISIONS_MAX_CHARS)}
@@ -61683,7 +62225,7 @@ function terminalErrorsFromEvent(event, provider) {
61683
62225
  if (codexTurn) {
61684
62226
  return normalizeCodexAspTranscriptStatus(codexTurn.status) === "failed" ? [codexTurn.error ?? "Codex run failed"] : void 0;
61685
62227
  }
61686
- const mayContainProviderError = provider === "cursor" && event.type === "cursor-error" || provider === "opencode" && (event.type === "opencode-error" || event.type === "opencode-message.updated") || provider === "pi" && (event.type === "pi-error" || event.type === "pi-message_end") || provider === "muse" && event.type === "muse-error";
62228
+ const mayContainProviderError = provider === "cursor" && event.type === "cursor-error" || provider === "gemini" && event.type === "gemini-error" || provider === "opencode" && (event.type === "opencode-error" || event.type === "opencode-message.updated") || provider === "pi" && (event.type === "pi-error" || event.type === "pi-message_end") || provider === "muse" && event.type === "muse-error";
61687
62229
  if (!mayContainProviderError) return void 0;
61688
62230
  const errors = parseAgentEvents([event], provider).flatMap((message) => message.type === "error" ? [message.message] : []);
61689
62231
  return errors.length > 0 ? errors : void 0;
@@ -61691,7 +62233,7 @@ function terminalErrorsFromEvent(event, provider) {
61691
62233
  var LAST_MESSAGE_PREVIEW_MAX = 200;
61692
62234
  var FINAL_MESSAGE_MAX = 6e3;
61693
62235
  var PROGRESS_INTERVAL_MS = 2e4;
61694
- var STREAM_RECORD_TYPES = /* @__PURE__ */ new Set(["pi-message_update", "opencode-message.part.delta", "muse-item-delta", "cursor-assistant", "cursor-thinking"]);
62236
+ var STREAM_RECORD_TYPES = /* @__PURE__ */ new Set(["pi-message_update", "opencode-message.part.delta", "muse-item-delta", "cursor-assistant", "cursor-thinking", "gemini-chunk"]);
61695
62237
  var PROGRESS_STEP_MAX = 120;
61696
62238
  var TURN_REQUEST_MAX = 8e3;
61697
62239
  var toolInputRequestSchema = z4.object({
@@ -61729,6 +62271,9 @@ var NOT_WORK_MESSAGE_TYPES = /* @__PURE__ */ new Set(["user", "error", "capacity
61729
62271
  function hasActiveAgentWork(chat) {
61730
62272
  return chat.provider.isProcessing() || hasActiveBackgroundWork(chat) || chat.turnCompletion !== null;
61731
62273
  }
62274
+ function isChatIdle(chat) {
62275
+ return chat.acceptingMessages === 0 && !hasActiveChatTurn(chat) && !hasActiveAgentWork(chat);
62276
+ }
61732
62277
  function hasActiveChatTurn(chat) {
61733
62278
  return chat.hasActiveTurn || chat.pendingMessageIds.length > 0 || isForkPreparing(chat) || chat.provider.isProcessing();
61734
62279
  }
@@ -61927,6 +62472,11 @@ var ChatService = class {
61927
62472
  hasActiveAgentWork(provider) {
61928
62473
  return [...this.chats.values()].some((chat) => chat.persisted.provider === provider && (hasActiveAgentWork(chat) || chat.acceptingMessages > 0 || chat.pendingMessageIds.length > 0));
61929
62474
  }
62475
+ async releaseAgentSessions(provider) {
62476
+ const chats = [...this.chats.values()].filter((chat) => !chat.persisted.deletedAt && chat.persisted.provider === provider);
62477
+ for (const chat of chats) chat.releaseWhenIdle = !isChatIdle(chat);
62478
+ await Promise.all(chats.filter((chat) => !chat.releaseWhenIdle).map((chat) => this.releaseAgentProcess(chat)));
62479
+ }
61930
62480
  listDeletedChats(includeChildren = false) {
61931
62481
  return Array.from(this.chats.values()).filter((chat) => chat.persisted.deletedAt && (includeChildren || chat.persisted.parentChatId === null)).map((chat) => this.toSummary(chat)).sort((a, b) => (b.deletedAt ?? "").localeCompare(a.deletedAt ?? ""));
61932
62482
  }
@@ -61943,7 +62493,7 @@ var ChatService = class {
61943
62493
  const [discovered, learnedSkills] = await Promise.all([
61944
62494
  chat.provider.listSlashCommands?.() ?? [],
61945
62495
  // Learned skills work in the background, so they stay out of the slash menu.
61946
- readFile17(LEARNED_SKILLS_MANIFEST_PATH, "utf-8").then((content) => new Set(learnedSkillsManifestSchema.parse(JSON.parse(content)).skills.flatMap(({ name }) => [`/${name}`, `/${LEARNED_SKILL_DIR_PREFIX}${name}`]))).catch(() => /* @__PURE__ */ new Set())
62496
+ readFile18(LEARNED_SKILLS_MANIFEST_PATH, "utf-8").then((content) => new Set(learnedSkillsManifestSchema.parse(JSON.parse(content)).skills.flatMap(({ name }) => [`/${name}`, `/${LEARNED_SKILL_DIR_PREFIX}${name}`]))).catch(() => /* @__PURE__ */ new Set())
61947
62497
  ]);
61948
62498
  const providerCommands = discovered.filter(({ command }) => !learnedSkills.has(command)).map((command) => ({
61949
62499
  ...command,
@@ -62421,7 +62971,7 @@ ${decisions}` };
62421
62971
  }
62422
62972
  }
62423
62973
  async readSenders(chatId) {
62424
- return readFile17(chatMessageSendersFilePath(chatId), "utf-8").then(parseChatMessageSendersJsonl).catch((error) => {
62974
+ return readFile18(chatMessageSendersFilePath(chatId), "utf-8").then(parseChatMessageSendersJsonl).catch((error) => {
62425
62975
  if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return [];
62426
62976
  console.error("[ChatService] Failed to read sender records:", error);
62427
62977
  return [];
@@ -62794,7 +63344,7 @@ ${decisions}` };
62794
63344
  `${historyPath}.pages.index.json`
62795
63345
  ].map((path8) => rm7(path8, { force: true })));
62796
63346
  await rm7(chatMessageSendersFilePath(persisted.id), { force: true });
62797
- await rm7(join30(FORKS_DIR, persisted.id), { recursive: true, force: true });
63347
+ await rm7(join31(FORKS_DIR, persisted.id), { recursive: true, force: true });
62798
63348
  }
62799
63349
  switchHarness(source, request) {
62800
63350
  const switching = (async () => {
@@ -63133,7 +63683,7 @@ ${note}`;
63133
63683
  };
63134
63684
  }
63135
63685
  historyPath(persisted) {
63136
- return join30(HISTORY_DIR_BY_PROVIDER[persisted.provider], `${persisted.id}.jsonl`);
63686
+ return join31(HISTORY_DIR_BY_PROVIDER[persisted.provider], `${persisted.id}.jsonl`);
63137
63687
  }
63138
63688
  async recordUploadedHistory(chatId, artifact) {
63139
63689
  const chat = this.getRuntimeChat(chatId);
@@ -63322,6 +63872,8 @@ ${note}`;
63322
63872
  provider = new ClaudeManager(managerOptions);
63323
63873
  } else if (baseProvider === "cursor") {
63324
63874
  provider = new CursorManager(managerOptions);
63875
+ } else if (baseProvider === "gemini") {
63876
+ provider = new GeminiManager(managerOptions);
63325
63877
  } else if (baseProvider === "muse") {
63326
63878
  provider = new MuseManager(managerOptions);
63327
63879
  } else if (baseProvider === "opencode") {
@@ -63367,6 +63919,7 @@ ${note}`;
63367
63919
  stopped: null,
63368
63920
  publishedQueue: null,
63369
63921
  idleReleaseTimer: null,
63922
+ releaseWhenIdle: false,
63370
63923
  history,
63371
63924
  outbox: new AsyncLock(),
63372
63925
  unpublishedHistoryStarts: [],
@@ -63625,7 +64178,8 @@ ${note}`;
63625
64178
  this.publish({ type: "chat.updated", payload: { chat: this.toSummary(chat) } }).catch(() => {
63626
64179
  });
63627
64180
  this.notifyWorkspaceAgentIdle();
63628
- this.scheduleIdleRelease(chat);
64181
+ if (chat.releaseWhenIdle && isChatIdle(chat)) void this.releaseAgentProcess(chat);
64182
+ else this.scheduleIdleRelease(chat);
63629
64183
  }
63630
64184
  // Idleness is re-checked when the timer fires: work that starts in between
63631
64185
  // ends with another processing stop, which schedules a fresh release.
@@ -63635,7 +64189,7 @@ ${note}`;
63635
64189
  this.enforceLiveProcessCap();
63636
64190
  chat.idleReleaseTimer = setTimeout(() => {
63637
64191
  chat.idleReleaseTimer = null;
63638
- if (chat.persisted.deletedAt || chat.acceptingMessages > 0 || hasActiveChatTurn(chat) || hasActiveAgentWork(chat)) return;
64192
+ if (chat.persisted.deletedAt || !isChatIdle(chat)) return;
63639
64193
  void this.releaseAgentProcess(chat);
63640
64194
  }, chat.persisted.parentChatId === null ? CHAT_IDLE_RELEASE_MS : CHILD_CHAT_IDLE_RELEASE_MS);
63641
64195
  chat.idleReleaseTimer.unref?.();
@@ -63646,13 +64200,14 @@ ${note}`;
63646
64200
  }
63647
64201
  enforceLiveProcessCap() {
63648
64202
  const live = [...this.chats.values()].filter((chat) => chat.live);
63649
- const idle = live.filter((chat) => chat.acceptingMessages === 0 && !hasActiveChatTurn(chat) && !hasActiveAgentWork(chat)).sort((a, b) => a.persisted.updatedAt.localeCompare(b.persisted.updatedAt));
64203
+ const idle = live.filter(isChatIdle).sort((a, b) => a.persisted.updatedAt.localeCompare(b.persisted.updatedAt));
63650
64204
  for (const chat of idle.slice(0, Math.max(0, live.length - maxLiveAgentProcesses()))) void this.releaseAgentProcess(chat);
63651
64205
  }
63652
64206
  /** Senders await `chat.release` so a new turn never starts against a session that is being torn down. */
63653
64207
  releaseAgentProcess(chat) {
63654
64208
  this.cancelIdleRelease(chat);
63655
64209
  chat.live = false;
64210
+ chat.releaseWhenIdle = false;
63656
64211
  chat.release ??= Promise.resolve().then(() => chat.provider.dispose?.()).catch((error) => console.error("[ChatService] Failed to release chat agent process:", { chatId: chat.persisted.id, error })).finally(() => {
63657
64212
  chat.release = null;
63658
64213
  });
@@ -63758,7 +64313,7 @@ ${note}`;
63758
64313
  }
63759
64314
  async loadChats() {
63760
64315
  try {
63761
- const content = await readFile17(CHATS_FILE, "utf-8");
64316
+ const content = await readFile18(CHATS_FILE, "utf-8");
63762
64317
  return parsePersistedChatsContent(content);
63763
64318
  } catch (error) {
63764
64319
  if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
@@ -63773,7 +64328,7 @@ ${note}`;
63773
64328
  console.error("[ChatService] Failed to quarantine corrupt chats file:", renameError);
63774
64329
  }
63775
64330
  try {
63776
- const backupContent = await readFile17(CHATS_BACKUP_FILE, "utf-8");
64331
+ const backupContent = await readFile18(CHATS_BACKUP_FILE, "utf-8");
63777
64332
  return parsePersistedChatsContent(backupContent);
63778
64333
  } catch (backupError) {
63779
64334
  if (backupError && typeof backupError === "object" && "code" in backupError && backupError.code === "ENOENT") {
@@ -63923,15 +64478,15 @@ ${note}`;
63923
64478
  // src/services/repo-file-service.ts
63924
64479
  import { execFile as execFile7 } from "child_process";
63925
64480
  import { createReadStream as createReadStream2 } from "fs";
63926
- import { readFile as readFile18, realpath as realpath2, stat as stat5 } from "fs/promises";
64481
+ import { readFile as readFile19, realpath as realpath2, stat as stat5 } from "fs/promises";
63927
64482
  import { homedir as homedir9 } from "os";
63928
- import { extname as extname3, isAbsolute as isAbsolute3, join as join32, resolve as resolve5 } from "path";
64483
+ import { extname as extname3, isAbsolute as isAbsolute3, join as join33, resolve as resolve5 } from "path";
63929
64484
 
63930
64485
  // src/services/language-server-service.ts
63931
64486
  import { spawn as spawn4 } from "child_process";
63932
64487
  import { existsSync as existsSync15, readFileSync as readFileSync6 } from "fs";
63933
64488
  import { createRequire as createRequire5 } from "module";
63934
- import { delimiter as delimiter2, dirname as dirname13, join as join31, relative as relative2 } from "path";
64489
+ import { delimiter as delimiter2, dirname as dirname13, join as join32, relative as relative2 } from "path";
63935
64490
  import { setTimeout as setTimeout3 } from "timers/promises";
63936
64491
  import { fileURLToPath as fileURLToPath5, pathToFileURL } from "url";
63937
64492
  import { createMessageConnection, StreamMessageReader, StreamMessageWriter } from "vscode-jsonrpc/node.js";
@@ -64050,7 +64605,7 @@ var LanguageServerService = class {
64050
64605
  if (config.package && config.bin) command = process.execPath;
64051
64606
  else if (config.command) {
64052
64607
  const commandName = config.command;
64053
- command = process.env.PATH?.split(delimiter2).map((directory) => join31(directory, commandName)).find(existsSync15);
64608
+ command = process.env.PATH?.split(delimiter2).map((directory) => join32(directory, commandName)).find(existsSync15);
64054
64609
  }
64055
64610
  const args = config.package && config.bin ? [packageBin(config.package, config.bin), ...config.args] : config.args;
64056
64611
  if (!command) return null;
@@ -64213,7 +64768,7 @@ var RepoFileService = class {
64213
64768
  ...isAbsolute3(filePath) ? ["/"] : [],
64214
64769
  ...repos.map((repo) => repo.path),
64215
64770
  ...await canvasDirectories(repos),
64216
- join32(this.homeDir, "workspaces"),
64771
+ join33(this.homeDir, "workspaces"),
64217
64772
  this.homeDir
64218
64773
  ];
64219
64774
  for (const root of roots) {
@@ -64305,7 +64860,7 @@ var RepoFileService = class {
64305
64860
  async inspectSymbol(repoName, filePath, line, character, action) {
64306
64861
  const resolved = await this.resolveFile(repoName, filePath);
64307
64862
  if (!resolved || line < 1 || character < 0 || isBinaryExtension(filePath)) return null;
64308
- const content = await readFile18(resolved.fullPath, "utf8");
64863
+ const content = await readFile19(resolved.fullPath, "utf8");
64309
64864
  const sourceLine = content.split("\n")[line - 1];
64310
64865
  if (sourceLine === void 0) return null;
64311
64866
  const symbolMatch = Array.from(sourceLine.matchAll(/[\p{L}_$][\p{L}\p{N}_$]*/gu)).find((match) => character >= match.index && character <= match.index + match[0].length);
@@ -64418,22 +64973,22 @@ var RepoFileService = class {
64418
64973
  // src/v1-routes.ts
64419
64974
  import { Hono } from "hono";
64420
64975
  import { z as z6 } from "zod";
64421
- import { readdir as readdir11, stat as stat6, readFile as readFile21 } from "fs/promises";
64976
+ import { readdir as readdir12, stat as stat6, readFile as readFile22 } from "fs/promises";
64422
64977
  import { openAsBlob } from "fs";
64423
- import { join as join35, resolve as resolve6 } from "path";
64978
+ import { join as join36, resolve as resolve6 } from "path";
64424
64979
 
64425
64980
  // src/services/warm-hooks-service.ts
64426
64981
  import { spawn as spawn5 } from "child_process";
64427
- import { readFile as readFile20 } from "fs/promises";
64982
+ import { readFile as readFile21 } from "fs/promises";
64428
64983
  import { existsSync as existsSync16 } from "fs";
64429
- import { join as join34 } from "path";
64984
+ import { join as join35 } from "path";
64430
64985
 
64431
64986
  // src/services/warm-hook-logs-service.ts
64432
- import { mkdir as mkdir16, readFile as readFile19, writeFile as writeFile9, readdir as readdir10, appendFile as appendFile5, unlink as unlink2 } from "fs/promises";
64987
+ import { mkdir as mkdir16, readFile as readFile20, writeFile as writeFile9, readdir as readdir11, appendFile as appendFile5, unlink as unlink2 } from "fs/promises";
64433
64988
  import { homedir as homedir10 } from "os";
64434
- import { join as join33 } from "path";
64435
- var LOGS_DIR2 = join33(homedir10(), ".replicas", "warm-hook-logs");
64436
- var CURRENT_RUN_LOG = join33(LOGS_DIR2, "current-run.log");
64989
+ import { join as join34 } from "path";
64990
+ var LOGS_DIR2 = join34(homedir10(), ".replicas", "warm-hook-logs");
64991
+ var CURRENT_RUN_LOG = join34(LOGS_DIR2, "current-run.log");
64437
64992
  function withPreview2(stored) {
64438
64993
  const preview = buildHookOutputPreview(stored.output);
64439
64994
  return { ...stored, ...preview };
@@ -64449,7 +65004,7 @@ var WarmHookLogsService = class {
64449
65004
  hookName: "environment",
64450
65005
  ...entry
64451
65006
  };
64452
- await writeFile9(join33(LOGS_DIR2, ENVIRONMENT_HOOK_LOG_FILENAME), `${JSON.stringify(log, null, 2)}
65007
+ await writeFile9(join34(LOGS_DIR2, ENVIRONMENT_HOOK_LOG_FILENAME), `${JSON.stringify(log, null, 2)}
64453
65008
  `, "utf-8");
64454
65009
  }
64455
65010
  async saveRepoHookLog(repoName, entry) {
@@ -64459,13 +65014,13 @@ var WarmHookLogsService = class {
64459
65014
  hookName: repoName,
64460
65015
  ...entry
64461
65016
  };
64462
- await writeFile9(join33(LOGS_DIR2, repoHookLogFilename(repoName)), `${JSON.stringify(log, null, 2)}
65017
+ await writeFile9(join34(LOGS_DIR2, repoHookLogFilename(repoName)), `${JSON.stringify(log, null, 2)}
64463
65018
  `, "utf-8");
64464
65019
  }
64465
65020
  async getAllLogs() {
64466
65021
  let files;
64467
65022
  try {
64468
- files = await readdir10(LOGS_DIR2);
65023
+ files = await readdir11(LOGS_DIR2);
64469
65024
  } catch (err) {
64470
65025
  if (err.code === "ENOENT") {
64471
65026
  return [];
@@ -64478,7 +65033,7 @@ var WarmHookLogsService = class {
64478
65033
  continue;
64479
65034
  }
64480
65035
  try {
64481
- const raw = await readFile19(join33(LOGS_DIR2, file), "utf-8");
65036
+ const raw = await readFile20(join34(LOGS_DIR2, file), "utf-8");
64482
65037
  const stored = JSON.parse(raw);
64483
65038
  if (stored.hookType !== "environment" && stored.hookType !== "repository") continue;
64484
65039
  logs.push(withPreview2(stored));
@@ -64505,7 +65060,7 @@ var WarmHookLogsService = class {
64505
65060
  }
64506
65061
  async getCurrentRunLog() {
64507
65062
  try {
64508
- return await readFile19(CURRENT_RUN_LOG, "utf-8");
65063
+ return await readFile20(CURRENT_RUN_LOG, "utf-8");
64509
65064
  } catch (err) {
64510
65065
  if (err.code === "ENOENT") return null;
64511
65066
  throw err;
@@ -64514,7 +65069,7 @@ var WarmHookLogsService = class {
64514
65069
  async getFullOutput(hookType, hookName) {
64515
65070
  const filename = hookType === "environment" ? ENVIRONMENT_HOOK_LOG_FILENAME : repoHookLogFilename(hookName);
64516
65071
  try {
64517
- const raw = await readFile19(join33(LOGS_DIR2, filename), "utf-8");
65072
+ const raw = await readFile20(join34(LOGS_DIR2, filename), "utf-8");
64518
65073
  const stored = JSON.parse(raw);
64519
65074
  if (stored.hookType !== hookType || stored.hookName !== hookName) {
64520
65075
  return null;
@@ -64533,12 +65088,12 @@ var warmHookLogsService = new WarmHookLogsService();
64533
65088
  // src/services/warm-hooks-service.ts
64534
65089
  async function readRepoWarmHook(repoPath) {
64535
65090
  for (const filename of REPLICAS_CONFIG_FILENAMES) {
64536
- const configPath = join34(repoPath, filename);
65091
+ const configPath = join35(repoPath, filename);
64537
65092
  if (!existsSync16(configPath)) {
64538
65093
  continue;
64539
65094
  }
64540
65095
  try {
64541
- const raw = await readFile20(configPath, "utf-8");
65096
+ const raw = await readFile21(configPath, "utf-8");
64542
65097
  const config = parseReplicasConfigString(raw, filename);
64543
65098
  if (!config.warmHook) {
64544
65099
  return null;
@@ -65653,6 +66208,14 @@ data: ${JSON.stringify("Terminal session not found")}
65653
66208
  );
65654
66209
  }
65655
66210
  });
66211
+ app2.post("/credentials/withdraw", async (c) => {
66212
+ const { logins } = await c.req.json();
66213
+ for (const { provider, ...login } of logins) {
66214
+ if (await withdrawAgentLogin(provider, login)) await deps.chatService.releaseAgentSessions(provider);
66215
+ clearCredentialFallbacks(provider);
66216
+ }
66217
+ return c.json(await environmentDetailsService.getDetails());
66218
+ });
65656
66219
  app2.post("/credentials/switch", async (c) => {
65657
66220
  const body = await c.req.json();
65658
66221
  const provider = workspaceCredentialProviderSchema.safeParse(body.provider);
@@ -65904,11 +66467,11 @@ data: ${JSON.stringify("Terminal session not found")}
65904
66467
  });
65905
66468
  app2.get("/logs", async (c) => {
65906
66469
  try {
65907
- const files = await readdir11(LOG_DIR).catch(() => []);
66470
+ const files = await readdir12(LOG_DIR).catch(() => []);
65908
66471
  const logFiles = files.filter((f) => f.endsWith(".log"));
65909
66472
  const sessions = await Promise.all(
65910
66473
  logFiles.map(async (filename) => {
65911
- const filePath = join35(LOG_DIR, filename);
66474
+ const filePath = join36(LOG_DIR, filename);
65912
66475
  const fileStat = await stat6(filePath);
65913
66476
  const sessionId = filename.replace(/\.log$/, "");
65914
66477
  return {
@@ -65943,7 +66506,7 @@ data: ${JSON.stringify("Terminal session not found")}
65943
66506
  }
65944
66507
  let content;
65945
66508
  try {
65946
- content = await readFile21(filePath, "utf-8");
66509
+ content = await readFile22(filePath, "utf-8");
65947
66510
  } catch {
65948
66511
  return c.json(jsonError("Log session not found"), 404);
65949
66512
  }
@@ -65967,7 +66530,7 @@ data: ${JSON.stringify("Terminal session not found")}
65967
66530
  import { randomUUID as randomUUID12 } from "crypto";
65968
66531
  import { mkdir as mkdir17, open as open3, stat as stat7, writeFile as writeFile10 } from "fs/promises";
65969
66532
  import { arch as arch2, platform as platform3 } from "os";
65970
- import { dirname as dirname14, join as join36, resolve as resolve7 } from "path";
66533
+ import { dirname as dirname14, join as join37, resolve as resolve7 } from "path";
65971
66534
  import { z as z7 } from "zod";
65972
66535
 
65973
66536
  // src/services/exec/process-registry.ts
@@ -66163,7 +66726,7 @@ function parse(schema, json) {
66163
66726
  return parsed.data;
66164
66727
  }
66165
66728
  function resolvePath(target) {
66166
- if (target === "~" || target.startsWith("~/")) return join36(ENGINE_ENV.HOME_DIR, target.slice(1));
66729
+ if (target === "~" || target.startsWith("~/")) return join37(ENGINE_ENV.HOME_DIR, target.slice(1));
66167
66730
  return resolve7(ENGINE_ENV.WORKSPACE_ROOT, target);
66168
66731
  }
66169
66732
  async function mcpServerProcess(name) {
@@ -66439,13 +67002,13 @@ function attachTerminalSocket(id, socket) {
66439
67002
  }
66440
67003
 
66441
67004
  // src/services/resource-monitor.ts
66442
- import { readFile as readFile22 } from "fs/promises";
67005
+ import { readFile as readFile23 } from "fs/promises";
66443
67006
  var SAMPLE_INTERVAL_MS = 5e3;
66444
67007
  var READ_TIMEOUT_MS = 2e3;
66445
67008
  var pendingReads = new InFlightMap();
66446
67009
  var boundedReads = /* @__PURE__ */ new WeakMap();
66447
67010
  function readWithin(path8) {
66448
- const read = pendingReads.run(path8, () => readFile22(path8, "utf8"));
67011
+ const read = pendingReads.run(path8, () => readFile23(path8, "utf8"));
66449
67012
  const bounded = boundedReads.get(read) ?? withTimeout(read, READ_TIMEOUT_MS, `Timed out reading ${path8}`);
66450
67013
  boundedReads.set(read, bounded);
66451
67014
  return bounded;
@@ -66704,8 +67267,8 @@ async function installWorkspaceSdk() {
66704
67267
  // src/services/git-push-tracker.ts
66705
67268
  import { mkdir as mkdir19, rm as rm8 } from "fs/promises";
66706
67269
  import { createServer as createServer3 } from "net";
66707
- import { join as join37 } from "path";
66708
- var SOCKET_PATH = join37(ENGINE_DIR, "git-trace2.sock");
67270
+ import { join as join38 } from "path";
67271
+ var SOCKET_PATH = join38(ENGINE_DIR, "git-trace2.sock");
66709
67272
  var MAX_LINE_LENGTH = 1024 * 1024;
66710
67273
  var listening = null;
66711
67274
  function startGitPushTracker() {