@ycodium-ai/agent-opencode 0.2.3976 → 0.2.3990

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 +106 -161
  2. package/package.json +4 -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 = 75;
8
+ var PLUGIN_API_VERSION = 77;
9
9
 
10
10
  // src/card.ts
11
11
  var OPENCODE_DRIVER_KIND = "opencode";
@@ -271,40 +271,6 @@ function hideGenericEffectText(message) {
271
271
  return trimmed;
272
272
  }
273
273
 
274
- // src/events.ts
275
- var EventBus = class {
276
- #queued = [];
277
- #waiters = [];
278
- #closed = false;
279
- push(event) {
280
- const waiter = this.#waiters.shift();
281
- if (waiter) {
282
- waiter({ done: false, value: event });
283
- return;
284
- }
285
- this.#queued.push(event);
286
- }
287
- close() {
288
- if (this.#closed) return;
289
- this.#closed = true;
290
- while (this.#waiters.length > 0) {
291
- this.#waiters.shift()?.({ done: true, value: void 0 });
292
- }
293
- }
294
- [Symbol.asyncIterator]() {
295
- return {
296
- next: () => {
297
- const queued = this.#queued.shift();
298
- if (queued !== void 0) return Promise.resolve({ done: false, value: queued });
299
- if (this.#closed) return Promise.resolve({ done: true, value: void 0 });
300
- return new Promise((resolve2) => {
301
- this.#waiters.push(resolve2);
302
- });
303
- }
304
- };
305
- }
306
- };
307
-
308
274
  // src/fileParts.ts
309
275
  import * as NodeFSP from "node:fs/promises";
310
276
  import * as NodeOS from "node:os";
@@ -393,7 +359,7 @@ function withLastError(session, lastError, failureCategory) {
393
359
  function openCodeModelLabel(ref) {
394
360
  return `${ref.providerID}/${ref.id}`;
395
361
  }
396
- function emitEvent(events, context, type2, payload, extra) {
362
+ function emitEvent(context, type2, payload, extra) {
397
363
  if (context.lifecycle?.canEmit === false) return;
398
364
  const turnId = extra?.turnId ?? context.session.activeTurnId;
399
365
  const event = {
@@ -409,16 +375,16 @@ function emitEvent(events, context, type2, payload, extra) {
409
375
  ...extra?.requestId ? { requestId: extra.requestId } : {},
410
376
  providerRefs: {}
411
377
  };
412
- events.push(event);
378
+ context.events.emit(event);
413
379
  }
414
- function reportOpenCodeModel(events, context, ref) {
380
+ function reportOpenCodeModel(context, ref) {
415
381
  const turnId = context.session.activeTurnId;
416
382
  if (turnId === void 0) return;
417
383
  const model = openCodeModelLabel(ref);
418
384
  const key = `${turnId}|${model}`;
419
385
  if (context.reportedModelKey === key) return;
420
386
  context.reportedModelKey = key;
421
- emitEvent(events, context, "thread.metadata.updated", { model, modelSource: "reported" });
387
+ emitEvent(context, "thread.metadata.updated", { model, modelSource: "reported" });
422
388
  }
423
389
 
424
390
  // src/formEvents.ts
@@ -449,16 +415,16 @@ function readForm(form) {
449
415
  }
450
416
  return fields.length === 0 ? void 0 : { id, pending: { sessionId, fields } };
451
417
  }
452
- function settle(events, context, formId, answers) {
418
+ function settle(context, formId, answers) {
453
419
  if (!context.pendingForms.delete(formId)) return;
454
- emitEvent(events, context, "user-input.resolved", { answers }, { requestId: formId });
420
+ emitEvent(context, "user-input.resolved", { answers }, { requestId: formId });
455
421
  if (context.pendingForms.size === 0 && context.pendingPermissions.size === 0 && context.session.activeTurnId !== void 0) {
456
422
  context.session = { ...context.session, status: "running", updatedAt: nowIso() };
457
- emitEvent(events, context, "session.state.changed", { state: "running" });
423
+ emitEvent(context, "session.state.changed", { state: "running" });
458
424
  }
459
425
  }
460
426
  function handleOpenCodeFormEvent(input) {
461
- const { events, context, event } = input;
427
+ const { context, event } = input;
462
428
  switch (event.type) {
463
429
  case "form.created": {
464
430
  const form = isRecord2(event.data["form"]) ? readForm(event.data["form"]) : void 0;
@@ -470,7 +436,6 @@ function handleOpenCodeFormEvent(input) {
470
436
  if (context.pendingForms.has(id)) return true;
471
437
  context.pendingForms.set(id, pending);
472
438
  emitEvent(
473
- events,
474
439
  context,
475
440
  "user-input.requested",
476
441
  {
@@ -484,17 +449,17 @@ function handleOpenCodeFormEvent(input) {
484
449
  { requestId: id }
485
450
  );
486
451
  context.session = { ...context.session, status: "waiting", updatedAt: nowIso() };
487
- emitEvent(events, context, "session.state.changed", { state: "waiting" });
452
+ emitEvent(context, "session.state.changed", { state: "waiting" });
488
453
  return true;
489
454
  }
490
455
  case "form.replied": {
491
456
  const id = text(event.data, "id");
492
- if (id !== void 0) settle(events, context, id, event.data["answer"]);
457
+ if (id !== void 0) settle(context, id, event.data["answer"]);
493
458
  return true;
494
459
  }
495
460
  case "form.cancelled": {
496
461
  const id = text(event.data, "id");
497
- if (id !== void 0) settle(events, context, id, { rejected: true });
462
+ if (id !== void 0) settle(context, id, { rejected: true });
498
463
  return true;
499
464
  }
500
465
  default:
@@ -2434,7 +2399,7 @@ function takeTurnUsage(usageByMessageId, sessionId) {
2434
2399
 
2435
2400
  // src/compactionEvents.ts
2436
2401
  function handleOpenCodeCompactionEvent(input) {
2437
- const { events, context, event } = input;
2402
+ const { context, event } = input;
2438
2403
  switch (event.type) {
2439
2404
  case "session.compaction.started": {
2440
2405
  const compaction = {
@@ -2443,8 +2408,8 @@ function handleOpenCodeCompactionEvent(input) {
2443
2408
  };
2444
2409
  context.compaction = compaction;
2445
2410
  context.session = { ...context.session, status: "compacting", updatedAt: nowIso() };
2446
- emitEvent(events, context, "session.state.changed", { state: "compacting" });
2447
- emitEvent(events, context, "thread.state.changed", { state: "compacting", compaction });
2411
+ emitEvent(context, "session.state.changed", { state: "compacting" });
2412
+ emitEvent(context, "thread.state.changed", { state: "compacting", compaction });
2448
2413
  return true;
2449
2414
  }
2450
2415
  case "session.compaction.delta":
@@ -2459,10 +2424,10 @@ function handleOpenCodeCompactionEvent(input) {
2459
2424
  typeof summary === "string" ? summary : void 0
2460
2425
  );
2461
2426
  context.compaction = void 0;
2462
- emitEvent(events, context, "thread.state.changed", { state: "compacted", compaction });
2427
+ emitEvent(context, "thread.state.changed", { state: "compacted", compaction });
2463
2428
  if (context.session.activeTurnId !== void 0) {
2464
2429
  context.session = { ...context.session, status: "running", updatedAt: nowIso() };
2465
- emitEvent(events, context, "session.state.changed", { state: "running" });
2430
+ emitEvent(context, "session.state.changed", { state: "running" });
2466
2431
  }
2467
2432
  return true;
2468
2433
  }
@@ -2529,25 +2494,25 @@ function activate(context, childId, names, callId, background) {
2529
2494
  context.childSessionIds.add(childId);
2530
2495
  return activation;
2531
2496
  }
2532
- function settleActivation(events, context, childId, status, boundary) {
2497
+ function settleActivation(context, childId, status, boundary) {
2533
2498
  const state = context.subagents;
2534
2499
  const activation = state.children.get(childId);
2535
2500
  if (activation === void 0 || activation.ended !== void 0) return;
2536
2501
  activation.ended = status;
2537
2502
  activation.endBoundary = boundary;
2538
2503
  const identity = { taskId: childId, ...identityOf(childId, activation, activation.callId) };
2539
- emitEvent(events, context, "task.completed", {
2504
+ emitEvent(context, "task.completed", {
2540
2505
  ...identity,
2541
2506
  status,
2542
2507
  ...activation.summary === void 0 ? {} : { summary: activation.summary }
2543
2508
  });
2544
2509
  }
2545
- function attachResult(events, context, childId, summary) {
2510
+ function attachResult(context, childId, summary) {
2546
2511
  const activation = context.subagents.children.get(childId);
2547
2512
  if (activation === void 0 || summary === void 0 || activation.summary !== void 0) return;
2548
2513
  activation.summary = summary;
2549
2514
  if (activation.ended === void 0) return;
2550
- emitEvent(events, context, "task.completed", {
2515
+ emitEvent(context, "task.completed", {
2551
2516
  taskId: childId,
2552
2517
  ...identityOf(childId, activation, activation.callId),
2553
2518
  status: activation.ended,
@@ -2572,7 +2537,7 @@ function noteSubagentInput(context, callId, input) {
2572
2537
  if (resumeId !== void 0) call.resumeId = resumeId;
2573
2538
  call.background = input["background"] === true;
2574
2539
  }
2575
- function attach(events, context, callId, call, childId) {
2540
+ function attach(context, callId, call, childId) {
2576
2541
  const state = context.subagents;
2577
2542
  if (call.childId !== void 0) return;
2578
2543
  const previous = state.children.get(childId);
@@ -2589,19 +2554,19 @@ function attach(events, context, callId, call, childId) {
2589
2554
  };
2590
2555
  activate(context, childId, names, callId, call.background);
2591
2556
  const identity = { taskId: childId, ...identityOf(childId, names, callId) };
2592
- emitEvent(events, context, "task.started", {
2557
+ emitEvent(context, "task.started", {
2593
2558
  ...identity,
2594
2559
  ...names.title === void 0 ? {} : { description: names.title }
2595
2560
  });
2596
- if (resumed) emitEvent(events, context, "task.updated", { ...identity, status: "running" });
2561
+ if (resumed) emitEvent(context, "task.updated", { ...identity, status: "running" });
2597
2562
  }
2598
- function attachSubagentCall(events, context, callId, metadata) {
2563
+ function attachSubagentCall(context, callId, metadata) {
2599
2564
  const call = context.subagents.calls.get(callId);
2600
2565
  const childId = readString2(metadata["sessionID"]);
2601
2566
  if (call === void 0 || childId === void 0) return;
2602
- attach(events, context, callId, call, childId);
2567
+ attach(context, callId, call, childId);
2603
2568
  }
2604
- function settleSubagentCall(events, context, callId, result) {
2569
+ function settleSubagentCall(context, callId, result) {
2605
2570
  const state = context.subagents;
2606
2571
  const metadata = isRecord2(result.data["metadata"]) ? result.data["metadata"] : {};
2607
2572
  const call = state.calls.get(callId);
@@ -2614,7 +2579,7 @@ function settleSubagentCall(events, context, callId, result) {
2614
2579
  let childId = call === void 0 ? linked : call.childId;
2615
2580
  if (call !== void 0 && childId === void 0 && !result.failed) {
2616
2581
  childId = readString2(metadata["sessionID"]);
2617
- if (childId !== void 0) attach(events, context, callId, call, childId);
2582
+ if (childId !== void 0) attach(context, callId, call, childId);
2618
2583
  }
2619
2584
  const activation = childId === void 0 ? void 0 : state.children.get(childId);
2620
2585
  if (childId === void 0 || activation === void 0) return;
@@ -2627,7 +2592,7 @@ function settleSubagentCall(events, context, callId, result) {
2627
2592
  const message = isRecord2(error) ? readString2(error["message"]) : void 0;
2628
2593
  const aborted = isRecord2(error) && readString2(error["type"]) === "aborted";
2629
2594
  const text4 = result.failed ? aborted ? void 0 : message : result.output;
2630
- attachResult(events, context, childId, summaryOf(text4));
2595
+ attachResult(context, childId, summaryOf(text4));
2631
2596
  }
2632
2597
  function announceSubagentSession(context, sessionId, data) {
2633
2598
  const title = readString2(data["title"]);
@@ -2639,7 +2604,7 @@ function announceSubagentSession(context, sessionId, data) {
2639
2604
  ...model === void 0 ? {} : { model }
2640
2605
  });
2641
2606
  }
2642
- function reportSubagentInbox(events, context, event) {
2607
+ function reportSubagentInbox(context, event) {
2643
2608
  if (event.type !== "session.inbox.enqueued") return false;
2644
2609
  const item = event.data["item"];
2645
2610
  const payload = isRecord2(item) && item["type"] === "synthetic" ? item["payload"] : void 0;
@@ -2660,7 +2625,7 @@ function reportSubagentInbox(events, context, event) {
2660
2625
  const key = readString2(event.data["inboxID"]) ?? `${childId}:${summary ?? ""}`;
2661
2626
  if (context.subagents.reports.has(key)) return true;
2662
2627
  context.subagents.reports.add(key);
2663
- attachResult(events, context, childId, summary);
2628
+ attachResult(context, childId, summary);
2664
2629
  return true;
2665
2630
  }
2666
2631
  function subagentOutcome(settled) {
@@ -2677,7 +2642,7 @@ function subagentOutcome(settled) {
2677
2642
  return void 0;
2678
2643
  }
2679
2644
  }
2680
- function endSubagentFromExecution(events, context, childId, event) {
2645
+ function endSubagentFromExecution(context, childId, event) {
2681
2646
  if (event.type === "session.execution.started") {
2682
2647
  const state = context.subagents;
2683
2648
  if (event.sequence !== void 0) {
@@ -2697,7 +2662,7 @@ function endSubagentFromExecution(events, context, childId, event) {
2697
2662
  activation.endBoundary = event.sequence;
2698
2663
  return;
2699
2664
  }
2700
- settleActivation(events, context, childId, status, event.sequence);
2665
+ settleActivation(context, childId, status, event.sequence);
2701
2666
  }
2702
2667
  function noteChildSequence(context, event) {
2703
2668
  const state = context.subagents;
@@ -2705,22 +2670,22 @@ function noteChildSequence(context, event) {
2705
2670
  const seen = state.childSequence.get(event.sessionId);
2706
2671
  state.childSequence.set(event.sessionId, Math.max(seen ?? event.sequence, event.sequence));
2707
2672
  }
2708
- function finishSubagentsForTurn(events, context, outcome) {
2673
+ function finishSubagentsForTurn(context, outcome) {
2709
2674
  if (outcome.sessionEnds) return;
2710
2675
  for (const [childId, activation] of context.subagents.children) {
2711
2676
  if (activation.ended !== void 0 || activation.background) continue;
2712
2677
  activation.background = true;
2713
- emitEvent(events, context, "task.updated", {
2678
+ emitEvent(context, "task.updated", {
2714
2679
  taskId: childId,
2715
2680
  ...identityOf(childId, activation, activation.callId),
2716
2681
  status: "idle"
2717
2682
  });
2718
2683
  }
2719
2684
  }
2720
- function stopSubagents(events, context, confirmed) {
2685
+ function stopSubagents(context, confirmed) {
2721
2686
  for (const childId of confirmed) {
2722
2687
  const boundary = context.subagents.childSequence.get(childId);
2723
- settleActivation(events, context, childId, "stopped", boundary);
2688
+ settleActivation(context, childId, "stopped", boundary);
2724
2689
  }
2725
2690
  }
2726
2691
  async function registerChildSessions(context, log) {
@@ -2741,10 +2706,10 @@ async function registerChildSessions(context, log) {
2741
2706
  );
2742
2707
  }
2743
2708
  }
2744
- function markSubagentsUnknown(events, context) {
2709
+ function markSubagentsUnknown(context) {
2745
2710
  for (const [childId, activation] of context.subagents.children) {
2746
2711
  if (activation.ended !== void 0) continue;
2747
- emitEvent(events, context, "task.updated", {
2712
+ emitEvent(context, "task.updated", {
2748
2713
  taskId: childId,
2749
2714
  ...identityOf(childId, activation, activation.callId),
2750
2715
  status: "idle",
@@ -2823,10 +2788,9 @@ function fileChangesOf(metadata) {
2823
2788
  }
2824
2789
  return changes.length > 0 ? changes : void 0;
2825
2790
  }
2826
- function emitTool(events, context, callId, phase, status, state, extra = {}) {
2791
+ function emitTool(context, callId, phase, status, state, extra = {}) {
2827
2792
  const tool = context.toolNames.get(callId) ?? "tool";
2828
2793
  emitEvent(
2829
- events,
2830
2794
  context,
2831
2795
  phase,
2832
2796
  {
@@ -2839,7 +2803,7 @@ function emitTool(events, context, callId, phase, status, state, extra = {}) {
2839
2803
  { itemId: callId }
2840
2804
  );
2841
2805
  }
2842
- async function openPermission(events, context, data) {
2806
+ async function openPermission(context, data) {
2843
2807
  const requestId = text2(data, "id");
2844
2808
  const action = text2(data, "action");
2845
2809
  const sessionId = text2(data, "sessionID") ?? context.sessionId;
@@ -2868,7 +2832,6 @@ async function openPermission(events, context, data) {
2868
2832
  ...toolCallId === void 0 ? {} : { toolCallId }
2869
2833
  });
2870
2834
  emitEvent(
2871
- events,
2872
2835
  context,
2873
2836
  "request.opened",
2874
2837
  {
@@ -2882,9 +2845,9 @@ async function openPermission(events, context, data) {
2882
2845
  { requestId }
2883
2846
  );
2884
2847
  context.session = { ...context.session, status: "waiting", updatedAt: nowIso() };
2885
- emitEvent(events, context, "session.state.changed", { state: "waiting" });
2848
+ emitEvent(context, "session.state.changed", { state: "waiting" });
2886
2849
  }
2887
- function resolvePermission(events, context, data) {
2850
+ function resolvePermission(context, data) {
2888
2851
  const requestId = text2(data, "requestID");
2889
2852
  const reply = text2(data, "reply");
2890
2853
  if (requestId === void 0 || reply === void 0) return;
@@ -2899,7 +2862,6 @@ function resolvePermission(events, context, data) {
2899
2862
  const reason = context.declineReasons.get(requestId);
2900
2863
  context.declineReasons.delete(requestId);
2901
2864
  emitEvent(
2902
- events,
2903
2865
  context,
2904
2866
  "request.resolved",
2905
2867
  {
@@ -2911,18 +2873,18 @@ function resolvePermission(events, context, data) {
2911
2873
  );
2912
2874
  if (context.pendingPermissions.size === 0 && context.pendingForms.size === 0 && context.session.activeTurnId !== void 0) {
2913
2875
  context.session = { ...context.session, status: "running", updatedAt: nowIso() };
2914
- emitEvent(events, context, "session.state.changed", { state: "running" });
2876
+ emitEvent(context, "session.state.changed", { state: "running" });
2915
2877
  }
2916
2878
  }
2917
2879
  async function handleOpenCodeToolEvent(input) {
2918
- const { events, context, event } = input;
2880
+ const { context, event } = input;
2919
2881
  const data = event.data;
2920
2882
  switch (event.type) {
2921
2883
  case "permission.asked":
2922
- await openPermission(events, context, data);
2884
+ await openPermission(context, data);
2923
2885
  return true;
2924
2886
  case "permission.replied":
2925
- resolvePermission(events, context, data);
2887
+ resolvePermission(context, data);
2926
2888
  return true;
2927
2889
  case "session.tool.input.started": {
2928
2890
  const callId = text2(data, "id");
@@ -2930,7 +2892,7 @@ async function handleOpenCodeToolEvent(input) {
2930
2892
  if (callId === void 0 || name === void 0) return true;
2931
2893
  context.toolNames.set(callId, name);
2932
2894
  if (name === OPENCODE_SUBAGENT_TOOL) beginSubagentCall(context, callId);
2933
- emitTool(events, context, callId, "item.started", "inProgress", "pending");
2895
+ emitTool(context, callId, "item.started", "inProgress", "pending");
2934
2896
  return true;
2935
2897
  }
2936
2898
  case "session.tool.input.delta":
@@ -2939,7 +2901,7 @@ async function handleOpenCodeToolEvent(input) {
2939
2901
  const callId = text2(data, "id");
2940
2902
  const argumentText = text2(data, "text");
2941
2903
  if (callId === void 0 || argumentText === void 0) return true;
2942
- emitTool(events, context, callId, "item.updated", "inProgress", "pending", {
2904
+ emitTool(context, callId, "item.updated", "inProgress", "pending", {
2943
2905
  data: { argumentText }
2944
2906
  });
2945
2907
  return true;
@@ -2949,7 +2911,7 @@ async function handleOpenCodeToolEvent(input) {
2949
2911
  if (callId === void 0) return true;
2950
2912
  const toolInput = isRecord2(data["input"]) ? data["input"] : void 0;
2951
2913
  if (toolInput !== void 0) context.toolInputs.set(callId, toolInput);
2952
- emitTool(events, context, callId, "item.updated", "inProgress", "running", {
2914
+ emitTool(context, callId, "item.updated", "inProgress", "running", {
2953
2915
  data: toolInput === void 0 ? {} : { input: toolInput }
2954
2916
  });
2955
2917
  if (toolInput !== void 0) noteSubagentInput(context, callId, toolInput);
@@ -2963,13 +2925,13 @@ async function handleOpenCodeToolEvent(input) {
2963
2925
  if (context.toolNames.get(callId) === "shell" && text2(data["metadata"], "shellID") !== void 0 && typeof command === "string" && !context.openShells.has(callId)) {
2964
2926
  context.openShells.set(callId, { command, startedAtMs: Date.now() });
2965
2927
  }
2966
- emitTool(events, context, callId, "item.updated", "inProgress", "running", {
2928
+ emitTool(context, callId, "item.updated", "inProgress", "running", {
2967
2929
  data: {
2968
2930
  ...toolInput === void 0 ? {} : { input: toolInput },
2969
2931
  metadata: data["metadata"]
2970
2932
  }
2971
2933
  });
2972
- attachSubagentCall(events, context, callId, data["metadata"]);
2934
+ attachSubagentCall(context, callId, data["metadata"]);
2973
2935
  return true;
2974
2936
  }
2975
2937
  case "session.tool.success":
@@ -2986,7 +2948,6 @@ async function handleOpenCodeToolEvent(input) {
2986
2948
  const toolInput = context.toolInputs.get(callId);
2987
2949
  const media = Array.isArray(data["content"]) ? data["content"].flatMap(inlineMediaOf) : [];
2988
2950
  emitTool(
2989
- events,
2990
2951
  context,
2991
2952
  callId,
2992
2953
  "item.completed",
@@ -3002,7 +2963,7 @@ async function handleOpenCodeToolEvent(input) {
3002
2963
  }
3003
2964
  }
3004
2965
  );
3005
- settleSubagentCall(events, context, callId, { failed, data, output });
2966
+ settleSubagentCall(context, callId, { failed, data, output });
3006
2967
  context.toolNames.delete(callId);
3007
2968
  context.toolInputs.delete(callId);
3008
2969
  context.openShells.delete(callId);
@@ -3014,7 +2975,7 @@ async function handleOpenCodeToolEvent(input) {
3014
2975
  }
3015
2976
 
3016
2977
  // src/turnCompletion.ts
3017
- function finishOpenCodeTurn(events, context, outcome) {
2978
+ function finishOpenCodeTurn(context, outcome) {
3018
2979
  const turnId = context.session.activeTurnId;
3019
2980
  const usage = takeTurnUsage(context.usageByMessageId, context.sessionId);
3020
2981
  context.abortedByDecline = false;
@@ -3023,18 +2984,17 @@ function finishOpenCodeTurn(events, context, outcome) {
3023
2984
  context.stepModels.clear();
3024
2985
  context.assistantTextByPartId.clear();
3025
2986
  context.completedTextParts.clear();
3026
- finishSubagentsForTurn(events, context, {
2987
+ finishSubagentsForTurn(context, {
3027
2988
  sessionEnds: outcome.state !== "completed" && outcome.sessionEnds === true
3028
2989
  });
3029
2990
  if (turnId === void 0) return;
3030
2991
  if (outcome.state === "interrupted") {
3031
- emitEvent(events, context, "turn.aborted", { reason: outcome.reason }, { turnId });
2992
+ emitEvent(context, "turn.aborted", { reason: outcome.reason }, { turnId });
3032
2993
  context.session = { ...withoutActiveTurn(context.session), updatedAt: nowIso() };
3033
2994
  return;
3034
2995
  }
3035
2996
  if (outcome.state === "completed") {
3036
2997
  emitEvent(
3037
- events,
3038
2998
  context,
3039
2999
  "turn.completed",
3040
3000
  { state: "completed", ...usage ? { tokenUsage: usage } : {} },
@@ -3045,7 +3005,6 @@ function finishOpenCodeTurn(events, context, outcome) {
3045
3005
  }
3046
3006
  const { errorMessage, failureCategory } = outcome;
3047
3007
  emitEvent(
3048
- events,
3049
3008
  context,
3050
3009
  "turn.completed",
3051
3010
  {
@@ -3061,16 +3020,16 @@ function finishOpenCodeTurn(events, context, outcome) {
3061
3020
  updatedAt: nowIso()
3062
3021
  };
3063
3022
  }
3064
- function finishOpenCodeTurnEvent(events, context, event) {
3023
+ function finishOpenCodeTurnEvent(context, event) {
3065
3024
  switch (event.type) {
3066
3025
  case "session.execution.succeeded":
3067
- finishOpenCodeTurn(events, context, { state: "completed" });
3026
+ finishOpenCodeTurn(context, { state: "completed" });
3068
3027
  return true;
3069
3028
  case "session.execution.failed": {
3070
3029
  const errorMessage = openCodeFailureMessage(event.data["error"]);
3071
3030
  const failureCategory = openCodeFailureCategory(event.data["error"]);
3072
- finishOpenCodeTurn(events, context, { state: "failed", errorMessage, failureCategory });
3073
- emitEvent(events, context, "runtime.error", {
3031
+ finishOpenCodeTurn(context, { state: "failed", errorMessage, failureCategory });
3032
+ emitEvent(context, "runtime.error", {
3074
3033
  message: errorMessage,
3075
3034
  class: "provider_error",
3076
3035
  ...failureCategoryField(failureCategory)
@@ -3080,7 +3039,7 @@ function finishOpenCodeTurnEvent(events, context, event) {
3080
3039
  case "session.execution.interrupted": {
3081
3040
  const value = event.data["reason"];
3082
3041
  const reason = typeof value === "string" ? value : void 0;
3083
- finishOpenCodeTurn(events, context, {
3042
+ finishOpenCodeTurn(context, {
3084
3043
  state: "interrupted",
3085
3044
  reason: reason === void 0 || reason === "user" ? "Interrupted by user." : reason === "shutdown" && context.abortedByDecline ? "Declined by user." : `Interrupted (${reason}).`
3086
3045
  });
@@ -3090,18 +3049,18 @@ function finishOpenCodeTurnEvent(events, context, event) {
3090
3049
  return false;
3091
3050
  }
3092
3051
  }
3093
- function finishOpenCodeTurnOnExit(events, context, cause) {
3052
+ function finishOpenCodeTurnOnExit(context, cause) {
3094
3053
  const message = cause instanceof Error && cause.message.trim().length > 0 ? cause.message.trim() : "OpenCode server exited unexpectedly.";
3095
3054
  const failureCategory = cause instanceof OpenCodeApiError && cause.kind !== "transport" ? void 0 : "transport";
3096
3055
  const turnId = context.session.activeTurnId;
3097
3056
  if (turnId) {
3098
- emitEvent(events, context, "runtime.error", {
3057
+ emitEvent(context, "runtime.error", {
3099
3058
  message,
3100
3059
  class: "transport_error",
3101
3060
  ...failureCategoryField(failureCategory)
3102
3061
  });
3103
3062
  }
3104
- finishOpenCodeTurn(events, context, {
3063
+ finishOpenCodeTurn(context, {
3105
3064
  state: "failed",
3106
3065
  errorMessage: message,
3107
3066
  failureCategory,
@@ -3123,9 +3082,9 @@ var streamItemId = (data, kind) => {
3123
3082
  }
3124
3083
  return `${messageId}:${kind}:${ordinal}`;
3125
3084
  };
3126
- function settleSession(events, context) {
3085
+ function settleSession(context) {
3127
3086
  context.session = { ...context.session, status: "ready", updatedAt: nowIso() };
3128
- emitEvent(events, context, "session.state.changed", { state: "ready" });
3087
+ emitEvent(context, "session.state.changed", { state: "ready" });
3129
3088
  }
3130
3089
  function remainderOf(context, itemId, full) {
3131
3090
  const sent = context.assistantTextByPartId.get(itemId) ?? "";
@@ -3133,7 +3092,7 @@ function remainderOf(context, itemId, full) {
3133
3092
  if (full.startsWith(sent)) return full.slice(sent.length);
3134
3093
  return "";
3135
3094
  }
3136
- function appendDelta(events, context, data, kind) {
3095
+ function appendDelta(context, data, kind) {
3137
3096
  const itemId = streamItemId(data, kind);
3138
3097
  const delta = text3(data, "delta");
3139
3098
  if (itemId === void 0 || delta === void 0 || delta.length === 0) return;
@@ -3142,21 +3101,19 @@ function appendDelta(events, context, data, kind) {
3142
3101
  (context.assistantTextByPartId.get(itemId) ?? "") + delta
3143
3102
  );
3144
3103
  emitEvent(
3145
- events,
3146
3104
  context,
3147
3105
  "content.delta",
3148
3106
  { streamKind: kind === "text" ? "assistant_text" : "reasoning_text", delta },
3149
3107
  { itemId }
3150
3108
  );
3151
3109
  }
3152
- function endStream(events, context, data, kind) {
3110
+ function endStream(context, data, kind) {
3153
3111
  const itemId = streamItemId(data, kind);
3154
3112
  const full = text3(data, "text");
3155
3113
  if (itemId === void 0 || full === void 0) return;
3156
3114
  const delta = remainderOf(context, itemId, full);
3157
3115
  if (delta.length > 0) {
3158
3116
  emitEvent(
3159
- events,
3160
3117
  context,
3161
3118
  "content.delta",
3162
3119
  { streamKind: kind === "text" ? "assistant_text" : "reasoning_text", delta },
@@ -3166,7 +3123,6 @@ function endStream(events, context, data, kind) {
3166
3123
  if (kind !== "text" || full.length === 0 || context.completedTextParts.has(itemId)) return;
3167
3124
  context.completedTextParts.add(itemId);
3168
3125
  emitEvent(
3169
- events,
3170
3126
  context,
3171
3127
  "item.completed",
3172
3128
  { itemType: "assistant_message", status: "completed", detail: full },
@@ -3174,9 +3130,9 @@ function endStream(events, context, data, kind) {
3174
3130
  );
3175
3131
  }
3176
3132
  function handleOpenCodeTurnEvent(input) {
3177
- const { events, context, event } = input;
3178
- if (finishOpenCodeTurnEvent(events, context, event)) {
3179
- settleSession(events, context);
3133
+ const { context, event } = input;
3134
+ if (finishOpenCodeTurnEvent(context, event)) {
3135
+ settleSession(context);
3180
3136
  return true;
3181
3137
  }
3182
3138
  const data = event.data;
@@ -3184,7 +3140,7 @@ function handleOpenCodeTurnEvent(input) {
3184
3140
  case "session.execution.started": {
3185
3141
  if (context.session.status !== "running") {
3186
3142
  context.session = { ...context.session, status: "running", updatedAt: nowIso() };
3187
- emitEvent(events, context, "session.state.changed", { state: "running" });
3143
+ emitEvent(context, "session.state.changed", { state: "running" });
3188
3144
  }
3189
3145
  return true;
3190
3146
  }
@@ -3193,7 +3149,7 @@ function handleOpenCodeTurnEvent(input) {
3193
3149
  const messageId = text3(data, "assistantMessageID");
3194
3150
  const model = data["model"];
3195
3151
  const stepModel = decodeOpenCodeModelRef(model);
3196
- if (stepModel !== void 0) reportOpenCodeModel(events, context, stepModel);
3152
+ if (stepModel !== void 0) reportOpenCodeModel(context, stepModel);
3197
3153
  if (messageId === void 0 || !isRecord2(model)) return true;
3198
3154
  const providerId = model["providerID"];
3199
3155
  const modelId = model["id"];
@@ -3218,21 +3174,21 @@ function handleOpenCodeTurnEvent(input) {
3218
3174
  case "session.reasoning.started":
3219
3175
  return true;
3220
3176
  case "session.text.delta":
3221
- appendDelta(events, context, data, "text");
3177
+ appendDelta(context, data, "text");
3222
3178
  return true;
3223
3179
  case "session.reasoning.delta":
3224
- appendDelta(events, context, data, "reasoning");
3180
+ appendDelta(context, data, "reasoning");
3225
3181
  return true;
3226
3182
  case "session.text.ended":
3227
- endStream(events, context, data, "text");
3183
+ endStream(context, data, "text");
3228
3184
  return true;
3229
3185
  case "session.reasoning.ended":
3230
- endStream(events, context, data, "reasoning");
3186
+ endStream(context, data, "reasoning");
3231
3187
  return true;
3232
3188
  case "session.renamed": {
3233
3189
  const title = text3(data, "title")?.trim() ?? "";
3234
3190
  if (title.length > 0 && !isOpenCodeDefaultTitle(title)) {
3235
- emitEvent(events, context, "thread.metadata.updated", { name: title });
3191
+ emitEvent(context, "thread.metadata.updated", { name: title });
3236
3192
  }
3237
3193
  return true;
3238
3194
  }
@@ -3242,13 +3198,12 @@ function handleOpenCodeTurnEvent(input) {
3242
3198
  }
3243
3199
 
3244
3200
  // src/sessionLifecycle.ts
3245
- function emitUnexpectedExit(events, context, cause) {
3201
+ function emitUnexpectedExit(context, cause) {
3246
3202
  if (context.stopped) return;
3247
3203
  context.stopped = true;
3248
- const { message, failureCategory, turnId } = finishOpenCodeTurnOnExit(events, context, cause);
3249
- markSubagentsUnknown(events, context);
3204
+ const { message, failureCategory, turnId } = finishOpenCodeTurnOnExit(context, cause);
3205
+ markSubagentsUnknown(context);
3250
3206
  emitEvent(
3251
- events,
3252
3207
  context,
3253
3208
  "session.exited",
3254
3209
  { reason: message, recoverable: false, exitKind: "error" },
@@ -3272,7 +3227,7 @@ async function interruptForStop(context) {
3272
3227
  }
3273
3228
  }
3274
3229
  function createOpenCodeSessionLifecycle(input) {
3275
- const { events, context, log, options } = input;
3230
+ const { context, log, options } = input;
3276
3231
  const pending = /* @__PURE__ */ new Set();
3277
3232
  const stopStarted = Promise.withResolvers();
3278
3233
  let stopping = false;
@@ -3304,7 +3259,7 @@ function createOpenCodeSessionLifecycle(input) {
3304
3259
  log.warn("OpenCode session tail handling timed out; closing the event boundary.");
3305
3260
  for (const registered of pending) {
3306
3261
  if (registered.event.sessionId === context.sessionId && registered.turnId !== void 0 && registered.turnId === context.session.activeTurnId) {
3307
- finishOpenCodeTurnEvent(events, context, registered.event);
3262
+ finishOpenCodeTurnEvent(context, registered.event);
3308
3263
  }
3309
3264
  }
3310
3265
  }
@@ -3317,9 +3272,9 @@ function createOpenCodeSessionLifecycle(input) {
3317
3272
  if (sealed) return;
3318
3273
  publishing = true;
3319
3274
  if (cause !== void 0 && !stopping) {
3320
- emitUnexpectedExit(events, context, cause);
3275
+ emitUnexpectedExit(context, cause);
3321
3276
  } else {
3322
- finishOpenCodeTurn(events, context, {
3277
+ finishOpenCodeTurn(context, {
3323
3278
  state: "interrupted",
3324
3279
  reason: "Interrupted by user.",
3325
3280
  sessionEnds: true
@@ -3329,8 +3284,8 @@ function createOpenCodeSessionLifecycle(input) {
3329
3284
  status: "stopped",
3330
3285
  updatedAt: nowIso()
3331
3286
  };
3332
- markSubagentsUnknown(events, context);
3333
- emitEvent(events, context, "session.exited", {
3287
+ markSubagentsUnknown(context);
3288
+ emitEvent(context, "session.exited", {
3334
3289
  reason: message,
3335
3290
  recoverable: false,
3336
3291
  exitKind: "graceful"
@@ -3440,7 +3395,7 @@ async function applyOpenCodeTurnSelection(input) {
3440
3395
  }
3441
3396
 
3442
3397
  // src/sessionEvents.ts
3443
- async function handleOtherSessionEvent(events, context, event, discoveredChild) {
3398
+ async function handleOtherSessionEvent(context, event, discoveredChild) {
3444
3399
  const sessionId = event.sessionId;
3445
3400
  if (sessionId === void 0) return;
3446
3401
  noteChildSequence(context, event);
@@ -3452,11 +3407,11 @@ async function handleOtherSessionEvent(events, context, event, discoveredChild)
3452
3407
  return;
3453
3408
  }
3454
3409
  if (event.type.startsWith("session.execution.")) {
3455
- endSubagentFromExecution(events, context, sessionId, event);
3410
+ endSubagentFromExecution(context, sessionId, event);
3456
3411
  return;
3457
3412
  }
3458
3413
  if (event.type === "permission.asked" || event.type === "permission.replied") {
3459
- await handleOpenCodeToolEvent({ events, context, event });
3414
+ await handleOpenCodeToolEvent({ context, event });
3460
3415
  return;
3461
3416
  }
3462
3417
  if (event.type === "session.step.started") {
@@ -3492,22 +3447,20 @@ var abortableDelay = (ms, signal) => new Promise((resolve2) => {
3492
3447
  }
3493
3448
  signal.addEventListener("abort", done, { once: true });
3494
3449
  });
3495
- async function recoverAfterReconnect(events, context, log) {
3496
- markSubagentsUnknown(events, context);
3450
+ async function recoverAfterReconnect(context, log) {
3451
+ markSubagentsUnknown(context);
3497
3452
  const ours = (sessionId) => typeof sessionId === "string" && (sessionId === context.sessionId || context.childSessionIds.has(sessionId));
3498
3453
  try {
3499
3454
  for (const request of await context.api.pendingPermissions()) {
3500
3455
  const sessionId = request["sessionID"];
3501
3456
  if (!ours(sessionId)) continue;
3502
3457
  await handleOpenCodeToolEvent({
3503
- events,
3504
3458
  context,
3505
3459
  event: { type: "permission.asked", sessionId, data: request }
3506
3460
  });
3507
3461
  }
3508
3462
  for (const form of await context.api.pendingForms()) {
3509
3463
  handleOpenCodeFormEvent({
3510
- events,
3511
3464
  context,
3512
3465
  event: { type: "form.created", sessionId: void 0, data: { form } }
3513
3466
  });
@@ -3519,7 +3472,6 @@ async function recoverAfterReconnect(events, context, log) {
3519
3472
  const outcome = current.settledOutcome;
3520
3473
  if (outcome === void 0) return;
3521
3474
  handleOpenCodeTurnEvent({
3522
- events,
3523
3475
  context,
3524
3476
  event: {
3525
3477
  type: outcome === "succeeded" ? "session.execution.succeeded" : outcome === "interrupted" ? "session.execution.interrupted" : "session.execution.failed",
@@ -3537,7 +3489,7 @@ async function recoverAfterReconnect(events, context, log) {
3537
3489
  }
3538
3490
  }
3539
3491
  function startEventPump(input) {
3540
- const { events, context, log } = input;
3492
+ const { context, log } = input;
3541
3493
  const lifecycle = createOpenCodeSessionLifecycle(input);
3542
3494
  context.lifecycle = lifecycle;
3543
3495
  const onSkipped = (reason) => {
@@ -3589,24 +3541,24 @@ function startEventPump(input) {
3589
3541
  const recover = reconnecting;
3590
3542
  reconnecting = false;
3591
3543
  await lifecycle.consume(event, async () => {
3592
- if (recover) await recoverAfterReconnect(events, context, log);
3544
+ if (recover) await recoverAfterReconnect(context, log);
3593
3545
  if (lifecycle.sealed) return;
3594
3546
  if (event.sessionId !== void 0 && event.sessionId !== context.sessionId) {
3595
- await handleOtherSessionEvent(events, context, event, discoveredChild);
3547
+ await handleOtherSessionEvent(context, event, discoveredChild);
3596
3548
  return;
3597
3549
  }
3598
3550
  if (event.sessionId === context.sessionId) noteParentSequence(context, event);
3599
- if (handleOpenCodeTurnEvent({ events, context, event })) return;
3551
+ if (handleOpenCodeTurnEvent({ context, event })) return;
3600
3552
  if (noteOpenCodeSelectionEvent(context, event)) {
3601
3553
  if (event.type === "session.model.selected" && context.selectedModel !== void 0) {
3602
- reportOpenCodeModel(events, context, context.selectedModel);
3554
+ reportOpenCodeModel(context, context.selectedModel);
3603
3555
  }
3604
3556
  return;
3605
3557
  }
3606
- if (handleOpenCodeCompactionEvent({ events, context, event })) return;
3607
- if (handleOpenCodeFormEvent({ events, context, event })) return;
3608
- if (reportSubagentInbox(events, context, event)) return;
3609
- await handleOpenCodeToolEvent({ events, context, event });
3558
+ if (handleOpenCodeCompactionEvent({ context, event })) return;
3559
+ if (handleOpenCodeFormEvent({ context, event })) return;
3560
+ if (reportSubagentInbox(context, event)) return;
3561
+ await handleOpenCodeToolEvent({ context, event });
3610
3562
  });
3611
3563
  }
3612
3564
  return new Error("OpenCode event stream ended.");
@@ -4431,7 +4383,6 @@ function requestedModelOf(modelSelection) {
4431
4383
  }
4432
4384
  function createOpenCodeInstance(config, host, attachments, lifecycleOptions) {
4433
4385
  const recipe = parseOpenCodeInstanceConfig(config);
4434
- const events = new EventBus();
4435
4386
  const sessions = /* @__PURE__ */ new Map();
4436
4387
  const pendingServers = /* @__PURE__ */ new Map();
4437
4388
  const rememberPendingServer = (threadId, server) => {
@@ -4607,6 +4558,7 @@ function createOpenCodeInstance(config, host, attachments, lifecycleOptions) {
4607
4558
  } : {}
4608
4559
  };
4609
4560
  const context = {
4561
+ events: input.events,
4610
4562
  threadId: input.threadId,
4611
4563
  session,
4612
4564
  sessionId,
@@ -4638,7 +4590,6 @@ function createOpenCodeInstance(config, host, attachments, lifecycleOptions) {
4638
4590
  ...selection
4639
4591
  };
4640
4592
  await startEventPump({
4641
- events,
4642
4593
  context,
4643
4594
  log: host.log,
4644
4595
  ...lifecycleOptions ? { options: lifecycleOptions } : {}
@@ -4652,13 +4603,12 @@ function createOpenCodeInstance(config, host, attachments, lifecycleOptions) {
4652
4603
  }
4653
4604
  sessions.set(input.threadId, context);
4654
4605
  emitEvent(
4655
- events,
4656
4606
  context,
4657
4607
  "session.started",
4658
4608
  input.resumeCursor !== void 0 ? { resume: input.resumeCursor } : {}
4659
4609
  );
4660
- emitEvent(events, context, "thread.started", { providerThreadId: sessionId });
4661
- emitEvent(events, context, "session.state.changed", { state: "ready" });
4610
+ emitEvent(context, "thread.started", { providerThreadId: sessionId });
4611
+ emitEvent(context, "session.state.changed", { state: "ready" });
4662
4612
  if (resumedInPlace) await registerChildSessions(context, host.log);
4663
4613
  return sessionFromContext(context);
4664
4614
  } catch (cause) {
@@ -4707,7 +4657,6 @@ function createOpenCodeInstance(config, host, attachments, lifecycleOptions) {
4707
4657
  updatedAt: nowIso()
4708
4658
  };
4709
4659
  emitEvent(
4710
- events,
4711
4660
  context,
4712
4661
  "turn.started",
4713
4662
  requestedModel ? {
@@ -4717,7 +4666,7 @@ function createOpenCodeInstance(config, host, attachments, lifecycleOptions) {
4717
4666
  } : {},
4718
4667
  { turnId }
4719
4668
  );
4720
- emitEvent(events, context, "session.state.changed", { state: "running" });
4669
+ emitEvent(context, "session.state.changed", { state: "running" });
4721
4670
  }
4722
4671
  try {
4723
4672
  if (!steering) {
@@ -4742,7 +4691,6 @@ function createOpenCodeInstance(config, host, attachments, lifecycleOptions) {
4742
4691
  updatedAt: nowIso()
4743
4692
  };
4744
4693
  emitEvent(
4745
- events,
4746
4694
  context,
4747
4695
  "turn.aborted",
4748
4696
  { reason: openCodeRuntimeErrorDetail(cause) },
@@ -4779,13 +4727,12 @@ function createOpenCodeInstance(config, host, attachments, lifecycleOptions) {
4779
4727
  )
4780
4728
  );
4781
4729
  stopSubagents(
4782
- events,
4783
4730
  context,
4784
4731
  interrupted.filter((child) => child !== void 0)
4785
4732
  );
4786
4733
  const active = context.session.activeTurnId;
4787
4734
  if (active && (turnId === void 0 || turnId === active)) {
4788
- finishOpenCodeTurn(events, context, {
4735
+ finishOpenCodeTurn(context, {
4789
4736
  state: "interrupted",
4790
4737
  reason: "Interrupted by user."
4791
4738
  });
@@ -4842,7 +4789,6 @@ function createOpenCodeInstance(config, host, attachments, lifecycleOptions) {
4842
4789
  }));
4843
4790
  return { threadId, turns };
4844
4791
  },
4845
- events,
4846
4792
  // 额度:OpenCode Go 套餐,读这个实例自己的 key(连外部服务器的实例不读本机);token 仍走编排账本。
4847
4793
  usage: createOpenCodeUsage({
4848
4794
  homePath: recipe.homePath,
@@ -4868,7 +4814,6 @@ function createOpenCodeInstance(config, host, attachments, lifecycleOptions) {
4868
4814
  throw new AggregateError(failures, "OpenCode instance disposal failed.", {
4869
4815
  cause: failures[0]
4870
4816
  });
4871
- events.close();
4872
4817
  })();
4873
4818
  disposal = work;
4874
4819
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ycodium-ai/agent-opencode",
3
- "version": "0.2.3976",
3
+ "version": "0.2.3990",
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.3976",
24
+ "@ycodium-ai/plugin-api": "0.2.3990",
25
+ "ycodium-sse-stream": "0.0.0",
25
26
  "ycodium-fetch-ports": "0.0.0",
26
- "ycodium-executor-testing": "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",