replicas-engine 0.1.918 → 0.1.920
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-EKD67W3D.js → asp-host-7ZSVWHTS.js} +4 -4
- package/dist/src/{chunk-RR6XEPD5.js → chunk-6GY7ZCSO.js} +2 -2
- package/dist/src/{chunk-2RQDQPNW.js → chunk-AOBS7XEL.js} +2 -2
- package/dist/src/{chunk-ATGTT7V6.js → chunk-CO3743XW.js} +1 -1
- package/dist/src/{chunk-ARKS7AJS.js → chunk-FJV46MRD.js} +5 -5
- package/dist/src/{chunk-VFIWV6OG.js → chunk-MLSB5HUT.js} +2 -167
- package/dist/src/{chunk-4MUVOH34.js → chunk-UMXQF6DT.js} +1 -2
- package/dist/src/command-protection-hook.js +4 -4
- package/dist/src/headless-agent.js +2 -2
- package/dist/src/index.js +308 -954
- package/dist/src/post-tool-pr-hook.js +2 -2
- package/dist/src/relay-mcp.js +1 -1
- package/package.json +1 -2
package/dist/src/index.js
CHANGED
|
@@ -27,7 +27,7 @@ import {
|
|
|
27
27
|
evaluateCommandProtection,
|
|
28
28
|
extractToolCommand,
|
|
29
29
|
reportCommandProtectionBlock
|
|
30
|
-
} from "./chunk-
|
|
30
|
+
} from "./chunk-AOBS7XEL.js";
|
|
31
31
|
import {
|
|
32
32
|
ACCOUNT_RATE_LIMITS_UPDATED_METHOD,
|
|
33
33
|
AGENT_MESSAGE_DELTA_METHOD,
|
|
@@ -52,7 +52,7 @@ import {
|
|
|
52
52
|
} from "./chunk-FLDA7BX3.js";
|
|
53
53
|
import {
|
|
54
54
|
publishedPullRequestUrls
|
|
55
|
-
} from "./chunk-
|
|
55
|
+
} from "./chunk-CO3743XW.js";
|
|
56
56
|
import {
|
|
57
57
|
RELAY_MCP_TOOLS,
|
|
58
58
|
RELAY_MCP_TOOL_NAMES,
|
|
@@ -73,21 +73,21 @@ import {
|
|
|
73
73
|
refreshDelayMs,
|
|
74
74
|
restartCodexAspHost,
|
|
75
75
|
routineRefreshExclusions
|
|
76
|
-
} from "./chunk-
|
|
76
|
+
} from "./chunk-FJV46MRD.js";
|
|
77
77
|
import {
|
|
78
78
|
ENGINE_ENV,
|
|
79
79
|
IS_WARMING_MODE,
|
|
80
80
|
monolithRequest,
|
|
81
81
|
monolithService,
|
|
82
82
|
setAgentCredentialSnapshot
|
|
83
|
-
} from "./chunk-
|
|
83
|
+
} from "./chunk-UMXQF6DT.js";
|
|
84
84
|
import {
|
|
85
85
|
AspClient,
|
|
86
86
|
SUBPROCESS_MAX_BUFFER,
|
|
87
87
|
execAsync,
|
|
88
88
|
execFileAsync,
|
|
89
89
|
getCodexModelProvider
|
|
90
|
-
} from "./chunk-
|
|
90
|
+
} from "./chunk-6GY7ZCSO.js";
|
|
91
91
|
import {
|
|
92
92
|
isRecord as isRecord2
|
|
93
93
|
} from "./chunk-UZSNFLDQ.js";
|
|
@@ -97,7 +97,6 @@ import {
|
|
|
97
97
|
AGENT_CREDENTIAL_METHODS_IN_ORDER,
|
|
98
98
|
AGENT_MODELS,
|
|
99
99
|
AGENT_QUOTA_EXHAUSTED_EVENT_TYPE,
|
|
100
|
-
AI_GATEWAY_BASE_URL,
|
|
101
100
|
ASTER_BASE_URL,
|
|
102
101
|
ASTER_MODELS,
|
|
103
102
|
ASTER_MODEL_LABELS,
|
|
@@ -136,9 +135,7 @@ import {
|
|
|
136
135
|
DEFAULT_CLAUDE_MODEL,
|
|
137
136
|
DEFAULT_CODEX_MODEL,
|
|
138
137
|
DEFAULT_CURSOR_MODEL,
|
|
139
|
-
DEFAULT_FX_MODEL,
|
|
140
138
|
DEFAULT_HOOK_OUTPUT_PREVIEW_CHARS,
|
|
141
|
-
DEFAULT_KIMI_MODEL,
|
|
142
139
|
DEFAULT_MUSE_MODEL,
|
|
143
140
|
DEFAULT_OLLAMA_MODEL,
|
|
144
141
|
DEFAULT_OPENCODE_GO_MODEL,
|
|
@@ -223,7 +220,6 @@ import {
|
|
|
223
220
|
extractErrorText,
|
|
224
221
|
extractLatestContextUsage,
|
|
225
222
|
extractToolResultText,
|
|
226
|
-
fetchAiGatewayModels,
|
|
227
223
|
fetchOpenCodeGoCatalog,
|
|
228
224
|
forkChatRequestSchema,
|
|
229
225
|
formatChatForkHandoffMessage,
|
|
@@ -313,7 +309,7 @@ import {
|
|
|
313
309
|
workspaceCredentialProviderSchema,
|
|
314
310
|
workspaceTokenRequestSchema,
|
|
315
311
|
workspaceTokenResponseSchema
|
|
316
|
-
} from "./chunk-
|
|
312
|
+
} from "./chunk-MLSB5HUT.js";
|
|
317
313
|
import {
|
|
318
314
|
cloneMcpConfig,
|
|
319
315
|
ensureCompatibilityImports,
|
|
@@ -514,7 +510,7 @@ var require_lib = __commonJS({
|
|
|
514
510
|
"../node_modules/.bun/which@5.0.0/node_modules/which/lib/index.js"(exports, module) {
|
|
515
511
|
"use strict";
|
|
516
512
|
var { isexe, sync: isexeSync } = require_index_min();
|
|
517
|
-
var { join:
|
|
513
|
+
var { join: join40, delimiter: delimiter3, sep: sep2, posix } = __require("path");
|
|
518
514
|
var isWindows = process.platform === "win32";
|
|
519
515
|
var rSlash = new RegExp(`[${posix.sep}${sep2 === posix.sep ? "" : sep2}]`.replace(/(\\)/g, "\\$1"));
|
|
520
516
|
var rRel = new RegExp(`^\\.${rSlash.source}`);
|
|
@@ -543,7 +539,7 @@ var require_lib = __commonJS({
|
|
|
543
539
|
var getPathPart = (raw, cmd) => {
|
|
544
540
|
const pathPart = /^".*"$/.test(raw) ? raw.slice(1, -1) : raw;
|
|
545
541
|
const prefix = !pathPart && rRel.test(cmd) ? cmd.slice(0, 2) : "";
|
|
546
|
-
return prefix +
|
|
542
|
+
return prefix + join40(pathPart, cmd);
|
|
547
543
|
};
|
|
548
544
|
var which = async (cmd, opt = {}) => {
|
|
549
545
|
const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
|
|
@@ -851,7 +847,7 @@ var require_cross_spawn = __commonJS({
|
|
|
851
847
|
var cp2 = __require("child_process");
|
|
852
848
|
var parse = require_parse();
|
|
853
849
|
var enoent = require_enoent();
|
|
854
|
-
function
|
|
850
|
+
function spawn9(command, args, options) {
|
|
855
851
|
const parsed = parse(command, args, options);
|
|
856
852
|
const spawned = cp2.spawn(parsed.command, parsed.args, parsed.options);
|
|
857
853
|
enoent.hookChildProcess(spawned, parsed);
|
|
@@ -863,8 +859,8 @@ var require_cross_spawn = __commonJS({
|
|
|
863
859
|
result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
|
|
864
860
|
return result;
|
|
865
861
|
}
|
|
866
|
-
module.exports =
|
|
867
|
-
module.exports.spawn =
|
|
862
|
+
module.exports = spawn9;
|
|
863
|
+
module.exports.spawn = spawn9;
|
|
868
864
|
module.exports.sync = spawnSync3;
|
|
869
865
|
module.exports._parse = parse;
|
|
870
866
|
module.exports._enoent = enoent;
|
|
@@ -8555,7 +8551,7 @@ var require_dist2 = __commonJS({
|
|
|
8555
8551
|
import { serve } from "@hono/node-server";
|
|
8556
8552
|
import { Hono as Hono2 } from "hono";
|
|
8557
8553
|
import { existsSync as existsSync19 } from "fs";
|
|
8558
|
-
import { randomUUID as
|
|
8554
|
+
import { randomUUID as randomUUID13 } from "crypto";
|
|
8559
8555
|
import { connect } from "net";
|
|
8560
8556
|
|
|
8561
8557
|
// src/managers/github-token-manager.ts
|
|
@@ -10001,9 +9997,6 @@ function detectAgentAuthMethod(provider) {
|
|
|
10001
9997
|
return detectCodexAuthMethod();
|
|
10002
9998
|
case AGENT.CURSOR:
|
|
10003
9999
|
return ENGINE_ENV.CURSOR_API_KEY ? "api_key" : "none";
|
|
10004
|
-
case AGENT.FX:
|
|
10005
|
-
case AGENT.KIMI:
|
|
10006
|
-
return ENGINE_ENV.AI_GATEWAY_API_KEY ? "api_key" : "none";
|
|
10007
10000
|
case AGENT.MUSE:
|
|
10008
10001
|
if (!existsSync2(MUSE_AUTH_PATH)) return "none";
|
|
10009
10002
|
if (ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS.muse?.method === "api_key") return "api_key";
|
|
@@ -10101,8 +10094,6 @@ function createDefaultDetails() {
|
|
|
10101
10094
|
claudeAuthMethod: "none",
|
|
10102
10095
|
codexAuthMethod: "none",
|
|
10103
10096
|
cursorAuthMethod: "none",
|
|
10104
|
-
fxAuthMethod: "none",
|
|
10105
|
-
kimiAuthMethod: "none",
|
|
10106
10097
|
museAuthMethod: "none",
|
|
10107
10098
|
opencodeAuthMethod: "none",
|
|
10108
10099
|
piAuthMethod: "none",
|
|
@@ -10150,8 +10141,6 @@ var EnvironmentDetailsService = class {
|
|
|
10150
10141
|
details.claudeAuthMethod = detectAgentAuthMethod(AGENT.CLAUDE);
|
|
10151
10142
|
details.codexAuthMethod = detectAgentAuthMethod(AGENT.CODEX);
|
|
10152
10143
|
details.cursorAuthMethod = detectAgentAuthMethod(AGENT.CURSOR);
|
|
10153
|
-
details.fxAuthMethod = detectAgentAuthMethod(AGENT.FX);
|
|
10154
|
-
details.kimiAuthMethod = detectAgentAuthMethod(AGENT.KIMI);
|
|
10155
10144
|
details.museAuthMethod = detectAgentAuthMethod(AGENT.MUSE);
|
|
10156
10145
|
details.opencodeAuthMethod = detectAgentAuthMethod(AGENT.OPENCODE);
|
|
10157
10146
|
details.piAuthMethod = detectAgentAuthMethod(AGENT.PI);
|
|
@@ -10910,9 +10899,9 @@ async function registerDesktopPreview() {
|
|
|
10910
10899
|
}
|
|
10911
10900
|
|
|
10912
10901
|
// src/services/chat/chat-service.ts
|
|
10913
|
-
import { appendFile as appendFile5, copyFile as copyFile2, mkdir as
|
|
10914
|
-
import { join as
|
|
10915
|
-
import { randomUUID as
|
|
10902
|
+
import { appendFile as appendFile5, copyFile as copyFile2, mkdir as mkdir20, readFile as readFile19, rename as rename4, rm as rm4 } from "fs/promises";
|
|
10903
|
+
import { join as join35 } from "path";
|
|
10904
|
+
import { randomUUID as randomUUID11 } from "crypto";
|
|
10916
10905
|
|
|
10917
10906
|
// ../shared/src/workspace-chat.ts
|
|
10918
10907
|
var WORKSPACE_CHATS_QUERY_SCHEMA_VERSION = 7;
|
|
@@ -12565,11 +12554,11 @@ async function findClaudePluginRoots(registryDir) {
|
|
|
12565
12554
|
async function hasCodexMarketplace(registryDir) {
|
|
12566
12555
|
return await fileExists(join15(registryDir, ".agents", "plugins", "marketplace.json")) || await fileExists(join15(registryDir, ".codex", "plugins", "marketplace.json"));
|
|
12567
12556
|
}
|
|
12568
|
-
async function installCodexRegistryPlugins(
|
|
12557
|
+
async function installCodexRegistryPlugins(client, inventory) {
|
|
12569
12558
|
const cwds = inventory.codexMarketplaceCwds;
|
|
12570
12559
|
if (cwds.length === 0) return;
|
|
12571
12560
|
try {
|
|
12572
|
-
const response = await
|
|
12561
|
+
const response = await client.request("plugin/list", { cwds });
|
|
12573
12562
|
for (const marketplace of response.marketplaces) {
|
|
12574
12563
|
if (!marketplace.path || !isPathInside(inventory.registryRoot, marketplace.path)) continue;
|
|
12575
12564
|
for (const plugin of marketplace.plugins) {
|
|
@@ -12577,7 +12566,7 @@ async function installCodexRegistryPlugins(client2, inventory) {
|
|
|
12577
12566
|
continue;
|
|
12578
12567
|
}
|
|
12579
12568
|
try {
|
|
12580
|
-
await
|
|
12569
|
+
await client.request("plugin/install", {
|
|
12581
12570
|
marketplacePath: marketplace.path,
|
|
12582
12571
|
pluginName: plugin.name
|
|
12583
12572
|
});
|
|
@@ -16211,34 +16200,6 @@ async function ensureCursorCommandProtectionHook() {
|
|
|
16211
16200
|
await writeFile7(path7, `${JSON.stringify({ ...config, version: 1, hooks }, null, 2)}
|
|
16212
16201
|
`, "utf8");
|
|
16213
16202
|
}
|
|
16214
|
-
async function ensureKimiCommandProtectionHook() {
|
|
16215
|
-
const path7 = join18(ENGINE_ENV.HOME_DIR, ".kimi-code", "config.toml");
|
|
16216
|
-
const start = "# Replicas command protection hook";
|
|
16217
|
-
const end = "# End Replicas command protection hook";
|
|
16218
|
-
let config = "";
|
|
16219
|
-
try {
|
|
16220
|
-
config = await readFile11(path7, "utf8");
|
|
16221
|
-
} catch (error) {
|
|
16222
|
-
if (!(error && typeof error === "object" && "code" in error && error.code === "ENOENT")) throw error;
|
|
16223
|
-
}
|
|
16224
|
-
const block = `${start}
|
|
16225
|
-
[[hooks]]
|
|
16226
|
-
event = "PreToolUse"
|
|
16227
|
-
command = ${JSON.stringify(shellCommand(hookPath, "kimi"))}
|
|
16228
|
-
timeout = 30
|
|
16229
|
-
|
|
16230
|
-
[[hooks]]
|
|
16231
|
-
event = "PostToolUse"
|
|
16232
|
-
command = ${JSON.stringify(shellCommand(postToolHookPath))}
|
|
16233
|
-
timeout = 30
|
|
16234
|
-
${end}`;
|
|
16235
|
-
const markerStart = config.indexOf(start);
|
|
16236
|
-
const markerEnd = config.indexOf(end, markerStart + start.length);
|
|
16237
|
-
config = markerStart >= 0 && markerEnd >= 0 ? `${config.slice(0, markerStart)}${block}${config.slice(markerEnd + end.length)}` : `${config.trimEnd()}${config.trim() ? "\n\n" : ""}${block}
|
|
16238
|
-
`;
|
|
16239
|
-
await mkdir12(dirname5(path7), { recursive: true });
|
|
16240
|
-
await writeFile7(path7, config, "utf8");
|
|
16241
|
-
}
|
|
16242
16203
|
|
|
16243
16204
|
// src/managers/cursor-run-recovery.ts
|
|
16244
16205
|
import { Agent as CursorAgent, AgentBusyError } from "@cursor/sdk";
|
|
@@ -16688,610 +16649,11 @@ ${instructions}
|
|
|
16688
16649
|
}
|
|
16689
16650
|
};
|
|
16690
16651
|
|
|
16691
|
-
// src/managers/fx-manager.ts
|
|
16692
|
-
import { readFile as readFile15 } from "fs/promises";
|
|
16693
|
-
import { spawn as spawn4 } from "child_process";
|
|
16694
|
-
|
|
16695
|
-
// src/managers/acp-manager.ts
|
|
16696
|
-
import { spawn as spawn3 } from "child_process";
|
|
16697
|
-
import { randomUUID as randomUUID6 } from "crypto";
|
|
16698
|
-
import { mkdir as mkdir14, readFile as readFile14, writeFile as writeFile8 } from "fs/promises";
|
|
16699
|
-
import { dirname as dirname7 } from "path";
|
|
16700
|
-
import { Writable } from "stream";
|
|
16701
|
-
import {
|
|
16702
|
-
PROTOCOL_VERSION,
|
|
16703
|
-
client,
|
|
16704
|
-
methods,
|
|
16705
|
-
ndJsonStream
|
|
16706
|
-
} from "@agentclientprotocol/sdk";
|
|
16707
|
-
|
|
16708
|
-
// src/services/installed-skill-service.ts
|
|
16709
|
-
import { readFile as readFile13, readdir as readdir6 } from "fs/promises";
|
|
16710
|
-
import { join as join20 } from "path";
|
|
16711
|
-
var installedSkillsByHome = /* @__PURE__ */ new Map();
|
|
16712
|
-
function isNotFoundError2(error) {
|
|
16713
|
-
return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
|
|
16714
|
-
}
|
|
16715
|
-
async function loadInstalledSkills(homeDir) {
|
|
16716
|
-
const skillsDir = join20(homeDir, ".agents/skills");
|
|
16717
|
-
let entries;
|
|
16718
|
-
try {
|
|
16719
|
-
entries = await readdir6(skillsDir, { withFileTypes: true });
|
|
16720
|
-
} catch (error) {
|
|
16721
|
-
if (!isNotFoundError2(error)) console.warn("[InstalledSkills] Failed to list installed skills:", error);
|
|
16722
|
-
return [];
|
|
16723
|
-
}
|
|
16724
|
-
const skills = await Promise.all(entries.filter((entry) => entry.isDirectory() || entry.isSymbolicLink()).map(async (entry) => {
|
|
16725
|
-
try {
|
|
16726
|
-
const metadata = parseFrontmatter(await readFile13(join20(skillsDir, entry.name, "SKILL.md"), "utf8"));
|
|
16727
|
-
return metadata.name && metadata.description ? metadata : null;
|
|
16728
|
-
} catch (error) {
|
|
16729
|
-
if (!isNotFoundError2(error)) console.warn(`[InstalledSkills] Failed to read ${entry.name}:`, error);
|
|
16730
|
-
return null;
|
|
16731
|
-
}
|
|
16732
|
-
}));
|
|
16733
|
-
return skills.filter((skill) => skill !== null);
|
|
16734
|
-
}
|
|
16735
|
-
async function getInstalledSkillsAsSlashCommands(homeDir, provider) {
|
|
16736
|
-
let installedSkills = installedSkillsByHome.get(homeDir);
|
|
16737
|
-
if (!installedSkills) {
|
|
16738
|
-
installedSkills = loadInstalledSkills(homeDir);
|
|
16739
|
-
installedSkillsByHome.set(homeDir, installedSkills);
|
|
16740
|
-
}
|
|
16741
|
-
return (await installedSkills).flatMap(({ name, description }) => {
|
|
16742
|
-
const command = createProviderSlashCommand(provider, name, description);
|
|
16743
|
-
return command ? [command] : [];
|
|
16744
|
-
});
|
|
16745
|
-
}
|
|
16746
|
-
|
|
16747
|
-
// src/managers/acp-manager.ts
|
|
16748
|
-
function selectOptions(option) {
|
|
16749
|
-
if (option.type !== "select") return [];
|
|
16750
|
-
return option.options.flatMap((entry) => "group" in entry ? entry.options : [entry]);
|
|
16751
|
-
}
|
|
16752
|
-
var AcpManager = class extends CodingAgentManager {
|
|
16753
|
-
acp;
|
|
16754
|
-
historyFile;
|
|
16755
|
-
historyFilePath;
|
|
16756
|
-
process = null;
|
|
16757
|
-
connection = null;
|
|
16758
|
-
context = null;
|
|
16759
|
-
sessionId = null;
|
|
16760
|
-
deliveredInstructions = null;
|
|
16761
|
-
activeModel = null;
|
|
16762
|
-
activeThinkingLevel;
|
|
16763
|
-
planMode = false;
|
|
16764
|
-
replaying = false;
|
|
16765
|
-
slashCommands = [];
|
|
16766
|
-
configOptions = [];
|
|
16767
|
-
modes = null;
|
|
16768
|
-
capabilities = {};
|
|
16769
|
-
interactiveTools = false;
|
|
16770
|
-
pendingPermissions = /* @__PURE__ */ new Map();
|
|
16771
|
-
terminals = /* @__PURE__ */ new Map();
|
|
16772
|
-
constructor(options) {
|
|
16773
|
-
super({ ...options, provider: options.acp.provider });
|
|
16774
|
-
this.acp = options.acp;
|
|
16775
|
-
this.historyFilePath = options.historyFilePath;
|
|
16776
|
-
this.historyFile = new CodexHistoryFile(this.historyFilePath);
|
|
16777
|
-
this.initializeManager(this.processMessageInternal.bind(this));
|
|
16778
|
-
}
|
|
16779
|
-
async initialize() {
|
|
16780
|
-
await mkdir14(dirname7(this.historyFilePath), { recursive: true });
|
|
16781
|
-
await this.acp.prepare?.();
|
|
16782
|
-
}
|
|
16783
|
-
getHistorySink() {
|
|
16784
|
-
return this.historyFile;
|
|
16785
|
-
}
|
|
16786
|
-
async start(model, thinkingLevel) {
|
|
16787
|
-
if (this.context && this.activeModel === model && (!this.acp.restartOnThinkingChange || this.activeThinkingLevel === thinkingLevel)) return;
|
|
16788
|
-
this.dispose();
|
|
16789
|
-
const agentEnv = await this.acp.env?.(model, thinkingLevel);
|
|
16790
|
-
const child = spawn3(this.acp.command, this.acp.args(model), {
|
|
16791
|
-
cwd: this.workingDirectory,
|
|
16792
|
-
env: { ...process.env, NO_COLOR: "1", ...agentEnv },
|
|
16793
|
-
stdio: ["pipe", "pipe", "pipe"]
|
|
16794
|
-
});
|
|
16795
|
-
this.process = child;
|
|
16796
|
-
child.stderr.on("data", (chunk) => console.error(`[${this.acp.provider} ACP]`, chunk.toString().trimEnd()));
|
|
16797
|
-
child.on("exit", (code, signal) => {
|
|
16798
|
-
if (this.process !== child) return;
|
|
16799
|
-
this.process = null;
|
|
16800
|
-
this.context = null;
|
|
16801
|
-
this.connection = null;
|
|
16802
|
-
if (code !== 0 && signal !== "SIGTERM") {
|
|
16803
|
-
this.recordHistoryEvent("acp-error", {
|
|
16804
|
-
provider: this.acp.provider,
|
|
16805
|
-
message: `${this.acp.command} ACP exited with code ${code ?? signal}`
|
|
16806
|
-
}, this.historyFile);
|
|
16807
|
-
}
|
|
16808
|
-
});
|
|
16809
|
-
const app2 = client({ name: "Replicas" }).onNotification(methods.client.session.update, ({ params }) => this.recordUpdate(params)).onRequest(methods.client.fs.readTextFile, async ({ params }) => {
|
|
16810
|
-
this.assertSession(params.sessionId);
|
|
16811
|
-
const content = await readFile14(params.path, "utf8");
|
|
16812
|
-
if (params.line === void 0 && params.limit === void 0) return { content };
|
|
16813
|
-
const start = Math.max(0, (params.line ?? 1) - 1);
|
|
16814
|
-
const end = params.limit === null || params.limit === void 0 ? void 0 : start + params.limit;
|
|
16815
|
-
return { content: content.split("\n").slice(start, end).join("\n") };
|
|
16816
|
-
}).onRequest(methods.client.fs.writeTextFile, async ({ params }) => {
|
|
16817
|
-
this.assertSession(params.sessionId);
|
|
16818
|
-
if (this.planMode) throw new Error("ACP file writes are disabled in plan mode.");
|
|
16819
|
-
await writeFile8(params.path, params.content, "utf8");
|
|
16820
|
-
return {};
|
|
16821
|
-
}).onRequest(methods.client.terminal.create, ({ params }) => this.createTerminal(params)).onRequest(methods.client.terminal.output, ({ params }) => {
|
|
16822
|
-
this.assertSession(params.sessionId);
|
|
16823
|
-
const terminal = this.getTerminal(params.terminalId);
|
|
16824
|
-
return {
|
|
16825
|
-
output: terminal.output.toString("utf8"),
|
|
16826
|
-
truncated: terminal.truncated,
|
|
16827
|
-
exitStatus: terminal.exitStatus
|
|
16828
|
-
};
|
|
16829
|
-
}).onRequest(methods.client.terminal.waitForExit, async ({ params }) => {
|
|
16830
|
-
this.assertSession(params.sessionId);
|
|
16831
|
-
return this.getTerminal(params.terminalId).exited;
|
|
16832
|
-
}).onRequest(methods.client.terminal.kill, ({ params }) => {
|
|
16833
|
-
this.assertSession(params.sessionId);
|
|
16834
|
-
this.getTerminal(params.terminalId).process.kill("SIGTERM");
|
|
16835
|
-
return {};
|
|
16836
|
-
}).onRequest(methods.client.terminal.release, ({ params }) => {
|
|
16837
|
-
this.assertSession(params.sessionId);
|
|
16838
|
-
const terminal = this.getTerminal(params.terminalId);
|
|
16839
|
-
if (terminal.exitStatus === null) terminal.process.kill("SIGTERM");
|
|
16840
|
-
this.terminals.delete(params.terminalId);
|
|
16841
|
-
return {};
|
|
16842
|
-
}).onRequest(methods.client.session.requestPermission, ({ params }) => {
|
|
16843
|
-
if (params.toolCall.title === "AskUserQuestion") return this.requestUserInput(params);
|
|
16844
|
-
const preferred = this.planMode ? ["reject_once", "reject_always"] : ["allow_always", "allow_once"];
|
|
16845
|
-
const option = preferred.flatMap((kind) => params.options.filter((candidate) => candidate.kind === kind))[0];
|
|
16846
|
-
return option ? { outcome: { outcome: "selected", optionId: option.optionId } } : { outcome: { outcome: "cancelled" } };
|
|
16847
|
-
});
|
|
16848
|
-
const stdout = new ReadableStream({
|
|
16849
|
-
start(controller) {
|
|
16850
|
-
child.stdout.on("data", (chunk) => controller.enqueue(chunk));
|
|
16851
|
-
child.stdout.on("end", () => controller.close());
|
|
16852
|
-
child.stdout.on("error", (error) => controller.error(error));
|
|
16853
|
-
},
|
|
16854
|
-
cancel() {
|
|
16855
|
-
child.stdout.destroy();
|
|
16856
|
-
}
|
|
16857
|
-
});
|
|
16858
|
-
this.connection = app2.connect(ndJsonStream(Writable.toWeb(child.stdin), stdout));
|
|
16859
|
-
this.context = this.connection.agent;
|
|
16860
|
-
const initialized = await this.context.request(methods.agent.initialize, {
|
|
16861
|
-
protocolVersion: PROTOCOL_VERSION,
|
|
16862
|
-
clientCapabilities: {
|
|
16863
|
-
fs: { readTextFile: true, writeTextFile: true },
|
|
16864
|
-
terminal: true,
|
|
16865
|
-
plan: {}
|
|
16866
|
-
},
|
|
16867
|
-
clientInfo: { name: "Replicas", version: "1" }
|
|
16868
|
-
});
|
|
16869
|
-
this.capabilities = initialized.agentCapabilities ?? {};
|
|
16870
|
-
if (this.acp.authMethodId) {
|
|
16871
|
-
await this.context.request(methods.agent.authenticate, { methodId: this.acp.authMethodId });
|
|
16872
|
-
}
|
|
16873
|
-
const additionalDirectories = await getAgentAdditionalDirectories();
|
|
16874
|
-
const sessionId = this.sessionId ?? this.initialSessionId;
|
|
16875
|
-
if (sessionId && this.capabilities.loadSession) {
|
|
16876
|
-
this.replaying = true;
|
|
16877
|
-
try {
|
|
16878
|
-
const session = await this.context.request(methods.agent.session.load, {
|
|
16879
|
-
sessionId,
|
|
16880
|
-
cwd: this.workingDirectory,
|
|
16881
|
-
additionalDirectories,
|
|
16882
|
-
mcpServers: []
|
|
16883
|
-
});
|
|
16884
|
-
this.configOptions = session.configOptions ?? [];
|
|
16885
|
-
this.modes = session.modes ?? null;
|
|
16886
|
-
} finally {
|
|
16887
|
-
this.replaying = false;
|
|
16888
|
-
}
|
|
16889
|
-
this.sessionId = sessionId;
|
|
16890
|
-
} else {
|
|
16891
|
-
const session = await this.context.request(methods.agent.session.new, {
|
|
16892
|
-
cwd: this.workingDirectory,
|
|
16893
|
-
additionalDirectories,
|
|
16894
|
-
mcpServers: []
|
|
16895
|
-
});
|
|
16896
|
-
this.sessionId = session.sessionId;
|
|
16897
|
-
this.deliveredInstructions = null;
|
|
16898
|
-
this.configOptions = session.configOptions ?? [];
|
|
16899
|
-
this.modes = session.modes ?? null;
|
|
16900
|
-
await this.onSaveSessionId(session.sessionId);
|
|
16901
|
-
}
|
|
16902
|
-
this.activeModel = model;
|
|
16903
|
-
this.activeThinkingLevel = thinkingLevel;
|
|
16904
|
-
}
|
|
16905
|
-
assertSession(sessionId) {
|
|
16906
|
-
if (sessionId !== this.sessionId) throw new Error(`Unknown ACP session: ${sessionId}`);
|
|
16907
|
-
}
|
|
16908
|
-
getTerminal(terminalId) {
|
|
16909
|
-
const terminal = this.terminals.get(terminalId);
|
|
16910
|
-
if (!terminal) throw new Error(`Unknown ACP terminal: ${terminalId}`);
|
|
16911
|
-
return terminal;
|
|
16912
|
-
}
|
|
16913
|
-
createTerminal(params) {
|
|
16914
|
-
this.assertSession(params.sessionId);
|
|
16915
|
-
if (this.planMode) throw new Error("ACP terminals are disabled in plan mode.");
|
|
16916
|
-
const terminalId = randomUUID6();
|
|
16917
|
-
const outputByteLimit = Math.max(1, Math.min(params.outputByteLimit ?? 1048576, 10485760));
|
|
16918
|
-
const child = spawn3(params.command, params.args ?? [], {
|
|
16919
|
-
cwd: params.cwd ?? this.workingDirectory,
|
|
16920
|
-
env: {
|
|
16921
|
-
...process.env,
|
|
16922
|
-
...Object.fromEntries(params.env?.map(({ name, value }) => [name, value]) ?? [])
|
|
16923
|
-
},
|
|
16924
|
-
stdio: ["pipe", "pipe", "pipe"]
|
|
16925
|
-
});
|
|
16926
|
-
let resolveExit;
|
|
16927
|
-
const terminal = {
|
|
16928
|
-
process: child,
|
|
16929
|
-
output: Buffer.alloc(0),
|
|
16930
|
-
outputByteLimit,
|
|
16931
|
-
truncated: false,
|
|
16932
|
-
exitStatus: null,
|
|
16933
|
-
exited: new Promise((resolve8) => {
|
|
16934
|
-
resolveExit = resolve8;
|
|
16935
|
-
})
|
|
16936
|
-
};
|
|
16937
|
-
const append = (chunk) => {
|
|
16938
|
-
terminal.output = Buffer.concat([terminal.output, chunk]);
|
|
16939
|
-
if (terminal.output.length <= outputByteLimit) return;
|
|
16940
|
-
let start = terminal.output.length - outputByteLimit;
|
|
16941
|
-
while (start < terminal.output.length && (terminal.output[start] & 192) === 128) start += 1;
|
|
16942
|
-
terminal.output = terminal.output.subarray(start);
|
|
16943
|
-
terminal.truncated = true;
|
|
16944
|
-
};
|
|
16945
|
-
child.stdout.on("data", append);
|
|
16946
|
-
child.stderr.on("data", append);
|
|
16947
|
-
child.on("error", () => {
|
|
16948
|
-
const status = { exitCode: null, signal: null };
|
|
16949
|
-
terminal.exitStatus = status;
|
|
16950
|
-
resolveExit?.(status);
|
|
16951
|
-
});
|
|
16952
|
-
child.on("exit", (exitCode, signal) => {
|
|
16953
|
-
const status = { exitCode, signal };
|
|
16954
|
-
terminal.exitStatus = status;
|
|
16955
|
-
resolveExit?.(status);
|
|
16956
|
-
});
|
|
16957
|
-
this.terminals.set(terminalId, terminal);
|
|
16958
|
-
return { terminalId };
|
|
16959
|
-
}
|
|
16960
|
-
recordUpdate(notification) {
|
|
16961
|
-
if (notification.sessionId !== this.sessionId && this.sessionId !== null) return;
|
|
16962
|
-
const update = notification.update;
|
|
16963
|
-
if (update.sessionUpdate === "available_commands_update") {
|
|
16964
|
-
this.slashCommands = mergeSlashCommands(update.availableCommands.flatMap((command) => {
|
|
16965
|
-
const parsed = createProviderSlashCommand(this.acp.provider, command.name, command.description, command.input?.hint);
|
|
16966
|
-
return parsed ? [parsed] : [];
|
|
16967
|
-
}));
|
|
16968
|
-
} else if (update.sessionUpdate === "config_option_update") {
|
|
16969
|
-
this.configOptions = update.configOptions;
|
|
16970
|
-
} else if (update.sessionUpdate === "current_mode_update" && this.modes) {
|
|
16971
|
-
this.modes = { ...this.modes, currentModeId: update.currentModeId };
|
|
16972
|
-
} else if (update.sessionUpdate === "usage_update" && !this.replaying) {
|
|
16973
|
-
const occurredAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
16974
|
-
const { used, size } = update;
|
|
16975
|
-
this.historyFile.append(this.emitContextUsage({
|
|
16976
|
-
provider: this.acp.provider,
|
|
16977
|
-
source: "provider_usage",
|
|
16978
|
-
model: this.activeModel,
|
|
16979
|
-
totalTokens: used,
|
|
16980
|
-
maxTokens: size,
|
|
16981
|
-
percentage: size > 0 ? used / size * 100 : 0,
|
|
16982
|
-
categories: [],
|
|
16983
|
-
updatedAt: occurredAt
|
|
16984
|
-
}));
|
|
16985
|
-
}
|
|
16986
|
-
if (!this.replaying) {
|
|
16987
|
-
this.recordHistoryEvent("acp-session-update", {
|
|
16988
|
-
provider: this.acp.provider,
|
|
16989
|
-
update
|
|
16990
|
-
}, this.historyFile);
|
|
16991
|
-
}
|
|
16992
|
-
}
|
|
16993
|
-
async setConfig(category, value) {
|
|
16994
|
-
const context = this.context;
|
|
16995
|
-
const sessionId = this.sessionId;
|
|
16996
|
-
const option = this.configOptions.find((candidate) => candidate.category === category || candidate.id === category);
|
|
16997
|
-
if (!context || !sessionId || !option) return false;
|
|
16998
|
-
if (option.type === "select" && !selectOptions(option).some((candidate) => candidate.value === value)) return false;
|
|
16999
|
-
if (option.currentValue === value) return true;
|
|
17000
|
-
const response = typeof value === "boolean" ? await context.request(methods.agent.session.setConfigOption, {
|
|
17001
|
-
sessionId,
|
|
17002
|
-
configId: option.id,
|
|
17003
|
-
value,
|
|
17004
|
-
type: "boolean"
|
|
17005
|
-
}) : await context.request(methods.agent.session.setConfigOption, {
|
|
17006
|
-
sessionId,
|
|
17007
|
-
configId: option.id,
|
|
17008
|
-
value
|
|
17009
|
-
});
|
|
17010
|
-
this.configOptions = response.configOptions;
|
|
17011
|
-
return true;
|
|
17012
|
-
}
|
|
17013
|
-
async setMode(planMode) {
|
|
17014
|
-
const context = this.context;
|
|
17015
|
-
const sessionId = this.sessionId;
|
|
17016
|
-
if (!context || !sessionId) return;
|
|
17017
|
-
const candidates = planMode ? ["plan", "ask", "architect"] : ["code", "default", "auto", "yolo"];
|
|
17018
|
-
const mode = this.modes?.availableModes.find((candidate) => candidates.includes(candidate.id.toLowerCase())) ?? this.modes?.availableModes.find((candidate) => candidates.some((name) => candidate.name.toLowerCase().includes(name)));
|
|
17019
|
-
if (mode) {
|
|
17020
|
-
await context.request(methods.agent.session.setMode, { sessionId, modeId: mode.id });
|
|
17021
|
-
if (this.modes) this.modes = { ...this.modes, currentModeId: mode.id };
|
|
17022
|
-
return;
|
|
17023
|
-
}
|
|
17024
|
-
const option = this.configOptions.find((candidate) => candidate.category === "mode" || candidate.id === "mode");
|
|
17025
|
-
if (!option || option.type !== "select") return;
|
|
17026
|
-
const selected = selectOptions(option).find((candidate) => candidates.includes(candidate.value.toLowerCase())) ?? selectOptions(option).find((candidate) => candidates.some((name) => candidate.name.toLowerCase().includes(name)));
|
|
17027
|
-
if (selected) await this.setConfig("mode", selected.value);
|
|
17028
|
-
}
|
|
17029
|
-
async setThinking(level) {
|
|
17030
|
-
if (!level) return;
|
|
17031
|
-
const option = this.configOptions.find((candidate) => candidate.category === "thought_level" || candidate.id === "thinking");
|
|
17032
|
-
if (!option || option.type !== "select") return;
|
|
17033
|
-
const values = selectOptions(option).map((candidate) => candidate.value);
|
|
17034
|
-
const aliases = {
|
|
17035
|
-
low: ["low", "on"],
|
|
17036
|
-
medium: ["medium", "on"],
|
|
17037
|
-
high: ["high", "on"],
|
|
17038
|
-
xhigh: ["xhigh", "high", "on"],
|
|
17039
|
-
max: ["max", "xhigh", "high", "on"],
|
|
17040
|
-
ultra: ["ultra", "max", "xhigh", "high", "on"],
|
|
17041
|
-
ultracode: ["max", "xhigh", "high", "on"]
|
|
17042
|
-
};
|
|
17043
|
-
const value = aliases[level].find((candidate) => values.includes(candidate));
|
|
17044
|
-
if (value) await this.setConfig("thought_level", value);
|
|
17045
|
-
}
|
|
17046
|
-
async requestUserInput(params) {
|
|
17047
|
-
if (!this.interactiveTools) return { outcome: { outcome: "cancelled" } };
|
|
17048
|
-
const requestId = randomUUID6();
|
|
17049
|
-
const toolCallId = params.toolCall.toolCallId;
|
|
17050
|
-
return new Promise((resolve8) => {
|
|
17051
|
-
this.pendingPermissions.set(requestId, { toolCallId, options: params.options, resolve: resolve8 });
|
|
17052
|
-
this.recordHistoryEvent("acp-session-update", {
|
|
17053
|
-
provider: this.acp.provider,
|
|
17054
|
-
update: { ...params.toolCall, sessionUpdate: "tool_call", status: "pending" }
|
|
17055
|
-
}, this.historyFile);
|
|
17056
|
-
this.recordHistoryEvent("replicas-tool-input-request", {
|
|
17057
|
-
requestId,
|
|
17058
|
-
toolUseId: toolCallId,
|
|
17059
|
-
toolName: params.toolCall.title,
|
|
17060
|
-
options: params.options.map((option) => ({
|
|
17061
|
-
id: option.optionId,
|
|
17062
|
-
label: option.name,
|
|
17063
|
-
variant: option.kind.startsWith("reject") ? "secondary" : "primary"
|
|
17064
|
-
})),
|
|
17065
|
-
parent_tool_use_id: null
|
|
17066
|
-
}, this.historyFile);
|
|
17067
|
-
});
|
|
17068
|
-
}
|
|
17069
|
-
async respondToToolInput(requestId, selectionId) {
|
|
17070
|
-
const pending = this.pendingPermissions.get(requestId);
|
|
17071
|
-
if (!pending) return false;
|
|
17072
|
-
const option = pending.options.find((candidate) => candidate.optionId === selectionId);
|
|
17073
|
-
if (!option) return false;
|
|
17074
|
-
this.pendingPermissions.delete(requestId);
|
|
17075
|
-
pending.resolve({ outcome: { outcome: "selected", optionId: selectionId } });
|
|
17076
|
-
this.recordHistoryEvent("replicas-tool-input-resolved", {
|
|
17077
|
-
requestId,
|
|
17078
|
-
toolUseId: pending.toolCallId,
|
|
17079
|
-
toolName: "AskUserQuestion",
|
|
17080
|
-
selectionId,
|
|
17081
|
-
selectionSummary: option.name,
|
|
17082
|
-
parent_tool_use_id: null
|
|
17083
|
-
}, this.historyFile);
|
|
17084
|
-
return true;
|
|
17085
|
-
}
|
|
17086
|
-
isAwaitingInput() {
|
|
17087
|
-
return this.pendingPermissions.size > 0;
|
|
17088
|
-
}
|
|
17089
|
-
abortPendingPermissions() {
|
|
17090
|
-
for (const [requestId, pending] of this.pendingPermissions) {
|
|
17091
|
-
pending.resolve({ outcome: { outcome: "cancelled" } });
|
|
17092
|
-
this.recordHistoryEvent("replicas-tool-input-resolved", {
|
|
17093
|
-
requestId,
|
|
17094
|
-
toolUseId: pending.toolCallId,
|
|
17095
|
-
toolName: "AskUserQuestion",
|
|
17096
|
-
selectionId: "aborted",
|
|
17097
|
-
parent_tool_use_id: null
|
|
17098
|
-
}, this.historyFile);
|
|
17099
|
-
}
|
|
17100
|
-
this.pendingPermissions.clear();
|
|
17101
|
-
}
|
|
17102
|
-
async processMessageInternal(request) {
|
|
17103
|
-
try {
|
|
17104
|
-
const model = request.model ?? this.acp.defaultModel;
|
|
17105
|
-
await this.start(model, request.thinkingLevel);
|
|
17106
|
-
const context = this.context;
|
|
17107
|
-
const sessionId = this.sessionId;
|
|
17108
|
-
if (!context || !sessionId) throw new Error(`${this.acp.command} ACP failed to initialize.`);
|
|
17109
|
-
this.recordUserMessageHistoryEvent(request, this.historyFile);
|
|
17110
|
-
this.planMode = request.planMode ?? false;
|
|
17111
|
-
this.interactiveTools = request.enableInteractiveTools ?? false;
|
|
17112
|
-
await this.setConfig("model", model);
|
|
17113
|
-
await this.setThinking(request.thinkingLevel);
|
|
17114
|
-
await this.setMode(this.planMode);
|
|
17115
|
-
const instructions = this.buildCombinedInstructions(request.customInstructions);
|
|
17116
|
-
const pending = instructions && instructions !== this.deliveredInstructions ? instructions : null;
|
|
17117
|
-
const prompt = [{
|
|
17118
|
-
type: "text",
|
|
17119
|
-
text: pending ? `<workspace-instructions>
|
|
17120
|
-
${pending}
|
|
17121
|
-
</workspace-instructions>
|
|
17122
|
-
|
|
17123
|
-
${request.message}` : request.message
|
|
17124
|
-
}];
|
|
17125
|
-
for (const image of request.images ?? []) {
|
|
17126
|
-
if (!this.capabilities.promptCapabilities?.image) throw new Error(`${this.acp.provider} does not advertise ACP image support.`);
|
|
17127
|
-
if (image.source.type !== "base64") throw new Error(`${this.acp.provider} requires uploaded images to be base64 encoded.`);
|
|
17128
|
-
prompt.push({ type: "image", mimeType: image.source.media_type, data: image.source.data });
|
|
17129
|
-
}
|
|
17130
|
-
const response = await context.request(methods.agent.session.prompt, { sessionId, prompt });
|
|
17131
|
-
this.onUsageUpdate(response, (/* @__PURE__ */ new Date()).toISOString());
|
|
17132
|
-
if (pending) this.deliveredInstructions = pending;
|
|
17133
|
-
this.recordHistoryEvent("acp-turn-complete", {
|
|
17134
|
-
provider: this.acp.provider,
|
|
17135
|
-
stopReason: response.stopReason
|
|
17136
|
-
}, this.historyFile);
|
|
17137
|
-
} catch (error) {
|
|
17138
|
-
this.recordHistoryEvent("acp-error", {
|
|
17139
|
-
provider: this.acp.provider,
|
|
17140
|
-
message: error instanceof Error ? error.message : String(error)
|
|
17141
|
-
}, this.historyFile);
|
|
17142
|
-
throw error;
|
|
17143
|
-
} finally {
|
|
17144
|
-
this.planMode = false;
|
|
17145
|
-
this.interactiveTools = false;
|
|
17146
|
-
try {
|
|
17147
|
-
await this.historyFile.flush();
|
|
17148
|
-
} finally {
|
|
17149
|
-
await this.onTurnComplete();
|
|
17150
|
-
}
|
|
17151
|
-
}
|
|
17152
|
-
}
|
|
17153
|
-
async interruptActiveTurn() {
|
|
17154
|
-
if (!this.context || !this.sessionId) return;
|
|
17155
|
-
this.abortPendingPermissions();
|
|
17156
|
-
await this.context.notify(methods.agent.session.cancel, { sessionId: this.sessionId });
|
|
17157
|
-
}
|
|
17158
|
-
keepSteeredMessageQueued() {
|
|
17159
|
-
return true;
|
|
17160
|
-
}
|
|
17161
|
-
async steerRequest() {
|
|
17162
|
-
if (!this.isProcessing() || !this.context || !this.sessionId) return false;
|
|
17163
|
-
await this.interruptActiveTurn();
|
|
17164
|
-
return true;
|
|
17165
|
-
}
|
|
17166
|
-
async getHistory(page2 = {}) {
|
|
17167
|
-
await this.historyFile.flush();
|
|
17168
|
-
return {
|
|
17169
|
-
thread_id: this.sessionId ?? this.initialSessionId,
|
|
17170
|
-
...await this.historyFile.loadEventsPage(page2),
|
|
17171
|
-
goal: null
|
|
17172
|
-
};
|
|
17173
|
-
}
|
|
17174
|
-
async listSlashCommands() {
|
|
17175
|
-
await this.initialized;
|
|
17176
|
-
const localSkills = await getInstalledSkillsAsSlashCommands(ENGINE_ENV.HOME_DIR, this.acp.provider);
|
|
17177
|
-
return mergeSlashCommands(this.slashCommands, localSkills);
|
|
17178
|
-
}
|
|
17179
|
-
dispose() {
|
|
17180
|
-
for (const terminal of this.terminals.values()) {
|
|
17181
|
-
if (terminal.exitStatus === null) terminal.process.kill("SIGTERM");
|
|
17182
|
-
}
|
|
17183
|
-
this.terminals.clear();
|
|
17184
|
-
this.connection?.close();
|
|
17185
|
-
this.process?.kill("SIGTERM");
|
|
17186
|
-
this.connection = null;
|
|
17187
|
-
this.context = null;
|
|
17188
|
-
this.process = null;
|
|
17189
|
-
this.activeModel = null;
|
|
17190
|
-
this.activeThinkingLevel = void 0;
|
|
17191
|
-
this.configOptions = [];
|
|
17192
|
-
this.modes = null;
|
|
17193
|
-
this.capabilities = {};
|
|
17194
|
-
this.planMode = false;
|
|
17195
|
-
this.interactiveTools = false;
|
|
17196
|
-
this.abortPendingPermissions();
|
|
17197
|
-
}
|
|
17198
|
-
};
|
|
17199
|
-
|
|
17200
|
-
// src/managers/fx-manager.ts
|
|
17201
|
-
async function ensureResolvableDnsConfig() {
|
|
17202
|
-
const contents = await readFile15("/etc/resolv.conf");
|
|
17203
|
-
if (contents.length === 0 || contents.at(-1) === 10) return;
|
|
17204
|
-
await new Promise((resolve8, reject) => {
|
|
17205
|
-
const child = spawn4("sudo", ["tee", "-a", "/etc/resolv.conf"], { stdio: ["pipe", "ignore", "pipe"] });
|
|
17206
|
-
let stderr = "";
|
|
17207
|
-
child.stderr.on("data", (chunk) => {
|
|
17208
|
-
stderr += chunk;
|
|
17209
|
-
});
|
|
17210
|
-
child.on("error", reject);
|
|
17211
|
-
child.on("exit", (code) => code === 0 ? resolve8() : reject(new Error(`Failed to normalize /etc/resolv.conf: ${stderr.trim()}`)));
|
|
17212
|
-
child.stdin.end("\n");
|
|
17213
|
-
});
|
|
17214
|
-
}
|
|
17215
|
-
var FxManager = class extends AcpManager {
|
|
17216
|
-
constructor(options) {
|
|
17217
|
-
super({
|
|
17218
|
-
...options,
|
|
17219
|
-
acp: {
|
|
17220
|
-
provider: "fx",
|
|
17221
|
-
command: "fx",
|
|
17222
|
-
args: (model) => ["acp", "--model", model],
|
|
17223
|
-
env: () => ({ FX_AUTO_UPGRADE: "0", AI_GATEWAY_API_KEY: ENGINE_ENV.AI_GATEWAY_API_KEY }),
|
|
17224
|
-
defaultModel: DEFAULT_FX_MODEL,
|
|
17225
|
-
prepare: ensureResolvableDnsConfig
|
|
17226
|
-
}
|
|
17227
|
-
});
|
|
17228
|
-
}
|
|
17229
|
-
};
|
|
17230
|
-
|
|
17231
|
-
// src/managers/kimi-manager.ts
|
|
17232
|
-
var KimiManager = class extends AcpManager {
|
|
17233
|
-
constructor(options) {
|
|
17234
|
-
super({
|
|
17235
|
-
...options,
|
|
17236
|
-
acp: {
|
|
17237
|
-
provider: "kimi",
|
|
17238
|
-
command: "kimi",
|
|
17239
|
-
args: () => ["acp"],
|
|
17240
|
-
env: async (model, thinkingLevel) => {
|
|
17241
|
-
const ollama = readOllamaAuthEnv("kimi", process.env);
|
|
17242
|
-
let contextSize = "262144";
|
|
17243
|
-
let capabilities = model.startsWith("moonshotai/kimi") ? "image_in,thinking,tool_use" : "tool_use";
|
|
17244
|
-
if (ollama) {
|
|
17245
|
-
const definition = (await listOllamaModels(ollama)).find((candidate) => candidate.id === model);
|
|
17246
|
-
if (!definition?.contextWindow || !definition.capabilities?.includes("tools")) {
|
|
17247
|
-
throw new Error(`Ollama did not report context length and tool support for ${model}. Choose a coding model with model details available.`);
|
|
17248
|
-
}
|
|
17249
|
-
contextSize = String(definition.contextWindow);
|
|
17250
|
-
capabilities = [
|
|
17251
|
-
"tool_use",
|
|
17252
|
-
...definition.capabilities.includes("vision") ? ["image_in"] : [],
|
|
17253
|
-
...definition.capabilities.includes("thinking") ? ["thinking"] : []
|
|
17254
|
-
].join(",");
|
|
17255
|
-
} else {
|
|
17256
|
-
try {
|
|
17257
|
-
const entry = (await fetchAiGatewayModels()).find((candidate) => candidate.id === model);
|
|
17258
|
-
if (entry) {
|
|
17259
|
-
if (entry.contextWindow) contextSize = String(entry.contextWindow);
|
|
17260
|
-
capabilities = [
|
|
17261
|
-
entry.tags.includes("vision") ? "image_in" : null,
|
|
17262
|
-
entry.tags.includes("reasoning") ? "thinking" : null,
|
|
17263
|
-
entry.tags.includes("tool-use") ? "tool_use" : null
|
|
17264
|
-
].filter((value) => value !== null).join(",") || capabilities;
|
|
17265
|
-
}
|
|
17266
|
-
} catch {
|
|
17267
|
-
}
|
|
17268
|
-
}
|
|
17269
|
-
return {
|
|
17270
|
-
KIMI_DISABLE_TELEMETRY: "1",
|
|
17271
|
-
KIMI_MODEL_NAME: model,
|
|
17272
|
-
KIMI_MODEL_API_KEY: ollama?.apiKey ?? ENGINE_ENV.AI_GATEWAY_API_KEY,
|
|
17273
|
-
KIMI_MODEL_PROVIDER_TYPE: "openai",
|
|
17274
|
-
KIMI_MODEL_BASE_URL: ollama ? `${ollama.baseUrl}/v1` : AI_GATEWAY_BASE_URL,
|
|
17275
|
-
KIMI_MODEL_MAX_CONTEXT_SIZE: contextSize,
|
|
17276
|
-
KIMI_MODEL_CAPABILITIES: capabilities,
|
|
17277
|
-
...thinkingLevel ? {
|
|
17278
|
-
KIMI_MODEL_THINKING_EFFORT: ["low", "medium", "high"].includes(thinkingLevel) ? thinkingLevel : "high"
|
|
17279
|
-
} : {}
|
|
17280
|
-
};
|
|
17281
|
-
},
|
|
17282
|
-
defaultModel: readOllamaAuthEnv("kimi", process.env) ? DEFAULT_OLLAMA_MODEL : DEFAULT_KIMI_MODEL,
|
|
17283
|
-
prepare: ensureKimiCommandProtectionHook,
|
|
17284
|
-
restartOnThinkingChange: true
|
|
17285
|
-
}
|
|
17286
|
-
});
|
|
17287
|
-
}
|
|
17288
|
-
};
|
|
17289
|
-
|
|
17290
16652
|
// src/managers/muse-manager.ts
|
|
17291
|
-
import { spawn as
|
|
16653
|
+
import { spawn as spawn3 } from "child_process";
|
|
17292
16654
|
import { randomBytes as randomBytes2 } from "crypto";
|
|
17293
|
-
import { mkdir as
|
|
17294
|
-
import { dirname as
|
|
16655
|
+
import { mkdir as mkdir14 } from "fs/promises";
|
|
16656
|
+
import { dirname as dirname7 } from "path";
|
|
17295
16657
|
var MuseQuotaError = class extends Error {
|
|
17296
16658
|
};
|
|
17297
16659
|
function uuidV7() {
|
|
@@ -17332,29 +16694,29 @@ var MuseManager = class extends CodingAgentManager {
|
|
|
17332
16694
|
this.initializeManager(this.processMessageInternal.bind(this));
|
|
17333
16695
|
}
|
|
17334
16696
|
async initialize() {
|
|
17335
|
-
await
|
|
16697
|
+
await mkdir14(dirname7(this.historyFilePath), { recursive: true });
|
|
17336
16698
|
}
|
|
17337
16699
|
getHistorySink() {
|
|
17338
16700
|
return this.historyFile;
|
|
17339
16701
|
}
|
|
17340
16702
|
async start(model) {
|
|
17341
16703
|
if (this.process) return;
|
|
17342
|
-
const child =
|
|
16704
|
+
const child = spawn3("muse", ["serve", "--disable-sandbox", "--trust-workspace"], {
|
|
17343
16705
|
cwd: this.workingDirectory,
|
|
17344
16706
|
env: { ...process.env, MUSE_NO_AUTO_UPDATE: "1", NO_COLOR: "1" },
|
|
17345
16707
|
stdio: ["pipe", "pipe", "pipe"]
|
|
17346
16708
|
});
|
|
17347
16709
|
this.process = child;
|
|
17348
|
-
const
|
|
17349
|
-
this.client =
|
|
17350
|
-
|
|
17351
|
-
|
|
16710
|
+
const client = new AspClient({ stdin: child.stdin, stdout: child.stdout, jsonRpcVersion: "2.0" });
|
|
16711
|
+
this.client = client;
|
|
16712
|
+
client.on("notification", (notification) => this.handleNotification(notification));
|
|
16713
|
+
client.on("serverRequest", (request) => {
|
|
17352
16714
|
const frame = request;
|
|
17353
16715
|
if (isRecord(frame) && frame.method === "approval/request") {
|
|
17354
16716
|
this.handleNotification({ method: "approval/requested", params: frame.params });
|
|
17355
|
-
|
|
16717
|
+
client.respond(request.id, {});
|
|
17356
16718
|
} else {
|
|
17357
|
-
|
|
16719
|
+
client.reject(request.id, -32601, "Unsupported Muse request");
|
|
17358
16720
|
}
|
|
17359
16721
|
});
|
|
17360
16722
|
child.stderr.on("data", (chunk) => console.error("[muse MSP]", chunk.toString().trimEnd()));
|
|
@@ -17802,8 +17164,8 @@ ${pending}
|
|
|
17802
17164
|
|
|
17803
17165
|
// src/managers/opencode-manager.ts
|
|
17804
17166
|
import { existsSync as existsSync9 } from "fs";
|
|
17805
|
-
import { copyFile, mkdir as
|
|
17806
|
-
import { delimiter, dirname as
|
|
17167
|
+
import { copyFile, mkdir as mkdir15, readFile as readFile13, rm as rm2 } from "fs/promises";
|
|
17168
|
+
import { delimiter, dirname as dirname8, join as join20 } from "path";
|
|
17807
17169
|
import { randomBytes as randomBytes3 } from "crypto";
|
|
17808
17170
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
17809
17171
|
import { Agent } from "undici";
|
|
@@ -17831,11 +17193,11 @@ async function getAllowedOpenRouterModels() {
|
|
|
17831
17193
|
}
|
|
17832
17194
|
|
|
17833
17195
|
// src/managers/opencode-manager.ts
|
|
17834
|
-
var OPENCODE_SHIM_DIR =
|
|
17835
|
-
var OPENCODE_COMMAND_PROTECTION_PLUGIN_SOURCE =
|
|
17836
|
-
var OPENCODE_COMMAND_PROTECTION_PLUGIN_PATH =
|
|
17837
|
-
var OPENCODE_LEGACY_COMMAND_PROTECTION_PLUGIN_PATH =
|
|
17838
|
-
var OPENCODE_CONFIG_PATH =
|
|
17196
|
+
var OPENCODE_SHIM_DIR = dirname8(fileURLToPath2(new URL("../../scripts/opencode", import.meta.url)));
|
|
17197
|
+
var OPENCODE_COMMAND_PROTECTION_PLUGIN_SOURCE = join20(OPENCODE_SHIM_DIR, "opencode-command-protection-plugin.ts");
|
|
17198
|
+
var OPENCODE_COMMAND_PROTECTION_PLUGIN_PATH = join20(ENGINE_ENV.HOME_DIR, ".config", "opencode", "plugins", "replicas-command-protection.ts");
|
|
17199
|
+
var OPENCODE_LEGACY_COMMAND_PROTECTION_PLUGIN_PATH = join20(ENGINE_ENV.HOME_DIR, ".config", "opencode", "plugins", "replicas-command-protection.mjs");
|
|
17200
|
+
var OPENCODE_CONFIG_PATH = join20(ENGINE_ENV.HOME_DIR, ".config", "opencode", "opencode.json");
|
|
17839
17201
|
var OPENCODE_FETCH_DISPATCHER = new Agent({ headersTimeout: 0, bodyTimeout: 0 });
|
|
17840
17202
|
var OPENCODE_SERVER_STARTUP_TIMEOUT_MS = 3e4;
|
|
17841
17203
|
var OPENCODE_WORKSPACE_PERMISSION = "allow";
|
|
@@ -17857,7 +17219,7 @@ async function hasOpencodeCredentials(provider) {
|
|
|
17857
17219
|
if (provider === "ollama") return !!readOllamaAuthEnv("opencode", process.env);
|
|
17858
17220
|
if (!existsSync9(OPENCODE_AUTH_PATH)) return false;
|
|
17859
17221
|
try {
|
|
17860
|
-
const auth2 = opencodeAuthSchema.safeParse(JSON.parse(await
|
|
17222
|
+
const auth2 = opencodeAuthSchema.safeParse(JSON.parse(await readFile13(OPENCODE_AUTH_PATH, "utf8")));
|
|
17861
17223
|
return auth2.success && auth2.data[provider]?.type === "api" && Boolean(auth2.data[provider]?.key);
|
|
17862
17224
|
} catch {
|
|
17863
17225
|
return false;
|
|
@@ -17970,7 +17332,7 @@ function isOpencodeMcpEntry(value) {
|
|
|
17970
17332
|
async function readProvisionedOpencodeMcpConfig() {
|
|
17971
17333
|
let raw;
|
|
17972
17334
|
try {
|
|
17973
|
-
raw = await
|
|
17335
|
+
raw = await readFile13(OPENCODE_CONFIG_PATH, "utf8");
|
|
17974
17336
|
} catch (error) {
|
|
17975
17337
|
if (isRecord2(error) && error.code === "ENOENT") return void 0;
|
|
17976
17338
|
console.error("[OpencodeManager] Failed to read Opencode config:", error);
|
|
@@ -18056,12 +17418,12 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
18056
17418
|
constructor(options) {
|
|
18057
17419
|
super({ ...options, provider: "opencode" });
|
|
18058
17420
|
this.sessionId = options.initialSessionId;
|
|
18059
|
-
this.historyFilePath = options.historyFilePath ??
|
|
17421
|
+
this.historyFilePath = options.historyFilePath ?? join20(ENGINE_ENV.HOME_DIR, ".replicas", "opencode", "history.jsonl");
|
|
18060
17422
|
this.historyFile = new CodexHistoryFile(this.historyFilePath);
|
|
18061
17423
|
this.initializeManager(this.processMessageInternal.bind(this));
|
|
18062
17424
|
}
|
|
18063
17425
|
async initialize() {
|
|
18064
|
-
await
|
|
17426
|
+
await mkdir15(dirname8(this.historyFilePath), { recursive: true });
|
|
18065
17427
|
}
|
|
18066
17428
|
getHistorySink() {
|
|
18067
17429
|
return this.historyFile;
|
|
@@ -18099,14 +17461,14 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
18099
17461
|
this.slashCommandsRequest ??= (async () => {
|
|
18100
17462
|
try {
|
|
18101
17463
|
const provider = await getOpencodeProvider();
|
|
18102
|
-
const
|
|
17464
|
+
const client = await this.ensureClient(await getDefaultOpencodeModel(provider), provider, true);
|
|
18103
17465
|
const directories = [this.workingDirectory, ...await getAgentAdditionalDirectories()];
|
|
18104
17466
|
const perDirectory = await Promise.all(directories.map(async (directory) => {
|
|
18105
17467
|
try {
|
|
18106
17468
|
const location = { directory };
|
|
18107
17469
|
const [commandResponse, skillResponse] = await Promise.all([
|
|
18108
|
-
|
|
18109
|
-
|
|
17470
|
+
client.v2.command.list({ location }, { throwOnError: true }),
|
|
17471
|
+
client.v2.skill.list({ location }, { throwOnError: true })
|
|
18110
17472
|
]);
|
|
18111
17473
|
return mergeSlashCommands(
|
|
18112
17474
|
opencodeCommandListToSlashCommands(commandResponse.data),
|
|
@@ -18162,7 +17524,7 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
18162
17524
|
if (!existsSync9(OPENCODE_COMMAND_PROTECTION_PLUGIN_SOURCE)) {
|
|
18163
17525
|
throw new Error("Opencode command protection plugin is missing from the engine package.");
|
|
18164
17526
|
}
|
|
18165
|
-
await
|
|
17527
|
+
await mkdir15(dirname8(OPENCODE_COMMAND_PROTECTION_PLUGIN_PATH), { recursive: true });
|
|
18166
17528
|
await copyFile(OPENCODE_COMMAND_PROTECTION_PLUGIN_SOURCE, OPENCODE_COMMAND_PROTECTION_PLUGIN_PATH);
|
|
18167
17529
|
await rm2(OPENCODE_LEGACY_COMMAND_PROTECTION_PLUGIN_PATH, { force: true });
|
|
18168
17530
|
process.env.REPLICAS_COMMAND_PROTECTION_HOOK_PATH = getCommandProtectionHookPath();
|
|
@@ -18196,14 +17558,14 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
18196
17558
|
timeout: OPENCODE_SERVER_STARTUP_TIMEOUT_MS,
|
|
18197
17559
|
config
|
|
18198
17560
|
});
|
|
18199
|
-
const
|
|
17561
|
+
const client = createOpencodeClient({
|
|
18200
17562
|
baseUrl: server2.url,
|
|
18201
17563
|
fetch: opencodeFetch,
|
|
18202
17564
|
headers: {
|
|
18203
17565
|
Authorization: `Basic ${Buffer.from(`opencode:${password}`).toString("base64")}`
|
|
18204
17566
|
}
|
|
18205
17567
|
});
|
|
18206
|
-
this.client =
|
|
17568
|
+
this.client = client;
|
|
18207
17569
|
this.server = server2;
|
|
18208
17570
|
this.configuredModels = new Set(providerModels);
|
|
18209
17571
|
const eventController = new AbortController();
|
|
@@ -18211,7 +17573,7 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
18211
17573
|
this.eventSubscriptionReady = new Promise((resolve8) => {
|
|
18212
17574
|
this.resolveEventSubscriptionReady = resolve8;
|
|
18213
17575
|
});
|
|
18214
|
-
this.subscribeToEvents(
|
|
17576
|
+
this.subscribeToEvents(client, eventController).catch((error) => {
|
|
18215
17577
|
this.resolveEventSubscriptionReady?.();
|
|
18216
17578
|
this.resolveEventSubscriptionReady = null;
|
|
18217
17579
|
console.error("[OpencodeManager] Event subscription failed:", error);
|
|
@@ -18221,15 +17583,15 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
18221
17583
|
this.eventSubscriptionReady,
|
|
18222
17584
|
new Promise((resolve8) => setTimeout(resolve8, 2e3))
|
|
18223
17585
|
]);
|
|
18224
|
-
return
|
|
17586
|
+
return client;
|
|
18225
17587
|
} finally {
|
|
18226
17588
|
finishUpdate();
|
|
18227
17589
|
}
|
|
18228
17590
|
}
|
|
18229
|
-
async ensureSession(
|
|
17591
|
+
async ensureSession(client, model, agent, variant) {
|
|
18230
17592
|
if (this.sessionId) {
|
|
18231
17593
|
try {
|
|
18232
|
-
await
|
|
17594
|
+
await client.session.get(
|
|
18233
17595
|
{ sessionID: this.sessionId, directory: this.workingDirectory },
|
|
18234
17596
|
{ throwOnError: true }
|
|
18235
17597
|
);
|
|
@@ -18238,7 +17600,7 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
18238
17600
|
this.sessionId = null;
|
|
18239
17601
|
}
|
|
18240
17602
|
}
|
|
18241
|
-
const result = await
|
|
17603
|
+
const result = await client.session.create({
|
|
18242
17604
|
directory: this.workingDirectory,
|
|
18243
17605
|
agent,
|
|
18244
17606
|
model: { providerID: this.providerId, id: model, ...variant ? { variant } : {} }
|
|
@@ -18248,11 +17610,11 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
18248
17610
|
await this.onSaveSessionId(session.id);
|
|
18249
17611
|
return session.id;
|
|
18250
17612
|
}
|
|
18251
|
-
async getModelVariants(
|
|
17613
|
+
async getModelVariants(client, model) {
|
|
18252
17614
|
const cached = this.modelVariants.get(model);
|
|
18253
17615
|
if (cached) return cached;
|
|
18254
17616
|
try {
|
|
18255
|
-
const result = await
|
|
17617
|
+
const result = await client.v2.model.list(
|
|
18256
17618
|
{ location: { directory: this.workingDirectory } },
|
|
18257
17619
|
{ throwOnError: true }
|
|
18258
17620
|
);
|
|
@@ -18266,9 +17628,9 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
18266
17628
|
}
|
|
18267
17629
|
return this.modelVariants.get(model) ?? /* @__PURE__ */ new Set();
|
|
18268
17630
|
}
|
|
18269
|
-
async getThinkingVariant(
|
|
17631
|
+
async getThinkingVariant(client, model, thinkingLevel) {
|
|
18270
17632
|
if (!thinkingLevel) return void 0;
|
|
18271
|
-
const variants = await this.getModelVariants(
|
|
17633
|
+
const variants = await this.getModelVariants(client, model);
|
|
18272
17634
|
return OPENCODE_VARIANT_CANDIDATES_BY_THINKING_LEVEL[thinkingLevel].find((variant) => variants.has(variant));
|
|
18273
17635
|
}
|
|
18274
17636
|
async processMessageInternal(request) {
|
|
@@ -18282,14 +17644,14 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
18282
17644
|
this.forwardedLinearPartKeys.clear();
|
|
18283
17645
|
try {
|
|
18284
17646
|
const model = request.model ?? await getDefaultOpencodeModel(provider);
|
|
18285
|
-
const
|
|
17647
|
+
const client = await this.ensureClient(model, provider);
|
|
18286
17648
|
const providerModel = this.providerId === OPENCODE_GO_PROVIDER ? getOpenCodeGoModel(model) : model;
|
|
18287
17649
|
const agent = request.planMode ? "plan" : "build";
|
|
18288
|
-
const variant = await this.getThinkingVariant(
|
|
18289
|
-
const sessionId = await this.ensureSession(
|
|
17650
|
+
const variant = await this.getThinkingVariant(client, providerModel, request.thinkingLevel);
|
|
17651
|
+
const sessionId = await this.ensureSession(client, providerModel, agent, variant);
|
|
18290
17652
|
const system = this.buildCombinedInstructions(request.customInstructions);
|
|
18291
17653
|
this.recordUserMessageHistoryEvent(request, this.historyFile);
|
|
18292
|
-
const result = await
|
|
17654
|
+
const result = await client.session.prompt({
|
|
18293
17655
|
sessionID: sessionId,
|
|
18294
17656
|
directory: this.workingDirectory,
|
|
18295
17657
|
agent,
|
|
@@ -18318,9 +17680,9 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
18318
17680
|
await this.onTurnComplete();
|
|
18319
17681
|
}
|
|
18320
17682
|
}
|
|
18321
|
-
async subscribeToEvents(
|
|
17683
|
+
async subscribeToEvents(client, controller) {
|
|
18322
17684
|
let streamError;
|
|
18323
|
-
const result = await
|
|
17685
|
+
const result = await client.v2.event.subscribe(
|
|
18324
17686
|
{ location: { directory: this.workingDirectory } },
|
|
18325
17687
|
{
|
|
18326
17688
|
signal: controller.signal,
|
|
@@ -18477,8 +17839,8 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
18477
17839
|
};
|
|
18478
17840
|
|
|
18479
17841
|
// src/managers/pi-manager.ts
|
|
18480
|
-
import { mkdir as
|
|
18481
|
-
import { dirname as
|
|
17842
|
+
import { mkdir as mkdir17, readFile as readFile14 } from "fs/promises";
|
|
17843
|
+
import { dirname as dirname16, join as join28 } from "path";
|
|
18482
17844
|
import {
|
|
18483
17845
|
createAgentSession,
|
|
18484
17846
|
ModelRegistry,
|
|
@@ -18489,26 +17851,22 @@ import {
|
|
|
18489
17851
|
|
|
18490
17852
|
// src/services/chat/history-paths.ts
|
|
18491
17853
|
import { homedir as homedir12 } from "os";
|
|
18492
|
-
import { join as
|
|
18493
|
-
var ENGINE_DIR2 =
|
|
18494
|
-
var CHATS_FILE =
|
|
18495
|
-
var CLAUDE_HISTORY_DIR =
|
|
18496
|
-
var RELAY_HISTORY_DIR =
|
|
18497
|
-
var CODEX_HISTORY_DIR =
|
|
18498
|
-
var CURSOR_HISTORY_DIR =
|
|
18499
|
-
var OPENCODE_HISTORY_DIR =
|
|
18500
|
-
var PI_HISTORY_DIR =
|
|
18501
|
-
var
|
|
18502
|
-
var
|
|
18503
|
-
var MUSE_HISTORY_DIR = join22(ENGINE_DIR2, "muse-histories");
|
|
18504
|
-
var FORKS_DIR = join22(ENGINE_DIR2, "forks");
|
|
17854
|
+
import { join as join21 } from "path";
|
|
17855
|
+
var ENGINE_DIR2 = join21(homedir12(), ".replicas", "engine");
|
|
17856
|
+
var CHATS_FILE = join21(ENGINE_DIR2, "chats.json");
|
|
17857
|
+
var CLAUDE_HISTORY_DIR = join21(ENGINE_DIR2, "claude-histories");
|
|
17858
|
+
var RELAY_HISTORY_DIR = join21(ENGINE_DIR2, "relay-histories");
|
|
17859
|
+
var CODEX_HISTORY_DIR = join21(ENGINE_DIR2, "codex-histories");
|
|
17860
|
+
var CURSOR_HISTORY_DIR = join21(ENGINE_DIR2, "cursor-histories");
|
|
17861
|
+
var OPENCODE_HISTORY_DIR = join21(ENGINE_DIR2, "opencode-histories");
|
|
17862
|
+
var PI_HISTORY_DIR = join21(ENGINE_DIR2, "pi-histories");
|
|
17863
|
+
var MUSE_HISTORY_DIR = join21(ENGINE_DIR2, "muse-histories");
|
|
17864
|
+
var FORKS_DIR = join21(ENGINE_DIR2, "forks");
|
|
18505
17865
|
var HISTORY_DIR_BY_PROVIDER = {
|
|
18506
17866
|
claude: CLAUDE_HISTORY_DIR,
|
|
18507
17867
|
relay: RELAY_HISTORY_DIR,
|
|
18508
17868
|
codex: CODEX_HISTORY_DIR,
|
|
18509
17869
|
cursor: CURSOR_HISTORY_DIR,
|
|
18510
|
-
fx: FX_HISTORY_DIR,
|
|
18511
|
-
kimi: KIMI_HISTORY_DIR,
|
|
18512
17870
|
muse: MUSE_HISTORY_DIR,
|
|
18513
17871
|
opencode: OPENCODE_HISTORY_DIR,
|
|
18514
17872
|
pi: PI_HISTORY_DIR
|
|
@@ -41044,7 +40402,7 @@ async function probeMcpEndpoint(url3) {
|
|
|
41044
40402
|
|
|
41045
40403
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/npx-resolver.ts
|
|
41046
40404
|
import { existsSync as existsSync10, readFileSync as readFileSync3, realpathSync, readdirSync as readdirSync2, statSync as statSync2, writeFileSync, renameSync, mkdirSync, openSync, readSync, closeSync, unlinkSync } from "fs";
|
|
41047
|
-
import { join as
|
|
40405
|
+
import { join as join22, dirname as dirname9, extname as extname2, resolve as resolve3, sep } from "path";
|
|
41048
40406
|
|
|
41049
40407
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/abort.ts
|
|
41050
40408
|
function throwIfAborted(signal) {
|
|
@@ -41201,7 +40559,7 @@ function resolveFromNpmCache(packageSpec, binName) {
|
|
|
41201
40559
|
const { packageName, exactVersion } = parsedSpec;
|
|
41202
40560
|
const packageDir = findCachedPackageDir(cacheDir, packageName, exactVersion);
|
|
41203
40561
|
if (!packageDir) return null;
|
|
41204
|
-
const packageJsonPath =
|
|
40562
|
+
const packageJsonPath = join22(packageDir, "package.json");
|
|
41205
40563
|
if (!existsSync10(packageJsonPath)) return null;
|
|
41206
40564
|
let pkg = null;
|
|
41207
40565
|
try {
|
|
@@ -41235,7 +40593,7 @@ function resolveFromNpmCache(packageSpec, binName) {
|
|
|
41235
40593
|
}
|
|
41236
40594
|
if (!binRel) return null;
|
|
41237
40595
|
const nodeModulesDir = findNodeModulesDir(packageDir);
|
|
41238
|
-
const binLink = chosenBinName ?
|
|
40596
|
+
const binLink = chosenBinName ? join22(nodeModulesDir, ".bin", chosenBinName) : null;
|
|
41239
40597
|
let resolvedBin = binLink && existsSync10(binLink) ? safeRealpath(binLink) : "";
|
|
41240
40598
|
if (!resolvedBin) {
|
|
41241
40599
|
resolvedBin = resolve3(packageDir, binRel);
|
|
@@ -41337,17 +40695,17 @@ function defaultBinName(packageName) {
|
|
|
41337
40695
|
return packageName;
|
|
41338
40696
|
}
|
|
41339
40697
|
function findCachedPackageDir(cacheDir, packageName, exactVersion) {
|
|
41340
|
-
const npxDir =
|
|
40698
|
+
const npxDir = join22(cacheDir, "_npx");
|
|
41341
40699
|
if (!existsSync10(npxDir)) return null;
|
|
41342
40700
|
const packagePathParts = packageName.startsWith("@") ? packageName.split("/") : [packageName];
|
|
41343
40701
|
const candidates = readdirSync2(npxDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => {
|
|
41344
|
-
const full =
|
|
40702
|
+
const full = join22(npxDir, entry.name);
|
|
41345
40703
|
const mtime = safeStatMtime(full);
|
|
41346
40704
|
return { name: entry.name, mtime };
|
|
41347
40705
|
}).sort((a, b) => b.mtime - a.mtime);
|
|
41348
40706
|
for (const entry of candidates) {
|
|
41349
|
-
const pkgDir =
|
|
41350
|
-
const packageJsonPath =
|
|
40707
|
+
const pkgDir = join22(npxDir, entry.name, "node_modules", ...packagePathParts);
|
|
40708
|
+
const packageJsonPath = join22(pkgDir, "package.json");
|
|
41351
40709
|
if (!existsSync10(packageJsonPath)) continue;
|
|
41352
40710
|
if (exactVersion) {
|
|
41353
40711
|
try {
|
|
@@ -41367,7 +40725,7 @@ function findNodeModulesDir(packageDir) {
|
|
|
41367
40725
|
if (idx >= 0) {
|
|
41368
40726
|
return parts.slice(0, idx + 1).join(sep);
|
|
41369
40727
|
}
|
|
41370
|
-
return
|
|
40728
|
+
return join22(packageDir, "..");
|
|
41371
40729
|
}
|
|
41372
40730
|
function detectJsBinary(binPath) {
|
|
41373
40731
|
const ext = extname2(binPath).toLowerCase();
|
|
@@ -41472,7 +40830,7 @@ function loadCache() {
|
|
|
41472
40830
|
function saveCacheEntry(key, entry) {
|
|
41473
40831
|
try {
|
|
41474
40832
|
const cachePath = getNpxCachePath();
|
|
41475
|
-
const dir =
|
|
40833
|
+
const dir = dirname9(cachePath);
|
|
41476
40834
|
mkdirSync(dir, { recursive: true });
|
|
41477
40835
|
const existing = toNpxCache(readNpxCachePayload(cachePath));
|
|
41478
40836
|
const entries = createCacheEntries();
|
|
@@ -41559,7 +40917,7 @@ import { spawnSync } from "child_process";
|
|
|
41559
40917
|
import { createHash as createHash2 } from "crypto";
|
|
41560
40918
|
import { createRequire } from "module";
|
|
41561
40919
|
import { readFileSync as readFileSync4, existsSync as existsSync11, rmSync } from "fs";
|
|
41562
|
-
import { dirname as
|
|
40920
|
+
import { dirname as dirname10, join as join23 } from "path";
|
|
41563
40921
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
41564
40922
|
var require2 = createRequire(import.meta.url);
|
|
41565
40923
|
var AUTH_SECRET_SERVICE = "pi-mcp-adapter.oauth";
|
|
@@ -41715,7 +41073,7 @@ function loadKeyringNativeBindingFallback(keyringRequire, platform3, arch2) {
|
|
|
41715
41073
|
for (const target of targets) {
|
|
41716
41074
|
try {
|
|
41717
41075
|
const packageJsonPath = keyringRequire.resolve(`${target.packageName}/package.json`);
|
|
41718
|
-
return keyringRequire(
|
|
41076
|
+
return keyringRequire(join23(dirname10(packageJsonPath), target.bindingFile));
|
|
41719
41077
|
} catch (error) {
|
|
41720
41078
|
lastError = error;
|
|
41721
41079
|
}
|
|
@@ -41820,7 +41178,7 @@ function getServerDir(serverName, options) {
|
|
|
41820
41178
|
throw new Error(`Invalid MCP server name: ${JSON.stringify(serverName)}`);
|
|
41821
41179
|
}
|
|
41822
41180
|
const storageKey = getAuthEntryAccount(serverName);
|
|
41823
|
-
return
|
|
41181
|
+
return join23(getAuthBaseDir(options), storageKey);
|
|
41824
41182
|
}
|
|
41825
41183
|
function getAuthEntryAccount(serverName) {
|
|
41826
41184
|
if (typeof serverName !== "string") {
|
|
@@ -41829,7 +41187,7 @@ function getAuthEntryAccount(serverName) {
|
|
|
41829
41187
|
return `sha256-${createHash2("sha256").update(serverName, "utf8").digest("hex")}`;
|
|
41830
41188
|
}
|
|
41831
41189
|
function getAuthEntryFilePath(serverName, options) {
|
|
41832
|
-
return
|
|
41190
|
+
return join23(getServerDir(serverName, options), "tokens.json");
|
|
41833
41191
|
}
|
|
41834
41192
|
function parseJsonPayload(serverName, payload, source) {
|
|
41835
41193
|
try {
|
|
@@ -44432,7 +43790,7 @@ async function shutdownOAuth(runtime = legacyRuntime) {
|
|
|
44432
43790
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/mcp-bearer-store.ts
|
|
44433
43791
|
import { createHash as createHash3 } from "crypto";
|
|
44434
43792
|
import { createRequire as createRequire2 } from "module";
|
|
44435
|
-
import { dirname as
|
|
43793
|
+
import { dirname as dirname11, join as join24 } from "path";
|
|
44436
43794
|
var require3 = createRequire2(import.meta.url);
|
|
44437
43795
|
var BEARER_SECRET_SERVICE = "pi-mcp-adapter.bearer";
|
|
44438
43796
|
var TEST_AUTH_STORE_ENV2 = "PI_MCP_ADAPTER_TEST_AUTH_STORE";
|
|
@@ -44534,7 +43892,7 @@ function loadKeyringNativeBindingFallback2(keyringRequire, platform3, arch2) {
|
|
|
44534
43892
|
for (const target of targets) {
|
|
44535
43893
|
try {
|
|
44536
43894
|
const packageJsonPath = keyringRequire.resolve(`${target.packageName}/package.json`);
|
|
44537
|
-
return keyringRequire(
|
|
43895
|
+
return keyringRequire(join24(dirname11(packageJsonPath), target.bindingFile));
|
|
44538
43896
|
} catch (error) {
|
|
44539
43897
|
lastError = error;
|
|
44540
43898
|
}
|
|
@@ -44669,8 +44027,8 @@ function inspectBearerTokenForUrl(serverName, serverUrl) {
|
|
|
44669
44027
|
|
|
44670
44028
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/sampling-handler.ts
|
|
44671
44029
|
import { complete } from "@earendil-works/pi-ai/compat";
|
|
44672
|
-
function registerSamplingHandler(
|
|
44673
|
-
|
|
44030
|
+
function registerSamplingHandler(client, options) {
|
|
44031
|
+
client.setRequestHandler("sampling/createMessage", (request) => {
|
|
44674
44032
|
return handleSamplingRequest(options, request);
|
|
44675
44033
|
});
|
|
44676
44034
|
}
|
|
@@ -44884,8 +44242,8 @@ function zeroUsage() {
|
|
|
44884
44242
|
}
|
|
44885
44243
|
|
|
44886
44244
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/elicitation-handler.ts
|
|
44887
|
-
function registerElicitationHandler(
|
|
44888
|
-
|
|
44245
|
+
function registerElicitationHandler(client, options) {
|
|
44246
|
+
client.setRequestHandler("elicitation/create", (request) => handleElicitationRequest(options, request));
|
|
44889
44247
|
}
|
|
44890
44248
|
async function handleElicitationRequest(options, request) {
|
|
44891
44249
|
return request.params.mode === "url" ? handleUrlElicitation(options, request.params) : handleFormElicitation(options, request.params);
|
|
@@ -45146,9 +44504,9 @@ function humanizeName(name) {
|
|
|
45146
44504
|
}
|
|
45147
44505
|
|
|
45148
44506
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/mcp-trace.ts
|
|
45149
|
-
import { appendFile as appendFile3, mkdir as
|
|
44507
|
+
import { appendFile as appendFile3, mkdir as mkdir16, writeFile as writeFile8 } from "fs/promises";
|
|
45150
44508
|
import { Buffer as Buffer3 } from "buffer";
|
|
45151
|
-
import { dirname as
|
|
44509
|
+
import { dirname as dirname12, isAbsolute as isAbsolute2, resolve as resolve4 } from "path";
|
|
45152
44510
|
var MCP_TRACE_SCHEMA_VERSION = 1;
|
|
45153
44511
|
var DEFAULT_MCP_TRACE_MAX_BYTES = 256 * 1024;
|
|
45154
44512
|
var DEFAULT_MCP_TRACE_MAX_EVENTS = 1e4;
|
|
@@ -45215,13 +44573,13 @@ var McpTraceWriter = class {
|
|
|
45215
44573
|
await appendFile3(path7, data, appendOptions);
|
|
45216
44574
|
});
|
|
45217
44575
|
this.resetFile = options.writeFile ?? (async (path7, data, writeOptions) => {
|
|
45218
|
-
await
|
|
44576
|
+
await writeFile8(path7, data, writeOptions);
|
|
45219
44577
|
});
|
|
45220
44578
|
this.makeDirectory = options.mkdir ?? (async (path7) => {
|
|
45221
|
-
await
|
|
44579
|
+
await mkdir16(path7, { recursive: true });
|
|
45222
44580
|
return void 0;
|
|
45223
44581
|
});
|
|
45224
|
-
this.fileReady = this.makeDirectory(
|
|
44582
|
+
this.fileReady = this.makeDirectory(dirname12(this.options.filePath), { recursive: true }).then(() => this.resetFile(this.options.filePath, "", { encoding: "utf8" })).catch(() => {
|
|
45225
44583
|
this.initializationFailed = true;
|
|
45226
44584
|
this.disabled = true;
|
|
45227
44585
|
});
|
|
@@ -45349,8 +44707,8 @@ function traceTransportKind(definition, transport) {
|
|
|
45349
44707
|
}
|
|
45350
44708
|
|
|
45351
44709
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/request-headers-command.ts
|
|
45352
|
-
import { spawn as
|
|
45353
|
-
import { randomUUID as
|
|
44710
|
+
import { spawn as spawn5, spawnSync as spawnSync2 } from "child_process";
|
|
44711
|
+
import { randomUUID as randomUUID6 } from "crypto";
|
|
45354
44712
|
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
45355
44713
|
var MAX_OUTPUT_BYTES = 64 * 1024;
|
|
45356
44714
|
var USE_PROCESS_GROUP = process.platform !== "win32";
|
|
@@ -45498,8 +44856,8 @@ async function invokeRequestHeadersCommand(config, envelope, signal) {
|
|
|
45498
44856
|
return new Promise((resolve8, reject) => {
|
|
45499
44857
|
let stdout = Buffer.alloc(0);
|
|
45500
44858
|
let settled = false;
|
|
45501
|
-
const cleanupToken =
|
|
45502
|
-
const child =
|
|
44859
|
+
const cleanupToken = randomUUID6();
|
|
44860
|
+
const child = spawn5(resolved.command, resolved.args, {
|
|
45503
44861
|
env: { ...resolved.env, [CLEANUP_TOKEN_ENV]: cleanupToken },
|
|
45504
44862
|
stdio: ["pipe", "pipe", "ignore"],
|
|
45505
44863
|
windowsHide: true,
|
|
@@ -46129,7 +45487,7 @@ var McpServerManager = class {
|
|
|
46129
45487
|
const tracingEnabled = isMcpTraceEnabled(definition, this.traceSettings);
|
|
46130
45488
|
const traceWriter = tracingEnabled ? this.traceWriter ??= createMcpTraceWriter(this.defaultCwd, this.traceSettings ?? {}) : void 0;
|
|
46131
45489
|
const traceObserver = traceWriter ? { record: (event) => traceWriter.write(event) } : void 0;
|
|
46132
|
-
let
|
|
45490
|
+
let client;
|
|
46133
45491
|
let transport;
|
|
46134
45492
|
let clientConnected = false;
|
|
46135
45493
|
let invalidated = credentialsInvalidated;
|
|
@@ -46141,7 +45499,7 @@ var McpServerManager = class {
|
|
|
46141
45499
|
}
|
|
46142
45500
|
const requestOptions = this.buildRequestOptions(definition, requestSignal);
|
|
46143
45501
|
if (definition.command) {
|
|
46144
|
-
|
|
45502
|
+
client = this.createClient(name, definition);
|
|
46145
45503
|
let command = definition.command;
|
|
46146
45504
|
let args = (definition.args ?? []).map((argument) => interpolateEnvVars(argument));
|
|
46147
45505
|
const cwd = resolveConfigPath(definition.cwd) ?? this.defaultCwd;
|
|
@@ -46182,12 +45540,12 @@ var McpServerManager = class {
|
|
|
46182
45540
|
traceObserver,
|
|
46183
45541
|
invalidated
|
|
46184
45542
|
);
|
|
46185
|
-
|
|
45543
|
+
client = httpConnection.client;
|
|
46186
45544
|
transport = httpConnection.transport;
|
|
46187
45545
|
invalidated = httpConnection.credentialsInvalidated;
|
|
46188
45546
|
if (httpConnection.status === "needs-auth") {
|
|
46189
45547
|
return {
|
|
46190
|
-
client
|
|
45548
|
+
client,
|
|
46191
45549
|
transport,
|
|
46192
45550
|
definition,
|
|
46193
45551
|
tools: [],
|
|
@@ -46203,7 +45561,7 @@ var McpServerManager = class {
|
|
|
46203
45561
|
clientConnected = true;
|
|
46204
45562
|
transportAlreadyTraced = traceObserver !== void 0;
|
|
46205
45563
|
} else {
|
|
46206
|
-
|
|
45564
|
+
client = this.createClient(name, definition);
|
|
46207
45565
|
transport = new UnixSocketClientTransport(resolveConfigPath(definition.socket));
|
|
46208
45566
|
}
|
|
46209
45567
|
if (traceObserver && !transportAlreadyTraced) {
|
|
@@ -46213,14 +45571,14 @@ var McpServerManager = class {
|
|
|
46213
45571
|
try {
|
|
46214
45572
|
throwIfAborted(signal);
|
|
46215
45573
|
if (!clientConnected) {
|
|
46216
|
-
await this.connectClientWithAbort(
|
|
45574
|
+
await this.connectClientWithAbort(client, transport, requestOptions, signal);
|
|
46217
45575
|
}
|
|
46218
|
-
this.attachAdapterNotificationHandlers(name,
|
|
46219
|
-
const instructions =
|
|
46220
|
-
const protocolEra =
|
|
46221
|
-
const autoOpenedSubscription =
|
|
45576
|
+
this.attachAdapterNotificationHandlers(name, client);
|
|
45577
|
+
const instructions = client.getInstructions?.();
|
|
45578
|
+
const protocolEra = client.getProtocolEra?.();
|
|
45579
|
+
const autoOpenedSubscription = client.autoOpenedSubscription;
|
|
46222
45580
|
const connection = {
|
|
46223
|
-
client
|
|
45581
|
+
client,
|
|
46224
45582
|
transport,
|
|
46225
45583
|
definition,
|
|
46226
45584
|
tools: [],
|
|
@@ -46237,15 +45595,15 @@ var McpServerManager = class {
|
|
|
46237
45595
|
} : {}
|
|
46238
45596
|
};
|
|
46239
45597
|
if (autoOpenedSubscription) connection.listenFilter = this.catalogListenFilter(connection);
|
|
46240
|
-
|
|
45598
|
+
client.onclose = () => {
|
|
46241
45599
|
if (this.connections.get(name) === connection) {
|
|
46242
45600
|
connection.status = "closed";
|
|
46243
45601
|
}
|
|
46244
45602
|
};
|
|
46245
45603
|
const [toolResult, resources, promptResult] = await Promise.all([
|
|
46246
|
-
this.fetchAllTools(
|
|
46247
|
-
this.fetchAllResources(
|
|
46248
|
-
this.fetchAllPrompts(
|
|
45604
|
+
this.fetchAllTools(client, requestOptions),
|
|
45605
|
+
this.fetchAllResources(client, requestOptions),
|
|
45606
|
+
this.fetchAllPrompts(client, requestOptions)
|
|
46249
45607
|
]);
|
|
46250
45608
|
connection.tools = toolResult.tools;
|
|
46251
45609
|
connection.toolListHints = toolResult.hints;
|
|
@@ -46257,7 +45615,7 @@ var McpServerManager = class {
|
|
|
46257
45615
|
const abortCleanup = abortCleanupPromises.get(transport);
|
|
46258
45616
|
const abortCleanupFailed = error instanceof AggregateError && error.message === "MCP connection abort cleanup failed";
|
|
46259
45617
|
const cleanupResults = abortCleanupFailed ? [] : await Promise.allSettled([
|
|
46260
|
-
abortCleanup ?? Promise.resolve().then(() =>
|
|
45618
|
+
abortCleanup ?? Promise.resolve().then(() => client.close())
|
|
46261
45619
|
]);
|
|
46262
45620
|
const cleanupFailures = cleanupResults.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
|
|
46263
45621
|
let reportedError = error;
|
|
@@ -46270,7 +45628,7 @@ var McpServerManager = class {
|
|
|
46270
45628
|
invalidated = true;
|
|
46271
45629
|
}
|
|
46272
45630
|
return {
|
|
46273
|
-
client
|
|
45631
|
+
client,
|
|
46274
45632
|
transport,
|
|
46275
45633
|
definition,
|
|
46276
45634
|
tools: [],
|
|
@@ -46307,7 +45665,7 @@ var McpServerManager = class {
|
|
|
46307
45665
|
return error instanceof Error ? error : new Error(originalMessage);
|
|
46308
45666
|
}
|
|
46309
45667
|
}
|
|
46310
|
-
async connectClientWithAbort(
|
|
45668
|
+
async connectClientWithAbort(client, transport, requestOptions, signal) {
|
|
46311
45669
|
throwIfAborted(signal);
|
|
46312
45670
|
let abortCleanup;
|
|
46313
45671
|
const closeTransport = () => {
|
|
@@ -46316,7 +45674,7 @@ var McpServerManager = class {
|
|
|
46316
45674
|
};
|
|
46317
45675
|
signal?.addEventListener("abort", closeTransport, { once: true });
|
|
46318
45676
|
try {
|
|
46319
|
-
await abortable(
|
|
45677
|
+
await abortable(client.connect(transport, requestOptions), signal);
|
|
46320
45678
|
await abortCleanup;
|
|
46321
45679
|
} catch (error) {
|
|
46322
45680
|
if (abortCleanup) {
|
|
@@ -46350,8 +45708,8 @@ var McpServerManager = class {
|
|
|
46350
45708
|
createClient(serverName, definition) {
|
|
46351
45709
|
const capabilities = this.buildClientCapabilities();
|
|
46352
45710
|
const versionNegotiation = resolveVersionNegotiation2(definition);
|
|
46353
|
-
let
|
|
46354
|
-
|
|
45711
|
+
let client;
|
|
45712
|
+
client = new Client(
|
|
46355
45713
|
{ name: `pi-mcp-${serverName}`, version: "1.0.0" },
|
|
46356
45714
|
{
|
|
46357
45715
|
jsonSchemaValidator: createJsonSchemaValidator(),
|
|
@@ -46360,33 +45718,33 @@ var McpServerManager = class {
|
|
|
46360
45718
|
listChanged: {
|
|
46361
45719
|
tools: {
|
|
46362
45720
|
onChanged: (error, tools) => {
|
|
46363
|
-
this.handleToolsListChanged(serverName,
|
|
45721
|
+
this.handleToolsListChanged(serverName, client, error, tools);
|
|
46364
45722
|
}
|
|
46365
45723
|
},
|
|
46366
45724
|
resources: {
|
|
46367
45725
|
onChanged: (error, resources) => {
|
|
46368
|
-
this.handleResourcesListChanged(serverName,
|
|
45726
|
+
this.handleResourcesListChanged(serverName, client, error, resources);
|
|
46369
45727
|
}
|
|
46370
45728
|
},
|
|
46371
45729
|
prompts: {
|
|
46372
45730
|
onChanged: (error, prompts) => {
|
|
46373
|
-
this.handlePromptsListChanged(serverName,
|
|
45731
|
+
this.handlePromptsListChanged(serverName, client, error, prompts);
|
|
46374
45732
|
}
|
|
46375
45733
|
}
|
|
46376
45734
|
}
|
|
46377
45735
|
}
|
|
46378
45736
|
);
|
|
46379
45737
|
if (this.samplingConfig) {
|
|
46380
|
-
registerSamplingHandler(
|
|
45738
|
+
registerSamplingHandler(client, { ...this.samplingConfig, serverName });
|
|
46381
45739
|
}
|
|
46382
45740
|
if (this.elicitationConfig) {
|
|
46383
|
-
registerElicitationHandler(
|
|
45741
|
+
registerElicitationHandler(client, {
|
|
46384
45742
|
...this.elicitationConfig,
|
|
46385
45743
|
serverName,
|
|
46386
45744
|
onUrlAccepted: (elicitationId) => this.rememberUrlElicitation(serverName, elicitationId)
|
|
46387
45745
|
});
|
|
46388
45746
|
if (this.elicitationConfig.allowUrl) {
|
|
46389
|
-
|
|
45747
|
+
client.setNotificationHandler("notifications/elicitation/complete", (notification) => {
|
|
46390
45748
|
if (this.runtimeSignal?.aborted) return;
|
|
46391
45749
|
const accepted = this.acceptedUrlElicitations.get(serverName);
|
|
46392
45750
|
if (!accepted?.delete(notification.params.elicitationId)) return;
|
|
@@ -46397,42 +45755,42 @@ var McpServerManager = class {
|
|
|
46397
45755
|
});
|
|
46398
45756
|
}
|
|
46399
45757
|
}
|
|
46400
|
-
return
|
|
45758
|
+
return client;
|
|
46401
45759
|
}
|
|
46402
|
-
handleToolsListChanged(serverName,
|
|
45760
|
+
handleToolsListChanged(serverName, client, error, tools) {
|
|
46403
45761
|
if (error) {
|
|
46404
45762
|
logger.debug(`MCP: tools/list_changed refresh failed for ${serverName}: ${error.message}`);
|
|
46405
45763
|
return;
|
|
46406
45764
|
}
|
|
46407
45765
|
if (!tools) return;
|
|
46408
45766
|
const connection = this.connections.get(serverName);
|
|
46409
|
-
if (!connection || connection.client !==
|
|
45767
|
+
if (!connection || connection.client !== client || connection.status !== "connected") return;
|
|
46410
45768
|
connection.tools = tools;
|
|
46411
45769
|
connection.toolsRevision = (connection.toolsRevision ?? 0) + 1;
|
|
46412
45770
|
this.metadataListChangedListener?.(serverName, "tools-list-changed");
|
|
46413
45771
|
this.pendingMetadataPublications.delete(serverName);
|
|
46414
45772
|
}
|
|
46415
|
-
handlePromptsListChanged(serverName,
|
|
45773
|
+
handlePromptsListChanged(serverName, client, error, prompts) {
|
|
46416
45774
|
if (error) {
|
|
46417
45775
|
logger.debug(`MCP: prompts/list_changed refresh failed for ${serverName}: ${error.message}`);
|
|
46418
45776
|
return;
|
|
46419
45777
|
}
|
|
46420
45778
|
if (!prompts) return;
|
|
46421
45779
|
const connection = this.connections.get(serverName);
|
|
46422
|
-
if (!connection || connection.client !==
|
|
45780
|
+
if (!connection || connection.client !== client || connection.status !== "connected") return;
|
|
46423
45781
|
connection.prompts = prompts;
|
|
46424
45782
|
connection.promptDiscoveryFailed = false;
|
|
46425
45783
|
this.metadataListChangedListener?.(serverName, "prompts-list-changed");
|
|
46426
45784
|
this.pendingMetadataPublications.delete(serverName);
|
|
46427
45785
|
}
|
|
46428
|
-
handleResourcesListChanged(serverName,
|
|
45786
|
+
handleResourcesListChanged(serverName, client, error, resources) {
|
|
46429
45787
|
if (error) {
|
|
46430
45788
|
logger.debug(`MCP: resources/list_changed refresh failed for ${serverName}: ${error.message}`);
|
|
46431
45789
|
return;
|
|
46432
45790
|
}
|
|
46433
45791
|
if (!resources) return;
|
|
46434
45792
|
const connection = this.connections.get(serverName);
|
|
46435
|
-
if (!connection || connection.client !==
|
|
45793
|
+
if (!connection || connection.client !== client || connection.status !== "connected") return;
|
|
46436
45794
|
connection.resources = resources;
|
|
46437
45795
|
this.metadataListChangedListener?.(serverName, "resources-list-changed");
|
|
46438
45796
|
this.pendingMetadataPublications.delete(serverName);
|
|
@@ -46510,20 +45868,20 @@ var McpServerManager = class {
|
|
|
46510
45868
|
};
|
|
46511
45869
|
const baseTransport = kind2 === "streamable-http" ? new StreamableHTTPClientTransport(url3, transportOptions) : new SSEClientTransport(url3, transportOptions);
|
|
46512
45870
|
const transport = traceObserver ? wrapTransportWithMcpTrace(baseTransport, serverName, kind2, traceObserver) : baseTransport;
|
|
46513
|
-
const
|
|
45871
|
+
const client = this.createClient(serverName, definition);
|
|
46514
45872
|
try {
|
|
46515
|
-
await this.connectClientWithAbort(
|
|
46516
|
-
return { status: "connected", client
|
|
45873
|
+
await this.connectClientWithAbort(client, transport, requestOptions, signal);
|
|
45874
|
+
return { status: "connected", client, transport };
|
|
46517
45875
|
} catch (error) {
|
|
46518
45876
|
const abortCleanupFailed = error instanceof AggregateError && error.message === "MCP connection abort cleanup failed";
|
|
46519
45877
|
if (!abortCleanupFailed) {
|
|
46520
45878
|
try {
|
|
46521
|
-
await (abortCleanupPromises.get(transport) ??
|
|
45879
|
+
await (abortCleanupPromises.get(transport) ?? client.close());
|
|
46522
45880
|
} catch (cleanupError) {
|
|
46523
45881
|
throw new AggregateError([error, cleanupError], "MCP HTTP connection cleanup failed");
|
|
46524
45882
|
}
|
|
46525
45883
|
}
|
|
46526
|
-
return { status: "failed", client
|
|
45884
|
+
return { status: "failed", client, transport, error };
|
|
46527
45885
|
}
|
|
46528
45886
|
};
|
|
46529
45887
|
let kind = definition.httpTransport ?? "streamable-http";
|
|
@@ -46561,13 +45919,13 @@ var McpServerManager = class {
|
|
|
46561
45919
|
throw result.error;
|
|
46562
45920
|
}
|
|
46563
45921
|
}
|
|
46564
|
-
async fetchAllTools(
|
|
45922
|
+
async fetchAllTools(client, requestOptions) {
|
|
46565
45923
|
const allTools = [];
|
|
46566
45924
|
let cursor;
|
|
46567
45925
|
let hints;
|
|
46568
45926
|
let firstPage = true;
|
|
46569
45927
|
do {
|
|
46570
|
-
const result = await
|
|
45928
|
+
const result = await client.listTools(cursor ? { cursor } : void 0, requestOptions);
|
|
46571
45929
|
if (firstPage) {
|
|
46572
45930
|
const ttlMs = typeof result.ttlMs === "number" && Number.isSafeInteger(result.ttlMs) && result.ttlMs >= 0 ? result.ttlMs : void 0;
|
|
46573
45931
|
const cacheScope = result.cacheScope === "public" || result.cacheScope === "private" ? result.cacheScope : void 0;
|
|
@@ -46584,14 +45942,14 @@ var McpServerManager = class {
|
|
|
46584
45942
|
} while (cursor);
|
|
46585
45943
|
return { tools: allTools, ...hints !== void 0 ? { hints } : {} };
|
|
46586
45944
|
}
|
|
46587
|
-
async fetchAllPrompts(
|
|
46588
|
-
const capabilities =
|
|
45945
|
+
async fetchAllPrompts(client, requestOptions) {
|
|
45946
|
+
const capabilities = client.getServerCapabilities?.();
|
|
46589
45947
|
if (!capabilities?.prompts) return { prompts: [], failed: false };
|
|
46590
45948
|
try {
|
|
46591
45949
|
const prompts = [];
|
|
46592
45950
|
let cursor;
|
|
46593
45951
|
do {
|
|
46594
|
-
const result = await
|
|
45952
|
+
const result = await client.listPrompts(cursor ? { cursor } : void 0, requestOptions);
|
|
46595
45953
|
prompts.push(...result.prompts ?? []);
|
|
46596
45954
|
cursor = result.nextCursor;
|
|
46597
45955
|
} while (cursor);
|
|
@@ -46604,14 +45962,14 @@ var McpServerManager = class {
|
|
|
46604
45962
|
return { prompts: [], failed: true };
|
|
46605
45963
|
}
|
|
46606
45964
|
}
|
|
46607
|
-
async fetchAllResources(
|
|
46608
|
-
const capabilities =
|
|
45965
|
+
async fetchAllResources(client, requestOptions, strict = false) {
|
|
45966
|
+
const capabilities = client.getServerCapabilities?.();
|
|
46609
45967
|
if (!capabilities?.resources) return [];
|
|
46610
45968
|
try {
|
|
46611
45969
|
const allResources = [];
|
|
46612
45970
|
let cursor;
|
|
46613
45971
|
do {
|
|
46614
|
-
const result = await
|
|
45972
|
+
const result = await client.listResources(cursor ? { cursor } : void 0, requestOptions);
|
|
46615
45973
|
allResources.push(...result.resources ?? []);
|
|
46616
45974
|
cursor = result.nextCursor;
|
|
46617
45975
|
} while (cursor);
|
|
@@ -46625,11 +45983,11 @@ var McpServerManager = class {
|
|
|
46625
45983
|
return [];
|
|
46626
45984
|
}
|
|
46627
45985
|
}
|
|
46628
|
-
attachAdapterNotificationHandlers(serverName,
|
|
46629
|
-
|
|
45986
|
+
attachAdapterNotificationHandlers(serverName, client) {
|
|
45987
|
+
client.setNotificationHandler("notifications/resources/updated", (notification) => {
|
|
46630
45988
|
const uri = notification.params.uri;
|
|
46631
45989
|
const connection = this.connections.get(serverName);
|
|
46632
|
-
if (!connection || connection.client !==
|
|
45990
|
+
if (!connection || connection.client !== client || connection.status !== "connected") return;
|
|
46633
45991
|
for (const registration of this.resourceUpdatedListeners.values()) {
|
|
46634
45992
|
if (registration.serverName === serverName && registration.uri === uri) {
|
|
46635
45993
|
try {
|
|
@@ -46639,7 +45997,7 @@ var McpServerManager = class {
|
|
|
46639
45997
|
}
|
|
46640
45998
|
}
|
|
46641
45999
|
});
|
|
46642
|
-
|
|
46000
|
+
client.setNotificationHandler(
|
|
46643
46001
|
SERVER_STREAM_RESULT_PATCH_METHOD,
|
|
46644
46002
|
{ params: serverStreamResultPatchNotificationSchema.shape.params },
|
|
46645
46003
|
(params) => {
|
|
@@ -48347,7 +47705,7 @@ function getEffectiveIdleTimeoutMinutes(state, serverName) {
|
|
|
48347
47705
|
|
|
48348
47706
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/onboarding-state.ts
|
|
48349
47707
|
import { existsSync as existsSync13, mkdirSync as mkdirSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync2, renameSync as renameSync2 } from "fs";
|
|
48350
|
-
import { dirname as
|
|
47708
|
+
import { dirname as dirname13 } from "path";
|
|
48351
47709
|
var DEFAULT_STATE2 = {
|
|
48352
47710
|
version: 1,
|
|
48353
47711
|
sharedConfigHintShown: false,
|
|
@@ -48374,7 +47732,7 @@ function loadOnboardingState() {
|
|
|
48374
47732
|
}
|
|
48375
47733
|
function saveOnboardingState(state) {
|
|
48376
47734
|
const path7 = getOnboardingStatePath();
|
|
48377
|
-
mkdirSync3(
|
|
47735
|
+
mkdirSync3(dirname13(path7), { recursive: true });
|
|
48378
47736
|
const tmpPath = `${path7}.${process.pid}.tmp`;
|
|
48379
47737
|
writeFileSync2(tmpPath, `${JSON.stringify(state, null, 2)}
|
|
48380
47738
|
`, "utf-8");
|
|
@@ -49001,7 +48359,7 @@ async function openMcpAuthPanel(state, pi, ctx, configOverridePath) {
|
|
|
49001
48359
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/tool-registrar.ts
|
|
49002
48360
|
import { mkdtempSync, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
|
|
49003
48361
|
import { tmpdir } from "os";
|
|
49004
|
-
import { join as
|
|
48362
|
+
import { join as join25 } from "path";
|
|
49005
48363
|
var MAX_BINARY_RESOURCE_BYTES = 10 * 1024 * 1024;
|
|
49006
48364
|
var MAX_SESSION_RESOURCE_BYTES = 100 * 1024 * 1024;
|
|
49007
48365
|
var MAX_SESSION_RESOURCE_FILES = 1e4;
|
|
@@ -49108,11 +48466,11 @@ function materializeBinaryResource(resource, scope) {
|
|
|
49108
48466
|
return omitBinaryResource(resource, "session resource limit reached");
|
|
49109
48467
|
}
|
|
49110
48468
|
try {
|
|
49111
|
-
session.directory ??= mkdtempSync(
|
|
48469
|
+
session.directory ??= mkdtempSync(join25(tmpdir(), "pi-mcp-resource-"));
|
|
49112
48470
|
} catch {
|
|
49113
48471
|
return omitBinaryResource(resource, "could not be saved");
|
|
49114
48472
|
}
|
|
49115
|
-
const filePath =
|
|
48473
|
+
const filePath = join25(session.directory, `resource-${++session.sequence}.bin`);
|
|
49116
48474
|
session.bytes += decodedBytes;
|
|
49117
48475
|
session.files += 1;
|
|
49118
48476
|
try {
|
|
@@ -49203,9 +48561,9 @@ function stringifyStructuredContent(value) {
|
|
|
49203
48561
|
|
|
49204
48562
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/mcp-output-guard.ts
|
|
49205
48563
|
import { randomBytes as randomBytes4 } from "crypto";
|
|
49206
|
-
import { mkdtemp, rm as rm3, writeFile as
|
|
48564
|
+
import { mkdtemp, rm as rm3, writeFile as writeFile9 } from "fs/promises";
|
|
49207
48565
|
import { tmpdir as tmpdir2 } from "os";
|
|
49208
|
-
import { dirname as
|
|
48566
|
+
import { dirname as dirname14, join as join26 } from "path";
|
|
49209
48567
|
var DEFAULT_MCP_OUTPUT_MAX_BYTES = 50 * 1024;
|
|
49210
48568
|
var DEFAULT_MCP_OUTPUT_MAX_LINES = 2e3;
|
|
49211
48569
|
var DEFAULT_MCP_DETAILS_MAX_BYTES = 16 * 1024;
|
|
@@ -49513,9 +48871,9 @@ function serializedObjectEntryBytes(key, value, hasPrevious) {
|
|
|
49513
48871
|
}
|
|
49514
48872
|
async function saveArtifact(kind, text) {
|
|
49515
48873
|
try {
|
|
49516
|
-
const dir = await mkdtemp(
|
|
49517
|
-
const path7 =
|
|
49518
|
-
await
|
|
48874
|
+
const dir = await mkdtemp(join26(tmpdir2(), "pi-mcp-output-"));
|
|
48875
|
+
const path7 = join26(dir, `${kind}-${randomBytes4(4).toString("hex")}.txt`);
|
|
48876
|
+
await writeFile9(path7, text, { encoding: "utf8", mode: 384 });
|
|
49519
48877
|
return { path: path7 };
|
|
49520
48878
|
} catch (error) {
|
|
49521
48879
|
return { error: error instanceof Error ? error.message : String(error) };
|
|
@@ -49523,7 +48881,7 @@ async function saveArtifact(kind, text) {
|
|
|
49523
48881
|
}
|
|
49524
48882
|
async function discardArtifact(path7) {
|
|
49525
48883
|
try {
|
|
49526
|
-
await rm3(
|
|
48884
|
+
await rm3(dirname14(path7), { recursive: true, force: true });
|
|
49527
48885
|
} catch {
|
|
49528
48886
|
}
|
|
49529
48887
|
}
|
|
@@ -49563,14 +48921,14 @@ function formatSize(bytes) {
|
|
|
49563
48921
|
|
|
49564
48922
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/ui-session.ts
|
|
49565
48923
|
import { execFile as execFile6 } from "child_process";
|
|
49566
|
-
import { randomUUID as
|
|
48924
|
+
import { randomUUID as randomUUID9 } from "crypto";
|
|
49567
48925
|
import net from "net";
|
|
49568
48926
|
|
|
49569
48927
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/ui-server.ts
|
|
49570
48928
|
import http2 from "http";
|
|
49571
48929
|
import fs7 from "fs/promises";
|
|
49572
48930
|
import path6 from "path";
|
|
49573
|
-
import { randomUUID as
|
|
48931
|
+
import { randomUUID as randomUUID8 } from "crypto";
|
|
49574
48932
|
|
|
49575
48933
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/host-html-template.ts
|
|
49576
48934
|
var DEFAULT_APP_BRIDGE_MODULE_URL = "/app-bridge.bundle.js";
|
|
@@ -50232,7 +49590,7 @@ function safeInlineJSON2(value) {
|
|
|
50232
49590
|
}
|
|
50233
49591
|
|
|
50234
49592
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/tool-approval.ts
|
|
50235
|
-
import { createHash as createHash4, randomUUID as
|
|
49593
|
+
import { createHash as createHash4, randomUUID as randomUUID7 } from "crypto";
|
|
50236
49594
|
function stableStringify(value) {
|
|
50237
49595
|
if (value === null || value === void 0 || typeof value !== "object") {
|
|
50238
49596
|
const serialized = JSON.stringify(value);
|
|
@@ -50298,7 +49656,7 @@ async function requestBrokerApproval(state, serverName, toolMeta, args, origin,
|
|
|
50298
49656
|
let acceptingClaim = true;
|
|
50299
49657
|
let handler;
|
|
50300
49658
|
const request = {
|
|
50301
|
-
requestId:
|
|
49659
|
+
requestId: randomUUID7(),
|
|
50302
49660
|
serverName,
|
|
50303
49661
|
originalToolName: toolMeta.originalName,
|
|
50304
49662
|
prefixedToolName: toolMeta.name,
|
|
@@ -50377,8 +49735,8 @@ var MOSHI_DISCOVERY_PORT_START = 8377;
|
|
|
50377
49735
|
var MOSHI_DISCOVERY_PORT_END = 8396;
|
|
50378
49736
|
var nextMoshiDiscoveryPort = MOSHI_DISCOVERY_PORT_START;
|
|
50379
49737
|
async function startUiServer(options) {
|
|
50380
|
-
const sessionToken = options.sessionToken ??
|
|
50381
|
-
const uiResourceToken =
|
|
49738
|
+
const sessionToken = options.sessionToken ?? randomUUID8();
|
|
49739
|
+
const uiResourceToken = randomUUID8();
|
|
50382
49740
|
const log = logger.child({
|
|
50383
49741
|
component: "UiServer",
|
|
50384
49742
|
server: options.serverName,
|
|
@@ -50510,11 +49868,11 @@ data: ${JSON.stringify(payload)}
|
|
|
50510
49868
|
updateStreamSummary(eventId, payload);
|
|
50511
49869
|
pruneEventLog();
|
|
50512
49870
|
const chunk = serializeEvent(eventId, name, payload);
|
|
50513
|
-
for (const
|
|
49871
|
+
for (const client of sseClients) {
|
|
50514
49872
|
try {
|
|
50515
|
-
|
|
49873
|
+
client.write(chunk);
|
|
50516
49874
|
} catch {
|
|
50517
|
-
sseClients.delete(
|
|
49875
|
+
sseClients.delete(client);
|
|
50518
49876
|
}
|
|
50519
49877
|
}
|
|
50520
49878
|
};
|
|
@@ -50534,9 +49892,9 @@ data: ${JSON.stringify(payload)}
|
|
|
50534
49892
|
}
|
|
50535
49893
|
};
|
|
50536
49894
|
const closeSse = () => {
|
|
50537
|
-
for (const
|
|
49895
|
+
for (const client of sseClients) {
|
|
50538
49896
|
try {
|
|
50539
|
-
|
|
49897
|
+
client.end();
|
|
50540
49898
|
} catch {
|
|
50541
49899
|
}
|
|
50542
49900
|
}
|
|
@@ -51161,7 +50519,7 @@ function sendText(res, status, text) {
|
|
|
51161
50519
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/glimpse-ui.ts
|
|
51162
50520
|
import { existsSync as existsSync14 } from "fs";
|
|
51163
50521
|
import { execFileSync as execFileSync2 } from "child_process";
|
|
51164
|
-
import { join as
|
|
50522
|
+
import { join as join27, dirname as dirname15 } from "path";
|
|
51165
50523
|
import { platform as platform2 } from "os";
|
|
51166
50524
|
import { createRequire as createRequire3 } from "module";
|
|
51167
50525
|
var glimpseAvailable = null;
|
|
@@ -51183,20 +50541,20 @@ function getGlimpseBinaryPath() {
|
|
|
51183
50541
|
try {
|
|
51184
50542
|
const require6 = createRequire3(import.meta.url);
|
|
51185
50543
|
const glimpseuiPath = require6.resolve("glimpseui");
|
|
51186
|
-
const binaryPath =
|
|
50544
|
+
const binaryPath = join27(dirname15(glimpseuiPath), "glimpse");
|
|
51187
50545
|
if (existsSync14(binaryPath)) return binaryPath;
|
|
51188
50546
|
} catch {
|
|
51189
50547
|
}
|
|
51190
50548
|
try {
|
|
51191
50549
|
const globalRoot = execFileSync2("npm", ["root", "-g"], { encoding: "utf-8" }).trim();
|
|
51192
|
-
const binaryPath =
|
|
50550
|
+
const binaryPath = join27(globalRoot, "glimpseui", "src", "glimpse");
|
|
51193
50551
|
if (existsSync14(binaryPath)) return binaryPath;
|
|
51194
50552
|
} catch {
|
|
51195
50553
|
}
|
|
51196
50554
|
return null;
|
|
51197
50555
|
}
|
|
51198
50556
|
async function openGlimpseWindow(html, options) {
|
|
51199
|
-
const modulePath = resolvedBinaryPath ?
|
|
50557
|
+
const modulePath = resolvedBinaryPath ? join27(dirname15(resolvedBinaryPath), "glimpse.mjs") : "glimpseui";
|
|
51200
50558
|
const glimpse = await import(modulePath);
|
|
51201
50559
|
let active = true;
|
|
51202
50560
|
const win = glimpse.open(html, {
|
|
@@ -51337,8 +50695,8 @@ async function maybeStartUiSession(state, request) {
|
|
|
51337
50695
|
if (state.uiServer && state.uiServer.serverName === request.serverName && state.uiServer.toolName === request.toolName) {
|
|
51338
50696
|
const existingHandle = state.uiServer;
|
|
51339
50697
|
const streamMode2 = request.streamMode;
|
|
51340
|
-
const streamId2 = streamMode2 ?
|
|
51341
|
-
const streamToken2 = streamMode2 ?
|
|
50698
|
+
const streamId2 = streamMode2 ? randomUUID9() : void 0;
|
|
50699
|
+
const streamToken2 = streamMode2 ? randomUUID9() : void 0;
|
|
51342
50700
|
let active2 = true;
|
|
51343
50701
|
let nextStreamSequence2 = 0;
|
|
51344
50702
|
const cleanupStreamListener = () => {
|
|
@@ -51414,8 +50772,8 @@ async function maybeStartUiSession(state, request) {
|
|
|
51414
50772
|
activeGlimpseWindow = null;
|
|
51415
50773
|
}
|
|
51416
50774
|
const streamMode = request.streamMode;
|
|
51417
|
-
const streamId = streamMode ?
|
|
51418
|
-
const streamToken = streamMode ?
|
|
50775
|
+
const streamId = streamMode ? randomUUID9() : void 0;
|
|
50776
|
+
const streamToken = streamMode ? randomUUID9() : void 0;
|
|
51419
50777
|
const hostContext = streamMode && streamId ? {
|
|
51420
50778
|
[UI_STREAM_HOST_CONTEXT_KEY]: {
|
|
51421
50779
|
mode: streamMode,
|
|
@@ -51427,7 +50785,7 @@ async function maybeStartUiSession(state, request) {
|
|
|
51427
50785
|
let active = true;
|
|
51428
50786
|
let nextStreamSequence = 0;
|
|
51429
50787
|
let handle;
|
|
51430
|
-
const resourceListenerToken =
|
|
50788
|
+
const resourceListenerToken = randomUUID9();
|
|
51431
50789
|
const cleanupListeners = () => {
|
|
51432
50790
|
if (streamToken) {
|
|
51433
50791
|
state.manager.removeUiStreamListener(streamToken);
|
|
@@ -58986,7 +58344,7 @@ var pi_mcp_adapter_default = createMcpAdapter();
|
|
|
58986
58344
|
// src/managers/pi-manager.ts
|
|
58987
58345
|
async function getManagedPiMcpServers() {
|
|
58988
58346
|
try {
|
|
58989
|
-
const parsed = JSON.parse(await
|
|
58347
|
+
const parsed = JSON.parse(await readFile14(PI_MCP_CONFIG_PATH, "utf8"));
|
|
58990
58348
|
if (!isRecord2(parsed) || !isRecord2(parsed.mcpServers)) return {};
|
|
58991
58349
|
return Object.fromEntries(Object.entries(parsed.mcpServers).filter(
|
|
58992
58350
|
(entry) => isRecord2(entry[1]) && (typeof entry[1].command === "string" || typeof entry[1].url === "string")
|
|
@@ -59108,12 +58466,12 @@ var PiManager = class extends CodingAgentManager {
|
|
|
59108
58466
|
modelRuntime = null;
|
|
59109
58467
|
constructor(options) {
|
|
59110
58468
|
super(options);
|
|
59111
|
-
this.historyFilePath = options.historyFilePath ??
|
|
58469
|
+
this.historyFilePath = options.historyFilePath ?? join28(PI_HISTORY_DIR, `${Date.now()}.jsonl`);
|
|
59112
58470
|
this.historyFile = new CodexHistoryFile(this.historyFilePath);
|
|
59113
58471
|
this.initializeManager(this.processMessageInternal.bind(this));
|
|
59114
58472
|
}
|
|
59115
58473
|
async initialize() {
|
|
59116
|
-
await
|
|
58474
|
+
await mkdir17(dirname16(this.historyFilePath), { recursive: true });
|
|
59117
58475
|
}
|
|
59118
58476
|
getHistorySink() {
|
|
59119
58477
|
return this.historyFile;
|
|
@@ -59266,7 +58624,7 @@ var PiManager = class extends CodingAgentManager {
|
|
|
59266
58624
|
}
|
|
59267
58625
|
const resourceLoader = new DefaultResourceLoader({
|
|
59268
58626
|
cwd: this.workingDirectory,
|
|
59269
|
-
agentDir:
|
|
58627
|
+
agentDir: join28(ENGINE_ENV.HOME_DIR, ".pi", "agent"),
|
|
59270
58628
|
extensionFactories,
|
|
59271
58629
|
appendSystemPrompt: [this.buildCombinedInstructions() ?? ""]
|
|
59272
58630
|
});
|
|
@@ -59369,7 +58727,7 @@ function extractFinalResponse(history, provider) {
|
|
|
59369
58727
|
}
|
|
59370
58728
|
|
|
59371
58729
|
// src/analytics/agent/activity/agent-chat-activity-tracker-service.ts
|
|
59372
|
-
import { randomUUID as
|
|
58730
|
+
import { randomUUID as randomUUID10 } from "crypto";
|
|
59373
58731
|
|
|
59374
58732
|
// src/analytics/analytics-upload.ts
|
|
59375
58733
|
async function uploadAnalytics(endpoint, body) {
|
|
@@ -59382,14 +58740,14 @@ async function uploadAnalytics(endpoint, body) {
|
|
|
59382
58740
|
// src/analytics/analytics-record-buffer.ts
|
|
59383
58741
|
import {
|
|
59384
58742
|
appendFile as appendFile4,
|
|
59385
|
-
mkdir as
|
|
59386
|
-
readFile as
|
|
59387
|
-
readdir as
|
|
58743
|
+
mkdir as mkdir18,
|
|
58744
|
+
readFile as readFile15,
|
|
58745
|
+
readdir as readdir6,
|
|
59388
58746
|
rename as rename3,
|
|
59389
58747
|
unlink as unlink3
|
|
59390
58748
|
} from "fs/promises";
|
|
59391
58749
|
import { existsSync as existsSync15, readFileSync as readFileSync6, readdirSync as readdirSync3 } from "fs";
|
|
59392
|
-
import { join as
|
|
58750
|
+
import { join as join29 } from "path";
|
|
59393
58751
|
var MAX_FAILED_RECORDS = 500;
|
|
59394
58752
|
var FLUSH_DEBOUNCE_MS = 15e3;
|
|
59395
58753
|
var MAX_UPLOADED_SEGMENTS = 50;
|
|
@@ -59401,7 +58759,7 @@ var AnalyticsRecordBuffer = class {
|
|
|
59401
58759
|
options.storageName,
|
|
59402
58760
|
...options.legacyStorageNames ?? []
|
|
59403
58761
|
];
|
|
59404
|
-
this.liveFile =
|
|
58762
|
+
this.liveFile = join29(ENGINE_DIR2, `${options.storageName}.jsonl`);
|
|
59405
58763
|
this.segmentFilePatterns = this.storageNames.map(
|
|
59406
58764
|
(storageName) => new RegExp(`^${storageName}\\.(\\d+)\\.jsonl$`)
|
|
59407
58765
|
);
|
|
@@ -59424,7 +58782,7 @@ var AnalyticsRecordBuffer = class {
|
|
|
59424
58782
|
if (this.recordIds.has(recordId)) return;
|
|
59425
58783
|
this.recordIds.add(recordId);
|
|
59426
58784
|
}
|
|
59427
|
-
const pending =
|
|
58785
|
+
const pending = mkdir18(ENGINE_DIR2, { recursive: true }).then(() => appendFile4(this.liveFile, `${JSON.stringify(record3)}
|
|
59428
58786
|
`, "utf-8")).catch((error) => {
|
|
59429
58787
|
console.error(
|
|
59430
58788
|
`[${this.options.storageName}] Append failed, will retry on flush:`,
|
|
@@ -59439,7 +58797,7 @@ var AnalyticsRecordBuffer = class {
|
|
|
59439
58797
|
if (!existsSync15(ENGINE_DIR2)) return [];
|
|
59440
58798
|
return readdirSync3(ENGINE_DIR2, { withFileTypes: true }).filter((entry) => entry.isFile() && this.storageNames.some(
|
|
59441
58799
|
(storageName) => entry.name === `${storageName}.jsonl` || entry.name.startsWith(`${storageName}.`) && (entry.name.endsWith(".jsonl") || entry.name.endsWith(`.jsonl${UPLOADED_SUFFIX}`))
|
|
59442
|
-
)).map(({ name }) => name).sort().flatMap((name) => this.parseRecords(readFileSync6(
|
|
58800
|
+
)).map(({ name }) => name).sort().flatMap((name) => this.parseRecords(readFileSync6(join29(ENGINE_DIR2, name), "utf-8"))).map((record3) => {
|
|
59443
58801
|
const recordId = this.options.getRecordId?.(record3);
|
|
59444
58802
|
if (recordId) this.recordIds.add(recordId);
|
|
59445
58803
|
return record3;
|
|
@@ -59474,18 +58832,18 @@ var AnalyticsRecordBuffer = class {
|
|
|
59474
58832
|
}
|
|
59475
58833
|
for (const storageName of this.storageNames) {
|
|
59476
58834
|
await rename3(
|
|
59477
|
-
|
|
59478
|
-
|
|
58835
|
+
join29(ENGINE_DIR2, `${storageName}.jsonl`),
|
|
58836
|
+
join29(ENGINE_DIR2, `${storageName}.${Date.now()}.jsonl`)
|
|
59479
58837
|
).catch(() => {
|
|
59480
58838
|
});
|
|
59481
58839
|
}
|
|
59482
|
-
const entries = await
|
|
58840
|
+
const entries = await readdir6(ENGINE_DIR2).catch(() => []);
|
|
59483
58841
|
let flushed = 0;
|
|
59484
58842
|
let failed = 0;
|
|
59485
58843
|
for (const entry of entries) {
|
|
59486
58844
|
if (!this.segmentFilePatterns.some((pattern) => pattern.test(entry))) continue;
|
|
59487
58845
|
try {
|
|
59488
|
-
await this.uploadSegment(
|
|
58846
|
+
await this.uploadSegment(join29(ENGINE_DIR2, entry));
|
|
59489
58847
|
flushed++;
|
|
59490
58848
|
} catch (error) {
|
|
59491
58849
|
failed++;
|
|
@@ -59514,14 +58872,14 @@ var AnalyticsRecordBuffer = class {
|
|
|
59514
58872
|
(storageName) => entry.startsWith(`${storageName}.`)
|
|
59515
58873
|
) && entry.endsWith(UPLOADED_SUFFIX)).sort();
|
|
59516
58874
|
for (const entry of uploaded.slice(0, -MAX_UPLOADED_SEGMENTS)) {
|
|
59517
|
-
await unlink3(
|
|
58875
|
+
await unlink3(join29(ENGINE_DIR2, entry)).catch(() => {
|
|
59518
58876
|
});
|
|
59519
58877
|
}
|
|
59520
58878
|
}
|
|
59521
58879
|
return { flushed, failed };
|
|
59522
58880
|
}
|
|
59523
58881
|
async uploadSegment(filePath) {
|
|
59524
|
-
const records = this.parseRecords(await
|
|
58882
|
+
const records = this.parseRecords(await readFile15(filePath, "utf-8"));
|
|
59525
58883
|
if (records.length > 0) await this.options.upload(records);
|
|
59526
58884
|
await rename3(filePath, `${filePath}${UPLOADED_SUFFIX}`).catch(() => {
|
|
59527
58885
|
});
|
|
@@ -59539,7 +58897,7 @@ var AnalyticsRecordBuffer = class {
|
|
|
59539
58897
|
};
|
|
59540
58898
|
|
|
59541
58899
|
// src/analytics/agent/activity/skill-mcp-call-extractor.ts
|
|
59542
|
-
var NON_MCP_SERVERS = /* @__PURE__ */ new Set(["claude", "cursor", "
|
|
58900
|
+
var NON_MCP_SERVERS = /* @__PURE__ */ new Set(["claude", "cursor", "muse", "opencode", "pi", "custom", "dynamic"]);
|
|
59543
58901
|
function mcpNameFromToolCall(message) {
|
|
59544
58902
|
const parsedName = parseMcpToolName(message.tool);
|
|
59545
58903
|
if (parsedName) return parsedName.server;
|
|
@@ -59629,7 +58987,7 @@ var AgentChatTurnActivityTracker = class {
|
|
|
59629
58987
|
this.pendingMessages.delete(messageId);
|
|
59630
58988
|
const context = {
|
|
59631
58989
|
chatId,
|
|
59632
|
-
turnId:
|
|
58990
|
+
turnId: randomUUID10(),
|
|
59633
58991
|
provider,
|
|
59634
58992
|
model: attributes.model ?? getDefaultAgentModel(provider),
|
|
59635
58993
|
senderUserId: attributes.senderUserId,
|
|
@@ -60303,9 +59661,9 @@ var KeepAliveService = class _KeepAliveService {
|
|
|
60303
59661
|
var keepAliveService = new KeepAliveService();
|
|
60304
59662
|
|
|
60305
59663
|
// src/services/canvas-service.ts
|
|
60306
|
-
import { readdir as
|
|
59664
|
+
import { readdir as readdir7, readFile as readFile17, stat as stat4 } from "fs/promises";
|
|
60307
59665
|
import { homedir as homedir13 } from "os";
|
|
60308
|
-
import { join as
|
|
59666
|
+
import { join as join30 } from "path";
|
|
60309
59667
|
|
|
60310
59668
|
// src/utils/contained-file.ts
|
|
60311
59669
|
import { realpath, stat as stat3 } from "fs/promises";
|
|
@@ -60331,9 +59689,9 @@ function fileRevision(content) {
|
|
|
60331
59689
|
}
|
|
60332
59690
|
|
|
60333
59691
|
// src/utils/revisioned-text-file.ts
|
|
60334
|
-
import { readFile as
|
|
59692
|
+
import { readFile as readFile16 } from "fs/promises";
|
|
60335
59693
|
async function writeRevisionedTextFile(filePath, content, expectedRevision) {
|
|
60336
|
-
const current = await
|
|
59694
|
+
const current = await readFile16(filePath, "utf8");
|
|
60337
59695
|
const revision = fileRevision(current);
|
|
60338
59696
|
if (revision !== expectedRevision) {
|
|
60339
59697
|
return {
|
|
@@ -60347,15 +59705,15 @@ async function writeRevisionedTextFile(filePath, content, expectedRevision) {
|
|
|
60347
59705
|
|
|
60348
59706
|
// src/services/canvas-service.ts
|
|
60349
59707
|
var GLOBAL_CANVAS_DIRECTORIES = [
|
|
60350
|
-
|
|
60351
|
-
|
|
60352
|
-
|
|
59708
|
+
join30(homedir13(), ".claude", "plans"),
|
|
59709
|
+
join30(process.env.XDG_DATA_HOME ?? join30(homedir13(), ".local", "share"), "opencode", "plans"),
|
|
59710
|
+
join30(homedir13(), ".replicas", "canvas")
|
|
60353
59711
|
];
|
|
60354
59712
|
async function canvasDirectories() {
|
|
60355
59713
|
const repositories = await gitService.listRepositories().catch(() => []);
|
|
60356
59714
|
return [
|
|
60357
59715
|
...GLOBAL_CANVAS_DIRECTORIES,
|
|
60358
|
-
...repositories.map((repository) =>
|
|
59716
|
+
...repositories.map((repository) => join30(repository.path, ".opencode", "plans"))
|
|
60359
59717
|
];
|
|
60360
59718
|
}
|
|
60361
59719
|
var CanvasService = class {
|
|
@@ -60373,14 +59731,14 @@ var CanvasService = class {
|
|
|
60373
59731
|
if (!current) continue;
|
|
60374
59732
|
let entries;
|
|
60375
59733
|
try {
|
|
60376
|
-
entries = await
|
|
59734
|
+
entries = await readdir7(current.directory, { withFileTypes: true });
|
|
60377
59735
|
} catch {
|
|
60378
59736
|
continue;
|
|
60379
59737
|
}
|
|
60380
59738
|
for (const entry of entries) {
|
|
60381
59739
|
if (entry.name.startsWith(".")) continue;
|
|
60382
59740
|
const filename = current.relativePath ? `${current.relativePath}/${entry.name}` : entry.name;
|
|
60383
|
-
const filePath =
|
|
59741
|
+
const filePath = join30(current.directory, entry.name);
|
|
60384
59742
|
if (entry.isDirectory()) {
|
|
60385
59743
|
pending.push({ directory: filePath, relativePath: filename });
|
|
60386
59744
|
continue;
|
|
@@ -60405,7 +59763,7 @@ var CanvasService = class {
|
|
|
60405
59763
|
if (!safe) return null;
|
|
60406
59764
|
const { kind, mimeType } = classifyCanvasFilename(safe);
|
|
60407
59765
|
for (const directory of await this.directories()) {
|
|
60408
|
-
const filePath =
|
|
59766
|
+
const filePath = join30(directory, safe);
|
|
60409
59767
|
let sizeBytes = 0;
|
|
60410
59768
|
let updatedAt = "";
|
|
60411
59769
|
try {
|
|
@@ -60426,7 +59784,7 @@ var CanvasService = class {
|
|
|
60426
59784
|
};
|
|
60427
59785
|
}
|
|
60428
59786
|
try {
|
|
60429
|
-
const bytes = await
|
|
59787
|
+
const bytes = await readFile17(filePath);
|
|
60430
59788
|
return { filename: safe, kind, sizeBytes, mimeType, updatedAt, bytes };
|
|
60431
59789
|
} catch {
|
|
60432
59790
|
continue;
|
|
@@ -60588,14 +59946,14 @@ async function reconcileCanvasItems(filenames) {
|
|
|
60588
59946
|
// src/services/upload-chat-transcripts.ts
|
|
60589
59947
|
import { createReadStream as createReadStream2 } from "fs";
|
|
60590
59948
|
import { createHash as createHash7 } from "crypto";
|
|
60591
|
-
import { readFile as
|
|
60592
|
-
import { basename as basename3, join as
|
|
59949
|
+
import { readFile as readFile18, readdir as readdir8, stat as stat5 } from "fs/promises";
|
|
59950
|
+
import { basename as basename3, join as join32 } from "path";
|
|
60593
59951
|
|
|
60594
59952
|
// src/services/chat/chat-senders.ts
|
|
60595
|
-
import { join as
|
|
60596
|
-
var CHAT_SENDERS_DIR =
|
|
59953
|
+
import { join as join31 } from "path";
|
|
59954
|
+
var CHAT_SENDERS_DIR = join31(ENGINE_DIR2, "chat-senders");
|
|
60597
59955
|
function chatMessageSendersFilePath(chatId) {
|
|
60598
|
-
return
|
|
59956
|
+
return join31(CHAT_SENDERS_DIR, `${chatId}.jsonl`);
|
|
60599
59957
|
}
|
|
60600
59958
|
function parseChatMessageSendersJsonl(content) {
|
|
60601
59959
|
return content.split("\n").flatMap((line) => {
|
|
@@ -60628,7 +59986,7 @@ async function flushAllChatTranscripts(chatsById = /* @__PURE__ */ new Map(), ca
|
|
|
60628
59986
|
for (const dir of HISTORY_DIRS) {
|
|
60629
59987
|
let entries;
|
|
60630
59988
|
try {
|
|
60631
|
-
entries = await
|
|
59989
|
+
entries = await readdir8(dir);
|
|
60632
59990
|
} catch {
|
|
60633
59991
|
continue;
|
|
60634
59992
|
}
|
|
@@ -60638,7 +59996,7 @@ async function flushAllChatTranscripts(chatsById = /* @__PURE__ */ new Map(), ca
|
|
|
60638
59996
|
const chat = chatsById.get(chatId);
|
|
60639
59997
|
if (!shouldFlushChatTranscript(dir, chat, chatsById)) continue;
|
|
60640
59998
|
tasks.push(
|
|
60641
|
-
uploadChatTranscript(chatId,
|
|
59999
|
+
uploadChatTranscript(chatId, join32(dir, entry), chat, capture).then((artifact) => {
|
|
60642
60000
|
flushed++;
|
|
60643
60001
|
if (artifact && capture) revisions.push(artifact);
|
|
60644
60002
|
}).catch((err) => {
|
|
@@ -60686,7 +60044,7 @@ async function uploadChatTranscriptNow(chatId, filePath, chat, capture) {
|
|
|
60686
60044
|
}
|
|
60687
60045
|
try {
|
|
60688
60046
|
metadata.senders = parseChatMessageSendersJsonl(
|
|
60689
|
-
await
|
|
60047
|
+
await readFile18(chatMessageSendersFilePath(chatId), "utf-8")
|
|
60690
60048
|
);
|
|
60691
60049
|
} catch (error) {
|
|
60692
60050
|
if (!(error && typeof error === "object" && "code" in error && error.code === "ENOENT")) throw error;
|
|
@@ -60725,8 +60083,8 @@ async function uploadChatTranscriptNow(chatId, filePath, chat, capture) {
|
|
|
60725
60083
|
|
|
60726
60084
|
// src/services/upload-engine-logs.ts
|
|
60727
60085
|
import { createReadStream as createReadStream3 } from "fs";
|
|
60728
|
-
import { readdir as
|
|
60729
|
-
import { join as
|
|
60086
|
+
import { readdir as readdir9, stat as stat6 } from "fs/promises";
|
|
60087
|
+
import { join as join33 } from "path";
|
|
60730
60088
|
var MAX_ENGINE_LOG_FLUSH_SESSIONS = 10;
|
|
60731
60089
|
var MAX_ENGINE_LOG_FLUSH_BYTES = 5 * 1024 * 1024;
|
|
60732
60090
|
var ENGINE_LOG_FLUSH_TIMEOUT_MS = 2e4;
|
|
@@ -60736,7 +60094,7 @@ async function flushAllEngineLogs() {
|
|
|
60736
60094
|
let failed = 0;
|
|
60737
60095
|
const deadline = Date.now() + ENGINE_LOG_FLUSH_TIMEOUT_MS;
|
|
60738
60096
|
await runBeforeDeadline((signal) => engineLogger.flush(signal), deadline);
|
|
60739
|
-
const files = await runBeforeDeadline(() =>
|
|
60097
|
+
const files = await runBeforeDeadline(() => readdir9(LOG_DIR), deadline).catch(() => []);
|
|
60740
60098
|
const currentFilename = engineLogger.sessionId ? `${engineLogger.sessionId}.log` : null;
|
|
60741
60099
|
const filenames = files.filter((filename) => {
|
|
60742
60100
|
if (!filename.endsWith(".log")) return false;
|
|
@@ -60755,7 +60113,7 @@ async function flushAllEngineLogs() {
|
|
|
60755
60113
|
const candidates = (await Promise.all(filenames.slice(0, MAX_ENGINE_LOG_FLUSH_SESSIONS).map(async (filename) => {
|
|
60756
60114
|
try {
|
|
60757
60115
|
const sessionId = filename.slice(0, -".log".length);
|
|
60758
|
-
const filePath =
|
|
60116
|
+
const filePath = join33(LOG_DIR, filename);
|
|
60759
60117
|
const fileStat = await runBeforeDeadline(() => stat6(filePath), deadline);
|
|
60760
60118
|
if (!fileStat.isFile()) {
|
|
60761
60119
|
skipped++;
|
|
@@ -60851,8 +60209,8 @@ async function uploadEngineLog(input, timeoutMs) {
|
|
|
60851
60209
|
}
|
|
60852
60210
|
|
|
60853
60211
|
// src/services/chat/fork-handoff.ts
|
|
60854
|
-
import { mkdir as
|
|
60855
|
-
import { join as
|
|
60212
|
+
import { mkdir as mkdir19, open as open3, writeFile as writeFile10 } from "fs/promises";
|
|
60213
|
+
import { join as join34 } from "path";
|
|
60856
60214
|
var EXCERPT_MAX_CHARS = 24e3;
|
|
60857
60215
|
var MAX_SANITIZED_SOURCE_BYTES = 32 * 1024 * 1024;
|
|
60858
60216
|
function unansweredRequest(blocks) {
|
|
@@ -60887,7 +60245,7 @@ function tailBlocks(blocks, maxChars) {
|
|
|
60887
60245
|
return { excerpt, truncated: start > 0 };
|
|
60888
60246
|
}
|
|
60889
60247
|
async function buildForkHandoff(input) {
|
|
60890
|
-
const rawHistoryPath =
|
|
60248
|
+
const rawHistoryPath = join34(HISTORY_DIR_BY_PROVIDER[input.sourceProvider], `${input.sourceChatId}.jsonl`);
|
|
60891
60249
|
const { content, truncated: sourceTruncated } = await readHistoryTail(rawHistoryPath, MAX_SANITIZED_SOURCE_BYTES);
|
|
60892
60250
|
let blocks = canonicalizeChatTranscriptBlocks(content, input.executionProvider, input.senders);
|
|
60893
60251
|
if (input.turnLimit !== void 0) {
|
|
@@ -60895,13 +60253,13 @@ async function buildForkHandoff(input) {
|
|
|
60895
60253
|
const start = blocks.findLastIndex((block) => block.startsWith("## User") && ++turns === input.turnLimit);
|
|
60896
60254
|
blocks = blocks.slice(Math.max(0, start));
|
|
60897
60255
|
}
|
|
60898
|
-
const forkDir =
|
|
60899
|
-
await
|
|
60900
|
-
const transcriptPath =
|
|
60256
|
+
const forkDir = join34(FORKS_DIR, input.targetChatId);
|
|
60257
|
+
await mkdir19(forkDir, { recursive: true });
|
|
60258
|
+
const transcriptPath = join34(forkDir, "source-transcript.md");
|
|
60901
60259
|
const header = sourceTruncated ? `_This file was generated from only the most recent ${MAX_SANITIZED_SOURCE_BYTES / 1024 / 1024} MB of the source chat.${input.turnLimit === void 0 ? ` The complete raw event log is at ${rawHistoryPath}; grep it for anything earlier.` : ""}_
|
|
60902
60260
|
|
|
60903
60261
|
` : "";
|
|
60904
|
-
await
|
|
60262
|
+
await writeFile10(transcriptPath, `${header}${blocks.join("\n\n")}
|
|
60905
60263
|
`, "utf-8");
|
|
60906
60264
|
const { excerpt, truncated } = tailBlocks(blocks, EXCERPT_MAX_CHARS);
|
|
60907
60265
|
return {
|
|
@@ -61049,13 +60407,13 @@ var ChatService = class {
|
|
|
61049
60407
|
persistPromise = null;
|
|
61050
60408
|
persistQueued = false;
|
|
61051
60409
|
async initialize() {
|
|
61052
|
-
await
|
|
61053
|
-
await
|
|
61054
|
-
await
|
|
61055
|
-
await
|
|
61056
|
-
await
|
|
61057
|
-
await
|
|
61058
|
-
await
|
|
60410
|
+
await mkdir20(ENGINE_DIR2, { recursive: true });
|
|
60411
|
+
await mkdir20(CLAUDE_HISTORY_DIR, { recursive: true });
|
|
60412
|
+
await mkdir20(RELAY_HISTORY_DIR, { recursive: true });
|
|
60413
|
+
await mkdir20(CODEX_HISTORY_DIR, { recursive: true });
|
|
60414
|
+
await mkdir20(CURSOR_HISTORY_DIR, { recursive: true });
|
|
60415
|
+
await mkdir20(OPENCODE_HISTORY_DIR, { recursive: true });
|
|
60416
|
+
await mkdir20(CHAT_SENDERS_DIR, { recursive: true });
|
|
61059
60417
|
const persisted = await this.loadChats();
|
|
61060
60418
|
for (const chat of persisted) {
|
|
61061
60419
|
const runtime = this.createRuntimeChat(chat);
|
|
@@ -61141,7 +60499,7 @@ var ChatService = class {
|
|
|
61141
60499
|
}
|
|
61142
60500
|
const source = request.forkSourceChatId ? this.requireChat(request.forkSourceChatId) : void 0;
|
|
61143
60501
|
const persisted = {
|
|
61144
|
-
id: request.id ??
|
|
60502
|
+
id: request.id ?? randomUUID11(),
|
|
61145
60503
|
provider: request.provider,
|
|
61146
60504
|
...relayBaseProvider ? { relayBaseProvider } : {},
|
|
61147
60505
|
title,
|
|
@@ -61418,7 +60776,7 @@ var ChatService = class {
|
|
|
61418
60776
|
}
|
|
61419
60777
|
}
|
|
61420
60778
|
async readSenders(chatId) {
|
|
61421
|
-
return
|
|
60779
|
+
return readFile19(chatMessageSendersFilePath(chatId), "utf-8").then(parseChatMessageSendersJsonl).catch((error) => {
|
|
61422
60780
|
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return [];
|
|
61423
60781
|
console.error("[ChatService] Failed to read sender records:", error);
|
|
61424
60782
|
return [];
|
|
@@ -61665,14 +61023,14 @@ var ChatService = class {
|
|
|
61665
61023
|
return descendants;
|
|
61666
61024
|
}
|
|
61667
61025
|
async deleteHistoryFile(persisted) {
|
|
61668
|
-
const historyPath =
|
|
61026
|
+
const historyPath = join35(HISTORY_DIR_BY_PROVIDER[persisted.provider], `${persisted.id}.jsonl`);
|
|
61669
61027
|
await Promise.all([
|
|
61670
61028
|
historyPath,
|
|
61671
61029
|
`${historyPath}.pages.jsonl`,
|
|
61672
61030
|
`${historyPath}.pages.index.json`
|
|
61673
61031
|
].map((path7) => rm4(path7, { force: true })));
|
|
61674
61032
|
await rm4(chatMessageSendersFilePath(persisted.id), { force: true });
|
|
61675
|
-
await rm4(
|
|
61033
|
+
await rm4(join35(FORKS_DIR, persisted.id), { recursive: true, force: true });
|
|
61676
61034
|
}
|
|
61677
61035
|
/** Resolves once the target chat exists; the handoff and its first turn run in the background. */
|
|
61678
61036
|
async forkChat(sourceChatId, request, trigger = "manual", reason) {
|
|
@@ -61868,7 +61226,7 @@ var ChatService = class {
|
|
|
61868
61226
|
const chatId = chat.persisted.id;
|
|
61869
61227
|
uploadChatTranscript(
|
|
61870
61228
|
chatId,
|
|
61871
|
-
|
|
61229
|
+
join35(HISTORY_DIR_BY_PROVIDER[chat.persisted.provider], `${chatId}.jsonl`),
|
|
61872
61230
|
this.toTranscriptSource(chat)
|
|
61873
61231
|
).catch((err) => {
|
|
61874
61232
|
console.error("[ChatService] Failed to upload chat transcript:", { chatId, err });
|
|
@@ -61951,7 +61309,7 @@ var ChatService = class {
|
|
|
61951
61309
|
}
|
|
61952
61310
|
const baseProvider = getChatExecutionProvider(persisted);
|
|
61953
61311
|
const additionalInstructions = persisted.provider === "relay" ? buildRelayInstructions(this.workingDirectory) : void 0;
|
|
61954
|
-
const historyFilePath =
|
|
61312
|
+
const historyFilePath = join35(HISTORY_DIR_BY_PROVIDER[persisted.provider], `${persisted.id}.jsonl`);
|
|
61955
61313
|
const managerOptions = {
|
|
61956
61314
|
provider: baseProvider,
|
|
61957
61315
|
workingDirectory: this.workingDirectory,
|
|
@@ -61973,10 +61331,6 @@ var ChatService = class {
|
|
|
61973
61331
|
provider = new ClaudeManager(managerOptions);
|
|
61974
61332
|
} else if (baseProvider === "cursor") {
|
|
61975
61333
|
provider = new CursorManager(managerOptions);
|
|
61976
|
-
} else if (baseProvider === "fx") {
|
|
61977
|
-
provider = new FxManager(managerOptions);
|
|
61978
|
-
} else if (baseProvider === "kimi") {
|
|
61979
|
-
provider = new KimiManager(managerOptions);
|
|
61980
61334
|
} else if (baseProvider === "muse") {
|
|
61981
61335
|
provider = new MuseManager(managerOptions);
|
|
61982
61336
|
} else if (baseProvider === "opencode") {
|
|
@@ -61999,7 +61353,7 @@ var ChatService = class {
|
|
|
61999
61353
|
}
|
|
62000
61354
|
return {
|
|
62001
61355
|
persisted,
|
|
62002
|
-
historyVersion:
|
|
61356
|
+
historyVersion: randomUUID11(),
|
|
62003
61357
|
provider,
|
|
62004
61358
|
pendingMessageIds: [],
|
|
62005
61359
|
acceptedUserEvents: /* @__PURE__ */ new Map(),
|
|
@@ -62239,7 +61593,7 @@ var ChatService = class {
|
|
|
62239
61593
|
}
|
|
62240
61594
|
async loadChats() {
|
|
62241
61595
|
try {
|
|
62242
|
-
const content = await
|
|
61596
|
+
const content = await readFile19(CHATS_FILE, "utf-8");
|
|
62243
61597
|
return parsePersistedChatsContent(content);
|
|
62244
61598
|
} catch (error) {
|
|
62245
61599
|
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
|
|
@@ -62254,7 +61608,7 @@ var ChatService = class {
|
|
|
62254
61608
|
console.error("[ChatService] Failed to quarantine corrupt chats file:", renameError);
|
|
62255
61609
|
}
|
|
62256
61610
|
try {
|
|
62257
|
-
const backupContent = await
|
|
61611
|
+
const backupContent = await readFile19(CHATS_BACKUP_FILE, "utf-8");
|
|
62258
61612
|
return parsePersistedChatsContent(backupContent);
|
|
62259
61613
|
} catch (backupError) {
|
|
62260
61614
|
if (backupError && typeof backupError === "object" && "code" in backupError && backupError.code === "ENOENT") {
|
|
@@ -62291,7 +61645,7 @@ var ChatService = class {
|
|
|
62291
61645
|
}
|
|
62292
61646
|
async publish(input) {
|
|
62293
61647
|
const event = {
|
|
62294
|
-
id:
|
|
61648
|
+
id: randomUUID11(),
|
|
62295
61649
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
62296
61650
|
...input
|
|
62297
61651
|
};
|
|
@@ -62357,14 +61711,14 @@ var ChatService = class {
|
|
|
62357
61711
|
|
|
62358
61712
|
// src/services/repo-file-service.ts
|
|
62359
61713
|
import { execFile as execFile7 } from "child_process";
|
|
62360
|
-
import { readFile as
|
|
61714
|
+
import { readFile as readFile20 } from "fs/promises";
|
|
62361
61715
|
import { extname as extname3 } from "path";
|
|
62362
61716
|
|
|
62363
61717
|
// src/services/language-server-service.ts
|
|
62364
|
-
import { spawn as
|
|
61718
|
+
import { spawn as spawn6 } from "child_process";
|
|
62365
61719
|
import { existsSync as existsSync16, readFileSync as readFileSync7 } from "fs";
|
|
62366
61720
|
import { createRequire as createRequire5 } from "module";
|
|
62367
|
-
import { delimiter as delimiter2, dirname as
|
|
61721
|
+
import { delimiter as delimiter2, dirname as dirname17, join as join36, relative as relative2 } from "path";
|
|
62368
61722
|
import { setTimeout as setTimeout2 } from "timers/promises";
|
|
62369
61723
|
import { fileURLToPath as fileURLToPath5, pathToFileURL } from "url";
|
|
62370
61724
|
import { createMessageConnection, StreamMessageReader, StreamMessageWriter } from "vscode-jsonrpc/node.js";
|
|
@@ -62405,7 +61759,7 @@ function packageBin(packageName, binName) {
|
|
|
62405
61759
|
const packageJson = JSON.parse(readFileSync7(packageJsonPath, "utf8"));
|
|
62406
61760
|
const bin = typeof packageJson.bin === "string" ? packageJson.bin : packageJson.bin[binName];
|
|
62407
61761
|
if (!bin) throw new Error(`Missing ${binName} binary`);
|
|
62408
|
-
return `${
|
|
61762
|
+
return `${dirname17(packageJsonPath)}/${bin}`;
|
|
62409
61763
|
}
|
|
62410
61764
|
function markdownText(value) {
|
|
62411
61765
|
if (typeof value === "string") return value;
|
|
@@ -62416,7 +61770,7 @@ function markdownText(value) {
|
|
|
62416
61770
|
var LanguageServerClient = class {
|
|
62417
61771
|
constructor(command, args, rootPath) {
|
|
62418
61772
|
this.rootPath = rootPath;
|
|
62419
|
-
this.process =
|
|
61773
|
+
this.process = spawn6(command, args, {
|
|
62420
61774
|
cwd: rootPath,
|
|
62421
61775
|
stdio: ["pipe", "pipe", "pipe"],
|
|
62422
61776
|
env: { ...process.env, ...command.includes("rust-analyzer") && { RA_LOG: "rust_analyzer=error" } }
|
|
@@ -62483,18 +61837,18 @@ var LanguageServerService = class {
|
|
|
62483
61837
|
if (config.package && config.bin) command = process.execPath;
|
|
62484
61838
|
else if (config.command) {
|
|
62485
61839
|
const commandName = config.command;
|
|
62486
|
-
command = process.env.PATH?.split(delimiter2).map((directory) =>
|
|
61840
|
+
command = process.env.PATH?.split(delimiter2).map((directory) => join36(directory, commandName)).find(existsSync16);
|
|
62487
61841
|
}
|
|
62488
61842
|
const args = config.package && config.bin ? [packageBin(config.package, config.bin), ...config.args] : config.args;
|
|
62489
61843
|
if (!command) return null;
|
|
62490
61844
|
const key = `${repoPath}:${languageId}`;
|
|
62491
|
-
let
|
|
62492
|
-
if (!
|
|
62493
|
-
|
|
62494
|
-
this.clients.set(key,
|
|
61845
|
+
let client = this.clients.get(key);
|
|
61846
|
+
if (!client) {
|
|
61847
|
+
client = new LanguageServerClient(command, args, repoPath);
|
|
61848
|
+
this.clients.set(key, client);
|
|
62495
61849
|
}
|
|
62496
61850
|
try {
|
|
62497
|
-
const result = await
|
|
61851
|
+
const result = await client.inspect(filePath, languageId, content, line, character, action);
|
|
62498
61852
|
if (action === "hover") {
|
|
62499
61853
|
const detail = result && !Array.isArray(result) && "contents" in result ? markdownText(result.contents) : null;
|
|
62500
61854
|
return detail ? { symbol: "", detail, documentation: null, locations: [], provider: "language-server" } : null;
|
|
@@ -62511,7 +61865,7 @@ var LanguageServerService = class {
|
|
|
62511
61865
|
});
|
|
62512
61866
|
return { symbol: "", detail: null, documentation: null, locations, provider: "language-server" };
|
|
62513
61867
|
} catch {
|
|
62514
|
-
|
|
61868
|
+
client.dispose();
|
|
62515
61869
|
this.clients.delete(key);
|
|
62516
61870
|
return null;
|
|
62517
61871
|
}
|
|
@@ -62654,7 +62008,7 @@ var RepoFileService = class {
|
|
|
62654
62008
|
sizeBytes,
|
|
62655
62009
|
binary: true,
|
|
62656
62010
|
tooLarge: false,
|
|
62657
|
-
base64: (await
|
|
62011
|
+
base64: (await readFile20(fullPath)).toString("base64"),
|
|
62658
62012
|
mimeType
|
|
62659
62013
|
};
|
|
62660
62014
|
}
|
|
@@ -62679,7 +62033,7 @@ var RepoFileService = class {
|
|
|
62679
62033
|
tooLarge: true
|
|
62680
62034
|
};
|
|
62681
62035
|
}
|
|
62682
|
-
const content = await
|
|
62036
|
+
const content = await readFile20(fullPath, "utf-8");
|
|
62683
62037
|
return {
|
|
62684
62038
|
repoName,
|
|
62685
62039
|
path: filePath,
|
|
@@ -62711,7 +62065,7 @@ var RepoFileService = class {
|
|
|
62711
62065
|
async inspectSymbol(repoName, filePath, line, character, action) {
|
|
62712
62066
|
const resolved = await this.resolveFile(repoName, filePath);
|
|
62713
62067
|
if (!resolved || line < 1 || character < 0 || isBinaryExtension(filePath)) return null;
|
|
62714
|
-
const content = await
|
|
62068
|
+
const content = await readFile20(resolved.fullPath, "utf8");
|
|
62715
62069
|
const sourceLine = content.split("\n")[line - 1];
|
|
62716
62070
|
if (sourceLine === void 0) return null;
|
|
62717
62071
|
const symbolMatch = Array.from(sourceLine.matchAll(/[\p{L}_$][\p{L}\p{N}_$]*/gu)).find((match) => character >= match.index && character <= match.index + match[0].length);
|
|
@@ -62824,21 +62178,21 @@ var RepoFileService = class {
|
|
|
62824
62178
|
// src/v1-routes.ts
|
|
62825
62179
|
import { Hono } from "hono";
|
|
62826
62180
|
import { z as z4 } from "zod";
|
|
62827
|
-
import { readdir as
|
|
62828
|
-
import { join as
|
|
62181
|
+
import { readdir as readdir11, stat as stat7, readFile as readFile23 } from "fs/promises";
|
|
62182
|
+
import { join as join39, resolve as resolve6 } from "path";
|
|
62829
62183
|
|
|
62830
62184
|
// src/services/warm-hooks-service.ts
|
|
62831
|
-
import { spawn as
|
|
62832
|
-
import { readFile as
|
|
62185
|
+
import { spawn as spawn7 } from "child_process";
|
|
62186
|
+
import { readFile as readFile22 } from "fs/promises";
|
|
62833
62187
|
import { existsSync as existsSync17 } from "fs";
|
|
62834
|
-
import { join as
|
|
62188
|
+
import { join as join38 } from "path";
|
|
62835
62189
|
|
|
62836
62190
|
// src/services/warm-hook-logs-service.ts
|
|
62837
|
-
import { mkdir as
|
|
62191
|
+
import { mkdir as mkdir21, readFile as readFile21, writeFile as writeFile11, readdir as readdir10, appendFile as appendFile6, unlink as unlink4 } from "fs/promises";
|
|
62838
62192
|
import { homedir as homedir14 } from "os";
|
|
62839
|
-
import { join as
|
|
62840
|
-
var LOGS_DIR2 =
|
|
62841
|
-
var CURRENT_RUN_LOG =
|
|
62193
|
+
import { join as join37 } from "path";
|
|
62194
|
+
var LOGS_DIR2 = join37(homedir14(), ".replicas", "warm-hook-logs");
|
|
62195
|
+
var CURRENT_RUN_LOG = join37(LOGS_DIR2, "current-run.log");
|
|
62842
62196
|
var GLOBAL_FILENAME = "global.json";
|
|
62843
62197
|
function withPreview2(stored) {
|
|
62844
62198
|
const preview = buildHookOutputPreview(stored.output);
|
|
@@ -62846,7 +62200,7 @@ function withPreview2(stored) {
|
|
|
62846
62200
|
}
|
|
62847
62201
|
var WarmHookLogsService = class {
|
|
62848
62202
|
async ensureDir() {
|
|
62849
|
-
await
|
|
62203
|
+
await mkdir21(LOGS_DIR2, { recursive: true });
|
|
62850
62204
|
}
|
|
62851
62205
|
async saveGlobalHookLog(entry) {
|
|
62852
62206
|
await this.ensureDir();
|
|
@@ -62855,7 +62209,7 @@ var WarmHookLogsService = class {
|
|
|
62855
62209
|
hookName: "organization",
|
|
62856
62210
|
...entry
|
|
62857
62211
|
};
|
|
62858
|
-
await
|
|
62212
|
+
await writeFile11(join37(LOGS_DIR2, GLOBAL_FILENAME), `${JSON.stringify(log, null, 2)}
|
|
62859
62213
|
`, "utf-8");
|
|
62860
62214
|
}
|
|
62861
62215
|
async saveEnvironmentHookLog(entry) {
|
|
@@ -62865,7 +62219,7 @@ var WarmHookLogsService = class {
|
|
|
62865
62219
|
hookName: "environment",
|
|
62866
62220
|
...entry
|
|
62867
62221
|
};
|
|
62868
|
-
await
|
|
62222
|
+
await writeFile11(join37(LOGS_DIR2, ENVIRONMENT_HOOK_LOG_FILENAME), `${JSON.stringify(log, null, 2)}
|
|
62869
62223
|
`, "utf-8");
|
|
62870
62224
|
}
|
|
62871
62225
|
async saveRepoHookLog(repoName, entry) {
|
|
@@ -62875,13 +62229,13 @@ var WarmHookLogsService = class {
|
|
|
62875
62229
|
hookName: repoName,
|
|
62876
62230
|
...entry
|
|
62877
62231
|
};
|
|
62878
|
-
await
|
|
62232
|
+
await writeFile11(join37(LOGS_DIR2, repoHookLogFilename(repoName)), `${JSON.stringify(log, null, 2)}
|
|
62879
62233
|
`, "utf-8");
|
|
62880
62234
|
}
|
|
62881
62235
|
async getAllLogs() {
|
|
62882
62236
|
let files;
|
|
62883
62237
|
try {
|
|
62884
|
-
files = await
|
|
62238
|
+
files = await readdir10(LOGS_DIR2);
|
|
62885
62239
|
} catch (err) {
|
|
62886
62240
|
if (err.code === "ENOENT") {
|
|
62887
62241
|
return [];
|
|
@@ -62894,7 +62248,7 @@ var WarmHookLogsService = class {
|
|
|
62894
62248
|
continue;
|
|
62895
62249
|
}
|
|
62896
62250
|
try {
|
|
62897
|
-
const raw = await
|
|
62251
|
+
const raw = await readFile21(join37(LOGS_DIR2, file), "utf-8");
|
|
62898
62252
|
const stored = JSON.parse(raw);
|
|
62899
62253
|
logs.push(withPreview2(stored));
|
|
62900
62254
|
} catch {
|
|
@@ -62923,7 +62277,7 @@ var WarmHookLogsService = class {
|
|
|
62923
62277
|
}
|
|
62924
62278
|
async getCurrentRunLog() {
|
|
62925
62279
|
try {
|
|
62926
|
-
return await
|
|
62280
|
+
return await readFile21(CURRENT_RUN_LOG, "utf-8");
|
|
62927
62281
|
} catch (err) {
|
|
62928
62282
|
if (err.code === "ENOENT") return null;
|
|
62929
62283
|
throw err;
|
|
@@ -62932,7 +62286,7 @@ var WarmHookLogsService = class {
|
|
|
62932
62286
|
async getFullOutput(hookType, hookName) {
|
|
62933
62287
|
const filename = hookType === "global" ? GLOBAL_FILENAME : hookType === "environment" ? ENVIRONMENT_HOOK_LOG_FILENAME : repoHookLogFilename(hookName);
|
|
62934
62288
|
try {
|
|
62935
|
-
const raw = await
|
|
62289
|
+
const raw = await readFile21(join37(LOGS_DIR2, filename), "utf-8");
|
|
62936
62290
|
const stored = JSON.parse(raw);
|
|
62937
62291
|
if (stored.hookType !== hookType || stored.hookName !== hookName) {
|
|
62938
62292
|
return null;
|
|
@@ -62951,12 +62305,12 @@ var warmHookLogsService = new WarmHookLogsService();
|
|
|
62951
62305
|
// src/services/warm-hooks-service.ts
|
|
62952
62306
|
async function readRepoWarmHook(repoPath) {
|
|
62953
62307
|
for (const filename of REPLICAS_CONFIG_FILENAMES) {
|
|
62954
|
-
const configPath =
|
|
62308
|
+
const configPath = join38(repoPath, filename);
|
|
62955
62309
|
if (!existsSync17(configPath)) {
|
|
62956
62310
|
continue;
|
|
62957
62311
|
}
|
|
62958
62312
|
try {
|
|
62959
|
-
const raw = await
|
|
62313
|
+
const raw = await readFile22(configPath, "utf-8");
|
|
62960
62314
|
const config = parseReplicasConfigString(raw, filename);
|
|
62961
62315
|
if (!config.warmHook) {
|
|
62962
62316
|
return null;
|
|
@@ -63003,7 +62357,7 @@ async function executeHookScriptStreaming(params) {
|
|
|
63003
62357
|
params.onChunk(`$ ${params.label}
|
|
63004
62358
|
`);
|
|
63005
62359
|
return new Promise((resolve8) => {
|
|
63006
|
-
const proc =
|
|
62360
|
+
const proc = spawn7("bash", ["-lc", params.content], {
|
|
63007
62361
|
cwd: params.cwd,
|
|
63008
62362
|
env: process.env,
|
|
63009
62363
|
stdio: ["pipe", "pipe", "pipe"]
|
|
@@ -63212,9 +62566,9 @@ ${combinedScript}` : combinedScript;
|
|
|
63212
62566
|
}
|
|
63213
62567
|
|
|
63214
62568
|
// src/services/terminal-service.ts
|
|
63215
|
-
import { randomUUID as
|
|
62569
|
+
import { randomUUID as randomUUID12 } from "crypto";
|
|
63216
62570
|
import { existsSync as existsSync18 } from "fs";
|
|
63217
|
-
import { spawn as
|
|
62571
|
+
import { spawn as spawn8 } from "node-pty";
|
|
63218
62572
|
var MAX_REPLAY_CHARS = 1024 * 1024;
|
|
63219
62573
|
var MAX_TERMINAL_SESSIONS = 8;
|
|
63220
62574
|
var MAX_PENDING_INPUT = 64;
|
|
@@ -63231,9 +62585,9 @@ var TerminalService = class {
|
|
|
63231
62585
|
code: "limit"
|
|
63232
62586
|
});
|
|
63233
62587
|
}
|
|
63234
|
-
const id =
|
|
62588
|
+
const id = randomUUID12();
|
|
63235
62589
|
const shell = process.env.SHELL && existsSync18(process.env.SHELL) ? process.env.SHELL : "/bin/bash";
|
|
63236
|
-
const pty =
|
|
62590
|
+
const pty = spawn8(shell, ["-l"], {
|
|
63237
62591
|
name: "xterm-256color",
|
|
63238
62592
|
cols,
|
|
63239
62593
|
rows,
|
|
@@ -64307,11 +63661,11 @@ data: ${JSON.stringify("Terminal session not found")}
|
|
|
64307
63661
|
});
|
|
64308
63662
|
app2.get("/logs", async (c) => {
|
|
64309
63663
|
try {
|
|
64310
|
-
const files = await
|
|
63664
|
+
const files = await readdir11(LOG_DIR).catch(() => []);
|
|
64311
63665
|
const logFiles = files.filter((f) => f.endsWith(".log"));
|
|
64312
63666
|
const sessions = await Promise.all(
|
|
64313
63667
|
logFiles.map(async (filename) => {
|
|
64314
|
-
const filePath =
|
|
63668
|
+
const filePath = join39(LOG_DIR, filename);
|
|
64315
63669
|
const fileStat = await stat7(filePath);
|
|
64316
63670
|
const sessionId = filename.replace(/\.log$/, "");
|
|
64317
63671
|
return {
|
|
@@ -64346,7 +63700,7 @@ data: ${JSON.stringify("Terminal session not found")}
|
|
|
64346
63700
|
}
|
|
64347
63701
|
let content;
|
|
64348
63702
|
try {
|
|
64349
|
-
content = await
|
|
63703
|
+
content = await readFile23(filePath, "utf-8");
|
|
64350
63704
|
} catch {
|
|
64351
63705
|
return c.json(jsonError("Log session not found"), 404);
|
|
64352
63706
|
}
|
|
@@ -64417,17 +63771,17 @@ var HeartbeatService = class _HeartbeatService {
|
|
|
64417
63771
|
var heartbeatService = new HeartbeatService();
|
|
64418
63772
|
|
|
64419
63773
|
// src/services/workspace-sdk-service.ts
|
|
64420
|
-
import { cp, mkdir as
|
|
64421
|
-
import { dirname as
|
|
63774
|
+
import { cp, mkdir as mkdir22 } from "fs/promises";
|
|
63775
|
+
import { dirname as dirname18, resolve as resolve7 } from "path";
|
|
64422
63776
|
import { fileURLToPath as fileURLToPath6 } from "url";
|
|
64423
63777
|
async function installWorkspaceSdk() {
|
|
64424
|
-
const source = resolve7(
|
|
63778
|
+
const source = resolve7(dirname18(fileURLToPath6(import.meta.url)), "../../workspace-sdk");
|
|
64425
63779
|
const targets = [
|
|
64426
63780
|
resolve7(ENGINE_ENV.HOME_DIR, "node_modules/@replicas/sdk"),
|
|
64427
63781
|
"/tmp/node_modules/@replicas/sdk"
|
|
64428
63782
|
];
|
|
64429
63783
|
await Promise.all(targets.map(async (target) => {
|
|
64430
|
-
await
|
|
63784
|
+
await mkdir22(target, { recursive: true });
|
|
64431
63785
|
await cp(source, target, { recursive: true, force: true });
|
|
64432
63786
|
}));
|
|
64433
63787
|
}
|
|
@@ -64627,7 +63981,7 @@ function startStatusBroadcaster() {
|
|
|
64627
63981
|
if (serialized !== previousRepoStatus) {
|
|
64628
63982
|
previousRepoStatus = serialized;
|
|
64629
63983
|
eventService.publish({
|
|
64630
|
-
id:
|
|
63984
|
+
id: randomUUID13(),
|
|
64631
63985
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
64632
63986
|
type: "repo.status.changed",
|
|
64633
63987
|
payload: { repos }
|
|
@@ -64648,7 +64002,7 @@ function startStatusBroadcaster() {
|
|
|
64648
64002
|
if (engineStatusJson !== previousEngineStatus) {
|
|
64649
64003
|
previousEngineStatus = engineStatusJson;
|
|
64650
64004
|
eventService.publish({
|
|
64651
|
-
id:
|
|
64005
|
+
id: randomUUID13(),
|
|
64652
64006
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
64653
64007
|
type: "engine.status.changed",
|
|
64654
64008
|
payload: { status: engineStatus }
|
|
@@ -64667,7 +64021,7 @@ function startStatusBroadcaster() {
|
|
|
64667
64021
|
previousHookStatus = hookSnapshot;
|
|
64668
64022
|
if (!lastHooksRunning && hooksRunning) {
|
|
64669
64023
|
eventService.publish({
|
|
64670
|
-
id:
|
|
64024
|
+
id: randomUUID13(),
|
|
64671
64025
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
64672
64026
|
type: "hooks.started",
|
|
64673
64027
|
payload: { running: true, completed: false }
|
|
@@ -64676,7 +64030,7 @@ function startStatusBroadcaster() {
|
|
|
64676
64030
|
}
|
|
64677
64031
|
if (hooksRunning) {
|
|
64678
64032
|
eventService.publish({
|
|
64679
|
-
id:
|
|
64033
|
+
id: randomUUID13(),
|
|
64680
64034
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
64681
64035
|
type: "hooks.progress",
|
|
64682
64036
|
payload: { running: true, completed: false }
|
|
@@ -64685,7 +64039,7 @@ function startStatusBroadcaster() {
|
|
|
64685
64039
|
}
|
|
64686
64040
|
if (lastHooksRunning && !hooksRunning && hooksCompleted && !hooksFailed) {
|
|
64687
64041
|
eventService.publish({
|
|
64688
|
-
id:
|
|
64042
|
+
id: randomUUID13(),
|
|
64689
64043
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
64690
64044
|
type: "hooks.completed",
|
|
64691
64045
|
payload: { running: false, completed: true }
|
|
@@ -64694,7 +64048,7 @@ function startStatusBroadcaster() {
|
|
|
64694
64048
|
}
|
|
64695
64049
|
if (lastHooksRunning && !hooksRunning && hooksFailed) {
|
|
64696
64050
|
eventService.publish({
|
|
64697
|
-
id:
|
|
64051
|
+
id: randomUUID13(),
|
|
64698
64052
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
64699
64053
|
type: "hooks.failed",
|
|
64700
64054
|
payload: { running: false, completed: hooksCompleted }
|
|
@@ -64702,7 +64056,7 @@ function startStatusBroadcaster() {
|
|
|
64702
64056
|
});
|
|
64703
64057
|
}
|
|
64704
64058
|
eventService.publish({
|
|
64705
|
-
id:
|
|
64059
|
+
id: randomUUID13(),
|
|
64706
64060
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
64707
64061
|
type: "hooks.status",
|
|
64708
64062
|
payload: {
|
|
@@ -64758,20 +64112,20 @@ serve(
|
|
|
64758
64112
|
}
|
|
64759
64113
|
const repos = await gitService.listRepos();
|
|
64760
64114
|
await eventService.publish({
|
|
64761
|
-
id:
|
|
64115
|
+
id: randomUUID13(),
|
|
64762
64116
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
64763
64117
|
type: "repo.discovered",
|
|
64764
64118
|
payload: { repos }
|
|
64765
64119
|
});
|
|
64766
64120
|
const repoStatuses = await gitService.listRepos();
|
|
64767
64121
|
await eventService.publish({
|
|
64768
|
-
id:
|
|
64122
|
+
id: randomUUID13(),
|
|
64769
64123
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
64770
64124
|
type: "repo.status.changed",
|
|
64771
64125
|
payload: { repos: repoStatuses }
|
|
64772
64126
|
});
|
|
64773
64127
|
await eventService.publish({
|
|
64774
|
-
id:
|
|
64128
|
+
id: randomUUID13(),
|
|
64775
64129
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
64776
64130
|
type: "engine.ready",
|
|
64777
64131
|
payload: { version: "v1" }
|