replicas-engine 0.1.1725 → 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/{asp-host-7DGBCD52.js → asp-host-TWRX3YXW.js} +6 -6
- package/dist/src/{chunk-UDR2HT74.js → chunk-2X4SV2H7.js} +2 -2
- package/dist/src/{chunk-LIXZEE44.js → chunk-F2YDU3AP.js} +3 -3
- package/dist/src/{chunk-YNHFXBHT.js → chunk-GBVHK7GR.js} +416 -227
- package/dist/src/{chunk-ESENYL7M.js → chunk-LWHGKKNM.js} +1 -1
- package/dist/src/{chunk-DHAQM6LA.js → chunk-M6ELG3GK.js} +1 -1
- package/dist/src/{chunk-APCSKPLU.js → chunk-NTSUADYM.js} +1 -1
- package/dist/src/{chunk-3SJP6X3P.js → chunk-OAFO4KYM.js} +86 -43
- package/dist/src/{chunk-ZYRAETMX.js → chunk-OY6X5AUJ.js} +2 -2
- package/dist/src/{chunk-4YQ4UWFY.js → chunk-QN5PAZSN.js} +65 -8
- package/dist/src/{chunk-7ZDAVYTV.js → chunk-XCFPXSY4.js} +4 -0
- package/dist/src/{chunk-EZWCNWX2.js → chunk-YKUHRKKX.js} +2 -2
- package/dist/src/codemode-mcp.js +4 -4
- package/dist/src/command-protection-hook.js +17 -6
- package/dist/src/headless-agent.js +48 -5
- package/dist/src/index.js +620 -157
- package/dist/src/post-tool-pr-hook.js +4 -3
- package/dist/src/subagent-mcp.js +1 -1
- package/package.json +1 -1
package/dist/src/index.js
CHANGED
|
@@ -90,12 +90,12 @@ import {
|
|
|
90
90
|
import {
|
|
91
91
|
getManagedPiMcpServers,
|
|
92
92
|
managedMcpServerProcess
|
|
93
|
-
} from "./chunk-
|
|
93
|
+
} from "./chunk-2X4SV2H7.js";
|
|
94
94
|
import {
|
|
95
95
|
evaluateCommandProtection,
|
|
96
96
|
extractToolCommand,
|
|
97
97
|
reportCommandProtectionBlock
|
|
98
|
-
} from "./chunk-
|
|
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-
|
|
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-
|
|
145
|
+
} from "./chunk-XCFPXSY4.js";
|
|
138
146
|
import {
|
|
139
147
|
publishedPullRequestUrls
|
|
140
|
-
} from "./chunk-
|
|
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-
|
|
228
|
+
} from "./chunk-OAFO4KYM.js";
|
|
219
229
|
import {
|
|
220
230
|
SUBAGENT_MCP_TOOL_TIMEOUT_MS,
|
|
221
231
|
engineScriptProcess,
|
|
222
232
|
subagentMcpProcessConfig
|
|
223
|
-
} from "./chunk-
|
|
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-
|
|
244
|
+
} from "./chunk-OY6X5AUJ.js";
|
|
235
245
|
import {
|
|
236
246
|
AspRequestTimeoutError,
|
|
237
247
|
AspResponseError,
|
|
238
248
|
buildCodexAgentEnv,
|
|
239
249
|
getCodexModelProvider
|
|
240
|
-
} from "./chunk-
|
|
250
|
+
} from "./chunk-F2YDU3AP.js";
|
|
241
251
|
import {
|
|
242
252
|
SUBPROCESS_MAX_BUFFER,
|
|
243
253
|
execAsync,
|
|
244
254
|
execFileAsync
|
|
245
|
-
} from "./chunk-
|
|
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,
|
|
@@ -522,6 +533,7 @@ import {
|
|
|
522
533
|
sendChatMessageRequestSchema,
|
|
523
534
|
sendChatMessageResponseSchema,
|
|
524
535
|
serializeCanvasContentResponse,
|
|
536
|
+
serializeGeminiAuthFile,
|
|
525
537
|
serializeMuseAuthFile,
|
|
526
538
|
shellQuotePosix,
|
|
527
539
|
shouldRefreshPullRequests,
|
|
@@ -542,7 +554,7 @@ import {
|
|
|
542
554
|
workspaceTokenRequestSchema,
|
|
543
555
|
workspaceTokenResponseSchema,
|
|
544
556
|
wrapInTag
|
|
545
|
-
} from "./chunk-
|
|
557
|
+
} from "./chunk-GBVHK7GR.js";
|
|
546
558
|
import {
|
|
547
559
|
__commonJS,
|
|
548
560
|
__export,
|
|
@@ -679,7 +691,7 @@ var require_lib = __commonJS({
|
|
|
679
691
|
"../node_modules/.bun/which@5.0.0/node_modules/which/lib/index.js"(exports, module) {
|
|
680
692
|
"use strict";
|
|
681
693
|
var { isexe, sync: isexeSync } = require_index_min();
|
|
682
|
-
var { join:
|
|
694
|
+
var { join: join39, delimiter: delimiter3, sep: sep2, posix } = __require("path");
|
|
683
695
|
var isWindows = process.platform === "win32";
|
|
684
696
|
var rSlash = new RegExp(`[${posix.sep}${sep2 === posix.sep ? "" : sep2}]`.replace(/(\\)/g, "\\$1"));
|
|
685
697
|
var rRel = new RegExp(`^\\.${rSlash.source}`);
|
|
@@ -708,7 +720,7 @@ var require_lib = __commonJS({
|
|
|
708
720
|
var getPathPart = (raw, cmd) => {
|
|
709
721
|
const pathPart = /^".*"$/.test(raw) ? raw.slice(1, -1) : raw;
|
|
710
722
|
const prefix = !pathPart && rRel.test(cmd) ? cmd.slice(0, 2) : "";
|
|
711
|
-
return prefix +
|
|
723
|
+
return prefix + join39(pathPart, cmd);
|
|
712
724
|
};
|
|
713
725
|
var which = async (cmd, opt = {}) => {
|
|
714
726
|
const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
|
|
@@ -9291,7 +9303,13 @@ var ClaudeTokenManager = class extends BaseRefreshManager {
|
|
|
9291
9303
|
}
|
|
9292
9304
|
async requestAndApplyCredentials(generation, request) {
|
|
9293
9305
|
console.log("[ClaudeTokenManager] Refreshing Claude credentials...");
|
|
9294
|
-
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
|
+
});
|
|
9295
9313
|
await this.applyCredentialUpdate(generation, () => this.applyCredentialsResponse(data));
|
|
9296
9314
|
console.log(`[ClaudeTokenManager] Credentials refreshed (method=${data.type})`);
|
|
9297
9315
|
}
|
|
@@ -9961,6 +9979,8 @@ function detectAgentAuthMethod(provider) {
|
|
|
9961
9979
|
return detectCodexAuthMethod();
|
|
9962
9980
|
case AGENT.CURSOR:
|
|
9963
9981
|
return ENGINE_ENV.CURSOR_API_KEY ? "api_key" : "none";
|
|
9982
|
+
case AGENT.GEMINI:
|
|
9983
|
+
return existsSync(GEMINI_AUTH_PATH) ? "oauth" : "none";
|
|
9964
9984
|
case AGENT.MUSE:
|
|
9965
9985
|
if (!existsSync(MUSE_AUTH_PATH)) return "none";
|
|
9966
9986
|
if (ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS.muse?.method === "api_key") return "api_key";
|
|
@@ -10120,6 +10140,7 @@ var EnvironmentDetailsService = class {
|
|
|
10120
10140
|
details.claudeAuthMethod = detectAgentAuthMethod(AGENT.CLAUDE);
|
|
10121
10141
|
details.codexAuthMethod = detectAgentAuthMethod(AGENT.CODEX);
|
|
10122
10142
|
details.cursorAuthMethod = detectAgentAuthMethod(AGENT.CURSOR);
|
|
10143
|
+
details.geminiAuthMethod = existsSync2(GEMINI_CLI_PATH) ? detectAgentAuthMethod(AGENT.GEMINI) : void 0;
|
|
10123
10144
|
details.museAuthMethod = detectAgentAuthMethod(AGENT.MUSE);
|
|
10124
10145
|
details.opencodeAuthMethod = detectAgentAuthMethod(AGENT.OPENCODE);
|
|
10125
10146
|
details.piAuthMethod = detectAgentAuthMethod(AGENT.PI);
|
|
@@ -11128,14 +11149,14 @@ function localControlComputers() {
|
|
|
11128
11149
|
}
|
|
11129
11150
|
|
|
11130
11151
|
// src/services/chat/chat-service.ts
|
|
11131
|
-
import { appendFile as appendFile4, copyFile as copyFile2, mkdir as mkdir15, readFile as
|
|
11132
|
-
import { join as
|
|
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";
|
|
11133
11154
|
import { randomUUID as randomUUID9 } from "crypto";
|
|
11134
11155
|
import { z as z4 } from "zod";
|
|
11135
11156
|
|
|
11136
11157
|
// ../shared/src/persisted-query-hashes.ts
|
|
11137
11158
|
var PERSISTED_QUERY_HASHES = {
|
|
11138
|
-
workspaceChats: "
|
|
11159
|
+
workspaceChats: "79cb548c"
|
|
11139
11160
|
};
|
|
11140
11161
|
|
|
11141
11162
|
// ../shared/src/workspace-chat.ts
|
|
@@ -11391,7 +11412,10 @@ var MuseTokenManager = class extends BaseRefreshManager {
|
|
|
11391
11412
|
};
|
|
11392
11413
|
const response = await monolithRequest("/v1/engine/muse/refresh-credentials", { body: request, signal: AbortSignal.timeout(12e4) });
|
|
11393
11414
|
if (!response.ok) {
|
|
11394
|
-
|
|
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;
|
|
11395
11419
|
}
|
|
11396
11420
|
const data = await response.json();
|
|
11397
11421
|
await writeSecureCredentialFile(MUSE_AUTH_PATH, serializeMuseAuthFile(data), { ensureParentDir: true });
|
|
@@ -11403,6 +11427,41 @@ var MuseTokenManager = class extends BaseRefreshManager {
|
|
|
11403
11427
|
};
|
|
11404
11428
|
var museTokenManager = new MuseTokenManager();
|
|
11405
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
|
+
|
|
11406
11465
|
// src/managers/opencode-token-manager.ts
|
|
11407
11466
|
var OPENCODE_AUTH_ENV_KEYS = [...ollamaAuthEnvKeys("opencode"), ...openAICompatibleAuthEnvKeys("opencode")];
|
|
11408
11467
|
var OpencodeTokenManager = class extends BaseRefreshManager {
|
|
@@ -11432,7 +11491,10 @@ var OpencodeTokenManager = class extends BaseRefreshManager {
|
|
|
11432
11491
|
};
|
|
11433
11492
|
const response = await monolithRequest("/v1/engine/opencode/refresh-credentials", { body: request, signal: AbortSignal.timeout(12e4) });
|
|
11434
11493
|
if (!response.ok) {
|
|
11435
|
-
|
|
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;
|
|
11436
11498
|
}
|
|
11437
11499
|
const data = await response.json();
|
|
11438
11500
|
for (const file of data.auth.files ?? []) {
|
|
@@ -11452,6 +11514,7 @@ var opencodeTokenManager = new OpencodeTokenManager();
|
|
|
11452
11514
|
var SWAPPABLE_AGENTS = {
|
|
11453
11515
|
claude: claudeTokenManager,
|
|
11454
11516
|
codex: codexTokenManager,
|
|
11517
|
+
gemini: geminiTokenManager,
|
|
11455
11518
|
muse: museTokenManager,
|
|
11456
11519
|
opencode: opencodeTokenManager
|
|
11457
11520
|
};
|
|
@@ -17007,32 +17070,45 @@ function getPostToolPrHookPath() {
|
|
|
17007
17070
|
if (!postToolHookPath) throw new Error("Replicas post-tool PR hook executable is missing.");
|
|
17008
17071
|
return postToolHookPath;
|
|
17009
17072
|
}
|
|
17010
|
-
async function
|
|
17011
|
-
const path8 = join13(ENGINE_ENV.HOME_DIR, ".cursor", "hooks.json");
|
|
17073
|
+
async function updateHooksFile(path8, label, update) {
|
|
17012
17074
|
let config = {};
|
|
17013
17075
|
try {
|
|
17014
17076
|
const content = await readFile8(path8, "utf8");
|
|
17015
17077
|
const parsed = content.trim() ? JSON.parse(content) : {};
|
|
17016
|
-
if (!isRecord(parsed)) throw new Error(
|
|
17078
|
+
if (!isRecord(parsed)) throw new Error(`Invalid ${label} hooks configuration.`);
|
|
17017
17079
|
config = parsed;
|
|
17018
17080
|
} catch (error) {
|
|
17019
17081
|
if (!(error && typeof error === "object" && "code" in error && error.code === "ENOENT")) throw error;
|
|
17020
17082
|
}
|
|
17021
|
-
const hooks = isRecord(config.hooks) ? config.hooks : {};
|
|
17022
|
-
const existing = Array.isArray(hooks.preToolUse) ? hooks.preToolUse : [];
|
|
17023
|
-
hooks.preToolUse = [
|
|
17024
|
-
...existing.filter((entry) => !isRecord(entry) || typeof entry.command !== "string" || !entry.command.includes("command-protection-hook")),
|
|
17025
|
-
{ command: shellCommand(hookPath, "cursor") }
|
|
17026
|
-
];
|
|
17027
|
-
const existingPost = Array.isArray(hooks.postToolUse) ? hooks.postToolUse : [];
|
|
17028
|
-
hooks.postToolUse = [
|
|
17029
|
-
...existingPost.filter((entry) => !isRecord(entry) || typeof entry.command !== "string" || !entry.command.includes("post-tool-pr-hook")),
|
|
17030
|
-
{ command: shellCommand(postToolHookPath) }
|
|
17031
|
-
];
|
|
17032
17083
|
await mkdir9(dirname4(path8), { recursive: true });
|
|
17033
|
-
await atomicWriteFile(path8, `${JSON.stringify(
|
|
17084
|
+
await atomicWriteFile(path8, `${JSON.stringify(update(config), null, 2)}
|
|
17034
17085
|
`);
|
|
17035
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
|
+
}
|
|
17036
17112
|
|
|
17037
17113
|
// src/managers/cursor-run-recovery.ts
|
|
17038
17114
|
import { Agent as CursorAgent, AgentBusyError } from "@cursor/sdk";
|
|
@@ -17998,10 +18074,353 @@ ${pending}
|
|
|
17998
18074
|
}
|
|
17999
18075
|
};
|
|
18000
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
|
+
|
|
18001
18420
|
// src/managers/opencode-manager.ts
|
|
18002
18421
|
import { existsSync as existsSync8 } from "fs";
|
|
18003
|
-
import { copyFile, mkdir as mkdir10, readFile as
|
|
18004
|
-
import { delimiter, dirname as dirname5, join as
|
|
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";
|
|
18005
18424
|
import { randomBytes as randomBytes2 } from "crypto";
|
|
18006
18425
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
18007
18426
|
import { Agent } from "undici";
|
|
@@ -18029,10 +18448,10 @@ async function getAllowedOpenRouterModels() {
|
|
|
18029
18448
|
|
|
18030
18449
|
// src/managers/opencode-manager.ts
|
|
18031
18450
|
var OPENCODE_SHIM_DIR = dirname5(fileURLToPath2(new URL("../../scripts/opencode", import.meta.url)));
|
|
18032
|
-
var OPENCODE_COMMAND_PROTECTION_PLUGIN_SOURCE =
|
|
18033
|
-
var OPENCODE_COMMAND_PROTECTION_PLUGIN_PATH =
|
|
18034
|
-
var OPENCODE_LEGACY_COMMAND_PROTECTION_PLUGIN_PATH =
|
|
18035
|
-
var OPENCODE_CONFIG_PATH =
|
|
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");
|
|
18036
18455
|
var OPENCODE_SERVER_STARTUP_TIMEOUT_MS = 3e4;
|
|
18037
18456
|
var OPENCODE_SLASH_COMMANDS_CACHE_MS = 3e4;
|
|
18038
18457
|
var OPENCODE_HEARTBEAT_TIMEOUT_MS = 6e4;
|
|
@@ -18100,7 +18519,7 @@ function isOpencodeMcpEntry(value) {
|
|
|
18100
18519
|
async function readProvisionedOpencodeMcpConfig() {
|
|
18101
18520
|
let raw;
|
|
18102
18521
|
try {
|
|
18103
|
-
raw = await
|
|
18522
|
+
raw = await readFile11(OPENCODE_CONFIG_PATH, "utf8");
|
|
18104
18523
|
} catch (error) {
|
|
18105
18524
|
if (isRecord(error) && error.code === "ENOENT") return void 0;
|
|
18106
18525
|
console.error("[OpencodeManager] Failed to read Opencode config:", error);
|
|
@@ -18378,6 +18797,9 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
18378
18797
|
finishUpdate();
|
|
18379
18798
|
}
|
|
18380
18799
|
}
|
|
18800
|
+
dispose() {
|
|
18801
|
+
this.stopServer();
|
|
18802
|
+
}
|
|
18381
18803
|
stopServer() {
|
|
18382
18804
|
this.eventAbortController?.abort();
|
|
18383
18805
|
this.server?.close();
|
|
@@ -18733,7 +19155,7 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
18733
19155
|
};
|
|
18734
19156
|
|
|
18735
19157
|
// src/managers/pi-manager.ts
|
|
18736
|
-
import { join as
|
|
19158
|
+
import { join as join23 } from "path";
|
|
18737
19159
|
import {
|
|
18738
19160
|
createAgentSession,
|
|
18739
19161
|
ModelRegistry,
|
|
@@ -41558,7 +41980,7 @@ async function probeMcpEndpoint(url3) {
|
|
|
41558
41980
|
|
|
41559
41981
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+f2da34192be1730e/node_modules/pi-mcp-adapter/npx-resolver.ts
|
|
41560
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";
|
|
41561
|
-
import { join as
|
|
41983
|
+
import { join as join17, dirname as dirname6, extname as extname2, resolve as resolve2, sep } from "path";
|
|
41562
41984
|
|
|
41563
41985
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+f2da34192be1730e/node_modules/pi-mcp-adapter/abort.ts
|
|
41564
41986
|
function throwIfAborted(signal) {
|
|
@@ -41715,7 +42137,7 @@ function resolveFromNpmCache(packageSpec, binName) {
|
|
|
41715
42137
|
const { packageName, exactVersion } = parsedSpec;
|
|
41716
42138
|
const packageDir = findCachedPackageDir(cacheDir, packageName, exactVersion);
|
|
41717
42139
|
if (!packageDir) return null;
|
|
41718
|
-
const packageJsonPath =
|
|
42140
|
+
const packageJsonPath = join17(packageDir, "package.json");
|
|
41719
42141
|
if (!existsSync9(packageJsonPath)) return null;
|
|
41720
42142
|
let pkg = null;
|
|
41721
42143
|
try {
|
|
@@ -41749,7 +42171,7 @@ function resolveFromNpmCache(packageSpec, binName) {
|
|
|
41749
42171
|
}
|
|
41750
42172
|
if (!binRel) return null;
|
|
41751
42173
|
const nodeModulesDir = findNodeModulesDir(packageDir);
|
|
41752
|
-
const binLink = chosenBinName ?
|
|
42174
|
+
const binLink = chosenBinName ? join17(nodeModulesDir, ".bin", chosenBinName) : null;
|
|
41753
42175
|
let resolvedBin = binLink && existsSync9(binLink) ? safeRealpath(binLink) : "";
|
|
41754
42176
|
if (!resolvedBin) {
|
|
41755
42177
|
resolvedBin = resolve2(packageDir, binRel);
|
|
@@ -41851,17 +42273,17 @@ function defaultBinName(packageName) {
|
|
|
41851
42273
|
return packageName;
|
|
41852
42274
|
}
|
|
41853
42275
|
function findCachedPackageDir(cacheDir, packageName, exactVersion) {
|
|
41854
|
-
const npxDir =
|
|
42276
|
+
const npxDir = join17(cacheDir, "_npx");
|
|
41855
42277
|
if (!existsSync9(npxDir)) return null;
|
|
41856
42278
|
const packagePathParts = packageName.startsWith("@") ? packageName.split("/") : [packageName];
|
|
41857
42279
|
const candidates = readdirSync2(npxDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => {
|
|
41858
|
-
const full =
|
|
42280
|
+
const full = join17(npxDir, entry.name);
|
|
41859
42281
|
const mtime = safeStatMtime(full);
|
|
41860
42282
|
return { name: entry.name, mtime };
|
|
41861
42283
|
}).sort((a, b) => b.mtime - a.mtime);
|
|
41862
42284
|
for (const entry of candidates) {
|
|
41863
|
-
const pkgDir =
|
|
41864
|
-
const packageJsonPath =
|
|
42285
|
+
const pkgDir = join17(npxDir, entry.name, "node_modules", ...packagePathParts);
|
|
42286
|
+
const packageJsonPath = join17(pkgDir, "package.json");
|
|
41865
42287
|
if (!existsSync9(packageJsonPath)) continue;
|
|
41866
42288
|
if (exactVersion) {
|
|
41867
42289
|
try {
|
|
@@ -41881,7 +42303,7 @@ function findNodeModulesDir(packageDir) {
|
|
|
41881
42303
|
if (idx >= 0) {
|
|
41882
42304
|
return parts.slice(0, idx + 1).join(sep);
|
|
41883
42305
|
}
|
|
41884
|
-
return
|
|
42306
|
+
return join17(packageDir, "..");
|
|
41885
42307
|
}
|
|
41886
42308
|
function detectJsBinary(binPath) {
|
|
41887
42309
|
const ext = extname2(binPath).toLowerCase();
|
|
@@ -42073,7 +42495,7 @@ import { spawnSync } from "child_process";
|
|
|
42073
42495
|
import { createHash as createHash3 } from "crypto";
|
|
42074
42496
|
import { createRequire } from "module";
|
|
42075
42497
|
import { readFileSync as readFileSync3, existsSync as existsSync10, rmSync as rmSync2 } from "fs";
|
|
42076
|
-
import { dirname as dirname7, join as
|
|
42498
|
+
import { dirname as dirname7, join as join18 } from "path";
|
|
42077
42499
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
42078
42500
|
var require2 = createRequire(import.meta.url);
|
|
42079
42501
|
var AUTH_SECRET_SERVICE = "pi-mcp-adapter.oauth";
|
|
@@ -42229,7 +42651,7 @@ function loadKeyringNativeBindingFallback(keyringRequire, platform4, arch3) {
|
|
|
42229
42651
|
for (const target of targets) {
|
|
42230
42652
|
try {
|
|
42231
42653
|
const packageJsonPath = keyringRequire.resolve(`${target.packageName}/package.json`);
|
|
42232
|
-
return keyringRequire(
|
|
42654
|
+
return keyringRequire(join18(dirname7(packageJsonPath), target.bindingFile));
|
|
42233
42655
|
} catch (error) {
|
|
42234
42656
|
lastError = error;
|
|
42235
42657
|
}
|
|
@@ -42334,7 +42756,7 @@ function getServerDir(serverName, options) {
|
|
|
42334
42756
|
throw new Error(`Invalid MCP server name: ${JSON.stringify(serverName)}`);
|
|
42335
42757
|
}
|
|
42336
42758
|
const storageKey = getAuthEntryAccount(serverName);
|
|
42337
|
-
return
|
|
42759
|
+
return join18(getAuthBaseDir(options), storageKey);
|
|
42338
42760
|
}
|
|
42339
42761
|
function getAuthEntryAccount(serverName) {
|
|
42340
42762
|
if (typeof serverName !== "string") {
|
|
@@ -42343,7 +42765,7 @@ function getAuthEntryAccount(serverName) {
|
|
|
42343
42765
|
return `sha256-${createHash3("sha256").update(serverName, "utf8").digest("hex")}`;
|
|
42344
42766
|
}
|
|
42345
42767
|
function getAuthEntryFilePath(serverName, options) {
|
|
42346
|
-
return
|
|
42768
|
+
return join18(getServerDir(serverName, options), "tokens.json");
|
|
42347
42769
|
}
|
|
42348
42770
|
function parseJsonPayload(serverName, payload, source) {
|
|
42349
42771
|
try {
|
|
@@ -44946,7 +45368,7 @@ async function shutdownOAuth(runtime = legacyRuntime) {
|
|
|
44946
45368
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+f2da34192be1730e/node_modules/pi-mcp-adapter/mcp-bearer-store.ts
|
|
44947
45369
|
import { createHash as createHash4 } from "crypto";
|
|
44948
45370
|
import { createRequire as createRequire2 } from "module";
|
|
44949
|
-
import { dirname as dirname8, join as
|
|
45371
|
+
import { dirname as dirname8, join as join19 } from "path";
|
|
44950
45372
|
var require3 = createRequire2(import.meta.url);
|
|
44951
45373
|
var BEARER_SECRET_SERVICE = "pi-mcp-adapter.bearer";
|
|
44952
45374
|
var TEST_AUTH_STORE_ENV2 = "PI_MCP_ADAPTER_TEST_AUTH_STORE";
|
|
@@ -45048,7 +45470,7 @@ function loadKeyringNativeBindingFallback2(keyringRequire, platform4, arch3) {
|
|
|
45048
45470
|
for (const target of targets) {
|
|
45049
45471
|
try {
|
|
45050
45472
|
const packageJsonPath = keyringRequire.resolve(`${target.packageName}/package.json`);
|
|
45051
|
-
return keyringRequire(
|
|
45473
|
+
return keyringRequire(join19(dirname8(packageJsonPath), target.bindingFile));
|
|
45052
45474
|
} catch (error) {
|
|
45053
45475
|
lastError = error;
|
|
45054
45476
|
}
|
|
@@ -49515,7 +49937,7 @@ async function openMcpAuthPanel(state, pi, ctx, configOverridePath) {
|
|
|
49515
49937
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+f2da34192be1730e/node_modules/pi-mcp-adapter/tool-registrar.ts
|
|
49516
49938
|
import { mkdtempSync, rmSync as rmSync3, writeFileSync as writeFileSync5 } from "fs";
|
|
49517
49939
|
import { tmpdir } from "os";
|
|
49518
|
-
import { join as
|
|
49940
|
+
import { join as join20 } from "path";
|
|
49519
49941
|
var MAX_BINARY_RESOURCE_BYTES = 10 * 1024 * 1024;
|
|
49520
49942
|
var MAX_SESSION_RESOURCE_BYTES = 100 * 1024 * 1024;
|
|
49521
49943
|
var MAX_SESSION_RESOURCE_FILES = 1e4;
|
|
@@ -49622,11 +50044,11 @@ function materializeBinaryResource(resource, scope) {
|
|
|
49622
50044
|
return omitBinaryResource(resource, "session resource limit reached");
|
|
49623
50045
|
}
|
|
49624
50046
|
try {
|
|
49625
|
-
session.directory ??= mkdtempSync(
|
|
50047
|
+
session.directory ??= mkdtempSync(join20(tmpdir(), "pi-mcp-resource-"));
|
|
49626
50048
|
} catch {
|
|
49627
50049
|
return omitBinaryResource(resource, "could not be saved");
|
|
49628
50050
|
}
|
|
49629
|
-
const filePath =
|
|
50051
|
+
const filePath = join20(session.directory, `resource-${++session.sequence}.bin`);
|
|
49630
50052
|
session.bytes += decodedBytes;
|
|
49631
50053
|
session.files += 1;
|
|
49632
50054
|
try {
|
|
@@ -49719,7 +50141,7 @@ function stringifyStructuredContent(value) {
|
|
|
49719
50141
|
import { randomBytes as randomBytes3 } from "crypto";
|
|
49720
50142
|
import { mkdtemp, rm as rm5, writeFile as writeFile7 } from "fs/promises";
|
|
49721
50143
|
import { tmpdir as tmpdir2 } from "os";
|
|
49722
|
-
import { dirname as dirname11, join as
|
|
50144
|
+
import { dirname as dirname11, join as join21 } from "path";
|
|
49723
50145
|
var DEFAULT_MCP_OUTPUT_MAX_BYTES = 50 * 1024;
|
|
49724
50146
|
var DEFAULT_MCP_OUTPUT_MAX_LINES = 2e3;
|
|
49725
50147
|
var DEFAULT_MCP_DETAILS_MAX_BYTES = 16 * 1024;
|
|
@@ -50027,8 +50449,8 @@ function serializedObjectEntryBytes(key, value, hasPrevious) {
|
|
|
50027
50449
|
}
|
|
50028
50450
|
async function saveArtifact(kind, text) {
|
|
50029
50451
|
try {
|
|
50030
|
-
const dir = await mkdtemp(
|
|
50031
|
-
const path8 =
|
|
50452
|
+
const dir = await mkdtemp(join21(tmpdir2(), "pi-mcp-output-"));
|
|
50453
|
+
const path8 = join21(dir, `${kind}-${randomBytes3(4).toString("hex")}.txt`);
|
|
50032
50454
|
await writeFile7(path8, text, { encoding: "utf8", mode: 384 });
|
|
50033
50455
|
return { path: path8 };
|
|
50034
50456
|
} catch (error) {
|
|
@@ -51675,7 +52097,7 @@ function sendText(res, status, text) {
|
|
|
51675
52097
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+f2da34192be1730e/node_modules/pi-mcp-adapter/glimpse-ui.ts
|
|
51676
52098
|
import { existsSync as existsSync13 } from "fs";
|
|
51677
52099
|
import { execFileSync as execFileSync2 } from "child_process";
|
|
51678
|
-
import { join as
|
|
52100
|
+
import { join as join22, dirname as dirname12 } from "path";
|
|
51679
52101
|
import { platform as platform2 } from "os";
|
|
51680
52102
|
import { createRequire as createRequire3 } from "module";
|
|
51681
52103
|
var glimpseAvailable = null;
|
|
@@ -51697,20 +52119,20 @@ function getGlimpseBinaryPath() {
|
|
|
51697
52119
|
try {
|
|
51698
52120
|
const require6 = createRequire3(import.meta.url);
|
|
51699
52121
|
const glimpseuiPath = require6.resolve("glimpseui");
|
|
51700
|
-
const binaryPath =
|
|
52122
|
+
const binaryPath = join22(dirname12(glimpseuiPath), "glimpse");
|
|
51701
52123
|
if (existsSync13(binaryPath)) return binaryPath;
|
|
51702
52124
|
} catch {
|
|
51703
52125
|
}
|
|
51704
52126
|
try {
|
|
51705
52127
|
const globalRoot = execFileSync2("npm", ["root", "-g"], { encoding: "utf-8" }).trim();
|
|
51706
|
-
const binaryPath =
|
|
52128
|
+
const binaryPath = join22(globalRoot, "glimpseui", "src", "glimpse");
|
|
51707
52129
|
if (existsSync13(binaryPath)) return binaryPath;
|
|
51708
52130
|
} catch {
|
|
51709
52131
|
}
|
|
51710
52132
|
return null;
|
|
51711
52133
|
}
|
|
51712
52134
|
async function openGlimpseWindow(html, options) {
|
|
51713
|
-
const modulePath = resolvedBinaryPath ?
|
|
52135
|
+
const modulePath = resolvedBinaryPath ? join22(dirname12(resolvedBinaryPath), "glimpse.mjs") : "glimpseui";
|
|
51714
52136
|
const glimpse = await import(modulePath);
|
|
51715
52137
|
let active = true;
|
|
51716
52138
|
const win = glimpse.open(html, {
|
|
@@ -59638,6 +60060,8 @@ var PiManager = class extends CodingAgentManager {
|
|
|
59638
60060
|
this.unsubscribe = null;
|
|
59639
60061
|
const session = this.session;
|
|
59640
60062
|
this.session = null;
|
|
60063
|
+
this.modelRuntime = null;
|
|
60064
|
+
this.providerApiKey = null;
|
|
59641
60065
|
if (session) {
|
|
59642
60066
|
await session.extensionRunner.emit({ type: "session_shutdown", reason: "quit" }).catch(() => {
|
|
59643
60067
|
});
|
|
@@ -59780,7 +60204,7 @@ var PiManager = class extends CodingAgentManager {
|
|
|
59780
60204
|
}
|
|
59781
60205
|
const resourceLoader = new DefaultResourceLoader({
|
|
59782
60206
|
cwd: this.workingDirectory,
|
|
59783
|
-
agentDir:
|
|
60207
|
+
agentDir: join23(ENGINE_ENV.HOME_DIR, ".pi", "agent"),
|
|
59784
60208
|
extensionFactories,
|
|
59785
60209
|
appendSystemPrompt: [instructions]
|
|
59786
60210
|
});
|
|
@@ -59801,6 +60225,7 @@ var PiManager = class extends CodingAgentManager {
|
|
|
59801
60225
|
this.activeSessionFile = sessionManager.getSessionFile() ?? null;
|
|
59802
60226
|
await this.onSaveSessionId(this.activeSessionFile);
|
|
59803
60227
|
this.unsubscribe = this.session.subscribe((event) => this.handleEvent(event));
|
|
60228
|
+
await this.session.bindExtensions({});
|
|
59804
60229
|
return this.session;
|
|
59805
60230
|
}
|
|
59806
60231
|
async getModelRuntime() {
|
|
@@ -59838,10 +60263,10 @@ var PiManager = class extends CodingAgentManager {
|
|
|
59838
60263
|
};
|
|
59839
60264
|
|
|
59840
60265
|
// src/services/chat/chat-commands.ts
|
|
59841
|
-
import { mkdir as mkdir12, readFile as
|
|
59842
|
-
import { join as
|
|
60266
|
+
import { mkdir as mkdir12, readFile as readFile12, rm as rm6 } from "fs/promises";
|
|
60267
|
+
import { join as join24 } from "path";
|
|
59843
60268
|
import { z as z3 } from "zod";
|
|
59844
|
-
var CHAT_COMMANDS_DIR =
|
|
60269
|
+
var CHAT_COMMANDS_DIR = join24(ENGINE_DIR, "chat-commands");
|
|
59845
60270
|
var ACCEPTED_RETENTION_MS = 8 * 24 * 60 * 6e4;
|
|
59846
60271
|
var MAX_REMOVED_MESSAGE_IDS = 6e3;
|
|
59847
60272
|
var queuedMessageSchema = sendChatMessageRequestSchema.extend({ id: z3.string(), queuedAt: z3.string() });
|
|
@@ -59870,7 +60295,7 @@ var ChatCommands = class _ChatCommands {
|
|
|
59870
60295
|
state;
|
|
59871
60296
|
writing = Promise.resolve();
|
|
59872
60297
|
static async load(chatId) {
|
|
59873
|
-
const content = await
|
|
60298
|
+
const content = await readFile12(join24(CHAT_COMMANDS_DIR, `${chatId}.json`), "utf-8").catch((error) => {
|
|
59874
60299
|
if (error.code === "ENOENT") return null;
|
|
59875
60300
|
throw error;
|
|
59876
60301
|
});
|
|
@@ -59900,13 +60325,13 @@ var ChatCommands = class _ChatCommands {
|
|
|
59900
60325
|
this.writing = this.writing.catch(() => {
|
|
59901
60326
|
}).then(async () => {
|
|
59902
60327
|
await mkdir12(CHAT_COMMANDS_DIR, { recursive: true, mode: 448 });
|
|
59903
|
-
await atomicWriteFile(
|
|
60328
|
+
await atomicWriteFile(join24(CHAT_COMMANDS_DIR, `${this.chatId}.json`), data, { mode: 384, flush: true });
|
|
59904
60329
|
});
|
|
59905
60330
|
return this.writing;
|
|
59906
60331
|
}
|
|
59907
60332
|
remove() {
|
|
59908
60333
|
this.writing = this.writing.catch(() => {
|
|
59909
|
-
}).then(() => rm6(
|
|
60334
|
+
}).then(() => rm6(join24(CHAT_COMMANDS_DIR, `${this.chatId}.json`), { force: true }));
|
|
59910
60335
|
return this.writing;
|
|
59911
60336
|
}
|
|
59912
60337
|
};
|
|
@@ -59926,13 +60351,13 @@ async function uploadAnalytics(endpoint, body) {
|
|
|
59926
60351
|
import {
|
|
59927
60352
|
appendFile as appendFile3,
|
|
59928
60353
|
mkdir as mkdir13,
|
|
59929
|
-
readFile as
|
|
59930
|
-
readdir as
|
|
60354
|
+
readFile as readFile13,
|
|
60355
|
+
readdir as readdir7,
|
|
59931
60356
|
rename as rename2,
|
|
59932
60357
|
unlink
|
|
59933
60358
|
} from "fs/promises";
|
|
59934
60359
|
import { existsSync as existsSync14, readFileSync as readFileSync5, readdirSync as readdirSync3 } from "fs";
|
|
59935
|
-
import { join as
|
|
60360
|
+
import { join as join25 } from "path";
|
|
59936
60361
|
var MAX_FAILED_RECORDS = 500;
|
|
59937
60362
|
var FLUSH_DEBOUNCE_MS = 15e3;
|
|
59938
60363
|
var MAX_UPLOADED_SEGMENTS = 50;
|
|
@@ -59944,7 +60369,7 @@ var AnalyticsRecordBuffer = class {
|
|
|
59944
60369
|
options.storageName,
|
|
59945
60370
|
...options.legacyStorageNames ?? []
|
|
59946
60371
|
];
|
|
59947
|
-
this.liveFile =
|
|
60372
|
+
this.liveFile = join25(ENGINE_DIR, `${options.storageName}.jsonl`);
|
|
59948
60373
|
this.segmentFilePatterns = this.storageNames.map(
|
|
59949
60374
|
(storageName) => new RegExp(`^${storageName}\\.(\\d+)\\.jsonl$`)
|
|
59950
60375
|
);
|
|
@@ -59982,7 +60407,7 @@ var AnalyticsRecordBuffer = class {
|
|
|
59982
60407
|
if (!existsSync14(ENGINE_DIR)) return [];
|
|
59983
60408
|
return readdirSync3(ENGINE_DIR, { withFileTypes: true }).filter((entry) => entry.isFile() && this.storageNames.some(
|
|
59984
60409
|
(storageName) => entry.name === `${storageName}.jsonl` || entry.name.startsWith(`${storageName}.`) && (entry.name.endsWith(".jsonl") || entry.name.endsWith(`.jsonl${UPLOADED_SUFFIX}`))
|
|
59985
|
-
)).map(({ name }) => name).sort().flatMap((name) => this.parseRecords(readFileSync5(
|
|
60410
|
+
)).map(({ name }) => name).sort().flatMap((name) => this.parseRecords(readFileSync5(join25(ENGINE_DIR, name), "utf-8"))).map((record3) => {
|
|
59986
60411
|
const recordId = this.options.getRecordId?.(record3);
|
|
59987
60412
|
if (recordId) this.recordIds.add(recordId);
|
|
59988
60413
|
return record3;
|
|
@@ -60017,18 +60442,18 @@ var AnalyticsRecordBuffer = class {
|
|
|
60017
60442
|
}
|
|
60018
60443
|
for (const storageName of this.storageNames) {
|
|
60019
60444
|
await rename2(
|
|
60020
|
-
|
|
60021
|
-
|
|
60445
|
+
join25(ENGINE_DIR, `${storageName}.jsonl`),
|
|
60446
|
+
join25(ENGINE_DIR, `${storageName}.${Date.now()}.jsonl`)
|
|
60022
60447
|
).catch(() => {
|
|
60023
60448
|
});
|
|
60024
60449
|
}
|
|
60025
|
-
const entries = await
|
|
60450
|
+
const entries = await readdir7(ENGINE_DIR).catch(() => []);
|
|
60026
60451
|
let flushed = 0;
|
|
60027
60452
|
let failed = 0;
|
|
60028
60453
|
for (const entry of entries) {
|
|
60029
60454
|
if (!this.segmentFilePatterns.some((pattern) => pattern.test(entry))) continue;
|
|
60030
60455
|
try {
|
|
60031
|
-
await this.uploadSegment(
|
|
60456
|
+
await this.uploadSegment(join25(ENGINE_DIR, entry));
|
|
60032
60457
|
flushed++;
|
|
60033
60458
|
} catch (error) {
|
|
60034
60459
|
failed++;
|
|
@@ -60057,14 +60482,14 @@ var AnalyticsRecordBuffer = class {
|
|
|
60057
60482
|
(storageName) => entry.startsWith(`${storageName}.`)
|
|
60058
60483
|
) && entry.endsWith(UPLOADED_SUFFIX)).sort();
|
|
60059
60484
|
for (const entry of uploaded.slice(0, -MAX_UPLOADED_SEGMENTS)) {
|
|
60060
|
-
await unlink(
|
|
60485
|
+
await unlink(join25(ENGINE_DIR, entry)).catch(() => {
|
|
60061
60486
|
});
|
|
60062
60487
|
}
|
|
60063
60488
|
}
|
|
60064
60489
|
return { flushed, failed };
|
|
60065
60490
|
}
|
|
60066
60491
|
async uploadSegment(filePath) {
|
|
60067
|
-
const records = this.parseRecords(await
|
|
60492
|
+
const records = this.parseRecords(await readFile13(filePath, "utf-8"));
|
|
60068
60493
|
if (records.length > 0) await this.options.upload(records);
|
|
60069
60494
|
await rename2(filePath, `${filePath}${UPLOADED_SUFFIX}`).catch(() => {
|
|
60070
60495
|
});
|
|
@@ -60082,7 +60507,7 @@ var AnalyticsRecordBuffer = class {
|
|
|
60082
60507
|
};
|
|
60083
60508
|
|
|
60084
60509
|
// src/analytics/agent/activity/skill-mcp-call-extractor.ts
|
|
60085
|
-
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"]);
|
|
60086
60511
|
function mcpNameFromToolCall(message) {
|
|
60087
60512
|
const parsedName = parseMcpToolName(message.tool);
|
|
60088
60513
|
if (parsedName) return parsedName.server;
|
|
@@ -60643,6 +61068,21 @@ var CursorTokenUsageService = class {
|
|
|
60643
61068
|
}
|
|
60644
61069
|
};
|
|
60645
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
|
+
|
|
60646
61086
|
// src/analytics/token-usage/muse/index.ts
|
|
60647
61087
|
var MuseTokenUsageService = class {
|
|
60648
61088
|
record(event) {
|
|
@@ -60720,6 +61160,8 @@ function createAgentTokenUsageService(harness) {
|
|
|
60720
61160
|
return new CodexTokenUsageService();
|
|
60721
61161
|
case AGENT.CURSOR:
|
|
60722
61162
|
return new CursorTokenUsageService();
|
|
61163
|
+
case AGENT.GEMINI:
|
|
61164
|
+
return new GeminiTokenUsageService();
|
|
60723
61165
|
case AGENT.MUSE:
|
|
60724
61166
|
return new MuseTokenUsageService();
|
|
60725
61167
|
case AGENT.OPENCODE:
|
|
@@ -60885,9 +61327,9 @@ var KeepAliveService = class _KeepAliveService {
|
|
|
60885
61327
|
var keepAliveService = new KeepAliveService();
|
|
60886
61328
|
|
|
60887
61329
|
// src/services/canvas-service.ts
|
|
60888
|
-
import { readdir as
|
|
61330
|
+
import { readdir as readdir8, readFile as readFile15, stat as stat3 } from "fs/promises";
|
|
60889
61331
|
import { homedir as homedir7 } from "os";
|
|
60890
|
-
import { join as
|
|
61332
|
+
import { join as join26 } from "path";
|
|
60891
61333
|
|
|
60892
61334
|
// src/utils/contained-file.ts
|
|
60893
61335
|
import { realpath, stat as stat2 } from "fs/promises";
|
|
@@ -60913,9 +61355,9 @@ function fileRevision(content) {
|
|
|
60913
61355
|
}
|
|
60914
61356
|
|
|
60915
61357
|
// src/utils/revisioned-text-file.ts
|
|
60916
|
-
import { readFile as
|
|
61358
|
+
import { readFile as readFile14 } from "fs/promises";
|
|
60917
61359
|
async function writeRevisionedTextFile(filePath, content, expectedRevision) {
|
|
60918
|
-
const current = await
|
|
61360
|
+
const current = await readFile14(filePath, "utf8");
|
|
60919
61361
|
const revision = fileRevision(current);
|
|
60920
61362
|
if (revision !== expectedRevision) {
|
|
60921
61363
|
return {
|
|
@@ -60929,15 +61371,15 @@ async function writeRevisionedTextFile(filePath, content, expectedRevision) {
|
|
|
60929
61371
|
|
|
60930
61372
|
// src/services/canvas-service.ts
|
|
60931
61373
|
var GLOBAL_CANVAS_DIRECTORIES = [
|
|
60932
|
-
|
|
60933
|
-
|
|
60934
|
-
|
|
61374
|
+
join26(homedir7(), ".claude", "plans"),
|
|
61375
|
+
join26(process.env.XDG_DATA_HOME ?? join26(homedir7(), ".local", "share"), "opencode", "plans"),
|
|
61376
|
+
join26(homedir7(), ".replicas", "canvas")
|
|
60935
61377
|
];
|
|
60936
61378
|
async function canvasDirectories(repositories) {
|
|
60937
61379
|
repositories ??= await gitService.listRepositories().catch(() => []);
|
|
60938
61380
|
return [
|
|
60939
61381
|
...GLOBAL_CANVAS_DIRECTORIES,
|
|
60940
|
-
...repositories.map((repository) =>
|
|
61382
|
+
...repositories.map((repository) => join26(repository.path, ".opencode", "plans"))
|
|
60941
61383
|
];
|
|
60942
61384
|
}
|
|
60943
61385
|
var CanvasService = class {
|
|
@@ -60955,14 +61397,14 @@ var CanvasService = class {
|
|
|
60955
61397
|
if (!current) continue;
|
|
60956
61398
|
let entries;
|
|
60957
61399
|
try {
|
|
60958
|
-
entries = await
|
|
61400
|
+
entries = await readdir8(current.directory, { withFileTypes: true });
|
|
60959
61401
|
} catch {
|
|
60960
61402
|
continue;
|
|
60961
61403
|
}
|
|
60962
61404
|
for (const entry of entries) {
|
|
60963
61405
|
if (entry.name.startsWith(".")) continue;
|
|
60964
61406
|
const filename = current.relativePath ? `${current.relativePath}/${entry.name}` : entry.name;
|
|
60965
|
-
const filePath =
|
|
61407
|
+
const filePath = join26(current.directory, entry.name);
|
|
60966
61408
|
if (entry.isDirectory()) {
|
|
60967
61409
|
pending.push({ directory: filePath, relativePath: filename });
|
|
60968
61410
|
continue;
|
|
@@ -60986,7 +61428,7 @@ var CanvasService = class {
|
|
|
60986
61428
|
const safe = sanitizeCanvasFilename(filename);
|
|
60987
61429
|
if (!safe) return null;
|
|
60988
61430
|
for (const directory of await this.directories()) {
|
|
60989
|
-
const path8 =
|
|
61431
|
+
const path8 = join26(directory, safe);
|
|
60990
61432
|
const stats = await stat3(path8).catch(() => null);
|
|
60991
61433
|
if (stats?.isFile()) {
|
|
60992
61434
|
return {
|
|
@@ -61005,7 +61447,7 @@ var CanvasService = class {
|
|
|
61005
61447
|
if (!item) return null;
|
|
61006
61448
|
const { path: path8, ...file } = item;
|
|
61007
61449
|
if (file.sizeBytes > maxBytes) return { ...file, tooLarge: true };
|
|
61008
|
-
const bytes = await
|
|
61450
|
+
const bytes = await readFile15(path8).catch(() => null);
|
|
61009
61451
|
return bytes ? { ...file, bytes } : null;
|
|
61010
61452
|
}
|
|
61011
61453
|
async getItem(filename) {
|
|
@@ -61145,15 +61587,15 @@ async function reconcileCanvasItems(filenames) {
|
|
|
61145
61587
|
|
|
61146
61588
|
// src/services/upload-chat-transcripts.ts
|
|
61147
61589
|
import { createHash as createHash8 } from "crypto";
|
|
61148
|
-
import { readFile as
|
|
61590
|
+
import { readFile as readFile16, readdir as readdir9 } from "fs/promises";
|
|
61149
61591
|
import { Readable } from "stream";
|
|
61150
|
-
import { basename as basename3, join as
|
|
61592
|
+
import { basename as basename3, join as join28 } from "path";
|
|
61151
61593
|
|
|
61152
61594
|
// src/services/chat/chat-senders.ts
|
|
61153
|
-
import { join as
|
|
61154
|
-
var CHAT_SENDERS_DIR =
|
|
61595
|
+
import { join as join27 } from "path";
|
|
61596
|
+
var CHAT_SENDERS_DIR = join27(ENGINE_DIR, "chat-senders");
|
|
61155
61597
|
function chatMessageSendersFilePath(chatId) {
|
|
61156
|
-
return
|
|
61598
|
+
return join27(CHAT_SENDERS_DIR, `${chatId}.jsonl`);
|
|
61157
61599
|
}
|
|
61158
61600
|
function parseChatMessageSendersJsonl(content) {
|
|
61159
61601
|
return content.split("\n").flatMap((line) => {
|
|
@@ -61229,7 +61671,7 @@ async function flushAllChatTranscripts(chatsById = /* @__PURE__ */ new Map(), ca
|
|
|
61229
61671
|
for (const dir of HISTORY_DIRS) {
|
|
61230
61672
|
let entries;
|
|
61231
61673
|
try {
|
|
61232
|
-
entries = await
|
|
61674
|
+
entries = await readdir9(dir);
|
|
61233
61675
|
} catch {
|
|
61234
61676
|
continue;
|
|
61235
61677
|
}
|
|
@@ -61239,7 +61681,7 @@ async function flushAllChatTranscripts(chatsById = /* @__PURE__ */ new Map(), ca
|
|
|
61239
61681
|
const chat = chatsById.get(chatId);
|
|
61240
61682
|
if (!shouldFlushChatTranscript(dir, chat, chatsById, Boolean(capture))) continue;
|
|
61241
61683
|
tasks.push(
|
|
61242
|
-
uploadChatTranscript(chatId,
|
|
61684
|
+
uploadChatTranscript(chatId, join28(dir, entry), chat, capture).then(async (artifact) => {
|
|
61243
61685
|
flushed++;
|
|
61244
61686
|
if (artifact && capture) revisions.push(artifact);
|
|
61245
61687
|
await onUploaded?.(chatId, artifact).catch((err) => {
|
|
@@ -61308,7 +61750,7 @@ async function uploadOpenedTranscript(chatId, opened, historyVersion, chat, capt
|
|
|
61308
61750
|
} : {};
|
|
61309
61751
|
try {
|
|
61310
61752
|
metadata.senders = parseChatMessageSendersJsonl(
|
|
61311
|
-
await
|
|
61753
|
+
await readFile16(chatMessageSendersFilePath(chatId), "utf-8")
|
|
61312
61754
|
);
|
|
61313
61755
|
} catch (error) {
|
|
61314
61756
|
if (!(error && typeof error === "object" && "code" in error && error.code === "ENOENT")) throw error;
|
|
@@ -61397,8 +61839,8 @@ async function flushRepoState() {
|
|
|
61397
61839
|
|
|
61398
61840
|
// src/services/upload-engine-logs.ts
|
|
61399
61841
|
import { createReadStream } from "fs";
|
|
61400
|
-
import { readdir as
|
|
61401
|
-
import { join as
|
|
61842
|
+
import { readdir as readdir10, stat as stat4 } from "fs/promises";
|
|
61843
|
+
import { join as join29 } from "path";
|
|
61402
61844
|
var MAX_ENGINE_LOG_FLUSH_SESSIONS = 10;
|
|
61403
61845
|
var MAX_ENGINE_LOG_FLUSH_BYTES = 5 * 1024 * 1024;
|
|
61404
61846
|
var ENGINE_LOG_FLUSH_TIMEOUT_MS = 2e4;
|
|
@@ -61408,7 +61850,7 @@ async function flushAllEngineLogs() {
|
|
|
61408
61850
|
let failed = 0;
|
|
61409
61851
|
const deadline = Date.now() + ENGINE_LOG_FLUSH_TIMEOUT_MS;
|
|
61410
61852
|
await runBeforeDeadline((signal) => engineLogger.flush(signal), deadline);
|
|
61411
|
-
const files = await runBeforeDeadline(() =>
|
|
61853
|
+
const files = await runBeforeDeadline(() => readdir10(LOG_DIR), deadline).catch(() => []);
|
|
61412
61854
|
const currentFilename = engineLogger.sessionId ? `${engineLogger.sessionId}.log` : null;
|
|
61413
61855
|
const filenames = files.filter((filename) => {
|
|
61414
61856
|
if (!filename.endsWith(".log")) return false;
|
|
@@ -61427,7 +61869,7 @@ async function flushAllEngineLogs() {
|
|
|
61427
61869
|
const candidates = (await Promise.all(filenames.slice(0, MAX_ENGINE_LOG_FLUSH_SESSIONS).map(async (filename) => {
|
|
61428
61870
|
try {
|
|
61429
61871
|
const sessionId = filename.slice(0, -".log".length);
|
|
61430
|
-
const filePath =
|
|
61872
|
+
const filePath = join29(LOG_DIR, filename);
|
|
61431
61873
|
const fileStat = await runBeforeDeadline(() => stat4(filePath), deadline);
|
|
61432
61874
|
if (!fileStat.isFile()) {
|
|
61433
61875
|
skipped++;
|
|
@@ -61524,9 +61966,9 @@ async function uploadEngineLog(input, timeoutMs) {
|
|
|
61524
61966
|
|
|
61525
61967
|
// src/services/chat/fork-handoff.ts
|
|
61526
61968
|
import { createHash as createHash9 } from "crypto";
|
|
61527
|
-
import { mkdir as mkdir14, readFile as
|
|
61969
|
+
import { mkdir as mkdir14, readFile as readFile17, writeFile as writeFile8 } from "fs/promises";
|
|
61528
61970
|
import { homedir as homedir8 } from "os";
|
|
61529
|
-
import { join as
|
|
61971
|
+
import { join as join30 } from "path";
|
|
61530
61972
|
var EXCERPT_MAX_CHARS = 24e3;
|
|
61531
61973
|
var CONVERSATION_UPDATE_MAX_CHARS = 8e3;
|
|
61532
61974
|
var PULL_REQUEST_DECISIONS_MAX_CHARS = 4e3;
|
|
@@ -61589,7 +62031,7 @@ ${text}` : null;
|
|
|
61589
62031
|
}
|
|
61590
62032
|
async function buildForkHandoff(input) {
|
|
61591
62033
|
const sources = await Promise.all(input.segments.map(async (segment, index) => {
|
|
61592
|
-
const rawHistoryPath =
|
|
62034
|
+
const rawHistoryPath = join30(HISTORY_DIR_BY_PROVIDER[segment.provider], `${segment.chatId}.jsonl`);
|
|
61593
62035
|
const { content, truncated: truncated2 } = await readHistoryTail(rawHistoryPath, MAX_SANITIZED_SOURCE_BYTES, segment.openHistory);
|
|
61594
62036
|
const last = index === input.segments.length - 1;
|
|
61595
62037
|
const blocks2 = canonicalizeChatTranscriptBlocks(content, segment.provider, segment.senders, last ? input.beforeMessageId : void 0).filter((block) => !block.startsWith("## Agent reasoning"));
|
|
@@ -61603,9 +62045,9 @@ async function buildForkHandoff(input) {
|
|
|
61603
62045
|
const start = blocks.findLastIndex((block) => block.startsWith("## User") && ++turns === input.turnLimit);
|
|
61604
62046
|
blocks = blocks.slice(Math.max(0, start));
|
|
61605
62047
|
}
|
|
61606
|
-
const forkDir =
|
|
62048
|
+
const forkDir = join30(FORKS_DIR, input.targetChatId);
|
|
61607
62049
|
await mkdir14(forkDir, { recursive: true });
|
|
61608
|
-
const transcriptPath =
|
|
62050
|
+
const transcriptPath = join30(forkDir, input.transcriptName ?? "source-transcript.md");
|
|
61609
62051
|
const rawHistoryPaths = sources.map((source) => source.rawHistoryPath);
|
|
61610
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.` : ""}_
|
|
61611
62053
|
|
|
@@ -61624,7 +62066,7 @@ async function buildForkHandoff(input) {
|
|
|
61624
62066
|
};
|
|
61625
62067
|
}
|
|
61626
62068
|
async function readPullRequestDecisions(notesPath) {
|
|
61627
|
-
const notes = await
|
|
62069
|
+
const notes = await readFile17(notesPath.replace(/^~(?=\/)/, homedir8()), "utf-8").catch(() => "");
|
|
61628
62070
|
const decisions = /^## Decisions[^\n]*\n([\s\S]*?)(?=^## |(?![\s\S]))/m.exec(notes)?.[1].trim();
|
|
61629
62071
|
if (!decisions) return null;
|
|
61630
62072
|
const body = decisions.length > PULL_REQUEST_DECISIONS_MAX_CHARS ? `${decisions.slice(0, PULL_REQUEST_DECISIONS_MAX_CHARS)}
|
|
@@ -61683,7 +62125,7 @@ function terminalErrorsFromEvent(event, provider) {
|
|
|
61683
62125
|
if (codexTurn) {
|
|
61684
62126
|
return normalizeCodexAspTranscriptStatus(codexTurn.status) === "failed" ? [codexTurn.error ?? "Codex run failed"] : void 0;
|
|
61685
62127
|
}
|
|
61686
|
-
const mayContainProviderError = provider === "cursor" && event.type === "cursor-error" || provider === "opencode" && (event.type === "opencode-error" || event.type === "opencode-message.updated") || provider === "pi" && (event.type === "pi-error" || event.type === "pi-message_end") || provider === "muse" && event.type === "muse-error";
|
|
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";
|
|
61687
62129
|
if (!mayContainProviderError) return void 0;
|
|
61688
62130
|
const errors = parseAgentEvents([event], provider).flatMap((message) => message.type === "error" ? [message.message] : []);
|
|
61689
62131
|
return errors.length > 0 ? errors : void 0;
|
|
@@ -61691,7 +62133,7 @@ function terminalErrorsFromEvent(event, provider) {
|
|
|
61691
62133
|
var LAST_MESSAGE_PREVIEW_MAX = 200;
|
|
61692
62134
|
var FINAL_MESSAGE_MAX = 6e3;
|
|
61693
62135
|
var PROGRESS_INTERVAL_MS = 2e4;
|
|
61694
|
-
var STREAM_RECORD_TYPES = /* @__PURE__ */ new Set(["pi-message_update", "opencode-message.part.delta", "muse-item-delta", "cursor-assistant", "cursor-thinking"]);
|
|
62136
|
+
var STREAM_RECORD_TYPES = /* @__PURE__ */ new Set(["pi-message_update", "opencode-message.part.delta", "muse-item-delta", "cursor-assistant", "cursor-thinking", "gemini-chunk"]);
|
|
61695
62137
|
var PROGRESS_STEP_MAX = 120;
|
|
61696
62138
|
var TURN_REQUEST_MAX = 8e3;
|
|
61697
62139
|
var toolInputRequestSchema = z4.object({
|
|
@@ -61729,6 +62171,9 @@ var NOT_WORK_MESSAGE_TYPES = /* @__PURE__ */ new Set(["user", "error", "capacity
|
|
|
61729
62171
|
function hasActiveAgentWork(chat) {
|
|
61730
62172
|
return chat.provider.isProcessing() || hasActiveBackgroundWork(chat) || chat.turnCompletion !== null;
|
|
61731
62173
|
}
|
|
62174
|
+
function isChatIdle(chat) {
|
|
62175
|
+
return chat.acceptingMessages === 0 && !hasActiveChatTurn(chat) && !hasActiveAgentWork(chat);
|
|
62176
|
+
}
|
|
61732
62177
|
function hasActiveChatTurn(chat) {
|
|
61733
62178
|
return chat.hasActiveTurn || chat.pendingMessageIds.length > 0 || isForkPreparing(chat) || chat.provider.isProcessing();
|
|
61734
62179
|
}
|
|
@@ -61927,6 +62372,11 @@ var ChatService = class {
|
|
|
61927
62372
|
hasActiveAgentWork(provider) {
|
|
61928
62373
|
return [...this.chats.values()].some((chat) => chat.persisted.provider === provider && (hasActiveAgentWork(chat) || chat.acceptingMessages > 0 || chat.pendingMessageIds.length > 0));
|
|
61929
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
|
+
}
|
|
61930
62380
|
listDeletedChats(includeChildren = false) {
|
|
61931
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 ?? ""));
|
|
61932
62382
|
}
|
|
@@ -61943,7 +62393,7 @@ var ChatService = class {
|
|
|
61943
62393
|
const [discovered, learnedSkills] = await Promise.all([
|
|
61944
62394
|
chat.provider.listSlashCommands?.() ?? [],
|
|
61945
62395
|
// Learned skills work in the background, so they stay out of the slash menu.
|
|
61946
|
-
|
|
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())
|
|
61947
62397
|
]);
|
|
61948
62398
|
const providerCommands = discovered.filter(({ command }) => !learnedSkills.has(command)).map((command) => ({
|
|
61949
62399
|
...command,
|
|
@@ -62421,7 +62871,7 @@ ${decisions}` };
|
|
|
62421
62871
|
}
|
|
62422
62872
|
}
|
|
62423
62873
|
async readSenders(chatId) {
|
|
62424
|
-
return
|
|
62874
|
+
return readFile18(chatMessageSendersFilePath(chatId), "utf-8").then(parseChatMessageSendersJsonl).catch((error) => {
|
|
62425
62875
|
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return [];
|
|
62426
62876
|
console.error("[ChatService] Failed to read sender records:", error);
|
|
62427
62877
|
return [];
|
|
@@ -62794,7 +63244,7 @@ ${decisions}` };
|
|
|
62794
63244
|
`${historyPath}.pages.index.json`
|
|
62795
63245
|
].map((path8) => rm7(path8, { force: true })));
|
|
62796
63246
|
await rm7(chatMessageSendersFilePath(persisted.id), { force: true });
|
|
62797
|
-
await rm7(
|
|
63247
|
+
await rm7(join31(FORKS_DIR, persisted.id), { recursive: true, force: true });
|
|
62798
63248
|
}
|
|
62799
63249
|
switchHarness(source, request) {
|
|
62800
63250
|
const switching = (async () => {
|
|
@@ -63133,7 +63583,7 @@ ${note}`;
|
|
|
63133
63583
|
};
|
|
63134
63584
|
}
|
|
63135
63585
|
historyPath(persisted) {
|
|
63136
|
-
return
|
|
63586
|
+
return join31(HISTORY_DIR_BY_PROVIDER[persisted.provider], `${persisted.id}.jsonl`);
|
|
63137
63587
|
}
|
|
63138
63588
|
async recordUploadedHistory(chatId, artifact) {
|
|
63139
63589
|
const chat = this.getRuntimeChat(chatId);
|
|
@@ -63322,6 +63772,8 @@ ${note}`;
|
|
|
63322
63772
|
provider = new ClaudeManager(managerOptions);
|
|
63323
63773
|
} else if (baseProvider === "cursor") {
|
|
63324
63774
|
provider = new CursorManager(managerOptions);
|
|
63775
|
+
} else if (baseProvider === "gemini") {
|
|
63776
|
+
provider = new GeminiManager(managerOptions);
|
|
63325
63777
|
} else if (baseProvider === "muse") {
|
|
63326
63778
|
provider = new MuseManager(managerOptions);
|
|
63327
63779
|
} else if (baseProvider === "opencode") {
|
|
@@ -63367,6 +63819,7 @@ ${note}`;
|
|
|
63367
63819
|
stopped: null,
|
|
63368
63820
|
publishedQueue: null,
|
|
63369
63821
|
idleReleaseTimer: null,
|
|
63822
|
+
releaseWhenIdle: false,
|
|
63370
63823
|
history,
|
|
63371
63824
|
outbox: new AsyncLock(),
|
|
63372
63825
|
unpublishedHistoryStarts: [],
|
|
@@ -63625,7 +64078,8 @@ ${note}`;
|
|
|
63625
64078
|
this.publish({ type: "chat.updated", payload: { chat: this.toSummary(chat) } }).catch(() => {
|
|
63626
64079
|
});
|
|
63627
64080
|
this.notifyWorkspaceAgentIdle();
|
|
63628
|
-
this.
|
|
64081
|
+
if (chat.releaseWhenIdle && isChatIdle(chat)) void this.releaseAgentProcess(chat);
|
|
64082
|
+
else this.scheduleIdleRelease(chat);
|
|
63629
64083
|
}
|
|
63630
64084
|
// Idleness is re-checked when the timer fires: work that starts in between
|
|
63631
64085
|
// ends with another processing stop, which schedules a fresh release.
|
|
@@ -63635,7 +64089,7 @@ ${note}`;
|
|
|
63635
64089
|
this.enforceLiveProcessCap();
|
|
63636
64090
|
chat.idleReleaseTimer = setTimeout(() => {
|
|
63637
64091
|
chat.idleReleaseTimer = null;
|
|
63638
|
-
if (chat.persisted.deletedAt ||
|
|
64092
|
+
if (chat.persisted.deletedAt || !isChatIdle(chat)) return;
|
|
63639
64093
|
void this.releaseAgentProcess(chat);
|
|
63640
64094
|
}, chat.persisted.parentChatId === null ? CHAT_IDLE_RELEASE_MS : CHILD_CHAT_IDLE_RELEASE_MS);
|
|
63641
64095
|
chat.idleReleaseTimer.unref?.();
|
|
@@ -63646,13 +64100,14 @@ ${note}`;
|
|
|
63646
64100
|
}
|
|
63647
64101
|
enforceLiveProcessCap() {
|
|
63648
64102
|
const live = [...this.chats.values()].filter((chat) => chat.live);
|
|
63649
|
-
const idle = live.filter(
|
|
64103
|
+
const idle = live.filter(isChatIdle).sort((a, b) => a.persisted.updatedAt.localeCompare(b.persisted.updatedAt));
|
|
63650
64104
|
for (const chat of idle.slice(0, Math.max(0, live.length - maxLiveAgentProcesses()))) void this.releaseAgentProcess(chat);
|
|
63651
64105
|
}
|
|
63652
64106
|
/** Senders await `chat.release` so a new turn never starts against a session that is being torn down. */
|
|
63653
64107
|
releaseAgentProcess(chat) {
|
|
63654
64108
|
this.cancelIdleRelease(chat);
|
|
63655
64109
|
chat.live = false;
|
|
64110
|
+
chat.releaseWhenIdle = false;
|
|
63656
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(() => {
|
|
63657
64112
|
chat.release = null;
|
|
63658
64113
|
});
|
|
@@ -63758,7 +64213,7 @@ ${note}`;
|
|
|
63758
64213
|
}
|
|
63759
64214
|
async loadChats() {
|
|
63760
64215
|
try {
|
|
63761
|
-
const content = await
|
|
64216
|
+
const content = await readFile18(CHATS_FILE, "utf-8");
|
|
63762
64217
|
return parsePersistedChatsContent(content);
|
|
63763
64218
|
} catch (error) {
|
|
63764
64219
|
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
|
|
@@ -63773,7 +64228,7 @@ ${note}`;
|
|
|
63773
64228
|
console.error("[ChatService] Failed to quarantine corrupt chats file:", renameError);
|
|
63774
64229
|
}
|
|
63775
64230
|
try {
|
|
63776
|
-
const backupContent = await
|
|
64231
|
+
const backupContent = await readFile18(CHATS_BACKUP_FILE, "utf-8");
|
|
63777
64232
|
return parsePersistedChatsContent(backupContent);
|
|
63778
64233
|
} catch (backupError) {
|
|
63779
64234
|
if (backupError && typeof backupError === "object" && "code" in backupError && backupError.code === "ENOENT") {
|
|
@@ -63923,15 +64378,15 @@ ${note}`;
|
|
|
63923
64378
|
// src/services/repo-file-service.ts
|
|
63924
64379
|
import { execFile as execFile7 } from "child_process";
|
|
63925
64380
|
import { createReadStream as createReadStream2 } from "fs";
|
|
63926
|
-
import { readFile as
|
|
64381
|
+
import { readFile as readFile19, realpath as realpath2, stat as stat5 } from "fs/promises";
|
|
63927
64382
|
import { homedir as homedir9 } from "os";
|
|
63928
|
-
import { extname as extname3, isAbsolute as isAbsolute3, join as
|
|
64383
|
+
import { extname as extname3, isAbsolute as isAbsolute3, join as join33, resolve as resolve5 } from "path";
|
|
63929
64384
|
|
|
63930
64385
|
// src/services/language-server-service.ts
|
|
63931
64386
|
import { spawn as spawn4 } from "child_process";
|
|
63932
64387
|
import { existsSync as existsSync15, readFileSync as readFileSync6 } from "fs";
|
|
63933
64388
|
import { createRequire as createRequire5 } from "module";
|
|
63934
|
-
import { delimiter as delimiter2, dirname as dirname13, join as
|
|
64389
|
+
import { delimiter as delimiter2, dirname as dirname13, join as join32, relative as relative2 } from "path";
|
|
63935
64390
|
import { setTimeout as setTimeout3 } from "timers/promises";
|
|
63936
64391
|
import { fileURLToPath as fileURLToPath5, pathToFileURL } from "url";
|
|
63937
64392
|
import { createMessageConnection, StreamMessageReader, StreamMessageWriter } from "vscode-jsonrpc/node.js";
|
|
@@ -64050,7 +64505,7 @@ var LanguageServerService = class {
|
|
|
64050
64505
|
if (config.package && config.bin) command = process.execPath;
|
|
64051
64506
|
else if (config.command) {
|
|
64052
64507
|
const commandName = config.command;
|
|
64053
|
-
command = process.env.PATH?.split(delimiter2).map((directory) =>
|
|
64508
|
+
command = process.env.PATH?.split(delimiter2).map((directory) => join32(directory, commandName)).find(existsSync15);
|
|
64054
64509
|
}
|
|
64055
64510
|
const args = config.package && config.bin ? [packageBin(config.package, config.bin), ...config.args] : config.args;
|
|
64056
64511
|
if (!command) return null;
|
|
@@ -64213,7 +64668,7 @@ var RepoFileService = class {
|
|
|
64213
64668
|
...isAbsolute3(filePath) ? ["/"] : [],
|
|
64214
64669
|
...repos.map((repo) => repo.path),
|
|
64215
64670
|
...await canvasDirectories(repos),
|
|
64216
|
-
|
|
64671
|
+
join33(this.homeDir, "workspaces"),
|
|
64217
64672
|
this.homeDir
|
|
64218
64673
|
];
|
|
64219
64674
|
for (const root of roots) {
|
|
@@ -64305,7 +64760,7 @@ var RepoFileService = class {
|
|
|
64305
64760
|
async inspectSymbol(repoName, filePath, line, character, action) {
|
|
64306
64761
|
const resolved = await this.resolveFile(repoName, filePath);
|
|
64307
64762
|
if (!resolved || line < 1 || character < 0 || isBinaryExtension(filePath)) return null;
|
|
64308
|
-
const content = await
|
|
64763
|
+
const content = await readFile19(resolved.fullPath, "utf8");
|
|
64309
64764
|
const sourceLine = content.split("\n")[line - 1];
|
|
64310
64765
|
if (sourceLine === void 0) return null;
|
|
64311
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);
|
|
@@ -64418,22 +64873,22 @@ var RepoFileService = class {
|
|
|
64418
64873
|
// src/v1-routes.ts
|
|
64419
64874
|
import { Hono } from "hono";
|
|
64420
64875
|
import { z as z6 } from "zod";
|
|
64421
|
-
import { readdir as
|
|
64876
|
+
import { readdir as readdir12, stat as stat6, readFile as readFile22 } from "fs/promises";
|
|
64422
64877
|
import { openAsBlob } from "fs";
|
|
64423
|
-
import { join as
|
|
64878
|
+
import { join as join36, resolve as resolve6 } from "path";
|
|
64424
64879
|
|
|
64425
64880
|
// src/services/warm-hooks-service.ts
|
|
64426
64881
|
import { spawn as spawn5 } from "child_process";
|
|
64427
|
-
import { readFile as
|
|
64882
|
+
import { readFile as readFile21 } from "fs/promises";
|
|
64428
64883
|
import { existsSync as existsSync16 } from "fs";
|
|
64429
|
-
import { join as
|
|
64884
|
+
import { join as join35 } from "path";
|
|
64430
64885
|
|
|
64431
64886
|
// src/services/warm-hook-logs-service.ts
|
|
64432
|
-
import { mkdir as mkdir16, readFile as
|
|
64887
|
+
import { mkdir as mkdir16, readFile as readFile20, writeFile as writeFile9, readdir as readdir11, appendFile as appendFile5, unlink as unlink2 } from "fs/promises";
|
|
64433
64888
|
import { homedir as homedir10 } from "os";
|
|
64434
|
-
import { join as
|
|
64435
|
-
var LOGS_DIR2 =
|
|
64436
|
-
var 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");
|
|
64437
64892
|
function withPreview2(stored) {
|
|
64438
64893
|
const preview = buildHookOutputPreview(stored.output);
|
|
64439
64894
|
return { ...stored, ...preview };
|
|
@@ -64449,7 +64904,7 @@ var WarmHookLogsService = class {
|
|
|
64449
64904
|
hookName: "environment",
|
|
64450
64905
|
...entry
|
|
64451
64906
|
};
|
|
64452
|
-
await writeFile9(
|
|
64907
|
+
await writeFile9(join34(LOGS_DIR2, ENVIRONMENT_HOOK_LOG_FILENAME), `${JSON.stringify(log, null, 2)}
|
|
64453
64908
|
`, "utf-8");
|
|
64454
64909
|
}
|
|
64455
64910
|
async saveRepoHookLog(repoName, entry) {
|
|
@@ -64459,13 +64914,13 @@ var WarmHookLogsService = class {
|
|
|
64459
64914
|
hookName: repoName,
|
|
64460
64915
|
...entry
|
|
64461
64916
|
};
|
|
64462
|
-
await writeFile9(
|
|
64917
|
+
await writeFile9(join34(LOGS_DIR2, repoHookLogFilename(repoName)), `${JSON.stringify(log, null, 2)}
|
|
64463
64918
|
`, "utf-8");
|
|
64464
64919
|
}
|
|
64465
64920
|
async getAllLogs() {
|
|
64466
64921
|
let files;
|
|
64467
64922
|
try {
|
|
64468
|
-
files = await
|
|
64923
|
+
files = await readdir11(LOGS_DIR2);
|
|
64469
64924
|
} catch (err) {
|
|
64470
64925
|
if (err.code === "ENOENT") {
|
|
64471
64926
|
return [];
|
|
@@ -64478,7 +64933,7 @@ var WarmHookLogsService = class {
|
|
|
64478
64933
|
continue;
|
|
64479
64934
|
}
|
|
64480
64935
|
try {
|
|
64481
|
-
const raw = await
|
|
64936
|
+
const raw = await readFile20(join34(LOGS_DIR2, file), "utf-8");
|
|
64482
64937
|
const stored = JSON.parse(raw);
|
|
64483
64938
|
if (stored.hookType !== "environment" && stored.hookType !== "repository") continue;
|
|
64484
64939
|
logs.push(withPreview2(stored));
|
|
@@ -64505,7 +64960,7 @@ var WarmHookLogsService = class {
|
|
|
64505
64960
|
}
|
|
64506
64961
|
async getCurrentRunLog() {
|
|
64507
64962
|
try {
|
|
64508
|
-
return await
|
|
64963
|
+
return await readFile20(CURRENT_RUN_LOG, "utf-8");
|
|
64509
64964
|
} catch (err) {
|
|
64510
64965
|
if (err.code === "ENOENT") return null;
|
|
64511
64966
|
throw err;
|
|
@@ -64514,7 +64969,7 @@ var WarmHookLogsService = class {
|
|
|
64514
64969
|
async getFullOutput(hookType, hookName) {
|
|
64515
64970
|
const filename = hookType === "environment" ? ENVIRONMENT_HOOK_LOG_FILENAME : repoHookLogFilename(hookName);
|
|
64516
64971
|
try {
|
|
64517
|
-
const raw = await
|
|
64972
|
+
const raw = await readFile20(join34(LOGS_DIR2, filename), "utf-8");
|
|
64518
64973
|
const stored = JSON.parse(raw);
|
|
64519
64974
|
if (stored.hookType !== hookType || stored.hookName !== hookName) {
|
|
64520
64975
|
return null;
|
|
@@ -64533,12 +64988,12 @@ var warmHookLogsService = new WarmHookLogsService();
|
|
|
64533
64988
|
// src/services/warm-hooks-service.ts
|
|
64534
64989
|
async function readRepoWarmHook(repoPath) {
|
|
64535
64990
|
for (const filename of REPLICAS_CONFIG_FILENAMES) {
|
|
64536
|
-
const configPath =
|
|
64991
|
+
const configPath = join35(repoPath, filename);
|
|
64537
64992
|
if (!existsSync16(configPath)) {
|
|
64538
64993
|
continue;
|
|
64539
64994
|
}
|
|
64540
64995
|
try {
|
|
64541
|
-
const raw = await
|
|
64996
|
+
const raw = await readFile21(configPath, "utf-8");
|
|
64542
64997
|
const config = parseReplicasConfigString(raw, filename);
|
|
64543
64998
|
if (!config.warmHook) {
|
|
64544
64999
|
return null;
|
|
@@ -65653,6 +66108,14 @@ data: ${JSON.stringify("Terminal session not found")}
|
|
|
65653
66108
|
);
|
|
65654
66109
|
}
|
|
65655
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
|
+
});
|
|
65656
66119
|
app2.post("/credentials/switch", async (c) => {
|
|
65657
66120
|
const body = await c.req.json();
|
|
65658
66121
|
const provider = workspaceCredentialProviderSchema.safeParse(body.provider);
|
|
@@ -65904,11 +66367,11 @@ data: ${JSON.stringify("Terminal session not found")}
|
|
|
65904
66367
|
});
|
|
65905
66368
|
app2.get("/logs", async (c) => {
|
|
65906
66369
|
try {
|
|
65907
|
-
const files = await
|
|
66370
|
+
const files = await readdir12(LOG_DIR).catch(() => []);
|
|
65908
66371
|
const logFiles = files.filter((f) => f.endsWith(".log"));
|
|
65909
66372
|
const sessions = await Promise.all(
|
|
65910
66373
|
logFiles.map(async (filename) => {
|
|
65911
|
-
const filePath =
|
|
66374
|
+
const filePath = join36(LOG_DIR, filename);
|
|
65912
66375
|
const fileStat = await stat6(filePath);
|
|
65913
66376
|
const sessionId = filename.replace(/\.log$/, "");
|
|
65914
66377
|
return {
|
|
@@ -65943,7 +66406,7 @@ data: ${JSON.stringify("Terminal session not found")}
|
|
|
65943
66406
|
}
|
|
65944
66407
|
let content;
|
|
65945
66408
|
try {
|
|
65946
|
-
content = await
|
|
66409
|
+
content = await readFile22(filePath, "utf-8");
|
|
65947
66410
|
} catch {
|
|
65948
66411
|
return c.json(jsonError("Log session not found"), 404);
|
|
65949
66412
|
}
|
|
@@ -65967,7 +66430,7 @@ data: ${JSON.stringify("Terminal session not found")}
|
|
|
65967
66430
|
import { randomUUID as randomUUID12 } from "crypto";
|
|
65968
66431
|
import { mkdir as mkdir17, open as open3, stat as stat7, writeFile as writeFile10 } from "fs/promises";
|
|
65969
66432
|
import { arch as arch2, platform as platform3 } from "os";
|
|
65970
|
-
import { dirname as dirname14, join as
|
|
66433
|
+
import { dirname as dirname14, join as join37, resolve as resolve7 } from "path";
|
|
65971
66434
|
import { z as z7 } from "zod";
|
|
65972
66435
|
|
|
65973
66436
|
// src/services/exec/process-registry.ts
|
|
@@ -66163,7 +66626,7 @@ function parse(schema, json) {
|
|
|
66163
66626
|
return parsed.data;
|
|
66164
66627
|
}
|
|
66165
66628
|
function resolvePath(target) {
|
|
66166
|
-
if (target === "~" || target.startsWith("~/")) return
|
|
66629
|
+
if (target === "~" || target.startsWith("~/")) return join37(ENGINE_ENV.HOME_DIR, target.slice(1));
|
|
66167
66630
|
return resolve7(ENGINE_ENV.WORKSPACE_ROOT, target);
|
|
66168
66631
|
}
|
|
66169
66632
|
async function mcpServerProcess(name) {
|
|
@@ -66439,13 +66902,13 @@ function attachTerminalSocket(id, socket) {
|
|
|
66439
66902
|
}
|
|
66440
66903
|
|
|
66441
66904
|
// src/services/resource-monitor.ts
|
|
66442
|
-
import { readFile as
|
|
66905
|
+
import { readFile as readFile23 } from "fs/promises";
|
|
66443
66906
|
var SAMPLE_INTERVAL_MS = 5e3;
|
|
66444
66907
|
var READ_TIMEOUT_MS = 2e3;
|
|
66445
66908
|
var pendingReads = new InFlightMap();
|
|
66446
66909
|
var boundedReads = /* @__PURE__ */ new WeakMap();
|
|
66447
66910
|
function readWithin(path8) {
|
|
66448
|
-
const read = pendingReads.run(path8, () =>
|
|
66911
|
+
const read = pendingReads.run(path8, () => readFile23(path8, "utf8"));
|
|
66449
66912
|
const bounded = boundedReads.get(read) ?? withTimeout(read, READ_TIMEOUT_MS, `Timed out reading ${path8}`);
|
|
66450
66913
|
boundedReads.set(read, bounded);
|
|
66451
66914
|
return bounded;
|
|
@@ -66704,8 +67167,8 @@ async function installWorkspaceSdk() {
|
|
|
66704
67167
|
// src/services/git-push-tracker.ts
|
|
66705
67168
|
import { mkdir as mkdir19, rm as rm8 } from "fs/promises";
|
|
66706
67169
|
import { createServer as createServer3 } from "net";
|
|
66707
|
-
import { join as
|
|
66708
|
-
var SOCKET_PATH =
|
|
67170
|
+
import { join as join38 } from "path";
|
|
67171
|
+
var SOCKET_PATH = join38(ENGINE_DIR, "git-trace2.sock");
|
|
66709
67172
|
var MAX_LINE_LENGTH = 1024 * 1024;
|
|
66710
67173
|
var listening = null;
|
|
66711
67174
|
function startGitPushTracker() {
|