@ycodium-ai/agent-opencode 0.2.4343 → 0.2.4351

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 +235 -217
  2. package/package.json +3 -3
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 = 109;
8
+ var PLUGIN_API_VERSION = 110;
9
9
 
10
10
  // src/card.ts
11
11
  var OPENCODE_DRIVER_KIND = "opencode";
@@ -1508,6 +1508,15 @@ async function spawnOpenCodeServer(input) {
1508
1508
  });
1509
1509
  const stdoutDrained = Promise.withResolvers();
1510
1510
  const stderrDrained = Promise.withResolvers();
1511
+ const stderrTail = drainStderrTail({
1512
+ async *[Symbol.asyncIterator]() {
1513
+ try {
1514
+ yield* spawned.stderr;
1515
+ } finally {
1516
+ stderrDrained.resolve();
1517
+ }
1518
+ }
1519
+ });
1511
1520
  const processHandle = {
1512
1521
  kill: spawned.kill,
1513
1522
  exited: spawned.exited,
@@ -1515,21 +1524,13 @@ async function spawnOpenCodeServer(input) {
1515
1524
  program: input.program,
1516
1525
  args,
1517
1526
  drained: Promise.all([stdoutDrained.promise, stderrDrained.promise]).then(() => {
1518
- })
1527
+ }),
1528
+ stderrTail
1519
1529
  };
1520
1530
  input.onSpawn?.({ external: false, process: processHandle });
1521
1531
  const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
1522
1532
  let stdoutText = "";
1523
1533
  const stdoutDecoder = new TextDecoder();
1524
- const stderrTail = drainStderrTail({
1525
- async *[Symbol.asyncIterator]() {
1526
- try {
1527
- yield* spawned.stderr;
1528
- } finally {
1529
- stderrDrained.resolve();
1530
- }
1531
- }
1532
- });
1533
1534
  const startupOutput = async () => `stdout=${stdoutText.trim()} stderr=${(await stderrTail()).slice(-OPENCODE_STDERR_TAIL_CHARS)}`;
1534
1535
  let settled = false;
