@ycodium-ai/agent-opencode 0.2.3130 → 0.2.3168

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 +314 -183
  2. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -380,6 +380,7 @@ function withLastError(session, lastError, failureCategory) {
380
380
  return { ...rest, lastError, ...failureCategoryField(failureCategory) };
381
381
  }
382
382
  function emitEvent(events, context, type2, payload, extra) {
383
+ if (context.lifecycle?.canEmit === false) return;
383
384
  const turnId = extra?.turnId ?? context.session.activeTurnId;
384
385
  const event = {
385
386
  eventId: randomUUID(),
@@ -1406,16 +1407,20 @@ async function spawnOpenCodeServer(input) {
1406
1407
  const hostname = DEFAULT_HOSTNAME;
1407
1408
  const password = NodeCrypto2.randomBytes(32).toString("base64url");
1408
1409
  const env = buildSpawnEnv(input.recipe, input.configContent, password);
1410
+ const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];
1409
1411
  const spawned = await input.host.process.spawn({
1410
1412
  program: input.program,
1411
- args: ["serve", `--hostname=${hostname}`, `--port=${port}`],
1413
+ args,
1412
1414
  cwd: input.directory,
1413
1415
  env,
1414
1416
  owner: { bindingId: input.host.bindingId }
1415
1417
  });
1416
1418
  const processHandle = {
1417
1419
  kill: spawned.kill,
1418
- exited: spawned.exited
1420
+ exited: spawned.exited,
1421
+ pid: spawned.pid,
1422
+ program: input.program,
1423
+ args
1419
1424
  };
1420
1425
  input.onSpawn?.({ external: false, process: processHandle });
1421
1426
  const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
@@ -2462,6 +2467,10 @@ async function handleOpenCodeToolEvent(input) {
2462
2467
  const callId = text2(data, "id");
2463
2468
  if (callId === void 0 || !isRecord2(data["metadata"])) return true;
2464
2469
  const toolInput = context.toolInputs.get(callId);
2470
+ const command = toolInput?.["command"];
2471
+ if (context.toolNames.get(callId) === "shell" && text2(data["metadata"], "shellID") !== void 0 && typeof command === "string" && !context.openShells.has(callId)) {
2472
+ context.openShells.set(callId, { command, startedAtMs: Date.now() });
2473
+ }
2465
2474
  emitTool(events, context, callId, "item.updated", "inProgress", "running", {
2466
2475
  data: {
2467
2476
  ...toolInput === void 0 ? {} : { input: toolInput },
@@ -2500,6 +2509,7 @@ async function handleOpenCodeToolEvent(input) {
2500
2509
  );
2501
2510
  context.toolNames.delete(callId);
2502
2511
  context.toolInputs.delete(callId);
2512
+ context.openShells.delete(callId);
2503
2513
  return true;
2504
2514
  }
2505
2515
  default:
@@ -2507,39 +2517,20 @@ async function handleOpenCodeToolEvent(input) {
2507
2517
  }
2508
2518
  }
2509
2519
 
2510
- // src/turnEvents.ts
2511
- var text3 = (data, key) => {
2512
- const value = data[key];
2513
- return typeof value === "string" ? value : void 0;
2514
- };
2515
- var streamItemId = (data, kind) => {
2516
- const messageId = text3(data, "assistantMessageID");
2517
- const ordinal = data["ordinal"];
2518
- if (messageId === void 0 || messageId.length === 0 || typeof ordinal !== "number") {
2519
- return void 0;
2520
- }
2521
- return `${messageId}:${kind}:${ordinal}`;
2522
- };
2523
- function settleSession(events, context) {
2524
- context.session = { ...context.session, status: "ready", updatedAt: nowIso() };
2525
- emitEvent(events, context, "session.state.changed", { state: "ready" });
2526
- }
2527
- function finishTurn(events, context, outcome) {
2520
+ // src/turnCompletion.ts
2521
+ function finishOpenCodeTurn(events, context, outcome) {
2528
2522
  const turnId = context.session.activeTurnId;
2529
2523
  const usage = takeTurnUsage(context.usageByMessageId, context.sessionId);
2530
2524
  context.abortedByDecline = false;
2531
2525
  context.declinedToolCalls.clear();
2526
+ context.openShells.clear();
2532
2527
  context.stepModels.clear();
2533
2528
  context.assistantTextByPartId.clear();
2534
2529
  context.completedTextParts.clear();
2535
2530
  if (turnId === void 0) return;
2536
2531
  if (outcome.state === "interrupted") {
2537
2532
  emitEvent(events, context, "turn.aborted", { reason: outcome.reason }, { turnId });
2538
- context.session = {
2539
- ...withoutActiveTurn(context.session),
2540
- status: "ready",
2541
- updatedAt: nowIso()
2542
- };
2533
+ context.session = { ...withoutActiveTurn(context.session), updatedAt: nowIso() };
2543
2534
  return;
2544
2535
  }
2545
2536
  if (outcome.state === "completed") {
@@ -2550,15 +2541,10 @@ function finishTurn(events, context, outcome) {
2550
2541
  { state: "completed", ...usage ? { tokenUsage: usage } : {} },
2551
2542
  { turnId }
2552
2543
  );
2553
- context.session = {
2554
- ...withoutActiveTurn(context.session),
2555
- status: "ready",
2556
- updatedAt: nowIso()
2557
- };
2544
+ context.session = { ...withoutActiveTurn(context.session), updatedAt: nowIso() };
2558
2545
  return;
2559
2546
  }
2560
- const errorMessage = openCodeFailureMessage(outcome.error);
2561
- const failureCategory = openCodeFailureCategory(outcome.error);
2547
+ const { errorMessage, failureCategory } = outcome;
2562
2548
  emitEvent(
2563
2549
  events,
2564
2550
  context,
@@ -2573,14 +2559,69 @@ function finishTurn(events, context, outcome) {
2573
2559
  );
2574
2560
  context.session = {
2575
2561
  ...withLastError(withoutActiveTurn(context.session), errorMessage, failureCategory),
2576
- status: "error",
2577
2562
  updatedAt: nowIso()
2578
2563
  };
2579
- emitEvent(events, context, "runtime.error", {
2580
- message: errorMessage,
2581
- class: "provider_error",
2582
- ...failureCategoryField(failureCategory)
2583
- });
2564
+ }
2565
+ function finishOpenCodeTurnEvent(events, context, event) {
2566
+ switch (event.type) {
2567
+ case "session.execution.succeeded":
2568
+ finishOpenCodeTurn(events, context, { state: "completed" });
2569
+ return true;
2570
+ case "session.execution.failed": {
2571
+ const errorMessage = openCodeFailureMessage(event.data["error"]);
2572
+ const failureCategory = openCodeFailureCategory(event.data["error"]);
2573
+ finishOpenCodeTurn(events, context, { state: "failed", errorMessage, failureCategory });
2574
+ emitEvent(events, context, "runtime.error", {
2575
+ message: errorMessage,
2576
+ class: "provider_error",
2577
+ ...failureCategoryField(failureCategory)
2578
+ });
2579
+ return true;
2580
+ }
2581
+ case "session.execution.interrupted": {
2582
+ const value = event.data["reason"];
2583
+ const reason = typeof value === "string" ? value : void 0;
2584
+ finishOpenCodeTurn(events, context, {
2585
+ state: "interrupted",
2586
+ reason: reason === void 0 || reason === "user" ? "Interrupted by user." : reason === "shutdown" && context.abortedByDecline ? "Declined by user." : `Interrupted (${reason}).`
2587
+ });
2588
+ return true;
2589
+ }
2590
+ default:
2591
+ return false;
2592
+ }
2593
+ }
2594
+ function finishOpenCodeTurnOnExit(events, context, cause) {
2595
+ const message = cause instanceof Error && cause.message.trim().length > 0 ? cause.message.trim() : "OpenCode server exited unexpectedly.";
2596
+ const failureCategory = cause instanceof OpenCodeApiError && cause.kind !== "transport" ? void 0 : "transport";
2597
+ const turnId = context.session.activeTurnId;
2598
+ if (turnId) {
2599
+ emitEvent(events, context, "runtime.error", {
2600
+ message,
2601
+ class: "transport_error",
2602
+ ...failureCategoryField(failureCategory)
2603
+ });
2604
+ }
2605
+ finishOpenCodeTurn(events, context, { state: "failed", errorMessage: message, failureCategory });
2606
+ return { message, failureCategory, turnId };
2607
+ }
2608
+
2609
+ // src/turnEvents.ts
2610
+ var text3 = (data, key) => {
2611
+ const value = data[key];
2612
+ return typeof value === "string" ? value : void 0;
2613
+ };
2614
+ var streamItemId = (data, kind) => {
2615
+ const messageId = text3(data, "assistantMessageID");
2616
+ const ordinal = data["ordinal"];
2617
+ if (messageId === void 0 || messageId.length === 0 || typeof ordinal !== "number") {
2618
+ return void 0;
2619
+ }
2620
+ return `${messageId}:${kind}:${ordinal}`;
2621
+ };
2622
+ function settleSession(events, context) {
2623
+ context.session = { ...context.session, status: "ready", updatedAt: nowIso() };
2624
+ emitEvent(events, context, "session.state.changed", { state: "ready" });
2584
2625
  }
2585
2626
  function remainderOf(context, itemId, full) {
2586
2627
  const sent = context.assistantTextByPartId.get(itemId) ?? "";
@@ -2630,6 +2671,10 @@ function endStream(events, context, data, kind) {
2630
2671
  }
2631
2672
  function handleOpenCodeTurnEvent(input) {
2632
2673
  const { events, context, event } = input;
2674
+ if (finishOpenCodeTurnEvent(events, context, event)) {
2675
+ settleSession(events, context);
2676
+ return true;
2677
+ }
2633
2678
  const data = event.data;
2634
2679
  switch (event.type) {
2635
2680
  case "session.execution.started": {
@@ -2639,33 +2684,6 @@ function handleOpenCodeTurnEvent(input) {
2639
2684
  }
2640
2685
  return true;
2641
2686
  }
2642
- case "session.execution.succeeded": {
2643
- finishTurn(events, context, { state: "completed" });
2644
- settleSession(events, context);
2645
- return true;
2646
- }
2647
- case "session.execution.failed": {
2648
- const hadTurn = context.session.activeTurnId !== void 0;
2649
- finishTurn(events, context, { state: "failed", error: data["error"] });
2650
- if (!hadTurn) {
2651
- emitEvent(events, context, "runtime.error", {
2652
- message: openCodeFailureMessage(data["error"]),
2653
- class: "provider_error",
2654
- ...failureCategoryField(openCodeFailureCategory(data["error"]))
2655
- });
2656
- }
2657
- settleSession(events, context);
2658
- return true;
2659
- }
2660
- case "session.execution.interrupted": {
2661
- const reason = text3(data, "reason");
2662
- finishTurn(events, context, {
2663
- state: "interrupted",
2664
- reason: reason === void 0 || reason === "user" ? "Interrupted by user." : reason === "shutdown" && context.abortedByDecline ? "Declined by user." : `Interrupted (${reason}).`
2665
- });
2666
- settleSession(events, context);
2667
- return true;
2668
- }
2669
2687
  case "session.step.started": {
2670
2688
  context.abortedByDecline = false;
2671
2689
  const messageId = text3(data, "assistantMessageID");
@@ -2717,6 +2735,160 @@ function handleOpenCodeTurnEvent(input) {
2717
2735
  }
2718
2736
  }
2719
2737
 
2738
+ // src/sessionLifecycle.ts
2739
+ function emitUnexpectedExit(events, context, cause) {
2740
+ if (context.stopped) return;
2741
+ context.stopped = true;
2742
+ const { message, failureCategory, turnId } = finishOpenCodeTurnOnExit(events, context, cause);
2743
+ emitEvent(
2744
+ events,
2745
+ context,
2746
+ "session.exited",
2747
+ { reason: message, recoverable: false, exitKind: "error" },
2748
+ turnId === void 0 ? void 0 : { turnId }
2749
+ );
2750
+ context.session = {
2751
+ ...withLastError(context.session, message, failureCategory),
2752
+ status: "error",
2753
+ updatedAt: nowIso()
2754
+ };
2755
+ }
2756
+ async function interruptForStop(context) {
2757
+ if (context.session.activeTurnId === void 0) return;
2758
+ const abort = new AbortController();
2759
+ const timer = setTimeout(() => abort.abort(), 2e3);
2760
+ try {
2761
+ await context.api.interrupt(context.sessionId, abort.signal);
2762
+ } catch {
2763
+ } finally {
2764
+ clearTimeout(timer);
2765
+ }
2766
+ }
2767
+ function createOpenCodeSessionLifecycle(input) {
2768
+ const { events, context, log, options } = input;
2769
+ const pending = /* @__PURE__ */ new Set();
2770
+ const stopStarted = Promise.withResolvers();
2771
+ let stopping = false;
2772
+ let exiting = false;
2773
+ let sealed = false;
2774
+ let handlersClosed = false;
2775
+ let publishing = false;
2776
+ let closing;
2777
+ let cleanup;
2778
+ const drain = async () => {
2779
+ if (!stopping) await Promise.race([context.pump, stopStarted.promise]);
2780
+ await Promise.all([...pending].map(({ task }) => task));
2781
+ };
2782
+ const close = (cause, message = "Session stopped.") => {
2783
+ if (closing) return closing;
2784
+ const work = Promise.resolve().then(async () => {
2785
+ if (!sealed) {
2786
+ let timer;
2787
+ try {
2788
+ const timedOut = await Promise.race([
2789
+ drain().catch((error) => {
2790
+ log.warn(`OpenCode tail handler failed: ${String(error)}`);
2791
+ }).then(() => false),
2792
+ new Promise((resolve2) => {
2793
+ timer = setTimeout(() => resolve2(true), options?.tailTimeoutMs ?? 2e3);
2794
+ })
2795
+ ]);
2796
+ if (timedOut) {
2797
+ log.warn("OpenCode session tail handling timed out; closing the event boundary.");
2798
+ for (const registered of pending) {
2799
+ if (registered.event.sessionId === context.sessionId && registered.turnId !== void 0 && registered.turnId === context.session.activeTurnId) {
2800
+ finishOpenCodeTurnEvent(events, context, registered.event);
2801
+ }
2802
+ }
2803
+ }
2804
+ } finally {
2805
+ clearTimeout(timer);
2806
+ handlersClosed = true;
2807
+ }
2808
+ }
2809
+ await cleanup;
2810
+ if (sealed) return;
2811
+ publishing = true;
2812
+ if (cause !== void 0 && !stopping) {
2813
+ emitUnexpectedExit(events, context, cause);
2814
+ } else {
2815
+ finishOpenCodeTurn(events, context, {
2816
+ state: "interrupted",
2817
+ reason: "Interrupted by user."
2818
+ });
2819
+ context.session = {
2820
+ ...context.session,
2821
+ status: "stopped",
2822
+ updatedAt: nowIso()
2823
+ };
2824
+ emitEvent(events, context, "session.exited", {
2825
+ reason: message,
2826
+ recoverable: false,
2827
+ exitKind: "graceful"
2828
+ });
2829
+ }
2830
+ sealed = true;
2831
+ publishing = false;
2832
+ context.stopped = true;
2833
+ context.eventAbort.abort();
2834
+ });
2835
+ closing = work;
2836
+ void work.catch(() => {
2837
+ closing = void 0;
2838
+ cleanup = void 0;
2839
+ });
2840
+ return work;
2841
+ };
2842
+ return {
2843
+ get exiting() {
2844
+ return exiting;
2845
+ },
2846
+ get closing() {
2847
+ return closing !== void 0;
2848
+ },
2849
+ get sealed() {
2850
+ return sealed;
2851
+ },
2852
+ get canEmit() {
2853
+ return !sealed && (!handlersClosed || publishing);
2854
+ },
2855
+ consume(event, handle) {
2856
+ if (stopping || handlersClosed) return Promise.resolve();
2857
+ const turnId = context.session.activeTurnId;
2858
+ const task = Promise.resolve().then(async () => {
2859
+ await options?.beforeHandleEvent?.(event);
2860
+ if (handlersClosed) return;
2861
+ await handle();
2862
+ });
2863
+ const registered = { event, turnId, task };
2864
+ pending.add(registered);
2865
+ return task.finally(() => pending.delete(registered));
2866
+ },
2867
+ exit(cause, processExited = false) {
2868
+ if (processExited) exiting = true;
2869
+ void close(cause).catch((error) => {
2870
+ log.warn(`OpenCode exit handling failed: ${String(error)}`);
2871
+ });
2872
+ },
2873
+ stop(message) {
2874
+ stopping = true;
2875
+ context.stopped = true;
2876
+ stopStarted.resolve();
2877
+ context.eventAbort.abort();
2878
+ cleanup ??= (async () => {
2879
+ await interruptForStop(context);
2880
+ await closeOpenCodeServer(context.server);
2881
+ })();
2882
+ void cleanup.catch(() => void 0);
2883
+ const ownedCleanup = cleanup;
2884
+ return close(void 0, message).then(() => ownedCleanup).catch((cause) => {
2885
+ if (cleanup === ownedCleanup) cleanup = void 0;
2886
+ throw cause;
2887
+ });
2888
+ }
2889
+ };
2890
+ }
2891
+
2720
2892
  // src/turnSelection.ts
2721
2893
  var OPENCODE_PLAN_AGENT = "plan";
2722
2894
  function openCodeSelectionOf(session) {
@@ -2760,60 +2932,13 @@ async function applyOpenCodeTurnSelection(input) {
2760
2932
  }
2761
2933
 
2762
2934
  // src/sessionEvents.ts
2763
- function exitFailureCategory(cause) {
2764
- return cause instanceof OpenCodeApiError && cause.kind !== "transport" ? void 0 : "transport";
2765
- }
2766
- function emitUnexpectedExit(events, context, cause) {
2767
- if (context.stopped) return;
2768
- context.stopped = true;
2769
- const message = cause instanceof Error && cause.message.trim().length > 0 ? cause.message.trim() : "OpenCode server exited unexpectedly.";
2770
- const failureCategory = exitFailureCategory(cause);
2771
- const category = failureCategoryField(failureCategory);
2772
- const turnId = context.session.activeTurnId;
2773
- if (turnId) {
2774
- emitEvent(events, context, "runtime.error", {
2775
- message,
2776
- class: "transport_error",
2777
- ...category
2778
- });
2779
- }
2780
- const usage = takeTurnUsage(context.usageByMessageId, context.sessionId);
2781
- if (turnId) {
2782
- emitEvent(
2783
- events,
2784
- context,
2785
- "turn.completed",
2786
- {
2787
- state: "failed",
2788
- ...usage ? { tokenUsage: usage } : {},
2789
- errorMessage: message,
2790
- ...category
2791
- },
2792
- { turnId }
2793
- );
2794
- }
2795
- emitEvent(events, context, "session.exited", {
2796
- reason: message,
2797
- recoverable: false,
2798
- exitKind: "error"
2799
- });
2800
- context.session = {
2801
- ...withLastError(withoutActiveTurn(context.session), message, failureCategory),
2802
- status: "error",
2803
- updatedAt: nowIso()
2804
- };
2805
- }
2806
- async function handleOtherSessionEvent(events, context, event) {
2935
+ async function handleOtherSessionEvent(events, context, event, discoveredChild) {
2807
2936
  const sessionId = event.sessionId;
2808
2937
  if (sessionId === void 0) return;
2809
2938
  if (event.type === "session.created") {
2810
- const parentId = event.data["parentID"];
2811
- if (typeof parentId === "string" && (parentId === context.sessionId || context.childSessionIds.has(parentId))) {
2812
- context.childSessionIds.add(sessionId);
2813
- }
2939
+ if (discoveredChild) context.childSessionIds.add(sessionId);
2814
2940
  return;
2815
2941
  }
2816
- if (!context.childSessionIds.has(sessionId)) return;
2817
2942
  if (event.type === "permission.asked" || event.type === "permission.replied") {
2818
2943
  await handleOpenCodeToolEvent({ events, context, event });
2819
2944
  return;
@@ -2871,6 +2996,7 @@ async function recoverAfterReconnect(events, context, log) {
2871
2996
  });
2872
2997
  }
2873
2998
  const current = await context.api.getSession(context.sessionId);
2999
+ if (context.stopped || context.lifecycle?.sealed) return;
2874
3000
  Object.assign(context, openCodeSelectionOf(current));
2875
3001
  if (context.session.activeTurnId === void 0) return;
2876
3002
  const outcome = current.settledOutcome;
@@ -2895,6 +3021,8 @@ async function recoverAfterReconnect(events, context, log) {
2895
3021
  }
2896
3022
  function startEventPump(input) {
2897
3023
  const { events, context, log } = input;
3024
+ const lifecycle = createOpenCodeSessionLifecycle(input);
3025
+ context.lifecycle = lifecycle;
2898
3026
  const onSkipped = (reason) => {
2899
3027
  log.warn(`OpenCode event skipped: ${reason}`);
2900
3028
  };
@@ -2912,7 +3040,7 @@ function startEventPump(input) {
2912
3040
  }, OPENCODE_EVENT_READY_TIMEOUT_MS);
2913
3041
  const fail = (cause) => {
2914
3042
  if (connected) {
2915
- emitUnexpectedExit(events, context, cause);
3043
+ lifecycle.exit(cause);
2916
3044
  return;
2917
3045
  }
2918
3046
  clearTimeout(readyTimer);
@@ -2934,18 +3062,28 @@ function startEventPump(input) {
2934
3062
  if (first) {
2935
3063
  first = false;
2936
3064
  receivedOnThisConnection = true;
2937
- if (reconnecting) await recoverAfterReconnect(events, context, log);
2938
3065
  }
2939
3066
  if (context.stopped) break;
2940
- if (event.sessionId !== void 0 && event.sessionId !== context.sessionId) {
2941
- await handleOtherSessionEvent(events, context, event);
3067
+ const sessionId = event.sessionId;
3068
+ const parentId = event.type === "session.created" ? event.data["parentID"] : void 0;
3069
+ const discoveredChild = typeof parentId === "string" && (parentId === context.sessionId || context.childSessionIds.has(parentId));
3070
+ if (sessionId !== void 0 && sessionId !== context.sessionId && !context.childSessionIds.has(sessionId) && !discoveredChild)
2942
3071
  continue;
2943
- }
2944
- if (handleOpenCodeTurnEvent({ events, context, event })) continue;
2945
- if (noteOpenCodeSelectionEvent(context, event)) continue;
2946
- if (handleOpenCodeCompactionEvent({ events, context, event })) continue;
2947
- if (handleOpenCodeFormEvent({ events, context, event })) continue;
2948
- await handleOpenCodeToolEvent({ events, context, event });
3072
+ const recover = reconnecting;
3073
+ reconnecting = false;
3074
+ await lifecycle.consume(event, async () => {
3075
+ if (recover) await recoverAfterReconnect(events, context, log);
3076
+ if (lifecycle.sealed) return;
3077
+ if (event.sessionId !== void 0 && event.sessionId !== context.sessionId) {
3078
+ await handleOtherSessionEvent(events, context, event, discoveredChild);
3079
+ return;
3080
+ }
3081
+ if (handleOpenCodeTurnEvent({ events, context, event })) return;
3082
+ if (noteOpenCodeSelectionEvent(context, event)) return;
3083
+ if (handleOpenCodeCompactionEvent({ events, context, event })) return;
3084
+ if (handleOpenCodeFormEvent({ events, context, event })) return;
3085
+ await handleOpenCodeToolEvent({ events, context, event });
3086
+ });
2949
3087
  }
2950
3088
  return new Error("OpenCode event stream ended.");
2951
3089
  } catch (cause) {
@@ -2956,6 +3094,7 @@ function startEventPump(input) {
2956
3094
  for (let attempt = 0; ; attempt += 1) {
2957
3095
  receivedOnThisConnection = false;
2958
3096
  const cause = await readOnce(attempt > 0);
3097
+ if (lifecycle.exiting) return;
2959
3098
  if (context.stopped || context.eventAbort.signal.aborted) {
2960
3099
  if (!connected) {
2961
3100
  clearTimeout(readyTimer);
@@ -2971,20 +3110,46 @@ function startEventPump(input) {
2971
3110
  }
2972
3111
  log.warn(`OpenCode event stream dropped; reconnecting in ${delay} ms`);
2973
3112
  await abortableDelay(delay, context.eventAbort.signal);
2974
- if (context.stopped || context.eventAbort.signal.aborted) return;
3113
+ if (context.stopped || lifecycle.exiting || context.eventAbort.signal.aborted) return;
2975
3114
  }
2976
3115
  })();
2977
3116
  if (!context.server.external && context.server.process) {
2978
- context.serverWatch = context.server.process.exited.then((code) => {
3117
+ void context.server.process.exited.then((code) => {
2979
3118
  if (context.stopped) return;
2980
3119
  const cause = new Error(`OpenCode server exited with code ${code}.`);
2981
- context.eventAbort.abort();
2982
- fail(cause);
3120
+ if (connected) lifecycle.exit(cause, true);
3121
+ else fail(cause);
2983
3122
  });
2984
3123
  }
2985
3124
  return ready;
2986
3125
  }
2987
3126
 
3127
+ // src/openCommands.ts
3128
+ import { sameArgv } from "@ycodium-ai/plugin-api/executor";
3129
+ var programName = (path) => (path.split(/[\\/]/).at(-1) ?? "").toLowerCase().replace(/\.(exe|cmd)$/, "");
3130
+ function opencodeCommandMatcher(command) {
3131
+ return (argv, platform) => platform === "win32" && argv.length === 3 && programName(argv[0] ?? "") === "bash" && argv[1] === "-c" && argv[2] === command;
3132
+ }
3133
+ function opencodeSessionProcessMatcher(program, args) {
3134
+ return (argv) => programName(argv[0] ?? "") === programName(program) && sameArgv(argv.slice(1), args);
3135
+ }
3136
+ function opencodeOpenCommands(context) {
3137
+ if (context === void 0 || context.stopped) return void 0;
3138
+ const owned = context.server.process;
3139
+ if (context.server.external || owned === void 0) return void 0;
3140
+ const commands = [...context.openShells].map(([toolCallId, shell]) => ({
3141
+ toolCallId,
3142
+ startedAtMs: shell.startedAtMs,
3143
+ matches: opencodeCommandMatcher(shell.command)
3144
+ }));
3145
+ if (commands.length === 0) return void 0;
3146
+ return {
3147
+ rootPid: owned.pid,
3148
+ sessionProcess: opencodeSessionProcessMatcher(owned.program, owned.args),
3149
+ commands
3150
+ };
3151
+ }
3152
+
2988
3153
  // src/textGeneration.ts
2989
3154
  import {
2990
3155
  createCatalogModelMatcher
@@ -3628,18 +3793,6 @@ function createOpenCodeTextGeneration(recipe, host) {
3628
3793
  }
3629
3794
 
3630
3795
  // src/opencodeInstance.ts
3631
- var OPENCODE_STOP_INTERRUPT_TIMEOUT_MS = 2e3;
3632
- async function interruptActiveTurnForStop(context) {
3633
- if (context.session.activeTurnId === void 0) return;
3634
- const abort = new AbortController();
3635
- const timer = setTimeout(() => abort.abort(), OPENCODE_STOP_INTERRUPT_TIMEOUT_MS);
3636
- try {
3637
- await context.api.interrupt(context.sessionId, abort.signal);
3638
- } catch {
3639
- } finally {
3640
- clearTimeout(timer);
3641
- }
3642
- }
3643
3796
  function requireCwd(input, host) {
3644
3797
  const fromInput = input.cwd?.trim() ?? "";
3645
3798
  if (fromInput.length > 0) return fromInput;
@@ -3653,12 +3806,11 @@ function sessionFromContext(context) {
3653
3806
  function requestedModelOf(modelSelection) {
3654
3807
  return modelIdFromSelection(modelSelection) ?? readString2(modelSelection?.model);
3655
3808
  }
3656
- function createOpenCodeInstance(config, host, attachments) {
3809
+ function createOpenCodeInstance(config, host, attachments, lifecycleOptions) {
3657
3810
  const recipe = parseOpenCodeInstanceConfig(config);
3658
3811
  const events = new EventBus();
3659
3812
  const sessions = /* @__PURE__ */ new Map();
3660
3813
  const pendingServers = /* @__PURE__ */ new Map();
3661
- const stops = /* @__PURE__ */ new WeakMap();
3662
3814
  const rememberPendingServer = (threadId, server) => {
3663
3815
  const pending = pendingServers.get(threadId) ?? /* @__PURE__ */ new Set();
3664
3816
  pending.add(server);
@@ -3686,36 +3838,12 @@ function createOpenCodeInstance(config, host, attachments) {
3686
3838
  const requireSession = (threadId) => {
3687
3839
  const context = sessions.get(threadId);
3688
3840
  if (!context) throw new Error(`unknown thread ${threadId}`);
3841
+ if (context.stopped || context.lifecycle?.closing)
3842
+ throw new Error("OpenCode session is closing.");
3689
3843
  return context;
3690
3844
  };
3691
- const stopContext = async (context, reason, message) => {
3692
- const pending = stops.get(context);
3693
- if (pending) return pending;
3694
- const work = (async () => {
3695
- context.stopped = true;
3696
- context.eventAbort.abort();
3697
- await interruptActiveTurnForStop(context);
3698
- await closeOpenCodeServer(context.server);
3699
- await context.pump?.catch(() => void 0);
3700
- await context.serverWatch?.catch(() => void 0);
3701
- if (reason === "graceful") {
3702
- emitEvent(events, context, "session.exited", {
3703
- reason: message ?? "Session stopped.",
3704
- recoverable: false,
3705
- exitKind: "graceful"
3706
- });
3707
- context.session = { ...context.session, status: "stopped", updatedAt: nowIso() };
3708
- } else {
3709
- emitUnexpectedExit(events, context, new Error(message ?? "OpenCode session failed."));
3710
- }
3711
- })();
3712
- stops.set(context, work);
3713
- try {
3714
- await work;
3715
- } catch (cause) {
3716
- stops.delete(context);
3717
- throw cause;
3718
- }
3845
+ const stopContext = async (context, message) => {
3846
+ await context.lifecycle?.stop(message);
3719
3847
  };
3720
3848
  const instance = {
3721
3849
  probe: (signal) => probeOpenCode({
@@ -3732,7 +3860,7 @@ function createOpenCodeInstance(config, host, attachments) {
3732
3860
  if (disposed) throw new Error("OpenCode instance has been disposed.");
3733
3861
  const existing = sessions.get(input.threadId);
3734
3862
  if (existing) {
3735
- await stopContext(existing, "graceful", "Replaced by a new session.");
3863
+ await stopContext(existing, "Replaced by a new session.");
3736
3864
  sessions.delete(input.threadId);
3737
3865
  }
3738
3866
  await closePendingServers(input.threadId);
@@ -3857,7 +3985,6 @@ function createOpenCodeInstance(config, host, attachments) {
3857
3985
  server,
3858
3986
  eventAbort: new AbortController(),
3859
3987
  pump: void 0,
3860
- serverWatch: void 0,
3861
3988
  stopped: false,
3862
3989
  usageByMessageId: /* @__PURE__ */ new Map(),
3863
3990
  assistantTextByPartId: /* @__PURE__ */ new Map(),
@@ -3865,6 +3992,7 @@ function createOpenCodeInstance(config, host, attachments) {
3865
3992
  stepModels: /* @__PURE__ */ new Map(),
3866
3993
  toolNames: /* @__PURE__ */ new Map(),
3867
3994
  toolInputs: /* @__PURE__ */ new Map(),
3995
+ openShells: /* @__PURE__ */ new Map(),
3868
3996
  pendingPermissions: /* @__PURE__ */ new Map(),
3869
3997
  pendingForms: /* @__PURE__ */ new Map(),
3870
3998
  childSessionIds: /* @__PURE__ */ new Set(),
@@ -3877,7 +4005,12 @@ function createOpenCodeInstance(config, host, attachments) {
3877
4005
  ...selection,
3878
4006
  matchModel
3879
4007
  };
3880
- await startEventPump({ events, context, log: host.log });
4008
+ await startEventPump({
4009
+ events,
4010
+ context,
4011
+ log: host.log,
4012
+ ...lifecycleOptions ? { options: lifecycleOptions } : {}
4013
+ });
3881
4014
  const winner = sessions.get(input.threadId);
3882
4015
  if (winner) {
3883
4016
  context.stopped = true;
@@ -3984,6 +4117,7 @@ function createOpenCodeInstance(config, host, attachments) {
3984
4117
  await staged.cleanup();
3985
4118
  }
3986
4119
  },
4120
+ openCommandProcesses: async (threadId) => opencodeOpenCommands(sessions.get(threadId)),
3987
4121
  interruptTurn: async (threadId, turnId) => {
3988
4122
  const context = requireSession(threadId);
3989
4123
  if (turnId !== void 0 && context.session.activeTurnId !== turnId) {
@@ -3997,15 +4131,12 @@ function createOpenCodeInstance(config, host, attachments) {
3997
4131
  );
3998
4132
  const active = context.session.activeTurnId;
3999
4133
  if (active && (turnId === void 0 || turnId === active)) {
4000
- emitEvent(
4001
- events,
4002
- context,
4003
- "turn.aborted",
4004
- { reason: "Interrupted by user." },
4005
- { turnId: active }
4006
- );
4134
+ finishOpenCodeTurn(events, context, {
4135
+ state: "interrupted",
4136
+ reason: "Interrupted by user."
4137
+ });
4007
4138
  context.session = {
4008
- ...withoutActiveTurn(context.session),
4139
+ ...context.session,
4009
4140
  status: "ready",
4010
4141
  updatedAt: nowIso()
4011
4142
  };
@@ -4040,7 +4171,7 @@ function createOpenCodeInstance(config, host, attachments) {
4040
4171
  stopSession: async (threadId) => {
4041
4172
  const context = sessions.get(threadId);
4042
4173
  if (context) {
4043
- await stopContext(context, "graceful");
4174
+ await stopContext(context);
4044
4175
  if (sessions.get(threadId) === context) sessions.delete(threadId);
4045
4176
  }
4046
4177
  await closePendingServers(threadId);
@@ -4100,7 +4231,7 @@ var executors = [
4100
4231
  ];
4101
4232
  var index_default = definePlugin({
4102
4233
  id: "agent-opencode",
4103
- apiVersion: 14,
4234
+ apiVersion: 16,
4104
4235
  executors,
4105
4236
  activate(ctx) {
4106
4237
  capturedAttachments = ctx.attachments;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ycodium-ai/agent-opencode",
3
- "version": "0.2.3130",
3
+ "version": "0.2.3168",
4
4
  "description": "OpenCode executor: OpenCode CLI (2.x) over its HTTP API.",
5
5
  "keywords": [
6
6
  "ycodium",
@@ -21,10 +21,10 @@
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.3130",
25
- "ycodium-executor-testing": "0.0.0",
24
+ "@ycodium-ai/plugin-api": "0.2.3168",
25
+ "ycodium-sse-stream": "0.0.0",
26
26
  "ycodium-fetch-ports": "0.0.0",
27
- "ycodium-sse-stream": "0.0.0"
27
+ "ycodium-executor-testing": "0.0.0"
28
28
  },
29
29
  "ycodium": {
30
30
  "plugin": "./dist/index.js",