opencode-completion-gate 1.3.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/plugin.js CHANGED
@@ -1,3 +1,6 @@
1
+ // src/gate.ts
2
+ import { Plugin } from "@opencode/plugin";
3
+
1
4
  // src/process.ts
2
5
  import { appendFileSync } from "fs";
3
6
  import { join } from "path";
@@ -605,47 +608,33 @@ function parseVerdict(output) {
605
608
  const last = matches[matches.length - 1];
606
609
  return last ? last[1].toUpperCase() : null;
607
610
  }
608
- function unwrapSdk(res) {
609
- if (res && typeof res === "object" && ("data" in res || "error" in res)) {
610
- const r = res;
611
- if (r.error != null)
612
- throw new Error(
613
- typeof r.error === "string" ? r.error : r.error && typeof r.error === "object" && "message" in r.error ? String(r.error.message) : JSON.stringify(r.error)
614
- );
615
- return r.data;
616
- }
617
- return res;
618
- }
619
- function reviewerText(res) {
620
- const parts = res?.parts;
621
- if (!Array.isArray(parts)) return "";
622
- return parts.filter(
623
- (p) => !!p && typeof p === "object" && p.type === "text"
624
- ).map((p) => String(p.text ?? "")).join("\n");
625
- }
626
611
  async function runReviewAssertion(a, cwd, client, isAborted) {
627
612
  if (isAborted?.()) throw new GateAborted();
628
613
  if (!client?.session)
629
- return fail(a.name, "no opencode SDK client available to run the reviewer session");
614
+ return fail(a.name, "no opencode plugin context available to run the reviewer session");
630
615
  const prompt = [
631
616
  a.prompt ?? "Review the changes on this branch against the task requirements.",
632
617
  'Finish your reply with a final line containing exactly "VERDICT: PASS" or "VERDICT: FAIL" followed by a one-line justification.'
633
618
  ].join("\n");
619
+ let sessionId;
634
620
  try {
635
- const created = unwrapSdk(
636
- await client.session.create({ query: { directory: cwd } })
637
- );
638
- const sessionId = created?.id;
621
+ const created = await client.session.create({ directory: cwd });
622
+ sessionId = created?.id;
639
623
  if (!sessionId)
640
624
  return fail(a.name, "could not create reviewer session (no session id in response)");
641
625
  let timer;
642
626
  try {
643
627
  const raced = await Promise.race([
644
- client.session.prompt({
645
- path: { id: sessionId },
646
- body: { agent: a.agent, parts: [{ type: "text", text: prompt }] }
647
- }).then(
648
- (r) => ({ ok: true, r }),
628
+ (async () => {
629
+ await client.session.prompt({
630
+ sessionID: sessionId,
631
+ text: prompt,
632
+ agent: a.agent
633
+ });
634
+ const text2 = await client.session.context({ sessionID: sessionId });
635
+ return { ok: true, text: text2 };
636
+ })().then(
637
+ (r) => r,
649
638
  (err) => ({ ok: false, err })
650
639
  ),
651
640
  new Promise((resolve) => {
@@ -654,7 +643,7 @@ async function runReviewAssertion(a, cwd, client, isAborted) {
654
643
  ]);
655
644
  if ("timedOut" in raced) {
656
645
  try {
657
- await Promise.resolve(client.session.abort?.({ path: { id: sessionId } }));
646
+ await Promise.resolve(client.session.abort?.({ sessionID: sessionId }));
658
647
  } catch {
659
648
  }
660
649
  return fail(
@@ -663,7 +652,7 @@ async function runReviewAssertion(a, cwd, client, isAborted) {
663
652
  );
664
653
  }
665
654
  if (!raced.ok) return fail(a.name, `reviewer session failed: ${describeSdkError(raced.err)}`);
666
- const text = reviewerText(unwrapSdk(raced.r));
655
+ const text = raced.text;
667
656
  const verdict = parseVerdict(text);
668
657
  logDiag(`review "${a.name}": verdict=${verdict ?? "none"}`);
669
658
  const evidence = truncateTail(text);
@@ -686,14 +675,30 @@ var INTERNAL_MARKER = "[completion-gate-internal]";
686
675
  var TOGGLE_RE = /^\[completion-gate\](?:\s+(.*?))?\s*$/i;
687
676
  var INJECTED_FAILURE_RE = /^✖ Completion gate failed — "[^"]+"\. Fix these issues, then finish again\.\n\n```[\s\S]*\n```\n\n\(RETRY \d+\/\d+\)$/;
688
677
  var INJECTED_SUCCESS_RE = /^✅ Completion gate passed \([^\n]*\)\. You may report done\.$/;
689
- var sessions = /* @__PURE__ */ new Map();
690
- var deletedSessionIDs = /* @__PURE__ */ new Set();
691
- var sessionGenerations = /* @__PURE__ */ new Map();
678
+ var RUNTIME_KEY = /* @__PURE__ */ Symbol.for("opencode.completion-gate.runtime.v2");
679
+ function runtime() {
680
+ const store = globalThis;
681
+ let rt = store[RUNTIME_KEY];
682
+ if (!rt) {
683
+ rt = {
684
+ sessions: /* @__PURE__ */ new Map(),
685
+ deleted: /* @__PURE__ */ new Set(),
686
+ generations: /* @__PURE__ */ new Map(),
687
+ bootstrapPending: null,
688
+ bootstrapCaptured: false,
689
+ seen: /* @__PURE__ */ new Set(),
690
+ seenPrompts: /* @__PURE__ */ new Set()
691
+ };
692
+ store[RUNTIME_KEY] = rt;
693
+ }
694
+ return rt;
695
+ }
692
696
  function getSessionGeneration(sessionID) {
693
- return sessionGenerations.get(sessionID) ?? 0;
697
+ return runtime().generations.get(sessionID) ?? 0;
694
698
  }
695
699
  function advanceSessionGeneration(sessionID) {
696
- sessionGenerations.set(sessionID, getSessionGeneration(sessionID) + 1);
700
+ const rt = runtime();
701
+ rt.generations.set(sessionID, (rt.generations.get(sessionID) ?? 0) + 1);
697
702
  }
698
703
  function createGateSessionState(sessionID, directory) {
699
704
  return {
@@ -709,30 +714,36 @@ function createGateSessionState(sessionID, directory) {
709
714
  deleted: false
710
715
  };
711
716
  }
712
- async function getOrRegisterSession(client, sessionID) {
713
- const existing = sessions.get(sessionID);
717
+ function asString(value) {
718
+ return typeof value === "string" && value.trim() !== "" ? value : void 0;
719
+ }
720
+ async function getOrRegisterSession(ctx, sessionID) {
721
+ const rt = runtime();
722
+ const existing = rt.sessions.get(sessionID);
714
723
  if (existing) return existing.deleted ? null : existing;
715
724
  const lookupSessionID = sessionID;
716
725
  const lookupGeneration = getSessionGeneration(lookupSessionID);
717
726
  try {
718
- const info = unwrapSdk2(
719
- await client.session.get({ path: { id: lookupSessionID } })
720
- );
721
- const validated = validateTopLevelSessionMetadata(info, lookupSessionID);
727
+ const info = await ctx.session.get({ sessionID: lookupSessionID });
728
+ const validated = validateTopLevelSessionMetadata({
729
+ id: info?.id,
730
+ directory: info?.location?.directory,
731
+ parentID: info?.parentID
732
+ });
722
733
  if (!validated) {
723
734
  logDiag(
724
735
  `lazy registration rejected session ${lookupSessionID}: invalid top-level session metadata`
725
736
  );
726
737
  return null;
727
738
  }
728
- if (deletedSessionIDs.has(lookupSessionID) || getSessionGeneration(lookupSessionID) !== lookupGeneration) {
739
+ if (rt.deleted.has(lookupSessionID) || getSessionGeneration(lookupSessionID) !== lookupGeneration) {
729
740
  logDiag(
730
741
  `lazy registration ignored session ${lookupSessionID}: session was deleted or superseded while lookup was pending`
731
742
  );
732
743
  return null;
733
744
  }
734
745
  const state = createGateSessionState(validated.sessionID, validated.directory);
735
- sessions.set(state.sessionID, state);
746
+ rt.sessions.set(state.sessionID, state);
736
747
  logDiag(`lazily registered session ${state.sessionID} (${state.directory})`);
737
748
  return state;
738
749
  } catch (err) {
@@ -740,24 +751,29 @@ async function getOrRegisterSession(client, sessionID) {
740
751
  return null;
741
752
  }
742
753
  }
743
- async function safeToast(client, message, variant = "info") {
754
+ async function notify(ctx, state, message) {
755
+ logDiag(`notify ${state.sessionID}: ${message}`);
744
756
  try {
745
- await client.tui.showToast({ body: { variant, message } });
746
- } catch {
757
+ await ctx.session.synthetic({ sessionID: state.sessionID, text: message });
758
+ } catch (err) {
759
+ logDiag(`notify failed: ${describeSdkError(err)}`);
747
760
  }
748
761
  }
749
- function clearParts(output) {
750
- if (Array.isArray(output?.parts)) output.parts.length = 0;
762
+ async function injectPrompt(ctx, sessionID, text) {
763
+ try {
764
+ await ctx.session.prompt({ sessionID, text });
765
+ } catch (err) {
766
+ logDiag(`prompt injection error: ${describeSdkError(err)}`);
767
+ }
751
768
  }
752
- var ABORT_COMMAND_TURN = true;
753
- async function applyToggle(client, state, rawArgument) {
769
+ async function applyToggle(ctx, state, rawArgument) {
754
770
  const normalized = rawArgument.trim().toLowerCase();
755
771
  const arg = normalized || "on";
756
772
  if (arg === "status") {
757
773
  const loaded = loadGateConfig(state.directory);
758
774
  const cap = state.gateMode === "command-only" && state.sessionMaxRetries !== null ? { value: state.sessionMaxRetries, source: "session" } : { value: loaded?.config.maxRetries ?? 3, source: "config" };
759
775
  const notice2 = `Completion gate: ${state.gateEnabled ? "ENABLED" : "disabled"} \xB7 retries=${state.retries} \xB7 lastOutcome=${state.lastOutcome ?? "n/a"} \xB7 extraCommand=${state.extraCommand ? "configured" : "none"} \xB7 mode=${state.gateMode} \xB7 maxRetries=${cap.value} (${cap.source})`;
760
- await safeToast(client, notice2);
776
+ await notify(ctx, state, notice2);
761
777
  return { notice: notice2, kind: "status" };
762
778
  }
763
779
  if (/^--only/i.test(rawArgument.trim())) {
@@ -766,7 +782,7 @@ async function applyToggle(client, state, rawArgument) {
766
782
  const parsed = parseOnlyCommand(remainder);
767
783
  if (!parsed.command || parsed.invalidRetry) {
768
784
  const notice3 = 'Usage: /gate --only "command" [--retries N]';
769
- await safeToast(client, notice3, "error");
785
+ await notify(ctx, state, notice3);
770
786
  return { notice: notice3, kind: "usage" };
771
787
  }
772
788
  state.extraCommand = parsed.command;
@@ -777,7 +793,7 @@ async function applyToggle(client, state, rawArgument) {
777
793
  state.escalated = false;
778
794
  state.lastOutcome = null;
779
795
  const notice2 = parsed.maxRetries !== void 0 ? `Completion gate armed (command-only): ${parsed.command} \xB7 maxRetries=${parsed.maxRetries}` : `Completion gate armed (command-only): ${parsed.command}`;
780
- await safeToast(client, notice2);
796
+ await notify(ctx, state, notice2);
781
797
  logDiag(
782
798
  `gate command-only custom command registered on ${state.sessionID}` + (parsed.maxRetries !== void 0 ? ` (session maxRetries=${parsed.maxRetries})` : "")
783
799
  );
@@ -791,7 +807,7 @@ async function applyToggle(client, state, rawArgument) {
791
807
  state.escalated = false;
792
808
  state.lastOutcome = null;
793
809
  const notice2 = `Completion gate armed (combined): ${state.extraCommand}`;
794
- await safeToast(client, notice2);
810
+ await notify(ctx, state, notice2);
795
811
  logDiag(`gate custom command registered on ${state.sessionID}`);
796
812
  return { notice: notice2, kind: "enabled" };
797
813
  }
@@ -802,23 +818,23 @@ async function applyToggle(client, state, rawArgument) {
802
818
  state.lastOutcome = null;
803
819
  }
804
820
  const notice = `Completion gate ${state.gateEnabled ? "enabled" : "disabled"} for this session.`;
805
- await safeToast(client, notice);
821
+ await notify(ctx, state, notice);
806
822
  logDiag(`gate ${arg} on ${state.sessionID}`);
807
823
  return { notice, kind: state.gateEnabled ? "enabled" : "disabled" };
808
824
  }
809
- async function warnIfNothingToRun(client, state) {
825
+ async function warnIfNothingToRun(ctx, state) {
810
826
  if (state.extraCommand) return;
811
827
  if (loadGateConfig(state.directory)) return;
812
828
  const msg = `Completion gate enabled but nothing to run: no .opencode/completion-gate.json found from ${state.directory}.`;
813
829
  logDiag(`gate on ${state.sessionID}: ${msg}`);
814
- await safeToast(client, msg, "error");
830
+ await notify(ctx, state, msg);
815
831
  }
816
- function kickGateTurnEnd(client, state, reason) {
832
+ function kickGateTurnEnd(ctx, state, reason) {
817
833
  if (state.deleted || !state.gateEnabled || state.busy) return;
818
834
  if (process.env.OPENCODE_GATE_DISABLED === "1") return;
819
835
  state.busy = true;
820
836
  logDiag(`gate kick on ${state.sessionID} (${reason}) \u2014 evaluation starting`);
821
- runGateTurnEnd(client, state).catch((err) => logDiag(`gate flow error: ${describeSdkError(err)}`)).finally(() => {
837
+ runGateTurnEnd(ctx, state).catch((err) => logDiag(`gate flow error: ${describeSdkError(err)}`)).finally(() => {
822
838
  state.busy = false;
823
839
  });
824
840
  }
@@ -839,19 +855,6 @@ async function runCommandAssertion(a, cwd, isAborted) {
839
855
  ${truncateTail([r.stderr, r.stdout].filter((s) => s.trim()).join("\n---\n"))}`
840
856
  );
841
857
  }
842
- function unwrapSdk2(res) {
843
- if (res && typeof res === "object" && ("data" in res || "error" in res)) {
844
- const r = res;
845
- if (r.error != null) {
846
- const e = r.error;
847
- throw new Error(
848
- typeof e === "string" ? e : e && typeof e === "object" && "message" in e ? String(e.message) : JSON.stringify(e)
849
- );
850
- }
851
- return r.data;
852
- }
853
- return res;
854
- }
855
858
  async function evaluateAssertions(assertions, projectRoot, client, isAborted, adoOpts) {
856
859
  const results = [];
857
860
  for (const a of assertions) {
@@ -884,6 +887,44 @@ async function evaluateAssertions(assertions, projectRoot, client, isAborted, ad
884
887
  }
885
888
  return results;
886
889
  }
890
+ function buildReviewClient(ctx) {
891
+ const assistantText = (messages) => {
892
+ const out = [];
893
+ for (const message of messages ?? []) {
894
+ if (!message || message.type !== "assistant") continue;
895
+ for (const content of message.content ?? []) {
896
+ if (content && content.type === "text" && typeof content.text === "string")
897
+ out.push(content.text);
898
+ }
899
+ }
900
+ return out.join("\n");
901
+ };
902
+ return {
903
+ session: {
904
+ create: async (input) => {
905
+ const created = await ctx.session.create(
906
+ input?.directory ? { title: "completion-gate self-review", location: { directory: input.directory } } : { title: "completion-gate self-review" }
907
+ );
908
+ return { id: created?.id };
909
+ },
910
+ prompt: async ({ sessionID, text, agent }) => {
911
+ if (agent) await ctx.session.switchAgent({ sessionID, agent });
912
+ await ctx.session.prompt({ sessionID, text });
913
+ await ctx.session.wait({ sessionID });
914
+ },
915
+ context: async ({ sessionID }) => {
916
+ const messages = await ctx.session.context({ sessionID });
917
+ return assistantText(messages);
918
+ },
919
+ abort: async ({ sessionID }) => {
920
+ try {
921
+ await ctx.session.interrupt({ sessionID });
922
+ } catch {
923
+ }
924
+ }
925
+ }
926
+ };
927
+ }
887
928
  function injectFailureText(state, outcome, maxRetries) {
888
929
  return [
889
930
  `${MARKER} \u2716 Completion gate failed \u2014 "${outcome.name}". Fix these issues, then finish again.`,
@@ -895,7 +936,7 @@ function injectFailureText(state, outcome, maxRetries) {
895
936
  `(RETRY ${state.retries}/${maxRetries})`
896
937
  ].join("\n");
897
938
  }
898
- async function runGateTurnEnd(client, state) {
939
+ async function runGateTurnEnd(ctx, state) {
899
940
  const isAborted = () => state.deleted || !state.gateEnabled || process.env.OPENCODE_GATE_DISABLED === "1";
900
941
  if (state.lastOutcome === "pass") {
901
942
  logDiag(`gate turn-end skipped on ${state.sessionID} \u2014 already green this streak`);
@@ -921,7 +962,12 @@ async function runGateTurnEnd(client, state) {
921
962
  logDiag(
922
963
  `gate turn-end on ${state.sessionID}: ${loaded ? `config ${loaded.path}` : "command-only without project config"} (${assertions.length} assertion(s), maxRetries=${cap.value} (${cap.source}), retries so far=${state.retries})`
923
964
  );
924
- const results = await evaluateAssertions(assertions, projectRoot, client, isAborted);
965
+ const results = await evaluateAssertions(
966
+ assertions,
967
+ projectRoot,
968
+ buildReviewClient(ctx),
969
+ isAborted
970
+ );
925
971
  if (results === null) {
926
972
  logDiag(
927
973
  `gate turn-end ABORTED on ${state.sessionID} \u2014 gate was disabled mid-run, staying silent`
@@ -937,18 +983,11 @@ async function runGateTurnEnd(client, state) {
937
983
  return;
938
984
  }
939
985
  state.lastOutcome = "pass";
940
- await client.session.promptAsync({
941
- path: { id: state.sessionID },
942
- body: {
943
- ...state.currentAgent ? { agent: state.currentAgent } : {},
944
- parts: [
945
- {
946
- type: "text",
947
- text: `${MARKER} \u2705 Completion gate passed (${results.map((r) => r.name).join(", ")}). You may report done.`
948
- }
949
- ]
950
- }
951
- }).catch((err) => logDiag(`success prompt error: ${describeSdkError(err)}`));
986
+ await injectPrompt(
987
+ ctx,
988
+ state.sessionID,
989
+ `${MARKER} \u2705 Completion gate passed (${results.map((r) => r.name).join(", ")}). You may report done.`
990
+ );
952
991
  return;
953
992
  }
954
993
  if (isAborted()) {
@@ -959,14 +998,11 @@ async function runGateTurnEnd(client, state) {
959
998
  if (state.retries >= cap.value) {
960
999
  if (!state.escalated) {
961
1000
  state.escalated = true;
962
- await client.tui.showToast({
963
- body: {
964
- variant: "error",
965
- message: `\u2192 Completion gate "${last.name}" still failing after ${cap.value} retries \u2014 manual attention needed`,
966
- duration: 15e3
967
- }
968
- }).catch(() => {
969
- });
1001
+ await notify(
1002
+ ctx,
1003
+ state,
1004
+ `\u2192 Completion gate "${last.name}" still failing after ${cap.value} retries \u2014 manual attention needed`
1005
+ );
970
1006
  logDiag(
971
1007
  `gate ESCALATED on ${state.sessionID}: "${last.name}" still failing after ${cap.value} retries \u2014 manual attention needed`
972
1008
  );
@@ -977,146 +1013,191 @@ async function runGateTurnEnd(client, state) {
977
1013
  logDiag(
978
1014
  `gate FAILED on ${state.sessionID}: "${last.name}" \u2014 retry ${state.retries}/${cap.value}, injecting fix request`
979
1015
  );
980
- await client.session.promptAsync({
981
- path: { id: state.sessionID },
982
- body: {
983
- ...state.currentAgent ? { agent: state.currentAgent } : {},
984
- parts: [{ type: "text", text: injectFailureText(state, last, cap.value) }]
1016
+ await injectPrompt(ctx, state.sessionID, injectFailureText(state, last, cap.value));
1017
+ }
1018
+ async function handlePrompt(ctx, event) {
1019
+ const sessionID = asString(event?.sessionID);
1020
+ if (!sessionID) return;
1021
+ const messageID = asString(event?.messageID);
1022
+ if (messageID) {
1023
+ const rt = runtime();
1024
+ if (rt.seenPrompts.has(messageID)) return;
1025
+ rt.seenPrompts.add(messageID);
1026
+ if (rt.seenPrompts.size > 5e3) rt.seenPrompts.clear();
1027
+ }
1028
+ const state = runtime().sessions.get(sessionID);
1029
+ if (!state || state.deleted) return;
1030
+ const text = event?.prompt?.text ?? "";
1031
+ if (text.trimStart().startsWith(INTERNAL_MARKER)) {
1032
+ const lines = text.split(/\r?\n/);
1033
+ const directive = lines.shift()?.trim() ?? "";
1034
+ const argument2 = directive.slice(INTERNAL_MARKER.length).trim();
1035
+ if (/^--only\s+/i.test(argument2)) {
1036
+ await applyToggle(ctx, state, argument2);
1037
+ const remainder = lines.join("\n").replace(/^\n+/, "");
1038
+ if (event.prompt) event.prompt.text = remainder;
985
1039
  }
986
- }).catch((err) => logDiag(`retry prompt error: ${describeSdkError(err)}`));
1040
+ return;
1041
+ }
1042
+ if (!text.trimStart().startsWith(MARKER)) {
1043
+ state.retries = 0;
1044
+ state.escalated = false;
1045
+ state.lastOutcome = null;
1046
+ return;
1047
+ }
1048
+ const t = TOGGLE_RE.exec(text.trim());
1049
+ const argument = (t?.[1] ?? "").trim();
1050
+ if (!t || INJECTED_FAILURE_RE.test(argument) || INJECTED_SUCCESS_RE.test(argument)) return;
1051
+ const applied = await applyToggle(ctx, state, argument);
1052
+ if (applied.kind === "enabled") await warnIfNothingToRun(ctx, state);
1053
+ if (event.prompt)
1054
+ event.prompt.text = `${applied.notice} (Plugin-handled; acknowledge briefly, take no other action, call no tools.)`;
987
1055
  }
988
- var plugin = async ({ client }) => {
989
- let pendingBootstrap = readBootstrapGateCommand();
990
- if (pendingBootstrap) consumeBootstrapGateCommand();
991
- return {
992
- event: async ({ event }) => {
993
- try {
994
- if (event.type === "session.deleted") {
995
- const info = event.properties?.info;
996
- const deletedInfo = info && typeof info === "object" ? info : void 0;
997
- if (typeof deletedInfo?.id === "string" && deletedInfo.id.trim() !== "") {
998
- const sessionID = deletedInfo.id;
999
- deletedSessionIDs.add(sessionID);
1000
- advanceSessionGeneration(sessionID);
1001
- const state = sessions.get(sessionID);
1002
- if (state) {
1003
- state.deleted = true;
1004
- state.gateEnabled = false;
1056
+ async function armBootstrapIfPending(ctx, state) {
1057
+ const rt = runtime();
1058
+ const bootstrap = rt.bootstrapPending ?? readBootstrapGateCommand();
1059
+ rt.bootstrapPending = null;
1060
+ if (!bootstrap) return;
1061
+ consumeBootstrapGateCommand();
1062
+ state.extraCommand = bootstrap.command;
1063
+ state.gateMode = bootstrap.mode;
1064
+ state.sessionMaxRetries = bootstrap.mode === "command-only" && bootstrap.maxRetries !== void 0 ? bootstrap.maxRetries : null;
1065
+ state.gateEnabled = true;
1066
+ state.retries = 0;
1067
+ state.escalated = false;
1068
+ state.lastOutcome = null;
1069
+ logDiag(
1070
+ `gate bootstrap ${bootstrap.mode} custom command registered on ${state.sessionID}` + (state.sessionMaxRetries !== null ? ` (session maxRetries=${state.sessionMaxRetries})` : "")
1071
+ );
1072
+ await notify(
1073
+ ctx,
1074
+ state,
1075
+ state.sessionMaxRetries !== null ? `Completion gate armed (${bootstrap.mode}): ${bootstrap.command} \xB7 maxRetries=${state.sessionMaxRetries}` : `Completion gate armed (${bootstrap.mode}): ${bootstrap.command}`
1076
+ );
1077
+ }
1078
+ async function handleEvent(ctx, event) {
1079
+ const type = typeof event.type === "string" ? event.type : "";
1080
+ const rt = runtime();
1081
+ if (type === "session.deleted") {
1082
+ const sessionID = asString(event.data?.sessionID);
1083
+ if (!sessionID) return;
1084
+ rt.deleted.add(sessionID);
1085
+ advanceSessionGeneration(sessionID);
1086
+ const state = rt.sessions.get(sessionID);
1087
+ if (state) {
1088
+ state.deleted = true;
1089
+ state.gateEnabled = false;
1090
+ }
1091
+ rt.sessions.delete(sessionID);
1092
+ return;
1093
+ }
1094
+ if (type === "session.created") {
1095
+ const validated = validateTopLevelSessionMetadata({
1096
+ id: event.data?.sessionID,
1097
+ directory: event.data?.location?.directory,
1098
+ parentID: event.data?.parentID
1099
+ });
1100
+ if (!validated) {
1101
+ logDiag("session.created ignored: invalid top-level session metadata");
1102
+ return;
1103
+ }
1104
+ const existing = rt.sessions.get(validated.sessionID);
1105
+ if (existing && !existing.deleted) return;
1106
+ rt.deleted.delete(validated.sessionID);
1107
+ advanceSessionGeneration(validated.sessionID);
1108
+ const created = createGateSessionState(validated.sessionID, validated.directory);
1109
+ rt.sessions.set(created.sessionID, created);
1110
+ logDiag(`registered session ${created.sessionID} (${created.directory})`);
1111
+ await armBootstrapIfPending(ctx, created);
1112
+ return;
1113
+ }
1114
+ if (type === "session.idle" || type === "session.execution.succeeded") {
1115
+ const sessionID = asString(event.data?.sessionID);
1116
+ if (!sessionID) return;
1117
+ let state = rt.sessions.get(sessionID);
1118
+ if (!state || state.deleted) {
1119
+ state = await getOrRegisterSession(ctx, sessionID) ?? void 0;
1120
+ if (!state) return;
1121
+ await armBootstrapIfPending(ctx, state);
1122
+ }
1123
+ if (!state.gateEnabled || state.busy) return;
1124
+ if (process.env.OPENCODE_GATE_DISABLED === "1") return;
1125
+ logDiag(`session ${sessionID} went idle \u2014 gate turn-end starting`);
1126
+ kickGateTurnEnd(ctx, state, "idle");
1127
+ return;
1128
+ }
1129
+ }
1130
+ var plugin = Plugin.define({
1131
+ id: "opencode.completion-gate",
1132
+ async setup(ctx) {
1133
+ const rt = runtime();
1134
+ if (!rt.bootstrapCaptured) {
1135
+ rt.bootstrapPending = readBootstrapGateCommand();
1136
+ rt.bootstrapCaptured = true;
1137
+ if (rt.bootstrapPending) consumeBootstrapGateCommand();
1138
+ logDiag(
1139
+ `completion-gate: first setup (bootstrap=${rt.bootstrapPending ? rt.bootstrapPending.mode : "none"})`
1140
+ );
1141
+ }
1142
+ const commandReg = await ctx.command.transform((editor) => {
1143
+ editor.add({
1144
+ name: "gate",
1145
+ description: "Control the completion gate for this session (/gate [on|off|status|command] or /gate --only command)",
1146
+ execute: async ({ sessionID, prompt }) => {
1147
+ try {
1148
+ const state = await getOrRegisterSession(ctx, sessionID);
1149
+ if (!state || state.deleted) return;
1150
+ const argument = (prompt?.text ?? "").trim().replace(/^\/gate\b/i, "").trim();
1151
+ const applied = await applyToggle(ctx, state, argument);
1152
+ if (applied.kind === "enabled") {
1153
+ await warnIfNothingToRun(ctx, state);
1154
+ kickGateTurnEnd(ctx, state, "enabled via /gate");
1005
1155
  }
1006
- sessions.delete(sessionID);
1007
- }
1008
- return;
1009
- }
1010
- if (event.type === "session.created") {
1011
- const info = event.properties.info;
1012
- const validated = validateTopLevelSessionMetadata(info);
1013
- if (!validated) {
1014
- logDiag("session.created ignored: invalid top-level session metadata");
1015
- return;
1016
- }
1017
- deletedSessionIDs.delete(validated.sessionID);
1018
- advanceSessionGeneration(validated.sessionID);
1019
- const created = createGateSessionState(validated.sessionID, validated.directory);
1020
- sessions.set(created.sessionID, created);
1021
- logDiag(`registered session ${created.sessionID} (${created.directory})`);
1022
- const bootstrap = pendingBootstrap ?? readBootstrapGateCommand();
1023
- pendingBootstrap = null;
1024
- if (bootstrap) {
1025
- consumeBootstrapGateCommand();
1026
- created.extraCommand = bootstrap.command;
1027
- created.gateMode = bootstrap.mode;
1028
- created.sessionMaxRetries = bootstrap.mode === "command-only" && bootstrap.maxRetries !== void 0 ? bootstrap.maxRetries : null;
1029
- created.gateEnabled = true;
1030
- created.retries = 0;
1031
- created.escalated = false;
1032
- created.lastOutcome = null;
1033
- logDiag(
1034
- `gate bootstrap ${bootstrap.mode} custom command registered on ${created.sessionID}` + (created.sessionMaxRetries !== null ? ` (session maxRetries=${created.sessionMaxRetries})` : "")
1035
- );
1036
- await client.tui.showToast({
1037
- body: {
1038
- variant: "info",
1039
- message: created.sessionMaxRetries !== null ? `Completion gate armed (${bootstrap.mode}): ${bootstrap.command} \xB7 maxRetries=${created.sessionMaxRetries}` : `Completion gate armed (${bootstrap.mode}): ${bootstrap.command}`
1040
- }
1041
- }).catch(() => {
1042
- });
1156
+ } catch (err) {
1157
+ logDiag(`gate command error: ${describeSdkError(err)}`);
1043
1158
  }
1044
1159
  }
1045
- if (event.type === "session.status") {
1046
- const props = event.properties;
1047
- if (typeof props.sessionID !== "string") return;
1048
- const state = sessions.get(props.sessionID);
1049
- if (!state || !state.gateEnabled || state.busy) return;
1050
- if (props.status?.type !== "idle") return;
1051
- if (process.env.OPENCODE_GATE_DISABLED === "1") return;
1052
- logDiag(`session ${props.sessionID} went idle \u2014 gate turn-end starting`);
1053
- kickGateTurnEnd(client, state, "idle");
1054
- return;
1055
- }
1056
- } catch (err) {
1057
- logDiag(`event error: ${err}`);
1058
- }
1059
- },
1060
- "command.execute.before": async ({ command, sessionID, arguments: commandArguments }, output) => {
1061
- let applied = null;
1160
+ });
1161
+ });
1162
+ const hookReg = await ctx.session.hook("prompt", async (event) => {
1062
1163
  try {
1063
- if (command !== "gate") return;
1064
- const state = await getOrRegisterSession(client, sessionID);
1065
- if (!state || state.deleted) return;
1066
- applied = await applyToggle(client, state, commandArguments);
1067
- output.noReply = true;
1068
- clearParts(output);
1069
- if (applied.kind === "enabled") {
1070
- await warnIfNothingToRun(client, state);
1071
- kickGateTurnEnd(client, state, "enabled via /gate");
1072
- }
1164
+ await handlePrompt(ctx, event);
1073
1165
  } catch (err) {
1074
- logDiag(`command.execute.before error: ${err}`);
1075
- }
1076
- if (applied !== null && ABORT_COMMAND_TURN) {
1077
- logDiag(`gate command handled on ${sessionID} \u2014 aborting turn (sentinel)`);
1078
- throw new Error(applied.notice);
1166
+ logDiag(`prompt hook error: ${describeSdkError(err)}`);
1079
1167
  }
1080
- },
1081
- "chat.message": async ({ sessionID, agent }, output) => {
1168
+ });
1169
+ const controller = new AbortController();
1170
+ void (async () => {
1082
1171
  try {
1083
- const state = sessions.get(sessionID);
1084
- if (!state || state.deleted) return;
1085
- if (typeof agent === "string" && agent.trim() !== "") state.currentAgent = agent;
1086
- if (!Array.isArray(output?.parts) || output.parts.length === 0) return;
1087
- const textPart = output.parts.find((p) => p?.type === "text");
1088
- if (!textPart) return;
1089
- const text = textPart?.text ?? "";
1090
- if (text.trimStart().startsWith(INTERNAL_MARKER)) {
1091
- const lines = text.split(/\r?\n/);
1092
- const directive = lines.shift()?.trim() ?? "";
1093
- const argument2 = directive.slice(INTERNAL_MARKER.length).trim();
1094
- if (/^--only\s+/i.test(argument2)) {
1095
- await applyToggle(client, state, argument2);
1096
- const remainder = lines.join("\n").replace(/^\n+/, "");
1097
- if (!remainder) clearParts(output);
1098
- else textPart.text = remainder;
1172
+ for await (const raw of ctx.event.subscribe({ signal: controller.signal })) {
1173
+ try {
1174
+ const evt = raw;
1175
+ const type = typeof evt.type === "string" ? evt.type : "";
1176
+ if (type !== "session.created" && type !== "session.deleted" && type !== "session.idle" && type !== "session.execution.succeeded")
1177
+ continue;
1178
+ const id = asString(evt.id);
1179
+ if (id) {
1180
+ if (rt.seen.has(id)) continue;
1181
+ rt.seen.add(id);
1182
+ if (rt.seen.size > 5e3) rt.seen.clear();
1183
+ }
1184
+ await handleEvent(ctx, evt);
1185
+ } catch (err) {
1186
+ logDiag(`event error: ${describeSdkError(err)}`);
1099
1187
  }
1100
- return;
1101
- }
1102
- if (!text.trimStart().startsWith(MARKER)) {
1103
- state.retries = 0;
1104
- state.escalated = false;
1105
- state.lastOutcome = null;
1106
- return;
1107
1188
  }
1108
- const t = TOGGLE_RE.exec(text.trim());
1109
- const argument = (t?.[1] ?? "").trim();
1110
- if (!t || INJECTED_FAILURE_RE.test(argument) || INJECTED_SUCCESS_RE.test(argument)) return;
1111
- const applied = await applyToggle(client, state, argument);
1112
- if (applied.kind === "enabled") await warnIfNothingToRun(client, state);
1113
- textPart.text = `${applied.notice} (Plugin-handled; acknowledge briefly, take no other action, call no tools.)`;
1114
1189
  } catch (err) {
1115
- logDiag(`chat.message error: ${err}`);
1190
+ if (!controller.signal.aborted)
1191
+ logDiag(`event subscription error: ${describeSdkError(err)}`);
1116
1192
  }
1117
- }
1118
- };
1119
- };
1193
+ })();
1194
+ return () => {
1195
+ controller.abort();
1196
+ void commandReg?.dispose?.();
1197
+ void hookReg?.dispose?.();
1198
+ };
1199
+ }
1200
+ });
1120
1201
  var gate_default = plugin;
1121
1202
 
1122
1203
  // src/plugin.ts