1535
1536
  const url = await new Promise((resolve2, reject) => {
@@ -2326,115 +2327,8 @@ var loadOpenCodeWorkspaceInventory = async (input) => {
2326
2327
  }
2327
2328
  };
2328
2329
 
2329
- // src/usage.ts
2330
- var OPENCODE_COMPACTION_SUMMARY_MAX_CHARS = 8e3;
2331
- function withOpenCodeCompactionSummary(snapshot, summary) {
2332
- const trimmed = summary?.trim() ?? "";
2333
- if (trimmed.length === 0) {
2334
- return snapshot;
2335
- }
2336
- const truncated = trimmed.length > OPENCODE_COMPACTION_SUMMARY_MAX_CHARS;
2337
- return {
2338
- ...snapshot,
2339
- summary: truncated ? trimmed.slice(0, OPENCODE_COMPACTION_SUMMARY_MAX_CHARS) : trimmed,
2340
- ...truncated ? { summaryTruncated: true } : {}
2341
- };
2342
- }
2343
- function toCount(value) {
2344
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;
2345
- }
2346
- function readOpenCodeStepUsage(data, model) {
2347
- const tokens = data["tokens"];
2348
- if (typeof tokens !== "object" || tokens === null) return void 0;
2349
- const cache = "cache" in tokens ? tokens.cache : void 0;
2350
- const cost = data["cost"];
2351
- return {
2352
- model,
2353
- costUsd: typeof cost === "number" && Number.isFinite(cost) ? cost : 0,
2354
- uncachedInputTokens: toCount("input" in tokens ? tokens.input : void 0),
2355
- cachedInputTokens: toCount(
2356
- typeof cache === "object" && cache !== null && "read" in cache ? cache.read : void 0
2357
- ),
2358
- cacheCreationTokens: toCount(
2359
- typeof cache === "object" && cache !== null && "write" in cache ? cache.write : void 0
2360
- ),
2361
- outputTokens: toCount("output" in tokens ? tokens.output : void 0),
2362
- reasoningTokens: toCount("reasoning" in tokens ? tokens.reasoning : void 0)
2363
- };
2364
- }
2365
- function takeTurnUsage(usageByMessageId, sessionId) {
2366
- const entries = Array.from(usageByMessageId.values());
2367
- usageByMessageId.clear();
2368
- const last = entries.findLast((entry) => entry.child !== true) ?? entries.at(-1);
2369
- if (!last) {
2370
- return void 0;
2371
- }
2372
- const totals = {
2373
- uncachedInputTokens: 0,
2374
- cachedInputTokens: 0,
2375
- cacheCreationTokens: 0,
2376
- outputTokens: 0,
2377
- reasoningTokens: 0
2378
- };
2379
- let costUsd = 0;
2380
- for (const entry of entries) {
2381
- totals.uncachedInputTokens += entry.uncachedInputTokens;
2382
- totals.cachedInputTokens += entry.cachedInputTokens;
2383
- totals.cacheCreationTokens += entry.cacheCreationTokens;
2384
- totals.outputTokens += entry.outputTokens;
2385
- totals.reasoningTokens += entry.reasoningTokens;
2386
- costUsd += entry.costUsd;
2387
- }
2388
- if (totals.uncachedInputTokens === 0 && totals.cachedInputTokens === 0 && totals.cacheCreationTokens === 0 && totals.outputTokens === 0) {
2389
- return void 0;
2390
- }
2391
- return {
2392
- provider: "opencode",
2393
- model: last.model,
2394
- totals,
2395
- ...costUsd > 0 ? { reportedCostUsd: costUsd } : {},
2396
- sessionId
2397
- };
2398
- }
2399
-
2400
- // src/compactionEvents.ts
2401
- function handleOpenCodeCompactionEvent(input) {
2402
- const { context, event } = input;
2403
- switch (event.type) {
2404
- case "session.compaction.started": {
2405
- const compaction = {
2406
- compactionId: randomUUID(),
2407
- trigger: event.data["reason"] === "manual" ? "manual" : "automatic"
2408
- };
2409
- context.compaction = compaction;
2410
- context.session = { ...context.session, status: "compacting", updatedAt: nowIso() };
2411
- emitEvent(context, "session.state.changed", { state: "compacting" });
2412
- emitEvent(context, "thread.state.changed", { state: "compacting", compaction });
2413
- return true;
2414
- }
2415
- case "session.compaction.delta":
2416
- return true;
2417
- case "session.compaction.ended": {
2418
- const summary = event.data["text"];
2419
- const compaction = withOpenCodeCompactionSummary(
2420
- context.compaction ?? {
2421
- compactionId: randomUUID(),
2422
- trigger: event.data["reason"] === "manual" ? "manual" : "automatic"
2423
- },
2424
- typeof summary === "string" ? summary : void 0
2425
- );
2426
- context.compaction = void 0;
2427
- emitEvent(context, "thread.state.changed", { state: "compacted", compaction });
2428
- if (context.session.activeTurnId !== void 0) {
2429
- context.session = { ...context.session, status: "running", updatedAt: nowIso() };
2430
- emitEvent(context, "session.state.changed", { state: "running" });
2431
- }
2432
- return true;
2433
- }
2434
- default:
2435
- return false;
2436
- }
2437
- }
2330
+ // src/turnCompletion.ts
2331
+ import { lastStderrLines } from "@ycodium-ai/plugin-api/process-stdin";
2438
2332
 
2439
2333
  // src/subagents.ts
2440
2334
  var OPENCODE_SUBAGENT_TOOL = "subagent";
@@ -2718,6 +2612,222 @@ function markSubagentsUnknown(context) {
2718
2612
  }
2719
2613
  }
2720
2614
 
