@ycodium-ai/agent-opencode 0.2.5004 → 0.2.5093
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/index.js +495 -456
- package/package.json +6 -4
package/dist/index.js
CHANGED
|
@@ -5,7 +5,7 @@ const require = __ycodiumCreateRequire(import.meta.url);
|
|
|
5
5
|
import { definePlugin } from "@ycodium-ai/plugin-api";
|
|
6
6
|
|
|
7
7
|
// ../../packages/plugin-api/src/version.ts
|
|
8
|
-
var PLUGIN_API_VERSION =
|
|
8
|
+
var PLUGIN_API_VERSION = 147;
|
|
9
9
|
|
|
10
10
|
// src/card.ts
|
|
11
11
|
var OPENCODE_DRIVER_KIND = "opencode";
|
|
@@ -149,7 +149,8 @@ var OPENCODE_CARD = {
|
|
|
149
149
|
// src/opencodeInstance.ts
|
|
150
150
|
import "@ycodium-ai/plugin-api/executor";
|
|
151
151
|
|
|
152
|
-
// src/
|
|
152
|
+
// ../../packages/ycodium-instance-config/src/instanceConfig.ts
|
|
153
|
+
import { modelSelectionStringOption } from "@ycodium-ai/plugin-api/executor";
|
|
153
154
|
function isRecord(value) {
|
|
154
155
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
155
156
|
}
|
|
@@ -159,6 +160,11 @@ function readString(value) {
|
|
|
159
160
|
function readTrimmed(value) {
|
|
160
161
|
return readString(value).trim();
|
|
161
162
|
}
|
|
163
|
+
function modelIdFromSelection(selection) {
|
|
164
|
+
if (!isRecord(selection)) return void 0;
|
|
165
|
+
const model = selection["model"];
|
|
166
|
+
return typeof model === "string" ? model.trim() || void 0 : void 0;
|
|
167
|
+
}
|
|
162
168
|
function readEnvironment(value) {
|
|
163
169
|
if (!Array.isArray(value)) return {};
|
|
164
170
|
const env = {};
|
|
@@ -170,56 +176,59 @@ function readEnvironment(value) {
|
|
|
170
176
|
}
|
|
171
177
|
return env;
|
|
172
178
|
}
|
|
179
|
+
function instanceSettings(config) {
|
|
180
|
+
if (!isRecord(config)) return {};
|
|
181
|
+
return isRecord(config["config"]) ? config["config"] : config;
|
|
182
|
+
}
|
|
183
|
+
function readInstanceEnvelope(config) {
|
|
184
|
+
const envelope = isRecord(config) ? config : {};
|
|
185
|
+
const settings = instanceSettings(config);
|
|
186
|
+
return {
|
|
187
|
+
settings,
|
|
188
|
+
settingOrEnvelope: (key) => readTrimmed(settings[key]) || readTrimmed(envelope[key]),
|
|
189
|
+
environment: readEnvironment(envelope["environment"]),
|
|
190
|
+
envelopeDriver: readTrimmed(envelope["driver"]) || void 0
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
function readCustomModel(entry) {
|
|
194
|
+
if (typeof entry === "string") {
|
|
195
|
+
const slug2 = entry.trim();
|
|
196
|
+
return slug2.length > 0 ? { slug: slug2 } : void 0;
|
|
197
|
+
}
|
|
198
|
+
if (!isRecord(entry)) return void 0;
|
|
199
|
+
const slug = readTrimmed(entry["slug"]);
|
|
200
|
+
if (slug.length === 0) return void 0;
|
|
201
|
+
const aliasesRaw = entry["aliases"];
|
|
202
|
+
const aliases = Array.isArray(aliasesRaw) ? aliasesRaw.filter(
|
|
203
|
+
(alias) => typeof alias === "string" && alias.trim().length > 0
|
|
204
|
+
) : void 0;
|
|
205
|
+
const contextWindow = typeof entry["contextWindow"] === "number" && Number.isFinite(entry["contextWindow"]) && entry["contextWindow"] > 0 ? Math.round(entry["contextWindow"]) : void 0;
|
|
206
|
+
const label = readTrimmed(entry["label"]);
|
|
207
|
+
return {
|
|
208
|
+
slug,
|
|
209
|
+
...label ? { label } : {},
|
|
210
|
+
...contextWindow !== void 0 ? { contextWindow } : {},
|
|
211
|
+
...aliases && aliases.length > 0 ? { aliases } : {}
|
|
212
|
+
};
|
|
213
|
+
}
|
|
173
214
|
function readCustomModels(value) {
|
|
174
215
|
if (!Array.isArray(value)) return [];
|
|
175
|
-
|
|
176
|
-
for (const entry of value) {
|
|
177
|
-
if (typeof entry === "string") {
|
|
178
|
-
const slug2 = entry.trim();
|
|
179
|
-
if (slug2.length > 0) models.push({ slug: slug2 });
|
|
180
|
-
continue;
|
|
181
|
-
}
|
|
182
|
-
if (!isRecord(entry)) continue;
|
|
183
|
-
const slug = readTrimmed(entry["slug"]);
|
|
184
|
-
if (slug.length === 0) continue;
|
|
185
|
-
const aliasesRaw = entry["aliases"];
|
|
186
|
-
const aliases = Array.isArray(aliasesRaw) ? aliasesRaw.filter(
|
|
187
|
-
(alias) => typeof alias === "string" && alias.trim().length > 0
|
|
188
|
-
) : void 0;
|
|
189
|
-
const contextWindow = typeof entry["contextWindow"] === "number" && Number.isFinite(entry["contextWindow"]) && entry["contextWindow"] > 0 ? Math.round(entry["contextWindow"]) : void 0;
|
|
190
|
-
models.push({
|
|
191
|
-
slug,
|
|
192
|
-
...readTrimmed(entry["label"]) ? { label: readTrimmed(entry["label"]) } : {},
|
|
193
|
-
...contextWindow !== void 0 ? { contextWindow } : {},
|
|
194
|
-
...aliases && aliases.length > 0 ? { aliases } : {}
|
|
195
|
-
});
|
|
196
|
-
}
|
|
197
|
-
return models;
|
|
216
|
+
return value.flatMap((entry) => readCustomModel(entry) ?? []);
|
|
198
217
|
}
|
|
218
|
+
|
|
219
|
+
// src/config.ts
|
|
199
220
|
function parseOpenCodeInstanceConfig(config) {
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
binaryPath: "",
|
|
203
|
-
homePath: "",
|
|
204
|
-
serverUrl: "",
|
|
205
|
-
serverPassword: "",
|
|
206
|
-
customModels: [],
|
|
207
|
-
enabled: true,
|
|
208
|
-
environment: {},
|
|
209
|
-
envelopeDriver: void 0
|
|
210
|
-
};
|
|
211
|
-
}
|
|
212
|
-
const nested = isRecord(config["config"]) ? config["config"] : void 0;
|
|
213
|
-
const settings = nested ?? config;
|
|
221
|
+
const envelope = readInstanceEnvelope(config);
|
|
222
|
+
const { settings } = envelope;
|
|
214
223
|
return {
|
|
215
224
|
binaryPath: readTrimmed(settings["binaryPath"]),
|
|
216
|
-
homePath:
|
|
225
|
+
homePath: envelope.settingOrEnvelope("homePath"),
|
|
217
226
|
serverUrl: readTrimmed(settings["serverUrl"]),
|
|
218
227
|
serverPassword: readTrimmed(settings["serverPassword"]),
|
|
219
228
|
customModels: readCustomModels(settings["customModels"]),
|
|
220
229
|
enabled: settings["enabled"] !== false,
|
|
221
|
-
environment:
|
|
222
|
-
envelopeDriver:
|
|
230
|
+
environment: envelope.environment,
|
|
231
|
+
envelopeDriver: envelope.envelopeDriver
|
|
223
232
|
};
|
|
224
233
|
}
|
|
225
234
|
|
|
@@ -484,9 +493,10 @@ function toOpenCodeFormAnswer(form, answers) {
|
|
|
484
493
|
import * as NodeFSP2 from "node:fs/promises";
|
|
485
494
|
import * as NodePath3 from "node:path";
|
|
486
495
|
|
|
487
|
-
// src/
|
|
496
|
+
// ../../packages/ycodium-instance-config/src/homePath.ts
|
|
488
497
|
import * as NodeOS2 from "node:os";
|
|
489
498
|
import * as NodePath2 from "node:path";
|
|
499
|
+
import { mergeLaunchEnv } from "@ycodium-ai/plugin-api/executor";
|
|
490
500
|
function expandHomePath(value) {
|
|
491
501
|
if (value === "~") return NodeOS2.homedir();
|
|
492
502
|
if (value.startsWith("~/") || value.startsWith("~\\")) {
|
|
@@ -543,6 +553,7 @@ async function isSameOpenCodeDirectory(left, right) {
|
|
|
543
553
|
// src/model.ts
|
|
544
554
|
import {
|
|
545
555
|
describeExecutorSpawnFailure,
|
|
556
|
+
modelSelectionStringOption as modelSelectionStringOption2,
|
|
546
557
|
REASONING_OPTION_LABEL
|
|
547
558
|
} from "@ycodium-ai/plugin-api/executor";
|
|
548
559
|
|
|
@@ -550,8 +561,8 @@ import {
|
|
|
550
561
|
var OPENCODE_LIST_WARMUP_MS = 5e3;
|
|
551
562
|
function watchListLoad(api, directory, signal) {
|
|
552
563
|
let markConnected = () => void 0;
|
|
553
|
-
const connected = new Promise((
|
|
554
|
-
markConnected =
|
|
564
|
+
const connected = new Promise((resolve3) => {
|
|
565
|
+
markConnected = resolve3;
|
|
555
566
|
});
|
|
556
567
|
const loaded = (async () => {
|
|
557
568
|
try {
|
|
@@ -574,8 +585,8 @@ async function readWhenLoaded(api, directory, read, complete, timeoutMs, signal)
|
|
|
574
585
|
const onAbort = () => abort.abort();
|
|
575
586
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
576
587
|
let timer;
|
|
577
|
-
const deadline = new Promise((
|
|
578
|
-
timer = setTimeout(
|
|
588
|
+
const deadline = new Promise((resolve3) => {
|
|
589
|
+
timer = setTimeout(resolve3, timeoutMs);
|
|
579
590
|
});
|
|
580
591
|
try {
|
|
581
592
|
const watch = watchListLoad(api, directory, abort.signal);
|
|
@@ -701,59 +712,10 @@ async function loadOpenCodeInventory(api, directory, signal) {
|
|
|
701
712
|
...defaultModel === void 0 ? {} : { defaultModelSlug: `${defaultModel.providerId}/${defaultModel.id}` }
|
|
702
713
|
};
|
|
703
714
|
}
|
|
704
|
-
function extractJsonObject(raw) {
|
|
705
|
-
const trimmed = raw.trim();
|
|
706
|
-
if (trimmed.length === 0) return trimmed;
|
|
707
|
-
const start = trimmed.indexOf("{");
|
|
708
|
-
if (start < 0) return trimmed;
|
|
709
|
-
let depth = 0;
|
|
710
|
-
let inString = false;
|
|
711
|
-
let escaping = false;
|
|
712
|
-
for (let index = start; index < trimmed.length; index += 1) {
|
|
713
|
-
const char = trimmed[index];
|
|
714
|
-
if (inString) {
|
|
715
|
-
if (escaping) escaping = false;
|
|
716
|
-
else if (char === "\\") escaping = true;
|
|
717
|
-
else if (char === '"') inString = false;
|
|
718
|
-
continue;
|
|
719
|
-
}
|
|
720
|
-
if (char === '"') {
|
|
721
|
-
inString = true;
|
|
722
|
-
continue;
|
|
723
|
-
}
|
|
724
|
-
if (char === "{") {
|
|
725
|
-
depth += 1;
|
|
726
|
-
continue;
|
|
727
|
-
}
|
|
728
|
-
if (char === "}") {
|
|
729
|
-
depth -= 1;
|
|
730
|
-
if (depth === 0) return trimmed.slice(start, index + 1);
|
|
731
|
-
}
|
|
732
|
-
}
|
|
733
|
-
return trimmed.slice(start);
|
|
734
|
-
}
|
|
735
|
-
function getModelSelectionStringOptionValue(modelSelection, optionId) {
|
|
736
|
-
if (!isRecord2(modelSelection)) return void 0;
|
|
737
|
-
const options = modelSelection["options"];
|
|
738
|
-
if (!Array.isArray(options)) return void 0;
|
|
739
|
-
for (const entry of options) {
|
|
740
|
-
if (!isRecord2(entry)) continue;
|
|
741
|
-
if (entry["id"] === optionId && typeof entry["value"] === "string") {
|
|
742
|
-
const trimmed = entry["value"].trim();
|
|
743
|
-
if (trimmed.length > 0) return trimmed;
|
|
744
|
-
}
|
|
745
|
-
}
|
|
746
|
-
return void 0;
|
|
747
|
-
}
|
|
748
|
-
function modelIdFromSelection(selection) {
|
|
749
|
-
if (!isRecord2(selection)) return void 0;
|
|
750
|
-
const model = selection["model"];
|
|
751
|
-
return typeof model === "string" ? model.trim() || void 0 : void 0;
|
|
752
|
-
}
|
|
753
715
|
function toOpenCodeModelRef(input) {
|
|
754
716
|
const parsed = chooseOpenCodeModel(input.requested);
|
|
755
717
|
if (parsed === void 0) return void 0;
|
|
756
|
-
const variant =
|
|
718
|
+
const variant = modelSelectionStringOption2(input.modelSelection, "variant");
|
|
757
719
|
return {
|
|
758
720
|
providerID: parsed.providerID,
|
|
759
721
|
id: parsed.modelID,
|
|
@@ -1037,7 +999,7 @@ import * as NodeCrypto from "node:crypto";
|
|
|
1037
999
|
import * as NodeFSP3 from "node:fs/promises";
|
|
1038
1000
|
import * as NodeOS3 from "node:os";
|
|
1039
1001
|
import * as NodePath4 from "node:path";
|
|
1040
|
-
import { mergeLaunchEnv } from "@ycodium-ai/plugin-api";
|
|
1002
|
+
import { mergeLaunchEnv as mergeLaunchEnv2 } from "@ycodium-ai/plugin-api";
|
|
1041
1003
|
import {
|
|
1042
1004
|
parseRetryAfterMs
|
|
1043
1005
|
} from "@ycodium-ai/plugin-api/usage";
|
|
@@ -1107,7 +1069,7 @@ var createOpenCodeUsage = (input) => {
|
|
|
1107
1069
|
const readTextFile = input.readTextFile ?? readTextOrNull;
|
|
1108
1070
|
const timeoutMs = input.timeoutMs ?? QUOTA_TIMEOUT_MS;
|
|
1109
1071
|
const xdg = resolveOpenCodeXdgPaths(input.homePath);
|
|
1110
|
-
const env =
|
|
1072
|
+
const env = mergeLaunchEnv2({
|
|
1111
1073
|
inherited: input.processEnv ?? process.env,
|
|
1112
1074
|
accountHome: xdg === void 0 ? void 0 : { XDG_DATA_HOME: xdg.dataHome },
|
|
1113
1075
|
instanceTable: input.environment
|
|
@@ -1278,7 +1240,7 @@ var OpenCodeApiError = class extends Error {
|
|
|
1278
1240
|
// src/server.ts
|
|
1279
1241
|
import * as NodeCrypto2 from "node:crypto";
|
|
1280
1242
|
import {
|
|
1281
|
-
mergeLaunchEnv as
|
|
1243
|
+
mergeLaunchEnv as mergeLaunchEnv3,
|
|
1282
1244
|
throwIfExecutorSpawnAborted
|
|
1283
1245
|
} from "@ycodium-ai/plugin-api/executor";
|
|
1284
1246
|
import { drainStderrTail } from "@ycodium-ai/plugin-api/process-stdin";
|
|
@@ -1376,12 +1338,12 @@ var FETCH_BLOCKED_PORTS = /* @__PURE__ */ new Set([
|
|
|
1376
1338
|
var isFetchSafePort = (port) => !FETCH_BLOCKED_PORTS.has(port);
|
|
1377
1339
|
var MAX_SAFE_PORT_ATTEMPTS = 50;
|
|
1378
1340
|
var systemAssigned = () => 0;
|
|
1379
|
-
var listenOnce = (server, host, port) => new Promise((
|
|
1341
|
+
var listenOnce = (server, host, port) => new Promise((resolve3, reject) => {
|
|
1380
1342
|
server.once("error", reject);
|
|
1381
1343
|
server.listen(port, host, () => {
|
|
1382
1344
|
server.off("error", reject);
|
|
1383
1345
|
const address = server.address();
|
|
1384
|
-
|
|
1346
|
+
resolve3(typeof address === "object" && address !== null ? address.port : 0);
|
|
1385
1347
|
});
|
|
1386
1348
|
});
|
|
1387
1349
|
var listenOnSafePort = async (server, options = {}) => {
|
|
@@ -1390,7 +1352,7 @@ var listenOnSafePort = async (server, options = {}) => {
|
|
|
1390
1352
|
for (let attempt = 0; attempt < MAX_SAFE_PORT_ATTEMPTS; attempt++) {
|
|
1391
1353
|
const port = await listenOnce(server, host, portForAttempt(attempt));
|
|
1392
1354
|
if (isFetchSafePort(port)) return port;
|
|
1393
|
-
await new Promise((
|
|
1355
|
+
await new Promise((resolve3) => server.close(() => resolve3()));
|
|
1394
1356
|
}
|
|
1395
1357
|
throw new Error(`\u8FDE\u7EED ${String(MAX_SAFE_PORT_ATTEMPTS)} \u6B21\u5206\u5230 fetch \u7684\u574F\u7AEF\u53E3`);
|
|
1396
1358
|
};
|
|
@@ -1398,7 +1360,7 @@ var reserveFetchSafePort = async (options = {}) => {
|
|
|
1398
1360
|
const probe = NodeNet.createServer();
|
|
1399
1361
|
try {
|
|
1400
1362
|
const port = await listenOnSafePort(probe, options);
|
|
1401
|
-
await new Promise((
|
|
1363
|
+
await new Promise((resolve3) => probe.close(() => resolve3()));
|
|
1402
1364
|
if (port <= 0) throw new Error("\u65E0\u6CD5\u53D6\u5F97\u76D1\u542C\u7AEF\u53E3");
|
|
1403
1365
|
return port;
|
|
1404
1366
|
} catch (cause) {
|
|
@@ -1450,7 +1412,7 @@ function openCodeSessionSkillsConfig(skills, inherited, log) {
|
|
|
1450
1412
|
var OPENCODE_STDERR_TAIL_CHARS = 600;
|
|
1451
1413
|
function buildSpawnEnv(recipe, configContent, password) {
|
|
1452
1414
|
const xdgHome = makeOpenCodeEnvironment(recipe.homePath, {});
|
|
1453
|
-
return
|
|
1415
|
+
return mergeLaunchEnv3({
|
|
1454
1416
|
accountHome: xdgHome,
|
|
1455
1417
|
instanceTable: recipe.environment,
|
|
1456
1418
|
handOverrides: {
|
|
@@ -1535,7 +1497,7 @@ async function spawnOpenCodeServer(input) {
|
|
|
1535
1497
|
const stdoutDecoder = new TextDecoder();
|
|
1536
1498
|
const startupOutput = async () => `stdout=${stdoutText.trim()} stderr=${(await stderrTail()).slice(-OPENCODE_STDERR_TAIL_CHARS)}`;
|
|
1537
1499
|
let settled = false;
|
|
1538
|
-
const url = await new Promise((
|
|
1500
|
+
const url = await new Promise((resolve3, reject) => {
|
|
1539
1501
|
const fail = (cause) => {
|
|
1540
1502
|
if (settled) return;
|
|
1541
1503
|
settled = true;
|
|
@@ -1557,7 +1519,7 @@ async function spawnOpenCodeServer(input) {
|
|
|
1557
1519
|
if (parsed) {
|
|
1558
1520
|
settled = true;
|
|
1559
1521
|
clearTimeout(timer);
|
|
1560
|
-
|
|
1522
|
+
resolve3(parsed);
|
|
1561
1523
|
}
|
|
1562
1524
|
}
|
|
1563
1525
|
if (!settled) await failWithOutput("OpenCode server exited before becoming ready.");
|
|
@@ -3308,8 +3270,8 @@ function createOpenCodeSessionLifecycle(input) {
|
|
|
3308
3270
|
drain().catch((error) => {
|
|
3309
3271
|
log.warn(`OpenCode tail handler failed: ${String(error)}`);
|
|
3310
3272
|
}).then(() => false),
|
|
3311
|
-
new Promise((
|
|
3312
|
-
timer = setTimeout(() =>
|
|
3273
|
+
new Promise((resolve3) => {
|
|
3274
|
+
timer = setTimeout(() => resolve3(true), options?.tailTimeoutMs ?? 2e3);
|
|
3313
3275
|
})
|
|
3314
3276
|
]);
|
|
3315
3277
|
if (timedOut) {
|
|
@@ -3411,6 +3373,7 @@ function createOpenCodeSessionLifecycle(input) {
|
|
|
3411
3373
|
}
|
|
3412
3374
|
|
|
3413
3375
|
// src/turnSelection.ts
|
|
3376
|
+
import { modelSelectionStringOption as modelSelectionStringOption3 } from "@ycodium-ai/plugin-api/executor";
|
|
3414
3377
|
var OPENCODE_PLAN_AGENT = "plan";
|
|
3415
3378
|
function openCodeSelectionOf(session) {
|
|
3416
3379
|
return { selectedModel: session.model, selectedAgent: session.agent ?? null };
|
|
@@ -3438,7 +3401,7 @@ async function applyOpenCodeTurnSelection(input) {
|
|
|
3438
3401
|
await context.api.selectModel(context.sessionId, model);
|
|
3439
3402
|
context.selectedModel = model;
|
|
3440
3403
|
}
|
|
3441
|
-
const chosen =
|
|
3404
|
+
const chosen = modelSelectionStringOption3(input.modelSelection, "agent") ?? (input.interactionMode === "plan" ? OPENCODE_PLAN_AGENT : void 0);
|
|
3442
3405
|
if (chosen === void 0 && context.selectedAgent === null) return;
|
|
3443
3406
|
if (chosen !== void 0 && chosen === context.selectedAgent) return;
|
|
3444
3407
|
const known = await listOpenCodeAgentsForSelection(context.api, context.directory, chosen);
|
|
@@ -3495,12 +3458,12 @@ async function handleOtherSessionEvent(context, event, discoveredChild) {
|
|
|
3495
3458
|
}
|
|
3496
3459
|
var OPENCODE_EVENT_RECONNECT_DELAYS_MS = [200, 1e3, 3e3];
|
|
3497
3460
|
var OPENCODE_EVENT_READY_TIMEOUT_MS = 1e4;
|
|
3498
|
-
var abortableDelay = (ms, signal) => new Promise((
|
|
3461
|
+
var abortableDelay = (ms, signal) => new Promise((resolve3) => {
|
|
3499
3462
|
const timer = setTimeout(done, ms);
|
|
3500
3463
|
function done() {
|
|
3501
3464
|
clearTimeout(timer);
|
|
3502
3465
|
signal.removeEventListener("abort", done);
|
|
3503
|
-
|
|
3466
|
+
resolve3();
|
|
3504
3467
|
}
|
|
3505
3468
|
signal.addEventListener("abort", done, { once: true });
|
|
3506
3469
|
});
|
|
@@ -3554,8 +3517,8 @@ function startEventPump(input) {
|
|
|
3554
3517
|
};
|
|
3555
3518
|
let connected = false;
|
|
3556
3519
|
let settleConnected;
|
|
3557
|
-
const ready = new Promise((
|
|
3558
|
-
settleConnected = { resolve:
|
|
3520
|
+
const ready = new Promise((resolve3, reject) => {
|
|
3521
|
+
settleConnected = { resolve: resolve3, reject };
|
|
3559
3522
|
});
|
|
3560
3523
|
const readyTimer = setTimeout(() => {
|
|
3561
3524
|
fail(
|
|
@@ -3688,185 +3651,12 @@ function opencodeOpenCommands(context) {
|
|
|
3688
3651
|
|
|
3689
3652
|
// src/textGeneration.ts
|
|
3690
3653
|
import "@ycodium-ai/plugin-api/executor";
|
|
3691
|
-
import { isOperationCleanupError as isOperationCleanupError3 } from "@ycodium-ai/plugin-api/process-operation";
|
|
3692
3654
|
import { redactStderrExcerpt } from "@ycodium-ai/plugin-api/process-stdin";
|
|
3693
3655
|
|
|
3694
|
-
// src/
|
|
3695
|
-
import {
|
|
3696
|
-
import {
|
|
3697
|
-
OperationCleanupError as OperationCleanupError2,
|
|
3698
|
-
isOperationCleanupError as isOperationCleanupError2
|
|
3699
|
-
} from "@ycodium-ai/plugin-api/process-operation";
|
|
3700
|
-
var IDLE_TTL_MS = 3e4;
|
|
3701
|
-
var REQUEST_DRAIN_TIMEOUT_MS = 3e3;
|
|
3702
|
-
var SERVER_CLOSE_TIMEOUT_MS = 2e3;
|
|
3703
|
-
async function within(work, milliseconds) {
|
|
3704
|
-
let timer;
|
|
3705
|
-
try {
|
|
3706
|
-
return await Promise.race([
|
|
3707
|
-
work,
|
|
3708
|
-
new Promise((_resolve, reject) => {
|
|
3709
|
-
timer = setTimeout(
|
|
3710
|
-
() => reject(new Error("OpenCode text generation disposal timed out.")),
|
|
3711
|
-
milliseconds
|
|
3712
|
-
);
|
|
3713
|
-
})
|
|
3714
|
-
]);
|
|
3715
|
-
} finally {
|
|
3716
|
-
clearTimeout(timer);
|
|
3717
|
-
}
|
|
3718
|
-
}
|
|
3719
|
-
function createTextGenerationServer(recipe, host) {
|
|
3720
|
-
let handle;
|
|
3721
|
-
let starting;
|
|
3722
|
-
let client;
|
|
3723
|
-
let binaryPath;
|
|
3724
|
-
let borrowers = 0;
|
|
3725
|
-
let idleTimer;
|
|
3726
|
-
let mutex = Promise.resolve();
|
|
3727
|
-
let disposed = false;
|
|
3728
|
-
let disposal;
|
|
3729
|
-
const lifetime = new AbortController();
|
|
3730
|
-
const requests = /* @__PURE__ */ new Set();
|
|
3731
|
-
const withMutex = async (work) => {
|
|
3732
|
-
const previous = mutex;
|
|
3733
|
-
const next = Promise.withResolvers();
|
|
3734
|
-
mutex = next.promise;
|
|
3735
|
-
await previous;
|
|
3736
|
-
try {
|
|
3737
|
-
return await work();
|
|
3738
|
-
} finally {
|
|
3739
|
-
next.resolve();
|
|
3740
|
-
}
|
|
3741
|
-
};
|
|
3742
|
-
const clearIdle = () => {
|
|
3743
|
-
clearTimeout(idleTimer);
|
|
3744
|
-
idleTimer = void 0;
|
|
3745
|
-
};
|
|
3746
|
-
const close = async () => {
|
|
3747
|
-
clearIdle();
|
|
3748
|
-
try {
|
|
3749
|
-
if (handle && !handle.external) await closeOpenCodeServer(handle);
|
|
3750
|
-
if (starting) await closeOpenCodeServer(starting);
|
|
3751
|
-
} catch (cause) {
|
|
3752
|
-
if (isOperationCleanupError2(cause)) throw cause;
|
|
3753
|
-
throw new OperationCleanupError2([cause]);
|
|
3754
|
-
}
|
|
3755
|
-
handle = void 0;
|
|
3756
|
-
starting = void 0;
|
|
3757
|
-
client = void 0;
|
|
3758
|
-
binaryPath = void 0;
|
|
3759
|
-
};
|
|
3760
|
-
const scheduleIdle = () => {
|
|
3761
|
-
clearIdle();
|
|
3762
|
-
if (disposed || recipe.serverUrl.trim()) return;
|
|
3763
|
-
idleTimer = setTimeout(() => {
|
|
3764
|
-
void withMutex(async () => {
|
|
3765
|
-
if (!disposed && borrowers === 0) await close();
|
|
3766
|
-
}).catch((error) => {
|
|
3767
|
-
host.log.warn("Could not close the idle OpenCode text generation server", {
|
|
3768
|
-
error: String(error)
|
|
3769
|
-
});
|
|
3770
|
-
});
|
|
3771
|
-
}, IDLE_TTL_MS);
|
|
3772
|
-
};
|
|
3773
|
-
return {
|
|
3774
|
-
withClient(input, work) {
|
|
3775
|
-
if (disposed) return Promise.reject(new Error("OpenCode text generation has been disposed."));
|
|
3776
|
-
const signal = AbortSignal.any([
|
|
3777
|
-
lifetime.signal,
|
|
3778
|
-
...input.signal === void 0 ? [] : [input.signal]
|
|
3779
|
-
]);
|
|
3780
|
-
const request = (async () => {
|
|
3781
|
-
let borrowed = false;
|
|
3782
|
-
const acquisition = withMutex(async () => {
|
|
3783
|
-
signal.throwIfAborted();
|
|
3784
|
-
clearIdle();
|
|
3785
|
-
if (starting) await close();
|
|
3786
|
-
const program = recipe.binaryPath.trim() || "opencode";
|
|
3787
|
-
if (client && binaryPath !== program && borrowers === 0 && !handle?.external)
|
|
3788
|
-
await close();
|
|
3789
|
-
if (!client) {
|
|
3790
|
-
const startup = new AbortController();
|
|
3791
|
-
const abortStartup = () => startup.abort(lifetime.signal.reason);
|
|
3792
|
-
lifetime.signal.addEventListener("abort", abortStartup, { once: true });
|
|
3793
|
-
if (lifetime.signal.aborted) abortStartup();
|
|
3794
|
-
try {
|
|
3795
|
-
handle = await connectToOpenCodeServer({
|
|
3796
|
-
host,
|
|
3797
|
-
recipe,
|
|
3798
|
-
directory: input.cwd,
|
|
3799
|
-
program,
|
|
3800
|
-
signal: startup.signal,
|
|
3801
|
-
onSpawn: (resource) => {
|
|
3802
|
-
starting = resource;
|
|
3803
|
-
}
|
|
3804
|
-
});
|
|
3805
|
-
starting = void 0;
|
|
3806
|
-
} finally {
|
|
3807
|
-
lifetime.signal.removeEventListener("abort", abortStartup);
|
|
3808
|
-
}
|
|
3809
|
-
binaryPath = program;
|
|
3810
|
-
client = createOpenCodeApi({ url: handle.url, password: handle.password });
|
|
3811
|
-
}
|
|
3812
|
-
if (signal.aborted) {
|
|
3813
|
-
scheduleIdle();
|
|
3814
|
-
signal.throwIfAborted();
|
|
3815
|
-
}
|
|
3816
|
-
borrowers += 1;
|
|
3817
|
-
borrowed = true;
|
|
3818
|
-
return client;
|
|
3819
|
-
});
|
|
3820
|
-
try {
|
|
3821
|
-
const api = await raceAbort(acquisition, signal);
|
|
3822
|
-
return await work(api, signal);
|
|
3823
|
-
} finally {
|
|
3824
|
-
if (borrowed) {
|
|
3825
|
-
await withMutex(async () => {
|
|
3826
|
-
borrowers -= 1;
|
|
3827
|
-
if (borrowers === 0) scheduleIdle();
|
|
3828
|
-
});
|
|
3829
|
-
}
|
|
3830
|
-
}
|
|
3831
|
-
})();
|
|
3832
|
-
requests.add(request);
|
|
3833
|
-
void request.then(
|
|
3834
|
-
() => requests.delete(request),
|
|
3835
|
-
() => requests.delete(request)
|
|
3836
|
-
);
|
|
3837
|
-
return request;
|
|
3838
|
-
},
|
|
3839
|
-
dispose() {
|
|
3840
|
-
if (disposal) return disposal;
|
|
3841
|
-
disposed = true;
|
|
3842
|
-
clearIdle();
|
|
3843
|
-
lifetime.abort(new Error("OpenCode text generation has been disposed."));
|
|
3844
|
-
const work = (async () => {
|
|
3845
|
-
let drainError;
|
|
3846
|
-
try {
|
|
3847
|
-
await within(Promise.allSettled(requests), REQUEST_DRAIN_TIMEOUT_MS);
|
|
3848
|
-
} catch (cause) {
|
|
3849
|
-
drainError = cause;
|
|
3850
|
-
}
|
|
3851
|
-
try {
|
|
3852
|
-
await within(withMutex(close), SERVER_CLOSE_TIMEOUT_MS);
|
|
3853
|
-
} catch (cause) {
|
|
3854
|
-
if (drainError) throw new OperationCleanupError2([drainError, cause]);
|
|
3855
|
-
if (isOperationCleanupError2(cause)) throw cause;
|
|
3856
|
-
throw new OperationCleanupError2([cause]);
|
|
3857
|
-
}
|
|
3858
|
-
if (drainError) throw new OperationCleanupError2([drainError]);
|
|
3859
|
-
})();
|
|
3860
|
-
disposal = work;
|
|
3861
|
-
void disposal.catch(() => {
|
|
3862
|
-
disposal = void 0;
|
|
3863
|
-
});
|
|
3864
|
-
return disposal;
|
|
3865
|
-
}
|
|
3866
|
-
};
|
|
3867
|
-
}
|
|
3656
|
+
// ../../packages/ycodium-text-generation/src/structuredTextGeneration.ts
|
|
3657
|
+
import { isOperationCleanupError as isOperationCleanupError2 } from "@ycodium-ai/plugin-api/process-operation";
|
|
3868
3658
|
|
|
3869
|
-
// src/
|
|
3659
|
+
// ../../packages/ycodium-text-generation/src/sanitize.ts
|
|
3870
3660
|
function limitSection(value, maxChars) {
|
|
3871
3661
|
if (value.length <= maxChars) return value;
|
|
3872
3662
|
const truncated = value.slice(0, maxChars);
|
|
@@ -3929,18 +3719,6 @@ function sanitizeThreadTitle(raw) {
|
|
|
3929
3719
|
}
|
|
3930
3720
|
return `${normalized.slice(0, MAX_THREAD_TITLE_CHARS - 3).trimEnd()}...`;
|
|
3931
3721
|
}
|
|
3932
|
-
function sanitizeBranchFragment(raw) {
|
|
3933
|
-
const normalized = raw.trim().toLowerCase().replace(/['"`]/g, "").replace(/^[./\s_-]+|[./\s_-]+$/g, "");
|
|
3934
|
-
const branchFragment = normalized.replace(/[^a-z0-9/_-]+/g, "-").replace(/\/+/g, "/").replace(/-+/g, "-").replace(/^[./_-]+|[./_-]+$/g, "").slice(0, 64).replace(/[./_-]+$/g, "");
|
|
3935
|
-
return branchFragment.length > 0 ? branchFragment : "update";
|
|
3936
|
-
}
|
|
3937
|
-
function sanitizeFeatureBranchName(raw) {
|
|
3938
|
-
const sanitized = sanitizeBranchFragment(raw);
|
|
3939
|
-
if (sanitized.includes("/")) {
|
|
3940
|
-
return sanitized.startsWith("feature/") ? sanitized : `feature/${sanitized}`;
|
|
3941
|
-
}
|
|
3942
|
-
return `feature/${sanitized}`;
|
|
3943
|
-
}
|
|
3944
3722
|
function normalizeCliError(cliName, error, fallback) {
|
|
3945
3723
|
if (error instanceof Error) {
|
|
3946
3724
|
const lower = error.message.toLowerCase();
|
|
@@ -3951,13 +3729,44 @@ function normalizeCliError(cliName, error, fallback) {
|
|
|
3951
3729
|
}
|
|
3952
3730
|
return new Error(fallback);
|
|
3953
3731
|
}
|
|
3954
|
-
|
|
3955
|
-
|
|
3956
|
-
|
|
3957
|
-
|
|
3958
|
-
|
|
3959
|
-
|
|
3960
|
-
|
|
3732
|
+
function extractJsonObject(raw) {
|
|
3733
|
+
const trimmed = raw.trim();
|
|
3734
|
+
if (trimmed.length === 0) return trimmed;
|
|
3735
|
+
const start = trimmed.indexOf("{");
|
|
3736
|
+
if (start < 0) return trimmed;
|
|
3737
|
+
let depth = 0;
|
|
3738
|
+
let inString = false;
|
|
3739
|
+
let escaping = false;
|
|
3740
|
+
for (let index = start; index < trimmed.length; index += 1) {
|
|
3741
|
+
const char = trimmed[index];
|
|
3742
|
+
if (inString) {
|
|
3743
|
+
if (escaping) escaping = false;
|
|
3744
|
+
else if (char === "\\") escaping = true;
|
|
3745
|
+
else if (char === '"') inString = false;
|
|
3746
|
+
continue;
|
|
3747
|
+
}
|
|
3748
|
+
if (char === '"') {
|
|
3749
|
+
inString = true;
|
|
3750
|
+
continue;
|
|
3751
|
+
}
|
|
3752
|
+
if (char === "{") {
|
|
3753
|
+
depth += 1;
|
|
3754
|
+
continue;
|
|
3755
|
+
}
|
|
3756
|
+
if (char === "}") {
|
|
3757
|
+
depth -= 1;
|
|
3758
|
+
if (depth === 0) return trimmed.slice(start, index + 1);
|
|
3759
|
+
}
|
|
3760
|
+
}
|
|
3761
|
+
return trimmed.slice(start);
|
|
3762
|
+
}
|
|
3763
|
+
|
|
3764
|
+
// ../../packages/ycodium-text-generation/src/prompts.ts
|
|
3765
|
+
var EARLIER_CONTENT_TRUNCATION_MARKER = "[Earlier content truncated]\n\n";
|
|
3766
|
+
function policyInstruction(instruction) {
|
|
3767
|
+
const trimmed = instruction?.trim();
|
|
3768
|
+
return trimmed ? ["", "Additional instructions:", limitSection(trimmed, 4e3)] : [];
|
|
3769
|
+
}
|
|
3961
3770
|
var COMMIT_MESSAGE_SCHEMA = {
|
|
3962
3771
|
type: "object",
|
|
3963
3772
|
properties: {
|
|
@@ -4226,13 +4035,358 @@ function buildHandoverSummaryPrompt(input) {
|
|
|
4226
4035
|
return { prompt, outputSchema: HANDOVER_SUMMARY_SCHEMA };
|
|
4227
4036
|
}
|
|
4228
4037
|
|
|
4038
|
+
// ../../packages/ycodium-text-generation/src/branchName.ts
|
|
4039
|
+
function sanitizeBranchFragment(raw) {
|
|
4040
|
+
const normalized = raw.trim().toLowerCase().replace(/['"`]/g, "").replace(/^[./\s_-]+|[./\s_-]+$/g, "");
|
|
4041
|
+
const branchFragment = normalized.replace(/[^a-z0-9/_-]+/g, "-").replace(/\/+/g, "/").replace(/-+/g, "-").replace(/^[./_-]+|[./_-]+$/g, "").slice(0, 64).replace(/[./_-]+$/g, "");
|
|
4042
|
+
return branchFragment.length > 0 ? branchFragment : "update";
|
|
4043
|
+
}
|
|
4044
|
+
function sanitizeFeatureBranchName(raw) {
|
|
4045
|
+
const sanitized = sanitizeBranchFragment(raw);
|
|
4046
|
+
if (sanitized.includes("/")) {
|
|
4047
|
+
return sanitized.startsWith("feature/") ? sanitized : `feature/${sanitized}`;
|
|
4048
|
+
}
|
|
4049
|
+
return `feature/${sanitized}`;
|
|
4050
|
+
}
|
|
4051
|
+
|
|
4052
|
+
// ../../packages/ycodium-text-generation/src/structuredTextGeneration.ts
|
|
4053
|
+
var FAILURE_MESSAGES = {
|
|
4054
|
+
generateCommitMessage: "Failed to generate commit message",
|
|
4055
|
+
generatePrContent: "Failed to generate change request content",
|
|
4056
|
+
generateBranchName: "Failed to generate branch name",
|
|
4057
|
+
generateThreadTitle: "Failed to generate thread title",
|
|
4058
|
+
summarizeHandover: "Failed to summarize handover"
|
|
4059
|
+
};
|
|
4060
|
+
function isRecord3(value) {
|
|
4061
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
4062
|
+
}
|
|
4063
|
+
function readString3(value) {
|
|
4064
|
+
return typeof value === "string" ? value : "";
|
|
4065
|
+
}
|
|
4066
|
+
function optionalString(value) {
|
|
4067
|
+
return typeof value === "string" ? value : void 0;
|
|
4068
|
+
}
|
|
4069
|
+
function readPolicy(value) {
|
|
4070
|
+
if (!isRecord3(value)) return void 0;
|
|
4071
|
+
const commitInstructions = optionalString(value["commitInstructions"]);
|
|
4072
|
+
const changeRequestInstructions = optionalString(value["changeRequestInstructions"]);
|
|
4073
|
+
const branchInstructions = optionalString(value["branchInstructions"]);
|
|
4074
|
+
const threadTitleInstructions = optionalString(value["threadTitleInstructions"]);
|
|
4075
|
+
return {
|
|
4076
|
+
...commitInstructions === void 0 ? {} : { commitInstructions },
|
|
4077
|
+
...changeRequestInstructions === void 0 ? {} : { changeRequestInstructions },
|
|
4078
|
+
...branchInstructions === void 0 ? {} : { branchInstructions },
|
|
4079
|
+
...threadTitleInstructions === void 0 ? {} : { threadTitleInstructions }
|
|
4080
|
+
};
|
|
4081
|
+
}
|
|
4082
|
+
function promptAttachments(attachments) {
|
|
4083
|
+
return attachments.filter(isRecord3).map((attachment) => ({
|
|
4084
|
+
name: optionalString(attachment["name"]) ?? "attachment",
|
|
4085
|
+
mimeType: optionalString(attachment["mimeType"]) ?? "application/octet-stream",
|
|
4086
|
+
sizeBytes: typeof attachment["sizeBytes"] === "number" ? attachment["sizeBytes"] : 0
|
|
4087
|
+
}));
|
|
4088
|
+
}
|
|
4089
|
+
function createStructuredTextGeneration(options) {
|
|
4090
|
+
const generate = async (operation, raw, signal, produce) => {
|
|
4091
|
+
try {
|
|
4092
|
+
if (!isRecord3(raw) && options.invalidInput !== void 0) {
|
|
4093
|
+
throw options.invalidInput(operation);
|
|
4094
|
+
}
|
|
4095
|
+
const input = isRecord3(raw) ? raw : {};
|
|
4096
|
+
return await produce(
|
|
4097
|
+
input,
|
|
4098
|
+
(request) => options.run({
|
|
4099
|
+
...request,
|
|
4100
|
+
operation,
|
|
4101
|
+
cwd: readString3(input["cwd"]) || ".",
|
|
4102
|
+
modelSelection: input["modelSelection"],
|
|
4103
|
+
...signal === void 0 ? {} : { signal }
|
|
4104
|
+
})
|
|
4105
|
+
);
|
|
4106
|
+
} catch (error) {
|
|
4107
|
+
if (options.cliName === void 0 || isOperationCleanupError2(error)) throw error;
|
|
4108
|
+
throw normalizeCliError(options.cliName, error, FAILURE_MESSAGES[operation]);
|
|
4109
|
+
}
|
|
4110
|
+
};
|
|
4111
|
+
return {
|
|
4112
|
+
generateCommitMessage: (raw, signal) => generate("generateCommitMessage", raw, signal, async (input, run) => {
|
|
4113
|
+
const includeBranch = input["includeBranch"] === true;
|
|
4114
|
+
const policy = readPolicy(input["policy"]);
|
|
4115
|
+
const { prompt, outputSchema } = buildCommitMessagePrompt({
|
|
4116
|
+
branch: optionalString(input["branch"]) ?? null,
|
|
4117
|
+
stagedSummary: readString3(input["stagedSummary"]),
|
|
4118
|
+
stagedPatch: readString3(input["stagedPatch"]),
|
|
4119
|
+
includeBranch,
|
|
4120
|
+
...policy === void 0 ? {} : { policy }
|
|
4121
|
+
});
|
|
4122
|
+
const generated = await run({
|
|
4123
|
+
prompt,
|
|
4124
|
+
outputSchema,
|
|
4125
|
+
schemaKeys: includeBranch ? ["subject", "body", "branch"] : ["subject", "body"],
|
|
4126
|
+
attachments: []
|
|
4127
|
+
});
|
|
4128
|
+
return {
|
|
4129
|
+
subject: sanitizeCommitSubject(readString3(generated["subject"])),
|
|
4130
|
+
body: readString3(generated["body"]).trim(),
|
|
4131
|
+
...typeof generated["branch"] === "string" ? { branch: sanitizeFeatureBranchName(generated["branch"]) } : {}
|
|
4132
|
+
};
|
|
4133
|
+
}),
|
|
4134
|
+
generatePrContent: (raw, signal) => generate("generatePrContent", raw, signal, async (input, run) => {
|
|
4135
|
+
const changeRequestTemplate = optionalString(input["changeRequestTemplate"]);
|
|
4136
|
+
const policy = readPolicy(input["policy"]);
|
|
4137
|
+
const { prompt, outputSchema } = buildPrContentPrompt({
|
|
4138
|
+
baseBranch: readString3(input["baseBranch"]),
|
|
4139
|
+
headBranch: readString3(input["headBranch"]),
|
|
4140
|
+
commitSummary: readString3(input["commitSummary"]),
|
|
4141
|
+
diffSummary: readString3(input["diffSummary"]),
|
|
4142
|
+
diffPatch: readString3(input["diffPatch"]),
|
|
4143
|
+
...changeRequestTemplate === void 0 ? {} : { changeRequestTemplate },
|
|
4144
|
+
...policy === void 0 ? {} : { policy }
|
|
4145
|
+
});
|
|
4146
|
+
const generated = await run({
|
|
4147
|
+
prompt,
|
|
4148
|
+
outputSchema,
|
|
4149
|
+
schemaKeys: ["title", "body"],
|
|
4150
|
+
attachments: []
|
|
4151
|
+
});
|
|
4152
|
+
return {
|
|
4153
|
+
title: sanitizePrTitle(readString3(generated["title"])),
|
|
4154
|
+
body: readString3(generated["body"]).trim()
|
|
4155
|
+
};
|
|
4156
|
+
}),
|
|
4157
|
+
generateBranchName: (raw, signal) => generate("generateBranchName", raw, signal, async (input, run) => {
|
|
4158
|
+
const attachments = Array.isArray(input["attachments"]) ? input["attachments"] : [];
|
|
4159
|
+
const policy = readPolicy(input["policy"]);
|
|
4160
|
+
const { prompt, outputSchema } = buildBranchNamePrompt({
|
|
4161
|
+
message: readString3(input["message"]),
|
|
4162
|
+
attachments: promptAttachments(attachments),
|
|
4163
|
+
...policy === void 0 ? {} : { policy }
|
|
4164
|
+
});
|
|
4165
|
+
const generated = await run({
|
|
4166
|
+
prompt,
|
|
4167
|
+
outputSchema,
|
|
4168
|
+
schemaKeys: ["branch"],
|
|
4169
|
+
attachments
|
|
4170
|
+
});
|
|
4171
|
+
return { branch: sanitizeBranchFragment(readString3(generated["branch"])) };
|
|
4172
|
+
}),
|
|
4173
|
+
generateThreadTitle: (raw, signal) => generate("generateThreadTitle", raw, signal, async (input, run) => {
|
|
4174
|
+
const attachments = Array.isArray(input["attachments"]) ? input["attachments"] : [];
|
|
4175
|
+
const linkedContext = optionalString(input["linkedContext"]);
|
|
4176
|
+
const previousTitle = optionalString(input["previousTitle"]);
|
|
4177
|
+
const policy = readPolicy(input["policy"]);
|
|
4178
|
+
const { prompt, outputSchema } = buildThreadTitlePrompt({
|
|
4179
|
+
message: readString3(input["message"]),
|
|
4180
|
+
...linkedContext ? { linkedContext } : {},
|
|
4181
|
+
...previousTitle === void 0 ? {} : { previousTitle },
|
|
4182
|
+
attachments: promptAttachments(attachments),
|
|
4183
|
+
...policy === void 0 ? {} : { policy }
|
|
4184
|
+
});
|
|
4185
|
+
const generated = await run({
|
|
4186
|
+
prompt,
|
|
4187
|
+
outputSchema,
|
|
4188
|
+
schemaKeys: ["title"],
|
|
4189
|
+
attachments
|
|
4190
|
+
});
|
|
4191
|
+
return {
|
|
4192
|
+
title: sanitizeThreadTitle(readString3(generated["title"])),
|
|
4193
|
+
...generated["needsRefinement"] === true ? { needsRefinement: true } : {}
|
|
4194
|
+
};
|
|
4195
|
+
}),
|
|
4196
|
+
summarizeHandover: (raw, signal) => generate("summarizeHandover", raw, signal, async (input, run) => {
|
|
4197
|
+
const { prompt, outputSchema } = buildHandoverSummaryPrompt({
|
|
4198
|
+
transcript: readString3(input["transcript"])
|
|
4199
|
+
});
|
|
4200
|
+
const generated = await run({
|
|
4201
|
+
prompt,
|
|
4202
|
+
outputSchema,
|
|
4203
|
+
schemaKeys: ["summary"],
|
|
4204
|
+
attachments: []
|
|
4205
|
+
});
|
|
4206
|
+
return { summary: readString3(generated["summary"]).trim() };
|
|
4207
|
+
})
|
|
4208
|
+
};
|
|
4209
|
+
}
|
|
4210
|
+
|
|
4211
|
+
// src/textGenerationServer.ts
|
|
4212
|
+
import { raceAbort } from "@ycodium-ai/plugin-api/executor";
|
|
4213
|
+
import {
|
|
4214
|
+
OperationCleanupError as OperationCleanupError2,
|
|
4215
|
+
isOperationCleanupError as isOperationCleanupError3
|
|
4216
|
+
} from "@ycodium-ai/plugin-api/process-operation";
|
|
4217
|
+
var IDLE_TTL_MS = 3e4;
|
|
4218
|
+
var REQUEST_DRAIN_TIMEOUT_MS = 3e3;
|
|
4219
|
+
var SERVER_CLOSE_TIMEOUT_MS = 2e3;
|
|
4220
|
+
async function within(work, milliseconds) {
|
|
4221
|
+
let timer;
|
|
4222
|
+
try {
|
|
4223
|
+
return await Promise.race([
|
|
4224
|
+
work,
|
|
4225
|
+
new Promise((_resolve, reject) => {
|
|
4226
|
+
timer = setTimeout(
|
|
4227
|
+
() => reject(new Error("OpenCode text generation disposal timed out.")),
|
|
4228
|
+
milliseconds
|
|
4229
|
+
);
|
|
4230
|
+
})
|
|
4231
|
+
]);
|
|
4232
|
+
} finally {
|
|
4233
|
+
clearTimeout(timer);
|
|
4234
|
+
}
|
|
4235
|
+
}
|
|
4236
|
+
function createTextGenerationServer(recipe, host) {
|
|
4237
|
+
let handle;
|
|
4238
|
+
let starting;
|
|
4239
|
+
let client;
|
|
4240
|
+
let binaryPath;
|
|
4241
|
+
let borrowers = 0;
|
|
4242
|
+
let idleTimer;
|
|
4243
|
+
let mutex = Promise.resolve();
|
|
4244
|
+
let disposed = false;
|
|
4245
|
+
let disposal;
|
|
4246
|
+
const lifetime = new AbortController();
|
|
4247
|
+
const requests = /* @__PURE__ */ new Set();
|
|
4248
|
+
const withMutex = async (work) => {
|
|
4249
|
+
const previous = mutex;
|
|
4250
|
+
const next = Promise.withResolvers();
|
|
4251
|
+
mutex = next.promise;
|
|
4252
|
+
await previous;
|
|
4253
|
+
try {
|
|
4254
|
+
return await work();
|
|
4255
|
+
} finally {
|
|
4256
|
+
next.resolve();
|
|
4257
|
+
}
|
|
4258
|
+
};
|
|
4259
|
+
const clearIdle = () => {
|
|
4260
|
+
clearTimeout(idleTimer);
|
|
4261
|
+
idleTimer = void 0;
|
|
4262
|
+
};
|
|
4263
|
+
const close = async () => {
|
|
4264
|
+
clearIdle();
|
|
4265
|
+
try {
|
|
4266
|
+
if (handle && !handle.external) await closeOpenCodeServer(handle);
|
|
4267
|
+
if (starting) await closeOpenCodeServer(starting);
|
|
4268
|
+
} catch (cause) {
|
|
4269
|
+
if (isOperationCleanupError3(cause)) throw cause;
|
|
4270
|
+
throw new OperationCleanupError2([cause]);
|
|
4271
|
+
}
|
|
4272
|
+
handle = void 0;
|
|
4273
|
+
starting = void 0;
|
|
4274
|
+
client = void 0;
|
|
4275
|
+
binaryPath = void 0;
|
|
4276
|
+
};
|
|
4277
|
+
const scheduleIdle = () => {
|
|
4278
|
+
clearIdle();
|
|
4279
|
+
if (disposed || recipe.serverUrl.trim()) return;
|
|
4280
|
+
idleTimer = setTimeout(() => {
|
|
4281
|
+
void withMutex(async () => {
|
|
4282
|
+
if (!disposed && borrowers === 0) await close();
|
|
4283
|
+
}).catch((error) => {
|
|
4284
|
+
host.log.warn("Could not close the idle OpenCode text generation server", {
|
|
4285
|
+
error: String(error)
|
|
4286
|
+
});
|
|
4287
|
+
});
|
|
4288
|
+
}, IDLE_TTL_MS);
|
|
4289
|
+
};
|
|
4290
|
+
return {
|
|
4291
|
+
withClient(input, work) {
|
|
4292
|
+
if (disposed) return Promise.reject(new Error("OpenCode text generation has been disposed."));
|
|
4293
|
+
const signal = AbortSignal.any([
|
|
4294
|
+
lifetime.signal,
|
|
4295
|
+
...input.signal === void 0 ? [] : [input.signal]
|
|
4296
|
+
]);
|
|
4297
|
+
const request = (async () => {
|
|
4298
|
+
let borrowed = false;
|
|
4299
|
+
const acquisition = withMutex(async () => {
|
|
4300
|
+
signal.throwIfAborted();
|
|
4301
|
+
clearIdle();
|
|
4302
|
+
if (starting) await close();
|
|
4303
|
+
const program = recipe.binaryPath.trim() || "opencode";
|
|
4304
|
+
if (client && binaryPath !== program && borrowers === 0 && !handle?.external)
|
|
4305
|
+
await close();
|
|
4306
|
+
if (!client) {
|
|
4307
|
+
const startup = new AbortController();
|
|
4308
|
+
const abortStartup = () => startup.abort(lifetime.signal.reason);
|
|
4309
|
+
lifetime.signal.addEventListener("abort", abortStartup, { once: true });
|
|
4310
|
+
if (lifetime.signal.aborted) abortStartup();
|
|
4311
|
+
try {
|
|
4312
|
+
handle = await connectToOpenCodeServer({
|
|
4313
|
+
host,
|
|
4314
|
+
recipe,
|
|
4315
|
+
directory: input.cwd,
|
|
4316
|
+
program,
|
|
4317
|
+
signal: startup.signal,
|
|
4318
|
+
onSpawn: (resource) => {
|
|
4319
|
+
starting = resource;
|
|
4320
|
+
}
|
|
4321
|
+
});
|
|
4322
|
+
starting = void 0;
|
|
4323
|
+
} finally {
|
|
4324
|
+
lifetime.signal.removeEventListener("abort", abortStartup);
|
|
4325
|
+
}
|
|
4326
|
+
binaryPath = program;
|
|
4327
|
+
client = createOpenCodeApi({ url: handle.url, password: handle.password });
|
|
4328
|
+
}
|
|
4329
|
+
if (signal.aborted) {
|
|
4330
|
+
scheduleIdle();
|
|
4331
|
+
signal.throwIfAborted();
|
|
4332
|
+
}
|
|
4333
|
+
borrowers += 1;
|
|
4334
|
+
borrowed = true;
|
|
4335
|
+
return client;
|
|
4336
|
+
});
|
|
4337
|
+
try {
|
|
4338
|
+
const api = await raceAbort(acquisition, signal);
|
|
4339
|
+
return await work(api, signal);
|
|
4340
|
+
} finally {
|
|
4341
|
+
if (borrowed) {
|
|
4342
|
+
await withMutex(async () => {
|
|
4343
|
+
borrowers -= 1;
|
|
4344
|
+
if (borrowers === 0) scheduleIdle();
|
|
4345
|
+
});
|
|
4346
|
+
}
|
|
4347
|
+
}
|
|
4348
|
+
})();
|
|
4349
|
+
requests.add(request);
|
|
4350
|
+
void request.then(
|
|
4351
|
+
() => requests.delete(request),
|
|
4352
|
+
() => requests.delete(request)
|
|
4353
|
+
);
|
|
4354
|
+
return request;
|
|
4355
|
+
},
|
|
4356
|
+
dispose() {
|
|
4357
|
+
if (disposal) return disposal;
|
|
4358
|
+
disposed = true;
|
|
4359
|
+
clearIdle();
|
|
4360
|
+
lifetime.abort(new Error("OpenCode text generation has been disposed."));
|
|
4361
|
+
const work = (async () => {
|
|
4362
|
+
let drainError;
|
|
4363
|
+
try {
|
|
4364
|
+
await within(Promise.allSettled(requests), REQUEST_DRAIN_TIMEOUT_MS);
|
|
4365
|
+
} catch (cause) {
|
|
4366
|
+
drainError = cause;
|
|
4367
|
+
}
|
|
4368
|
+
try {
|
|
4369
|
+
await within(withMutex(close), SERVER_CLOSE_TIMEOUT_MS);
|
|
4370
|
+
} catch (cause) {
|
|
4371
|
+
if (drainError) throw new OperationCleanupError2([drainError, cause]);
|
|
4372
|
+
if (isOperationCleanupError3(cause)) throw cause;
|
|
4373
|
+
throw new OperationCleanupError2([cause]);
|
|
4374
|
+
}
|
|
4375
|
+
if (drainError) throw new OperationCleanupError2([drainError]);
|
|
4376
|
+
})();
|
|
4377
|
+
disposal = work;
|
|
4378
|
+
void disposal.catch(() => {
|
|
4379
|
+
disposal = void 0;
|
|
4380
|
+
});
|
|
4381
|
+
return disposal;
|
|
4382
|
+
}
|
|
4383
|
+
};
|
|
4384
|
+
}
|
|
4385
|
+
|
|
4229
4386
|
// src/textGeneration.ts
|
|
4230
4387
|
var DENY_ALL_PERMISSIONS = [
|
|
4231
4388
|
{ action: "*", resource: "*", effect: "deny" }
|
|
4232
4389
|
];
|
|
4233
|
-
function readString3(value) {
|
|
4234
|
-
return typeof value === "string" ? value : "";
|
|
4235
|
-
}
|
|
4236
4390
|
function asRecord(value, operation) {
|
|
4237
4391
|
if (!isRecord2(value)) {
|
|
4238
4392
|
throw new Error(`${operation}: OpenCode returned invalid structured output.`);
|
|
@@ -4297,133 +4451,34 @@ function createOpenCodeTextGeneration(recipe, host) {
|
|
|
4297
4451
|
};
|
|
4298
4452
|
return {
|
|
4299
4453
|
dispose: shared.dispose,
|
|
4300
|
-
|
|
4301
|
-
|
|
4302
|
-
|
|
4303
|
-
|
|
4304
|
-
|
|
4305
|
-
|
|
4306
|
-
|
|
4307
|
-
|
|
4308
|
-
|
|
4309
|
-
|
|
4310
|
-
|
|
4311
|
-
|
|
4312
|
-
|
|
4313
|
-
|
|
4314
|
-
|
|
4315
|
-
|
|
4316
|
-
|
|
4317
|
-
|
|
4318
|
-
|
|
4319
|
-
|
|
4320
|
-
|
|
4321
|
-
|
|
4322
|
-
|
|
4323
|
-
|
|
4324
|
-
|
|
4325
|
-
|
|
4326
|
-
|
|
4327
|
-
|
|
4328
|
-
},
|
|
4329
|
-
generatePrContent: async (raw, signal) => {
|
|
4330
|
-
try {
|
|
4331
|
-
const input = asRecord(raw, "generatePrContent");
|
|
4332
|
-
const { prompt } = buildPrContentPrompt({
|
|
4333
|
-
baseBranch: readString3(input["baseBranch"]),
|
|
4334
|
-
headBranch: readString3(input["headBranch"]),
|
|
4335
|
-
commitSummary: readString3(input["commitSummary"]),
|
|
4336
|
-
diffSummary: readString3(input["diffSummary"]),
|
|
4337
|
-
diffPatch: readString3(input["diffPatch"]),
|
|
4338
|
-
...typeof input["changeRequestTemplate"] === "string" ? { changeRequestTemplate: input["changeRequestTemplate"] } : {},
|
|
4339
|
-
...isRecord2(input["policy"]) ? { policy: input["policy"] } : {}
|
|
4340
|
-
});
|
|
4341
|
-
const generated = await runOpenCodeJson({
|
|
4342
|
-
operation: "generatePrContent",
|
|
4343
|
-
cwd: readString3(input["cwd"]) || ".",
|
|
4344
|
-
prompt,
|
|
4345
|
-
schemaKeys: ["title", "body"],
|
|
4346
|
-
modelSelection: input["modelSelection"],
|
|
4347
|
-
...signal === void 0 ? {} : { signal }
|
|
4348
|
-
});
|
|
4349
|
-
return {
|
|
4350
|
-
title: sanitizePrTitle(readString3(generated["title"])),
|
|
4351
|
-
body: readString3(generated["body"]).trim()
|
|
4352
|
-
};
|
|
4353
|
-
} catch (error) {
|
|
4354
|
-
if (isOperationCleanupError3(error)) throw error;
|
|
4355
|
-
throw normalizeCliError("opencode", error, "Failed to generate change request content");
|
|
4356
|
-
}
|
|
4357
|
-
},
|
|
4358
|
-
generateBranchName: async (raw, signal) => {
|
|
4359
|
-
try {
|
|
4360
|
-
const input = asRecord(raw, "generateBranchName");
|
|
4361
|
-
const { prompt } = buildBranchNamePrompt({
|
|
4362
|
-
message: readString3(input["message"]),
|
|
4363
|
-
...Array.isArray(input["attachments"]) ? { attachments: input["attachments"] } : {},
|
|
4364
|
-
...isRecord2(input["policy"]) ? { policy: input["policy"] } : {}
|
|
4365
|
-
});
|
|
4366
|
-
const generated = await runOpenCodeJson({
|
|
4367
|
-
operation: "generateBranchName",
|
|
4368
|
-
cwd: readString3(input["cwd"]) || ".",
|
|
4369
|
-
prompt,
|
|
4370
|
-
schemaKeys: ["branch"],
|
|
4371
|
-
modelSelection: input["modelSelection"],
|
|
4372
|
-
...signal === void 0 ? {} : { signal }
|
|
4373
|
-
});
|
|
4374
|
-
return { branch: sanitizeBranchFragment(readString3(generated["branch"])) };
|
|
4375
|
-
} catch (error) {
|
|
4376
|
-
if (isOperationCleanupError3(error)) throw error;
|
|
4377
|
-
throw normalizeCliError("opencode", error, "Failed to generate branch name");
|
|
4378
|
-
}
|
|
4379
|
-
},
|
|
4380
|
-
generateThreadTitle: async (raw, signal) => {
|
|
4381
|
-
try {
|
|
4382
|
-
const input = asRecord(raw, "generateThreadTitle");
|
|
4383
|
-
const { prompt } = buildThreadTitlePrompt({
|
|
4384
|
-
message: readString3(input["message"]),
|
|
4385
|
-
...typeof input["linkedContext"] === "string" && input["linkedContext"].length > 0 ? { linkedContext: input["linkedContext"] } : {},
|
|
4386
|
-
...typeof input["previousTitle"] === "string" ? { previousTitle: input["previousTitle"] } : {},
|
|
4387
|
-
...Array.isArray(input["attachments"]) ? { attachments: input["attachments"] } : {},
|
|
4388
|
-
...isRecord2(input["policy"]) ? { policy: input["policy"] } : {}
|
|
4389
|
-
});
|
|
4390
|
-
const generated = await runOpenCodeJson({
|
|
4391
|
-
operation: "generateThreadTitle",
|
|
4392
|
-
cwd: readString3(input["cwd"]) || ".",
|
|
4393
|
-
prompt,
|
|
4394
|
-
schemaKeys: ["title"],
|
|
4395
|
-
modelSelection: input["modelSelection"],
|
|
4396
|
-
...signal === void 0 ? {} : { signal }
|
|
4397
|
-
});
|
|
4398
|
-
return {
|
|
4399
|
-
title: sanitizeThreadTitle(readString3(generated["title"])),
|
|
4400
|
-
...generated["needsRefinement"] === true ? { needsRefinement: true } : {}
|
|
4401
|
-
};
|
|
4402
|
-
} catch (error) {
|
|
4403
|
-
if (isOperationCleanupError3(error)) throw error;
|
|
4404
|
-
throw normalizeCliError("opencode", error, "Failed to generate thread title");
|
|
4405
|
-
}
|
|
4406
|
-
},
|
|
4407
|
-
summarizeHandover: async (raw, signal) => {
|
|
4408
|
-
try {
|
|
4409
|
-
const input = asRecord(raw, "summarizeHandover");
|
|
4410
|
-
const { prompt } = buildHandoverSummaryPrompt({
|
|
4411
|
-
transcript: readString3(input["transcript"])
|
|
4412
|
-
});
|
|
4413
|
-
const generated = await runOpenCodeJson({
|
|
4414
|
-
operation: "summarizeHandover",
|
|
4415
|
-
cwd: readString3(input["cwd"]) || ".",
|
|
4416
|
-
prompt,
|
|
4417
|
-
schemaKeys: ["summary"],
|
|
4418
|
-
modelSelection: input["modelSelection"],
|
|
4419
|
-
...signal === void 0 ? {} : { signal }
|
|
4420
|
-
});
|
|
4421
|
-
return { summary: readString3(generated["summary"]).trim() };
|
|
4422
|
-
} catch (error) {
|
|
4423
|
-
if (isOperationCleanupError3(error)) throw error;
|
|
4424
|
-
throw normalizeCliError("opencode", error, "Failed to summarize handover");
|
|
4425
|
-
}
|
|
4426
|
-
}
|
|
4454
|
+
...createStructuredTextGeneration({
|
|
4455
|
+
cliName: "opencode",
|
|
4456
|
+
invalidInput: (operation) => new Error(`${operation}: OpenCode returned invalid structured output.`),
|
|
4457
|
+
run: runOpenCodeJson
|
|
4458
|
+
})
|
|
4459
|
+
};
|
|
4460
|
+
}
|
|
4461
|
+
|
|
4462
|
+
// src/eventTracking.ts
|
|
4463
|
+
function freshOpenCodeEventTracking() {
|
|
4464
|
+
return {
|
|
4465
|
+
usageByMessageId: /* @__PURE__ */ new Map(),
|
|
4466
|
+
assistantTextByPartId: /* @__PURE__ */ new Map(),
|
|
4467
|
+
completedTextParts: /* @__PURE__ */ new Set(),
|
|
4468
|
+
stepModels: /* @__PURE__ */ new Map(),
|
|
4469
|
+
toolNames: /* @__PURE__ */ new Map(),
|
|
4470
|
+
toolInputs: /* @__PURE__ */ new Map(),
|
|
4471
|
+
openShells: /* @__PURE__ */ new Map(),
|
|
4472
|
+
pendingPermissions: /* @__PURE__ */ new Map(),
|
|
4473
|
+
pendingForms: /* @__PURE__ */ new Map(),
|
|
4474
|
+
childSessionIds: /* @__PURE__ */ new Set(),
|
|
4475
|
+
subagents: createOpenCodeSubagentState(),
|
|
4476
|
+
settledRequestIds: /* @__PURE__ */ new Set(),
|
|
4477
|
+
autoRepliedRequestIds: /* @__PURE__ */ new Set(),
|
|
4478
|
+
declineReasons: /* @__PURE__ */ new Map(),
|
|
4479
|
+
declinedToolCalls: /* @__PURE__ */ new Set(),
|
|
4480
|
+
abortedByDecline: false,
|
|
4481
|
+
compaction: void 0
|
|
4427
4482
|
};
|
|
4428
4483
|
}
|
|
4429
4484
|
|
|
@@ -4630,23 +4685,7 @@ function createOpenCodeInstance(config, host, attachments, lifecycleOptions) {
|
|
|
4630
4685
|
stopped: false,
|
|
4631
4686
|
interruptGeneration: 0,
|
|
4632
4687
|
pendingInterrupts: 0,
|
|
4633
|
-
|
|
4634
|
-
assistantTextByPartId: /* @__PURE__ */ new Map(),
|
|
4635
|
-
completedTextParts: /* @__PURE__ */ new Set(),
|
|
4636
|
-
stepModels: /* @__PURE__ */ new Map(),
|
|
4637
|
-
toolNames: /* @__PURE__ */ new Map(),
|
|
4638
|
-
toolInputs: /* @__PURE__ */ new Map(),
|
|
4639
|
-
openShells: /* @__PURE__ */ new Map(),
|
|
4640
|
-
pendingPermissions: /* @__PURE__ */ new Map(),
|
|
4641
|
-
pendingForms: /* @__PURE__ */ new Map(),
|
|
4642
|
-
childSessionIds: /* @__PURE__ */ new Set(),
|
|
4643
|
-
subagents: createOpenCodeSubagentState(),
|
|
4644
|
-
settledRequestIds: /* @__PURE__ */ new Set(),
|
|
4645
|
-
autoRepliedRequestIds: /* @__PURE__ */ new Set(),
|
|
4646
|
-
declineReasons: /* @__PURE__ */ new Map(),
|
|
4647
|
-
declinedToolCalls: /* @__PURE__ */ new Set(),
|
|
4648
|
-
abortedByDecline: false,
|
|
4649
|
-
compaction: void 0,
|
|
4688
|
+
...freshOpenCodeEventTracking(),
|
|
4650
4689
|
...selection
|
|
4651
4690
|
};
|
|
4652
4691
|
await startEventPump({
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ycodium-ai/agent-opencode",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.5093",
|
|
4
4
|
"description": "OpenCode executor: OpenCode CLI (2.x) over its HTTP API.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ycodium",
|
|
@@ -21,10 +21,12 @@
|
|
|
21
21
|
"@types/node": "24.12.4",
|
|
22
22
|
"esbuild": "0.28.1",
|
|
23
23
|
"vite-plus": "0.2.2",
|
|
24
|
-
"ycodium-
|
|
24
|
+
"@ycodium-ai/plugin-api": "0.2.5093",
|
|
25
25
|
"ycodium-executor-testing": "0.0.0",
|
|
26
|
-
"
|
|
27
|
-
"ycodium-
|
|
26
|
+
"ycodium-instance-config": "0.0.0",
|
|
27
|
+
"ycodium-fetch-ports": "0.0.0",
|
|
28
|
+
"ycodium-sse-stream": "0.0.0",
|
|
29
|
+
"ycodium-text-generation": "0.0.0"
|
|
28
30
|
},
|
|
29
31
|
"ycodium": {
|
|
30
32
|
"plugin": "./dist/index.js",
|