replicas-engine 0.1.958 → 0.1.959
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-QI7MAWDJ.js → asp-host-INCEKBYG.js} +5 -5
- package/dist/src/{chunk-NHEZTD3X.js → chunk-4HNUOSLS.js} +4 -5
- package/dist/src/{chunk-YNVHVJQR.js → chunk-CANEL3IU.js} +1 -1
- package/dist/src/{chunk-7GWXM2H5.js → chunk-QXISBAH5.js} +42 -75
- package/dist/src/{chunk-YEIV5OYO.js → chunk-SZTW4OGR.js} +3 -3
- package/dist/src/{chunk-LI5QEJBB.js → chunk-TFD6QK6J.js} +6 -6
- package/dist/src/{chunk-FHP2MB2M.js → chunk-X76Z5POI.js} +3 -3
- package/dist/src/{chunk-UQ3N4FNZ.js → chunk-XFGXRH7Q.js} +1 -1
- package/dist/src/command-protection-hook.js +4 -4
- package/dist/src/headless-agent.js +3 -3
- package/dist/src/index.js +388 -385
- package/dist/src/post-tool-pr-hook.js +2 -2
- package/dist/src/{relay-mcp.js → subagent-mcp.js} +38 -39
- package/package.json +2 -2
- package/dist/src/chunk-SJ6BDSN3.js +0 -45
package/dist/src/index.js
CHANGED
|
@@ -32,7 +32,7 @@ import {
|
|
|
32
32
|
reportCommandProtectionBlock,
|
|
33
33
|
resolveDiffBase,
|
|
34
34
|
runGitCommand
|
|
35
|
-
} from "./chunk-
|
|
35
|
+
} from "./chunk-SZTW4OGR.js";
|
|
36
36
|
import {
|
|
37
37
|
ACCOUNT_RATE_LIMITS_UPDATED_METHOD,
|
|
38
38
|
AGENT_MESSAGE_DELTA_METHOD,
|
|
@@ -56,12 +56,7 @@ import {
|
|
|
56
56
|
} from "./chunk-UPCC4BX5.js";
|
|
57
57
|
import {
|
|
58
58
|
publishedPullRequestUrls
|
|
59
|
-
} from "./chunk-
|
|
60
|
-
import {
|
|
61
|
-
RELAY_MCP_TOOL_TIMEOUT_MS,
|
|
62
|
-
relayCodexMcpConfig,
|
|
63
|
-
relayMcpProcessConfig
|
|
64
|
-
} from "./chunk-SJ6BDSN3.js";
|
|
59
|
+
} from "./chunk-XFGXRH7Q.js";
|
|
65
60
|
import {
|
|
66
61
|
BaseRefreshManager,
|
|
67
62
|
CodexAspAuthMethodChangedError,
|
|
@@ -76,7 +71,7 @@ import {
|
|
|
76
71
|
refreshDelayMs,
|
|
77
72
|
restartCodexAspHost,
|
|
78
73
|
routineRefreshExclusions
|
|
79
|
-
} from "./chunk-
|
|
74
|
+
} from "./chunk-TFD6QK6J.js";
|
|
80
75
|
import {
|
|
81
76
|
ENGINE_ENV,
|
|
82
77
|
monolithRequest,
|
|
@@ -84,16 +79,16 @@ import {
|
|
|
84
79
|
readRuntimeEnvFile,
|
|
85
80
|
reloadEngineEnv,
|
|
86
81
|
setAgentCredentialSnapshot
|
|
87
|
-
} from "./chunk-
|
|
82
|
+
} from "./chunk-4HNUOSLS.js";
|
|
88
83
|
import {
|
|
89
84
|
AspClient,
|
|
90
85
|
getCodexModelProvider
|
|
91
|
-
} from "./chunk-
|
|
86
|
+
} from "./chunk-X76Z5POI.js";
|
|
92
87
|
import {
|
|
93
88
|
SUBPROCESS_MAX_BUFFER,
|
|
94
89
|
execAsync,
|
|
95
90
|
execFileAsync
|
|
96
|
-
} from "./chunk-
|
|
91
|
+
} from "./chunk-CANEL3IU.js";
|
|
97
92
|
import {
|
|
98
93
|
isRecord as isRecord2
|
|
99
94
|
} from "./chunk-UZSNFLDQ.js";
|
|
@@ -151,7 +146,6 @@ import {
|
|
|
151
146
|
DEFAULT_OPENCODE_GO_MODEL,
|
|
152
147
|
DEFAULT_OPENCODE_MODEL,
|
|
153
148
|
DEFAULT_PI_MODEL,
|
|
154
|
-
DEFAULT_RELAY_BASE_PROVIDER,
|
|
155
149
|
DEFAULT_START_HOOK_TIMEOUT_MS,
|
|
156
150
|
DESKTOP_STREAM_PORT,
|
|
157
151
|
ENGINE_ACTIVATE_PATH,
|
|
@@ -178,12 +172,13 @@ import {
|
|
|
178
172
|
OPENCODE_GO_BASE_URL,
|
|
179
173
|
OPENCODE_GO_PROVIDER,
|
|
180
174
|
QUEUED_MESSAGE_REMOVED_EVENT_TYPE,
|
|
181
|
-
RELAY_MCP_SERVER_NAME,
|
|
182
|
-
RELAY_MCP_TOOLS,
|
|
183
|
-
RELAY_MCP_TOOL_NAMES,
|
|
184
175
|
REMOVED_MESSAGE_IDS_PAYLOAD_KEY,
|
|
185
176
|
REPLICAS_CONFIG_FILENAMES,
|
|
186
177
|
REPLICAS_RUNTIME_ENV_ALIASES,
|
|
178
|
+
SUBAGENT_MCP_HARNESSES,
|
|
179
|
+
SUBAGENT_MCP_SERVER_NAME,
|
|
180
|
+
SUBAGENT_MCP_TOOLS,
|
|
181
|
+
SUBAGENT_MCP_TOOL_NAMES,
|
|
187
182
|
TIMEOUT,
|
|
188
183
|
TOKEN_USAGE_PATH,
|
|
189
184
|
TaskAccumulator,
|
|
@@ -238,7 +233,6 @@ import {
|
|
|
238
233
|
forkChatRequestSchema,
|
|
239
234
|
formatChatForkHandoffMessage,
|
|
240
235
|
formatSideChatUpdateMessage,
|
|
241
|
-
getChatExecutionProvider,
|
|
242
236
|
getChatHistoryPageSenders,
|
|
243
237
|
getClaudeModelContextWindow,
|
|
244
238
|
getDefaultAgentModel,
|
|
@@ -278,14 +272,12 @@ import {
|
|
|
278
272
|
isTokenUsageUploadRecord,
|
|
279
273
|
isTransientErrorText,
|
|
280
274
|
isValidAgentProvider,
|
|
281
|
-
isValidCodingAgentProvider,
|
|
282
275
|
isValidEngineLogSessionId,
|
|
283
|
-
isValidRelayBaseProvider,
|
|
284
276
|
lastUserBlockText,
|
|
285
277
|
legacyWorkspaceTokenBundleSchema,
|
|
286
278
|
listOllamaModels,
|
|
287
279
|
mergeSlashCommands,
|
|
288
|
-
|
|
280
|
+
messageSubagentRequestSchema,
|
|
289
281
|
normalizeAutoCompactThreshold,
|
|
290
282
|
normalizeClaudeModel,
|
|
291
283
|
normalizeCodexAspTranscriptStatus,
|
|
@@ -316,16 +308,16 @@ import {
|
|
|
316
308
|
serializeMuseAuthFile,
|
|
317
309
|
shellQuotePosix,
|
|
318
310
|
shouldRefreshPullRequests,
|
|
319
|
-
|
|
311
|
+
spawnSubagentRequestSchema,
|
|
320
312
|
stripAgentDiagnosticErrors,
|
|
321
313
|
updateChatDisplayNameRequestSchema,
|
|
322
|
-
|
|
314
|
+
waitSubagentRequestSchema,
|
|
323
315
|
withTimeout,
|
|
324
316
|
workspaceAudienceSchema,
|
|
325
317
|
workspaceCredentialProviderSchema,
|
|
326
318
|
workspaceTokenRequestSchema,
|
|
327
319
|
workspaceTokenResponseSchema
|
|
328
|
-
} from "./chunk-
|
|
320
|
+
} from "./chunk-QXISBAH5.js";
|
|
329
321
|
import {
|
|
330
322
|
cloneMcpConfig,
|
|
331
323
|
ensureCompatibilityImports,
|
|
@@ -526,7 +518,7 @@ var require_lib = __commonJS({
|
|
|
526
518
|
"../node_modules/.bun/which@5.0.0/node_modules/which/lib/index.js"(exports, module) {
|
|
527
519
|
"use strict";
|
|
528
520
|
var { isexe, sync: isexeSync } = require_index_min();
|
|
529
|
-
var { join:
|
|
521
|
+
var { join: join41, delimiter: delimiter3, sep: sep2, posix } = __require("path");
|
|
530
522
|
var isWindows = process.platform === "win32";
|
|
531
523
|
var rSlash = new RegExp(`[${posix.sep}${sep2 === posix.sep ? "" : sep2}]`.replace(/(\\)/g, "\\$1"));
|
|
532
524
|
var rRel = new RegExp(`^\\.${rSlash.source}`);
|
|
@@ -555,7 +547,7 @@ var require_lib = __commonJS({
|
|
|
555
547
|
var getPathPart = (raw, cmd) => {
|
|
556
548
|
const pathPart = /^".*"$/.test(raw) ? raw.slice(1, -1) : raw;
|
|
557
549
|
const prefix = !pathPart && rRel.test(cmd) ? cmd.slice(0, 2) : "";
|
|
558
|
-
return prefix +
|
|
550
|
+
return prefix + join41(pathPart, cmd);
|
|
559
551
|
};
|
|
560
552
|
var which = async (cmd, opt = {}) => {
|
|
561
553
|
const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
|
|
@@ -10042,9 +10034,7 @@ function detectClaudeAuthMethod() {
|
|
|
10042
10034
|
function detectAgentAuthMethod(provider) {
|
|
10043
10035
|
if (OLLAMA_AGENTS.some((agent) => agent === provider && readOllamaAuthEnv(agent, process.env))) return "ollama";
|
|
10044
10036
|
switch (provider) {
|
|
10045
|
-
// Relay orchestrates subagents but authenticates as Claude.
|
|
10046
10037
|
case AGENT.CLAUDE:
|
|
10047
|
-
case AGENT.RELAY:
|
|
10048
10038
|
return detectClaudeAuthMethod();
|
|
10049
10039
|
case AGENT.CODEX:
|
|
10050
10040
|
return detectCodexAuthMethod();
|
|
@@ -10983,11 +10973,11 @@ async function registerDesktopPreview(signal) {
|
|
|
10983
10973
|
|
|
10984
10974
|
// src/services/chat/chat-service.ts
|
|
10985
10975
|
import { appendFile as appendFile5, copyFile as copyFile2, mkdir as mkdir20, readFile as readFile19, rename as rename4, rm as rm4 } from "fs/promises";
|
|
10986
|
-
import { join as
|
|
10976
|
+
import { join as join35 } from "path";
|
|
10987
10977
|
import { randomUUID as randomUUID11 } from "crypto";
|
|
10988
10978
|
|
|
10989
10979
|
// ../shared/src/workspace-chat.ts
|
|
10990
|
-
var WORKSPACE_CHATS_QUERY_SCHEMA_VERSION =
|
|
10980
|
+
var WORKSPACE_CHATS_QUERY_SCHEMA_VERSION = 10;
|
|
10991
10981
|
var WORKSPACE_CHATS_QUERY_ROOT = `workspace-chats:v${WORKSPACE_CHATS_QUERY_SCHEMA_VERSION}`;
|
|
10992
10982
|
function isAcceptedUserMessage(event) {
|
|
10993
10983
|
return getUserMessage(event) !== null && event.payload.source === ACCEPTED_USER_MESSAGE_SOURCE;
|
|
@@ -11160,7 +11150,7 @@ import {
|
|
|
11160
11150
|
query
|
|
11161
11151
|
} from "@anthropic-ai/claude-agent-sdk";
|
|
11162
11152
|
import { randomUUID as randomUUID5 } from "crypto";
|
|
11163
|
-
import { dirname as
|
|
11153
|
+
import { dirname as dirname5, join as join16 } from "path";
|
|
11164
11154
|
import { mkdir as mkdir10, readdir as readdir4, readFile as readFile10 } from "fs/promises";
|
|
11165
11155
|
import { homedir as homedir11 } from "os";
|
|
11166
11156
|
|
|
@@ -11982,9 +11972,15 @@ var MessageQueueService = class {
|
|
|
11982
11972
|
}
|
|
11983
11973
|
};
|
|
11984
11974
|
|
|
11975
|
+
// src/managers/subagent-mcp-prompt.ts
|
|
11976
|
+
var SUBAGENT_MCP_INSTRUCTIONS = `# Subagents
|
|
11977
|
+
|
|
11978
|
+
Native subagent tools are disabled in this workspace. To delegate work to a subagent, use the \`${SUBAGENT_MCP_SERVER_NAME}\` MCP server (\`${SUBAGENT_MCP_TOOLS.getProviders}\`, \`${SUBAGENT_MCP_TOOLS.spawnAgent}\`, \`${SUBAGENT_MCP_TOOLS.getAgent}\`, \`${SUBAGENT_MCP_TOOLS.waitAgent}\`, \`${SUBAGENT_MCP_TOOLS.messageAgent}\`, \`${SUBAGENT_MCP_TOOLS.deleteAgent}\`); your harness may prefix them, and Pi exposes them through its \`mcp\` gateway. Call \`${SUBAGENT_MCP_TOOLS.getProviders}\` before the first spawn. \`fork_turns\` sets inherited context: "all" (default), "none" (include every needed detail in the prompt), or "N" for the latest N user turns. \`${SUBAGENT_MCP_TOOLS.spawnAgent}\` and \`${SUBAGENT_MCP_TOOLS.messageAgent}\` block by default; pass \`blocking: false\` to keep working, then use \`${SUBAGENT_MCP_TOOLS.getAgent}\` or \`${SUBAGENT_MCP_TOOLS.waitAgent}\`. Subagents share this workspace.`;
|
|
11979
|
+
|
|
11985
11980
|
// src/managers/coding-agent-manager.ts
|
|
11986
11981
|
var MAX_INTERRUPT_QUEUE_ITEMS = 1e3;
|
|
11987
11982
|
var MAX_INTERRUPT_QUEUE_CHARS = 2e5;
|
|
11983
|
+
var subagentMcpConfigRequest = null;
|
|
11988
11984
|
var CodingAgentManager = class {
|
|
11989
11985
|
workingDirectory;
|
|
11990
11986
|
messageQueue;
|
|
@@ -11993,8 +11989,6 @@ var CodingAgentManager = class {
|
|
|
11993
11989
|
onSaveSessionId;
|
|
11994
11990
|
onEvent;
|
|
11995
11991
|
onUsageUpdate;
|
|
11996
|
-
isRelay;
|
|
11997
|
-
relayParentChatId;
|
|
11998
11992
|
linearSessionId;
|
|
11999
11993
|
chatId;
|
|
12000
11994
|
hostOnTurnComplete;
|
|
@@ -12002,7 +11996,8 @@ var CodingAgentManager = class {
|
|
|
12002
11996
|
onMessageStarted;
|
|
12003
11997
|
onModelSwitched;
|
|
12004
11998
|
authFallback;
|
|
12005
|
-
|
|
11999
|
+
subagentMcpChatId;
|
|
12000
|
+
subagentMcpEnabledForTurn = false;
|
|
12006
12001
|
compacting = false;
|
|
12007
12002
|
constructor(options) {
|
|
12008
12003
|
this.workingDirectory = options.workingDirectory ?? ENGINE_ENV.WORKSPACE_ROOT;
|
|
@@ -12011,11 +12006,9 @@ var CodingAgentManager = class {
|
|
|
12011
12006
|
this.onEvent = options.onEvent;
|
|
12012
12007
|
this.onUsageUpdate = options.onUsageUpdate ?? (() => {
|
|
12013
12008
|
});
|
|
12014
|
-
this.
|
|
12015
|
-
this.isRelay = Boolean(options.relayParentChatId);
|
|
12009
|
+
this.subagentMcpChatId = options.parentChatId === null && options.provider && SUBAGENT_MCP_HARNESSES.includes(options.provider) ? options.chatId : void 0;
|
|
12016
12010
|
this.linearSessionId = options.linearSessionId;
|
|
12017
12011
|
this.chatId = options.chatId;
|
|
12018
|
-
this.additionalInstructions = options.additionalInstructions;
|
|
12019
12012
|
this.hostOnTurnComplete = options.onTurnComplete;
|
|
12020
12013
|
this.onProcessingChanged = options.onProcessingChanged ?? (() => {
|
|
12021
12014
|
});
|
|
@@ -12093,12 +12086,31 @@ var CodingAgentManager = class {
|
|
|
12093
12086
|
}
|
|
12094
12087
|
initializeManager(processMessage) {
|
|
12095
12088
|
this.messageQueue = new MessageQueueService(
|
|
12096
|
-
|
|
12089
|
+
async (request) => {
|
|
12090
|
+
await this.refreshSubagentMcp();
|
|
12091
|
+
await processMessage(request);
|
|
12092
|
+
},
|
|
12097
12093
|
this.onProcessingChanged,
|
|
12098
12094
|
this.onMessageStarted
|
|
12099
12095
|
);
|
|
12100
12096
|
this.initialized = this.initialize();
|
|
12101
12097
|
}
|
|
12098
|
+
/** The workspace preference is resolved per turn so a change applies to the next turn; failures keep the last value. */
|
|
12099
|
+
async refreshSubagentMcp() {
|
|
12100
|
+
if (!this.subagentMcpChatId || !ENGINE_ENV.REPLICAS_WORKSPACE_ID) return;
|
|
12101
|
+
subagentMcpConfigRequest ??= monolithService.getSubagentMcpConfig().finally(() => {
|
|
12102
|
+
subagentMcpConfigRequest = null;
|
|
12103
|
+
});
|
|
12104
|
+
const config = await subagentMcpConfigRequest;
|
|
12105
|
+
if (config) this.subagentMcpEnabledForTurn = await this.subagentMcpForTurn(config.enabled);
|
|
12106
|
+
}
|
|
12107
|
+
/** Harnesses that fix their tool set per session override this to keep a session's original mode. */
|
|
12108
|
+
async subagentMcpForTurn(enabled) {
|
|
12109
|
+
return enabled;
|
|
12110
|
+
}
|
|
12111
|
+
subagentMcpParentChatId() {
|
|
12112
|
+
return this.subagentMcpEnabledForTurn ? this.subagentMcpChatId : void 0;
|
|
12113
|
+
}
|
|
12102
12114
|
async persistHistoryEvent(event) {
|
|
12103
12115
|
const history = this.getHistorySink();
|
|
12104
12116
|
if (!history?.appendDurably) throw new Error("Chat history is unavailable");
|
|
@@ -12251,8 +12263,8 @@ var CodingAgentManager = class {
|
|
|
12251
12263
|
if (memoryInstruction) {
|
|
12252
12264
|
parts.push(memoryInstruction);
|
|
12253
12265
|
}
|
|
12254
|
-
if (this.
|
|
12255
|
-
parts.push(
|
|
12266
|
+
if (this.subagentMcpParentChatId()) {
|
|
12267
|
+
parts.push(SUBAGENT_MCP_INSTRUCTIONS);
|
|
12256
12268
|
}
|
|
12257
12269
|
if (customInstructions) {
|
|
12258
12270
|
parts.push(customInstructions);
|
|
@@ -13043,6 +13055,39 @@ var ClaudeBackgroundTasks = class {
|
|
|
13043
13055
|
}
|
|
13044
13056
|
};
|
|
13045
13057
|
|
|
13058
|
+
// src/managers/subagent-mcp-config.ts
|
|
13059
|
+
import { existsSync as existsSync7 } from "fs";
|
|
13060
|
+
import { dirname as dirname4, join as join15 } from "path";
|
|
13061
|
+
import { fileURLToPath } from "url";
|
|
13062
|
+
import { createRequire } from "module";
|
|
13063
|
+
var SUBAGENT_MCP_TOOL_TIMEOUT_MS = 24 * 60 * 60 * 1e3 + 6e4;
|
|
13064
|
+
function subagentMcpProcessConfig(parentChatId) {
|
|
13065
|
+
const directory = dirname4(fileURLToPath(import.meta.url));
|
|
13066
|
+
const builtEntry = join15(directory, "subagent-mcp.js");
|
|
13067
|
+
const sourceEntry = join15(directory, "..", "subagent-mcp.ts");
|
|
13068
|
+
const entry = existsSync7(builtEntry) ? builtEntry : sourceEntry;
|
|
13069
|
+
return {
|
|
13070
|
+
command: process.execPath,
|
|
13071
|
+
args: [
|
|
13072
|
+
...entry.endsWith(".ts") ? ["--import", createRequire(import.meta.url).resolve("tsx/esm")] : [],
|
|
13073
|
+
entry,
|
|
13074
|
+
"--parent",
|
|
13075
|
+
parentChatId
|
|
13076
|
+
]
|
|
13077
|
+
};
|
|
13078
|
+
}
|
|
13079
|
+
function subagentCodexMcpConfig(parentChatId) {
|
|
13080
|
+
return {
|
|
13081
|
+
...subagentMcpProcessConfig(parentChatId),
|
|
13082
|
+
env_vars: ["REPLICAS_ENGINE_PORT", "REPLICAS_ENGINE_SECRET"],
|
|
13083
|
+
enabled_tools: [...SUBAGENT_MCP_TOOL_NAMES],
|
|
13084
|
+
required: true,
|
|
13085
|
+
default_tools_approval_mode: "approve",
|
|
13086
|
+
startup_timeout_sec: 10,
|
|
13087
|
+
tool_timeout_sec: Math.ceil(SUBAGENT_MCP_TOOL_TIMEOUT_MS / 1e3)
|
|
13088
|
+
};
|
|
13089
|
+
}
|
|
13090
|
+
|
|
13046
13091
|
// src/managers/claude-manager.ts
|
|
13047
13092
|
var PromptStream = class {
|
|
13048
13093
|
queue = [];
|
|
@@ -13329,7 +13374,7 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
13329
13374
|
});
|
|
13330
13375
|
this.onChatCredential = options.onChatCredential ?? (() => {
|
|
13331
13376
|
});
|
|
13332
|
-
this.historyFilePath = options.historyFilePath ??
|
|
13377
|
+
this.historyFilePath = options.historyFilePath ?? join16(homedir11(), ".replicas", "claude", "history.jsonl");
|
|
13333
13378
|
this.historyFile = new CodexHistoryFile(this.historyFilePath);
|
|
13334
13379
|
this.initializeManager(this.processMessageInternal.bind(this));
|
|
13335
13380
|
}
|
|
@@ -13591,7 +13636,7 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
13591
13636
|
const agentId = /^agent-(.+)\.jsonl$/.exec(file)?.[1];
|
|
13592
13637
|
if (!agentId) continue;
|
|
13593
13638
|
const offset = workflow.offsets.get(file) ?? 0;
|
|
13594
|
-
const buffer = await readFile10(
|
|
13639
|
+
const buffer = await readFile10(join16(workflow.dir, file)).catch(() => Buffer.alloc(0));
|
|
13595
13640
|
const end = buffer.lastIndexOf(10);
|
|
13596
13641
|
if (end < offset) continue;
|
|
13597
13642
|
workflow.offsets.set(file, end + 1);
|
|
@@ -13831,7 +13876,8 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
13831
13876
|
thinkingLevel,
|
|
13832
13877
|
enableInteractiveTools: Boolean(enableInteractiveTools),
|
|
13833
13878
|
fastMode: resolvedFastMode,
|
|
13834
|
-
permissionMode: resolvedPermissionMode
|
|
13879
|
+
permissionMode: resolvedPermissionMode,
|
|
13880
|
+
subagentMcpParentChatId: this.subagentMcpParentChatId()
|
|
13835
13881
|
};
|
|
13836
13882
|
await this.ensureSession({
|
|
13837
13883
|
signature,
|
|
@@ -13922,12 +13968,12 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
13922
13968
|
});
|
|
13923
13969
|
}
|
|
13924
13970
|
sessionSignaturesMatch(a, b) {
|
|
13925
|
-
return a.combinedInstructions === b.combinedInstructions && a.credential === b.credential && a.thinkingLevel === b.thinkingLevel && a.enableInteractiveTools === b.enableInteractiveTools && a.fastMode === b.fastMode && a.permissionMode === b.permissionMode;
|
|
13971
|
+
return a.combinedInstructions === b.combinedInstructions && a.credential === b.credential && a.thinkingLevel === b.thinkingLevel && a.enableInteractiveTools === b.enableInteractiveTools && a.fastMode === b.fastMode && a.permissionMode === b.permissionMode && a.subagentMcpParentChatId === b.subagentMcpParentChatId;
|
|
13926
13972
|
}
|
|
13927
13973
|
/** Query inputs shared by real sessions and slash-command discovery. */
|
|
13928
13974
|
async buildSharedQueryOptions() {
|
|
13929
13975
|
const env = buildClaudeAgentEnv(
|
|
13930
|
-
this.
|
|
13976
|
+
this.subagentMcpParentChatId() ? { CLAUDE_CODE_STREAM_CLOSE_TIMEOUT: "900000" } : void 0,
|
|
13931
13977
|
this.turnCredentials?.env()
|
|
13932
13978
|
);
|
|
13933
13979
|
const additionalDirectories = await getAgentAdditionalDirectories();
|
|
@@ -13961,14 +14007,15 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
13961
14007
|
};
|
|
13962
14008
|
const shared = await this.buildSharedQueryOptions();
|
|
13963
14009
|
const interactiveAllowed = enableInteractiveTools && resolvedPermissionMode === "plan";
|
|
14010
|
+
const subagentMcpParentChatId = signature.subagentMcpParentChatId;
|
|
13964
14011
|
const allowedTools = [
|
|
13965
|
-
...ALWAYS_ALLOWED_TOOLS.filter((tool) => !
|
|
13966
|
-
...
|
|
14012
|
+
...ALWAYS_ALLOWED_TOOLS.filter((tool) => !subagentMcpParentChatId || tool !== "Agent"),
|
|
14013
|
+
...subagentMcpParentChatId ? SUBAGENT_MCP_TOOL_NAMES.map((tool) => `mcp__${SUBAGENT_MCP_SERVER_NAME}__${tool}`) : [],
|
|
13967
14014
|
...interactiveAllowed ? INTERACTIVE_TOOL_NAMES : []
|
|
13968
14015
|
];
|
|
13969
14016
|
const disallowedTools = [
|
|
13970
14017
|
...ALWAYS_DISALLOWED_TOOLS,
|
|
13971
|
-
...
|
|
14018
|
+
...subagentMcpParentChatId ? ["Agent"] : [],
|
|
13972
14019
|
...interactiveAllowed ? [] : INTERACTIVE_TOOL_NAMES
|
|
13973
14020
|
];
|
|
13974
14021
|
const promptStream = new PromptStream();
|
|
@@ -13984,7 +14031,7 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
13984
14031
|
...disallowedTools.length > 0 ? { disallowedTools } : {},
|
|
13985
14032
|
settingSources: ["user", "project", "local"],
|
|
13986
14033
|
systemPrompt,
|
|
13987
|
-
...
|
|
14034
|
+
...subagentMcpParentChatId ? { mcpServers: { [SUBAGENT_MCP_SERVER_NAME]: { type: "stdio", alwaysLoad: true, ...subagentMcpProcessConfig(subagentMcpParentChatId) } } } : {},
|
|
13988
14035
|
...shared.plugins.length > 0 ? { plugins: shared.plugins } : {},
|
|
13989
14036
|
...shared.enableAllSkills ? { skills: "all" } : {},
|
|
13990
14037
|
env: {
|
|
@@ -14508,7 +14555,7 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
14508
14555
|
}
|
|
14509
14556
|
}
|
|
14510
14557
|
async initialize() {
|
|
14511
|
-
await mkdir10(
|
|
14558
|
+
await mkdir10(dirname5(this.historyFilePath), { recursive: true });
|
|
14512
14559
|
const goalEvent = await this.historyFile.findLastEventOfType(CHAT_GOAL_EVENT_TYPE);
|
|
14513
14560
|
if (goalEvent) this.currentGoal = coerceChatGoalPayload(goalEvent.payload);
|
|
14514
14561
|
if (this.initialSessionId) {
|
|
@@ -14596,8 +14643,9 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
14596
14643
|
};
|
|
14597
14644
|
|
|
14598
14645
|
// src/managers/codex-asp/codex-asp-manager.ts
|
|
14646
|
+
import { existsSync as existsSync9 } from "fs";
|
|
14599
14647
|
import { mkdir as mkdir11, writeFile as writeFile6 } from "fs/promises";
|
|
14600
|
-
import { join as
|
|
14648
|
+
import { join as join17 } from "path";
|
|
14601
14649
|
|
|
14602
14650
|
// src/utils/codex-quota.ts
|
|
14603
14651
|
function buildCodexRateLimitsSnapshot(fields) {
|
|
@@ -14661,7 +14709,7 @@ var CodexQuotaStatusTracker = class {
|
|
|
14661
14709
|
};
|
|
14662
14710
|
|
|
14663
14711
|
// src/managers/codex-asp/mappers.ts
|
|
14664
|
-
import { existsSync as
|
|
14712
|
+
import { existsSync as existsSync8, readFileSync as readFileSync2 } from "fs";
|
|
14665
14713
|
var localImageCache = /* @__PURE__ */ new Map();
|
|
14666
14714
|
var DEFAULT_MODEL = DEFAULT_CODEX_MODEL;
|
|
14667
14715
|
var THREAD_START_METHOD = "thread/start";
|
|
@@ -14785,7 +14833,7 @@ function transcriptItemsForTurn(turn) {
|
|
|
14785
14833
|
function userImageForLocalPath(path7) {
|
|
14786
14834
|
const cached = localImageCache.get(path7);
|
|
14787
14835
|
if (cached) return cached;
|
|
14788
|
-
if (!
|
|
14836
|
+
if (!existsSync8(path7)) return null;
|
|
14789
14837
|
const image = {
|
|
14790
14838
|
type: "image",
|
|
14791
14839
|
mediaType: inferMediaType(path7),
|
|
@@ -15028,7 +15076,7 @@ function turnsToAspTranscript(threadId, updatedAt, sourceTurns) {
|
|
|
15028
15076
|
});
|
|
15029
15077
|
return { threadId, updatedAt, turns };
|
|
15030
15078
|
}
|
|
15031
|
-
async function buildThreadStartParams(workingDirectory, request, developerInstructions, serviceTier,
|
|
15079
|
+
async function buildThreadStartParams(workingDirectory, request, developerInstructions, serviceTier, subagentMcpParentChatId) {
|
|
15032
15080
|
const additionalDirectories = await getAgentAdditionalDirectories();
|
|
15033
15081
|
return {
|
|
15034
15082
|
model: request.model ?? DEFAULT_MODEL,
|
|
@@ -15041,15 +15089,16 @@ async function buildThreadStartParams(workingDirectory, request, developerInstru
|
|
|
15041
15089
|
config: {
|
|
15042
15090
|
web_search: ENGINE_ENV.REPLICAS_CODEX_AUTH_METHOD === "ollama" ? "disabled" : "live",
|
|
15043
15091
|
model_reasoning_summary: "auto",
|
|
15044
|
-
...
|
|
15045
|
-
|
|
15046
|
-
|
|
15092
|
+
...subagentMcpParentChatId ? {
|
|
15093
|
+
// Codex gates its native collaboration tools on `agents.enabled`; `features.multi_agent` is now a no-op.
|
|
15094
|
+
"agents.enabled": false,
|
|
15095
|
+
[`mcp_servers.${SUBAGENT_MCP_SERVER_NAME}`]: subagentCodexMcpConfig(subagentMcpParentChatId)
|
|
15047
15096
|
} : {}
|
|
15048
15097
|
},
|
|
15049
15098
|
experimentalRawEvents: false
|
|
15050
15099
|
};
|
|
15051
15100
|
}
|
|
15052
|
-
async function buildThreadResumeParams(workingDirectory, threadId, request, developerInstructions, serviceTier,
|
|
15101
|
+
async function buildThreadResumeParams(workingDirectory, threadId, request, developerInstructions, serviceTier, subagentMcpParentChatId) {
|
|
15053
15102
|
const additionalDirectories = await getAgentAdditionalDirectories();
|
|
15054
15103
|
return {
|
|
15055
15104
|
threadId,
|
|
@@ -15063,9 +15112,10 @@ async function buildThreadResumeParams(workingDirectory, threadId, request, deve
|
|
|
15063
15112
|
config: {
|
|
15064
15113
|
web_search: ENGINE_ENV.REPLICAS_CODEX_AUTH_METHOD === "ollama" ? "disabled" : "live",
|
|
15065
15114
|
model_reasoning_summary: "auto",
|
|
15066
|
-
...
|
|
15067
|
-
|
|
15068
|
-
|
|
15115
|
+
...subagentMcpParentChatId ? {
|
|
15116
|
+
// Codex gates its native collaboration tools on `agents.enabled`; `features.multi_agent` is now a no-op.
|
|
15117
|
+
"agents.enabled": false,
|
|
15118
|
+
[`mcp_servers.${SUBAGENT_MCP_SERVER_NAME}`]: subagentCodexMcpConfig(subagentMcpParentChatId)
|
|
15069
15119
|
} : {}
|
|
15070
15120
|
},
|
|
15071
15121
|
excludeTurns: false
|
|
@@ -15191,6 +15241,11 @@ var CodexQuotaError = class extends Error {
|
|
|
15191
15241
|
};
|
|
15192
15242
|
var CODEX_SLASH_COMMANDS_CACHE_MS = 3e4;
|
|
15193
15243
|
var POLICY_REASON_INJECTION_TIMEOUT_MS = 5e3;
|
|
15244
|
+
var SUBAGENT_MCP_THREADS_DIR = join17(ENGINE_ENV.HOME_DIR, ".replicas", "codex", "subagent-mcp-threads");
|
|
15245
|
+
async function markSubagentMcpThread(threadId) {
|
|
15246
|
+
await mkdir11(SUBAGENT_MCP_THREADS_DIR, { recursive: true });
|
|
15247
|
+
await writeFile6(join17(SUBAGENT_MCP_THREADS_DIR, threadId), "");
|
|
15248
|
+
}
|
|
15194
15249
|
function formatBlockedCommandReason(reason) {
|
|
15195
15250
|
return reason?.includes("Blocked by organization policy") ? reason : `Blocked by organization policy: ${reason || "agents may not merge pull requests."}`;
|
|
15196
15251
|
}
|
|
@@ -15279,6 +15334,9 @@ var CodexAspManager = class extends CodingAgentManager {
|
|
|
15279
15334
|
}
|
|
15280
15335
|
};
|
|
15281
15336
|
}
|
|
15337
|
+
async subagentMcpForTurn(enabled) {
|
|
15338
|
+
return this.currentThreadId ? existsSync9(join17(SUBAGENT_MCP_THREADS_DIR, this.currentThreadId)) : enabled;
|
|
15339
|
+
}
|
|
15282
15340
|
async interruptActiveTurn() {
|
|
15283
15341
|
if (this.currentGoal?.status === "active") {
|
|
15284
15342
|
await this.updateGoal({ status: "paused" });
|
|
@@ -15612,13 +15670,14 @@ var CodexAspManager = class extends CodingAgentManager {
|
|
|
15612
15670
|
await this.applySkillRegistries(host);
|
|
15613
15671
|
const existingThreadId = this.currentThreadId;
|
|
15614
15672
|
const requestedModel = request.model ?? DEFAULT_MODEL;
|
|
15673
|
+
const subagentMcpParentChatId = this.subagentMcpParentChatId();
|
|
15615
15674
|
if (existingThreadId) {
|
|
15616
15675
|
if (this.attachedClient !== host.client || requestedModel !== this.attachedModel || (developerInstructions ?? null) !== this.attachedDeveloperInstructions) {
|
|
15617
15676
|
const serviceTier2 = await this.resolveRequestedServiceTier(host, request);
|
|
15618
15677
|
const previous = this.attachedClient !== host.client ? await host.client.request(THREAD_READ_METHOD, { threadId: existingThreadId, includeTurns: true }).catch(() => null) : null;
|
|
15619
15678
|
const response = previous?.thread.modelProvider && previous.thread.modelProvider !== getCodexModelProvider(ENGINE_ENV.REPLICAS_CODEX_AUTH_METHOD) ? await this.continueWithNewProvider(host, previous.thread, request, developerInstructions, serviceTier2) : await host.client.request(
|
|
15620
15679
|
THREAD_RESUME_METHOD,
|
|
15621
|
-
await buildThreadResumeParams(this.workingDirectory, existingThreadId, request, developerInstructions, serviceTier2,
|
|
15680
|
+
await buildThreadResumeParams(this.workingDirectory, existingThreadId, request, developerInstructions, serviceTier2, subagentMcpParentChatId)
|
|
15622
15681
|
);
|
|
15623
15682
|
this.currentThreadId = response.thread.id;
|
|
15624
15683
|
this.activeServiceTier = response.serviceTier;
|
|
@@ -15632,7 +15691,7 @@ var CodexAspManager = class extends CodingAgentManager {
|
|
|
15632
15691
|
const serviceTier = await this.resolveRequestedServiceTier(host, request);
|
|
15633
15692
|
const threadStartResponse = await host.client.request(
|
|
15634
15693
|
THREAD_START_METHOD,
|
|
15635
|
-
await buildThreadStartParams(this.workingDirectory, request, developerInstructions, serviceTier,
|
|
15694
|
+
await buildThreadStartParams(this.workingDirectory, request, developerInstructions, serviceTier, subagentMcpParentChatId)
|
|
15636
15695
|
);
|
|
15637
15696
|
const threadId = threadStartResponse.thread.id;
|
|
15638
15697
|
this.currentThreadId = threadId;
|
|
@@ -15640,19 +15699,20 @@ var CodexAspManager = class extends CodingAgentManager {
|
|
|
15640
15699
|
this.attachedClient = host.client;
|
|
15641
15700
|
this.attachedModel = requestedModel;
|
|
15642
15701
|
this.attachedDeveloperInstructions = developerInstructions ?? null;
|
|
15702
|
+
if (subagentMcpParentChatId) await markSubagentMcpThread(threadId);
|
|
15643
15703
|
await this.onSaveSessionId(this.currentThreadId);
|
|
15644
15704
|
return threadId;
|
|
15645
15705
|
}
|
|
15646
15706
|
async continueWithNewProvider(host, previous, request, developerInstructions, serviceTier) {
|
|
15647
15707
|
const events = codexTranscriptToEvents(threadToAspTranscript(previous));
|
|
15648
15708
|
const text = canonicalizeChatTranscriptBlocks(events.map((event) => JSON.stringify(event)).join("\n"), "codex", void 0).join("\n\n");
|
|
15649
|
-
const directory =
|
|
15709
|
+
const directory = join17(ENGINE_ENV.HOME_DIR, ".replicas", "codex", "provider-context");
|
|
15650
15710
|
await mkdir11(directory, { recursive: true });
|
|
15651
|
-
const transcriptPath =
|
|
15711
|
+
const transcriptPath = join17(directory, `${previous.id}.md`);
|
|
15652
15712
|
await writeFile6(transcriptPath, text, "utf8");
|
|
15653
15713
|
const response = await host.client.request(
|
|
15654
15714
|
THREAD_START_METHOD,
|
|
15655
|
-
await buildThreadStartParams(this.workingDirectory, request, developerInstructions, serviceTier, this.
|
|
15715
|
+
await buildThreadStartParams(this.workingDirectory, request, developerInstructions, serviceTier, this.subagentMcpParentChatId())
|
|
15656
15716
|
);
|
|
15657
15717
|
await host.client.request(THREAD_INJECT_ITEMS_METHOD, {
|
|
15658
15718
|
threadId: response.thread.id,
|
|
@@ -15663,6 +15723,7 @@ var CodexAspManager = class extends CodingAgentManager {
|
|
|
15663
15723
|
${text.slice(-24e3)}`
|
|
15664
15724
|
}] }]
|
|
15665
15725
|
});
|
|
15726
|
+
if (this.subagentMcpParentChatId()) await markSubagentMcpThread(response.thread.id);
|
|
15666
15727
|
if (this.currentGoal) {
|
|
15667
15728
|
await host.client.request(THREAD_GOAL_SET_METHOD, {
|
|
15668
15729
|
threadId: response.thread.id,
|
|
@@ -16275,23 +16336,23 @@ ${text.slice(-24e3)}`
|
|
|
16275
16336
|
|
|
16276
16337
|
// src/managers/cursor-manager.ts
|
|
16277
16338
|
import { mkdir as mkdir13, readFile as readFile12, readdir as readdir5 } from "fs/promises";
|
|
16278
|
-
import { basename as basename2, dirname as
|
|
16339
|
+
import { basename as basename2, dirname as dirname7, extname, join as join19 } from "path";
|
|
16279
16340
|
import { Agent as CursorAgent2 } from "@cursor/sdk";
|
|
16280
16341
|
|
|
16281
16342
|
// src/services/native-command-protection-hooks.ts
|
|
16282
|
-
import { existsSync as
|
|
16343
|
+
import { existsSync as existsSync10 } from "fs";
|
|
16283
16344
|
import { mkdir as mkdir12, readFile as readFile11, writeFile as writeFile7 } from "fs/promises";
|
|
16284
|
-
import { basename, dirname as
|
|
16285
|
-
import { fileURLToPath } from "url";
|
|
16286
|
-
var moduleDirectory =
|
|
16345
|
+
import { basename, dirname as dirname6, join as join18 } from "path";
|
|
16346
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
16347
|
+
var moduleDirectory = dirname6(fileURLToPath2(import.meta.url));
|
|
16287
16348
|
var hookPath = [
|
|
16288
|
-
|
|
16289
|
-
|
|
16290
|
-
].find(
|
|
16349
|
+
join18(moduleDirectory, "command-protection-hook.js"),
|
|
16350
|
+
join18(moduleDirectory, "..", "command-protection-hook.ts")
|
|
16351
|
+
].find(existsSync10);
|
|
16291
16352
|
var postToolHookPath = [
|
|
16292
|
-
|
|
16293
|
-
|
|
16294
|
-
].find(
|
|
16353
|
+
join18(moduleDirectory, "post-tool-pr-hook.js"),
|
|
16354
|
+
join18(moduleDirectory, "..", "post-tool-pr-hook.ts")
|
|
16355
|
+
].find(existsSync10);
|
|
16295
16356
|
function shellCommand(path7, provider) {
|
|
16296
16357
|
if (!path7) throw new Error("Replicas hook executable is missing.");
|
|
16297
16358
|
const args = [
|
|
@@ -16311,7 +16372,7 @@ function getPostToolPrHookPath() {
|
|
|
16311
16372
|
return postToolHookPath;
|
|
16312
16373
|
}
|
|
16313
16374
|
async function ensureCursorCommandProtectionHook() {
|
|
16314
|
-
const path7 =
|
|
16375
|
+
const path7 = join18(ENGINE_ENV.HOME_DIR, ".cursor", "hooks.json");
|
|
16315
16376
|
let config = {};
|
|
16316
16377
|
try {
|
|
16317
16378
|
const parsed = JSON.parse(await readFile11(path7, "utf8"));
|
|
@@ -16331,7 +16392,7 @@ async function ensureCursorCommandProtectionHook() {
|
|
|
16331
16392
|
...existingPost.filter((entry) => !isRecord2(entry) || typeof entry.command !== "string" || !entry.command.includes("post-tool-pr-hook")),
|
|
16332
16393
|
{ command: shellCommand(postToolHookPath) }
|
|
16333
16394
|
];
|
|
16334
|
-
await mkdir12(
|
|
16395
|
+
await mkdir12(dirname6(path7), { recursive: true });
|
|
16335
16396
|
await writeFile7(path7, `${JSON.stringify({ ...config, version: 1, hooks }, null, 2)}
|
|
16336
16397
|
`, "utf8");
|
|
16337
16398
|
}
|
|
@@ -16410,7 +16471,7 @@ async function listCursorCommandsInDirectory(directory) {
|
|
|
16410
16471
|
const name = basename2(entry.name, ".md");
|
|
16411
16472
|
let description;
|
|
16412
16473
|
try {
|
|
16413
|
-
description = extractCursorCommandDescription(await readFile12(
|
|
16474
|
+
description = extractCursorCommandDescription(await readFile12(join19(directory, entry.name), "utf8"));
|
|
16414
16475
|
} catch (error) {
|
|
16415
16476
|
console.warn("[CursorManager] Failed to read slash command file:", error);
|
|
16416
16477
|
}
|
|
@@ -16432,12 +16493,12 @@ var CursorManager = class extends CodingAgentManager {
|
|
|
16432
16493
|
slashCommandsRequest = null;
|
|
16433
16494
|
constructor(options) {
|
|
16434
16495
|
super(options);
|
|
16435
|
-
this.historyFilePath = options.historyFilePath ??
|
|
16496
|
+
this.historyFilePath = options.historyFilePath ?? join19(ENGINE_ENV.HOME_DIR, ".replicas", "cursor", "history.jsonl");
|
|
16436
16497
|
this.historyFile = new CodexHistoryFile(this.historyFilePath);
|
|
16437
16498
|
this.initializeManager(this.processMessageInternal.bind(this));
|
|
16438
16499
|
}
|
|
16439
16500
|
async initialize() {
|
|
16440
|
-
await mkdir13(
|
|
16501
|
+
await mkdir13(dirname7(this.historyFilePath), { recursive: true });
|
|
16441
16502
|
await ensureCursorCommandProtectionHook();
|
|
16442
16503
|
}
|
|
16443
16504
|
getHistorySink() {
|
|
@@ -16507,7 +16568,7 @@ var CursorManager = class extends CodingAgentManager {
|
|
|
16507
16568
|
this.slashCommandsRequest ??= (async () => {
|
|
16508
16569
|
try {
|
|
16509
16570
|
const repoDirectories = await getAgentAdditionalDirectories();
|
|
16510
|
-
const commandDirectories = [this.workingDirectory, ...repoDirectories, ENGINE_ENV.HOME_DIR].map((directory) =>
|
|
16571
|
+
const commandDirectories = [this.workingDirectory, ...repoDirectories, ENGINE_ENV.HOME_DIR].map((directory) => join19(directory, ".cursor", "commands"));
|
|
16511
16572
|
const commands = mergeSlashCommands(
|
|
16512
16573
|
...await Promise.all(commandDirectories.map(listCursorCommandsInDirectory))
|
|
16513
16574
|
);
|
|
@@ -16788,7 +16849,7 @@ ${instructions}
|
|
|
16788
16849
|
import { spawn as spawn3 } from "child_process";
|
|
16789
16850
|
import { randomBytes as randomBytes2 } from "crypto";
|
|
16790
16851
|
import { mkdir as mkdir14 } from "fs/promises";
|
|
16791
|
-
import { dirname as
|
|
16852
|
+
import { dirname as dirname8 } from "path";
|
|
16792
16853
|
var MuseQuotaError = class extends Error {
|
|
16793
16854
|
};
|
|
16794
16855
|
function uuidV7() {
|
|
@@ -16829,7 +16890,7 @@ var MuseManager = class extends CodingAgentManager {
|
|
|
16829
16890
|
this.initializeManager(this.processMessageInternal.bind(this));
|
|
16830
16891
|
}
|
|
16831
16892
|
async initialize() {
|
|
16832
|
-
await mkdir14(
|
|
16893
|
+
await mkdir14(dirname8(this.historyFilePath), { recursive: true });
|
|
16833
16894
|
}
|
|
16834
16895
|
getHistorySink() {
|
|
16835
16896
|
return this.historyFile;
|
|
@@ -17298,11 +17359,11 @@ ${pending}
|
|
|
17298
17359
|
};
|
|
17299
17360
|
|
|
17300
17361
|
// src/managers/opencode-manager.ts
|
|
17301
|
-
import { existsSync as
|
|
17362
|
+
import { existsSync as existsSync11 } from "fs";
|
|
17302
17363
|
import { copyFile, mkdir as mkdir15, readFile as readFile13, rm as rm2 } from "fs/promises";
|
|
17303
|
-
import { delimiter, dirname as
|
|
17364
|
+
import { delimiter, dirname as dirname9, join as join20 } from "path";
|
|
17304
17365
|
import { randomBytes as randomBytes3 } from "crypto";
|
|
17305
|
-
import { fileURLToPath as
|
|
17366
|
+
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
17306
17367
|
import { Agent } from "undici";
|
|
17307
17368
|
import { z } from "zod";
|
|
17308
17369
|
import {
|
|
@@ -17328,11 +17389,11 @@ async function getAllowedOpenRouterModels() {
|
|
|
17328
17389
|
}
|
|
17329
17390
|
|
|
17330
17391
|
// src/managers/opencode-manager.ts
|
|
17331
|
-
var OPENCODE_SHIM_DIR =
|
|
17332
|
-
var OPENCODE_COMMAND_PROTECTION_PLUGIN_SOURCE =
|
|
17333
|
-
var OPENCODE_COMMAND_PROTECTION_PLUGIN_PATH =
|
|
17334
|
-
var OPENCODE_LEGACY_COMMAND_PROTECTION_PLUGIN_PATH =
|
|
17335
|
-
var OPENCODE_CONFIG_PATH =
|
|
17392
|
+
var OPENCODE_SHIM_DIR = dirname9(fileURLToPath3(new URL("../../scripts/opencode", import.meta.url)));
|
|
17393
|
+
var OPENCODE_COMMAND_PROTECTION_PLUGIN_SOURCE = join20(OPENCODE_SHIM_DIR, "opencode-command-protection-plugin.ts");
|
|
17394
|
+
var OPENCODE_COMMAND_PROTECTION_PLUGIN_PATH = join20(ENGINE_ENV.HOME_DIR, ".config", "opencode", "plugins", "replicas-command-protection.ts");
|
|
17395
|
+
var OPENCODE_LEGACY_COMMAND_PROTECTION_PLUGIN_PATH = join20(ENGINE_ENV.HOME_DIR, ".config", "opencode", "plugins", "replicas-command-protection.mjs");
|
|
17396
|
+
var OPENCODE_CONFIG_PATH = join20(ENGINE_ENV.HOME_DIR, ".config", "opencode", "opencode.json");
|
|
17336
17397
|
var OPENCODE_FETCH_DISPATCHER = new Agent({ headersTimeout: 0, bodyTimeout: 0 });
|
|
17337
17398
|
var OPENCODE_SERVER_STARTUP_TIMEOUT_MS = 3e4;
|
|
17338
17399
|
var OPENCODE_WORKSPACE_PERMISSION = "allow";
|
|
@@ -17352,7 +17413,7 @@ var opencodeAuthSchema = z.record(z.string(), z.object({
|
|
|
17352
17413
|
}));
|
|
17353
17414
|
async function hasOpencodeCredentials(provider) {
|
|
17354
17415
|
if (provider === "ollama") return !!readOllamaAuthEnv("opencode", process.env);
|
|
17355
|
-
if (!
|
|
17416
|
+
if (!existsSync11(OPENCODE_AUTH_PATH)) return false;
|
|
17356
17417
|
try {
|
|
17357
17418
|
const auth2 = opencodeAuthSchema.safeParse(JSON.parse(await readFile13(OPENCODE_AUTH_PATH, "utf8")));
|
|
17358
17419
|
return auth2.success && auth2.data[provider]?.type === "api" && Boolean(auth2.data[provider]?.key);
|
|
@@ -17538,6 +17599,7 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
17538
17599
|
configuredModels = /* @__PURE__ */ new Set();
|
|
17539
17600
|
clientUpdate = Promise.resolve();
|
|
17540
17601
|
providerId = "openrouter";
|
|
17602
|
+
serverSubagentMcpParentChatId;
|
|
17541
17603
|
eventAbortController = null;
|
|
17542
17604
|
eventSubscriptionReady = Promise.resolve();
|
|
17543
17605
|
resolveEventSubscriptionReady = null;
|
|
@@ -17553,12 +17615,12 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
17553
17615
|
constructor(options) {
|
|
17554
17616
|
super({ ...options, provider: "opencode" });
|
|
17555
17617
|
this.sessionId = options.initialSessionId;
|
|
17556
|
-
this.historyFilePath = options.historyFilePath ??
|
|
17618
|
+
this.historyFilePath = options.historyFilePath ?? join20(ENGINE_ENV.HOME_DIR, ".replicas", "opencode", "history.jsonl");
|
|
17557
17619
|
this.historyFile = new CodexHistoryFile(this.historyFilePath);
|
|
17558
17620
|
this.initializeManager(this.processMessageInternal.bind(this));
|
|
17559
17621
|
}
|
|
17560
17622
|
async initialize() {
|
|
17561
|
-
await mkdir15(
|
|
17623
|
+
await mkdir15(dirname9(this.historyFilePath), { recursive: true });
|
|
17562
17624
|
}
|
|
17563
17625
|
getHistorySink() {
|
|
17564
17626
|
return this.historyFile;
|
|
@@ -17636,7 +17698,8 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
17636
17698
|
await previousUpdate;
|
|
17637
17699
|
try {
|
|
17638
17700
|
if (reuseExisting && this.client) return this.client;
|
|
17639
|
-
|
|
17701
|
+
const subagentMcpParentChatId = this.subagentMcpParentChatId();
|
|
17702
|
+
if (this.client && (this.providerId !== providerId || this.serverSubagentMcpParentChatId !== subagentMcpParentChatId)) {
|
|
17640
17703
|
this.eventAbortController?.abort();
|
|
17641
17704
|
this.server?.close();
|
|
17642
17705
|
this.client = null;
|
|
@@ -17656,10 +17719,10 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
17656
17719
|
if (!await hasOpencodeCredentials(providerId)) {
|
|
17657
17720
|
throw new Error("OpenCode Go, Aster, OpenRouter, or Ollama credentials are not configured for Opencode in this workspace.");
|
|
17658
17721
|
}
|
|
17659
|
-
if (!
|
|
17722
|
+
if (!existsSync11(OPENCODE_COMMAND_PROTECTION_PLUGIN_SOURCE)) {
|
|
17660
17723
|
throw new Error("Opencode command protection plugin is missing from the engine package.");
|
|
17661
17724
|
}
|
|
17662
|
-
await mkdir15(
|
|
17725
|
+
await mkdir15(dirname9(OPENCODE_COMMAND_PROTECTION_PLUGIN_PATH), { recursive: true });
|
|
17663
17726
|
await copyFile(OPENCODE_COMMAND_PROTECTION_PLUGIN_SOURCE, OPENCODE_COMMAND_PROTECTION_PLUGIN_PATH);
|
|
17664
17727
|
await rm2(OPENCODE_LEGACY_COMMAND_PROTECTION_PLUGIN_PATH, { force: true });
|
|
17665
17728
|
process.env.REPLICAS_COMMAND_PROTECTION_HOOK_PATH = getCommandProtectionHookPath();
|
|
@@ -17676,15 +17739,15 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
17676
17739
|
const config = opencodeConfig(providerId, configuredModel, providerModels);
|
|
17677
17740
|
const mcp = await readProvisionedOpencodeMcpConfig();
|
|
17678
17741
|
if (mcp && Object.keys(mcp).length > 0) config.mcp = mcp;
|
|
17679
|
-
if (
|
|
17680
|
-
const
|
|
17742
|
+
if (subagentMcpParentChatId) {
|
|
17743
|
+
const subagentMcp = subagentMcpProcessConfig(subagentMcpParentChatId);
|
|
17681
17744
|
config.mcp = {
|
|
17682
17745
|
...config.mcp,
|
|
17683
|
-
[
|
|
17746
|
+
[SUBAGENT_MCP_SERVER_NAME]: {
|
|
17684
17747
|
type: "local",
|
|
17685
|
-
command: [
|
|
17748
|
+
command: [subagentMcp.command, ...subagentMcp.args],
|
|
17686
17749
|
enabled: true,
|
|
17687
|
-
timeout:
|
|
17750
|
+
timeout: SUBAGENT_MCP_TOOL_TIMEOUT_MS
|
|
17688
17751
|
}
|
|
17689
17752
|
};
|
|
17690
17753
|
}
|
|
@@ -17702,6 +17765,7 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
17702
17765
|
});
|
|
17703
17766
|
this.client = client;
|
|
17704
17767
|
this.server = server2;
|
|
17768
|
+
this.serverSubagentMcpParentChatId = subagentMcpParentChatId;
|
|
17705
17769
|
this.configuredModels = new Set(providerModels);
|
|
17706
17770
|
const eventController = new AbortController();
|
|
17707
17771
|
this.eventAbortController = eventController;
|
|
@@ -17793,7 +17857,7 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
17793
17857
|
model: { providerID: this.providerId, modelID: providerModel },
|
|
17794
17858
|
...variant ? { variant } : {},
|
|
17795
17859
|
...system ? { system } : {},
|
|
17796
|
-
...this.
|
|
17860
|
+
...this.subagentMcpParentChatId() ? { tools: { task: false } } : {},
|
|
17797
17861
|
parts: [{ type: "text", text: request.message }]
|
|
17798
17862
|
}, { signal: controller.signal, throwOnError: true });
|
|
17799
17863
|
this.recordHistoryEvent("opencode-message.updated", { info: result.data.info }, this.historyFile);
|
|
@@ -17975,7 +18039,7 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
17975
18039
|
|
|
17976
18040
|
// src/managers/pi-manager.ts
|
|
17977
18041
|
import { mkdir as mkdir17, readFile as readFile14 } from "fs/promises";
|
|
17978
|
-
import { dirname as
|
|
18042
|
+
import { dirname as dirname17, join as join28 } from "path";
|
|
17979
18043
|
import {
|
|
17980
18044
|
createAgentSession,
|
|
17981
18045
|
ModelRegistry,
|
|
@@ -17986,20 +18050,18 @@ import {
|
|
|
17986
18050
|
|
|
17987
18051
|
// src/services/chat/history-paths.ts
|
|
17988
18052
|
import { homedir as homedir12 } from "os";
|
|
17989
|
-
import { join as
|
|
17990
|
-
var ENGINE_DIR2 =
|
|
17991
|
-
var CHATS_FILE =
|
|
17992
|
-
var CLAUDE_HISTORY_DIR =
|
|
17993
|
-
var
|
|
17994
|
-
var
|
|
17995
|
-
var
|
|
17996
|
-
var
|
|
17997
|
-
var
|
|
17998
|
-
var
|
|
17999
|
-
var FORKS_DIR = join20(ENGINE_DIR2, "forks");
|
|
18053
|
+
import { join as join21 } from "path";
|
|
18054
|
+
var ENGINE_DIR2 = join21(homedir12(), ".replicas", "engine");
|
|
18055
|
+
var CHATS_FILE = join21(ENGINE_DIR2, "chats.json");
|
|
18056
|
+
var CLAUDE_HISTORY_DIR = join21(ENGINE_DIR2, "claude-histories");
|
|
18057
|
+
var CODEX_HISTORY_DIR = join21(ENGINE_DIR2, "codex-histories");
|
|
18058
|
+
var CURSOR_HISTORY_DIR = join21(ENGINE_DIR2, "cursor-histories");
|
|
18059
|
+
var OPENCODE_HISTORY_DIR = join21(ENGINE_DIR2, "opencode-histories");
|
|
18060
|
+
var PI_HISTORY_DIR = join21(ENGINE_DIR2, "pi-histories");
|
|
18061
|
+
var MUSE_HISTORY_DIR = join21(ENGINE_DIR2, "muse-histories");
|
|
18062
|
+
var FORKS_DIR = join21(ENGINE_DIR2, "forks");
|
|
18000
18063
|
var HISTORY_DIR_BY_PROVIDER = {
|
|
18001
18064
|
claude: CLAUDE_HISTORY_DIR,
|
|
18002
|
-
relay: RELAY_HISTORY_DIR,
|
|
18003
18065
|
codex: CODEX_HISTORY_DIR,
|
|
18004
18066
|
cursor: CURSOR_HISTORY_DIR,
|
|
18005
18067
|
muse: MUSE_HISTORY_DIR,
|
|
@@ -22596,7 +22658,7 @@ __export(typebox_exports, {
|
|
|
22596
22658
|
});
|
|
22597
22659
|
|
|
22598
22660
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/init.ts
|
|
22599
|
-
import { existsSync as
|
|
22661
|
+
import { existsSync as existsSync14 } from "fs";
|
|
22600
22662
|
|
|
22601
22663
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/errors.ts
|
|
22602
22664
|
var McpUiError = class extends Error {
|
|
@@ -40536,8 +40598,8 @@ async function probeMcpEndpoint(url3) {
|
|
|
40536
40598
|
}
|
|
40537
40599
|
|
|
40538
40600
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/npx-resolver.ts
|
|
40539
|
-
import { existsSync as
|
|
40540
|
-
import { join as
|
|
40601
|
+
import { existsSync as existsSync12, readFileSync as readFileSync3, realpathSync, readdirSync, statSync, writeFileSync as writeFileSync2, renameSync, mkdirSync, openSync, readSync, closeSync, unlinkSync } from "fs";
|
|
40602
|
+
import { join as join22, dirname as dirname10, extname as extname2, resolve as resolve2, sep } from "path";
|
|
40541
40603
|
|
|
40542
40604
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/abort.ts
|
|
40543
40605
|
function throwIfAborted(signal) {
|
|
@@ -40587,7 +40649,7 @@ async function resolveNpxBinary(command, args, signal) {
|
|
|
40587
40649
|
const cacheKey = JSON.stringify([command, parsed.packageSpec, parsed.binName ?? ""]);
|
|
40588
40650
|
const cache2 = loadCache();
|
|
40589
40651
|
const cached = cache2?.entries?.[cacheKey];
|
|
40590
|
-
if (cached && Date.now() - cached.resolvedAt < CACHE_TTL_MS &&
|
|
40652
|
+
if (cached && Date.now() - cached.resolvedAt < CACHE_TTL_MS && existsSync12(cached.resolvedBin) && (!packageSpec?.exactVersion || cached.packageVersion === packageSpec.exactVersion)) {
|
|
40591
40653
|
return { binPath: cached.resolvedBin, extraArgs: parsed.extraArgs, isJs: cached.isJs };
|
|
40592
40654
|
}
|
|
40593
40655
|
const resolved = resolveFromNpmCache(parsed.packageSpec, parsed.binName);
|
|
@@ -40694,8 +40756,8 @@ function resolveFromNpmCache(packageSpec, binName) {
|
|
|
40694
40756
|
const { packageName, exactVersion } = parsedSpec;
|
|
40695
40757
|
const packageDir = findCachedPackageDir(cacheDir, packageName, exactVersion);
|
|
40696
40758
|
if (!packageDir) return null;
|
|
40697
|
-
const packageJsonPath =
|
|
40698
|
-
if (!
|
|
40759
|
+
const packageJsonPath = join22(packageDir, "package.json");
|
|
40760
|
+
if (!existsSync12(packageJsonPath)) return null;
|
|
40699
40761
|
let pkg = null;
|
|
40700
40762
|
try {
|
|
40701
40763
|
pkg = JSON.parse(readFileSync3(packageJsonPath, "utf-8"));
|
|
@@ -40728,11 +40790,11 @@ function resolveFromNpmCache(packageSpec, binName) {
|
|
|
40728
40790
|
}
|
|
40729
40791
|
if (!binRel) return null;
|
|
40730
40792
|
const nodeModulesDir = findNodeModulesDir(packageDir);
|
|
40731
|
-
const binLink = chosenBinName ?
|
|
40732
|
-
let resolvedBin = binLink &&
|
|
40793
|
+
const binLink = chosenBinName ? join22(nodeModulesDir, ".bin", chosenBinName) : null;
|
|
40794
|
+
let resolvedBin = binLink && existsSync12(binLink) ? safeRealpath(binLink) : "";
|
|
40733
40795
|
if (!resolvedBin) {
|
|
40734
40796
|
resolvedBin = resolve2(packageDir, binRel);
|
|
40735
|
-
if (!
|
|
40797
|
+
if (!existsSync12(resolvedBin)) return null;
|
|
40736
40798
|
}
|
|
40737
40799
|
const isJs = detectJsBinary(resolvedBin);
|
|
40738
40800
|
return {
|
|
@@ -40830,18 +40892,18 @@ function defaultBinName(packageName) {
|
|
|
40830
40892
|
return packageName;
|
|
40831
40893
|
}
|
|
40832
40894
|
function findCachedPackageDir(cacheDir, packageName, exactVersion) {
|
|
40833
|
-
const npxDir =
|
|
40834
|
-
if (!
|
|
40895
|
+
const npxDir = join22(cacheDir, "_npx");
|
|
40896
|
+
if (!existsSync12(npxDir)) return null;
|
|
40835
40897
|
const packagePathParts = packageName.startsWith("@") ? packageName.split("/") : [packageName];
|
|
40836
40898
|
const candidates = readdirSync(npxDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => {
|
|
40837
|
-
const full =
|
|
40899
|
+
const full = join22(npxDir, entry.name);
|
|
40838
40900
|
const mtime = safeStatMtime(full);
|
|
40839
40901
|
return { name: entry.name, mtime };
|
|
40840
40902
|
}).sort((a, b) => b.mtime - a.mtime);
|
|
40841
40903
|
for (const entry of candidates) {
|
|
40842
|
-
const pkgDir =
|
|
40843
|
-
const packageJsonPath =
|
|
40844
|
-
if (!
|
|
40904
|
+
const pkgDir = join22(npxDir, entry.name, "node_modules", ...packagePathParts);
|
|
40905
|
+
const packageJsonPath = join22(pkgDir, "package.json");
|
|
40906
|
+
if (!existsSync12(packageJsonPath)) continue;
|
|
40845
40907
|
if (exactVersion) {
|
|
40846
40908
|
try {
|
|
40847
40909
|
const pkg = JSON.parse(readFileSync3(packageJsonPath, "utf-8"));
|
|
@@ -40860,7 +40922,7 @@ function findNodeModulesDir(packageDir) {
|
|
|
40860
40922
|
if (idx >= 0) {
|
|
40861
40923
|
return parts.slice(0, idx + 1).join(sep);
|
|
40862
40924
|
}
|
|
40863
|
-
return
|
|
40925
|
+
return join22(packageDir, "..");
|
|
40864
40926
|
}
|
|
40865
40927
|
function detectJsBinary(binPath) {
|
|
40866
40928
|
const ext = extname2(binPath).toLowerCase();
|
|
@@ -40904,7 +40966,7 @@ function getNpxCachePath() {
|
|
|
40904
40966
|
return getAgentPath("mcp-npx-cache.json");
|
|
40905
40967
|
}
|
|
40906
40968
|
function readNpxCachePayload(cachePath) {
|
|
40907
|
-
if (!
|
|
40969
|
+
if (!existsSync12(cachePath)) return null;
|
|
40908
40970
|
try {
|
|
40909
40971
|
return JSON.parse(readFileSync3(cachePath, "utf-8"));
|
|
40910
40972
|
} catch {
|
|
@@ -40965,7 +41027,7 @@ function loadCache() {
|
|
|
40965
41027
|
function saveCacheEntry(key, entry) {
|
|
40966
41028
|
try {
|
|
40967
41029
|
const cachePath = getNpxCachePath();
|
|
40968
|
-
const dir =
|
|
41030
|
+
const dir = dirname10(cachePath);
|
|
40969
41031
|
mkdirSync(dir, { recursive: true });
|
|
40970
41032
|
const existing = toNpxCache(readNpxCachePayload(cachePath));
|
|
40971
41033
|
const entries = createCacheEntries();
|
|
@@ -41050,11 +41112,11 @@ function createJsonSchemaValidator() {
|
|
|
41050
41112
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/mcp-auth.ts
|
|
41051
41113
|
import { spawnSync } from "child_process";
|
|
41052
41114
|
import { createHash as createHash2 } from "crypto";
|
|
41053
|
-
import { createRequire } from "module";
|
|
41054
|
-
import { readFileSync as readFileSync4, existsSync as
|
|
41055
|
-
import { dirname as
|
|
41056
|
-
import { fileURLToPath as
|
|
41057
|
-
var require2 =
|
|
41115
|
+
import { createRequire as createRequire2 } from "module";
|
|
41116
|
+
import { readFileSync as readFileSync4, existsSync as existsSync13, rmSync as rmSync2 } from "fs";
|
|
41117
|
+
import { dirname as dirname11, join as join23 } from "path";
|
|
41118
|
+
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
41119
|
+
var require2 = createRequire2(import.meta.url);
|
|
41058
41120
|
var AUTH_SECRET_SERVICE = "pi-mcp-adapter.oauth";
|
|
41059
41121
|
var TEST_AUTH_STORE_ENV = "PI_MCP_ADAPTER_TEST_AUTH_STORE";
|
|
41060
41122
|
var AUTH_SECRET_CHUNK_SIZE = 1e3;
|
|
@@ -41208,7 +41270,7 @@ function loadKeyringNativeBindingFallback(keyringRequire, platform3, arch2) {
|
|
|
41208
41270
|
for (const target of targets) {
|
|
41209
41271
|
try {
|
|
41210
41272
|
const packageJsonPath = keyringRequire.resolve(`${target.packageName}/package.json`);
|
|
41211
|
-
return keyringRequire(
|
|
41273
|
+
return keyringRequire(join23(dirname11(packageJsonPath), target.bindingFile));
|
|
41212
41274
|
} catch (error) {
|
|
41213
41275
|
lastError = error;
|
|
41214
41276
|
}
|
|
@@ -41253,7 +41315,7 @@ function shouldAttemptLinuxKeyringRecovery(error) {
|
|
|
41253
41315
|
function runLinuxKeyringRecoveryOperation(operation, account, payload) {
|
|
41254
41316
|
const keyctl = process.env[KEYRING_RECOVERY_KEYCTL_ENV]?.trim() || "keyctl";
|
|
41255
41317
|
const node = process.env[KEYRING_RECOVERY_NODE_ENV]?.trim() || "node";
|
|
41256
|
-
const helper = process.env[KEYRING_RECOVERY_HELPER_ENV]?.trim() ||
|
|
41318
|
+
const helper = process.env[KEYRING_RECOVERY_HELPER_ENV]?.trim() || fileURLToPath4(new URL("./mcp-keyring-helper.cjs", import.meta.url));
|
|
41257
41319
|
const request = JSON.stringify({ operation, service: AUTH_SECRET_SERVICE, account, payload });
|
|
41258
41320
|
const result = spawnSync(keyctl, ["session", "-", node, helper], {
|
|
41259
41321
|
input: `${request}
|
|
@@ -41313,7 +41375,7 @@ function getServerDir(serverName, options) {
|
|
|
41313
41375
|
throw new Error(`Invalid MCP server name: ${JSON.stringify(serverName)}`);
|
|
41314
41376
|
}
|
|
41315
41377
|
const storageKey = getAuthEntryAccount(serverName);
|
|
41316
|
-
return
|
|
41378
|
+
return join23(getAuthBaseDir(options), storageKey);
|
|
41317
41379
|
}
|
|
41318
41380
|
function getAuthEntryAccount(serverName) {
|
|
41319
41381
|
if (typeof serverName !== "string") {
|
|
@@ -41322,7 +41384,7 @@ function getAuthEntryAccount(serverName) {
|
|
|
41322
41384
|
return `sha256-${createHash2("sha256").update(serverName, "utf8").digest("hex")}`;
|
|
41323
41385
|
}
|
|
41324
41386
|
function getAuthEntryFilePath(serverName, options) {
|
|
41325
|
-
return
|
|
41387
|
+
return join23(getServerDir(serverName, options), "tokens.json");
|
|
41326
41388
|
}
|
|
41327
41389
|
function parseJsonPayload(serverName, payload, source) {
|
|
41328
41390
|
try {
|
|
@@ -41471,13 +41533,13 @@ function readChunkedAuthEntry(store, serverName, account, manifest) {
|
|
|
41471
41533
|
}
|
|
41472
41534
|
function readLegacyAuthEntry(serverName, options) {
|
|
41473
41535
|
const filePath = getAuthEntryFilePath(serverName, options);
|
|
41474
|
-
if (!
|
|
41536
|
+
if (!existsSync13(filePath)) return void 0;
|
|
41475
41537
|
const data = readFileSync4(filePath, "utf-8");
|
|
41476
41538
|
return parseAuthEntryPayload(serverName, data, filePath);
|
|
41477
41539
|
}
|
|
41478
41540
|
function removeLegacyAuthEntry(serverName, options) {
|
|
41479
41541
|
const filePath = getAuthEntryFilePath(serverName, options);
|
|
41480
|
-
if (!
|
|
41542
|
+
if (!existsSync13(filePath)) return;
|
|
41481
41543
|
try {
|
|
41482
41544
|
rmSync2(filePath, { force: true });
|
|
41483
41545
|
} catch (error) {
|
|
@@ -42247,7 +42309,7 @@ var McpOAuthProvider = class {
|
|
|
42247
42309
|
import process9 from "process";
|
|
42248
42310
|
import { Buffer as Buffer2 } from "buffer";
|
|
42249
42311
|
import path5 from "path";
|
|
42250
|
-
import { fileURLToPath as
|
|
42312
|
+
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
42251
42313
|
import { promisify as promisify5 } from "util";
|
|
42252
42314
|
import childProcess from "child_process";
|
|
42253
42315
|
import fs6, { constants as fsConstants2 } from "fs/promises";
|
|
@@ -42504,7 +42566,7 @@ async function defaultBrowser2() {
|
|
|
42504
42566
|
|
|
42505
42567
|
// ../node_modules/.bun/open@10.2.0/node_modules/open/index.js
|
|
42506
42568
|
var execFile5 = promisify5(childProcess.execFile);
|
|
42507
|
-
var __dirname = path5.dirname(
|
|
42569
|
+
var __dirname = path5.dirname(fileURLToPath5(import.meta.url));
|
|
42508
42570
|
var localXdgOpenPath = path5.join(__dirname, "xdg-open");
|
|
42509
42571
|
var { platform, arch } = process9;
|
|
42510
42572
|
async function getWindowsDefaultBrowserFromWsl() {
|
|
@@ -43924,9 +43986,9 @@ async function shutdownOAuth(runtime = legacyRuntime) {
|
|
|
43924
43986
|
|
|
43925
43987
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/mcp-bearer-store.ts
|
|
43926
43988
|
import { createHash as createHash3 } from "crypto";
|
|
43927
|
-
import { createRequire as
|
|
43928
|
-
import { dirname as
|
|
43929
|
-
var require3 =
|
|
43989
|
+
import { createRequire as createRequire3 } from "module";
|
|
43990
|
+
import { dirname as dirname12, join as join24 } from "path";
|
|
43991
|
+
var require3 = createRequire3(import.meta.url);
|
|
43930
43992
|
var BEARER_SECRET_SERVICE = "pi-mcp-adapter.bearer";
|
|
43931
43993
|
var TEST_AUTH_STORE_ENV2 = "PI_MCP_ADAPTER_TEST_AUTH_STORE";
|
|
43932
43994
|
var BEARER_SECRET_VALUE_LIMIT = 1280;
|
|
@@ -44027,7 +44089,7 @@ function loadKeyringNativeBindingFallback2(keyringRequire, platform3, arch2) {
|
|
|
44027
44089
|
for (const target of targets) {
|
|
44028
44090
|
try {
|
|
44029
44091
|
const packageJsonPath = keyringRequire.resolve(`${target.packageName}/package.json`);
|
|
44030
|
-
return keyringRequire(
|
|
44092
|
+
return keyringRequire(join24(dirname12(packageJsonPath), target.bindingFile));
|
|
44031
44093
|
} catch (error) {
|
|
44032
44094
|
lastError = error;
|
|
44033
44095
|
}
|
|
@@ -44641,7 +44703,7 @@ function humanizeName(name) {
|
|
|
44641
44703
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/mcp-trace.ts
|
|
44642
44704
|
import { appendFile as appendFile3, mkdir as mkdir16, writeFile as writeFile8 } from "fs/promises";
|
|
44643
44705
|
import { Buffer as Buffer3 } from "buffer";
|
|
44644
|
-
import { dirname as
|
|
44706
|
+
import { dirname as dirname13, isAbsolute as isAbsolute3, resolve as resolve3 } from "path";
|
|
44645
44707
|
var MCP_TRACE_SCHEMA_VERSION = 1;
|
|
44646
44708
|
var DEFAULT_MCP_TRACE_MAX_BYTES = 256 * 1024;
|
|
44647
44709
|
var DEFAULT_MCP_TRACE_MAX_EVENTS = 1e4;
|
|
@@ -44714,7 +44776,7 @@ var McpTraceWriter = class {
|
|
|
44714
44776
|
await mkdir16(path7, { recursive: true });
|
|
44715
44777
|
return void 0;
|
|
44716
44778
|
});
|
|
44717
|
-
this.fileReady = this.makeDirectory(
|
|
44779
|
+
this.fileReady = this.makeDirectory(dirname13(this.options.filePath), { recursive: true }).then(() => this.resetFile(this.options.filePath, "", { encoding: "utf8" })).catch(() => {
|
|
44718
44780
|
this.initializationFailed = true;
|
|
44719
44781
|
this.disabled = true;
|
|
44720
44782
|
});
|
|
@@ -47448,7 +47510,7 @@ async function initializeMcp(pi, ctx, owner = createMcpRuntimeOwner(), options =
|
|
|
47448
47510
|
const idleSetting = typeof config.settings?.idleTimeout === "number" ? config.settings.idleTimeout : 10;
|
|
47449
47511
|
lifecycle2.setGlobalIdleTimeout(idleSetting);
|
|
47450
47512
|
const cachePath = getMetadataCachePath();
|
|
47451
|
-
const cacheFileExists =
|
|
47513
|
+
const cacheFileExists = existsSync14(cachePath);
|
|
47452
47514
|
let cache2 = loadMetadataCache();
|
|
47453
47515
|
let bootstrapAll = false;
|
|
47454
47516
|
if (!cacheFileExists) {
|
|
@@ -47839,8 +47901,8 @@ function getEffectiveIdleTimeoutMinutes(state, serverName) {
|
|
|
47839
47901
|
}
|
|
47840
47902
|
|
|
47841
47903
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/onboarding-state.ts
|
|
47842
|
-
import { existsSync as
|
|
47843
|
-
import { dirname as
|
|
47904
|
+
import { existsSync as existsSync15, mkdirSync as mkdirSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync3, renameSync as renameSync2 } from "fs";
|
|
47905
|
+
import { dirname as dirname14 } from "path";
|
|
47844
47906
|
var DEFAULT_STATE2 = {
|
|
47845
47907
|
version: 1,
|
|
47846
47908
|
sharedConfigHintShown: false,
|
|
@@ -47851,7 +47913,7 @@ function getOnboardingStatePath() {
|
|
|
47851
47913
|
}
|
|
47852
47914
|
function loadOnboardingState() {
|
|
47853
47915
|
const path7 = getOnboardingStatePath();
|
|
47854
|
-
if (!
|
|
47916
|
+
if (!existsSync15(path7)) return { ...DEFAULT_STATE2 };
|
|
47855
47917
|
try {
|
|
47856
47918
|
const raw = JSON.parse(readFileSync5(path7, "utf-8"));
|
|
47857
47919
|
if (!raw || typeof raw !== "object") return { ...DEFAULT_STATE2 };
|
|
@@ -47867,7 +47929,7 @@ function loadOnboardingState() {
|
|
|
47867
47929
|
}
|
|
47868
47930
|
function saveOnboardingState(state) {
|
|
47869
47931
|
const path7 = getOnboardingStatePath();
|
|
47870
|
-
mkdirSync3(
|
|
47932
|
+
mkdirSync3(dirname14(path7), { recursive: true });
|
|
47871
47933
|
const tmpPath = `${path7}.${process.pid}.tmp`;
|
|
47872
47934
|
writeFileSync3(tmpPath, `${JSON.stringify(state, null, 2)}
|
|
47873
47935
|
`, "utf-8");
|
|
@@ -48494,7 +48556,7 @@ async function openMcpAuthPanel(state, pi, ctx, configOverridePath) {
|
|
|
48494
48556
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/tool-registrar.ts
|
|
48495
48557
|
import { mkdtempSync, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "fs";
|
|
48496
48558
|
import { tmpdir } from "os";
|
|
48497
|
-
import { join as
|
|
48559
|
+
import { join as join25 } from "path";
|
|
48498
48560
|
var MAX_BINARY_RESOURCE_BYTES = 10 * 1024 * 1024;
|
|
48499
48561
|
var MAX_SESSION_RESOURCE_BYTES = 100 * 1024 * 1024;
|
|
48500
48562
|
var MAX_SESSION_RESOURCE_FILES = 1e4;
|
|
@@ -48601,11 +48663,11 @@ function materializeBinaryResource(resource, scope) {
|
|
|
48601
48663
|
return omitBinaryResource(resource, "session resource limit reached");
|
|
48602
48664
|
}
|
|
48603
48665
|
try {
|
|
48604
|
-
session.directory ??= mkdtempSync(
|
|
48666
|
+
session.directory ??= mkdtempSync(join25(tmpdir(), "pi-mcp-resource-"));
|
|
48605
48667
|
} catch {
|
|
48606
48668
|
return omitBinaryResource(resource, "could not be saved");
|
|
48607
48669
|
}
|
|
48608
|
-
const filePath =
|
|
48670
|
+
const filePath = join25(session.directory, `resource-${++session.sequence}.bin`);
|
|
48609
48671
|
session.bytes += decodedBytes;
|
|
48610
48672
|
session.files += 1;
|
|
48611
48673
|
try {
|
|
@@ -48698,7 +48760,7 @@ function stringifyStructuredContent(value) {
|
|
|
48698
48760
|
import { randomBytes as randomBytes4 } from "crypto";
|
|
48699
48761
|
import { mkdtemp, rm as rm3, writeFile as writeFile9 } from "fs/promises";
|
|
48700
48762
|
import { tmpdir as tmpdir2 } from "os";
|
|
48701
|
-
import { dirname as
|
|
48763
|
+
import { dirname as dirname15, join as join26 } from "path";
|
|
48702
48764
|
var DEFAULT_MCP_OUTPUT_MAX_BYTES = 50 * 1024;
|
|
48703
48765
|
var DEFAULT_MCP_OUTPUT_MAX_LINES = 2e3;
|
|
48704
48766
|
var DEFAULT_MCP_DETAILS_MAX_BYTES = 16 * 1024;
|
|
@@ -49006,8 +49068,8 @@ function serializedObjectEntryBytes(key, value, hasPrevious) {
|
|
|
49006
49068
|
}
|
|
49007
49069
|
async function saveArtifact(kind, text) {
|
|
49008
49070
|
try {
|
|
49009
|
-
const dir = await mkdtemp(
|
|
49010
|
-
const path7 =
|
|
49071
|
+
const dir = await mkdtemp(join26(tmpdir2(), "pi-mcp-output-"));
|
|
49072
|
+
const path7 = join26(dir, `${kind}-${randomBytes4(4).toString("hex")}.txt`);
|
|
49011
49073
|
await writeFile9(path7, text, { encoding: "utf8", mode: 384 });
|
|
49012
49074
|
return { path: path7 };
|
|
49013
49075
|
} catch (error) {
|
|
@@ -49016,7 +49078,7 @@ async function saveArtifact(kind, text) {
|
|
|
49016
49078
|
}
|
|
49017
49079
|
async function discardArtifact(path7) {
|
|
49018
49080
|
try {
|
|
49019
|
-
await rm3(
|
|
49081
|
+
await rm3(dirname15(path7), { recursive: true, force: true });
|
|
49020
49082
|
} catch {
|
|
49021
49083
|
}
|
|
49022
49084
|
}
|
|
@@ -50652,11 +50714,11 @@ function sendText(res, status, text) {
|
|
|
50652
50714
|
}
|
|
50653
50715
|
|
|
50654
50716
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/glimpse-ui.ts
|
|
50655
|
-
import { existsSync as
|
|
50717
|
+
import { existsSync as existsSync16 } from "fs";
|
|
50656
50718
|
import { execFileSync as execFileSync2 } from "child_process";
|
|
50657
|
-
import { join as
|
|
50719
|
+
import { join as join27, dirname as dirname16 } from "path";
|
|
50658
50720
|
import { platform as platform2 } from "os";
|
|
50659
|
-
import { createRequire as
|
|
50721
|
+
import { createRequire as createRequire4 } from "module";
|
|
50660
50722
|
var glimpseAvailable = null;
|
|
50661
50723
|
var resolvedBinaryPath = null;
|
|
50662
50724
|
function isGlimpseAvailable() {
|
|
@@ -50670,26 +50732,26 @@ function isGlimpseAvailable() {
|
|
|
50670
50732
|
return glimpseAvailable;
|
|
50671
50733
|
}
|
|
50672
50734
|
function getGlimpseBinaryPath() {
|
|
50673
|
-
if (process.env.GLIMPSE_BINARY &&
|
|
50735
|
+
if (process.env.GLIMPSE_BINARY && existsSync16(process.env.GLIMPSE_BINARY)) {
|
|
50674
50736
|
return process.env.GLIMPSE_BINARY;
|
|
50675
50737
|
}
|
|
50676
50738
|
try {
|
|
50677
|
-
const require6 =
|
|
50739
|
+
const require6 = createRequire4(import.meta.url);
|
|
50678
50740
|
const glimpseuiPath = require6.resolve("glimpseui");
|
|
50679
|
-
const binaryPath =
|
|
50680
|
-
if (
|
|
50741
|
+
const binaryPath = join27(dirname16(glimpseuiPath), "glimpse");
|
|
50742
|
+
if (existsSync16(binaryPath)) return binaryPath;
|
|
50681
50743
|
} catch {
|
|
50682
50744
|
}
|
|
50683
50745
|
try {
|
|
50684
50746
|
const globalRoot = execFileSync2("npm", ["root", "-g"], { encoding: "utf-8" }).trim();
|
|
50685
|
-
const binaryPath =
|
|
50686
|
-
if (
|
|
50747
|
+
const binaryPath = join27(globalRoot, "glimpseui", "src", "glimpse");
|
|
50748
|
+
if (existsSync16(binaryPath)) return binaryPath;
|
|
50687
50749
|
} catch {
|
|
50688
50750
|
}
|
|
50689
50751
|
return null;
|
|
50690
50752
|
}
|
|
50691
50753
|
async function openGlimpseWindow(html, options) {
|
|
50692
|
-
const modulePath = resolvedBinaryPath ?
|
|
50754
|
+
const modulePath = resolvedBinaryPath ? join27(dirname16(resolvedBinaryPath), "glimpse.mjs") : "glimpseui";
|
|
50693
50755
|
const glimpse = await import(modulePath);
|
|
50694
50756
|
let active = true;
|
|
50695
50757
|
const win = glimpse.open(html, {
|
|
@@ -55085,7 +55147,7 @@ function buildCommandDescription(metadata) {
|
|
|
55085
55147
|
}
|
|
55086
55148
|
|
|
55087
55149
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/proxy-modes.ts
|
|
55088
|
-
import { createRequire as
|
|
55150
|
+
import { createRequire as createRequire5 } from "module";
|
|
55089
55151
|
|
|
55090
55152
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/ts-shape.ts
|
|
55091
55153
|
var UNSUPPORTED_KEYWORDS = ["if", "then", "else", "allOf", "not", "patternProperties", "additionalProperties"];
|
|
@@ -55405,7 +55467,7 @@ function rankSuggestions(state, name, limit) {
|
|
|
55405
55467
|
}
|
|
55406
55468
|
|
|
55407
55469
|
// ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/proxy-modes.ts
|
|
55408
|
-
var require4 =
|
|
55470
|
+
var require4 = createRequire5(import.meta.url);
|
|
55409
55471
|
var MAX_REGEX_SEARCH_QUERY_LENGTH = 256;
|
|
55410
55472
|
var INSTRUCTIONS_PREVIEW_LENGTH = 300;
|
|
55411
55473
|
var REGEX_SAFETY_CHECK_PARAMS = {
|
|
@@ -58594,6 +58656,7 @@ var PiManager = class extends CodingAgentManager {
|
|
|
58594
58656
|
session = null;
|
|
58595
58657
|
unsubscribe = null;
|
|
58596
58658
|
activeSessionFile = null;
|
|
58659
|
+
sessionSubagentMcpParentChatId;
|
|
58597
58660
|
historyFilePath;
|
|
58598
58661
|
historyFile;
|
|
58599
58662
|
providerId = "openrouter";
|
|
@@ -58601,12 +58664,12 @@ var PiManager = class extends CodingAgentManager {
|
|
|
58601
58664
|
modelRuntime = null;
|
|
58602
58665
|
constructor(options) {
|
|
58603
58666
|
super(options);
|
|
58604
|
-
this.historyFilePath = options.historyFilePath ??
|
|
58667
|
+
this.historyFilePath = options.historyFilePath ?? join28(PI_HISTORY_DIR, `${Date.now()}.jsonl`);
|
|
58605
58668
|
this.historyFile = new CodexHistoryFile(this.historyFilePath);
|
|
58606
58669
|
this.initializeManager(this.processMessageInternal.bind(this));
|
|
58607
58670
|
}
|
|
58608
58671
|
async initialize() {
|
|
58609
|
-
await mkdir17(
|
|
58672
|
+
await mkdir17(dirname17(this.historyFilePath), { recursive: true });
|
|
58610
58673
|
}
|
|
58611
58674
|
getHistorySink() {
|
|
58612
58675
|
return this.historyFile;
|
|
@@ -58649,6 +58712,12 @@ var PiManager = class extends CodingAgentManager {
|
|
|
58649
58712
|
}
|
|
58650
58713
|
}
|
|
58651
58714
|
async ensureSession(request) {
|
|
58715
|
+
const subagentMcpParentChatId = this.subagentMcpParentChatId();
|
|
58716
|
+
let retainedModel;
|
|
58717
|
+
if (this.session && this.sessionSubagentMcpParentChatId !== subagentMcpParentChatId) {
|
|
58718
|
+
retainedModel = this.session.model?.id;
|
|
58719
|
+
await this.dispose();
|
|
58720
|
+
}
|
|
58652
58721
|
if (this.session) {
|
|
58653
58722
|
const turnModel = request.model ?? this.session.model?.id;
|
|
58654
58723
|
if (this.providerId === "openrouter" && turnModel && !(await getAllowedOpenRouterModels()).includes(turnModel)) {
|
|
@@ -58729,17 +58798,18 @@ var PiManager = class extends CodingAgentManager {
|
|
|
58729
58798
|
registerOpenRouterModels(modelRegistry, credentials.apiKey, allowedModels);
|
|
58730
58799
|
defaultModel = allowedModels[0] ?? DEFAULT_PI_MODEL;
|
|
58731
58800
|
}
|
|
58732
|
-
const modelId = request.model ?? defaultModel;
|
|
58801
|
+
const modelId = request.model ?? retainedModel ?? defaultModel;
|
|
58733
58802
|
const model = allowedModels && !allowedModels.includes(modelId) ? null : modelRegistry.find(this.providerId, modelId);
|
|
58734
58803
|
if (!model) throw new Error(`Pi model is not available through ${this.providerId}: ${modelId}`);
|
|
58735
|
-
const
|
|
58804
|
+
const sessionFile = this.activeSessionFile ?? this.initialSessionId;
|
|
58805
|
+
const sessionManager = sessionFile ? SessionManager.open(sessionFile, PI_HISTORY_DIR, this.workingDirectory) : SessionManager.create(this.workingDirectory, PI_HISTORY_DIR);
|
|
58736
58806
|
const mcpServers = await getManagedPiMcpServers();
|
|
58737
|
-
if (
|
|
58738
|
-
mcpServers[
|
|
58739
|
-
...
|
|
58807
|
+
if (subagentMcpParentChatId) {
|
|
58808
|
+
mcpServers[SUBAGENT_MCP_SERVER_NAME] = {
|
|
58809
|
+
...subagentMcpProcessConfig(subagentMcpParentChatId),
|
|
58740
58810
|
lifecycle: "lazy",
|
|
58741
58811
|
idleTimeout: 1,
|
|
58742
|
-
requestTimeoutMs:
|
|
58812
|
+
requestTimeoutMs: SUBAGENT_MCP_TOOL_TIMEOUT_MS,
|
|
58743
58813
|
directTools: true,
|
|
58744
58814
|
approveTools: false
|
|
58745
58815
|
};
|
|
@@ -58753,13 +58823,13 @@ var PiManager = class extends CodingAgentManager {
|
|
|
58753
58823
|
extensionFactories.push(createMcpAdapter({
|
|
58754
58824
|
config: {
|
|
58755
58825
|
mcpServers,
|
|
58756
|
-
...
|
|
58826
|
+
...subagentMcpParentChatId ? { settings: { scriptMode: false } } : {}
|
|
58757
58827
|
}
|
|
58758
58828
|
}));
|
|
58759
58829
|
}
|
|
58760
58830
|
const resourceLoader = new DefaultResourceLoader({
|
|
58761
58831
|
cwd: this.workingDirectory,
|
|
58762
|
-
agentDir:
|
|
58832
|
+
agentDir: join28(ENGINE_ENV.HOME_DIR, ".pi", "agent"),
|
|
58763
58833
|
extensionFactories,
|
|
58764
58834
|
appendSystemPrompt: [this.buildCombinedInstructions(request.customInstructions) ?? ""]
|
|
58765
58835
|
});
|
|
@@ -58772,6 +58842,7 @@ var PiManager = class extends CodingAgentManager {
|
|
|
58772
58842
|
resourceLoader
|
|
58773
58843
|
});
|
|
58774
58844
|
this.session = result.session;
|
|
58845
|
+
this.sessionSubagentMcpParentChatId = subagentMcpParentChatId;
|
|
58775
58846
|
if (request.thinkingLevel) {
|
|
58776
58847
|
this.session.setThinkingLevel(piThinkingLevel(request.thinkingLevel));
|
|
58777
58848
|
}
|
|
@@ -58816,46 +58887,7 @@ var PiManager = class extends CodingAgentManager {
|
|
|
58816
58887
|
}
|
|
58817
58888
|
};
|
|
58818
58889
|
|
|
58819
|
-
// src/managers/
|
|
58820
|
-
function buildRelayInstructions(workingDirectory) {
|
|
58821
|
-
return `# Relay orchestration
|
|
58822
|
-
|
|
58823
|
-
You are Relay, the coordinating coding agent for this chat. Deliver complete, verified outcomes while keeping the user informed at meaningful milestones.
|
|
58824
|
-
|
|
58825
|
-
## Environment
|
|
58826
|
-
|
|
58827
|
-
- Primary working directory: ${workingDirectory}
|
|
58828
|
-
- Platform: ${process.platform}
|
|
58829
|
-
- Shell: ${process.env.SHELL ?? "unknown"}
|
|
58830
|
-
|
|
58831
|
-
## Working style
|
|
58832
|
-
|
|
58833
|
-
Go straight to the point. Lead with outcomes and decisions, keep updates concise, and avoid filler, restating the request, or narrating obvious actions. Match the user's tone and do not use emojis unless asked. Reference code with file paths and line numbers. Surface blockers when they change the plan. Read and understand relevant code before changing it. If an approach fails, diagnose why before changing tactics.
|
|
58834
|
-
|
|
58835
|
-
## Delegation
|
|
58836
|
-
|
|
58837
|
-
Your primary constraint is context. Work directly when the task is small, tightly coupled to context you already hold, or cheaper to complete than explain. Delegate independent work that would consume substantial context, including broad investigation, multi-file implementation, iterative debugging, test-and-fix loops, and unbiased review or verification. Do not delegate trivial work or work whose full context would cost more to transfer than doing it yourself.
|
|
58838
|
-
|
|
58839
|
-
Use the \`${RELAY_MCP_SERVER_NAME}\` MCP server exclusively for delegation; never use terminal commands or the base harness's native agent-spawning, delegation, or collaboration tools. It exposes ${RELAY_MCP_TOOL_NAMES.map((name) => `\`${name}\``).join(", ")}; your harness may show them with an MCP server prefix. In Pi, call them through the \`mcp\` gateway for the \`${RELAY_MCP_SERVER_NAME}\` server if direct tools are not yet visible. Check \`${RELAY_MCP_TOOLS.getProviders}\` before the first delegation instead of guessing. Spawning and messaging block by default; use \`blocking: false\` only when you intend to continue independently, then inspect or join the child with \`${RELAY_MCP_TOOLS.getAgent}\` or \`${RELAY_MCP_TOOLS.waitAgent}\`.
|
|
58840
|
-
|
|
58841
|
-
Choose how much parent context each child inherits with \`${RELAY_MCP_TOOLS.spawnAgent}.fork_turns\`:
|
|
58842
|
-
|
|
58843
|
-
- \`"all"\` (default): inherit the conversation as an extension of yourself when the task depends on prior decisions and constraints.
|
|
58844
|
-
- \`"none"\`: start with only the task prompt to reduce input tokens or get an independent assessment without your prior reasoning. Include all necessary requirements, paths, constraints, and evidence in the prompt; the child cannot infer omitted context.
|
|
58845
|
-
- A positive integer string such as \`"3"\`: inherit only the latest N user-led turns when recent context is enough. A turn includes a user message and the agent activity that follows it, including the current unfinished turn.
|
|
58846
|
-
|
|
58847
|
-
Give every child a concrete task, clear scope, and definition of done, even when it inherits the conversation. The child should use inherited history as background and focus on its assigned task.
|
|
58848
|
-
|
|
58849
|
-
Run truly independent child agents concurrently. Because child agents share the workspace, run modifying work sequentially unless file ownership cannot overlap. Keep dependent work sequential when one result defines another task's contract, such as schema before queries, API before its client, or implementation before its focused verification. Review child results, follow up when they are incomplete, and verify the integrated outcome yourself. Do not delete child chats unless the user asks.
|
|
58850
|
-
|
|
58851
|
-
## Incremental progress
|
|
58852
|
-
|
|
58853
|
-
For complex work spanning multiple components or many files, do not attempt everything in one pass. Break it into discrete, meaningful stages. Complete, review, and verify each stage before continuing so mistakes are caught early and later work is based on a stable result. When the user or workflow calls for repository commits, create clean incremental commits after coherent stages; each checkpoint should be safe for another agent or human to continue from.
|
|
58854
|
-
|
|
58855
|
-
Match verification depth to the change: use focused checks for small changes and broader integration or end-to-end checks for cross-component work. A child agent's claim is evidence to review, not a substitute for your own final verification.`;
|
|
58856
|
-
}
|
|
58857
|
-
|
|
58858
|
-
// src/managers/relay-tools.ts
|
|
58890
|
+
// src/managers/subagent-tools.ts
|
|
58859
58891
|
function extractFinalResponse(history, provider) {
|
|
58860
58892
|
const message = parseAgentEvents(history.events ?? [], provider).findLast((candidate) => candidate.type === "agent");
|
|
58861
58893
|
return message?.type === "agent" && message.content ? message.content : null;
|
|
@@ -58881,8 +58913,8 @@ import {
|
|
|
58881
58913
|
rename as rename3,
|
|
58882
58914
|
unlink as unlink3
|
|
58883
58915
|
} from "fs/promises";
|
|
58884
|
-
import { existsSync as
|
|
58885
|
-
import { join as
|
|
58916
|
+
import { existsSync as existsSync17, readFileSync as readFileSync6, readdirSync as readdirSync2 } from "fs";
|
|
58917
|
+
import { join as join29 } from "path";
|
|
58886
58918
|
var MAX_FAILED_RECORDS = 500;
|
|
58887
58919
|
var FLUSH_DEBOUNCE_MS = 15e3;
|
|
58888
58920
|
var MAX_UPLOADED_SEGMENTS = 50;
|
|
@@ -58894,7 +58926,7 @@ var AnalyticsRecordBuffer = class {
|
|
|
58894
58926
|
options.storageName,
|
|
58895
58927
|
...options.legacyStorageNames ?? []
|
|
58896
58928
|
];
|
|
58897
|
-
this.liveFile =
|
|
58929
|
+
this.liveFile = join29(ENGINE_DIR2, `${options.storageName}.jsonl`);
|
|
58898
58930
|
this.segmentFilePatterns = this.storageNames.map(
|
|
58899
58931
|
(storageName) => new RegExp(`^${storageName}\\.(\\d+)\\.jsonl$`)
|
|
58900
58932
|
);
|
|
@@ -58929,10 +58961,10 @@ var AnalyticsRecordBuffer = class {
|
|
|
58929
58961
|
void pending.finally(() => this.pendingAppends.delete(pending));
|
|
58930
58962
|
}
|
|
58931
58963
|
readStoredRecords() {
|
|
58932
|
-
if (!
|
|
58964
|
+
if (!existsSync17(ENGINE_DIR2)) return [];
|
|
58933
58965
|
return readdirSync2(ENGINE_DIR2, { withFileTypes: true }).filter((entry) => entry.isFile() && this.storageNames.some(
|
|
58934
58966
|
(storageName) => entry.name === `${storageName}.jsonl` || entry.name.startsWith(`${storageName}.`) && (entry.name.endsWith(".jsonl") || entry.name.endsWith(`.jsonl${UPLOADED_SUFFIX}`))
|
|
58935
|
-
)).map(({ name }) => name).sort().flatMap((name) => this.parseRecords(readFileSync6(
|
|
58967
|
+
)).map(({ name }) => name).sort().flatMap((name) => this.parseRecords(readFileSync6(join29(ENGINE_DIR2, name), "utf-8"))).map((record3) => {
|
|
58936
58968
|
const recordId = this.options.getRecordId?.(record3);
|
|
58937
58969
|
if (recordId) this.recordIds.add(recordId);
|
|
58938
58970
|
return record3;
|
|
@@ -58967,8 +58999,8 @@ var AnalyticsRecordBuffer = class {
|
|
|
58967
58999
|
}
|
|
58968
59000
|
for (const storageName of this.storageNames) {
|
|
58969
59001
|
await rename3(
|
|
58970
|
-
|
|
58971
|
-
|
|
59002
|
+
join29(ENGINE_DIR2, `${storageName}.jsonl`),
|
|
59003
|
+
join29(ENGINE_DIR2, `${storageName}.${Date.now()}.jsonl`)
|
|
58972
59004
|
).catch(() => {
|
|
58973
59005
|
});
|
|
58974
59006
|
}
|
|
@@ -58978,7 +59010,7 @@ var AnalyticsRecordBuffer = class {
|
|
|
58978
59010
|
for (const entry of entries) {
|
|
58979
59011
|
if (!this.segmentFilePatterns.some((pattern) => pattern.test(entry))) continue;
|
|
58980
59012
|
try {
|
|
58981
|
-
await this.uploadSegment(
|
|
59013
|
+
await this.uploadSegment(join29(ENGINE_DIR2, entry));
|
|
58982
59014
|
flushed++;
|
|
58983
59015
|
} catch (error) {
|
|
58984
59016
|
failed++;
|
|
@@ -59007,7 +59039,7 @@ var AnalyticsRecordBuffer = class {
|
|
|
59007
59039
|
(storageName) => entry.startsWith(`${storageName}.`)
|
|
59008
59040
|
) && entry.endsWith(UPLOADED_SUFFIX)).sort();
|
|
59009
59041
|
for (const entry of uploaded.slice(0, -MAX_UPLOADED_SEGMENTS)) {
|
|
59010
|
-
await unlink3(
|
|
59042
|
+
await unlink3(join29(ENGINE_DIR2, entry)).catch(() => {
|
|
59011
59043
|
});
|
|
59012
59044
|
}
|
|
59013
59045
|
}
|
|
@@ -59051,10 +59083,9 @@ function skillCallsFromCommand(message) {
|
|
|
59051
59083
|
occurredAt: message.timestamp
|
|
59052
59084
|
}));
|
|
59053
59085
|
}
|
|
59054
|
-
function extractSkillMcpCalls(messages
|
|
59086
|
+
function extractSkillMcpCalls(messages) {
|
|
59055
59087
|
return messages.flatMap((message) => {
|
|
59056
59088
|
if (message.type === "skill") {
|
|
59057
|
-
if (provider === "relay") return [];
|
|
59058
59089
|
return [{ kind: "skill", id: message.id, skillName: message.skillName, occurredAt: message.timestamp }];
|
|
59059
59090
|
}
|
|
59060
59091
|
if (message.type === "command") {
|
|
@@ -59197,7 +59228,7 @@ var AgentChatActivityTrackerService = class {
|
|
|
59197
59228
|
noteSkillMcpCalls(chatId, messages) {
|
|
59198
59229
|
const turn = this.turnActivityTracker.getActiveTurn(chatId);
|
|
59199
59230
|
if (!turn) return;
|
|
59200
|
-
for (const call of extractSkillMcpCalls(messages
|
|
59231
|
+
for (const call of extractSkillMcpCalls(messages)) {
|
|
59201
59232
|
if (turn.seenCallIds.has(call.id)) continue;
|
|
59202
59233
|
turn.seenCallIds.add(call.id);
|
|
59203
59234
|
const activityRecord = {
|
|
@@ -59802,7 +59833,7 @@ var keepAliveService = new KeepAliveService();
|
|
|
59802
59833
|
// src/services/canvas-service.ts
|
|
59803
59834
|
import { readdir as readdir7, readFile as readFile17, stat as stat4 } from "fs/promises";
|
|
59804
59835
|
import { homedir as homedir13 } from "os";
|
|
59805
|
-
import { join as
|
|
59836
|
+
import { join as join30 } from "path";
|
|
59806
59837
|
|
|
59807
59838
|
// src/utils/contained-file.ts
|
|
59808
59839
|
import { realpath, stat as stat3 } from "fs/promises";
|
|
@@ -59844,15 +59875,15 @@ async function writeRevisionedTextFile(filePath, content, expectedRevision) {
|
|
|
59844
59875
|
|
|
59845
59876
|
// src/services/canvas-service.ts
|
|
59846
59877
|
var GLOBAL_CANVAS_DIRECTORIES = [
|
|
59847
|
-
|
|
59848
|
-
|
|
59849
|
-
|
|
59878
|
+
join30(homedir13(), ".claude", "plans"),
|
|
59879
|
+
join30(process.env.XDG_DATA_HOME ?? join30(homedir13(), ".local", "share"), "opencode", "plans"),
|
|
59880
|
+
join30(homedir13(), ".replicas", "canvas")
|
|
59850
59881
|
];
|
|
59851
59882
|
async function canvasDirectories() {
|
|
59852
59883
|
const repositories = await gitService.listRepositories().catch(() => []);
|
|
59853
59884
|
return [
|
|
59854
59885
|
...GLOBAL_CANVAS_DIRECTORIES,
|
|
59855
|
-
...repositories.map((repository) =>
|
|
59886
|
+
...repositories.map((repository) => join30(repository.path, ".opencode", "plans"))
|
|
59856
59887
|
];
|
|
59857
59888
|
}
|
|
59858
59889
|
var CanvasService = class {
|
|
@@ -59877,7 +59908,7 @@ var CanvasService = class {
|
|
|
59877
59908
|
for (const entry of entries) {
|
|
59878
59909
|
if (entry.name.startsWith(".")) continue;
|
|
59879
59910
|
const filename = current.relativePath ? `${current.relativePath}/${entry.name}` : entry.name;
|
|
59880
|
-
const filePath =
|
|
59911
|
+
const filePath = join30(current.directory, entry.name);
|
|
59881
59912
|
if (entry.isDirectory()) {
|
|
59882
59913
|
pending.push({ directory: filePath, relativePath: filename });
|
|
59883
59914
|
continue;
|
|
@@ -59902,7 +59933,7 @@ var CanvasService = class {
|
|
|
59902
59933
|
if (!safe) return null;
|
|
59903
59934
|
const { kind, mimeType } = classifyCanvasFilename(safe);
|
|
59904
59935
|
for (const directory of await this.directories()) {
|
|
59905
|
-
const filePath =
|
|
59936
|
+
const filePath = join30(directory, safe);
|
|
59906
59937
|
let sizeBytes = 0;
|
|
59907
59938
|
let updatedAt = "";
|
|
59908
59939
|
try {
|
|
@@ -60086,13 +60117,13 @@ async function reconcileCanvasItems(filenames) {
|
|
|
60086
60117
|
import { createReadStream as createReadStream3 } from "fs";
|
|
60087
60118
|
import { createHash as createHash7 } from "crypto";
|
|
60088
60119
|
import { readFile as readFile18, readdir as readdir8, stat as stat5 } from "fs/promises";
|
|
60089
|
-
import { basename as basename3, join as
|
|
60120
|
+
import { basename as basename3, join as join32 } from "path";
|
|
60090
60121
|
|
|
60091
60122
|
// src/services/chat/chat-senders.ts
|
|
60092
|
-
import { join as
|
|
60093
|
-
var CHAT_SENDERS_DIR =
|
|
60123
|
+
import { join as join31 } from "path";
|
|
60124
|
+
var CHAT_SENDERS_DIR = join31(ENGINE_DIR2, "chat-senders");
|
|
60094
60125
|
function chatMessageSendersFilePath(chatId) {
|
|
60095
|
-
return
|
|
60126
|
+
return join31(CHAT_SENDERS_DIR, `${chatId}.jsonl`);
|
|
60096
60127
|
}
|
|
60097
60128
|
function parseChatMessageSendersJsonl(content) {
|
|
60098
60129
|
return content.split("\n").flatMap((line) => {
|
|
@@ -60143,12 +60174,10 @@ async function putPresignedFile(urlValue, filePath, size, contentType) {
|
|
|
60143
60174
|
var HISTORY_DIRS = [...new Set(Object.values(HISTORY_DIR_BY_PROVIDER))];
|
|
60144
60175
|
var ALWAYS_UPLOAD_HISTORY_DIRS = /* @__PURE__ */ new Set([
|
|
60145
60176
|
HISTORY_DIR_BY_PROVIDER.claude,
|
|
60146
|
-
HISTORY_DIR_BY_PROVIDER.codex
|
|
60147
|
-
HISTORY_DIR_BY_PROVIDER.relay
|
|
60177
|
+
HISTORY_DIR_BY_PROVIDER.codex
|
|
60148
60178
|
]);
|
|
60149
60179
|
function shouldFlushChatTranscript(historyDir, chat, chatsById) {
|
|
60150
|
-
|
|
60151
|
-
return ALWAYS_UPLOAD_HISTORY_DIRS.has(historyDir) || parent?.provider === "relay";
|
|
60180
|
+
return ALWAYS_UPLOAD_HISTORY_DIRS.has(historyDir) || Boolean(chat?.parentChatId && chatsById.has(chat.parentChatId));
|
|
60152
60181
|
}
|
|
60153
60182
|
async function flushAllChatTranscripts(chatsById = /* @__PURE__ */ new Map(), capture) {
|
|
60154
60183
|
let flushed = 0;
|
|
@@ -60168,7 +60197,7 @@ async function flushAllChatTranscripts(chatsById = /* @__PURE__ */ new Map(), ca
|
|
|
60168
60197
|
const chat = chatsById.get(chatId);
|
|
60169
60198
|
if (!shouldFlushChatTranscript(dir, chat, chatsById)) continue;
|
|
60170
60199
|
tasks.push(
|
|
60171
|
-
uploadChatTranscript(chatId,
|
|
60200
|
+
uploadChatTranscript(chatId, join32(dir, entry), chat, capture).then((artifact) => {
|
|
60172
60201
|
flushed++;
|
|
60173
60202
|
if (artifact && capture) revisions.push(artifact);
|
|
60174
60203
|
}).catch((err) => {
|
|
@@ -60197,8 +60226,7 @@ async function uploadChatTranscriptNow(chatId, filePath, chat, capture) {
|
|
|
60197
60226
|
if (size === 0) return null;
|
|
60198
60227
|
const metadata = chat ? {
|
|
60199
60228
|
provider: chat.provider,
|
|
60200
|
-
|
|
60201
|
-
credential: ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS[getChatExecutionProvider(chat)],
|
|
60229
|
+
credential: ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS[chat.provider],
|
|
60202
60230
|
title: chat.title,
|
|
60203
60231
|
displayName: chat.displayName,
|
|
60204
60232
|
createdAt: chat.createdAt,
|
|
@@ -60256,7 +60284,7 @@ async function uploadChatTranscriptNow(chatId, filePath, chat, capture) {
|
|
|
60256
60284
|
// src/services/upload-engine-logs.ts
|
|
60257
60285
|
import { createReadStream as createReadStream4 } from "fs";
|
|
60258
60286
|
import { readdir as readdir9, stat as stat6 } from "fs/promises";
|
|
60259
|
-
import { join as
|
|
60287
|
+
import { join as join33 } from "path";
|
|
60260
60288
|
var MAX_ENGINE_LOG_FLUSH_SESSIONS = 10;
|
|
60261
60289
|
var MAX_ENGINE_LOG_FLUSH_BYTES = 5 * 1024 * 1024;
|
|
60262
60290
|
var ENGINE_LOG_FLUSH_TIMEOUT_MS = 2e4;
|
|
@@ -60285,7 +60313,7 @@ async function flushAllEngineLogs() {
|
|
|
60285
60313
|
const candidates = (await Promise.all(filenames.slice(0, MAX_ENGINE_LOG_FLUSH_SESSIONS).map(async (filename) => {
|
|
60286
60314
|
try {
|
|
60287
60315
|
const sessionId = filename.slice(0, -".log".length);
|
|
60288
|
-
const filePath =
|
|
60316
|
+
const filePath = join33(LOG_DIR, filename);
|
|
60289
60317
|
const fileStat = await runBeforeDeadline(() => stat6(filePath), deadline);
|
|
60290
60318
|
if (!fileStat.isFile()) {
|
|
60291
60319
|
skipped++;
|
|
@@ -60383,7 +60411,7 @@ async function uploadEngineLog(input, timeoutMs) {
|
|
|
60383
60411
|
// src/services/chat/fork-handoff.ts
|
|
60384
60412
|
import { createHash as createHash8 } from "crypto";
|
|
60385
60413
|
import { mkdir as mkdir19, open as open3, writeFile as writeFile10 } from "fs/promises";
|
|
60386
|
-
import { join as
|
|
60414
|
+
import { join as join34 } from "path";
|
|
60387
60415
|
var EXCERPT_MAX_CHARS = 24e3;
|
|
60388
60416
|
var MAX_SANITIZED_SOURCE_BYTES = 32 * 1024 * 1024;
|
|
60389
60417
|
function unansweredRequest(blocks) {
|
|
@@ -60431,17 +60459,17 @@ function unseenTurnsExcerpt(seenHashes, blocks) {
|
|
|
60431
60459
|
${excerpt}` : excerpt;
|
|
60432
60460
|
}
|
|
60433
60461
|
async function buildForkHandoff(input) {
|
|
60434
|
-
const rawHistoryPath =
|
|
60462
|
+
const rawHistoryPath = join34(HISTORY_DIR_BY_PROVIDER[input.sourceProvider], `${input.sourceChatId}.jsonl`);
|
|
60435
60463
|
const { content, truncated: sourceTruncated } = await readHistoryTail(rawHistoryPath, MAX_SANITIZED_SOURCE_BYTES);
|
|
60436
|
-
let blocks = canonicalizeChatTranscriptBlocks(content, input.
|
|
60464
|
+
let blocks = canonicalizeChatTranscriptBlocks(content, input.sourceProvider, input.senders);
|
|
60437
60465
|
if (input.turnLimit !== void 0) {
|
|
60438
60466
|
let turns = 0;
|
|
60439
60467
|
const start = blocks.findLastIndex((block) => block.startsWith("## User") && ++turns === input.turnLimit);
|
|
60440
60468
|
blocks = blocks.slice(Math.max(0, start));
|
|
60441
60469
|
}
|
|
60442
|
-
const forkDir =
|
|
60470
|
+
const forkDir = join34(FORKS_DIR, input.targetChatId);
|
|
60443
60471
|
await mkdir19(forkDir, { recursive: true });
|
|
60444
|
-
const transcriptPath =
|
|
60472
|
+
const transcriptPath = join34(forkDir, "source-transcript.md");
|
|
60445
60473
|
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.` : ""}_
|
|
60446
60474
|
|
|
60447
60475
|
` : "";
|
|
@@ -60515,11 +60543,7 @@ function terminalErrorsFromEvent(event, provider) {
|
|
|
60515
60543
|
var LAST_MESSAGE_PREVIEW_MAX = 200;
|
|
60516
60544
|
var MAX_ACCEPTED_SEND_RESPONSES = 50;
|
|
60517
60545
|
var MAX_REMOVED_MESSAGE_IDS = 6e3;
|
|
60518
|
-
var
|
|
60519
|
-
async function resolveRelayBaseProvider(provider, requested) {
|
|
60520
|
-
if (provider !== "relay") return null;
|
|
60521
|
-
return requested ?? (await monolithService.getRelayConfig())?.baseProvider ?? (!ENGINE_ENV.REPLICAS_WORKSPACE_ID ? DEFAULT_RELAY_BASE_PROVIDER : null);
|
|
60522
|
-
}
|
|
60546
|
+
var SUBAGENT_POLL_INTERVAL_MS = 2e3;
|
|
60523
60547
|
function createForkInfo(source, trigger, startedAt, reason) {
|
|
60524
60548
|
return {
|
|
60525
60549
|
source: { chatId: source.id, provider: source.provider, title: source.title },
|
|
@@ -60546,14 +60570,13 @@ function isPersistedChat(value) {
|
|
|
60546
60570
|
return false;
|
|
60547
60571
|
}
|
|
60548
60572
|
const candidate = value;
|
|
60549
|
-
return typeof candidate.id === "string" && typeof candidate.provider === "string" && isValidAgentProvider(candidate.provider) &&
|
|
60573
|
+
return typeof candidate.id === "string" && typeof candidate.provider === "string" && isValidAgentProvider(candidate.provider) && typeof candidate.title === "string" && (candidate.displayName === void 0 || typeof candidate.displayName === "string") && typeof candidate.createdAt === "string" && typeof candidate.updatedAt === "string" && (candidate.providerSessionId === null || typeof candidate.providerSessionId === "string") && (candidate.parentChatId === void 0 || candidate.parentChatId === null || typeof candidate.parentChatId === "string") && (candidate.deletedAt === void 0 || candidate.deletedAt === null || typeof candidate.deletedAt === "string");
|
|
60550
60574
|
}
|
|
60551
60575
|
function normalizePersistedChat(chat) {
|
|
60552
60576
|
return {
|
|
60553
60577
|
id: chat.id,
|
|
60554
60578
|
provider: chat.provider,
|
|
60555
60579
|
...typeof chat.model === "string" && chat.model ? { model: chat.model } : {},
|
|
60556
|
-
...chat.provider === "relay" ? { relayBaseProvider: getChatExecutionProvider(chat) } : {},
|
|
60557
60580
|
title: chat.title,
|
|
60558
60581
|
...chat.displayName ? { displayName: chat.displayName } : {},
|
|
60559
60582
|
createdAt: chat.createdAt,
|
|
@@ -60601,7 +60624,6 @@ var ChatService = class {
|
|
|
60601
60624
|
async initialize() {
|
|
60602
60625
|
await mkdir20(ENGINE_DIR2, { recursive: true });
|
|
60603
60626
|
await mkdir20(CLAUDE_HISTORY_DIR, { recursive: true });
|
|
60604
|
-
await mkdir20(RELAY_HISTORY_DIR, { recursive: true });
|
|
60605
60627
|
await mkdir20(CODEX_HISTORY_DIR, { recursive: true });
|
|
60606
60628
|
await mkdir20(CURSOR_HISTORY_DIR, { recursive: true });
|
|
60607
60629
|
await mkdir20(OPENCODE_HISTORY_DIR, { recursive: true });
|
|
@@ -60616,11 +60638,8 @@ var ChatService = class {
|
|
|
60616
60638
|
(c) => c.persisted.provider === provider && isDefaultChat(c.persisted)
|
|
60617
60639
|
);
|
|
60618
60640
|
if (!hasDefault) {
|
|
60619
|
-
const relayBaseProvider = await resolveRelayBaseProvider(provider);
|
|
60620
|
-
if (provider === "relay" && !relayBaseProvider) continue;
|
|
60621
60641
|
await this.createChat({
|
|
60622
60642
|
provider,
|
|
60623
|
-
...relayBaseProvider ? { relayBaseProvider } : {},
|
|
60624
60643
|
title: DEFAULT_CHAT_TITLES[provider]
|
|
60625
60644
|
});
|
|
60626
60645
|
}
|
|
@@ -60630,7 +60649,7 @@ var ChatService = class {
|
|
|
60630
60649
|
return Array.from(this.chats.values()).filter((chat) => !chat.persisted.deletedAt && (includeChildren || chat.persisted.parentChatId === null)).map((chat) => this.toSummary(chat)).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
|
60631
60650
|
}
|
|
60632
60651
|
hasActiveAgentWork(provider) {
|
|
60633
|
-
return [...this.chats.values()].some((chat) =>
|
|
60652
|
+
return [...this.chats.values()].some((chat) => chat.persisted.provider === provider && (chat.provider.isProcessing() || chat.acceptingMessages > 0 || chat.pendingMessageIds.length > 0));
|
|
60634
60653
|
}
|
|
60635
60654
|
listDeletedChats(includeChildren = false) {
|
|
60636
60655
|
return Array.from(this.chats.values()).filter((chat) => chat.persisted.deletedAt && (includeChildren || chat.persisted.parentChatId === null)).map((chat) => this.toSummary(chat)).sort((a, b) => (b.deletedAt ?? "").localeCompare(a.deletedAt ?? ""));
|
|
@@ -60645,7 +60664,6 @@ var ChatService = class {
|
|
|
60645
60664
|
async listSlashCommands(chatId) {
|
|
60646
60665
|
const chat = this.requireChat(chatId);
|
|
60647
60666
|
const provider = chat.persisted.provider;
|
|
60648
|
-
const executionProvider = getChatExecutionProvider(chat.persisted);
|
|
60649
60667
|
const discovered = await chat.provider.listSlashCommands?.() ?? [];
|
|
60650
60668
|
const providerCommands = discovered.map((command) => ({
|
|
60651
60669
|
...command,
|
|
@@ -60653,7 +60671,7 @@ var ChatService = class {
|
|
|
60653
60671
|
}));
|
|
60654
60672
|
return {
|
|
60655
60673
|
commands: mergeSlashCommands(
|
|
60656
|
-
getSlashCommandsForProvider(
|
|
60674
|
+
getSlashCommandsForProvider(provider),
|
|
60657
60675
|
providerCommands
|
|
60658
60676
|
)
|
|
60659
60677
|
};
|
|
@@ -60661,23 +60679,16 @@ var ChatService = class {
|
|
|
60661
60679
|
async createChat(request) {
|
|
60662
60680
|
const now = request.createdAt ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
60663
60681
|
const title = request.title?.trim() || `${request.provider} chat`;
|
|
60664
|
-
const relayBaseProvider = await resolveRelayBaseProvider(request.provider, request.relayBaseProvider);
|
|
60665
|
-
if (request.provider === "relay" && !relayBaseProvider) {
|
|
60666
|
-
throw new Error("Unable to resolve the configured Relay base provider");
|
|
60667
|
-
}
|
|
60668
60682
|
if (request.id) {
|
|
60669
60683
|
const existing = this.chats.get(request.id);
|
|
60670
60684
|
if (existing && !existing.persisted.deletedAt) {
|
|
60671
60685
|
if (request.forkSourceChatId && existing.persisted.fork) return this.toSummary(existing);
|
|
60672
|
-
if (existing.persisted.provider !== request.provider
|
|
60686
|
+
if (existing.persisted.provider !== request.provider) {
|
|
60673
60687
|
throw new Error(`Chat ${request.id} already exists with a different provider`);
|
|
60674
60688
|
}
|
|
60675
60689
|
return this.toSummary(existing);
|
|
60676
60690
|
}
|
|
60677
60691
|
}
|
|
60678
|
-
if (relayBaseProvider && !isValidRelayBaseProvider(relayBaseProvider)) {
|
|
60679
|
-
throw new Error(`${relayBaseProvider} cannot be used as a Relay base provider`);
|
|
60680
|
-
}
|
|
60681
60692
|
const existingDefault = isDefaultChat({ provider: request.provider, title }) ? Array.from(this.chats.values()).find((chat) => !chat.persisted.deletedAt && chat.persisted.provider === request.provider && isDefaultChat(chat.persisted)) : void 0;
|
|
60682
60693
|
if (existingDefault) {
|
|
60683
60694
|
if (!request.id || existingDefault.acceptingMessages > 0 || hasChatStarted(this.toSummary(existingDefault))) {
|
|
@@ -60693,7 +60704,6 @@ var ChatService = class {
|
|
|
60693
60704
|
const persisted = {
|
|
60694
60705
|
id: request.id ?? randomUUID11(),
|
|
60695
60706
|
provider: request.provider,
|
|
60696
|
-
...relayBaseProvider ? { relayBaseProvider } : {},
|
|
60697
60707
|
title,
|
|
60698
60708
|
createdAt: now,
|
|
60699
60709
|
updatedAt: now,
|
|
@@ -60702,7 +60712,7 @@ var ChatService = class {
|
|
|
60702
60712
|
fork: request.fork ?? null,
|
|
60703
60713
|
...source ? {
|
|
60704
60714
|
displayName: request.title?.trim() || void 0,
|
|
60705
|
-
model:
|
|
60715
|
+
model: source.persisted.provider === request.provider ? source.persisted.model : void 0,
|
|
60706
60716
|
pendingForkHandoff: true,
|
|
60707
60717
|
fork: createForkInfo(source.persisted, request.sideChat ? "side" : "manual", now)
|
|
60708
60718
|
} : {}
|
|
@@ -60719,18 +60729,16 @@ var ChatService = class {
|
|
|
60719
60729
|
});
|
|
60720
60730
|
return this.toSummary(runtime);
|
|
60721
60731
|
}
|
|
60722
|
-
async
|
|
60723
|
-
const
|
|
60724
|
-
if (!
|
|
60725
|
-
throw new Error(
|
|
60732
|
+
async spawnSubagent(parentChatId, request) {
|
|
60733
|
+
const { providers } = await this.getSubagentProviders(parentChatId);
|
|
60734
|
+
if (!providers.includes(request.provider)) {
|
|
60735
|
+
throw new Error(`${request.provider} is not allowed as a subagent provider`);
|
|
60726
60736
|
}
|
|
60727
|
-
|
|
60728
|
-
|
|
60729
|
-
throw new Error(`Relay cannot use ${executionProvider} because its credentials are unavailable`);
|
|
60737
|
+
if (!isAgentAvailable(request.provider)) {
|
|
60738
|
+
throw new Error(`Cannot spawn a ${request.provider} subagent because its credentials are unavailable`);
|
|
60730
60739
|
}
|
|
60731
60740
|
const chat = await this.createChat({
|
|
60732
60741
|
provider: request.provider,
|
|
60733
|
-
...request.provider === "relay" ? { relayBaseProvider: relayConfig.baseProvider } : {},
|
|
60734
60742
|
title: request.title?.trim() || `Subagent (${request.provider})`,
|
|
60735
60743
|
parentChatId
|
|
60736
60744
|
});
|
|
@@ -60756,57 +60764,60 @@ var ChatService = class {
|
|
|
60756
60764
|
});
|
|
60757
60765
|
throw error;
|
|
60758
60766
|
}
|
|
60759
|
-
return this.
|
|
60767
|
+
return this.getSubagent(parentChatId, chat.id);
|
|
60760
60768
|
}
|
|
60761
|
-
async
|
|
60762
|
-
|
|
60763
|
-
|
|
60764
|
-
|
|
60765
|
-
|
|
60766
|
-
return relayConfig;
|
|
60769
|
+
async getSubagentProviders(parentChatId) {
|
|
60770
|
+
this.requireSubagentParent(parentChatId);
|
|
60771
|
+
const config = await monolithService.getSubagentMcpConfig();
|
|
60772
|
+
if (!config) throw new Error("Unable to verify subagent settings");
|
|
60773
|
+
return { providers: config.providers };
|
|
60767
60774
|
}
|
|
60768
|
-
async
|
|
60769
|
-
this.
|
|
60775
|
+
async messageSubagent(parentChatId, chatId, request) {
|
|
60776
|
+
this.requireSubagent(parentChatId, chatId);
|
|
60770
60777
|
await this.sendMessage(chatId, {
|
|
60771
60778
|
message: request.message,
|
|
60772
60779
|
...request.model ? { model: request.model } : {},
|
|
60773
60780
|
...request.thinkingLevel ? { thinkingLevel: request.thinkingLevel } : {}
|
|
60774
60781
|
});
|
|
60775
|
-
return this.
|
|
60782
|
+
return this.getSubagent(parentChatId, chatId);
|
|
60776
60783
|
}
|
|
60777
|
-
async
|
|
60778
|
-
const chat = this.
|
|
60784
|
+
async getSubagent(parentChatId, chatId) {
|
|
60785
|
+
const chat = this.requireSubagent(parentChatId, chatId);
|
|
60779
60786
|
if (hasActiveChatTurn(chat)) return { chatId, status: "working" };
|
|
60780
60787
|
const history = await chat.provider.getHistory();
|
|
60781
60788
|
return {
|
|
60782
60789
|
chatId,
|
|
60783
60790
|
status: "completed",
|
|
60784
|
-
response: extractFinalResponse(history,
|
|
60791
|
+
response: extractFinalResponse(history, chat.persisted.provider) ?? "[No response from subagent]"
|
|
60785
60792
|
};
|
|
60786
60793
|
}
|
|
60787
|
-
async
|
|
60788
|
-
this.
|
|
60794
|
+
async deleteSubagent(parentChatId, chatId) {
|
|
60795
|
+
this.requireSubagent(parentChatId, chatId);
|
|
60789
60796
|
await this.deleteChat(chatId);
|
|
60790
60797
|
}
|
|
60791
|
-
|
|
60798
|
+
requireSubagentParent(parentChatId) {
|
|
60792
60799
|
const parent = this.requireChat(parentChatId);
|
|
60793
|
-
if (parent.persisted.
|
|
60800
|
+
if (parent.persisted.parentChatId !== null) throw new Error("Subagents cannot spawn their own subagents");
|
|
60801
|
+
return parent;
|
|
60802
|
+
}
|
|
60803
|
+
requireSubagent(parentChatId, chatId) {
|
|
60804
|
+
this.requireSubagentParent(parentChatId);
|
|
60794
60805
|
const child = this.requireChat(chatId);
|
|
60795
|
-
if (child.persisted.parentChatId !== parentChatId) throw new Error("Chat is not a
|
|
60806
|
+
if (child.persisted.parentChatId !== parentChatId) throw new Error("Chat is not a subagent of this chat");
|
|
60796
60807
|
return child;
|
|
60797
60808
|
}
|
|
60798
|
-
async
|
|
60809
|
+
async waitForSubagent(parentChatId, chatId, timeoutMinutes, signal) {
|
|
60799
60810
|
const timeoutMs = timeoutMinutes ? timeoutMinutes * 6e4 : null;
|
|
60800
60811
|
const startedAt = Date.now();
|
|
60801
60812
|
while (true) {
|
|
60802
|
-
if (signal?.aborted) throw new Error("
|
|
60803
|
-
const result = await this.
|
|
60813
|
+
if (signal?.aborted) throw new Error("Subagent wait was cancelled");
|
|
60814
|
+
const result = await this.getSubagent(parentChatId, chatId);
|
|
60804
60815
|
if (result.status === "completed") return result;
|
|
60805
60816
|
const remainingMs = timeoutMs === null ? null : timeoutMs - (Date.now() - startedAt);
|
|
60806
60817
|
if (remainingMs !== null && remainingMs <= 0) return { ...result, timedOut: true };
|
|
60807
60818
|
await new Promise((resolve7) => setTimeout(
|
|
60808
60819
|
resolve7,
|
|
60809
|
-
remainingMs === null ?
|
|
60820
|
+
remainingMs === null ? SUBAGENT_POLL_INTERVAL_MS : Math.min(SUBAGENT_POLL_INTERVAL_MS, remainingMs)
|
|
60810
60821
|
));
|
|
60811
60822
|
}
|
|
60812
60823
|
}
|
|
@@ -60840,7 +60851,7 @@ var ChatService = class {
|
|
|
60840
60851
|
})
|
|
60841
60852
|
};
|
|
60842
60853
|
}
|
|
60843
|
-
const savedModel = chat.persisted.model ?? (!request.model ? extractLatestContextUsage((await chat.provider.getHistory()).events,
|
|
60854
|
+
const savedModel = chat.persisted.model ?? (!request.model ? extractLatestContextUsage((await chat.provider.getHistory()).events, chat.persisted.provider)?.model : void 0);
|
|
60844
60855
|
request = { ...request, model: request.model ?? savedModel ?? void 0 };
|
|
60845
60856
|
return await chat.provider.enqueueMessage(
|
|
60846
60857
|
request,
|
|
@@ -61224,14 +61235,14 @@ var ChatService = class {
|
|
|
61224
61235
|
return descendants;
|
|
61225
61236
|
}
|
|
61226
61237
|
async deleteHistoryFile(persisted) {
|
|
61227
|
-
const historyPath =
|
|
61238
|
+
const historyPath = join35(HISTORY_DIR_BY_PROVIDER[persisted.provider], `${persisted.id}.jsonl`);
|
|
61228
61239
|
await Promise.all([
|
|
61229
61240
|
historyPath,
|
|
61230
61241
|
`${historyPath}.pages.jsonl`,
|
|
61231
61242
|
`${historyPath}.pages.index.json`
|
|
61232
61243
|
].map((path7) => rm4(path7, { force: true })));
|
|
61233
61244
|
await rm4(chatMessageSendersFilePath(persisted.id), { force: true });
|
|
61234
|
-
await rm4(
|
|
61245
|
+
await rm4(join35(FORKS_DIR, persisted.id), { recursive: true, force: true });
|
|
61235
61246
|
}
|
|
61236
61247
|
/** Resolves once the target chat exists; the handoff and its first turn run in the background. */
|
|
61237
61248
|
async forkChat(sourceChatId, request, trigger = "manual", reason) {
|
|
@@ -61243,15 +61254,12 @@ var ChatService = class {
|
|
|
61243
61254
|
}
|
|
61244
61255
|
async createForkTarget(sourceChatId, request, trigger, reason) {
|
|
61245
61256
|
const source = this.requireChat(sourceChatId);
|
|
61246
|
-
|
|
61247
|
-
const executionProvider = request.provider === "relay" ? relayBaseProvider : request.provider;
|
|
61248
|
-
if (trigger === "manual" && (!executionProvider || !isAgentAvailable(executionProvider))) {
|
|
61257
|
+
if (trigger === "manual" && !isAgentAvailable(request.provider)) {
|
|
61249
61258
|
throw new ChatProviderUnavailableError(request.provider);
|
|
61250
61259
|
}
|
|
61251
61260
|
return this.createChat({
|
|
61252
61261
|
id: request.id,
|
|
61253
61262
|
provider: request.provider,
|
|
61254
|
-
...relayBaseProvider ? { relayBaseProvider } : {},
|
|
61255
61263
|
title: request.title?.trim() || defaultForkChatTitle(source.persisted, request.provider),
|
|
61256
61264
|
clientRequestId: request.clientRequestId,
|
|
61257
61265
|
fork: createForkInfo(source.persisted, trigger, (/* @__PURE__ */ new Date()).toISOString(), reason)
|
|
@@ -61262,8 +61270,7 @@ var ChatService = class {
|
|
|
61262
61270
|
await source.provider.getHistory({ limit: 1 });
|
|
61263
61271
|
const handoff = await buildForkHandoff({
|
|
61264
61272
|
sourceChatId: options.source.chatId,
|
|
61265
|
-
sourceProvider:
|
|
61266
|
-
executionProvider: getChatExecutionProvider(source.persisted),
|
|
61273
|
+
sourceProvider: source.persisted.provider,
|
|
61267
61274
|
targetChatId,
|
|
61268
61275
|
senders: await this.readSenders(options.source.chatId),
|
|
61269
61276
|
turnLimit: options.turnLimit
|
|
@@ -61280,7 +61287,7 @@ var ChatService = class {
|
|
|
61280
61287
|
const fork = target?.persisted.fork;
|
|
61281
61288
|
if (!target || !fork) return false;
|
|
61282
61289
|
try {
|
|
61283
|
-
if (!isAgentAvailable(
|
|
61290
|
+
if (!isAgentAvailable(target.persisted.provider)) throw new ChatProviderUnavailableError(request.provider);
|
|
61284
61291
|
const message = await this.createForkHandoffMessage(targetId, {
|
|
61285
61292
|
source: fork.source,
|
|
61286
61293
|
trigger: fork.trigger,
|
|
@@ -61323,7 +61330,7 @@ var ChatService = class {
|
|
|
61323
61330
|
const providers = /* @__PURE__ */ new Set();
|
|
61324
61331
|
for (let current = chat; current; ) {
|
|
61325
61332
|
providers.add(current.persisted.provider);
|
|
61326
|
-
providers.add(
|
|
61333
|
+
providers.add(current.persisted.provider);
|
|
61327
61334
|
if (!current.persisted.fork) break;
|
|
61328
61335
|
const source = this.chats.get(current.persisted.fork.source.chatId);
|
|
61329
61336
|
if (!source) providers.add(current.persisted.fork.source.provider);
|
|
@@ -61339,7 +61346,6 @@ var ChatService = class {
|
|
|
61339
61346
|
const last = chat.lastSendRequest;
|
|
61340
61347
|
const request = {
|
|
61341
61348
|
provider: target.provider,
|
|
61342
|
-
relayBaseProvider: target.relayBaseProvider,
|
|
61343
61349
|
model: target.model,
|
|
61344
61350
|
thinkingLevel: target.thinkingLevel,
|
|
61345
61351
|
enableInteractiveTools: last?.enableInteractiveTools,
|
|
@@ -61432,7 +61438,7 @@ var ChatService = class {
|
|
|
61432
61438
|
const chatId = chat.persisted.id;
|
|
61433
61439
|
uploadChatTranscript(
|
|
61434
61440
|
chatId,
|
|
61435
|
-
|
|
61441
|
+
join35(HISTORY_DIR_BY_PROVIDER[chat.persisted.provider], `${chatId}.jsonl`),
|
|
61436
61442
|
this.toTranscriptSource(chat)
|
|
61437
61443
|
).catch((err) => {
|
|
61438
61444
|
console.error("[ChatService] Failed to upload chat transcript:", { chatId, err });
|
|
@@ -61533,9 +61539,8 @@ var ChatService = class {
|
|
|
61533
61539
|
if (persisted.parentChatId === void 0) {
|
|
61534
61540
|
persisted.parentChatId = null;
|
|
61535
61541
|
}
|
|
61536
|
-
const baseProvider =
|
|
61537
|
-
const
|
|
61538
|
-
const historyFilePath = join34(HISTORY_DIR_BY_PROVIDER[persisted.provider], `${persisted.id}.jsonl`);
|
|
61542
|
+
const baseProvider = persisted.provider;
|
|
61543
|
+
const historyFilePath = join35(HISTORY_DIR_BY_PROVIDER[persisted.provider], `${persisted.id}.jsonl`);
|
|
61539
61544
|
const managerOptions = {
|
|
61540
61545
|
provider: baseProvider,
|
|
61541
61546
|
workingDirectory: this.workingDirectory,
|
|
@@ -61551,9 +61556,8 @@ var ChatService = class {
|
|
|
61551
61556
|
chatId: persisted.id,
|
|
61552
61557
|
onModelSwitched,
|
|
61553
61558
|
onChatCredential,
|
|
61554
|
-
additionalInstructions,
|
|
61555
61559
|
linearSessionId: persisted.parentChatId === null ? ENGINE_ENV.REPLICAS_LINEAR_SESSION_ID : void 0,
|
|
61556
|
-
|
|
61560
|
+
parentChatId: persisted.parentChatId
|
|
61557
61561
|
};
|
|
61558
61562
|
let provider;
|
|
61559
61563
|
if (baseProvider === "claude") {
|
|
@@ -61610,7 +61614,6 @@ var ChatService = class {
|
|
|
61610
61614
|
id: chat.persisted.id,
|
|
61611
61615
|
provider: chat.persisted.provider,
|
|
61612
61616
|
model: chat.persisted.model,
|
|
61613
|
-
...chat.persisted.provider === "relay" ? { relayBaseProvider: getChatExecutionProvider(chat.persisted) } : {},
|
|
61614
61617
|
title: chat.persisted.title,
|
|
61615
61618
|
displayName: chat.persisted.displayName,
|
|
61616
61619
|
createdAt: chat.persisted.createdAt,
|
|
@@ -61644,7 +61647,7 @@ var ChatService = class {
|
|
|
61644
61647
|
const context = this.agentChatActivityTrackerService.noteTurnStarted(
|
|
61645
61648
|
chat.persisted.id,
|
|
61646
61649
|
messageId,
|
|
61647
|
-
|
|
61650
|
+
chat.persisted.provider
|
|
61648
61651
|
);
|
|
61649
61652
|
this.agentTokenUsageTracker.startTurn(context);
|
|
61650
61653
|
chat.activeErrorNotificationTargets = chat.errorNotificationTargets.get(messageId) ?? [];
|
|
@@ -61696,13 +61699,13 @@ var ChatService = class {
|
|
|
61696
61699
|
if (chat.hasActiveTurn) {
|
|
61697
61700
|
this.agentChatActivityTrackerService.noteSkillMcpCalls(
|
|
61698
61701
|
chatId,
|
|
61699
|
-
parseDisplayMessages([event],
|
|
61702
|
+
parseDisplayMessages([event], chat.persisted.provider, {
|
|
61700
61703
|
filter: false,
|
|
61701
61704
|
parentToolUseId: typeof event.payload.parent_tool_use_id === "string" ? event.payload.parent_tool_use_id : null
|
|
61702
61705
|
})
|
|
61703
61706
|
);
|
|
61704
61707
|
}
|
|
61705
|
-
const terminalErrors = terminalErrorsFromEvent(event,
|
|
61708
|
+
const terminalErrors = terminalErrorsFromEvent(event, chat.persisted.provider);
|
|
61706
61709
|
if (terminalErrors !== void 0) {
|
|
61707
61710
|
chat.lastTurnErrors = terminalErrors;
|
|
61708
61711
|
}
|
|
@@ -61957,13 +61960,13 @@ import { extname as extname3 } from "path";
|
|
|
61957
61960
|
|
|
61958
61961
|
// src/services/language-server-service.ts
|
|
61959
61962
|
import { spawn as spawn6 } from "child_process";
|
|
61960
|
-
import { existsSync as
|
|
61961
|
-
import { createRequire as
|
|
61962
|
-
import { delimiter as delimiter2, dirname as
|
|
61963
|
+
import { existsSync as existsSync18, readFileSync as readFileSync7 } from "fs";
|
|
61964
|
+
import { createRequire as createRequire6 } from "module";
|
|
61965
|
+
import { delimiter as delimiter2, dirname as dirname18, join as join36, relative as relative2 } from "path";
|
|
61963
61966
|
import { setTimeout as setTimeout3 } from "timers/promises";
|
|
61964
|
-
import { fileURLToPath as
|
|
61967
|
+
import { fileURLToPath as fileURLToPath6, pathToFileURL } from "url";
|
|
61965
61968
|
import { createMessageConnection, StreamMessageReader, StreamMessageWriter } from "vscode-jsonrpc/node.js";
|
|
61966
|
-
var require5 =
|
|
61969
|
+
var require5 = createRequire6(import.meta.url);
|
|
61967
61970
|
var SERVER_TIMEOUT_MS = 1e4;
|
|
61968
61971
|
var LANGUAGE_SERVERS = {
|
|
61969
61972
|
typescript: { package: "typescript-language-server", bin: "typescript-language-server", args: ["--stdio"] },
|
|
@@ -62000,7 +62003,7 @@ function packageBin(packageName, binName) {
|
|
|
62000
62003
|
const packageJson = JSON.parse(readFileSync7(packageJsonPath, "utf8"));
|
|
62001
62004
|
const bin = typeof packageJson.bin === "string" ? packageJson.bin : packageJson.bin[binName];
|
|
62002
62005
|
if (!bin) throw new Error(`Missing ${binName} binary`);
|
|
62003
|
-
return `${
|
|
62006
|
+
return `${dirname18(packageJsonPath)}/${bin}`;
|
|
62004
62007
|
}
|
|
62005
62008
|
function markdownText(value) {
|
|
62006
62009
|
if (typeof value === "string") return value;
|
|
@@ -62078,7 +62081,7 @@ var LanguageServerService = class {
|
|
|
62078
62081
|
if (config.package && config.bin) command = process.execPath;
|
|
62079
62082
|
else if (config.command) {
|
|
62080
62083
|
const commandName = config.command;
|
|
62081
|
-
command = process.env.PATH?.split(delimiter2).map((directory) =>
|
|
62084
|
+
command = process.env.PATH?.split(delimiter2).map((directory) => join36(directory, commandName)).find(existsSync18);
|
|
62082
62085
|
}
|
|
62083
62086
|
const args = config.package && config.bin ? [packageBin(config.package, config.bin), ...config.args] : config.args;
|
|
62084
62087
|
if (!command) return null;
|
|
@@ -62098,7 +62101,7 @@ var LanguageServerService = class {
|
|
|
62098
62101
|
const locations = rawLocations.flatMap((location) => {
|
|
62099
62102
|
const uri = "targetUri" in location ? location.targetUri : location.uri;
|
|
62100
62103
|
const range = "targetSelectionRange" in location ? location.targetSelectionRange : location.range;
|
|
62101
|
-
const absolutePath =
|
|
62104
|
+
const absolutePath = fileURLToPath6(uri);
|
|
62102
62105
|
const path7 = relative2(repoPath, absolutePath);
|
|
62103
62106
|
if (path7.startsWith("..")) return [];
|
|
62104
62107
|
const preview = readFileSync7(absolutePath, "utf8").split("\n")[range.start.line]?.trim() ?? "";
|
|
@@ -62420,20 +62423,20 @@ var RepoFileService = class {
|
|
|
62420
62423
|
import { Hono } from "hono";
|
|
62421
62424
|
import { z as z4 } from "zod";
|
|
62422
62425
|
import { readdir as readdir11, stat as stat7, readFile as readFile23 } from "fs/promises";
|
|
62423
|
-
import { join as
|
|
62426
|
+
import { join as join39, resolve as resolve5 } from "path";
|
|
62424
62427
|
|
|
62425
62428
|
// src/services/warm-hooks-service.ts
|
|
62426
62429
|
import { spawn as spawn7 } from "child_process";
|
|
62427
62430
|
import { readFile as readFile22 } from "fs/promises";
|
|
62428
|
-
import { existsSync as
|
|
62429
|
-
import { join as
|
|
62431
|
+
import { existsSync as existsSync19 } from "fs";
|
|
62432
|
+
import { join as join38 } from "path";
|
|
62430
62433
|
|
|
62431
62434
|
// src/services/warm-hook-logs-service.ts
|
|
62432
62435
|
import { mkdir as mkdir21, readFile as readFile21, writeFile as writeFile11, readdir as readdir10, appendFile as appendFile6, unlink as unlink4 } from "fs/promises";
|
|
62433
62436
|
import { homedir as homedir14 } from "os";
|
|
62434
|
-
import { join as
|
|
62435
|
-
var LOGS_DIR2 =
|
|
62436
|
-
var CURRENT_RUN_LOG =
|
|
62437
|
+
import { join as join37 } from "path";
|
|
62438
|
+
var LOGS_DIR2 = join37(homedir14(), ".replicas", "warm-hook-logs");
|
|
62439
|
+
var CURRENT_RUN_LOG = join37(LOGS_DIR2, "current-run.log");
|
|
62437
62440
|
var GLOBAL_FILENAME = "global.json";
|
|
62438
62441
|
function withPreview2(stored) {
|
|
62439
62442
|
const preview = buildHookOutputPreview(stored.output);
|
|
@@ -62450,7 +62453,7 @@ var WarmHookLogsService = class {
|
|
|
62450
62453
|
hookName: "organization",
|
|
62451
62454
|
...entry
|
|
62452
62455
|
};
|
|
62453
|
-
await writeFile11(
|
|
62456
|
+
await writeFile11(join37(LOGS_DIR2, GLOBAL_FILENAME), `${JSON.stringify(log, null, 2)}
|
|
62454
62457
|
`, "utf-8");
|
|
62455
62458
|
}
|
|
62456
62459
|
async saveEnvironmentHookLog(entry) {
|
|
@@ -62460,7 +62463,7 @@ var WarmHookLogsService = class {
|
|
|
62460
62463
|
hookName: "environment",
|
|
62461
62464
|
...entry
|
|
62462
62465
|
};
|
|
62463
|
-
await writeFile11(
|
|
62466
|
+
await writeFile11(join37(LOGS_DIR2, ENVIRONMENT_HOOK_LOG_FILENAME), `${JSON.stringify(log, null, 2)}
|
|
62464
62467
|
`, "utf-8");
|
|
62465
62468
|
}
|
|
62466
62469
|
async saveRepoHookLog(repoName, entry) {
|
|
@@ -62470,7 +62473,7 @@ var WarmHookLogsService = class {
|
|
|
62470
62473
|
hookName: repoName,
|
|
62471
62474
|
...entry
|
|
62472
62475
|
};
|
|
62473
|
-
await writeFile11(
|
|
62476
|
+
await writeFile11(join37(LOGS_DIR2, repoHookLogFilename(repoName)), `${JSON.stringify(log, null, 2)}
|
|
62474
62477
|
`, "utf-8");
|
|
62475
62478
|
}
|
|
62476
62479
|
async getAllLogs() {
|
|
@@ -62489,7 +62492,7 @@ var WarmHookLogsService = class {
|
|
|
62489
62492
|
continue;
|
|
62490
62493
|
}
|
|
62491
62494
|
try {
|
|
62492
|
-
const raw = await readFile21(
|
|
62495
|
+
const raw = await readFile21(join37(LOGS_DIR2, file), "utf-8");
|
|
62493
62496
|
const stored = JSON.parse(raw);
|
|
62494
62497
|
logs.push(withPreview2(stored));
|
|
62495
62498
|
} catch {
|
|
@@ -62527,7 +62530,7 @@ var WarmHookLogsService = class {
|
|
|
62527
62530
|
async getFullOutput(hookType, hookName) {
|
|
62528
62531
|
const filename = hookType === "global" ? GLOBAL_FILENAME : hookType === "environment" ? ENVIRONMENT_HOOK_LOG_FILENAME : repoHookLogFilename(hookName);
|
|
62529
62532
|
try {
|
|
62530
|
-
const raw = await readFile21(
|
|
62533
|
+
const raw = await readFile21(join37(LOGS_DIR2, filename), "utf-8");
|
|
62531
62534
|
const stored = JSON.parse(raw);
|
|
62532
62535
|
if (stored.hookType !== hookType || stored.hookName !== hookName) {
|
|
62533
62536
|
return null;
|
|
@@ -62546,8 +62549,8 @@ var warmHookLogsService = new WarmHookLogsService();
|
|
|
62546
62549
|
// src/services/warm-hooks-service.ts
|
|
62547
62550
|
async function readRepoWarmHook(repoPath) {
|
|
62548
62551
|
for (const filename of REPLICAS_CONFIG_FILENAMES) {
|
|
62549
|
-
const configPath =
|
|
62550
|
-
if (!
|
|
62552
|
+
const configPath = join38(repoPath, filename);
|
|
62553
|
+
if (!existsSync19(configPath)) {
|
|
62551
62554
|
continue;
|
|
62552
62555
|
}
|
|
62553
62556
|
try {
|
|
@@ -62808,7 +62811,7 @@ ${combinedScript}` : combinedScript;
|
|
|
62808
62811
|
|
|
62809
62812
|
// src/services/terminal-service.ts
|
|
62810
62813
|
import { randomUUID as randomUUID12 } from "crypto";
|
|
62811
|
-
import { existsSync as
|
|
62814
|
+
import { existsSync as existsSync20 } from "fs";
|
|
62812
62815
|
import { spawn as spawn8 } from "node-pty";
|
|
62813
62816
|
var MAX_REPLAY_CHARS = 1024 * 1024;
|
|
62814
62817
|
var MAX_TERMINAL_SESSIONS = 8;
|
|
@@ -62827,7 +62830,7 @@ var TerminalService = class {
|
|
|
62827
62830
|
});
|
|
62828
62831
|
}
|
|
62829
62832
|
const id = randomUUID12();
|
|
62830
|
-
const shell = process.env.SHELL &&
|
|
62833
|
+
const shell = process.env.SHELL && existsSync20(process.env.SHELL) ? process.env.SHELL : "/bin/bash";
|
|
62831
62834
|
const pty = spawn8(shell, ["-l"], {
|
|
62832
62835
|
name: "xterm-256color",
|
|
62833
62836
|
cols,
|
|
@@ -63105,65 +63108,65 @@ function createV1Routes(deps) {
|
|
|
63105
63108
|
app2.get("/chats/:chatId/subagents", async (c) => {
|
|
63106
63109
|
try {
|
|
63107
63110
|
return c.json(
|
|
63108
|
-
await deps.chatService.
|
|
63111
|
+
await deps.chatService.getSubagentProviders(c.req.param("chatId"))
|
|
63109
63112
|
);
|
|
63110
63113
|
} catch (error) {
|
|
63111
63114
|
return c.json(jsonError(
|
|
63112
|
-
"Failed to load
|
|
63115
|
+
"Failed to load subagent providers",
|
|
63113
63116
|
error instanceof Error ? error.message : "Unknown error"
|
|
63114
63117
|
), 400);
|
|
63115
63118
|
}
|
|
63116
63119
|
});
|
|
63117
63120
|
app2.post("/chats/:chatId/subagents", async (c) => {
|
|
63118
63121
|
try {
|
|
63119
|
-
const request =
|
|
63122
|
+
const request = spawnSubagentRequestSchema.parse(await c.req.json());
|
|
63120
63123
|
return c.json(
|
|
63121
|
-
await deps.chatService.
|
|
63124
|
+
await deps.chatService.spawnSubagent(c.req.param("chatId"), request),
|
|
63122
63125
|
201
|
|
63123
63126
|
);
|
|
63124
63127
|
} catch (error) {
|
|
63125
63128
|
return c.json(jsonError(
|
|
63126
|
-
"Failed to spawn
|
|
63129
|
+
"Failed to spawn subagent",
|
|
63127
63130
|
error instanceof Error ? error.message : "Unknown error"
|
|
63128
63131
|
), 400);
|
|
63129
63132
|
}
|
|
63130
63133
|
});
|
|
63131
63134
|
app2.post("/chats/:chatId/subagents/:subagentId/messages", async (c) => {
|
|
63132
63135
|
try {
|
|
63133
|
-
const request =
|
|
63134
|
-
return c.json(await deps.chatService.
|
|
63136
|
+
const request = messageSubagentRequestSchema.parse(await c.req.json());
|
|
63137
|
+
return c.json(await deps.chatService.messageSubagent(
|
|
63135
63138
|
c.req.param("chatId"),
|
|
63136
63139
|
c.req.param("subagentId"),
|
|
63137
63140
|
request
|
|
63138
63141
|
));
|
|
63139
63142
|
} catch (error) {
|
|
63140
63143
|
return c.json(jsonError(
|
|
63141
|
-
"Failed to message
|
|
63144
|
+
"Failed to message subagent",
|
|
63142
63145
|
error instanceof Error ? error.message : "Unknown error"
|
|
63143
63146
|
), 400);
|
|
63144
63147
|
}
|
|
63145
63148
|
});
|
|
63146
63149
|
app2.get("/chats/:chatId/subagents/:subagentId", async (c) => {
|
|
63147
63150
|
try {
|
|
63148
|
-
return c.json(await deps.chatService.
|
|
63151
|
+
return c.json(await deps.chatService.getSubagent(
|
|
63149
63152
|
c.req.param("chatId"),
|
|
63150
63153
|
c.req.param("subagentId")
|
|
63151
63154
|
));
|
|
63152
63155
|
} catch (error) {
|
|
63153
63156
|
return c.json(jsonError(
|
|
63154
|
-
"Failed to load
|
|
63157
|
+
"Failed to load subagent",
|
|
63155
63158
|
error instanceof Error ? error.message : "Unknown error"
|
|
63156
63159
|
), 400);
|
|
63157
63160
|
}
|
|
63158
63161
|
});
|
|
63159
63162
|
app2.get("/chats/:chatId/subagents/:subagentId/wait", async (c) => {
|
|
63160
|
-
const parsed =
|
|
63163
|
+
const parsed = waitSubagentRequestSchema.safeParse(c.req.query());
|
|
63161
63164
|
if (!parsed.success) {
|
|
63162
|
-
return c.json(jsonError("Failed to wait for
|
|
63165
|
+
return c.json(jsonError("Failed to wait for subagent", parsed.error.message), 400);
|
|
63163
63166
|
}
|
|
63164
63167
|
return createJsonEventStream(
|
|
63165
63168
|
async (send) => {
|
|
63166
|
-
send(await deps.chatService.
|
|
63169
|
+
send(await deps.chatService.waitForSubagent(
|
|
63167
63170
|
c.req.param("chatId"),
|
|
63168
63171
|
c.req.param("subagentId"),
|
|
63169
63172
|
parsed.data.timeoutMinutes,
|
|
@@ -63173,7 +63176,7 @@ function createV1Routes(deps) {
|
|
|
63173
63176
|
(error) => ({
|
|
63174
63177
|
event: "error",
|
|
63175
63178
|
data: {
|
|
63176
|
-
error: "Failed to wait for
|
|
63179
|
+
error: "Failed to wait for subagent",
|
|
63177
63180
|
details: error instanceof Error ? error.message : "Unknown error"
|
|
63178
63181
|
}
|
|
63179
63182
|
})
|
|
@@ -63181,11 +63184,11 @@ function createV1Routes(deps) {
|
|
|
63181
63184
|
});
|
|
63182
63185
|
app2.delete("/chats/:chatId/subagents/:subagentId", async (c) => {
|
|
63183
63186
|
try {
|
|
63184
|
-
await deps.chatService.
|
|
63187
|
+
await deps.chatService.deleteSubagent(c.req.param("chatId"), c.req.param("subagentId"));
|
|
63185
63188
|
return c.json({ success: true, chatId: c.req.param("subagentId") });
|
|
63186
63189
|
} catch (error) {
|
|
63187
63190
|
return c.json(jsonError(
|
|
63188
|
-
"Failed to delete
|
|
63191
|
+
"Failed to delete subagent",
|
|
63189
63192
|
error instanceof Error ? error.message : "Unknown error"
|
|
63190
63193
|
), 400);
|
|
63191
63194
|
}
|
|
@@ -63906,7 +63909,7 @@ data: ${JSON.stringify("Terminal session not found")}
|
|
|
63906
63909
|
const logFiles = files.filter((f) => f.endsWith(".log"));
|
|
63907
63910
|
const sessions = await Promise.all(
|
|
63908
63911
|
logFiles.map(async (filename) => {
|
|
63909
|
-
const filePath =
|
|
63912
|
+
const filePath = join39(LOG_DIR, filename);
|
|
63910
63913
|
const fileStat = await stat7(filePath);
|
|
63911
63914
|
const sessionId = filename.replace(/\.log$/, "");
|
|
63912
63915
|
return {
|
|
@@ -64017,10 +64020,10 @@ var heartbeatService = new HeartbeatService();
|
|
|
64017
64020
|
|
|
64018
64021
|
// src/services/workspace-sdk-service.ts
|
|
64019
64022
|
import { cp, mkdir as mkdir22 } from "fs/promises";
|
|
64020
|
-
import { dirname as
|
|
64021
|
-
import { fileURLToPath as
|
|
64023
|
+
import { dirname as dirname19, resolve as resolve6 } from "path";
|
|
64024
|
+
import { fileURLToPath as fileURLToPath7 } from "url";
|
|
64022
64025
|
async function installWorkspaceSdk() {
|
|
64023
|
-
const source = resolve6(
|
|
64026
|
+
const source = resolve6(dirname19(fileURLToPath7(import.meta.url)), "../../workspace-sdk");
|
|
64024
64027
|
const targets = [
|
|
64025
64028
|
resolve6(ENGINE_ENV.HOME_DIR, "node_modules/@replicas/sdk"),
|
|
64026
64029
|
"/tmp/node_modules/@replicas/sdk"
|
|
@@ -64034,8 +64037,8 @@ async function installWorkspaceSdk() {
|
|
|
64034
64037
|
// src/services/git-push-tracker.ts
|
|
64035
64038
|
import { mkdir as mkdir23, rm as rm5 } from "fs/promises";
|
|
64036
64039
|
import { createServer as createServer2 } from "net";
|
|
64037
|
-
import { join as
|
|
64038
|
-
var SOCKET_PATH =
|
|
64040
|
+
import { join as join40 } from "path";
|
|
64041
|
+
var SOCKET_PATH = join40(ENGINE_DIR2, "git-trace2.sock");
|
|
64039
64042
|
var MAX_LINE_LENGTH = 1024 * 1024;
|
|
64040
64043
|
var listening = null;
|
|
64041
64044
|
function startGitPushTracker() {
|