2615
+ // src/usage.ts
2616
+ var OPENCODE_COMPACTION_SUMMARY_MAX_CHARS = 8e3;
2617
+ function withOpenCodeCompactionSummary(snapshot, summary) {
2618
+ const trimmed = summary?.trim() ?? "";
2619
+ if (trimmed.length === 0) {
2620
+ return snapshot;
2621
+ }
2622
+ const truncated = trimmed.length > OPENCODE_COMPACTION_SUMMARY_MAX_CHARS;
2623
+ return {
2624
+ ...snapshot,
2625
+ summary: truncated ? trimmed.slice(0, OPENCODE_COMPACTION_SUMMARY_MAX_CHARS) : trimmed,
2626
+ ...truncated ? { summaryTruncated: true } : {}
2627
+ };
2628
+ }
2629
+ function toCount(value) {
2630
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;
2631
+ }
2632
+ function readOpenCodeStepUsage(data, model) {
2633
+ const tokens = data["tokens"];
2634
+ if (typeof tokens !== "object" || tokens === null) return void 0;
2635
+ const cache = "cache" in tokens ? tokens.cache : void 0;
2636
+ const cost = data["cost"];
2637
+ return {
2638
+ model,
2639
+ costUsd: typeof cost === "number" && Number.isFinite(cost) ? cost : 0,
2640
+ uncachedInputTokens: toCount("input" in tokens ? tokens.input : void 0),
2641
+ cachedInputTokens: toCount(
2642
+ typeof cache === "object" && cache !== null && "read" in cache ? cache.read : void 0
2643
+ ),
2644
+ cacheCreationTokens: toCount(
2645
+ typeof cache === "object" && cache !== null && "write" in cache ? cache.write : void 0
2646
+ ),
2647
+ outputTokens: toCount("output" in tokens ? tokens.output : void 0),
2648
+ reasoningTokens: toCount("reasoning" in tokens ? tokens.reasoning : void 0)
2649
+ };
2650
+ }
2651
+ function takeTurnUsage(usageByMessageId, sessionId) {
2652
+ const entries = Array.from(usageByMessageId.values());
2653
+ usageByMessageId.clear();
2654
+ const last = entries.findLast((entry) => entry.child !== true) ?? entries.at(-1);
2655
+ if (!last) {
2656
+ return void 0;
2657
+ }
2658
+ const totals = {
2659
+ uncachedInputTokens: 0,
2660
+ cachedInputTokens: 0,
2661
+ cacheCreationTokens: 0,
2662
+ outputTokens: 0,
2663
+ reasoningTokens: 0
2664
+ };
2665
+ let costUsd = 0;
2666
+ for (const entry of entries) {
2667
+ totals.uncachedInputTokens += entry.uncachedInputTokens;
2668
+ totals.cachedInputTokens += entry.cachedInputTokens;
2669
+ totals.cacheCreationTokens += entry.cacheCreationTokens;
2670
+ totals.outputTokens += entry.outputTokens;
2671
+ totals.reasoningTokens += entry.reasoningTokens;
2672
+ costUsd += entry.costUsd;
2673
+ }
2674
+ if (totals.uncachedInputTokens === 0 && totals.cachedInputTokens === 0 && totals.cacheCreationTokens === 0 && totals.outputTokens === 0) {
2675
+ return void 0;
2676
+ }
2677
+ return {
2678
+ provider: "opencode",
2679
+ model: last.model,
2680
+ totals,
2681
+ ...costUsd > 0 ? { reportedCostUsd: costUsd } : {},
2682
+ sessionId
2683
+ };
2684
+ }
2685
+
2686
+ // src/turnCompletion.ts
2687
+ function finishOpenCodeTurn(context, outcome) {
2688
+ const turnId = context.session.activeTurnId;
2689
+ const usage = takeTurnUsage(context.usageByMessageId, context.sessionId);
2690
+ context.abortedByDecline = false;
2691
+ context.declinedToolCalls.clear();
2692
+ context.openShells.clear();
2693
+ context.stepModels.clear();
2694
+ context.assistantTextByPartId.clear();
2695
+ context.completedTextParts.clear();
2696
+ finishSubagentsForTurn(context, {
2697
+ sessionEnds: outcome.state !== "completed" && outcome.sessionEnds === true
2698
+ });
2699
+ if (turnId === void 0) return;
2700
+ if (outcome.state === "interrupted") {
2701
+ emitEvent(context, "turn.aborted", { reason: outcome.reason }, { turnId });
2702
+ context.session = { ...withoutActiveTurn(context.session), updatedAt: nowIso() };
2703
+ return;
2704
+ }
2705
+ if (outcome.state === "completed") {
2706
+ emitEvent(
2707
+ context,
2708
+ "turn.completed",
2709
+ { state: "completed", ...usage ? { tokenUsage: usage } : {} },
2710
+ { turnId }
2711
+ );
2712
+ context.session = { ...withoutActiveTurn(context.session), updatedAt: nowIso() };
2713
+ return;
2714
+ }
2715
+ const { errorMessage, failureCategory } = outcome;
2716
+ emitEvent(
2717
+ context,
2718
+ "turn.completed",
2719
+ {
2720
+ state: "failed",
2721
+ ...usage ? { tokenUsage: usage } : {},
2722
+ errorMessage,
2723
+ ...failureCategoryField(failureCategory)
2724
+ },
2725
+ { turnId }
2726
+ );
2727
+ context.session = {
2728
+ ...withLastError(withoutActiveTurn(context.session), errorMessage, failureCategory),
2729
+ updatedAt: nowIso()
2730
+ };
2731
+ }
2732
+ function finishOpenCodeTurnEvent(context, event) {
2733
+ switch (event.type) {
2734
+ case "session.execution.succeeded":
2735
+ finishOpenCodeTurn(context, { state: "completed" });
2736
+ return true;
2737
+ case "session.execution.failed": {
2738
+ const errorMessage = openCodeFailureMessage(event.data["error"]);
2739
+ const failureCategory = openCodeFailureCategory(event.data["error"]);
2740
+ finishOpenCodeTurn(context, { state: "failed", errorMessage, failureCategory });
2741
+ emitEvent(context, "runtime.error", {
2742
+ message: errorMessage,
2743
+ class: "provider_error",
2744
+ ...failureCategoryField(failureCategory)
2745
+ });
2746
+ return true;
2747
+ }
2748
+ case "session.execution.interrupted": {
2749
+ const value = event.data["reason"];
2750
+ const reason = typeof value === "string" ? value : void 0;
2751
+ finishOpenCodeTurn(context, {
2752
+ state: "interrupted",
2753
+ reason: reason === void 0 || reason === "user" ? "Interrupted by user." : reason === "shutdown" && context.abortedByDecline ? "Declined by user." : `Interrupted (${reason}).`
2754
+ });
2755
+ return true;
2756
+ }
2757
+ default:
2758
+ return false;
2759
+ }
2760
+ }
2761
+ var SERVER_EXIT_STDERR_MAX_CHARS = 800;
2762
+ var OpenCodeServerExitedError = class extends Error {
2763
+ constructor(code, stderrTail) {
2764
+ const head = `OpenCode server exited with code ${code}.`;
2765
+ const excerpt = lastStderrLines(stderrTail, SERVER_EXIT_STDERR_MAX_CHARS);
2766
+ super(excerpt.length === 0 ? head : `${head}
2767
+ OpenCode stderr (last lines):
2768
+ ${excerpt}`);
2769
+ this.name = "OpenCodeServerExitedError";
2770
+ }
2771
+ };
2772
+ function finishOpenCodeTurnOnExit(context, cause) {
2773
+ const message = cause instanceof Error && cause.message.trim().length > 0 ? cause.message.trim() : "OpenCode server exited unexpectedly.";
2774
+ const failureCategory = cause instanceof OpenCodeServerExitedError ? "process-exit" : cause instanceof OpenCodeApiError && cause.kind !== "transport" ? void 0 : "transport";
2775
+ const turnId = context.session.activeTurnId;
2776
+ if (turnId && failureCategory !== "process-exit") {
2777
+ emitEvent(context, "runtime.error", {
2778
+ message,
2779
+ class: "transport_error",
2780
+ ...failureCategoryField(failureCategory)
2781
+ });
2782
+ }
2783
+ finishOpenCodeTurn(context, {
2784
+ state: "failed",
2785
+ errorMessage: message,
2786
+ failureCategory,
2787
+ sessionEnds: true
2788
+ });
2789
+ return { message, failureCategory, turnId };
2790
+ }
2791
+
2792
+ // src/compactionEvents.ts
2793
+ function handleOpenCodeCompactionEvent(input) {
2794
+ const { context, event } = input;
2795
+ switch (event.type) {
2796
+ case "session.compaction.started": {
2797
+ const compaction = {
2798
+ compactionId: randomUUID(),
2799
+ trigger: event.data["reason"] === "manual" ? "manual" : "automatic"
2800
+ };
2801
+ context.compaction = compaction;
2802
+ context.session = { ...context.session, status: "compacting", updatedAt: nowIso() };
2803
+ emitEvent(context, "session.state.changed", { state: "compacting" });
2804
+ emitEvent(context, "thread.state.changed", { state: "compacting", compaction });
2805
+ return true;
2806
+ }
2807
+ case "session.compaction.delta":
2808
+ return true;
2809
+ case "session.compaction.ended": {
2810
+ const summary = event.data["text"];
2811
+ const compaction = withOpenCodeCompactionSummary(
2812
+ context.compaction ?? {
2813
+ compactionId: randomUUID(),
2814
+ trigger: event.data["reason"] === "manual" ? "manual" : "automatic"
2815
+ },
2816
+ typeof summary === "string" ? summary : void 0
2817
+ );
2818
+ context.compaction = void 0;
2819
+ emitEvent(context, "thread.state.changed", { state: "compacted", compaction });
2820
+ if (context.session.activeTurnId !== void 0) {
2821
+ context.session = { ...context.session, status: "running", updatedAt: nowIso() };
2822
+ emitEvent(context, "session.state.changed", { state: "running" });
2823
+ }
2824
+ return true;
2825
+ }
2826
+ default:
2827
+ return false;
2828
+ }
2829
+ }
2830
+
2721
2831
  // src/toolEvents.ts
