replicas-engine 0.1.1723 → 0.1.1727

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-3CPR45ZM.js";
93
+ } from "./chunk-2X4SV2H7.js";
94
94
  import {
95
95
  evaluateCommandProtection,
96
96
  extractToolCommand,
97
97
  reportCommandProtectionBlock
98
- } from "./chunk-AOHM54TJ.js";
98
+ } from "./chunk-YKUHRKKX.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-XPAPYRHZ.js";
138
+ } from "./chunk-QN5PAZSN.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-6VLLTNFH.js";
148
+ } from "./chunk-LWHGKKNM.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-VMB5N26K.js";
228
+ } from "./chunk-OAFO4KYM.js";
219
229
  import {
220
230
  SUBAGENT_MCP_TOOL_TIMEOUT_MS,
221
231
  engineScriptProcess,
222
232
  subagentMcpProcessConfig
223
- } from "./chunk-WXIXFDZT.js";
233
+ } from "./chunk-M6ELG3GK.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-IZFPPNVH.js";
244
+ } from "./chunk-OY6X5AUJ.js";
235
245
  import {
236
246
  AspRequestTimeoutError,
237
247
  AspResponseError,
238
248
  buildCodexAgentEnv,
239
249
  getCodexModelProvider
240
- } from "./chunk-NXMU4YQB.js";
250
+ } from "./chunk-F2YDU3AP.js";
241
251
  import {
242
252
  SUBPROCESS_MAX_BUFFER,
243
253
  execAsync,
244
254
  execFileAsync
245
- } from "./chunk-7X2SLJ52.js";
255
+ } from "./chunk-NTSUADYM.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,
@@ -353,7 +364,6 @@ import {
353
364
  SUBAGENT_MCP_HARNESSES,
354
365
  SUBAGENT_MCP_SERVER_NAME,
355
366
  SUBAGENT_MCP_TOOLS,
356
- SUBAGENT_MCP_TOOL_NAMES,
357
367
  TENSORLAKE_IMAGE_NAME,
358
368
  TERMINAL_RTC_ICE_SERVER,
359
369
  TIMEOUT,
@@ -523,6 +533,7 @@ import {
523
533
  sendChatMessageRequestSchema,
524
534
  sendChatMessageResponseSchema,
525
535
  serializeCanvasContentResponse,
536
+ serializeGeminiAuthFile,
526
537
  serializeMuseAuthFile,
527
538
  shellQuotePosix,
528
539
  shouldRefreshPullRequests,
@@ -543,7 +554,7 @@ import {
543
554
  workspaceTokenRequestSchema,
544
555
  workspaceTokenResponseSchema,
545
556
  wrapInTag
546
- } from "./chunk-S32SJWSV.js";
557
+ } from "./chunk-GBVHK7GR.js";
547
558
  import {
548
559
  __commonJS,
549
560
  __export,
@@ -680,7 +691,7 @@ var require_lib = __commonJS({
680
691
  "../node_modules/.bun/which@5.0.0/node_modules/which/lib/index.js"(exports, module) {
681
692
  "use strict";
682
693
  var { isexe, sync: isexeSync } = require_index_min();
683
- var { join: join38, delimiter: delimiter3, sep: sep2, posix } = __require("path");
694
+ var { join: join39, delimiter: delimiter3, sep: sep2, posix } = __require("path");
684
695
  var isWindows = process.platform === "win32";
685
696
  var rSlash = new RegExp(`[${posix.sep}${sep2 === posix.sep ? "" : sep2}]`.replace(/(\\)/g, "\\$1"));
686
697
  var rRel = new RegExp(`^\\.${rSlash.source}`);
@@ -709,7 +720,7 @@ var require_lib = __commonJS({
709
720
  var getPathPart = (raw, cmd) => {
710
721
  const pathPart = /^".*"$/.test(raw) ? raw.slice(1, -1) : raw;
711
722
  const prefix = !pathPart && rRel.test(cmd) ? cmd.slice(0, 2) : "";
712
- return prefix + join38(pathPart, cmd);
723
+ return prefix + join39(pathPart, cmd);
713
724
  };
714
725
  var which = async (cmd, opt = {}) => {
715
726
  const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
@@ -9292,7 +9303,13 @@ var ClaudeTokenManager = class extends BaseRefreshManager {
9292
9303
  }
9293
9304
  async requestAndApplyCredentials(generation, request) {
9294
9305
  console.log("[ClaudeTokenManager] Refreshing Claude credentials...");
9295
- const data = await requestClaudeCredentials(request);
9306
+ const data = await requestClaudeCredentials(request).catch(async (error) => {
9307
+ const revocation = refreshRevocation(error);
9308
+ if (revocation) await this.applyCredentialUpdate(generation, async () => {
9309
+ await withdrawAgentLogin("claude", revocation);
9310
+ });
9311
+ throw error;
9312
+ });
9296
9313
  await this.applyCredentialUpdate(generation, () => this.applyCredentialsResponse(data));
9297
9314
  console.log(`[ClaudeTokenManager] Credentials refreshed (method=${data.type})`);
9298
9315
  }
@@ -9962,6 +9979,8 @@ function detectAgentAuthMethod(provider) {
9962
9979
  return detectCodexAuthMethod();
9963
9980
  case AGENT.CURSOR:
9964
9981
  return ENGINE_ENV.CURSOR_API_KEY ? "api_key" : "none";
9982
+ case AGENT.GEMINI:
9983
+ return existsSync(GEMINI_AUTH_PATH) ? "oauth" : "none";
9965
9984
  case AGENT.MUSE:
9966
9985
  if (!existsSync(MUSE_AUTH_PATH)) return "none";
9967
9986
  if (ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS.muse?.method === "api_key") return "api_key";
@@ -10121,6 +10140,7 @@ var EnvironmentDetailsService = class {
10121
10140
  details.claudeAuthMethod = detectAgentAuthMethod(AGENT.CLAUDE);
10122
10141
  details.codexAuthMethod = detectAgentAuthMethod(AGENT.CODEX);
10123
10142
  details.cursorAuthMethod = detectAgentAuthMethod(AGENT.CURSOR);
10143
+ details.geminiAuthMethod = existsSync2(GEMINI_CLI_PATH) ? detectAgentAuthMethod(AGENT.GEMINI) : void 0;
10124
10144
  details.museAuthMethod = detectAgentAuthMethod(AGENT.MUSE);
10125
10145
  details.opencodeAuthMethod = detectAgentAuthMethod(AGENT.OPENCODE);
10126
10146
  details.piAuthMethod = detectAgentAuthMethod(AGENT.PI);
@@ -11129,14 +11149,14 @@ function localControlComputers() {
11129
11149
  }
11130
11150
 
11131
11151
  // src/services/chat/chat-service.ts
11132
- import { appendFile as appendFile4, copyFile as copyFile2, mkdir as mkdir15, readFile as readFile17, rename as rename3, rm as rm7 } from "fs/promises";
11133
- import { join as join30 } from "path";
11152
+ import { appendFile as appendFile4, copyFile as copyFile2, mkdir as mkdir15, readFile as readFile18, rename as rename3, rm as rm7 } from "fs/promises";
11153
+ import { join as join31 } from "path";
11134
11154
  import { randomUUID as randomUUID9 } from "crypto";
11135
11155
  import { z as z4 } from "zod";
11136
11156
 
11137
11157
  // ../shared/src/persisted-query-hashes.ts
11138
11158
  var PERSISTED_QUERY_HASHES = {
11139
- workspaceChats: "15f7a29e"
11159
+ workspaceChats: "79cb548c"
11140
11160
  };
11141
11161
 
11142
11162
  // ../shared/src/workspace-chat.ts
@@ -11392,7 +11412,10 @@ var MuseTokenManager = class extends BaseRefreshManager {
11392
11412
  };
11393
11413
  const response = await monolithRequest("/v1/engine/muse/refresh-credentials", { body: request, signal: AbortSignal.timeout(12e4) });
11394
11414
  if (!response.ok) {
11395
- throw new Error(`Credentials refresh failed: ${response.status} ${await response.text()}`);
11415
+ const error = new Error(`Credentials refresh failed: ${response.status} ${await response.text()}`);
11416
+ const revocation = refreshRevocation(error);
11417
+ if (revocation) await withdrawAgentLogin("muse", revocation);
11418
+ throw error;
11396
11419
  }
11397
11420
  const data = await response.json();
11398
11421
  await writeSecureCredentialFile(MUSE_AUTH_PATH, serializeMuseAuthFile(data), { ensureParentDir: true });
@@ -11404,6 +11427,41 @@ var MuseTokenManager = class extends BaseRefreshManager {
11404
11427
  };
11405
11428
  var museTokenManager = new MuseTokenManager();
11406
11429
 
11430
+ // src/managers/gemini-token-manager.ts
11431
+ var GeminiTokenManager = class extends BaseRefreshManager {
11432
+ constructor() {
11433
+ super("GeminiTokenManager");
11434
+ }
11435
+ doRefresh() {
11436
+ return Promise.resolve();
11437
+ }
11438
+ async fetchFreshCredentials(failureReason, failureKind = "exhausted", failedCredential = ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS.gemini, allowedMethods) {
11439
+ return this.swapCredentials({
11440
+ provider: "gemini",
11441
+ failureKind,
11442
+ allowedMethods,
11443
+ refresh: async (exclusions) => {
11444
+ const request = {
11445
+ failedMethod: CREDENTIAL_METHOD.GEMINI_OAUTH,
11446
+ ...failedCredential ? { failedCredential } : {},
11447
+ failureReason,
11448
+ failureKind,
11449
+ ...exclusions
11450
+ };
11451
+ const response = await monolithRequest("/v1/engine/gemini/refresh-credentials", { body: request, signal: AbortSignal.timeout(12e4) });
11452
+ if (!response.ok) {
11453
+ throw new Error(`Credentials refresh failed: ${response.status} ${await response.text()}`);
11454
+ }
11455
+ const data = await response.json();
11456
+ await writeSecureCredentialFile(GEMINI_AUTH_PATH, serializeGeminiAuthFile(data), { ensureParentDir: true });
11457
+ setAgentCredentialSnapshot("gemini", data);
11458
+ },
11459
+ keepRefreshing: () => false
11460
+ });
11461
+ }
11462
+ };
11463
+ var geminiTokenManager = new GeminiTokenManager();
11464
+
11407
11465
  // src/managers/opencode-token-manager.ts
11408
11466
  var OPENCODE_AUTH_ENV_KEYS = [...ollamaAuthEnvKeys("opencode"), ...openAICompatibleAuthEnvKeys("opencode")];
11409
11467
  var OpencodeTokenManager = class extends BaseRefreshManager {
@@ -11433,7 +11491,10 @@ var OpencodeTokenManager = class extends BaseRefreshManager {
11433
11491
  };
11434
11492
  const response = await monolithRequest("/v1/engine/opencode/refresh-credentials", { body: request, signal: AbortSignal.timeout(12e4) });
11435
11493
  if (!response.ok) {
11436
- throw new Error(`Credentials refresh failed: ${response.status} ${await response.text()}`);
11494
+ const error = new Error(`Credentials refresh failed: ${response.status} ${await response.text()}`);
11495
+ const revocation = refreshRevocation(error);
11496
+ if (revocation) await withdrawAgentLogin("opencode", revocation);
11497
+ throw error;
11437
11498
  }
11438
11499
  const data = await response.json();
11439
11500
  for (const file of data.auth.files ?? []) {
@@ -11453,6 +11514,7 @@ var opencodeTokenManager = new OpencodeTokenManager();
11453
11514
  var SWAPPABLE_AGENTS = {
11454
11515
  claude: claudeTokenManager,
11455
11516
  codex: codexTokenManager,
11517
+ gemini: geminiTokenManager,
11456
11518
  muse: museTokenManager,
11457
11519
  opencode: opencodeTokenManager
11458
11520
  };
@@ -13411,32 +13473,10 @@ var PromptStream = class {
13411
13473
  };
13412
13474
  }
13413
13475
  };
13414
- var ALWAYS_ALLOWED_TOOLS = [
13415
- "Read",
13416
- "Glob",
13417
- "Grep",
13418
- "WebSearch",
13419
- "WebFetch",
13420
- "TaskCreate",
13421
- "TaskUpdate",
13422
- "TaskGet",
13423
- "TaskList",
13424
- "Agent",
13425
- "ListMcpResourcesTool",
13426
- "ReadMcpResourceTool",
13427
- "Skill",
13428
- "ToolSearch",
13429
- "Bash",
13430
- "Monitor",
13431
- "Write",
13432
- "Edit",
13433
- "NotebookEdit",
13434
- "TaskOutput",
13435
- "TaskStop",
13436
- "ScheduleWakeup"
13437
- ];
13438
13476
  var ALWAYS_DISALLOWED_TOOLS = [
13477
+ "AskUserQuestion",
13439
13478
  "EnterPlanMode",
13479
+ "ExitPlanMode",
13440
13480
  "EnterWorktree",
13441
13481
  "ExitWorktree",
13442
13482
  "CronCreate",
@@ -13445,7 +13485,6 @@ var ALWAYS_DISALLOWED_TOOLS = [
13445
13485
  "RemoteTrigger",
13446
13486
  "PushNotification"
13447
13487
  ];
13448
- var INTERACTIVE_TOOL_NAMES = ["AskUserQuestion", "ExitPlanMode"];
13449
13488
  var COMMAND_PROTECTION_SAFE_TOOLS = /* @__PURE__ */ new Set([
13450
13489
  "Read",
13451
13490
  "Write",
@@ -13468,80 +13507,6 @@ function supportsClaudeThinkingDisplay(model) {
13468
13507
  const normalized = (normalizeClaudeModel(model) ?? model).toLowerCase();
13469
13508
  return AGENT_MODELS.claude.includes(normalized) || /^claude-(?:opus|sonnet|haiku)-[4-9]/.test(normalized);
13470
13509
  }
13471
- var TOOL_INPUT_HANDLERS = {
13472
- ExitPlanMode: {
13473
- getRequest: () => ({
13474
- options: [
13475
- { id: "approve", label: "Start implementing", variant: "primary" },
13476
- { id: "deny", label: "Keep planning", variant: "secondary" }
13477
- ]
13478
- }),
13479
- resolve: (selectionId, input) => {
13480
- if (selectionId === "approve") {
13481
- return { result: { behavior: "allow", updatedInput: input }, summary: "Start implementing" };
13482
- }
13483
- return { result: { behavior: "deny", message: "User declined to exit plan mode." }, summary: "Keep planning" };
13484
- }
13485
- },
13486
- AskUserQuestion: {
13487
- getRequest: (input) => {
13488
- const questions = Array.isArray(input.questions) ? input.questions : [];
13489
- return {
13490
- questions: questions.map((q, qi) => ({
13491
- id: String(qi),
13492
- prompt: q.question,
13493
- multiSelect: Boolean(q.multiSelect),
13494
- options: (q.options ?? []).map((opt, oi) => ({
13495
- id: String(oi),
13496
- label: opt.label,
13497
- description: opt.description,
13498
- preview: opt.preview
13499
- }))
13500
- }))
13501
- };
13502
- },
13503
- resolve: (selectionId, input) => {
13504
- if (selectionId === "declined") {
13505
- return {
13506
- result: { behavior: "deny", message: "User declined to answer questions." },
13507
- summary: "Declined to answer"
13508
- };
13509
- }
13510
- let parsed;
13511
- try {
13512
- parsed = JSON.parse(selectionId);
13513
- } catch {
13514
- return {
13515
- result: { behavior: "deny", message: "Invalid selection payload." }
13516
- };
13517
- }
13518
- const questions = Array.isArray(input.questions) ? input.questions : [];
13519
- const answers = {};
13520
- const summaryParts = [];
13521
- for (let qi = 0; qi < questions.length; qi++) {
13522
- const q = questions[qi];
13523
- const { custom, options } = toolInputAnswer(parsed, String(qi));
13524
- let answer = null;
13525
- if (custom) {
13526
- answer = custom;
13527
- } else if (options.length > 0) {
13528
- const labels = options.map((idx) => q.options[Number(idx)]?.label).filter((l) => Boolean(l));
13529
- if (labels.length > 0) {
13530
- answer = labels.join(", ");
13531
- }
13532
- }
13533
- if (answer) {
13534
- answers[q.question] = answer;
13535
- summaryParts.push(`${q.question}: ${answer}`);
13536
- }
13537
- }
13538
- return {
13539
- result: { behavior: "allow", updatedInput: { ...input, answers } },
13540
- summary: summaryParts.join(" \u2022 ")
13541
- };
13542
- }
13543
- }
13544
- };
13545
13510
  var ClaudeAuthError = class extends Error {
13546
13511
  constructor(message) {
13547
13512
  super(message);
@@ -13664,8 +13629,6 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
13664
13629
  partialMessageStreams = /* @__PURE__ */ new Map();
13665
13630
  requestsInFlight = /* @__PURE__ */ new Map();
13666
13631
  partialMessageFlushTimers = /* @__PURE__ */ new Map();
13667
- /** Active tool-input requests keyed by requestId; resolved when the user selects an option. */
13668
- pendingToolInputs = /* @__PURE__ */ new Map();
13669
13632
  supportedSlashCommands = [];
13670
13633
  slashCommandsDiscoveredAt = 0;
13671
13634
  slashCommandsDiscovery = null;
@@ -13691,7 +13654,6 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
13691
13654
  this.pendingInterrupt = true;
13692
13655
  this.stoppedAtMs = stoppedAt ? Date.parse(stoppedAt) : Date.now();
13693
13656
  const stopping = (async () => {
13694
- await this.abortAllPendingToolInputs();
13695
13657
  const query2 = this.activeQuery;
13696
13658
  if (query2) {
13697
13659
  const interrupt = query2.interrupt.bind(query2);
@@ -13839,22 +13801,6 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
13839
13801
  return;
13840
13802
  }
13841
13803
  }
13842
- async abortAllPendingToolInputs() {
13843
- const pending = Array.from(this.pendingToolInputs.values());
13844
- this.pendingToolInputs.clear();
13845
- for (const entry of pending) {
13846
- entry.resolve({ behavior: "deny", message: "Turn interrupted" });
13847
- await this.emitToolInputEvent("replicas-tool-input-resolved", {
13848
- requestId: entry.requestId,
13849
- toolUseId: entry.toolUseId,
13850
- toolName: entry.toolName,
13851
- selectionId: "aborted"
13852
- });
13853
- }
13854
- }
13855
- isAwaitingInput() {
13856
- return this.pendingToolInputs.size > 0;
13857
- }
13858
13804
  isAuthRetrying() {
13859
13805
  return this.authRetrying;
13860
13806
  }
@@ -13967,82 +13913,6 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
13967
13913
  this.authRetrying = value;
13968
13914
  this.emitSyntheticEvent(AUTH_RETRY_STATUS_EVENT_TYPE, { isAuthRetrying: value });
13969
13915
  }
13970
- async respondToToolInput(requestId, selectionId) {
13971
- const pending = this.pendingToolInputs.get(requestId);
13972
- if (!pending) {
13973
- return false;
13974
- }
13975
- this.pendingToolInputs.delete(requestId);
13976
- const resolution = pending.handler.resolve(selectionId, pending.input);
13977
- pending.resolve(resolution.result);
13978
- await this.emitToolInputEvent("replicas-tool-input-resolved", {
13979
- requestId,
13980
- toolUseId: pending.toolUseId,
13981
- toolName: pending.toolName,
13982
- selectionId,
13983
- ...resolution.summary ? { selectionSummary: resolution.summary } : {}
13984
- });
13985
- return true;
13986
- }
13987
- async emitToolInputEvent(type, payload) {
13988
- const event = {
13989
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
13990
- type,
13991
- payload: { ...payload, parent_tool_use_id: null }
13992
- };
13993
- this.record(event);
13994
- }
13995
- buildCanUseTool() {
13996
- return async (toolName, input, options) => {
13997
- const handler = TOOL_INPUT_HANDLERS[toolName];
13998
- if (!handler) {
13999
- return { behavior: "allow" };
14000
- }
14001
- const requestId = randomUUID3();
14002
- const toolUseId = options.toolUseID;
14003
- const { options: requestOptions, questions: requestQuestions } = handler.getRequest(input);
14004
- const result = await new Promise((resolve9) => {
14005
- this.pendingToolInputs.set(requestId, {
14006
- requestId,
14007
- toolUseId,
14008
- toolName,
14009
- input,
14010
- handler,
14011
- resolve: resolve9
14012
- });
14013
- const onAbort = () => {
14014
- const pending = this.pendingToolInputs.get(requestId);
14015
- if (!pending) return;
14016
- this.pendingToolInputs.delete(requestId);
14017
- pending.resolve({ behavior: "deny", message: "Aborted." });
14018
- this.emitToolInputEvent("replicas-tool-input-resolved", {
14019
- requestId: pending.requestId,
14020
- toolUseId: pending.toolUseId,
14021
- toolName: pending.toolName,
14022
- selectionId: "aborted"
14023
- }).catch((err) => {
14024
- console.error("[ClaudeManager] Failed to emit resolved event on abort:", err);
14025
- });
14026
- };
14027
- if (options.signal.aborted) {
14028
- onAbort();
14029
- return;
14030
- }
14031
- options.signal.addEventListener("abort", onAbort, { once: true });
14032
- this.emitToolInputEvent("replicas-tool-input-request", {
14033
- requestId,
14034
- toolUseId,
14035
- toolName,
14036
- ...requestOptions ? { options: requestOptions } : {},
14037
- ...requestQuestions ? { questions: requestQuestions } : {},
14038
- ...typeof input.plan === "string" ? { plan: input.plan } : {}
14039
- }).catch((err) => {
14040
- console.error("[ClaudeManager] Failed to emit tool-input request event:", err);
14041
- });
14042
- });
14043
- return result;
14044
- };
14045
- }
14046
13916
  buildCommandProtectionHook() {
14047
13917
  return async (input, toolUseID, options) => {
14048
13918
  if (input.hook_event_name !== "PreToolUse") return {};
@@ -14335,9 +14205,7 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
14335
14205
  message,
14336
14206
  model,
14337
14207
  customInstructions,
14338
- planMode,
14339
14208
  thinkingLevel,
14340
- enableInteractiveTools,
14341
14209
  fastMode
14342
14210
  } = request;
14343
14211
  if (!message || !message.trim()) {
@@ -14375,25 +14243,20 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
14375
14243
  const authMethod = resolveClaudeAuthMethodForMessage();
14376
14244
  const isClaudeModel = !!requestedModel && /^claude-/i.test(requestedModel);
14377
14245
  const resolvedModel = authMethod === "ollama" ? getFallbackModel("claude") ?? (requestedModel && !isClaudeModel ? requestedModel : DEFAULT_OLLAMA_MODEL) : (authMethod === "oauth" || authMethod === "api_key") && requestedModel && !isClaudeModel ? DEFAULT_CLAUDE_MODEL : requestedModel || DEFAULT_CLAUDE_MODEL;
14378
- const resolvedPermissionMode = planMode ? "plan" : "bypassPermissions";
14379
14246
  const resolvedFastMode = Boolean(fastMode && canUseClaudeFastMode(resolvedModel));
14380
14247
  this.onChatCredential("workspace");
14381
14248
  const signature = {
14382
14249
  credential: JSON.stringify(ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS.claude),
14383
14250
  combinedInstructions,
14384
14251
  thinkingLevel,
14385
- enableInteractiveTools: Boolean(enableInteractiveTools),
14386
14252
  fastMode: resolvedFastMode,
14387
14253
  autoCompactTokens: this.autoCompactTokens,
14388
- permissionMode: resolvedPermissionMode,
14389
14254
  subagentMcpParentChatId: this.subagentMcpParentChatId()
14390
14255
  };
14391
14256
  await this.ensureSession({
14392
14257
  signature,
14393
14258
  combinedInstructions,
14394
14259
  resolvedModel,
14395
- resolvedPermissionMode,
14396
- enableInteractiveTools: signature.enableInteractiveTools,
14397
14260
  thinkingLevel
14398
14261
  });
14399
14262
  const promptStream = this.activePromptStream;
@@ -14491,8 +14354,6 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
14491
14354
  signature,
14492
14355
  combinedInstructions,
14493
14356
  resolvedModel,
14494
- resolvedPermissionMode,
14495
- enableInteractiveTools,
14496
14357
  thinkingLevel
14497
14358
  } = args;
14498
14359
  if (this.activeQuery && this.activeSessionSignature && (this.sessionSignaturesMatch(this.activeSessionSignature, signature) || this.backgroundTasks.active.size > 0 && this.activeSessionSignature.credential === signature.credential)) {
@@ -14512,14 +14373,12 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
14512
14373
  await this.startSession({
14513
14374
  combinedInstructions,
14514
14375
  resolvedModel,
14515
- resolvedPermissionMode,
14516
- enableInteractiveTools,
14517
14376
  thinkingLevel,
14518
14377
  signature
14519
14378
  });
14520
14379
  }
14521
14380
  sessionSignaturesMatch(a, b) {
14522
- return a.combinedInstructions === b.combinedInstructions && a.credential === b.credential && a.thinkingLevel === b.thinkingLevel && a.enableInteractiveTools === b.enableInteractiveTools && a.fastMode === b.fastMode && a.autoCompactTokens === b.autoCompactTokens && a.permissionMode === b.permissionMode && a.subagentMcpParentChatId === b.subagentMcpParentChatId;
14381
+ return a.combinedInstructions === b.combinedInstructions && a.credential === b.credential && a.thinkingLevel === b.thinkingLevel && a.fastMode === b.fastMode && a.autoCompactTokens === b.autoCompactTokens && a.subagentMcpParentChatId === b.subagentMcpParentChatId;
14523
14382
  }
14524
14383
  /** Query inputs shared by real sessions and slash-command discovery. */
14525
14384
  async buildSharedQueryOptions() {
@@ -14545,8 +14404,6 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
14545
14404
  const {
14546
14405
  combinedInstructions,
14547
14406
  resolvedModel,
14548
- resolvedPermissionMode,
14549
- enableInteractiveTools,
14550
14407
  thinkingLevel,
14551
14408
  signature
14552
14409
  } = args;
@@ -14560,17 +14417,10 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
14560
14417
  snapshot: false
14561
14418
  };
14562
14419
  const shared = await this.buildSharedQueryOptions();
14563
- const interactiveAllowed = enableInteractiveTools && resolvedPermissionMode === "plan";
14564
14420
  const subagentMcpParentChatId = signature.subagentMcpParentChatId;
14565
- const allowedTools = [
14566
- ...ALWAYS_ALLOWED_TOOLS.filter((tool) => !subagentMcpParentChatId || tool !== "Agent"),
14567
- ...subagentMcpParentChatId ? SUBAGENT_MCP_TOOL_NAMES.map((tool) => `mcp__${SUBAGENT_MCP_SERVER_NAME}__${tool}`) : [],
14568
- ...interactiveAllowed ? INTERACTIVE_TOOL_NAMES : []
14569
- ];
14570
14421
  const disallowedTools = [
14571
14422
  ...ALWAYS_DISALLOWED_TOOLS,
14572
- ...subagentMcpParentChatId ? ["Agent"] : [],
14573
- ...interactiveAllowed ? [] : INTERACTIVE_TOOL_NAMES
14423
+ ...subagentMcpParentChatId ? ["Agent"] : []
14574
14424
  ];
14575
14425
  const promptStream = new PromptStream();
14576
14426
  const response = query({
@@ -14579,10 +14429,9 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
14579
14429
  resume: this.sessionId || void 0,
14580
14430
  cwd: this.workingDirectory,
14581
14431
  additionalDirectories: shared.additionalDirectories,
14582
- permissionMode: resolvedPermissionMode,
14583
- allowDangerouslySkipPermissions: resolvedPermissionMode === "bypassPermissions",
14584
- allowedTools,
14585
- ...disallowedTools.length > 0 ? { disallowedTools } : {},
14432
+ permissionMode: "bypassPermissions",
14433
+ allowDangerouslySkipPermissions: true,
14434
+ disallowedTools,
14586
14435
  settingSources: ["user", "project", "local"],
14587
14436
  systemPrompt,
14588
14437
  ...subagentMcpParentChatId ? { mcpServers: { [SUBAGENT_MCP_SERVER_NAME]: { type: "stdio", alwaysLoad: true, ...subagentMcpProcessConfig(subagentMcpParentChatId) } } } : {},
@@ -14605,7 +14454,7 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
14605
14454
  ...this.chatTitle ? { title: this.chatTitle() } : {},
14606
14455
  settings: {
14607
14456
  fastMode: signature.fastMode,
14608
- // Every session in the sandbox is one of the user's chats; the default holds messages across permission modes, and a plan mode chat has no one to release them.
14457
+ // Every session in the sandbox is one of the user's chats; the default holds some peer messages for an approval no one is there to give.
14609
14458
  crossSessionInbound: "accept",
14610
14459
  ...signature.autoCompactTokens ? { autoCompactWindow: signature.autoCompactTokens } : {},
14611
14460
  ...ultracode ? { enableWorkflows: true, ultracode: true } : {}
@@ -14614,7 +14463,6 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
14614
14463
  forwardSubagentText: true,
14615
14464
  ...supportsClaudeThinkingDisplay(resolvedModel) ? { thinking: { type: "adaptive", display: "summarized" } } : {},
14616
14465
  ...effort ? { effort } : {},
14617
- ...resolvedPermissionMode === "plan" ? { canUseTool: this.buildCanUseTool() } : {},
14618
14466
  hooks: {
14619
14467
  PreToolUse: [{
14620
14468
  matcher: "*",
@@ -14914,7 +14762,7 @@ ${msg.result}` } : { ...msg, errors: [loginFailure, ...msg.errors] } : msg);
14914
14762
  this.backgroundContinuationTimer = null;
14915
14763
  if (this.pendingInterrupt || this.backgroundTasks.active.size > 0) return;
14916
14764
  if (this.sessionActivity.state === "running" && !this.pendingTurn) return;
14917
- if (this.pendingTurn || this.messageQueue.isProcessing() || this.isAwaitingInput() || this.sessionActivity.state === "requires_action") {
14765
+ if (this.pendingTurn || this.messageQueue.isProcessing() || this.sessionActivity.state === "requires_action") {
14918
14766
  this.backgroundContinuationTimer = setTimeout(() => this.recoverBackgroundContinuation(query2), CLAUDE_BACKGROUND_CONTINUATION_GRACE_MS);
14919
14767
  return;
14920
14768
  }
@@ -14939,11 +14787,9 @@ ${msg.result}` } : { ...msg, errors: [loginFailure, ...msg.errors] } : msg);
14939
14787
  async failBackgroundSession(query2, message) {
14940
14788
  if (this.activeQuery !== query2) return;
14941
14789
  await this.emitTerminalErrorResult(message, [message]);
14942
- await this.abortAllPendingToolInputs();
14943
14790
  if (this.activeQuery === query2) await this.tearDownSession();
14944
14791
  }
14945
14792
  async dispose() {
14946
- await this.abortAllPendingToolInputs();
14947
14793
  await this.tearDownSession();
14948
14794
  }
14949
14795
  async forkPoint(beforeMessageId) {
@@ -17224,32 +17070,45 @@ function getPostToolPrHookPath() {
17224
17070
  if (!postToolHookPath) throw new Error("Replicas post-tool PR hook executable is missing.");
17225
17071
  return postToolHookPath;
17226
17072
  }
17227
- async function ensureCursorCommandProtectionHook() {
17228
- const path8 = join13(ENGINE_ENV.HOME_DIR, ".cursor", "hooks.json");
17073
+ async function updateHooksFile(path8, label, update) {
17229
17074
  let config = {};
17230
17075
  try {
17231
17076
  const content = await readFile8(path8, "utf8");
17232
17077
  const parsed = content.trim() ? JSON.parse(content) : {};
17233
- if (!isRecord(parsed)) throw new Error("Invalid Cursor hooks configuration.");
17078
+ if (!isRecord(parsed)) throw new Error(`Invalid ${label} hooks configuration.`);
17234
17079
  config = parsed;
17235
17080
  } catch (error) {
17236
17081
  if (!(error && typeof error === "object" && "code" in error && error.code === "ENOENT")) throw error;
17237
17082
  }
17238
- const hooks = isRecord(config.hooks) ? config.hooks : {};
17239
- const existing = Array.isArray(hooks.preToolUse) ? hooks.preToolUse : [];
17240
- hooks.preToolUse = [
17241
- ...existing.filter((entry) => !isRecord(entry) || typeof entry.command !== "string" || !entry.command.includes("command-protection-hook")),
17242
- { command: shellCommand(hookPath, "cursor") }
17243
- ];
17244
- const existingPost = Array.isArray(hooks.postToolUse) ? hooks.postToolUse : [];
17245
- hooks.postToolUse = [
17246
- ...existingPost.filter((entry) => !isRecord(entry) || typeof entry.command !== "string" || !entry.command.includes("post-tool-pr-hook")),
17247
- { command: shellCommand(postToolHookPath) }
17248
- ];
17249
17083
  await mkdir9(dirname4(path8), { recursive: true });
17250
- await atomicWriteFile(path8, `${JSON.stringify({ ...config, version: 1, hooks }, null, 2)}
17084
+ await atomicWriteFile(path8, `${JSON.stringify(update(config), null, 2)}
17251
17085
  `);
17252
17086
  }
17087
+ async function ensureCursorCommandProtectionHook() {
17088
+ await updateHooksFile(join13(ENGINE_ENV.HOME_DIR, ".cursor", "hooks.json"), "Cursor", (config) => {
17089
+ const hooks = isRecord(config.hooks) ? config.hooks : {};
17090
+ const existing = Array.isArray(hooks.preToolUse) ? hooks.preToolUse : [];
17091
+ hooks.preToolUse = [
17092
+ ...existing.filter((entry) => !isRecord(entry) || typeof entry.command !== "string" || !entry.command.includes("command-protection-hook")),
17093
+ { command: shellCommand(hookPath, "cursor") }
17094
+ ];
17095
+ const existingPost = Array.isArray(hooks.postToolUse) ? hooks.postToolUse : [];
17096
+ hooks.postToolUse = [
17097
+ ...existingPost.filter((entry) => !isRecord(entry) || typeof entry.command !== "string" || !entry.command.includes("post-tool-pr-hook")),
17098
+ { command: shellCommand(postToolHookPath) }
17099
+ ];
17100
+ return { ...config, version: 1, hooks };
17101
+ });
17102
+ }
17103
+ async function ensureGeminiCommandProtectionHook() {
17104
+ await updateHooksFile(join13(ENGINE_ENV.HOME_DIR, ".gemini", "config", "hooks.json"), "Antigravity", (config) => ({
17105
+ ...config,
17106
+ "replicas-command-protection": {
17107
+ PreToolUse: [{ matcher: "", hooks: [{ type: "command", command: shellCommand(hookPath, "gemini"), timeout: 60 }] }],
17108
+ PostToolUse: [{ matcher: "run_command", hooks: [{ type: "command", command: shellCommand(postToolHookPath) }] }]
17109
+ }
17110
+ }));
17111
+ }
17253
17112
 
17254
17113
  // src/managers/cursor-run-recovery.ts
17255
17114
  import { Agent as CursorAgent, AgentBusyError } from "@cursor/sdk";
@@ -17521,7 +17380,7 @@ var CursorManager = class extends CodingAgentManager {
17521
17380
  this.recordUserMessageHistoryEvent(request, {}, this.turnBeganAt);
17522
17381
  const sending = sendCursorRun(agent, message, {
17523
17382
  model: { id: model },
17524
- mode: request.planMode ? "plan" : "agent",
17383
+ mode: "agent",
17525
17384
  onDelta: (args) => {
17526
17385
  markCursorActivity();
17527
17386
  this.recordCursorContextUsage(args.update);
@@ -18028,7 +17887,7 @@ ${typeof pending.subject.command === "string" ? pending.subject.command : JSON.s
18028
17887
  await this.request("session/setApprovalMode", {
18029
17888
  commandId: uuidV7(),
18030
17889
  sessionId: this.sessionId,
18031
- mode: request.planMode ? "denyUnmatched" : "allowAll"
17890
+ mode: "allowAll"
18032
17891
  });
18033
17892
  await this.request("session/setModel", {
18034
17893
  commandId: uuidV7(),
@@ -18041,7 +17900,7 @@ ${typeof pending.subject.command === "string" ? pending.subject.command : JSON.s
18041
17900
  ${pending}
18042
17901
  </workspace-instructions>
18043
17902
 
18044
- ` : ""}${request.planMode ? "Plan the requested work without modifying files or running mutating commands.\n\n" : ""}${request.message}`;
17903
+ ` : ""}${request.message}`;
18045
17904
  if (!this.deliver(signal)) return;
18046
17905
  recordUserMessage();
18047
17906
  this.turnError = null;
@@ -18215,10 +18074,353 @@ ${pending}
18215
18074
  }
18216
18075
  };
18217
18076
 
18077
+ // src/services/installed-skill-service.ts
18078
+ import { readFile as readFile10, readdir as readdir6 } from "fs/promises";
18079
+ import { join as join15 } from "path";
18080
+ var installedSkillsByHome = /* @__PURE__ */ new Map();
18081
+ function isNotFoundError2(error) {
18082
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
18083
+ }
18084
+ async function loadInstalledSkills(homeDir) {
18085
+ const skillsDir = join15(homeDir, ".agents/skills");
18086
+ let entries;
18087
+ try {
18088
+ entries = await readdir6(skillsDir, { withFileTypes: true });
18089
+ } catch (error) {
18090
+ if (!isNotFoundError2(error)) console.warn("[InstalledSkills] Failed to list installed skills:", error);
18091
+ return [];
18092
+ }
18093
+ const skills = await Promise.all(entries.filter((entry) => entry.isDirectory() || entry.isSymbolicLink()).map(async (entry) => {
18094
+ try {
18095
+ const metadata = parseFrontmatter(await readFile10(join15(skillsDir, entry.name, "SKILL.md"), "utf8"));
18096
+ return metadata.name && metadata.description ? metadata : null;
18097
+ } catch (error) {
18098
+ if (!isNotFoundError2(error)) console.warn(`[InstalledSkills] Failed to read ${entry.name}:`, error);
18099
+ return null;
18100
+ }
18101
+ }));
18102
+ return skills.filter((skill) => skill !== null);
18103
+ }
18104
+ async function getInstalledSkillsAsSlashCommands(homeDir, provider) {
18105
+ let installedSkills = installedSkillsByHome.get(homeDir);
18106
+ if (!installedSkills) {
18107
+ installedSkills = loadInstalledSkills(homeDir);
18108
+ installedSkillsByHome.set(homeDir, installedSkills);
18109
+ }
18110
+ return (await installedSkills).flatMap(({ name, description }) => {
18111
+ const command = createProviderSlashCommand(provider, name, description);
18112
+ return command ? [command] : [];
18113
+ });
18114
+ }
18115
+
18116
+ // src/managers/gemini-manager.ts
18117
+ var GeminiQuotaError = class extends Error {
18118
+ };
18119
+ var GEMINI_LOGIN_REJECTED = /invalid_grant|not logged into Antigravity|Authentication required|UNAUTHENTICATED|Please log out \(\/logout\) and log back in/i;
18120
+ var GeminiManager = class extends CodingAgentManager {
18121
+ process = null;
18122
+ client = null;
18123
+ session = null;
18124
+ sessionId;
18125
+ systemPrompt = null;
18126
+ activePrompt = null;
18127
+ turnError = null;
18128
+ pendingQuestions = /* @__PURE__ */ new Map();
18129
+ slashCommands = [];
18130
+ constructor(options) {
18131
+ super({ ...options, provider: "gemini" });
18132
+ this.sessionId = options.initialSessionId;
18133
+ this.initializeManager(this.processMessageInternal.bind(this));
18134
+ }
18135
+ async initialize() {
18136
+ await ensureGeminiCommandProtectionHook();
18137
+ }
18138
+ /** Antigravity appends instructions to its system prompt only when a session starts, so changed ones restart it on the same conversation. */
18139
+ async start(instructions) {
18140
+ if (this.session && this.client && this.systemPrompt === instructions) return this.session;
18141
+ this.stopProcess();
18142
+ const { child, client } = spawnGeminiAcp(this.workingDirectory, this.originChatId ? { REPLICAS_CHAT_ID: this.originChatId } : void 0);
18143
+ this.process = child;
18144
+ this.client = client;
18145
+ client.on("notification", (frame) => this.handleNotification(frame));
18146
+ client.on("serverRequest", (frame) => this.handleServerRequest(frame));
18147
+ child.stderr.on("data", (chunk) => console.error("[gemini ACP]", chunk.toString().trimEnd()));
18148
+ child.on("error", (error) => this.handleProcessExit(child, error));
18149
+ child.on("exit", (code, signal) => this.handleProcessExit(child, new Error(`Antigravity exited with code ${code ?? signal}`)));
18150
+ await initializeGeminiAcp(client, 0);
18151
+ let session = null;
18152
+ if (this.sessionId) {
18153
+ session = await startGeminiSession(client, { cwd: this.workingDirectory, resumeSessionId: this.sessionId, systemPrompt: instructions }, 0).catch(() => null);
18154
+ }
18155
+ if (!session) {
18156
+ session = await startGeminiSession(client, { cwd: this.workingDirectory, systemPrompt: instructions }, 0);
18157
+ this.sessionId = session.sessionId;
18158
+ await this.onSaveSessionId(session.sessionId);
18159
+ }
18160
+ this.session = session;
18161
+ this.systemPrompt = instructions;
18162
+ return session;
18163
+ }
18164
+ request(method, params) {
18165
+ if (!this.client) return Promise.reject(new Error("Antigravity is not running."));
18166
+ return this.client.request(method, params, { timeoutMs: 0 });
18167
+ }
18168
+ handleProcessExit(child, error) {
18169
+ if (this.process !== child) return;
18170
+ const midTurn = (this.client?.pendingRequestCount ?? 0) > 0;
18171
+ this.process = null;
18172
+ this.session = null;
18173
+ this.client?.dispose(error);
18174
+ this.client = null;
18175
+ this.abortPendingQuestions();
18176
+ if (midTurn) this.turnError = error.message;
18177
+ }
18178
+ stopProcess() {
18179
+ const process10 = this.process;
18180
+ this.process = null;
18181
+ this.session = null;
18182
+ this.client?.dispose();
18183
+ this.client = null;
18184
+ this.abortPendingQuestions();
18185
+ process10?.kill("SIGTERM");
18186
+ }
18187
+ handleNotification(frame) {
18188
+ if (!isRecord2(frame) || frame.method !== "session/update" || !isRecord2(frame.params) || !isRecord2(frame.params.update)) return;
18189
+ if (frame.params.sessionId !== this.sessionId) return;
18190
+ const update = frame.params.update;
18191
+ const kind = update.sessionUpdate;
18192
+ if (kind === "available_commands_update" && Array.isArray(update.availableCommands)) {
18193
+ this.slashCommands = update.availableCommands.flatMap((command) => {
18194
+ if (!isRecord2(command) || typeof command.name !== "string") return [];
18195
+ const parsed = createProviderSlashCommand(
18196
+ "gemini",
18197
+ command.name,
18198
+ typeof command.description === "string" ? command.description : void 0,
18199
+ isRecord2(command.input) && typeof command.input.hint === "string" ? command.input.hint : void 0
18200
+ );
18201
+ return parsed ? [parsed] : [];
18202
+ });
18203
+ return;
18204
+ }
18205
+ if (kind === "config_option_update" && Array.isArray(update.configOptions)) {
18206
+ if (this.session) this.session.configOptions = update.configOptions;
18207
+ return;
18208
+ }
18209
+ if (kind === "usage_update" && typeof update.used === "number" && typeof update.size === "number") {
18210
+ this.recordContextUsage({
18211
+ provider: "gemini",
18212
+ source: "provider_usage",
18213
+ model: this.session ? geminiSelectOption(this.session.configOptions, "model")?.currentValue ?? null : null,
18214
+ totalTokens: update.used,
18215
+ maxTokens: update.size,
18216
+ percentage: update.size > 0 ? update.used / update.size * 100 : 0,
18217
+ categories: [],
18218
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
18219
+ });
18220
+ return;
18221
+ }
18222
+ if (kind === "current_mode_update" || kind === "session_info_update") return;
18223
+ this.recordHistoryEvent(kind === "agent_message_chunk" || kind === "agent_thought_chunk" ? "gemini-chunk" : "gemini-session-update", { update });
18224
+ }
18225
+ handleServerRequest(frame) {
18226
+ const client = this.client;
18227
+ if (!client || !isRecord2(frame) || typeof frame.id !== "string" && typeof frame.id !== "number") return;
18228
+ if (frame.method !== "session/request_permission" || !isRecord2(frame.params) || !isRecord2(frame.params.toolCall) || !Array.isArray(frame.params.options)) {
18229
+ client.reject(frame.id, -32601, "Unsupported request");
18230
+ return;
18231
+ }
18232
+ const toolCall = frame.params.toolCall;
18233
+ 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 }] : []);
18234
+ const toolCallId = typeof toolCall.toolCallId === "string" ? toolCall.toolCallId : String(frame.id);
18235
+ if (toolCallId.startsWith("interaction_")) {
18236
+ const requestId = `gemini-question:${toolCallId}`;
18237
+ this.pendingQuestions.set(requestId, { requestId: frame.id, toolCallId, optionIds: options.map((option2) => option2.id) });
18238
+ this.recordHistoryEvent("gemini-session-update", { update: { ...toolCall, sessionUpdate: "tool_call", status: "pending" } });
18239
+ this.recordHistoryEvent("replicas-tool-input-request", {
18240
+ requestId,
18241
+ toolUseId: toolCallId,
18242
+ toolName: "AskUserQuestion",
18243
+ questions: [{
18244
+ id: "question",
18245
+ prompt: typeof toolCall.title === "string" && toolCall.title ? toolCall.title : "Choose an option.",
18246
+ multiSelect: false,
18247
+ options: options.map(({ id, label }) => ({ id, label }))
18248
+ }],
18249
+ parent_tool_use_id: null
18250
+ });
18251
+ return;
18252
+ }
18253
+ const option = ["allow_always", "allow_once"].flatMap((kind) => options.filter((candidate) => candidate.kind === kind))[0];
18254
+ client.respond(frame.id, { outcome: option ? { outcome: "selected", optionId: option.id } : { outcome: "cancelled" } });
18255
+ }
18256
+ resolveQuestion(requestId, selectionId, selectionSummary) {
18257
+ const pending = this.pendingQuestions.get(requestId);
18258
+ if (!pending) return void 0;
18259
+ this.pendingQuestions.delete(requestId);
18260
+ this.recordHistoryEvent("replicas-tool-input-resolved", {
18261
+ requestId,
18262
+ toolUseId: pending.toolCallId,
18263
+ toolName: "AskUserQuestion",
18264
+ selectionId,
18265
+ ...selectionSummary ? { selectionSummary } : {},
18266
+ parent_tool_use_id: null
18267
+ });
18268
+ return pending;
18269
+ }
18270
+ abortPendingQuestions() {
18271
+ for (const requestId of [...this.pendingQuestions.keys()]) {
18272
+ const pending = this.resolveQuestion(requestId, "aborted");
18273
+ if (pending) this.client?.respond(pending.requestId, { outcome: { outcome: "cancelled" } });
18274
+ }
18275
+ }
18276
+ async respondToToolInput(requestId, selectionId) {
18277
+ const pending = this.pendingQuestions.get(requestId);
18278
+ if (!pending || !this.client) return false;
18279
+ if (selectionId === "declined") {
18280
+ this.resolveQuestion(requestId, "declined");
18281
+ this.client.respond(pending.requestId, { outcome: { outcome: "cancelled" } });
18282
+ return true;
18283
+ }
18284
+ const answer = toolInputAnswer(JSON.parse(selectionId), "question");
18285
+ const optionId = answer.options.find((id) => pending.optionIds.includes(id));
18286
+ if (!optionId) return false;
18287
+ this.resolveQuestion(requestId, selectionId);
18288
+ this.client.respond(pending.requestId, { outcome: { outcome: "selected", optionId } });
18289
+ return true;
18290
+ }
18291
+ isAwaitingInput() {
18292
+ return this.pendingQuestions.size > 0;
18293
+ }
18294
+ async createPrompt(request) {
18295
+ const prompt = [{ type: "text", text: request.message }];
18296
+ for (const image of await normalizeImages(request.images ?? [])) {
18297
+ if (image.label) prompt.push({ type: "text", text: image.label });
18298
+ prompt.push({ type: "image", mimeType: image.source.media_type, data: image.source.data });
18299
+ }
18300
+ return prompt;
18301
+ }
18302
+ async steerRequest(request) {
18303
+ if (!this.activePrompt || !this.sessionId) return false;
18304
+ const prompt = await this.createPrompt(request);
18305
+ const running = this.activePrompt;
18306
+ if (!running) return false;
18307
+ const steer = this.request("session/prompt", { sessionId: this.sessionId, prompt });
18308
+ steer.catch(() => {
18309
+ });
18310
+ this.activePrompt = steer;
18311
+ const accepted = await Promise.race([running.then(() => true, () => true), steer.then(() => true, () => false)]);
18312
+ if (!accepted) {
18313
+ if (this.activePrompt === steer) this.activePrompt = running;
18314
+ return false;
18315
+ }
18316
+ const read = this.markSteerRead(request.id);
18317
+ if (read) this.recordUserMessageHistoryEvent(read);
18318
+ return true;
18319
+ }
18320
+ async processMessageInternal(request, signal) {
18321
+ let userMessageRecorded = false;
18322
+ const dispatch = async (request2) => {
18323
+ const session = await this.start(this.buildCombinedInstructions(request2.customInstructions));
18324
+ const client = this.client;
18325
+ if (!client) throw new Error("Antigravity failed to start.");
18326
+ if (!userMessageRecorded) {
18327
+ this.recordUserMessageHistoryEvent(request2);
18328
+ userMessageRecorded = true;
18329
+ }
18330
+ await selectGeminiModel(client, session, request2.model ?? DEFAULT_GEMINI_MODEL, 0);
18331
+ const thinking = geminiSelectOption(session.configOptions, "thought_level");
18332
+ const thinkingValue = thinking ? thinkingVariant(new Set(thinking.values), request2.thinkingLevel) : void 0;
18333
+ if (thinking && thinkingValue && thinkingValue !== thinking.currentValue) {
18334
+ const result = await this.request("session/set_config_option", { sessionId: session.sessionId, configId: thinking.id, value: thinkingValue });
18335
+ if (isRecord2(result) && Array.isArray(result.configOptions)) session.configOptions = result.configOptions;
18336
+ }
18337
+ const prompt = await this.createPrompt(request2);
18338
+ if (signal.aborted) return;
18339
+ this.turnError = null;
18340
+ let response;
18341
+ try {
18342
+ this.activePrompt = this.request("session/prompt", { sessionId: session.sessionId, prompt });
18343
+ for (let pending = this.activePrompt; ; pending = this.activePrompt) {
18344
+ response = await pending;
18345
+ if (pending === this.activePrompt) break;
18346
+ }
18347
+ } catch (error) {
18348
+ this.turnError = (error instanceof Error ? error.message : String(error)).replace(/^ASP request failed for session\/prompt: (?:-?\d+ )?/, "");
18349
+ }
18350
+ if (this.turnError) {
18351
+ if (detectAgentQuotaLimit(this.turnError)) throw new GeminiQuotaError(this.turnError);
18352
+ throw new Error(this.turnError);
18353
+ }
18354
+ if (isRecord2(response) && isRecord2(response.usage)) this.onUsageUpdate(response.usage, (/* @__PURE__ */ new Date()).toISOString());
18355
+ this.recordHistoryEvent("gemini-turn-complete", { stopReason: isRecord2(response) ? response.stopReason : void 0 });
18356
+ };
18357
+ let current = request;
18358
+ let afterLimit = false;
18359
+ const failedLogins = [];
18360
+ try {
18361
+ for (; ; ) {
18362
+ try {
18363
+ await dispatch(current);
18364
+ return;
18365
+ } catch (error) {
18366
+ if (signal.aborted) return;
18367
+ const message = error instanceof Error ? error.message : String(error);
18368
+ const quotaKind = error instanceof GeminiQuotaError ? detectAgentQuotaLimit(message) ?? "rate_limit" : null;
18369
+ if (!quotaKind && !GEMINI_LOGIN_REJECTED.test(message)) {
18370
+ this.recordHistoryEvent("gemini-error", { message });
18371
+ throw error;
18372
+ }
18373
+ const attempted = ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS.gemini;
18374
+ const repeated = !!attempted && failedLogins.some((failed) => isSameCredential(failed, attempted));
18375
+ if (attempted) failedLogins.push(attempted);
18376
+ const fallback = repeated ? { outcome: "unavailable" } : await this.fallBackCredential(quotaKind ?? "auth_failed", message, attempted, void 0, afterLimit);
18377
+ if (fallback.outcome === "switched") {
18378
+ afterLimit ||= !!quotaKind;
18379
+ if (fallback.model) current = { ...current, model: fallback.model };
18380
+ this.stopProcess();
18381
+ continue;
18382
+ }
18383
+ this.recordHistoryEvent("gemini-error", { message });
18384
+ if (fallback.outcome === "fork") {
18385
+ this.emitQuotaExhausted({ provider: "gemini", reason: quotaKind ?? "auth_failed", detail: message, forkTo: fallback.target });
18386
+ return;
18387
+ }
18388
+ if (quotaKind) return;
18389
+ throw error;
18390
+ }
18391
+ }
18392
+ } finally {
18393
+ this.activePrompt = null;
18394
+ this.turnError = null;
18395
+ this.abortPendingQuestions();
18396
+ try {
18397
+ await this.historyFile.flush();
18398
+ } finally {
18399
+ await this.onTurnComplete();
18400
+ }
18401
+ }
18402
+ }
18403
+ async interruptActiveTurn() {
18404
+ this.abortPendingQuestions();
18405
+ if (!this.activePrompt) this.stopProcess();
18406
+ else if (this.client && this.sessionId) this.client.notify("session/cancel", { sessionId: this.sessionId });
18407
+ }
18408
+ async getHistory(page2 = {}) {
18409
+ await this.historyFile.flush();
18410
+ return { thread_id: this.sessionId, ...await this.historyFile.loadEventsPage(page2), goal: null };
18411
+ }
18412
+ async listSlashCommands() {
18413
+ return mergeSlashCommands(this.slashCommands, await getInstalledSkillsAsSlashCommands(ENGINE_ENV.HOME_DIR, "gemini"));
18414
+ }
18415
+ dispose() {
18416
+ this.stopProcess();
18417
+ }
18418
+ };
18419
+
18218
18420
  // src/managers/opencode-manager.ts
18219
18421
  import { existsSync as existsSync8 } from "fs";
18220
- import { copyFile, mkdir as mkdir10, readFile as readFile10, rm as rm4 } from "fs/promises";
18221
- import { delimiter, dirname as dirname5, join as join15 } from "path";
18422
+ import { copyFile, mkdir as mkdir10, readFile as readFile11, rm as rm4 } from "fs/promises";
18423
+ import { delimiter, dirname as dirname5, join as join16 } from "path";
18222
18424
  import { randomBytes as randomBytes2 } from "crypto";
18223
18425
  import { fileURLToPath as fileURLToPath2 } from "url";
18224
18426
  import { Agent } from "undici";
@@ -18246,10 +18448,10 @@ async function getAllowedOpenRouterModels() {
18246
18448
 
18247
18449
  // src/managers/opencode-manager.ts
18248
18450
  var OPENCODE_SHIM_DIR = dirname5(fileURLToPath2(new URL("../../scripts/opencode", import.meta.url)));
18249
- var OPENCODE_COMMAND_PROTECTION_PLUGIN_SOURCE = join15(OPENCODE_SHIM_DIR, "opencode-command-protection-plugin.ts");
18250
- var OPENCODE_COMMAND_PROTECTION_PLUGIN_PATH = join15(ENGINE_ENV.HOME_DIR, ".config", "opencode", "plugins", "replicas-command-protection.ts");
18251
- var OPENCODE_LEGACY_COMMAND_PROTECTION_PLUGIN_PATH = join15(ENGINE_ENV.HOME_DIR, ".config", "opencode", "plugins", "replicas-command-protection.mjs");
18252
- var OPENCODE_CONFIG_PATH = join15(ENGINE_ENV.HOME_DIR, ".config", "opencode", "opencode.json");
18451
+ var OPENCODE_COMMAND_PROTECTION_PLUGIN_SOURCE = join16(OPENCODE_SHIM_DIR, "opencode-command-protection-plugin.ts");
18452
+ var OPENCODE_COMMAND_PROTECTION_PLUGIN_PATH = join16(ENGINE_ENV.HOME_DIR, ".config", "opencode", "plugins", "replicas-command-protection.ts");
18453
+ var OPENCODE_LEGACY_COMMAND_PROTECTION_PLUGIN_PATH = join16(ENGINE_ENV.HOME_DIR, ".config", "opencode", "plugins", "replicas-command-protection.mjs");
18454
+ var OPENCODE_CONFIG_PATH = join16(ENGINE_ENV.HOME_DIR, ".config", "opencode", "opencode.json");
18253
18455
  var OPENCODE_SERVER_STARTUP_TIMEOUT_MS = 3e4;
18254
18456
  var OPENCODE_SLASH_COMMANDS_CACHE_MS = 3e4;
18255
18457
  var OPENCODE_HEARTBEAT_TIMEOUT_MS = 6e4;
@@ -18317,7 +18519,7 @@ function isOpencodeMcpEntry(value) {
18317
18519
  async function readProvisionedOpencodeMcpConfig() {
18318
18520
  let raw;
18319
18521
  try {
18320
- raw = await readFile10(OPENCODE_CONFIG_PATH, "utf8");
18522
+ raw = await readFile11(OPENCODE_CONFIG_PATH, "utf8");
18321
18523
  } catch (error) {
18322
18524
  if (isRecord(error) && error.code === "ENOENT") return void 0;
18323
18525
  console.error("[OpencodeManager] Failed to read Opencode config:", error);
@@ -18595,6 +18797,9 @@ var OpencodeManager = class extends CodingAgentManager {
18595
18797
  finishUpdate();
18596
18798
  }
18597
18799
  }
18800
+ dispose() {
18801
+ this.stopServer();
18802
+ }
18598
18803
  stopServer() {
18599
18804
  this.eventAbortController?.abort();
18600
18805
  this.server?.close();
@@ -18615,7 +18820,7 @@ var OpencodeManager = class extends CodingAgentManager {
18615
18820
  });
18616
18821
  turn.abort();
18617
18822
  }
18618
- async ensureSession(client, providerID, model, agent, variant) {
18823
+ async ensureSession(client, providerID, model, variant) {
18619
18824
  if (this.sessionId) {
18620
18825
  try {
18621
18826
  await client.session.get(
@@ -18629,7 +18834,7 @@ var OpencodeManager = class extends CodingAgentManager {
18629
18834
  }
18630
18835
  const result = await client.session.create({
18631
18836
  directory: this.workingDirectory,
18632
- agent,
18837
+ agent: "build",
18633
18838
  model: { providerID, id: model, ...variant ? { variant } : {} }
18634
18839
  }, { throwOnError: true });
18635
18840
  const session = result.data;
@@ -18684,9 +18889,8 @@ var OpencodeManager = class extends CodingAgentManager {
18684
18889
  const client = await this.ensureClient(model, provider);
18685
18890
  server3 = this.server;
18686
18891
  const { providerID, modelID } = opencodeModelRef(this.providerId, model);
18687
- const agent = request.planMode ? "plan" : "build";
18688
18892
  const variant = await this.getThinkingVariant(client, providerID, modelID, request.thinkingLevel);
18689
- const sessionId = await this.ensureSession(client, providerID, modelID, agent, variant);
18893
+ const sessionId = await this.ensureSession(client, providerID, modelID, variant);
18690
18894
  const system = this.buildCombinedInstructions(request.customInstructions);
18691
18895
  if (!retry) {
18692
18896
  if (!this.deliver(signal)) return false;
@@ -18695,7 +18899,7 @@ var OpencodeManager = class extends CodingAgentManager {
18695
18899
  const result = await client.session.prompt({
18696
18900
  sessionID: sessionId,
18697
18901
  directory: this.workingDirectory,
18698
- agent,
18902
+ agent: "build",
18699
18903
  model: { providerID, modelID },
18700
18904
  ...variant ? { variant } : {},
18701
18905
  ...system ? { system } : {},
@@ -18951,7 +19155,7 @@ var OpencodeManager = class extends CodingAgentManager {
18951
19155
  };
18952
19156
 
18953
19157
  // src/managers/pi-manager.ts
18954
- import { join as join22 } from "path";
19158
+ import { join as join23 } from "path";
18955
19159
  import {
18956
19160
  createAgentSession,
18957
19161
  ModelRegistry,
@@ -41776,7 +41980,7 @@ async function probeMcpEndpoint(url3) {
41776
41980
 
41777
41981
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+f2da34192be1730e/node_modules/pi-mcp-adapter/npx-resolver.ts
41778
41982
  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";
41779
- import { join as join16, dirname as dirname6, extname as extname2, resolve as resolve2, sep } from "path";
41983
+ import { join as join17, dirname as dirname6, extname as extname2, resolve as resolve2, sep } from "path";
41780
41984
 
41781
41985
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+f2da34192be1730e/node_modules/pi-mcp-adapter/abort.ts
41782
41986
  function throwIfAborted(signal) {
@@ -41933,7 +42137,7 @@ function resolveFromNpmCache(packageSpec, binName) {
41933
42137
  const { packageName, exactVersion } = parsedSpec;
41934
42138
  const packageDir = findCachedPackageDir(cacheDir, packageName, exactVersion);
41935
42139
  if (!packageDir) return null;
41936
- const packageJsonPath = join16(packageDir, "package.json");
42140
+ const packageJsonPath = join17(packageDir, "package.json");
41937
42141
  if (!existsSync9(packageJsonPath)) return null;
41938
42142
  let pkg = null;
41939
42143
  try {
@@ -41967,7 +42171,7 @@ function resolveFromNpmCache(packageSpec, binName) {
41967
42171
  }
41968
42172
  if (!binRel) return null;
41969
42173
  const nodeModulesDir = findNodeModulesDir(packageDir);
41970
- const binLink = chosenBinName ? join16(nodeModulesDir, ".bin", chosenBinName) : null;
42174
+ const binLink = chosenBinName ? join17(nodeModulesDir, ".bin", chosenBinName) : null;
41971
42175
  let resolvedBin = binLink && existsSync9(binLink) ? safeRealpath(binLink) : "";
41972
42176
  if (!resolvedBin) {
41973
42177
  resolvedBin = resolve2(packageDir, binRel);
@@ -42069,17 +42273,17 @@ function defaultBinName(packageName) {
42069
42273
  return packageName;
42070
42274
  }
42071
42275
  function findCachedPackageDir(cacheDir, packageName, exactVersion) {
42072
- const npxDir = join16(cacheDir, "_npx");
42276
+ const npxDir = join17(cacheDir, "_npx");
42073
42277
  if (!existsSync9(npxDir)) return null;
42074
42278
  const packagePathParts = packageName.startsWith("@") ? packageName.split("/") : [packageName];
42075
42279
  const candidates = readdirSync2(npxDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => {
42076
- const full = join16(npxDir, entry.name);
42280
+ const full = join17(npxDir, entry.name);
42077
42281
  const mtime = safeStatMtime(full);
42078
42282
  return { name: entry.name, mtime };
42079
42283
  }).sort((a, b) => b.mtime - a.mtime);
42080
42284
  for (const entry of candidates) {
42081
- const pkgDir = join16(npxDir, entry.name, "node_modules", ...packagePathParts);
42082
- const packageJsonPath = join16(pkgDir, "package.json");
42285
+ const pkgDir = join17(npxDir, entry.name, "node_modules", ...packagePathParts);
42286
+ const packageJsonPath = join17(pkgDir, "package.json");
42083
42287
  if (!existsSync9(packageJsonPath)) continue;
42084
42288
  if (exactVersion) {
42085
42289
  try {
@@ -42099,7 +42303,7 @@ function findNodeModulesDir(packageDir) {
42099
42303
  if (idx >= 0) {
42100
42304
  return parts.slice(0, idx + 1).join(sep);
42101
42305
  }
42102
- return join16(packageDir, "..");
42306
+ return join17(packageDir, "..");
42103
42307
  }
42104
42308
  function detectJsBinary(binPath) {
42105
42309
  const ext = extname2(binPath).toLowerCase();
@@ -42291,7 +42495,7 @@ import { spawnSync } from "child_process";
42291
42495
  import { createHash as createHash3 } from "crypto";
42292
42496
  import { createRequire } from "module";
42293
42497
  import { readFileSync as readFileSync3, existsSync as existsSync10, rmSync as rmSync2 } from "fs";
42294
- import { dirname as dirname7, join as join17 } from "path";
42498
+ import { dirname as dirname7, join as join18 } from "path";
42295
42499
  import { fileURLToPath as fileURLToPath3 } from "url";
42296
42500
  var require2 = createRequire(import.meta.url);
42297
42501
  var AUTH_SECRET_SERVICE = "pi-mcp-adapter.oauth";
@@ -42447,7 +42651,7 @@ function loadKeyringNativeBindingFallback(keyringRequire, platform4, arch3) {
42447
42651
  for (const target of targets) {
42448
42652
  try {
42449
42653
  const packageJsonPath = keyringRequire.resolve(`${target.packageName}/package.json`);
42450
- return keyringRequire(join17(dirname7(packageJsonPath), target.bindingFile));
42654
+ return keyringRequire(join18(dirname7(packageJsonPath), target.bindingFile));
42451
42655
  } catch (error) {
42452
42656
  lastError = error;
42453
42657
  }
@@ -42552,7 +42756,7 @@ function getServerDir(serverName, options) {
42552
42756
  throw new Error(`Invalid MCP server name: ${JSON.stringify(serverName)}`);
42553
42757
  }
42554
42758
  const storageKey = getAuthEntryAccount(serverName);
42555
- return join17(getAuthBaseDir(options), storageKey);
42759
+ return join18(getAuthBaseDir(options), storageKey);
42556
42760
  }
42557
42761
  function getAuthEntryAccount(serverName) {
42558
42762
  if (typeof serverName !== "string") {
@@ -42561,7 +42765,7 @@ function getAuthEntryAccount(serverName) {
42561
42765
  return `sha256-${createHash3("sha256").update(serverName, "utf8").digest("hex")}`;
42562
42766
  }
42563
42767
  function getAuthEntryFilePath(serverName, options) {
42564
- return join17(getServerDir(serverName, options), "tokens.json");
42768
+ return join18(getServerDir(serverName, options), "tokens.json");
42565
42769
  }
42566
42770
  function parseJsonPayload(serverName, payload, source) {
42567
42771
  try {
@@ -45164,7 +45368,7 @@ async function shutdownOAuth(runtime = legacyRuntime) {
45164
45368
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+f2da34192be1730e/node_modules/pi-mcp-adapter/mcp-bearer-store.ts
45165
45369
  import { createHash as createHash4 } from "crypto";
45166
45370
  import { createRequire as createRequire2 } from "module";
45167
- import { dirname as dirname8, join as join18 } from "path";
45371
+ import { dirname as dirname8, join as join19 } from "path";
45168
45372
  var require3 = createRequire2(import.meta.url);
45169
45373
  var BEARER_SECRET_SERVICE = "pi-mcp-adapter.bearer";
45170
45374
  var TEST_AUTH_STORE_ENV2 = "PI_MCP_ADAPTER_TEST_AUTH_STORE";
@@ -45266,7 +45470,7 @@ function loadKeyringNativeBindingFallback2(keyringRequire, platform4, arch3) {
45266
45470
  for (const target of targets) {
45267
45471
  try {
45268
45472
  const packageJsonPath = keyringRequire.resolve(`${target.packageName}/package.json`);
45269
- return keyringRequire(join18(dirname8(packageJsonPath), target.bindingFile));
45473
+ return keyringRequire(join19(dirname8(packageJsonPath), target.bindingFile));
45270
45474
  } catch (error) {
45271
45475
  lastError = error;
45272
45476
  }
@@ -49733,7 +49937,7 @@ async function openMcpAuthPanel(state, pi, ctx, configOverridePath) {
49733
49937
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+f2da34192be1730e/node_modules/pi-mcp-adapter/tool-registrar.ts
49734
49938
  import { mkdtempSync, rmSync as rmSync3, writeFileSync as writeFileSync5 } from "fs";
49735
49939
  import { tmpdir } from "os";
49736
- import { join as join19 } from "path";
49940
+ import { join as join20 } from "path";
49737
49941
  var MAX_BINARY_RESOURCE_BYTES = 10 * 1024 * 1024;
49738
49942
  var MAX_SESSION_RESOURCE_BYTES = 100 * 1024 * 1024;
49739
49943
  var MAX_SESSION_RESOURCE_FILES = 1e4;
@@ -49840,11 +50044,11 @@ function materializeBinaryResource(resource, scope) {
49840
50044
  return omitBinaryResource(resource, "session resource limit reached");
49841
50045
  }
49842
50046
  try {
49843
- session.directory ??= mkdtempSync(join19(tmpdir(), "pi-mcp-resource-"));
50047
+ session.directory ??= mkdtempSync(join20(tmpdir(), "pi-mcp-resource-"));
49844
50048
  } catch {
49845
50049
  return omitBinaryResource(resource, "could not be saved");
49846
50050
  }
49847
- const filePath = join19(session.directory, `resource-${++session.sequence}.bin`);
50051
+ const filePath = join20(session.directory, `resource-${++session.sequence}.bin`);
49848
50052
  session.bytes += decodedBytes;
49849
50053
  session.files += 1;
49850
50054
  try {
@@ -49937,7 +50141,7 @@ function stringifyStructuredContent(value) {
49937
50141
  import { randomBytes as randomBytes3 } from "crypto";
49938
50142
  import { mkdtemp, rm as rm5, writeFile as writeFile7 } from "fs/promises";
49939
50143
  import { tmpdir as tmpdir2 } from "os";
49940
- import { dirname as dirname11, join as join20 } from "path";
50144
+ import { dirname as dirname11, join as join21 } from "path";
49941
50145
  var DEFAULT_MCP_OUTPUT_MAX_BYTES = 50 * 1024;
49942
50146
  var DEFAULT_MCP_OUTPUT_MAX_LINES = 2e3;
49943
50147
  var DEFAULT_MCP_DETAILS_MAX_BYTES = 16 * 1024;
@@ -50245,8 +50449,8 @@ function serializedObjectEntryBytes(key, value, hasPrevious) {
50245
50449
  }
50246
50450
  async function saveArtifact(kind, text) {
50247
50451
  try {
50248
- const dir = await mkdtemp(join20(tmpdir2(), "pi-mcp-output-"));
50249
- const path8 = join20(dir, `${kind}-${randomBytes3(4).toString("hex")}.txt`);
50452
+ const dir = await mkdtemp(join21(tmpdir2(), "pi-mcp-output-"));
50453
+ const path8 = join21(dir, `${kind}-${randomBytes3(4).toString("hex")}.txt`);
50250
50454
  await writeFile7(path8, text, { encoding: "utf8", mode: 384 });
50251
50455
  return { path: path8 };
50252
50456
  } catch (error) {
@@ -51893,7 +52097,7 @@ function sendText(res, status, text) {
51893
52097
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+f2da34192be1730e/node_modules/pi-mcp-adapter/glimpse-ui.ts
51894
52098
  import { existsSync as existsSync13 } from "fs";
51895
52099
  import { execFileSync as execFileSync2 } from "child_process";
51896
- import { join as join21, dirname as dirname12 } from "path";
52100
+ import { join as join22, dirname as dirname12 } from "path";
51897
52101
  import { platform as platform2 } from "os";
51898
52102
  import { createRequire as createRequire3 } from "module";
51899
52103
  var glimpseAvailable = null;
@@ -51915,20 +52119,20 @@ function getGlimpseBinaryPath() {
51915
52119
  try {
51916
52120
  const require6 = createRequire3(import.meta.url);
51917
52121
  const glimpseuiPath = require6.resolve("glimpseui");
51918
- const binaryPath = join21(dirname12(glimpseuiPath), "glimpse");
52122
+ const binaryPath = join22(dirname12(glimpseuiPath), "glimpse");
51919
52123
  if (existsSync13(binaryPath)) return binaryPath;
51920
52124
  } catch {
51921
52125
  }
51922
52126
  try {
51923
52127
  const globalRoot = execFileSync2("npm", ["root", "-g"], { encoding: "utf-8" }).trim();
51924
- const binaryPath = join21(globalRoot, "glimpseui", "src", "glimpse");
52128
+ const binaryPath = join22(globalRoot, "glimpseui", "src", "glimpse");
51925
52129
  if (existsSync13(binaryPath)) return binaryPath;
51926
52130
  } catch {
51927
52131
  }
51928
52132
  return null;
51929
52133
  }
51930
52134
  async function openGlimpseWindow(html, options) {
51931
- const modulePath = resolvedBinaryPath ? join21(dirname12(resolvedBinaryPath), "glimpse.mjs") : "glimpseui";
52135
+ const modulePath = resolvedBinaryPath ? join22(dirname12(resolvedBinaryPath), "glimpse.mjs") : "glimpseui";
51932
52136
  const glimpse = await import(modulePath);
51933
52137
  let active = true;
51934
52138
  const win = glimpse.open(html, {
@@ -59856,6 +60060,8 @@ var PiManager = class extends CodingAgentManager {
59856
60060
  this.unsubscribe = null;
59857
60061
  const session = this.session;
59858
60062
  this.session = null;
60063
+ this.modelRuntime = null;
60064
+ this.providerApiKey = null;
59859
60065
  if (session) {
59860
60066
  await session.extensionRunner.emit({ type: "session_shutdown", reason: "quit" }).catch(() => {
59861
60067
  });
@@ -59998,7 +60204,7 @@ var PiManager = class extends CodingAgentManager {
59998
60204
  }
59999
60205
  const resourceLoader = new DefaultResourceLoader({
60000
60206
  cwd: this.workingDirectory,
60001
- agentDir: join22(ENGINE_ENV.HOME_DIR, ".pi", "agent"),
60207
+ agentDir: join23(ENGINE_ENV.HOME_DIR, ".pi", "agent"),
60002
60208
  extensionFactories,
60003
60209
  appendSystemPrompt: [instructions]
60004
60210
  });
@@ -60019,6 +60225,7 @@ var PiManager = class extends CodingAgentManager {
60019
60225
  this.activeSessionFile = sessionManager.getSessionFile() ?? null;
60020
60226
  await this.onSaveSessionId(this.activeSessionFile);
60021
60227
  this.unsubscribe = this.session.subscribe((event) => this.handleEvent(event));
60228
+ await this.session.bindExtensions({});
60022
60229
  return this.session;
60023
60230
  }
60024
60231
  async getModelRuntime() {
@@ -60056,10 +60263,10 @@ var PiManager = class extends CodingAgentManager {
60056
60263
  };
60057
60264
 
60058
60265
  // src/services/chat/chat-commands.ts
60059
- import { mkdir as mkdir12, readFile as readFile11, rm as rm6 } from "fs/promises";
60060
- import { join as join23 } from "path";
60266
+ import { mkdir as mkdir12, readFile as readFile12, rm as rm6 } from "fs/promises";
60267
+ import { join as join24 } from "path";
60061
60268
  import { z as z3 } from "zod";
60062
- var CHAT_COMMANDS_DIR = join23(ENGINE_DIR, "chat-commands");
60269
+ var CHAT_COMMANDS_DIR = join24(ENGINE_DIR, "chat-commands");
60063
60270
  var ACCEPTED_RETENTION_MS = 8 * 24 * 60 * 6e4;
60064
60271
  var MAX_REMOVED_MESSAGE_IDS = 6e3;
60065
60272
  var queuedMessageSchema = sendChatMessageRequestSchema.extend({ id: z3.string(), queuedAt: z3.string() });
@@ -60088,7 +60295,7 @@ var ChatCommands = class _ChatCommands {
60088
60295
  state;
60089
60296
  writing = Promise.resolve();
60090
60297
  static async load(chatId) {
60091
- const content = await readFile11(join23(CHAT_COMMANDS_DIR, `${chatId}.json`), "utf-8").catch((error) => {
60298
+ const content = await readFile12(join24(CHAT_COMMANDS_DIR, `${chatId}.json`), "utf-8").catch((error) => {
60092
60299
  if (error.code === "ENOENT") return null;
60093
60300
  throw error;
60094
60301
  });
@@ -60118,13 +60325,13 @@ var ChatCommands = class _ChatCommands {
60118
60325
  this.writing = this.writing.catch(() => {
60119
60326
  }).then(async () => {
60120
60327
  await mkdir12(CHAT_COMMANDS_DIR, { recursive: true, mode: 448 });
60121
- await atomicWriteFile(join23(CHAT_COMMANDS_DIR, `${this.chatId}.json`), data, { mode: 384, flush: true });
60328
+ await atomicWriteFile(join24(CHAT_COMMANDS_DIR, `${this.chatId}.json`), data, { mode: 384, flush: true });
60122
60329
  });
60123
60330
  return this.writing;
60124
60331
  }
60125
60332
  remove() {
60126
60333
  this.writing = this.writing.catch(() => {
60127
- }).then(() => rm6(join23(CHAT_COMMANDS_DIR, `${this.chatId}.json`), { force: true }));
60334
+ }).then(() => rm6(join24(CHAT_COMMANDS_DIR, `${this.chatId}.json`), { force: true }));
60128
60335
  return this.writing;
60129
60336
  }
60130
60337
  };
@@ -60144,13 +60351,13 @@ async function uploadAnalytics(endpoint, body) {
60144
60351
  import {
60145
60352
  appendFile as appendFile3,
60146
60353
  mkdir as mkdir13,
60147
- readFile as readFile12,
60148
- readdir as readdir6,
60354
+ readFile as readFile13,
60355
+ readdir as readdir7,
60149
60356
  rename as rename2,
60150
60357
  unlink
60151
60358
  } from "fs/promises";
60152
60359
  import { existsSync as existsSync14, readFileSync as readFileSync5, readdirSync as readdirSync3 } from "fs";
60153
- import { join as join24 } from "path";
60360
+ import { join as join25 } from "path";
60154
60361
  var MAX_FAILED_RECORDS = 500;
60155
60362
  var FLUSH_DEBOUNCE_MS = 15e3;
60156
60363
  var MAX_UPLOADED_SEGMENTS = 50;
@@ -60162,7 +60369,7 @@ var AnalyticsRecordBuffer = class {
60162
60369
  options.storageName,
60163
60370
  ...options.legacyStorageNames ?? []
60164
60371
  ];
60165
- this.liveFile = join24(ENGINE_DIR, `${options.storageName}.jsonl`);
60372
+ this.liveFile = join25(ENGINE_DIR, `${options.storageName}.jsonl`);
60166
60373
  this.segmentFilePatterns = this.storageNames.map(
60167
60374
  (storageName) => new RegExp(`^${storageName}\\.(\\d+)\\.jsonl$`)
60168
60375
  );
@@ -60200,7 +60407,7 @@ var AnalyticsRecordBuffer = class {
60200
60407
  if (!existsSync14(ENGINE_DIR)) return [];
60201
60408
  return readdirSync3(ENGINE_DIR, { withFileTypes: true }).filter((entry) => entry.isFile() && this.storageNames.some(
60202
60409
  (storageName) => entry.name === `${storageName}.jsonl` || entry.name.startsWith(`${storageName}.`) && (entry.name.endsWith(".jsonl") || entry.name.endsWith(`.jsonl${UPLOADED_SUFFIX}`))
60203
- )).map(({ name }) => name).sort().flatMap((name) => this.parseRecords(readFileSync5(join24(ENGINE_DIR, name), "utf-8"))).map((record3) => {
60410
+ )).map(({ name }) => name).sort().flatMap((name) => this.parseRecords(readFileSync5(join25(ENGINE_DIR, name), "utf-8"))).map((record3) => {
60204
60411
  const recordId = this.options.getRecordId?.(record3);
60205
60412
  if (recordId) this.recordIds.add(recordId);
60206
60413
  return record3;
@@ -60235,18 +60442,18 @@ var AnalyticsRecordBuffer = class {
60235
60442
  }
60236
60443
  for (const storageName of this.storageNames) {
60237
60444
  await rename2(
60238
- join24(ENGINE_DIR, `${storageName}.jsonl`),
60239
- join24(ENGINE_DIR, `${storageName}.${Date.now()}.jsonl`)
60445
+ join25(ENGINE_DIR, `${storageName}.jsonl`),
60446
+ join25(ENGINE_DIR, `${storageName}.${Date.now()}.jsonl`)
60240
60447
  ).catch(() => {
60241
60448
  });
60242
60449
  }
60243
- const entries = await readdir6(ENGINE_DIR).catch(() => []);
60450
+ const entries = await readdir7(ENGINE_DIR).catch(() => []);
60244
60451
  let flushed = 0;
60245
60452
  let failed = 0;
60246
60453
  for (const entry of entries) {
60247
60454
  if (!this.segmentFilePatterns.some((pattern) => pattern.test(entry))) continue;
60248
60455
  try {
60249
- await this.uploadSegment(join24(ENGINE_DIR, entry));
60456
+ await this.uploadSegment(join25(ENGINE_DIR, entry));
60250
60457
  flushed++;
60251
60458
  } catch (error) {
60252
60459
  failed++;
@@ -60275,14 +60482,14 @@ var AnalyticsRecordBuffer = class {
60275
60482
  (storageName) => entry.startsWith(`${storageName}.`)
60276
60483
  ) && entry.endsWith(UPLOADED_SUFFIX)).sort();
60277
60484
  for (const entry of uploaded.slice(0, -MAX_UPLOADED_SEGMENTS)) {
60278
- await unlink(join24(ENGINE_DIR, entry)).catch(() => {
60485
+ await unlink(join25(ENGINE_DIR, entry)).catch(() => {
60279
60486
  });
60280
60487
  }
60281
60488
  }
60282
60489
  return { flushed, failed };
60283
60490
  }
60284
60491
  async uploadSegment(filePath) {
60285
- const records = this.parseRecords(await readFile12(filePath, "utf-8"));
60492
+ const records = this.parseRecords(await readFile13(filePath, "utf-8"));
60286
60493
  if (records.length > 0) await this.options.upload(records);
60287
60494
  await rename2(filePath, `${filePath}${UPLOADED_SUFFIX}`).catch(() => {
60288
60495
  });
@@ -60300,7 +60507,7 @@ var AnalyticsRecordBuffer = class {
60300
60507
  };
60301
60508
 
60302
60509
  // src/analytics/agent/activity/skill-mcp-call-extractor.ts
60303
- var NON_MCP_SERVERS = /* @__PURE__ */ new Set(["claude", "cursor", "muse", "opencode", "pi", "custom", "dynamic"]);
60510
+ var NON_MCP_SERVERS = /* @__PURE__ */ new Set(["claude", "cursor", "gemini", "muse", "opencode", "pi", "custom", "dynamic"]);
60304
60511
  function mcpNameFromToolCall(message) {
60305
60512
  const parsedName = parseMcpToolName(message.tool);
60306
60513
  if (parsedName) return parsedName.server;
@@ -60861,6 +61068,21 @@ var CursorTokenUsageService = class {
60861
61068
  }
60862
61069
  };
60863
61070
 
61071
+ // src/analytics/token-usage/gemini/index.ts
61072
+ var GeminiTokenUsageService = class {
61073
+ record(event) {
61074
+ return recordParsedTokenUsage(event, AGENT.GEMINI, (usage) => {
61075
+ if (!isRecord2(usage) || typeof usage.inputTokens !== "number" || typeof usage.outputTokens !== "number") return void 0;
61076
+ return {
61077
+ inputTokens: usage.inputTokens,
61078
+ outputTokens: usage.outputTokens + (typeof usage.thoughtTokens === "number" ? usage.thoughtTokens : 0),
61079
+ cacheReadInputTokens: typeof usage.cachedReadTokens === "number" ? usage.cachedReadTokens : 0,
61080
+ cacheWriteInputTokens: typeof usage.cachedWriteTokens === "number" ? usage.cachedWriteTokens : 0
61081
+ };
61082
+ });
61083
+ }
61084
+ };
61085
+
60864
61086
  // src/analytics/token-usage/muse/index.ts
60865
61087
  var MuseTokenUsageService = class {
60866
61088
  record(event) {
@@ -60938,6 +61160,8 @@ function createAgentTokenUsageService(harness) {
60938
61160
  return new CodexTokenUsageService();
60939
61161
  case AGENT.CURSOR:
60940
61162
  return new CursorTokenUsageService();
61163
+ case AGENT.GEMINI:
61164
+ return new GeminiTokenUsageService();
60941
61165
  case AGENT.MUSE:
60942
61166
  return new MuseTokenUsageService();
60943
61167
  case AGENT.OPENCODE:
@@ -61103,9 +61327,9 @@ var KeepAliveService = class _KeepAliveService {
61103
61327
  var keepAliveService = new KeepAliveService();
61104
61328
 
61105
61329
  // src/services/canvas-service.ts
61106
- import { readdir as readdir7, readFile as readFile14, stat as stat3 } from "fs/promises";
61330
+ import { readdir as readdir8, readFile as readFile15, stat as stat3 } from "fs/promises";
61107
61331
  import { homedir as homedir7 } from "os";
61108
- import { join as join25 } from "path";
61332
+ import { join as join26 } from "path";
61109
61333
 
61110
61334
  // src/utils/contained-file.ts
61111
61335
  import { realpath, stat as stat2 } from "fs/promises";
@@ -61131,9 +61355,9 @@ function fileRevision(content) {
61131
61355
  }
61132
61356
 
61133
61357
  // src/utils/revisioned-text-file.ts
61134
- import { readFile as readFile13 } from "fs/promises";
61358
+ import { readFile as readFile14 } from "fs/promises";
61135
61359
  async function writeRevisionedTextFile(filePath, content, expectedRevision) {
61136
- const current = await readFile13(filePath, "utf8");
61360
+ const current = await readFile14(filePath, "utf8");
61137
61361
  const revision = fileRevision(current);
61138
61362
  if (revision !== expectedRevision) {
61139
61363
  return {
@@ -61147,15 +61371,15 @@ async function writeRevisionedTextFile(filePath, content, expectedRevision) {
61147
61371
 
61148
61372
  // src/services/canvas-service.ts
61149
61373
  var GLOBAL_CANVAS_DIRECTORIES = [
61150
- join25(homedir7(), ".claude", "plans"),
61151
- join25(process.env.XDG_DATA_HOME ?? join25(homedir7(), ".local", "share"), "opencode", "plans"),
61152
- join25(homedir7(), ".replicas", "canvas")
61374
+ join26(homedir7(), ".claude", "plans"),
61375
+ join26(process.env.XDG_DATA_HOME ?? join26(homedir7(), ".local", "share"), "opencode", "plans"),
61376
+ join26(homedir7(), ".replicas", "canvas")
61153
61377
  ];
61154
61378
  async function canvasDirectories(repositories) {
61155
61379
  repositories ??= await gitService.listRepositories().catch(() => []);
61156
61380
  return [
61157
61381
  ...GLOBAL_CANVAS_DIRECTORIES,
61158
- ...repositories.map((repository) => join25(repository.path, ".opencode", "plans"))
61382
+ ...repositories.map((repository) => join26(repository.path, ".opencode", "plans"))
61159
61383
  ];
61160
61384
  }
61161
61385
  var CanvasService = class {
@@ -61173,14 +61397,14 @@ var CanvasService = class {
61173
61397
  if (!current) continue;
61174
61398
  let entries;
61175
61399
  try {
61176
- entries = await readdir7(current.directory, { withFileTypes: true });
61400
+ entries = await readdir8(current.directory, { withFileTypes: true });
61177
61401
  } catch {
61178
61402
  continue;
61179
61403
  }
61180
61404
  for (const entry of entries) {
61181
61405
  if (entry.name.startsWith(".")) continue;
61182
61406
  const filename = current.relativePath ? `${current.relativePath}/${entry.name}` : entry.name;
61183
- const filePath = join25(current.directory, entry.name);
61407
+ const filePath = join26(current.directory, entry.name);
61184
61408
  if (entry.isDirectory()) {
61185
61409
  pending.push({ directory: filePath, relativePath: filename });
61186
61410
  continue;
@@ -61204,7 +61428,7 @@ var CanvasService = class {
61204
61428
  const safe = sanitizeCanvasFilename(filename);
61205
61429
  if (!safe) return null;
61206
61430
  for (const directory of await this.directories()) {
61207
- const path8 = join25(directory, safe);
61431
+ const path8 = join26(directory, safe);
61208
61432
  const stats = await stat3(path8).catch(() => null);
61209
61433
  if (stats?.isFile()) {
61210
61434
  return {
@@ -61223,7 +61447,7 @@ var CanvasService = class {
61223
61447
  if (!item) return null;
61224
61448
  const { path: path8, ...file } = item;
61225
61449
  if (file.sizeBytes > maxBytes) return { ...file, tooLarge: true };
61226
- const bytes = await readFile14(path8).catch(() => null);
61450
+ const bytes = await readFile15(path8).catch(() => null);
61227
61451
  return bytes ? { ...file, bytes } : null;
61228
61452
  }
61229
61453
  async getItem(filename) {
@@ -61363,15 +61587,15 @@ async function reconcileCanvasItems(filenames) {
61363
61587
 
61364
61588
  // src/services/upload-chat-transcripts.ts
61365
61589
  import { createHash as createHash8 } from "crypto";
61366
- import { readFile as readFile15, readdir as readdir8 } from "fs/promises";
61590
+ import { readFile as readFile16, readdir as readdir9 } from "fs/promises";
61367
61591
  import { Readable } from "stream";
61368
- import { basename as basename3, join as join27 } from "path";
61592
+ import { basename as basename3, join as join28 } from "path";
61369
61593
 
61370
61594
  // src/services/chat/chat-senders.ts
61371
- import { join as join26 } from "path";
61372
- var CHAT_SENDERS_DIR = join26(ENGINE_DIR, "chat-senders");
61595
+ import { join as join27 } from "path";
61596
+ var CHAT_SENDERS_DIR = join27(ENGINE_DIR, "chat-senders");
61373
61597
  function chatMessageSendersFilePath(chatId) {
61374
- return join26(CHAT_SENDERS_DIR, `${chatId}.jsonl`);
61598
+ return join27(CHAT_SENDERS_DIR, `${chatId}.jsonl`);
61375
61599
  }
61376
61600
  function parseChatMessageSendersJsonl(content) {
61377
61601
  return content.split("\n").flatMap((line) => {
@@ -61447,7 +61671,7 @@ async function flushAllChatTranscripts(chatsById = /* @__PURE__ */ new Map(), ca
61447
61671
  for (const dir of HISTORY_DIRS) {
61448
61672
  let entries;
61449
61673
  try {
61450
- entries = await readdir8(dir);
61674
+ entries = await readdir9(dir);
61451
61675
  } catch {
61452
61676
  continue;
61453
61677
  }
@@ -61457,7 +61681,7 @@ async function flushAllChatTranscripts(chatsById = /* @__PURE__ */ new Map(), ca
61457
61681
  const chat = chatsById.get(chatId);
61458
61682
  if (!shouldFlushChatTranscript(dir, chat, chatsById, Boolean(capture))) continue;
61459
61683
  tasks.push(
61460
- uploadChatTranscript(chatId, join27(dir, entry), chat, capture).then(async (artifact) => {
61684
+ uploadChatTranscript(chatId, join28(dir, entry), chat, capture).then(async (artifact) => {
61461
61685
  flushed++;
61462
61686
  if (artifact && capture) revisions.push(artifact);
61463
61687
  await onUploaded?.(chatId, artifact).catch((err) => {
@@ -61526,7 +61750,7 @@ async function uploadOpenedTranscript(chatId, opened, historyVersion, chat, capt
61526
61750
  } : {};
61527
61751
  try {
61528
61752
  metadata.senders = parseChatMessageSendersJsonl(
61529
- await readFile15(chatMessageSendersFilePath(chatId), "utf-8")
61753
+ await readFile16(chatMessageSendersFilePath(chatId), "utf-8")
61530
61754
  );
61531
61755
  } catch (error) {
61532
61756
  if (!(error && typeof error === "object" && "code" in error && error.code === "ENOENT")) throw error;
@@ -61615,8 +61839,8 @@ async function flushRepoState() {
61615
61839
 
61616
61840
  // src/services/upload-engine-logs.ts
61617
61841
  import { createReadStream } from "fs";
61618
- import { readdir as readdir9, stat as stat4 } from "fs/promises";
61619
- import { join as join28 } from "path";
61842
+ import { readdir as readdir10, stat as stat4 } from "fs/promises";
61843
+ import { join as join29 } from "path";
61620
61844
  var MAX_ENGINE_LOG_FLUSH_SESSIONS = 10;
61621
61845
  var MAX_ENGINE_LOG_FLUSH_BYTES = 5 * 1024 * 1024;
61622
61846
  var ENGINE_LOG_FLUSH_TIMEOUT_MS = 2e4;
@@ -61626,7 +61850,7 @@ async function flushAllEngineLogs() {
61626
61850
  let failed = 0;
61627
61851
  const deadline = Date.now() + ENGINE_LOG_FLUSH_TIMEOUT_MS;
61628
61852
  await runBeforeDeadline((signal) => engineLogger.flush(signal), deadline);
61629
- const files = await runBeforeDeadline(() => readdir9(LOG_DIR), deadline).catch(() => []);
61853
+ const files = await runBeforeDeadline(() => readdir10(LOG_DIR), deadline).catch(() => []);
61630
61854
  const currentFilename = engineLogger.sessionId ? `${engineLogger.sessionId}.log` : null;
61631
61855
  const filenames = files.filter((filename) => {
61632
61856
  if (!filename.endsWith(".log")) return false;
@@ -61645,7 +61869,7 @@ async function flushAllEngineLogs() {
61645
61869
  const candidates = (await Promise.all(filenames.slice(0, MAX_ENGINE_LOG_FLUSH_SESSIONS).map(async (filename) => {
61646
61870
  try {
61647
61871
  const sessionId = filename.slice(0, -".log".length);
61648
- const filePath = join28(LOG_DIR, filename);
61872
+ const filePath = join29(LOG_DIR, filename);
61649
61873
  const fileStat = await runBeforeDeadline(() => stat4(filePath), deadline);
61650
61874
  if (!fileStat.isFile()) {
61651
61875
  skipped++;
@@ -61742,9 +61966,9 @@ async function uploadEngineLog(input, timeoutMs) {
61742
61966
 
61743
61967
  // src/services/chat/fork-handoff.ts
61744
61968
  import { createHash as createHash9 } from "crypto";
61745
- import { mkdir as mkdir14, readFile as readFile16, writeFile as writeFile8 } from "fs/promises";
61969
+ import { mkdir as mkdir14, readFile as readFile17, writeFile as writeFile8 } from "fs/promises";
61746
61970
  import { homedir as homedir8 } from "os";
61747
- import { join as join29 } from "path";
61971
+ import { join as join30 } from "path";
61748
61972
  var EXCERPT_MAX_CHARS = 24e3;
61749
61973
  var CONVERSATION_UPDATE_MAX_CHARS = 8e3;
61750
61974
  var PULL_REQUEST_DECISIONS_MAX_CHARS = 4e3;
@@ -61807,7 +62031,7 @@ ${text}` : null;
61807
62031
  }
61808
62032
  async function buildForkHandoff(input) {
61809
62033
  const sources = await Promise.all(input.segments.map(async (segment, index) => {
61810
- const rawHistoryPath = join29(HISTORY_DIR_BY_PROVIDER[segment.provider], `${segment.chatId}.jsonl`);
62034
+ const rawHistoryPath = join30(HISTORY_DIR_BY_PROVIDER[segment.provider], `${segment.chatId}.jsonl`);
61811
62035
  const { content, truncated: truncated2 } = await readHistoryTail(rawHistoryPath, MAX_SANITIZED_SOURCE_BYTES, segment.openHistory);
61812
62036
  const last = index === input.segments.length - 1;
61813
62037
  const blocks2 = canonicalizeChatTranscriptBlocks(content, segment.provider, segment.senders, last ? input.beforeMessageId : void 0).filter((block) => !block.startsWith("## Agent reasoning"));
@@ -61821,9 +62045,9 @@ async function buildForkHandoff(input) {
61821
62045
  const start = blocks.findLastIndex((block) => block.startsWith("## User") && ++turns === input.turnLimit);
61822
62046
  blocks = blocks.slice(Math.max(0, start));
61823
62047
  }
61824
- const forkDir = join29(FORKS_DIR, input.targetChatId);
62048
+ const forkDir = join30(FORKS_DIR, input.targetChatId);
61825
62049
  await mkdir14(forkDir, { recursive: true });
61826
- const transcriptPath = join29(forkDir, input.transcriptName ?? "source-transcript.md");
62050
+ const transcriptPath = join30(forkDir, input.transcriptName ?? "source-transcript.md");
61827
62051
  const rawHistoryPaths = sources.map((source) => source.rawHistoryPath);
61828
62052
  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.` : ""}_
61829
62053
 
@@ -61842,7 +62066,7 @@ async function buildForkHandoff(input) {
61842
62066
  };
61843
62067
  }
61844
62068
  async function readPullRequestDecisions(notesPath) {
61845
- const notes = await readFile16(notesPath.replace(/^~(?=\/)/, homedir8()), "utf-8").catch(() => "");
62069
+ const notes = await readFile17(notesPath.replace(/^~(?=\/)/, homedir8()), "utf-8").catch(() => "");
61846
62070
  const decisions = /^## Decisions[^\n]*\n([\s\S]*?)(?=^## |(?![\s\S]))/m.exec(notes)?.[1].trim();
61847
62071
  if (!decisions) return null;
61848
62072
  const body = decisions.length > PULL_REQUEST_DECISIONS_MAX_CHARS ? `${decisions.slice(0, PULL_REQUEST_DECISIONS_MAX_CHARS)}
@@ -61901,7 +62125,7 @@ function terminalErrorsFromEvent(event, provider) {
61901
62125
  if (codexTurn) {
61902
62126
  return normalizeCodexAspTranscriptStatus(codexTurn.status) === "failed" ? [codexTurn.error ?? "Codex run failed"] : void 0;
61903
62127
  }
61904
- 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";
62128
+ 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";
61905
62129
  if (!mayContainProviderError) return void 0;
61906
62130
  const errors = parseAgentEvents([event], provider).flatMap((message) => message.type === "error" ? [message.message] : []);
61907
62131
  return errors.length > 0 ? errors : void 0;
@@ -61909,7 +62133,7 @@ function terminalErrorsFromEvent(event, provider) {
61909
62133
  var LAST_MESSAGE_PREVIEW_MAX = 200;
61910
62134
  var FINAL_MESSAGE_MAX = 6e3;
61911
62135
  var PROGRESS_INTERVAL_MS = 2e4;
61912
- var STREAM_RECORD_TYPES = /* @__PURE__ */ new Set(["pi-message_update", "opencode-message.part.delta", "muse-item-delta", "cursor-assistant", "cursor-thinking"]);
62136
+ var STREAM_RECORD_TYPES = /* @__PURE__ */ new Set(["pi-message_update", "opencode-message.part.delta", "muse-item-delta", "cursor-assistant", "cursor-thinking", "gemini-chunk"]);
61913
62137
  var PROGRESS_STEP_MAX = 120;
61914
62138
  var TURN_REQUEST_MAX = 8e3;
61915
62139
  var toolInputRequestSchema = z4.object({
@@ -61947,6 +62171,9 @@ var NOT_WORK_MESSAGE_TYPES = /* @__PURE__ */ new Set(["user", "error", "capacity
61947
62171
  function hasActiveAgentWork(chat) {
61948
62172
  return chat.provider.isProcessing() || hasActiveBackgroundWork(chat) || chat.turnCompletion !== null;
61949
62173
  }
62174
+ function isChatIdle(chat) {
62175
+ return chat.acceptingMessages === 0 && !hasActiveChatTurn(chat) && !hasActiveAgentWork(chat);
62176
+ }
61950
62177
  function hasActiveChatTurn(chat) {
61951
62178
  return chat.hasActiveTurn || chat.pendingMessageIds.length > 0 || isForkPreparing(chat) || chat.provider.isProcessing();
61952
62179
  }
@@ -62145,6 +62372,11 @@ var ChatService = class {
62145
62372
  hasActiveAgentWork(provider) {
62146
62373
  return [...this.chats.values()].some((chat) => chat.persisted.provider === provider && (hasActiveAgentWork(chat) || chat.acceptingMessages > 0 || chat.pendingMessageIds.length > 0));
62147
62374
  }
62375
+ async releaseAgentSessions(provider) {
62376
+ const chats = [...this.chats.values()].filter((chat) => !chat.persisted.deletedAt && chat.persisted.provider === provider);
62377
+ for (const chat of chats) chat.releaseWhenIdle = !isChatIdle(chat);
62378
+ await Promise.all(chats.filter((chat) => !chat.releaseWhenIdle).map((chat) => this.releaseAgentProcess(chat)));
62379
+ }
62148
62380
  listDeletedChats(includeChildren = false) {
62149
62381
  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 ?? ""));
62150
62382
  }
@@ -62161,7 +62393,7 @@ var ChatService = class {
62161
62393
  const [discovered, learnedSkills] = await Promise.all([
62162
62394
  chat.provider.listSlashCommands?.() ?? [],
62163
62395
  // Learned skills work in the background, so they stay out of the slash menu.
62164
- 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())
62396
+ 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())
62165
62397
  ]);
62166
62398
  const providerCommands = discovered.filter(({ command }) => !learnedSkills.has(command)).map((command) => ({
62167
62399
  ...command,
@@ -62639,7 +62871,7 @@ ${decisions}` };
62639
62871
  }
62640
62872
  }
62641
62873
  async readSenders(chatId) {
62642
- return readFile17(chatMessageSendersFilePath(chatId), "utf-8").then(parseChatMessageSendersJsonl).catch((error) => {
62874
+ return readFile18(chatMessageSendersFilePath(chatId), "utf-8").then(parseChatMessageSendersJsonl).catch((error) => {
62643
62875
  if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return [];
62644
62876
  console.error("[ChatService] Failed to read sender records:", error);
62645
62877
  return [];
@@ -63012,7 +63244,7 @@ ${decisions}` };
63012
63244
  `${historyPath}.pages.index.json`
63013
63245
  ].map((path8) => rm7(path8, { force: true })));
63014
63246
  await rm7(chatMessageSendersFilePath(persisted.id), { force: true });
63015
- await rm7(join30(FORKS_DIR, persisted.id), { recursive: true, force: true });
63247
+ await rm7(join31(FORKS_DIR, persisted.id), { recursive: true, force: true });
63016
63248
  }
63017
63249
  switchHarness(source, request) {
63018
63250
  const switching = (async () => {
@@ -63351,7 +63583,7 @@ ${note}`;
63351
63583
  };
63352
63584
  }
63353
63585
  historyPath(persisted) {
63354
- return join30(HISTORY_DIR_BY_PROVIDER[persisted.provider], `${persisted.id}.jsonl`);
63586
+ return join31(HISTORY_DIR_BY_PROVIDER[persisted.provider], `${persisted.id}.jsonl`);
63355
63587
  }
63356
63588
  async recordUploadedHistory(chatId, artifact) {
63357
63589
  const chat = this.getRuntimeChat(chatId);
@@ -63540,6 +63772,8 @@ ${note}`;
63540
63772
  provider = new ClaudeManager(managerOptions);
63541
63773
  } else if (baseProvider === "cursor") {
63542
63774
  provider = new CursorManager(managerOptions);
63775
+ } else if (baseProvider === "gemini") {
63776
+ provider = new GeminiManager(managerOptions);
63543
63777
  } else if (baseProvider === "muse") {
63544
63778
  provider = new MuseManager(managerOptions);
63545
63779
  } else if (baseProvider === "opencode") {
@@ -63585,6 +63819,7 @@ ${note}`;
63585
63819
  stopped: null,
63586
63820
  publishedQueue: null,
63587
63821
  idleReleaseTimer: null,
63822
+ releaseWhenIdle: false,
63588
63823
  history,
63589
63824
  outbox: new AsyncLock(),
63590
63825
  unpublishedHistoryStarts: [],
@@ -63843,7 +64078,8 @@ ${note}`;
63843
64078
  this.publish({ type: "chat.updated", payload: { chat: this.toSummary(chat) } }).catch(() => {
63844
64079
  });
63845
64080
  this.notifyWorkspaceAgentIdle();
63846
- this.scheduleIdleRelease(chat);
64081
+ if (chat.releaseWhenIdle && isChatIdle(chat)) void this.releaseAgentProcess(chat);
64082
+ else this.scheduleIdleRelease(chat);
63847
64083
  }
63848
64084
  // Idleness is re-checked when the timer fires: work that starts in between
63849
64085
  // ends with another processing stop, which schedules a fresh release.
@@ -63853,7 +64089,7 @@ ${note}`;
63853
64089
  this.enforceLiveProcessCap();
63854
64090
  chat.idleReleaseTimer = setTimeout(() => {
63855
64091
  chat.idleReleaseTimer = null;
63856
- if (chat.persisted.deletedAt || chat.acceptingMessages > 0 || hasActiveChatTurn(chat) || hasActiveAgentWork(chat)) return;
64092
+ if (chat.persisted.deletedAt || !isChatIdle(chat)) return;
63857
64093
  void this.releaseAgentProcess(chat);
63858
64094
  }, chat.persisted.parentChatId === null ? CHAT_IDLE_RELEASE_MS : CHILD_CHAT_IDLE_RELEASE_MS);
63859
64095
  chat.idleReleaseTimer.unref?.();
@@ -63864,13 +64100,14 @@ ${note}`;
63864
64100
  }
63865
64101
  enforceLiveProcessCap() {
63866
64102
  const live = [...this.chats.values()].filter((chat) => chat.live);
63867
- const idle = live.filter((chat) => chat.acceptingMessages === 0 && !hasActiveChatTurn(chat) && !hasActiveAgentWork(chat)).sort((a, b) => a.persisted.updatedAt.localeCompare(b.persisted.updatedAt));
64103
+ const idle = live.filter(isChatIdle).sort((a, b) => a.persisted.updatedAt.localeCompare(b.persisted.updatedAt));
63868
64104
  for (const chat of idle.slice(0, Math.max(0, live.length - maxLiveAgentProcesses()))) void this.releaseAgentProcess(chat);
63869
64105
  }
63870
64106
  /** Senders await `chat.release` so a new turn never starts against a session that is being torn down. */
63871
64107
  releaseAgentProcess(chat) {
63872
64108
  this.cancelIdleRelease(chat);
63873
64109
  chat.live = false;
64110
+ chat.releaseWhenIdle = false;
63874
64111
  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(() => {
63875
64112
  chat.release = null;
63876
64113
  });
@@ -63976,7 +64213,7 @@ ${note}`;
63976
64213
  }
63977
64214
  async loadChats() {
63978
64215
  try {
63979
- const content = await readFile17(CHATS_FILE, "utf-8");
64216
+ const content = await readFile18(CHATS_FILE, "utf-8");
63980
64217
  return parsePersistedChatsContent(content);
63981
64218
  } catch (error) {
63982
64219
  if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
@@ -63991,7 +64228,7 @@ ${note}`;
63991
64228
  console.error("[ChatService] Failed to quarantine corrupt chats file:", renameError);
63992
64229
  }
63993
64230
  try {
63994
- const backupContent = await readFile17(CHATS_BACKUP_FILE, "utf-8");
64231
+ const backupContent = await readFile18(CHATS_BACKUP_FILE, "utf-8");
63995
64232
  return parsePersistedChatsContent(backupContent);
63996
64233
  } catch (backupError) {
63997
64234
  if (backupError && typeof backupError === "object" && "code" in backupError && backupError.code === "ENOENT") {
@@ -64141,15 +64378,15 @@ ${note}`;
64141
64378
  // src/services/repo-file-service.ts
64142
64379
  import { execFile as execFile7 } from "child_process";
64143
64380
  import { createReadStream as createReadStream2 } from "fs";
64144
- import { readFile as readFile18, realpath as realpath2, stat as stat5 } from "fs/promises";
64381
+ import { readFile as readFile19, realpath as realpath2, stat as stat5 } from "fs/promises";
64145
64382
  import { homedir as homedir9 } from "os";
64146
- import { extname as extname3, isAbsolute as isAbsolute3, join as join32, resolve as resolve5 } from "path";
64383
+ import { extname as extname3, isAbsolute as isAbsolute3, join as join33, resolve as resolve5 } from "path";
64147
64384
 
64148
64385
  // src/services/language-server-service.ts
64149
64386
  import { spawn as spawn4 } from "child_process";
64150
64387
  import { existsSync as existsSync15, readFileSync as readFileSync6 } from "fs";
64151
64388
  import { createRequire as createRequire5 } from "module";
64152
- import { delimiter as delimiter2, dirname as dirname13, join as join31, relative as relative2 } from "path";
64389
+ import { delimiter as delimiter2, dirname as dirname13, join as join32, relative as relative2 } from "path";
64153
64390
  import { setTimeout as setTimeout3 } from "timers/promises";
64154
64391
  import { fileURLToPath as fileURLToPath5, pathToFileURL } from "url";
64155
64392
  import { createMessageConnection, StreamMessageReader, StreamMessageWriter } from "vscode-jsonrpc/node.js";
@@ -64268,7 +64505,7 @@ var LanguageServerService = class {
64268
64505
  if (config.package && config.bin) command = process.execPath;
64269
64506
  else if (config.command) {
64270
64507
  const commandName = config.command;
64271
- command = process.env.PATH?.split(delimiter2).map((directory) => join31(directory, commandName)).find(existsSync15);
64508
+ command = process.env.PATH?.split(delimiter2).map((directory) => join32(directory, commandName)).find(existsSync15);
64272
64509
  }
64273
64510
  const args = config.package && config.bin ? [packageBin(config.package, config.bin), ...config.args] : config.args;
64274
64511
  if (!command) return null;
@@ -64431,7 +64668,7 @@ var RepoFileService = class {
64431
64668
  ...isAbsolute3(filePath) ? ["/"] : [],
64432
64669
  ...repos.map((repo) => repo.path),
64433
64670
  ...await canvasDirectories(repos),
64434
- join32(this.homeDir, "workspaces"),
64671
+ join33(this.homeDir, "workspaces"),
64435
64672
  this.homeDir
64436
64673
  ];
64437
64674
  for (const root of roots) {
@@ -64523,7 +64760,7 @@ var RepoFileService = class {
64523
64760
  async inspectSymbol(repoName, filePath, line, character, action) {
64524
64761
  const resolved = await this.resolveFile(repoName, filePath);
64525
64762
  if (!resolved || line < 1 || character < 0 || isBinaryExtension(filePath)) return null;
64526
- const content = await readFile18(resolved.fullPath, "utf8");
64763
+ const content = await readFile19(resolved.fullPath, "utf8");
64527
64764
  const sourceLine = content.split("\n")[line - 1];
64528
64765
  if (sourceLine === void 0) return null;
64529
64766
  const symbolMatch = Array.from(sourceLine.matchAll(/[\p{L}_$][\p{L}\p{N}_$]*/gu)).find((match) => character >= match.index && character <= match.index + match[0].length);
@@ -64636,22 +64873,22 @@ var RepoFileService = class {
64636
64873
  // src/v1-routes.ts
64637
64874
  import { Hono } from "hono";
64638
64875
  import { z as z6 } from "zod";
64639
- import { readdir as readdir11, stat as stat6, readFile as readFile21 } from "fs/promises";
64876
+ import { readdir as readdir12, stat as stat6, readFile as readFile22 } from "fs/promises";
64640
64877
  import { openAsBlob } from "fs";
64641
- import { join as join35, resolve as resolve6 } from "path";
64878
+ import { join as join36, resolve as resolve6 } from "path";
64642
64879
 
64643
64880
  // src/services/warm-hooks-service.ts
64644
64881
  import { spawn as spawn5 } from "child_process";
64645
- import { readFile as readFile20 } from "fs/promises";
64882
+ import { readFile as readFile21 } from "fs/promises";
64646
64883
  import { existsSync as existsSync16 } from "fs";
64647
- import { join as join34 } from "path";
64884
+ import { join as join35 } from "path";
64648
64885
 
64649
64886
  // src/services/warm-hook-logs-service.ts
64650
- import { mkdir as mkdir16, readFile as readFile19, writeFile as writeFile9, readdir as readdir10, appendFile as appendFile5, unlink as unlink2 } from "fs/promises";
64887
+ import { mkdir as mkdir16, readFile as readFile20, writeFile as writeFile9, readdir as readdir11, appendFile as appendFile5, unlink as unlink2 } from "fs/promises";
64651
64888
  import { homedir as homedir10 } from "os";
64652
- import { join as join33 } from "path";
64653
- var LOGS_DIR2 = join33(homedir10(), ".replicas", "warm-hook-logs");
64654
- var CURRENT_RUN_LOG = join33(LOGS_DIR2, "current-run.log");
64889
+ import { join as join34 } from "path";
64890
+ var LOGS_DIR2 = join34(homedir10(), ".replicas", "warm-hook-logs");
64891
+ var CURRENT_RUN_LOG = join34(LOGS_DIR2, "current-run.log");
64655
64892
  function withPreview2(stored) {
64656
64893
  const preview = buildHookOutputPreview(stored.output);
64657
64894
  return { ...stored, ...preview };
@@ -64667,7 +64904,7 @@ var WarmHookLogsService = class {
64667
64904
  hookName: "environment",
64668
64905
  ...entry
64669
64906
  };
64670
- await writeFile9(join33(LOGS_DIR2, ENVIRONMENT_HOOK_LOG_FILENAME), `${JSON.stringify(log, null, 2)}
64907
+ await writeFile9(join34(LOGS_DIR2, ENVIRONMENT_HOOK_LOG_FILENAME), `${JSON.stringify(log, null, 2)}
64671
64908
  `, "utf-8");
64672
64909
  }
64673
64910
  async saveRepoHookLog(repoName, entry) {
@@ -64677,13 +64914,13 @@ var WarmHookLogsService = class {
64677
64914
  hookName: repoName,
64678
64915
  ...entry
64679
64916
  };
64680
- await writeFile9(join33(LOGS_DIR2, repoHookLogFilename(repoName)), `${JSON.stringify(log, null, 2)}
64917
+ await writeFile9(join34(LOGS_DIR2, repoHookLogFilename(repoName)), `${JSON.stringify(log, null, 2)}
64681
64918
  `, "utf-8");
64682
64919
  }
64683
64920
  async getAllLogs() {
64684
64921
  let files;
64685
64922
  try {
64686
- files = await readdir10(LOGS_DIR2);
64923
+ files = await readdir11(LOGS_DIR2);
64687
64924
  } catch (err) {
64688
64925
  if (err.code === "ENOENT") {
64689
64926
  return [];
@@ -64696,7 +64933,7 @@ var WarmHookLogsService = class {
64696
64933
  continue;
64697
64934
  }
64698
64935
  try {
64699
- const raw = await readFile19(join33(LOGS_DIR2, file), "utf-8");
64936
+ const raw = await readFile20(join34(LOGS_DIR2, file), "utf-8");
64700
64937
  const stored = JSON.parse(raw);
64701
64938
  if (stored.hookType !== "environment" && stored.hookType !== "repository") continue;
64702
64939
  logs.push(withPreview2(stored));
@@ -64723,7 +64960,7 @@ var WarmHookLogsService = class {
64723
64960
  }
64724
64961
  async getCurrentRunLog() {
64725
64962
  try {
64726
- return await readFile19(CURRENT_RUN_LOG, "utf-8");
64963
+ return await readFile20(CURRENT_RUN_LOG, "utf-8");
64727
64964
  } catch (err) {
64728
64965
  if (err.code === "ENOENT") return null;
64729
64966
  throw err;
@@ -64732,7 +64969,7 @@ var WarmHookLogsService = class {
64732
64969
  async getFullOutput(hookType, hookName) {
64733
64970
  const filename = hookType === "environment" ? ENVIRONMENT_HOOK_LOG_FILENAME : repoHookLogFilename(hookName);
64734
64971
  try {
64735
- const raw = await readFile19(join33(LOGS_DIR2, filename), "utf-8");
64972
+ const raw = await readFile20(join34(LOGS_DIR2, filename), "utf-8");
64736
64973
  const stored = JSON.parse(raw);
64737
64974
  if (stored.hookType !== hookType || stored.hookName !== hookName) {
64738
64975
  return null;
@@ -64751,12 +64988,12 @@ var warmHookLogsService = new WarmHookLogsService();
64751
64988
  // src/services/warm-hooks-service.ts
64752
64989
  async function readRepoWarmHook(repoPath) {
64753
64990
  for (const filename of REPLICAS_CONFIG_FILENAMES) {
64754
- const configPath = join34(repoPath, filename);
64991
+ const configPath = join35(repoPath, filename);
64755
64992
  if (!existsSync16(configPath)) {
64756
64993
  continue;
64757
64994
  }
64758
64995
  try {
64759
- const raw = await readFile20(configPath, "utf-8");
64996
+ const raw = await readFile21(configPath, "utf-8");
64760
64997
  const config = parseReplicasConfigString(raw, filename);
64761
64998
  if (!config.warmHook) {
64762
64999
  return null;
@@ -65871,6 +66108,14 @@ data: ${JSON.stringify("Terminal session not found")}
65871
66108
  );
65872
66109
  }
65873
66110
  });
66111
+ app2.post("/credentials/withdraw", async (c) => {
66112
+ const { logins } = await c.req.json();
66113
+ for (const { provider, ...login } of logins) {
66114
+ if (await withdrawAgentLogin(provider, login)) await deps.chatService.releaseAgentSessions(provider);
66115
+ clearCredentialFallbacks(provider);
66116
+ }
66117
+ return c.json(await environmentDetailsService.getDetails());
66118
+ });
65874
66119
  app2.post("/credentials/switch", async (c) => {
65875
66120
  const body = await c.req.json();
65876
66121
  const provider = workspaceCredentialProviderSchema.safeParse(body.provider);
@@ -66122,11 +66367,11 @@ data: ${JSON.stringify("Terminal session not found")}
66122
66367
  });
66123
66368
  app2.get("/logs", async (c) => {
66124
66369
  try {
66125
- const files = await readdir11(LOG_DIR).catch(() => []);
66370
+ const files = await readdir12(LOG_DIR).catch(() => []);
66126
66371
  const logFiles = files.filter((f) => f.endsWith(".log"));
66127
66372
  const sessions = await Promise.all(
66128
66373
  logFiles.map(async (filename) => {
66129
- const filePath = join35(LOG_DIR, filename);
66374
+ const filePath = join36(LOG_DIR, filename);
66130
66375
  const fileStat = await stat6(filePath);
66131
66376
  const sessionId = filename.replace(/\.log$/, "");
66132
66377
  return {
@@ -66161,7 +66406,7 @@ data: ${JSON.stringify("Terminal session not found")}
66161
66406
  }
66162
66407
  let content;
66163
66408
  try {
66164
- content = await readFile21(filePath, "utf-8");
66409
+ content = await readFile22(filePath, "utf-8");
66165
66410
  } catch {
66166
66411
  return c.json(jsonError("Log session not found"), 404);
66167
66412
  }
@@ -66185,7 +66430,7 @@ data: ${JSON.stringify("Terminal session not found")}
66185
66430
  import { randomUUID as randomUUID12 } from "crypto";
66186
66431
  import { mkdir as mkdir17, open as open3, stat as stat7, writeFile as writeFile10 } from "fs/promises";
66187
66432
  import { arch as arch2, platform as platform3 } from "os";
66188
- import { dirname as dirname14, join as join36, resolve as resolve7 } from "path";
66433
+ import { dirname as dirname14, join as join37, resolve as resolve7 } from "path";
66189
66434
  import { z as z7 } from "zod";
66190
66435
 
66191
66436
  // src/services/exec/process-registry.ts
@@ -66381,7 +66626,7 @@ function parse(schema, json) {
66381
66626
  return parsed.data;
66382
66627
  }
66383
66628
  function resolvePath(target) {
66384
- if (target === "~" || target.startsWith("~/")) return join36(ENGINE_ENV.HOME_DIR, target.slice(1));
66629
+ if (target === "~" || target.startsWith("~/")) return join37(ENGINE_ENV.HOME_DIR, target.slice(1));
66385
66630
  return resolve7(ENGINE_ENV.WORKSPACE_ROOT, target);
66386
66631
  }
66387
66632
  async function mcpServerProcess(name) {
@@ -66657,13 +66902,13 @@ function attachTerminalSocket(id, socket) {
66657
66902
  }
66658
66903
 
66659
66904
  // src/services/resource-monitor.ts
66660
- import { readFile as readFile22 } from "fs/promises";
66905
+ import { readFile as readFile23 } from "fs/promises";
66661
66906
  var SAMPLE_INTERVAL_MS = 5e3;
66662
66907
  var READ_TIMEOUT_MS = 2e3;
66663
66908
  var pendingReads = new InFlightMap();
66664
66909
  var boundedReads = /* @__PURE__ */ new WeakMap();
66665
66910
  function readWithin(path8) {
66666
- const read = pendingReads.run(path8, () => readFile22(path8, "utf8"));
66911
+ const read = pendingReads.run(path8, () => readFile23(path8, "utf8"));
66667
66912
  const bounded = boundedReads.get(read) ?? withTimeout(read, READ_TIMEOUT_MS, `Timed out reading ${path8}`);
66668
66913
  boundedReads.set(read, bounded);
66669
66914
  return bounded;
@@ -66922,8 +67167,8 @@ async function installWorkspaceSdk() {
66922
67167
  // src/services/git-push-tracker.ts
66923
67168
  import { mkdir as mkdir19, rm as rm8 } from "fs/promises";
66924
67169
  import { createServer as createServer3 } from "net";
66925
- import { join as join37 } from "path";
66926
- var SOCKET_PATH = join37(ENGINE_DIR, "git-trace2.sock");
67170
+ import { join as join38 } from "path";
67171
+ var SOCKET_PATH = join38(ENGINE_DIR, "git-trace2.sock");
66927
67172
  var MAX_LINE_LENGTH = 1024 * 1024;
66928
67173
  var listening = null;
66929
67174
  function startGitPushTracker() {