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/index.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";
@@ -192,10 +195,49 @@ function loadGateConfig(startDir) {
192
195
  if (!config) return null;
193
196
  return { path, projectRoot: dirname(dirname(path)), config };
194
197
  }
198
+ var BOOTSTRAP_COMMAND_ENV = "OPENCODE_GATE_BOOTSTRAP_COMMAND";
199
+ var BOOTSTRAP_COMMAND_B64_ENV = "OPENCODE_GATE_BOOTSTRAP_COMMAND_B64";
200
+ var BOOTSTRAP_MODE_ENV = "OPENCODE_GATE_BOOTSTRAP_MODE";
201
+ var BOOTSTRAP_MAX_RETRIES_ENV = "OPENCODE_GATE_BOOTSTRAP_MAX_RETRIES";
195
202
  function parsePositiveIntToken(tok) {
196
203
  const n = Number(tok);
197
204
  return Number.isFinite(n) && n > 0 ? Math.floor(n) : null;
198
205
  }
206
+ function readBootstrapGateCommand() {
207
+ const b64 = process.env[BOOTSTRAP_COMMAND_B64_ENV];
208
+ const plain = process.env[BOOTSTRAP_COMMAND_ENV];
209
+ let command = "";
210
+ if (typeof b64 === "string" && b64.trim() !== "") {
211
+ const compact = b64.trim().replace(/\s+/g, "");
212
+ if (/^[A-Za-z0-9+/]*={0,2}$/.test(compact) && compact.length % 4 === 0) {
213
+ try {
214
+ command = Buffer.from(compact, "base64").toString("utf8");
215
+ } catch {
216
+ command = "";
217
+ }
218
+ }
219
+ } else if (typeof plain === "string") {
220
+ command = plain;
221
+ }
222
+ command = command.trim();
223
+ if (!command) return null;
224
+ const mode = process.env[BOOTSTRAP_MODE_ENV]?.trim().toLowerCase() === "combined" ? "combined" : "command-only";
225
+ let maxRetries;
226
+ if (mode === "command-only") {
227
+ const raw = process.env[BOOTSTRAP_MAX_RETRIES_ENV];
228
+ if (typeof raw === "string" && raw.trim() !== "") {
229
+ const parsed = parsePositiveIntToken(raw.trim());
230
+ if (parsed !== null) maxRetries = parsed;
231
+ }
232
+ }
233
+ return maxRetries !== void 0 ? { command, mode, maxRetries } : { command, mode };
234
+ }
235
+ function consumeBootstrapGateCommand() {
236
+ delete process.env[BOOTSTRAP_COMMAND_B64_ENV];
237
+ delete process.env[BOOTSTRAP_COMMAND_ENV];
238
+ delete process.env[BOOTSTRAP_MODE_ENV];
239
+ delete process.env[BOOTSTRAP_MAX_RETRIES_ENV];
240
+ }
199
241
  function parseOnlyCommand(remainder) {
200
242
  if (!/^\s/.test(remainder)) return { command: "", invalidRetry: false };
201
243
  let body = remainder.trim();
@@ -228,6 +270,13 @@ function effectiveMaxRetries(state, configMaxRetries) {
228
270
  return { value: state.sessionMaxRetries, source: "session" };
229
271
  return { value: configMaxRetries, source: "config" };
230
272
  }
273
+ function validateTopLevelSessionMetadata(info, expectedSessionID) {
274
+ if (!info || typeof info !== "object") return null;
275
+ const metadata = info;
276
+ if (typeof metadata.id !== "string" || metadata.id.trim() === "" || expectedSessionID !== void 0 && metadata.id !== expectedSessionID || typeof metadata.directory !== "string" || metadata.directory.trim() === "" || metadata.parentID !== void 0)
277
+ return null;
278
+ return { sessionID: metadata.id, directory: metadata.directory };
279
+ }
231
280
 
232
281
  // src/ado-pr.ts
233
282
  import { existsSync as existsSync2, mkdirSync, mkdtempSync } from "fs";
@@ -563,47 +612,33 @@ function parseVerdict(output) {
563
612
  const last = matches[matches.length - 1];
564
613
  return last ? last[1].toUpperCase() : null;
565
614
  }
566
- function unwrapSdk(res) {
567
- if (res && typeof res === "object" && ("data" in res || "error" in res)) {
568
- const r = res;
569
- if (r.error != null)
570
- throw new Error(
571
- typeof r.error === "string" ? r.error : r.error && typeof r.error === "object" && "message" in r.error ? String(r.error.message) : JSON.stringify(r.error)
572
- );
573
- return r.data;
574
- }
575
- return res;
576
- }
577
- function reviewerText(res) {
578
- const parts = res?.parts;
579
- if (!Array.isArray(parts)) return "";
580
- return parts.filter(
581
- (p) => !!p && typeof p === "object" && p.type === "text"
582
- ).map((p) => String(p.text ?? "")).join("\n");
583
- }
584
615
  async function runReviewAssertion(a, cwd, client, isAborted) {
585
616
  if (isAborted?.()) throw new GateAborted();
586
617
  if (!client?.session)
587
- return fail(a.name, "no opencode SDK client available to run the reviewer session");
618
+ return fail(a.name, "no opencode plugin context available to run the reviewer session");
588
619
  const prompt = [
589
620
  a.prompt ?? "Review the changes on this branch against the task requirements.",
590
621
  'Finish your reply with a final line containing exactly "VERDICT: PASS" or "VERDICT: FAIL" followed by a one-line justification.'
591
622
  ].join("\n");
623
+ let sessionId;
592
624
  try {
593
- const created = unwrapSdk(
594
- await client.session.create({ query: { directory: cwd } })
595
- );
596
- const sessionId = created?.id;
625
+ const created = await client.session.create({ directory: cwd });
626
+ sessionId = created?.id;
597
627
  if (!sessionId)
598
628
  return fail(a.name, "could not create reviewer session (no session id in response)");
599
629
  let timer;
600
630
  try {
601
631
  const raced = await Promise.race([
602
- client.session.prompt({
603
- path: { id: sessionId },
604
- body: { agent: a.agent, parts: [{ type: "text", text: prompt }] }
605
- }).then(
606
- (r) => ({ ok: true, r }),
632
+ (async () => {
633
+ await client.session.prompt({
634
+ sessionID: sessionId,
635
+ text: prompt,
636
+ agent: a.agent
637
+ });
638
+ const text2 = await client.session.context({ sessionID: sessionId });
639
+ return { ok: true, text: text2 };
640
+ })().then(
641
+ (r) => r,
607
642
  (err) => ({ ok: false, err })
608
643
  ),
609
644
  new Promise((resolve) => {
@@ -612,7 +647,7 @@ async function runReviewAssertion(a, cwd, client, isAborted) {
612
647
  ]);
613
648
  if ("timedOut" in raced) {
614
649
  try {
615
- await Promise.resolve(client.session.abort?.({ path: { id: sessionId } }));
650
+ await Promise.resolve(client.session.abort?.({ sessionID: sessionId }));
616
651
  } catch {
617
652
  }
618
653
  return fail(
@@ -621,7 +656,7 @@ async function runReviewAssertion(a, cwd, client, isAborted) {
621
656
  );
622
657
  }
623
658
  if (!raced.ok) return fail(a.name, `reviewer session failed: ${describeSdkError(raced.err)}`);
624
- const text = reviewerText(unwrapSdk(raced.r));
659
+ const text = raced.text;
625
660
  const verdict = parseVerdict(text);
626
661
  logDiag(`review "${a.name}": verdict=${verdict ?? "none"}`);
627
662
  const evidence = truncateTail(text);
@@ -639,6 +674,174 @@ ${evidence}`);
639
674
  }
640
675
 
641
676
  // src/gate.ts
677
+ var MARKER = "[completion-gate]";
678
+ var INTERNAL_MARKER = "[completion-gate-internal]";
679
+ var TOGGLE_RE = /^\[completion-gate\](?:\s+(.*?))?\s*$/i;
680
+ var INJECTED_FAILURE_RE = /^✖ Completion gate failed — "[^"]+"\. Fix these issues, then finish again\.\n\n```[\s\S]*\n```\n\n\(RETRY \d+\/\d+\)$/;
681
+ var INJECTED_SUCCESS_RE = /^✅ Completion gate passed \([^\n]*\)\. You may report done\.$/;
682
+ var RUNTIME_KEY = /* @__PURE__ */ Symbol.for("opencode.completion-gate.runtime.v2");
683
+ function runtime() {
684
+ const store = globalThis;
685
+ let rt = store[RUNTIME_KEY];
686
+ if (!rt) {
687
+ rt = {
688
+ sessions: /* @__PURE__ */ new Map(),
689
+ deleted: /* @__PURE__ */ new Set(),
690
+ generations: /* @__PURE__ */ new Map(),
691
+ bootstrapPending: null,
692
+ bootstrapCaptured: false,
693
+ seen: /* @__PURE__ */ new Set(),
694
+ seenPrompts: /* @__PURE__ */ new Set()
695
+ };
696
+ store[RUNTIME_KEY] = rt;
697
+ }
698
+ return rt;
699
+ }
700
+ function getSessionGeneration(sessionID) {
701
+ return runtime().generations.get(sessionID) ?? 0;
702
+ }
703
+ function advanceSessionGeneration(sessionID) {
704
+ const rt = runtime();
705
+ rt.generations.set(sessionID, (rt.generations.get(sessionID) ?? 0) + 1);
706
+ }
707
+ function createGateSessionState(sessionID, directory) {
708
+ return {
709
+ sessionID,
710
+ directory,
711
+ gateEnabled: false,
712
+ gateMode: "combined",
713
+ sessionMaxRetries: null,
714
+ retries: 0,
715
+ lastOutcome: null,
716
+ escalated: false,
717
+ busy: false,
718
+ deleted: false
719
+ };
720
+ }
721
+ function asString(value) {
722
+ return typeof value === "string" && value.trim() !== "" ? value : void 0;
723
+ }
724
+ async function getOrRegisterSession(ctx, sessionID) {
725
+ const rt = runtime();
726
+ const existing = rt.sessions.get(sessionID);
727
+ if (existing) return existing.deleted ? null : existing;
728
+ const lookupSessionID = sessionID;
729
+ const lookupGeneration = getSessionGeneration(lookupSessionID);
730
+ try {
731
+ const info = await ctx.session.get({ sessionID: lookupSessionID });
732
+ const validated = validateTopLevelSessionMetadata({
733
+ id: info?.id,
734
+ directory: info?.location?.directory,
735
+ parentID: info?.parentID
736
+ });
737
+ if (!validated) {
738
+ logDiag(
739
+ `lazy registration rejected session ${lookupSessionID}: invalid top-level session metadata`
740
+ );
741
+ return null;
742
+ }
743
+ if (rt.deleted.has(lookupSessionID) || getSessionGeneration(lookupSessionID) !== lookupGeneration) {
744
+ logDiag(
745
+ `lazy registration ignored session ${lookupSessionID}: session was deleted or superseded while lookup was pending`
746
+ );
747
+ return null;
748
+ }
749
+ const state = createGateSessionState(validated.sessionID, validated.directory);
750
+ rt.sessions.set(state.sessionID, state);
751
+ logDiag(`lazily registered session ${state.sessionID} (${state.directory})`);
752
+ return state;
753
+ } catch (err) {
754
+ logDiag(`lazy registration lookup failed for ${sessionID}: ${describeSdkError(err)}`);
755
+ return null;
756
+ }
757
+ }
758
+ async function notify(ctx, state, message) {
759
+ logDiag(`notify ${state.sessionID}: ${message}`);
760
+ try {
761
+ await ctx.session.synthetic({ sessionID: state.sessionID, text: message });
762
+ } catch (err) {
763
+ logDiag(`notify failed: ${describeSdkError(err)}`);
764
+ }
765
+ }
766
+ async function injectPrompt(ctx, sessionID, text) {
767
+ try {
768
+ await ctx.session.prompt({ sessionID, text });
769
+ } catch (err) {
770
+ logDiag(`prompt injection error: ${describeSdkError(err)}`);
771
+ }
772
+ }
773
+ async function applyToggle(ctx, state, rawArgument) {
774
+ const normalized = rawArgument.trim().toLowerCase();
775
+ const arg = normalized || "on";
776
+ if (arg === "status") {
777
+ const loaded = loadGateConfig(state.directory);
778
+ const cap = state.gateMode === "command-only" && state.sessionMaxRetries !== null ? { value: state.sessionMaxRetries, source: "session" } : { value: loaded?.config.maxRetries ?? 3, source: "config" };
779
+ 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})`;
780
+ await notify(ctx, state, notice2);
781
+ return { notice: notice2, kind: "status" };
782
+ }
783
+ if (/^--only/i.test(rawArgument.trim())) {
784
+ const onlyMatch = /^--only(.*)$/i.exec(rawArgument.trim());
785
+ const remainder = onlyMatch?.[1] ?? "";
786
+ const parsed = parseOnlyCommand(remainder);
787
+ if (!parsed.command || parsed.invalidRetry) {
788
+ const notice3 = 'Usage: /gate --only "command" [--retries N]';
789
+ await notify(ctx, state, notice3);
790
+ return { notice: notice3, kind: "usage" };
791
+ }
792
+ state.extraCommand = parsed.command;
793
+ state.gateMode = "command-only";
794
+ state.sessionMaxRetries = parsed.maxRetries ?? null;
795
+ state.gateEnabled = true;
796
+ state.retries = 0;
797
+ state.escalated = false;
798
+ state.lastOutcome = null;
799
+ const notice2 = parsed.maxRetries !== void 0 ? `Completion gate armed (command-only): ${parsed.command} \xB7 maxRetries=${parsed.maxRetries}` : `Completion gate armed (command-only): ${parsed.command}`;
800
+ await notify(ctx, state, notice2);
801
+ logDiag(
802
+ `gate command-only custom command registered on ${state.sessionID}` + (parsed.maxRetries !== void 0 ? ` (session maxRetries=${parsed.maxRetries})` : "")
803
+ );
804
+ return { notice: notice2, kind: "enabled" };
805
+ }
806
+ if (arg !== "on" && arg !== "off") {
807
+ state.extraCommand = rawArgument.trim();
808
+ state.gateMode = "combined";
809
+ state.gateEnabled = true;
810
+ state.retries = 0;
811
+ state.escalated = false;
812
+ state.lastOutcome = null;
813
+ const notice2 = `Completion gate armed (combined): ${state.extraCommand}`;
814
+ await notify(ctx, state, notice2);
815
+ logDiag(`gate custom command registered on ${state.sessionID}`);
816
+ return { notice: notice2, kind: "enabled" };
817
+ }
818
+ state.gateEnabled = arg === "on";
819
+ if (state.gateEnabled) {
820
+ state.retries = 0;
821
+ state.escalated = false;
822
+ state.lastOutcome = null;
823
+ }
824
+ const notice = `Completion gate ${state.gateEnabled ? "enabled" : "disabled"} for this session.`;
825
+ await notify(ctx, state, notice);
826
+ logDiag(`gate ${arg} on ${state.sessionID}`);
827
+ return { notice, kind: state.gateEnabled ? "enabled" : "disabled" };
828
+ }
829
+ async function warnIfNothingToRun(ctx, state) {
830
+ if (state.extraCommand) return;
831
+ if (loadGateConfig(state.directory)) return;
832
+ const msg = `Completion gate enabled but nothing to run: no .opencode/completion-gate.json found from ${state.directory}.`;
833
+ logDiag(`gate on ${state.sessionID}: ${msg}`);
834
+ await notify(ctx, state, msg);
835
+ }
836
+ function kickGateTurnEnd(ctx, state, reason) {
837
+ if (state.deleted || !state.gateEnabled || state.busy) return;
838
+ if (process.env.OPENCODE_GATE_DISABLED === "1") return;
839
+ state.busy = true;
840
+ logDiag(`gate kick on ${state.sessionID} (${reason}) \u2014 evaluation starting`);
841
+ runGateTurnEnd(ctx, state).catch((err) => logDiag(`gate flow error: ${describeSdkError(err)}`)).finally(() => {
842
+ state.busy = false;
843
+ });
844
+ }
642
845
  async function runCommandAssertion(a, cwd, isAborted) {
643
846
  if (isAborted?.()) throw new GateAborted();
644
847
  logDiag(
@@ -688,9 +891,320 @@ async function evaluateAssertions(assertions, projectRoot, client, isAborted, ad
688
891
  }
689
892
  return results;
690
893
  }
894
+ function buildReviewClient(ctx) {
895
+ const assistantText = (messages) => {
896
+ const out = [];
897
+ for (const message of messages ?? []) {
898
+ if (!message || message.type !== "assistant") continue;
899
+ for (const content of message.content ?? []) {
900
+ if (content && content.type === "text" && typeof content.text === "string")
901
+ out.push(content.text);
902
+ }
903
+ }
904
+ return out.join("\n");
905
+ };
906
+ return {
907
+ session: {
908
+ create: async (input) => {
909
+ const created = await ctx.session.create(
910
+ input?.directory ? { title: "completion-gate self-review", location: { directory: input.directory } } : { title: "completion-gate self-review" }
911
+ );
912
+ return { id: created?.id };
913
+ },
914
+ prompt: async ({ sessionID, text, agent }) => {
915
+ if (agent) await ctx.session.switchAgent({ sessionID, agent });
916
+ await ctx.session.prompt({ sessionID, text });
917
+ await ctx.session.wait({ sessionID });
918
+ },
919
+ context: async ({ sessionID }) => {
920
+ const messages = await ctx.session.context({ sessionID });
921
+ return assistantText(messages);
922
+ },
923
+ abort: async ({ sessionID }) => {
924
+ try {
925
+ await ctx.session.interrupt({ sessionID });
926
+ } catch {
927
+ }
928
+ }
929
+ }
930
+ };
931
+ }
932
+ function injectFailureText(state, outcome, maxRetries) {
933
+ return [
934
+ `${MARKER} \u2716 Completion gate failed \u2014 "${outcome.name}". Fix these issues, then finish again.`,
935
+ "",
936
+ "```",
937
+ outcome.evidence,
938
+ "```",
939
+ "",
940
+ `(RETRY ${state.retries}/${maxRetries})`
941
+ ].join("\n");
942
+ }
943
+ async function runGateTurnEnd(ctx, state) {
944
+ const isAborted = () => state.deleted || !state.gateEnabled || process.env.OPENCODE_GATE_DISABLED === "1";
945
+ if (state.lastOutcome === "pass") {
946
+ logDiag(`gate turn-end skipped on ${state.sessionID} \u2014 already green this streak`);
947
+ return;
948
+ }
949
+ const loaded = loadGateConfig(state.directory);
950
+ if (!loaded && !state.extraCommand) {
951
+ logDiag(
952
+ `gate turn-end on ${state.sessionID}: no .opencode/completion-gate.json found from ${state.directory} \u2014 nothing to run`
953
+ );
954
+ return;
955
+ }
956
+ const projectRoot = loaded?.projectRoot ?? state.directory;
957
+ const config = loaded?.config ?? { maxRetries: 3, assertions: [] };
958
+ const cap = effectiveMaxRetries(state, config.maxRetries);
959
+ const sessionAssertion = {
960
+ type: "command",
961
+ name: "session-command",
962
+ run: state.extraCommand ?? "",
963
+ timeoutSeconds: 300
964
+ };
965
+ const assertions = state.extraCommand ? state.gateMode === "command-only" ? [sessionAssertion] : [sessionAssertion, ...config.assertions] : config.assertions;
966
+ logDiag(
967
+ `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})`
968
+ );
969
+ const results = await evaluateAssertions(
970
+ assertions,
971
+ projectRoot,
972
+ buildReviewClient(ctx),
973
+ isAborted
974
+ );
975
+ if (results === null) {
976
+ logDiag(
977
+ `gate turn-end ABORTED on ${state.sessionID} \u2014 gate was disabled mid-run, staying silent`
978
+ );
979
+ return;
980
+ }
981
+ const last = results[results.length - 1];
982
+ if (!last) return;
983
+ if (last.passed) {
984
+ logDiag(`gate PASSED on ${state.sessionID}: all ${results.length} assertion(s) green`);
985
+ if (isAborted()) {
986
+ logDiag(`gate turn-end ABORTED on ${state.sessionID} \u2014 gate disabled before success notice`);
987
+ return;
988
+ }
989
+ state.lastOutcome = "pass";
990
+ await injectPrompt(
991
+ ctx,
992
+ state.sessionID,
993
+ `${MARKER} \u2705 Completion gate passed (${results.map((r) => r.name).join(", ")}). You may report done.`
994
+ );
995
+ return;
996
+ }
997
+ if (isAborted()) {
998
+ logDiag(`gate turn-end ABORTED on ${state.sessionID} \u2014 gate disabled before retry injection`);
999
+ return;
1000
+ }
1001
+ state.lastOutcome = "fail";
1002
+ if (state.retries >= cap.value) {
1003
+ if (!state.escalated) {
1004
+ state.escalated = true;
1005
+ await notify(
1006
+ ctx,
1007
+ state,
1008
+ `\u2192 Completion gate "${last.name}" still failing after ${cap.value} retries \u2014 manual attention needed`
1009
+ );
1010
+ logDiag(
1011
+ `gate ESCALATED on ${state.sessionID}: "${last.name}" still failing after ${cap.value} retries \u2014 manual attention needed`
1012
+ );
1013
+ }
1014
+ return;
1015
+ }
1016
+ state.retries += 1;
1017
+ logDiag(
1018
+ `gate FAILED on ${state.sessionID}: "${last.name}" \u2014 retry ${state.retries}/${cap.value}, injecting fix request`
1019
+ );
1020
+ await injectPrompt(ctx, state.sessionID, injectFailureText(state, last, cap.value));
1021
+ }
1022
+ async function handlePrompt(ctx, event) {
1023
+ const sessionID = asString(event?.sessionID);
1024
+ if (!sessionID) return;
1025
+ const messageID = asString(event?.messageID);
1026
+ if (messageID) {
1027
+ const rt = runtime();
1028
+ if (rt.seenPrompts.has(messageID)) return;
1029
+ rt.seenPrompts.add(messageID);
1030
+ if (rt.seenPrompts.size > 5e3) rt.seenPrompts.clear();
1031
+ }
1032
+ const state = runtime().sessions.get(sessionID);
1033
+ if (!state || state.deleted) return;
1034
+ const text = event?.prompt?.text ?? "";
1035
+ if (text.trimStart().startsWith(INTERNAL_MARKER)) {
1036
+ const lines = text.split(/\r?\n/);
1037
+ const directive = lines.shift()?.trim() ?? "";
1038
+ const argument2 = directive.slice(INTERNAL_MARKER.length).trim();
1039
+ if (/^--only\s+/i.test(argument2)) {
1040
+ await applyToggle(ctx, state, argument2);
1041
+ const remainder = lines.join("\n").replace(/^\n+/, "");
1042
+ if (event.prompt) event.prompt.text = remainder;
1043
+ }
1044
+ return;
1045
+ }
1046
+ if (!text.trimStart().startsWith(MARKER)) {
1047
+ state.retries = 0;
1048
+ state.escalated = false;
1049
+ state.lastOutcome = null;
1050
+ return;
1051
+ }
1052
+ const t = TOGGLE_RE.exec(text.trim());
1053
+ const argument = (t?.[1] ?? "").trim();
1054
+ if (!t || INJECTED_FAILURE_RE.test(argument) || INJECTED_SUCCESS_RE.test(argument)) return;
1055
+ const applied = await applyToggle(ctx, state, argument);
1056
+ if (applied.kind === "enabled") await warnIfNothingToRun(ctx, state);
1057
+ if (event.prompt)
1058
+ event.prompt.text = `${applied.notice} (Plugin-handled; acknowledge briefly, take no other action, call no tools.)`;
1059
+ }
1060
+ async function armBootstrapIfPending(ctx, state) {
1061
+ const rt = runtime();
1062
+ const bootstrap = rt.bootstrapPending ?? readBootstrapGateCommand();
1063
+ rt.bootstrapPending = null;
1064
+ if (!bootstrap) return;
1065
+ consumeBootstrapGateCommand();
1066
+ state.extraCommand = bootstrap.command;
1067
+ state.gateMode = bootstrap.mode;
1068
+ state.sessionMaxRetries = bootstrap.mode === "command-only" && bootstrap.maxRetries !== void 0 ? bootstrap.maxRetries : null;
1069
+ state.gateEnabled = true;
1070
+ state.retries = 0;
1071
+ state.escalated = false;
1072
+ state.lastOutcome = null;
1073
+ logDiag(
1074
+ `gate bootstrap ${bootstrap.mode} custom command registered on ${state.sessionID}` + (state.sessionMaxRetries !== null ? ` (session maxRetries=${state.sessionMaxRetries})` : "")
1075
+ );
1076
+ await notify(
1077
+ ctx,
1078
+ state,
1079
+ state.sessionMaxRetries !== null ? `Completion gate armed (${bootstrap.mode}): ${bootstrap.command} \xB7 maxRetries=${state.sessionMaxRetries}` : `Completion gate armed (${bootstrap.mode}): ${bootstrap.command}`
1080
+ );
1081
+ }
1082
+ async function handleEvent(ctx, event) {
1083
+ const type = typeof event.type === "string" ? event.type : "";
1084
+ const rt = runtime();
1085
+ if (type === "session.deleted") {
1086
+ const sessionID = asString(event.data?.sessionID);
1087
+ if (!sessionID) return;
1088
+ rt.deleted.add(sessionID);
1089
+ advanceSessionGeneration(sessionID);
1090
+ const state = rt.sessions.get(sessionID);
1091
+ if (state) {
1092
+ state.deleted = true;
1093
+ state.gateEnabled = false;
1094
+ }
1095
+ rt.sessions.delete(sessionID);
1096
+ return;
1097
+ }
1098
+ if (type === "session.created") {
1099
+ const validated = validateTopLevelSessionMetadata({
1100
+ id: event.data?.sessionID,
1101
+ directory: event.data?.location?.directory,
1102
+ parentID: event.data?.parentID
1103
+ });
1104
+ if (!validated) {
1105
+ logDiag("session.created ignored: invalid top-level session metadata");
1106
+ return;
1107
+ }
1108
+ const existing = rt.sessions.get(validated.sessionID);
1109
+ if (existing && !existing.deleted) return;
1110
+ rt.deleted.delete(validated.sessionID);
1111
+ advanceSessionGeneration(validated.sessionID);
1112
+ const created = createGateSessionState(validated.sessionID, validated.directory);
1113
+ rt.sessions.set(created.sessionID, created);
1114
+ logDiag(`registered session ${created.sessionID} (${created.directory})`);
1115
+ await armBootstrapIfPending(ctx, created);
1116
+ return;
1117
+ }
1118
+ if (type === "session.idle" || type === "session.execution.succeeded") {
1119
+ const sessionID = asString(event.data?.sessionID);
1120
+ if (!sessionID) return;
1121
+ let state = rt.sessions.get(sessionID);
1122
+ if (!state || state.deleted) {
1123
+ state = await getOrRegisterSession(ctx, sessionID) ?? void 0;
1124
+ if (!state) return;
1125
+ await armBootstrapIfPending(ctx, state);
1126
+ }
1127
+ if (!state.gateEnabled || state.busy) return;
1128
+ if (process.env.OPENCODE_GATE_DISABLED === "1") return;
1129
+ logDiag(`session ${sessionID} went idle \u2014 gate turn-end starting`);
1130
+ kickGateTurnEnd(ctx, state, "idle");
1131
+ return;
1132
+ }
1133
+ }
1134
+ var plugin = Plugin.define({
1135
+ id: "opencode.completion-gate",
1136
+ async setup(ctx) {
1137
+ const rt = runtime();
1138
+ if (!rt.bootstrapCaptured) {
1139
+ rt.bootstrapPending = readBootstrapGateCommand();
1140
+ rt.bootstrapCaptured = true;
1141
+ if (rt.bootstrapPending) consumeBootstrapGateCommand();
1142
+ logDiag(
1143
+ `completion-gate: first setup (bootstrap=${rt.bootstrapPending ? rt.bootstrapPending.mode : "none"})`
1144
+ );
1145
+ }
1146
+ const commandReg = await ctx.command.transform((editor) => {
1147
+ editor.add({
1148
+ name: "gate",
1149
+ description: "Control the completion gate for this session (/gate [on|off|status|command] or /gate --only command)",
1150
+ execute: async ({ sessionID, prompt }) => {
1151
+ try {
1152
+ const state = await getOrRegisterSession(ctx, sessionID);
1153
+ if (!state || state.deleted) return;
1154
+ const argument = (prompt?.text ?? "").trim().replace(/^\/gate\b/i, "").trim();
1155
+ const applied = await applyToggle(ctx, state, argument);
1156
+ if (applied.kind === "enabled") {
1157
+ await warnIfNothingToRun(ctx, state);
1158
+ kickGateTurnEnd(ctx, state, "enabled via /gate");
1159
+ }
1160
+ } catch (err) {
1161
+ logDiag(`gate command error: ${describeSdkError(err)}`);
1162
+ }
1163
+ }
1164
+ });
1165
+ });
1166
+ const hookReg = await ctx.session.hook("prompt", async (event) => {
1167
+ try {
1168
+ await handlePrompt(ctx, event);
1169
+ } catch (err) {
1170
+ logDiag(`prompt hook error: ${describeSdkError(err)}`);
1171
+ }
1172
+ });
1173
+ const controller = new AbortController();
1174
+ void (async () => {
1175
+ try {
1176
+ for await (const raw of ctx.event.subscribe({ signal: controller.signal })) {
1177
+ try {
1178
+ const evt = raw;
1179
+ const type = typeof evt.type === "string" ? evt.type : "";
1180
+ if (type !== "session.created" && type !== "session.deleted" && type !== "session.idle" && type !== "session.execution.succeeded")
1181
+ continue;
1182
+ const id = asString(evt.id);
1183
+ if (id) {
1184
+ if (rt.seen.has(id)) continue;
1185
+ rt.seen.add(id);
1186
+ if (rt.seen.size > 5e3) rt.seen.clear();
1187
+ }
1188
+ await handleEvent(ctx, evt);
1189
+ } catch (err) {
1190
+ logDiag(`event error: ${describeSdkError(err)}`);
1191
+ }
1192
+ }
1193
+ } catch (err) {
1194
+ if (!controller.signal.aborted)
1195
+ logDiag(`event subscription error: ${describeSdkError(err)}`);
1196
+ }
1197
+ })();
1198
+ return () => {
1199
+ controller.abort();
1200
+ void commandReg?.dispose?.();
1201
+ void hookReg?.dispose?.();
1202
+ };
1203
+ }
1204
+ });
691
1205
 
692
1206
  // src/index.ts
693
- var VERSION = "1.0.0";
1207
+ var VERSION = "2.0.0";
694
1208
  var pluginMeta = {
695
1209
  name: "opencode-completion-gate",
696
1210
  version: VERSION,