2722
2832
  var text2 = (data, key) => {
2723
2833
  const value = data[key];
@@ -2974,101 +3084,6 @@ async function handleOpenCodeToolEvent(input) {
2974
3084
  }
2975
3085
  }
2976
3086
 
2977
- // src/turnCompletion.ts
2978
- function finishOpenCodeTurn(context, outcome) {
2979
- const turnId = context.session.activeTurnId;
2980
- const usage = takeTurnUsage(context.usageByMessageId, context.sessionId);
2981
- context.abortedByDecline = false;
2982
- context.declinedToolCalls.clear();
2983
- context.openShells.clear();
2984
- context.stepModels.clear();
2985
- context.assistantTextByPartId.clear();
2986
- context.completedTextParts.clear();
2987
- finishSubagentsForTurn(context, {
2988
- sessionEnds: outcome.state !== "completed" && outcome.sessionEnds === true
2989
- });
2990
- if (turnId === void 0) return;
2991
- if (outcome.state === "interrupted") {
2992
- emitEvent(context, "turn.aborted", { reason: outcome.reason }, { turnId });
2993
- context.session = { ...withoutActiveTurn(context.session), updatedAt: nowIso() };
2994
- return;
2995
- }
2996
- if (outcome.state === "completed") {
2997
- emitEvent(
2998
- context,
2999
- "turn.completed",
3000
- { state: "completed", ...usage ? { tokenUsage: usage } : {} },
3001
- { turnId }
3002
- );
3003
- context.session = { ...withoutActiveTurn(context.session), updatedAt: nowIso() };
3004
- return;
3005
- }
3006
- const { errorMessage, failureCategory } = outcome;
3007
- emitEvent(
3008
- context,
3009
- "turn.completed",
3010
- {
3011
- state: "failed",
3012
- ...usage ? { tokenUsage: usage } : {},
3013
- errorMessage,
3014
- ...failureCategoryField(failureCategory)
3015
- },
3016
- { turnId }
3017
- );
3018
- context.session = {
3019
- ...withLastError(withoutActiveTurn(context.session), errorMessage, failureCategory),
3020
- updatedAt: nowIso()
3021
- };
3022
- }
3023
- function finishOpenCodeTurnEvent(context, event) {
3024
- switch (event.type) {
3025
- case "session.execution.succeeded":
3026
- finishOpenCodeTurn(context, { state: "completed" });
3027
- return true;
3028
- case "session.execution.failed": {
3029
- const errorMessage = openCodeFailureMessage(event.data["error"]);
3030
- const failureCategory = openCodeFailureCategory(event.data["error"]);
3031
- finishOpenCodeTurn(context, { state: "failed", errorMessage, failureCategory });
3032
- emitEvent(context, "runtime.error", {
3033
- message: errorMessage,
3034
- class: "provider_error",
3035
- ...failureCategoryField(failureCategory)
3036
- });
3037
- return true;
3038
- }
3039
- case "session.execution.interrupted": {
3040
- const value = event.data["reason"];
3041
- const reason = typeof value === "string" ? value : void 0;
3042
- finishOpenCodeTurn(context, {
3043
- state: "interrupted",
3044
- reason: reason === void 0 || reason === "user" ? "Interrupted by user." : reason === "shutdown" && context.abortedByDecline ? "Declined by user." : `Interrupted (${reason}).`
3045
- });
3046
- return true;
3047
- }
3048
- default:
3049
- return false;
3050
- }
3051
- }
3052
- function finishOpenCodeTurnOnExit(context, cause) {
3053
- const message = cause instanceof Error && cause.message.trim().length > 0 ? cause.message.trim() : "OpenCode server exited unexpectedly.";
3054
- const failureCategory = cause instanceof OpenCodeApiError && cause.kind !== "transport" ? void 0 : "transport";
3055
- const turnId = context.session.activeTurnId;
3056
- if (turnId) {
3057
- emitEvent(context, "runtime.error", {
3058
- message,
3059
- class: "transport_error",
3060
- ...failureCategoryField(failureCategory)
3061
- });
3062
- }
3063
- finishOpenCodeTurn(context, {
3064
- state: "failed",
3065
- errorMessage: message,
3066
- failureCategory,
3067
- sessionEnds: true
3068
- });
3069
- return { message, failureCategory, turnId };
3070
- }
3071
-
3072
3087
  // src/turnEvents.ts
