opencode-completion-gate 1.3.1 → 2.0.1

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