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