3073
3088
  var text3 = (data, key) => {
3074
3089
  const value = data[key];
@@ -3590,9 +3605,12 @@ function startEventPump(input) {
3590
3605
  }
3591
3606
  })();
3592
3607
  if (!context.server.external && context.server.process) {
3593
- void context.server.process.exited.then((code) => {
3608
+ const serverProcess = context.server.process;
3609
+ void serverProcess.exited.then(async (code) => {
3610
+ if (context.stopped) return;
3611
+ const tail = await serverProcess.stderrTail?.().catch(() => "") ?? "";
3594
3612
  if (context.stopped) return;
3595
- const cause = new Error(`OpenCode server exited with code ${code}.`);
3613
+ const cause = new OpenCodeServerExitedError(code, tail);
3596
3614
  if (connected) lifecycle.exit(cause, true);
3597
3615
  else fail(cause);
3598
3616
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ycodium-ai/agent-opencode",
3
- "version": "0.2.4343",
3
+ "version": "0.2.4351",
4
4
  "description": "OpenCode executor: OpenCode CLI (2.x) over its HTTP API.",
5
5
  "keywords": [
6
6
  "ycodium",
@@ -21,9 +21,9 @@
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.4343",
25
- "ycodium-executor-testing": "0.0.0",
24
+ "@ycodium-ai/plugin-api": "0.2.4351",
26
25
  "ycodium-fetch-ports": "0.0.0",
26
+ "ycodium-executor-testing": "0.0.0",
27
27
  "ycodium-sse-stream": "0.0.0"
28
28
  },
29
29
  "ycodium": {