@ycodium-ai/agent-opencode 0.2.3478 → 0.2.3502

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.
Files changed (2) hide show
  1. package/dist/index.js +339 -193
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -1258,6 +1258,10 @@ import {
1258
1258
  throwIfExecutorSpawnAborted
1259
1259
  } from "@ycodium-ai/plugin-api/executor";
1260
1260
  import { drainStderrTail } from "@ycodium-ai/plugin-api/process-stdin";
1261
+ import {
1262
+ OperationCleanupError,
1263
+ runProcessOperation
1264
+ } from "@ycodium-ai/plugin-api/process-operation";
1261
1265
 
1262
1266
  // ../../packages/ycodium-fetch-ports/src/fetchPorts.ts
1263
1267
  import * as NodeNet from "node:net";
@@ -1420,13 +1424,6 @@ function openCodeSessionSkillsConfig(skills, inherited, log) {
1420
1424
 
1421
1425
  // src/server.ts
1422
1426
  var OPENCODE_STDERR_TAIL_CHARS = 600;
1423
- async function collectText(stream) {
1424
- const chunks = [];
1425
- for await (const chunk of stream) {
1426
- chunks.push(Buffer.from(chunk));
1427
- }
1428
- return Buffer.concat(chunks).toString("utf8");
1429
- }
1430
1427
  function buildSpawnEnv(recipe, configContent, password) {
1431
1428
  const xdgHome = makeOpenCodeEnvironment(recipe.homePath, {});
1432
1429
  return mergeLaunchEnv2({
@@ -1439,23 +1436,37 @@ function buildSpawnEnv(recipe, configContent, password) {
1439
1436
  });
1440
1437
  }
1441
1438
  async function terminateOwnedProcess(handle) {
1439
+ let exited = false;
1440
+ void handle.exited.then(
1441
+ () => {
1442
+ exited = true;
1443
+ },
1444
+ () => {
1445
+ }
1446
+ );
1447
+ const term = Promise.resolve().then(() => handle.kill("SIGTERM"));
1448
+ const finished = Promise.all([term, handle.exited, handle.drained]);
1442
1449
  try {
1443
- await handle.kill("SIGTERM");
1450
+ await waitForTermination(finished, 250);
1444
1451
  } catch {
1452
+ const force = exited ? Promise.resolve() : Promise.resolve().then(() => handle.kill("SIGKILL"));
1453
+ await waitForTermination(Promise.all([term, force, handle.exited, handle.drained]), 1750);
1445
1454
  }
1455
+ }
1456
+ async function waitForTermination(work, milliseconds) {
1446
1457
  let timer;
1447
- const timed = await Promise.race([
1448
- handle.exited.then(() => "exited"),
1449
- new Promise((resolve2) => {
1450
- timer = setTimeout(() => resolve2("timeout"), 2e3);
1451
- })
1452
- ]).finally(() => clearTimeout(timer));
1453
- if (timed === "timeout") {
1454
- try {
1455
- await handle.kill("SIGKILL");
1456
- } catch {
1457
- }
1458
- await handle.exited;
1458
+ try {
1459
+ await Promise.race([
1460
+ work,
1461
+ new Promise((_resolve, reject) => {
1462
+ timer = setTimeout(
1463
+ () => reject(new Error("Could not confirm the OpenCode server exited and drained.")),
1464
+ milliseconds
1465
+ );
1466
+ })
1467
+ ]);
1468
+ } finally {
1469
+ clearTimeout(timer);
1459
1470
  }
1460
1471
  }
1461
1472
  async function spawnOpenCodeServer(input) {
@@ -1473,18 +1484,30 @@ async function spawnOpenCodeServer(input) {
1473
1484
  owner: { bindingId: input.host.bindingId },
1474
1485
  ...input.signal === void 0 ? {} : { signal: input.signal }
1475
1486
  });
1487
+ const stdoutDrained = Promise.withResolvers();
1488
+ const stderrDrained = Promise.withResolvers();
1476
1489
  const processHandle = {
1477
1490
  kill: spawned.kill,
1478
1491
  exited: spawned.exited,
1479
1492
  pid: spawned.pid,
1480
1493
  program: input.program,
1481
- args
1494
+ args,
1495
+ drained: Promise.all([stdoutDrained.promise, stderrDrained.promise]).then(() => {
1496
+ })
1482
1497
  };
1483
1498
  input.onSpawn?.({ external: false, process: processHandle });
1484
1499
  const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
1485
1500
  let stdoutText = "";
1486
1501
  const stdoutDecoder = new TextDecoder();
1487
- const stderrTail = drainStderrTail(spawned.stderr);
1502
+ const stderrTail = drainStderrTail({
1503
+ async *[Symbol.asyncIterator]() {
1504
+ try {
1505
+ yield* spawned.stderr;
1506
+ } finally {
1507
+ stderrDrained.resolve();
1508
+ }
1509
+ }
1510
+ });
1488
1511
  const startupOutput = async () => `stdout=${stdoutText.trim()} stderr=${(await stderrTail()).slice(-OPENCODE_STDERR_TAIL_CHARS)}`;
1489
1512
  let settled = false;
1490
1513
  const url = await new Promise((resolve2, reject) => {
@@ -1515,13 +1538,19 @@ async function spawnOpenCodeServer(input) {
1515
1538
  if (!settled) await failWithOutput("OpenCode server exited before becoming ready.");
1516
1539
  } catch (cause) {
1517
1540
  fail(cause);
1541
+ } finally {
1542
+ stdoutDrained.resolve();
1518
1543
  }
1519
1544
  })();
1520
1545
  void spawned.exited.then((code) => {
1521
1546
  if (!settled) void failWithOutput(`OpenCode server exited with code ${code}.`);
1522
1547
  }, fail);
1523
1548
  }).catch(async (cause) => {
1524
- await terminateOwnedProcess(processHandle);
1549
+ try {
1550
+ await terminateOwnedProcess(processHandle);
1551
+ } catch (cleanupError) {
1552
+ throw new OperationCleanupError([cause, cleanupError]);
1553
+ }
1525
1554
  throw cause;
1526
1555
  });
1527
1556
  return {
@@ -1630,35 +1659,15 @@ async function closeOpenCodeServer(handle) {
1630
1659
  await terminateOwnedProcess(handle.process);
1631
1660
  }
1632
1661
  async function runOpenCodeCommand(input) {
1633
- const env = buildSpawnEnv(input.recipe);
1634
- const spawned = await input.host.process.spawn({
1662
+ return runProcessOperation(input.host, {
1635
1663
  program: input.program,
1636
1664
  args: [...input.args],
1637
- env,
1665
+ env: buildSpawnEnv(input.recipe),
1638
1666
  owner: { bindingId: input.host.bindingId },
1667
+ timeoutMs: input.timeoutMs,
1668
+ cleanupTimeoutMs: 2e3,
1639
1669
  ...input.signal === void 0 ? {} : { signal: input.signal }
1640
1670
  });
1641
- const collected = Promise.all([
1642
- collectText(spawned.stdout),
1643
- collectText(spawned.stderr),
1644
- spawned.exited
1645
- ]);
1646
- let timer;
1647
- const timedOut = new Promise((resolve2) => {
1648
- timer = setTimeout(() => resolve2("timeout"), input.timeoutMs);
1649
- });
1650
- try {
1651
- const settled = await Promise.race([collected, timedOut]);
1652
- if (settled === "timeout") {
1653
- collected.catch(() => void 0);
1654
- await spawned.kill("SIGKILL").catch(() => void 0);
1655
- throw new Error(`OpenCode CLI ${input.args.join(" ")} timed out after ${input.timeoutMs}ms.`);
1656
- }
1657
- const [stdout, stderr, exitCode] = settled;
1658
- return { stdout, stderr, exitCode };
1659
- } finally {
1660
- clearTimeout(timer);
1661
- }
1662
1671
  }
1663
1672
 
1664
1673
  // src/openCodeApi.ts
@@ -1811,9 +1820,13 @@ function createOpenCodeApi(server) {
1811
1820
  const response = await send(method, path, options);
1812
1821
  await response.body?.cancel().catch(() => void 0);
1813
1822
  };
1814
- const callSession = async (method, path, body) => {
1823
+ const callSession = async (method, path, body, signal) => {
1815
1824
  const decoded = decodeSession(
1816
- await call(method, path, { wrapped: true, ...body === void 0 ? {} : { body } })
1825
+ await call(method, path, {
1826
+ wrapped: true,
1827
+ ...body === void 0 ? {} : { body },
1828
+ ...signal === void 0 ? {} : { signal }
1829
+ })
1817
1830
  );
1818
1831
  if (typeof decoded === "string") {
1819
1832
  throw new OpenCodeApiError({ kind: "shape", method, path, detail: decoded });
@@ -1826,6 +1839,7 @@ function createOpenCodeApi(server) {
1826
1839
  try {
1827
1840
  json = await response.json();
1828
1841
  } catch (cause) {
1842
+ if (server.signal?.aborted === true || options.signal?.aborted === true) throw cause;
1829
1843
  throw new OpenCodeApiError({ kind: "shape", method, path, detail: "not JSON", cause });
1830
1844
  }
1831
1845
  if (!options.wrapped) return json;
@@ -1851,23 +1865,36 @@ function createOpenCodeApi(server) {
1851
1865
  };
1852
1866
  const sessionPath = (sessionId, rest = "") => `/api/session/${encodeURIComponent(sessionId)}${rest}`;
1853
1867
  return {
1854
- createSession: (input) => callSession("POST", "/api/session", {
1855
- location: { directory: input.directory },
1856
- ...input.model === void 0 ? {} : { model: input.model },
1857
- ...input.title === void 0 ? {} : { title: input.title },
1858
- ...input.permissions === void 0 ? {} : { permissions: input.permissions }
1859
- }),
1860
- generate: async (sessionId, prompt) => {
1868
+ createSession: (input, signal) => callSession(
1869
+ "POST",
1870
+ "/api/session",
1871
+ {
1872
+ location: { directory: input.directory },
1873
+ ...input.model === void 0 ? {} : { model: input.model },
1874
+ ...input.title === void 0 ? {} : { title: input.title },
1875
+ ...input.permissions === void 0 ? {} : { permissions: input.permissions }
1876
+ },
1877
+ signal
1878
+ ),
1879
+ generate: async (sessionId, prompt, signal) => {
1861
1880
  const path = sessionPath(sessionId, "/generate");
1862
- const body = await call("POST", path, { wrapped: true, body: { prompt } });
1881
+ const body = await call("POST", path, {
1882
+ wrapped: true,
1883
+ body: { prompt },
1884
+ ...signal === void 0 ? {} : { signal }
1885
+ });
1863
1886
  const text4 = isRecord2(body) ? stringField(body, "text") : void 0;
1864
1887
  if (text4 === void 0) {
1865
1888
  throw new OpenCodeApiError({ kind: "shape", method: "POST", path, detail: "no text" });
1866
1889
  }
1867
1890
  return text4;
1868
1891
  },
1869
- deleteSession: async (sessionId) => {
1870
- await sendWithoutResult("DELETE", sessionPath(sessionId), {});
1892
+ deleteSession: async (sessionId, signal) => {
1893
+ await sendWithoutResult(
1894
+ "DELETE",
1895
+ sessionPath(sessionId),
1896
+ signal === void 0 ? {} : { signal }
1897
+ );
1871
1898
  },
1872
1899
  addMcpServer: async (name, config) => {
1873
1900
  await sendWithoutResult("PUT", `/api/experimental/mcp/${encodeURIComponent(name)}`, {
@@ -2033,9 +2060,9 @@ async function addOpenCodeMcpServers(input) {
2033
2060
  // src/probe.ts
2034
2061
  import * as NodeOS4 from "node:os";
2035
2062
  import {
2036
- ExecutorSpawnRefusedError,
2037
- raceAbort
2063
+ ExecutorSpawnRefusedError
2038
2064
  } from "@ycodium-ai/plugin-api/executor";
2065
+ import { isOperationCleanupError } from "@ycodium-ai/plugin-api/process-operation";
2039
2066
  var OPENCODE_VERSION_PROBE_TIMEOUT_MS = 4e3;
2040
2067
  var OPENCODE_NATIVE_MODE_REPORT = {
2041
2068
  nativeModes: OPENCODE_NATIVE_MODES.map((mode) => ({
@@ -2070,17 +2097,14 @@ async function probeOpenCode(input) {
2070
2097
  let version = null;
2071
2098
  if (!isExternal) {
2072
2099
  try {
2073
- const result = await raceAbort(
2074
- runOpenCodeCommand({
2075
- host: input.host,
2076
- recipe: input.recipe,
2077
- program,
2078
- args: ["--version"],
2079
- timeoutMs: OPENCODE_VERSION_PROBE_TIMEOUT_MS,
2080
- ...input.signal === void 0 ? {} : { signal: input.signal }
2081
- }),
2082
- input.signal
2083
- );
2100
+ const result = await runOpenCodeCommand({
2101
+ host: input.host,
2102
+ recipe: input.recipe,
2103
+ program,
2104
+ args: ["--version"],
2105
+ timeoutMs: OPENCODE_VERSION_PROBE_TIMEOUT_MS,
2106
+ ...input.signal === void 0 ? {} : { signal: input.signal }
2107
+ });
2084
2108
  version = parseGenericCliVersion(`${result.stdout}
2085
2109
  ${result.stderr}`);
2086
2110
  const tooOld = version ? openCodeTooOldDetail(version) : void 0;
@@ -2096,22 +2120,20 @@ ${result.stderr}`);
2096
2120
  };
2097
2121
  }
2098
2122
  } catch (cause) {
2123
+ if (isOperationCleanupError(cause)) throw cause;
2099
2124
  if (cause instanceof ExecutorSpawnRefusedError) throw cause;
2100
2125
  if (input.signal?.aborted) throw cause;
2101
2126
  return formatOpenCodeProbeError({ cause, isExternalServer: false, version });
2102
2127
  }
2103
2128
  }
2104
2129
  try {
2105
- const handle = await raceAbort(
2106
- connectToOpenCodeServer({
2107
- host: input.host,
2108
- recipe: input.recipe,
2109
- directory: isExternal ? "." : NodeOS4.homedir(),
2110
- program,
2111
- ...input.signal === void 0 ? {} : { signal: input.signal }
2112
- }),
2113
- input.signal
2114
- );
2130
+ const handle = await connectToOpenCodeServer({
2131
+ host: input.host,
2132
+ recipe: input.recipe,
2133
+ directory: isExternal ? "." : NodeOS4.homedir(),
2134
+ program,
2135
+ ...input.signal === void 0 ? {} : { signal: input.signal }
2136
+ });
2115
2137
  try {
2116
2138
  if (isExternal) {
2117
2139
  version = await readOpenCodeServerVersion({
@@ -2166,6 +2188,7 @@ ${result.stderr}`);
2166
2188
  await closeOpenCodeServer(handle);
2167
2189
  }
2168
2190
  } catch (cause) {
2191
+ if (isOperationCleanupError(cause)) throw cause;
2169
2192
  if (cause instanceof ExecutorSpawnRefusedError) throw cause;
2170
2193
  if (input.signal?.aborted) throw cause;
2171
2194
  const mapped = formatOpenCodeProbeError({ cause, isExternalServer: isExternal, version });
@@ -2180,14 +2203,18 @@ ${result.stderr}`);
2180
2203
  }
2181
2204
  }
2182
2205
  async function readOpenCodeCliVersion(input) {
2206
+ input.signal?.throwIfAborted();
2183
2207
  if (!input.recipe.enabled) return null;
2184
2208
  if (input.recipe.serverUrl.trim().length > 0) {
2185
2209
  try {
2186
2210
  return await readOpenCodeServerVersion({
2187
2211
  url: input.recipe.serverUrl,
2188
- password: input.recipe.serverPassword
2212
+ password: input.recipe.serverPassword,
2213
+ ...input.signal === void 0 ? {} : { signal: input.signal }
2189
2214
  });
2190
- } catch {
2215
+ } catch (cause) {
2216
+ if (isOperationCleanupError(cause)) throw cause;
2217
+ input.signal?.throwIfAborted();
2191
2218
  return null;
2192
2219
  }
2193
2220
  }
@@ -2199,11 +2226,14 @@ async function readOpenCodeCliVersion(input) {
2199
2226
  recipe: input.recipe,
2200
2227
  program,
2201
2228
  args: ["--version"],
2202
- timeoutMs: OPENCODE_VERSION_PROBE_TIMEOUT_MS
2229
+ timeoutMs: OPENCODE_VERSION_PROBE_TIMEOUT_MS,
2230
+ ...input.signal === void 0 ? {} : { signal: input.signal }
2203
2231
  });
2204
2232
  return parseGenericCliVersion(`${result.stdout}
2205
2233
  ${result.stderr}`);
2206
- } catch {
2234
+ } catch (cause) {
2235
+ if (isOperationCleanupError(cause)) throw cause;
2236
+ input.signal?.throwIfAborted();
2207
2237
  return null;
2208
2238
  }
2209
2239
  }
@@ -3279,6 +3309,183 @@ function buildTurnSummaryPrompt(raw) {
3279
3309
 
3280
3310
  // src/textGeneration.ts
3281
3311
  import "@ycodium-ai/plugin-api/executor";
3312
+ import { isOperationCleanupError as isOperationCleanupError3 } from "@ycodium-ai/plugin-api/process-operation";
3313
+ import { redactStderrExcerpt } from "@ycodium-ai/plugin-api/process-stdin";
3314
+
3315
+ // src/textGenerationServer.ts
3316
+ import { raceAbort } from "@ycodium-ai/plugin-api/executor";
3317
+ import {
3318
+ OperationCleanupError as OperationCleanupError2,
3319
+ isOperationCleanupError as isOperationCleanupError2
3320
+ } from "@ycodium-ai/plugin-api/process-operation";
3321
+ var IDLE_TTL_MS = 3e4;
3322
+ var REQUEST_DRAIN_TIMEOUT_MS = 3e3;
3323
+ var SERVER_CLOSE_TIMEOUT_MS = 2e3;
3324
+ async function within(work, milliseconds) {
3325
+ let timer;
3326
+ try {
3327
+ return await Promise.race([
3328
+ work,
3329
+ new Promise((_resolve, reject) => {
3330
+ timer = setTimeout(
3331
+ () => reject(new Error("OpenCode text generation disposal timed out.")),
3332
+ milliseconds
3333
+ );
3334
+ })
3335
+ ]);
3336
+ } finally {
3337
+ clearTimeout(timer);
3338
+ }
3339
+ }
3340
+ function createTextGenerationServer(recipe, host) {
3341
+ let handle;
3342
+ let starting;
3343
+ let client;
3344
+ let binaryPath;
3345
+ let borrowers = 0;
3346
+ let idleTimer;
3347
+ let mutex = Promise.resolve();
3348
+ let disposed = false;
3349
+ let disposal;
3350
+ const lifetime = new AbortController();
3351
+ const requests = /* @__PURE__ */ new Set();
3352
+ const withMutex = async (work) => {
3353
+ const previous = mutex;
3354
+ const next = Promise.withResolvers();
3355
+ mutex = next.promise;
3356
+ await previous;
3357
+ try {
3358
+ return await work();
3359
+ } finally {
3360
+ next.resolve();
3361
+ }
3362
+ };
3363
+ const clearIdle = () => {
3364
+ clearTimeout(idleTimer);
3365
+ idleTimer = void 0;
3366
+ };
3367
+ const close = async () => {
3368
+ clearIdle();
3369
+ try {
3370
+ if (handle && !handle.external) await closeOpenCodeServer(handle);
3371
+ if (starting) await closeOpenCodeServer(starting);
3372
+ } catch (cause) {
3373
+ if (isOperationCleanupError2(cause)) throw cause;
3374
+ throw new OperationCleanupError2([cause]);
3375
+ }
3376
+ handle = void 0;
3377
+ starting = void 0;
3378
+ client = void 0;
3379
+ binaryPath = void 0;
3380
+ };
3381
+ const scheduleIdle = () => {
3382
+ clearIdle();
3383
+ if (disposed || recipe.serverUrl.trim()) return;
3384
+ idleTimer = setTimeout(() => {
3385
+ void withMutex(async () => {
3386
+ if (!disposed && borrowers === 0) await close();
3387
+ }).catch((error) => {
3388
+ host.log.warn("Could not close the idle OpenCode text generation server", {
3389
+ error: String(error)
3390
+ });
3391
+ });
3392
+ }, IDLE_TTL_MS);
3393
+ };
3394
+ return {
3395
+ withClient(input, work) {
3396
+ if (disposed) return Promise.reject(new Error("OpenCode text generation has been disposed."));
3397
+ const signal = AbortSignal.any([
3398
+ lifetime.signal,
3399
+ ...input.signal === void 0 ? [] : [input.signal]
3400
+ ]);
3401
+ const request = (async () => {
3402
+ let borrowed = false;
3403
+ const acquisition = withMutex(async () => {
3404
+ signal.throwIfAborted();
3405
+ clearIdle();
3406
+ if (starting) await close();
3407
+ const program = recipe.binaryPath.trim() || "opencode";
3408
+ if (client && binaryPath !== program && borrowers === 0 && !handle?.external)
3409
+ await close();
3410
+ if (!client) {
3411
+ const startup = new AbortController();
3412
+ const abortStartup = () => startup.abort(lifetime.signal.reason);
3413
+ lifetime.signal.addEventListener("abort", abortStartup, { once: true });
3414
+ if (lifetime.signal.aborted) abortStartup();
3415
+ try {
3416
+ handle = await connectToOpenCodeServer({
3417
+ host,
3418
+ recipe,
3419
+ directory: input.cwd,
3420
+ program,
3421
+ signal: startup.signal,
3422
+ onSpawn: (resource) => {
3423
+ starting = resource;
3424
+ }
3425
+ });
3426
+ starting = void 0;
3427
+ } finally {
3428
+ lifetime.signal.removeEventListener("abort", abortStartup);
3429
+ }
3430
+ binaryPath = program;
3431
+ client = createOpenCodeApi({ url: handle.url, password: handle.password });
3432
+ }
3433
+ if (signal.aborted) {
3434
+ scheduleIdle();
3435
+ signal.throwIfAborted();
3436
+ }
3437
+ borrowers += 1;
3438
+ borrowed = true;
3439
+ return client;
3440
+ });
3441
+ try {
3442
+ const api = await raceAbort(acquisition, signal);
3443
+ return await work(api, signal);
3444
+ } finally {
3445
+ if (borrowed) {
3446
+ await withMutex(async () => {
3447
+ borrowers -= 1;
3448
+ if (borrowers === 0) scheduleIdle();
3449
+ });
3450
+ }
3451
+ }
3452
+ })();
3453
+ requests.add(request);
3454
+ void request.then(
3455
+ () => requests.delete(request),
3456
+ () => requests.delete(request)
3457
+ );
3458
+ return request;
3459
+ },
3460
+ dispose() {
3461
+ if (disposal) return disposal;
3462
+ disposed = true;
3463
+ clearIdle();
3464
+ lifetime.abort(new Error("OpenCode text generation has been disposed."));
3465
+ const work = (async () => {
3466
+ let drainError;
3467
+ try {
3468
+ await within(Promise.allSettled(requests), REQUEST_DRAIN_TIMEOUT_MS);
3469
+ } catch (cause) {
3470
+ drainError = cause;
3471
+ }
3472
+ try {
3473
+ await within(withMutex(close), SERVER_CLOSE_TIMEOUT_MS);
3474
+ } catch (cause) {
3475
+ if (drainError) throw new OperationCleanupError2([drainError, cause]);
3476
+ if (isOperationCleanupError2(cause)) throw cause;
3477
+ throw new OperationCleanupError2([cause]);
3478
+ }
3479
+ if (drainError) throw new OperationCleanupError2([drainError]);
3480
+ })();
3481
+ disposal = work;
3482
+ void disposal.catch(() => {
3483
+ disposal = void 0;
3484
+ });
3485
+ return disposal;
3486
+ }
3487
+ };
3488
+ }
3282
3489
 
3283
3490
  // src/textGenerationUtils.ts
3284
3491
  function limitSection(value, maxChars) {
@@ -3641,7 +3848,6 @@ function buildHandoverSummaryPrompt(input) {
3641
3848
  }
3642
3849
 
3643
3850
  // src/textGeneration.ts
3644
- var OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 3e4;
3645
3851
  var DENY_ALL_PERMISSIONS = [
3646
3852
  { action: "*", resource: "*", effect: "deny" }
3647
3853
  ];
@@ -3670,126 +3876,48 @@ function decodeStructuredOutput(rawText, operation, schemaKeys) {
3670
3876
  return record;
3671
3877
  }
3672
3878
  function createOpenCodeTextGeneration(recipe, host) {
3673
- const shared = {
3674
- handle: null,
3675
- client: null,
3676
- binaryPath: null,
3677
- activeRequests: 0,
3678
- idleTimer: null
3679
- };
3680
- let mutex = Promise.resolve();
3681
- const withMutex = async (fn) => {
3682
- let release;
3683
- const previous = mutex;
3684
- mutex = new Promise((resolve2) => {
3685
- release = resolve2;
3686
- });
3687
- await previous;
3688
- try {
3689
- return await fn();
3690
- } finally {
3691
- release();
3692
- }
3693
- };
3694
- const clearIdleTimer = () => {
3695
- if (shared.idleTimer) {
3696
- clearTimeout(shared.idleTimer);
3697
- shared.idleTimer = null;
3698
- }
3699
- };
3700
- const closeShared = async () => {
3701
- clearIdleTimer();
3702
- const handle = shared.handle;
3703
- shared.handle = null;
3704
- shared.client = null;
3705
- shared.binaryPath = null;
3706
- if (handle) await closeOpenCodeServer(handle);
3707
- };
3708
- const scheduleIdleClose = () => {
3709
- if (recipe.serverUrl.trim().length > 0) return;
3710
- clearIdleTimer();
3711
- shared.idleTimer = setTimeout(() => {
3712
- if (shared.activeRequests > 0) return;
3713
- void withMutex(closeShared);
3714
- }, OPENCODE_TEXT_GENERATION_IDLE_TTL_MS);
3715
- };
3716
- const acquireClient = async (input) => {
3717
- return withMutex(async () => {
3718
- shared.activeRequests += 1;
3719
- clearIdleTimer();
3720
- const configuredUrl = recipe.serverUrl.trim();
3721
- if (configuredUrl.length > 0) {
3722
- if (!shared.client) {
3723
- const handle = await connectToOpenCodeServer({
3724
- host,
3725
- recipe,
3726
- directory: input.cwd
3727
- });
3728
- shared.handle = handle;
3729
- shared.client = createOpenCodeApi({ url: handle.url, password: handle.password });
3730
- }
3731
- return shared.client;
3732
- }
3733
- const program = recipe.binaryPath.trim() || "opencode";
3734
- if (shared.handle && shared.client && shared.binaryPath !== null && shared.binaryPath !== program) {
3735
- if (shared.activeRequests > 1) {
3736
- return shared.client;
3737
- }
3738
- await closeShared();
3739
- }
3740
- if (!shared.client) {
3741
- const handle = await connectToOpenCodeServer({
3742
- host,
3743
- recipe,
3744
- directory: input.cwd,
3745
- program
3746
- });
3747
- shared.handle = handle;
3748
- shared.binaryPath = program;
3749
- shared.client = createOpenCodeApi({ url: handle.url, password: handle.password });
3750
- }
3751
- return shared.client;
3752
- });
3753
- };
3754
- const releaseClient = () => {
3755
- void withMutex(async () => {
3756
- shared.activeRequests = Math.max(0, shared.activeRequests - 1);
3757
- if (shared.activeRequests === 0) {
3758
- scheduleIdleClose();
3759
- }
3760
- });
3761
- };
3879
+ const shared = createTextGenerationServer(recipe, host);
3762
3880
  const runOpenCodeJson = async (input) => {
3763
- const api = await acquireClient({ cwd: input.cwd });
3764
- try {
3881
+ input.signal?.throwIfAborted();
3882
+ return shared.withClient(input, async (api, signal) => {
3765
3883
  const model = toOpenCodeModelRef({
3766
3884
  requested: modelIdFromSelection(input.modelSelection),
3767
3885
  modelSelection: input.modelSelection
3768
3886
  });
3769
- if (input.signal?.aborted) {
3887
+ if (signal.aborted) {
3770
3888
  throw new Error(`${input.operation}: aborted.`);
3771
3889
  }
3772
- const session = await api.createSession({
3773
- directory: input.cwd,
3774
- title: `Ycodium ${input.operation}`,
3775
- permissions: DENY_ALL_PERMISSIONS,
3776
- ...model === void 0 ? {} : { model }
3777
- });
3890
+ const session = await api.createSession(
3891
+ {
3892
+ directory: input.cwd,
3893
+ title: `Ycodium ${input.operation}`,
3894
+ permissions: DENY_ALL_PERMISSIONS,
3895
+ ...model === void 0 ? {} : { model }
3896
+ },
3897
+ signal
3898
+ );
3778
3899
  let rawText;
3779
3900
  try {
3780
- rawText = (await api.generate(session.id, input.prompt)).trim();
3901
+ signal.throwIfAborted();
3902
+ rawText = (await api.generate(session.id, input.prompt, signal)).trim();
3903
+ signal.throwIfAborted();
3781
3904
  } finally {
3782
- await api.deleteSession(session.id).catch(() => void 0);
3905
+ await api.deleteSession(session.id, AbortSignal.timeout(2e3)).catch((error) => {
3906
+ host.log.warn("Could not delete the OpenCode text generation session", {
3907
+ sessionId: session.id,
3908
+ operation: input.operation,
3909
+ error: redactStderrExcerpt(String(error))
3910
+ });
3911
+ });
3783
3912
  }
3784
3913
  if (rawText.length === 0) {
3785
3914
  throw new Error(`${input.operation}: OpenCode returned empty output.`);
3786
3915
  }
3787
3916
  return decodeStructuredOutput(rawText, input.operation, input.schemaKeys);
3788
- } finally {
3789
- releaseClient();
3790
- }
3917
+ });
3791
3918
  };
3792
3919
  return {
3920
+ dispose: shared.dispose,
3793
3921
  generateCommitMessage: async (raw, signal) => {
3794
3922
  try {
3795
3923
  const input = asRecord(raw, "generateCommitMessage");
@@ -3815,6 +3943,7 @@ function createOpenCodeTextGeneration(recipe, host) {
3815
3943
  ...typeof generated["branch"] === "string" ? { branch: sanitizeFeatureBranchName(generated["branch"]) } : {}
3816
3944
  };
3817
3945
  } catch (error) {
3946
+ if (isOperationCleanupError3(error)) throw error;
3818
3947
  throw normalizeCliError("opencode", error, "Failed to generate commit message");
3819
3948
  }
3820
3949
  },
@@ -3843,6 +3972,7 @@ function createOpenCodeTextGeneration(recipe, host) {
3843
3972
  body: readString3(generated["body"]).trim()
3844
3973
  };
3845
3974
  } catch (error) {
3975
+ if (isOperationCleanupError3(error)) throw error;
3846
3976
  throw normalizeCliError("opencode", error, "Failed to generate change request content");
3847
3977
  }
3848
3978
  },
@@ -3864,6 +3994,7 @@ function createOpenCodeTextGeneration(recipe, host) {
3864
3994
  });
3865
3995
  return { branch: sanitizeBranchFragment(readString3(generated["branch"])) };
3866
3996
  } catch (error) {
3997
+ if (isOperationCleanupError3(error)) throw error;
3867
3998
  throw normalizeCliError("opencode", error, "Failed to generate branch name");
3868
3999
  }
3869
4000
  },
@@ -3890,6 +4021,7 @@ function createOpenCodeTextGeneration(recipe, host) {
3890
4021
  ...generated["needsRefinement"] === true ? { needsRefinement: true } : {}
3891
4022
  };
3892
4023
  } catch (error) {
4024
+ if (isOperationCleanupError3(error)) throw error;
3893
4025
  throw normalizeCliError("opencode", error, "Failed to generate thread title");
3894
4026
  }
3895
4027
  },
@@ -3906,6 +4038,7 @@ function createOpenCodeTextGeneration(recipe, host) {
3906
4038
  });
3907
4039
  return { summary: readString3(generated["summary"]).trim() };
3908
4040
  } catch (error) {
4041
+ if (isOperationCleanupError3(error)) throw error;
3909
4042
  throw normalizeCliError("opencode", error, "Failed to summarize turn");
3910
4043
  }
3911
4044
  },
@@ -3925,6 +4058,7 @@ function createOpenCodeTextGeneration(recipe, host) {
3925
4058
  });
3926
4059
  return { summary: readString3(generated["summary"]).trim() };
3927
4060
  } catch (error) {
4061
+ if (isOperationCleanupError3(error)) throw error;
3928
4062
  throw normalizeCliError("opencode", error, "Failed to summarize handover");
3929
4063
  }
3930
4064
  }
@@ -3990,7 +4124,7 @@ function createOpenCodeInstance(config, host, attachments, lifecycleOptions) {
3990
4124
  host,
3991
4125
  ...signal ? { signal } : {}
3992
4126
  }),
3993
- readCliVersion: () => readOpenCodeCliVersion({ recipe, host }),
4127
+ readCliVersion: (signal) => readOpenCodeCliVersion({ recipe, host, ...signal === void 0 ? {} : { signal } }),
3994
4128
  // 项目里的命令与技能:探测在 home 下列,只看得到整机的;这里把 server 的工作目录设成项目再读。
3995
4129
  workspaceInventory: ({ cwd }) => {
3996
4130
  if (disposed) return Promise.reject(new Error("OpenCode instance has been disposed."));
@@ -4350,7 +4484,18 @@ function createOpenCodeInstance(config, host, attachments, lifecycleOptions) {
4350
4484
  disposed = true;
4351
4485
  const work = (async () => {
4352
4486
  const remaining = /* @__PURE__ */ new Set([...sessions.keys(), ...pendingServers.keys()]);
4353
- await Promise.all([...remaining].map((threadId) => instance.stopSession(threadId)));
4487
+ const outcomes = await Promise.allSettled([
4488
+ textGeneration?.dispose(),
4489
+ ...[...remaining].map((threadId) => instance.stopSession(threadId))
4490
+ ]);
4491
+ const failures = outcomes.flatMap(
4492
+ (outcome) => outcome.status === "rejected" ? [outcome.reason] : []
4493
+ );
4494
+ if (failures.length === 1) throw failures[0];
4495
+ if (failures.length > 1)
4496
+ throw new AggregateError(failures, "OpenCode instance disposal failed.", {
4497
+ cause: failures[0]
4498
+ });
4354
4499
  events.close();
4355
4500
  })();
4356
4501
  disposal = work;
@@ -4362,6 +4507,7 @@ function createOpenCodeInstance(config, host, attachments, lifecycleOptions) {
4362
4507
  }
4363
4508
  },
4364
4509
  get textGeneration() {
4510
+ if (disposed) throw new Error("OpenCode instance has been disposed.");
4365
4511
  textGeneration ??= createOpenCodeTextGeneration(recipe, host);
4366
4512
  return textGeneration;
4367
4513
  }
@@ -4382,7 +4528,7 @@ var executors = [
4382
4528
  ];
4383
4529
  var index_default = definePlugin({
4384
4530
  id: "agent-opencode",
4385
- apiVersion: 39,
4531
+ apiVersion: 41,
4386
4532
  executors,
4387
4533
  activate(ctx) {
4388
4534
  capturedAttachments = ctx.attachments;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ycodium-ai/agent-opencode",
3
- "version": "0.2.3478",
3
+ "version": "0.2.3502",
4
4
  "description": "OpenCode executor: OpenCode CLI (2.x) over its HTTP API.",
5
5
  "keywords": [
6
6
  "ycodium",
@@ -21,7 +21,7 @@
21
21
  "@types/node": "24.12.4",
22
22
  "esbuild": "0.28.1",
23
23
  "vite-plus": "0.2.2",
24
- "@ycodium-ai/plugin-api": "0.2.3478",
24
+ "@ycodium-ai/plugin-api": "0.2.3502",
25
25
  "ycodium-executor-testing": "0.0.0",
26
26
  "ycodium-fetch-ports": "0.0.0",
27
27
  "ycodium-sse-stream": "0.0.0"