opencode-completion-gate 1.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 ADDED
@@ -0,0 +1,1061 @@
1
+ // src/core.ts
2
+ import { readFileSync, appendFileSync, existsSync, mkdirSync, mkdtempSync } from "fs";
3
+ import { join, dirname } from "path";
4
+ import { homedir, tmpdir } from "os";
5
+ import { exec, execFile } from "child_process";
6
+ var BASE_DIR = join(homedir(), ".config", "opencode");
7
+ function logDiag(msg) {
8
+ try {
9
+ appendFileSync(join(BASE_DIR, "gate-diag.log"), `${(/* @__PURE__ */ new Date()).toISOString()} ${msg}
10
+ `);
11
+ } catch {
12
+ }
13
+ }
14
+ function brief(s) {
15
+ const line = s.replace(/\r\n/g, "\n").split("\n").find((l) => l.trim() !== "") ?? "";
16
+ return line.length > 160 ? `${line.slice(0, 157)}...` : line;
17
+ }
18
+ function truncateTail(text, maxLines = 50) {
19
+ const lines = text.replace(/\r\n/g, "\n").split("\n").filter((l) => l.trim() !== "");
20
+ if (lines.length <= maxLines) return lines.join("\n");
21
+ return `[... ${lines.length - maxLines} earlier lines omitted]
22
+ ${lines.slice(-maxLines).join("\n")}`;
23
+ }
24
+ function positiveInt(v, fallback) {
25
+ return typeof v === "number" && Number.isFinite(v) && v > 0 ? Math.floor(v) : fallback;
26
+ }
27
+ function validateGateConfig(raw) {
28
+ if (!raw || typeof raw !== "object") return null;
29
+ const obj = raw;
30
+ if (obj.enabled === false) return null;
31
+ if (!Array.isArray(obj.assertions)) return null;
32
+ const assertions = [];
33
+ for (const a of obj.assertions) {
34
+ if (!a || typeof a !== "object") return null;
35
+ const nameOf = (fb) => typeof a.name === "string" && a.name.trim() ? a.name : fb;
36
+ switch (a.type) {
37
+ case "command":
38
+ if (typeof a.run !== "string" || !a.run.trim()) return null;
39
+ assertions.push({
40
+ type: "command",
41
+ name: nameOf(a.run.split(/\s+/)[0]),
42
+ run: a.run,
43
+ timeoutSeconds: positiveInt(a.timeoutSeconds, 300)
44
+ });
45
+ break;
46
+ case "ado-pr":
47
+ assertions.push({
48
+ type: "ado-pr",
49
+ name: nameOf("ado-pr"),
50
+ pollTimeoutMinutes: positiveInt(a.pollTimeoutMinutes, 15),
51
+ pollIntervalSeconds: positiveInt(a.pollIntervalSeconds, 30),
52
+ skipIfNoPr: a.skipIfNoPr === true,
53
+ ignoreHumanPolicies: a.ignoreHumanPolicies === true
54
+ });
55
+ break;
56
+ case "opencode-review":
57
+ assertions.push({
58
+ type: "opencode-review",
59
+ name: nameOf("self-review"),
60
+ agent: typeof a.agent === "string" && a.agent.trim() ? a.agent : "reviewer",
61
+ prompt: typeof a.prompt === "string" && a.prompt.trim() ? a.prompt : void 0,
62
+ timeoutSeconds: positiveInt(a.timeoutSeconds, 900)
63
+ });
64
+ break;
65
+ default:
66
+ return null;
67
+ }
68
+ }
69
+ if (assertions.length === 0) return null;
70
+ return { enabled: true, maxRetries: positiveInt(obj.maxRetries, 3), assertions };
71
+ }
72
+ function findGateConfigPath(startDir) {
73
+ let dir = startDir;
74
+ for (; ; ) {
75
+ try {
76
+ const candidate = join(dir, ".opencode", "completion-gate.json");
77
+ if (existsSync(candidate)) return candidate;
78
+ if (existsSync(join(dir, ".git"))) return null;
79
+ const parent = dirname(dir);
80
+ if (parent === dir) return null;
81
+ dir = parent;
82
+ } catch {
83
+ return null;
84
+ }
85
+ }
86
+ }
87
+ function loadGateConfig(startDir) {
88
+ const path = findGateConfigPath(startDir);
89
+ if (!path) return null;
90
+ let config = null;
91
+ try {
92
+ config = validateGateConfig(JSON.parse(readFileSync(path, "utf8")));
93
+ } catch {
94
+ config = null;
95
+ }
96
+ if (!config) return null;
97
+ return { path, projectRoot: dirname(dirname(path)), config };
98
+ }
99
+ function outcomeFromErr(err) {
100
+ if (!err) return 0;
101
+ return typeof err.code === "number" ? err.code : null;
102
+ }
103
+ function runCommand(cmd, cwd, timeoutMs) {
104
+ return new Promise((resolve) => {
105
+ let childTimedOut = false;
106
+ const child = exec(
107
+ cmd,
108
+ { cwd, windowsHide: true, maxBuffer: 16 * 1024 * 1024 },
109
+ (err, stdout, stderr) => {
110
+ clearTimeout(timer);
111
+ resolve({
112
+ code: outcomeFromErr(err),
113
+ timedOut: Boolean(err && err.killed) || childTimedOut,
114
+ stdout: stdout?.toString() ?? "",
115
+ stderr: stderr?.toString() ?? ""
116
+ });
117
+ }
118
+ );
119
+ const timer = setTimeout(() => {
120
+ childTimedOut = true;
121
+ try {
122
+ child.kill();
123
+ } catch {
124
+ }
125
+ if (process.platform === "win32" && child.pid) {
126
+ exec(`taskkill /PID ${child.pid} /T /F`, { windowsHide: true }, () => {
127
+ });
128
+ }
129
+ }, timeoutMs);
130
+ });
131
+ }
132
+ function execFileOut(file, args, cwd, timeoutMs, spawnOpts) {
133
+ return new Promise((resolve) => {
134
+ execFile(
135
+ file,
136
+ args,
137
+ { cwd, windowsHide: true, timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024, ...spawnOpts },
138
+ (err, stdout, stderr) => {
139
+ resolve({
140
+ code: outcomeFromErr(err),
141
+ timedOut: Boolean(err && err.killed),
142
+ stdout: stdout?.toString() ?? "",
143
+ stderr: stderr?.toString() ?? ""
144
+ });
145
+ }
146
+ );
147
+ });
148
+ }
149
+ function pass(name) {
150
+ return { name, passed: true, evidence: "" };
151
+ }
152
+ function fail(name, evidence) {
153
+ return { name, passed: false, evidence: evidence.trim() };
154
+ }
155
+ async function runCommandAssertion(a, cwd, isAborted) {
156
+ if (isAborted?.()) throw new GateAborted();
157
+ logDiag(
158
+ `command "${a.name}": running ${JSON.stringify(a.run)} (cwd=${cwd}, timeout=${a.timeoutSeconds}s)`
159
+ );
160
+ const r = await runCommand(a.run, cwd, a.timeoutSeconds * 1e3);
161
+ logDiag(
162
+ r.timedOut ? `command "${a.name}": TIMED OUT after ${a.timeoutSeconds}s` : `command "${a.name}": exit code ${r.code}`
163
+ );
164
+ if (!r.timedOut && r.code === 0) return pass(a.name);
165
+ const why = r.timedOut ? `command timed out after ${a.timeoutSeconds}s` : `exit code ${r.code}`;
166
+ return fail(
167
+ a.name,
168
+ `${why}
169
+ ${truncateTail([r.stderr, r.stdout].filter((s) => s.trim()).join("\n---\n"))}`
170
+ );
171
+ }
172
+ var MARKER = "[completion-gate]";
173
+ var INTERNAL_MARKER = "[completion-gate-internal]";
174
+ var BOOTSTRAP_COMMAND_ENV = "OPENCODE_GATE_BOOTSTRAP_COMMAND";
175
+ var BOOTSTRAP_COMMAND_B64_ENV = "OPENCODE_GATE_BOOTSTRAP_COMMAND_B64";
176
+ var BOOTSTRAP_MODE_ENV = "OPENCODE_GATE_BOOTSTRAP_MODE";
177
+ function readBootstrapGateCommand() {
178
+ const b64 = process.env[BOOTSTRAP_COMMAND_B64_ENV];
179
+ const plain = process.env[BOOTSTRAP_COMMAND_ENV];
180
+ let command = "";
181
+ if (typeof b64 === "string" && b64.trim() !== "") {
182
+ const compact = b64.trim().replace(/\s+/g, "");
183
+ if (/^[A-Za-z0-9+/]*={0,2}$/.test(compact) && compact.length % 4 === 0) {
184
+ try {
185
+ command = Buffer.from(compact, "base64").toString("utf8");
186
+ } catch {
187
+ command = "";
188
+ }
189
+ }
190
+ } else if (typeof plain === "string") {
191
+ command = plain;
192
+ }
193
+ command = command.trim();
194
+ if (!command) return null;
195
+ const mode = process.env[BOOTSTRAP_MODE_ENV]?.trim().toLowerCase() === "combined" ? "combined" : "command-only";
196
+ return { command, mode };
197
+ }
198
+ function consumeBootstrapGateCommand() {
199
+ delete process.env[BOOTSTRAP_COMMAND_B64_ENV];
200
+ delete process.env[BOOTSTRAP_COMMAND_ENV];
201
+ delete process.env[BOOTSTRAP_MODE_ENV];
202
+ }
203
+ var TOGGLE_RE = /^\[completion-gate\](?:\s+(.*?))?\s*$/i;
204
+ var INJECTED_FAILURE_RE = /^✖ Completion gate failed — "[^"]+"\. Fix these issues, then finish again\.\n\n```[\s\S]*\n```\n\n\(RETRY \d+\/\d+\)$/;
205
+ var INJECTED_SUCCESS_RE = /^✅ Completion gate passed \([^\n]*\)\. You may report done\.$/;
206
+ var sessions = /* @__PURE__ */ new Map();
207
+ var deletedSessionIDs = /* @__PURE__ */ new Set();
208
+ var sessionGenerations = /* @__PURE__ */ new Map();
209
+ function getSessionGeneration(sessionID) {
210
+ return sessionGenerations.get(sessionID) ?? 0;
211
+ }
212
+ function advanceSessionGeneration(sessionID) {
213
+ sessionGenerations.set(sessionID, getSessionGeneration(sessionID) + 1);
214
+ }
215
+ function validateTopLevelSessionMetadata(info, expectedSessionID) {
216
+ if (!info || typeof info !== "object") return null;
217
+ const metadata = info;
218
+ 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) {
219
+ return null;
220
+ }
221
+ return { sessionID: metadata.id, directory: metadata.directory };
222
+ }
223
+ function createGateSessionState(sessionID, directory) {
224
+ return {
225
+ sessionID,
226
+ directory,
227
+ gateEnabled: false,
228
+ gateMode: "combined",
229
+ retries: 0,
230
+ lastOutcome: null,
231
+ escalated: false,
232
+ busy: false,
233
+ deleted: false
234
+ };
235
+ }
236
+ async function getOrRegisterSession(client, sessionID) {
237
+ const existing = sessions.get(sessionID);
238
+ if (existing) return existing.deleted ? null : existing;
239
+ const lookupSessionID = sessionID;
240
+ const lookupGeneration = getSessionGeneration(lookupSessionID);
241
+ try {
242
+ const info = unwrapSdk(
243
+ await client.session.get({ path: { id: lookupSessionID } })
244
+ );
245
+ const validated = validateTopLevelSessionMetadata(info, lookupSessionID);
246
+ if (!validated) {
247
+ logDiag(
248
+ `lazy registration rejected session ${lookupSessionID}: invalid top-level session metadata`
249
+ );
250
+ return null;
251
+ }
252
+ if (deletedSessionIDs.has(lookupSessionID) || getSessionGeneration(lookupSessionID) !== lookupGeneration) {
253
+ logDiag(
254
+ `lazy registration ignored session ${lookupSessionID}: session was deleted or superseded while lookup was pending`
255
+ );
256
+ return null;
257
+ }
258
+ const state = createGateSessionState(validated.sessionID, validated.directory);
259
+ sessions.set(state.sessionID, state);
260
+ logDiag(`lazily registered session ${state.sessionID} (${state.directory})`);
261
+ return state;
262
+ } catch (err) {
263
+ logDiag(`lazy registration lookup failed for ${sessionID}: ${describeSdkError(err)}`);
264
+ return null;
265
+ }
266
+ }
267
+ async function safeToast(client, message, variant = "info") {
268
+ try {
269
+ await client.tui.showToast({ body: { variant, message } });
270
+ } catch {
271
+ }
272
+ }
273
+ function clearParts(output) {
274
+ if (Array.isArray(output?.parts)) output.parts.length = 0;
275
+ }
276
+ var ABORT_COMMAND_TURN = true;
277
+ async function applyToggle(client, state, rawArgument) {
278
+ const normalized = rawArgument.trim().toLowerCase();
279
+ const arg = normalized || "on";
280
+ if (arg === "status") {
281
+ 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}`;
282
+ await safeToast(client, notice2);
283
+ return { notice: notice2, kind: "status" };
284
+ }
285
+ if (/^--only/i.test(rawArgument.trim())) {
286
+ const onlyMatch = /^--only(.*)$/i.exec(rawArgument.trim());
287
+ const remainder = onlyMatch?.[1] ?? "";
288
+ const command = /^\s/.test(remainder) ? remainder.trim() : "";
289
+ if (!command) {
290
+ const notice3 = 'Usage: /gate --only "command"';
291
+ await safeToast(client, notice3, "error");
292
+ return { notice: notice3, kind: "usage" };
293
+ }
294
+ state.extraCommand = command;
295
+ state.gateMode = "command-only";
296
+ state.gateEnabled = true;
297
+ state.retries = 0;
298
+ state.escalated = false;
299
+ state.lastOutcome = null;
300
+ const notice2 = `Completion gate armed (command-only): ${command}`;
301
+ await safeToast(client, notice2);
302
+ logDiag(`gate command-only custom command registered on ${state.sessionID}`);
303
+ return { notice: notice2, kind: "enabled" };
304
+ }
305
+ if (arg !== "on" && arg !== "off") {
306
+ state.extraCommand = rawArgument.trim();
307
+ state.gateMode = "combined";
308
+ state.gateEnabled = true;
309
+ state.retries = 0;
310
+ state.escalated = false;
311
+ state.lastOutcome = null;
312
+ const notice2 = `Completion gate armed (combined): ${state.extraCommand}`;
313
+ await safeToast(client, notice2);
314
+ logDiag(`gate custom command registered on ${state.sessionID}`);
315
+ return { notice: notice2, kind: "enabled" };
316
+ }
317
+ state.gateEnabled = arg === "on";
318
+ if (state.gateEnabled) {
319
+ state.retries = 0;
320
+ state.escalated = false;
321
+ state.lastOutcome = null;
322
+ }
323
+ const notice = `Completion gate ${state.gateEnabled ? "enabled" : "disabled"} for this session.`;
324
+ await safeToast(client, notice);
325
+ logDiag(`gate ${arg} on ${state.sessionID}`);
326
+ return { notice, kind: state.gateEnabled ? "enabled" : "disabled" };
327
+ }
328
+ async function warnIfNothingToRun(client, state) {
329
+ if (state.extraCommand) return;
330
+ if (loadGateConfig(state.directory)) return;
331
+ const msg = `Completion gate enabled but nothing to run: no .opencode/completion-gate.json found from ${state.directory}.`;
332
+ logDiag(`gate on ${state.sessionID}: ${msg}`);
333
+ await safeToast(client, msg, "error");
334
+ }
335
+ function kickGateTurnEnd(client, state, reason) {
336
+ if (state.deleted || !state.gateEnabled || state.busy) return;
337
+ if (process.env.OPENCODE_GATE_DISABLED === "1") return;
338
+ state.busy = true;
339
+ logDiag(`gate kick on ${state.sessionID} (${reason}) \u2014 evaluation starting`);
340
+ runGateTurnEnd(client, state).catch((err) => logDiag(`gate flow error: ${err?.message ?? err}`)).finally(() => {
341
+ state.busy = false;
342
+ });
343
+ }
344
+ function pickActivePrDetails(prListJson) {
345
+ let parsed;
346
+ try {
347
+ parsed = JSON.parse(prListJson);
348
+ } catch {
349
+ return { ok: false, reason: "unparsable", detail: "az repos pr list returned invalid JSON" };
350
+ }
351
+ if (!Array.isArray(parsed)) {
352
+ return { ok: false, reason: "unparsable", detail: "expected an array of PRs" };
353
+ }
354
+ if (parsed.length === 0) {
355
+ return { ok: false, reason: "none", detail: "no active PR found for this branch" };
356
+ }
357
+ const ids = parsed.map((p) => typeof p?.pullRequestId === "number" ? p.pullRequestId : p?.id).filter((n) => typeof n === "number");
358
+ if (ids.length !== parsed.length) {
359
+ return { ok: false, reason: "unparsable", detail: "PR entries missing numeric pullRequestId" };
360
+ }
361
+ if (ids.length > 1) {
362
+ return {
363
+ ok: false,
364
+ reason: "multiple",
365
+ detail: `multiple active PRs for this branch: ${ids.join(", ")}`
366
+ };
367
+ }
368
+ const projectName = typeof parsed[0]?.repository?.project?.name === "string" && parsed[0].repository.project.name.trim() ? parsed[0].repository.project.name : void 0;
369
+ return projectName ? { ok: true, prId: ids[0], projectName } : { ok: true, prId: ids[0] };
370
+ }
371
+ var GREEN_POLICY_STATUSES = /* @__PURE__ */ new Set(["approved", "succeeded", "notapplicable"]);
372
+ var IN_PROGRESS_POLICY_STATUSES = /* @__PURE__ */ new Set(["queued", "running"]);
373
+ var HUMAN_POLICY_RE = /minimum number of reviewers|required reviewers|comment requirements/i;
374
+ function isHumanReviewPolicy(e) {
375
+ return HUMAN_POLICY_RE.test(String(e?.configuration?.type?.displayName ?? ""));
376
+ }
377
+ function parseBuildId(value) {
378
+ const id = typeof value === "number" ? value : typeof value === "string" && value.trim() ? Number(value) : NaN;
379
+ return Number.isFinite(id) && id > 0 ? id : null;
380
+ }
381
+ function extractTerminalBuildFailures(policyListJson, opts = {}) {
382
+ let evals;
383
+ try {
384
+ evals = JSON.parse(policyListJson);
385
+ } catch {
386
+ return [];
387
+ }
388
+ if (!Array.isArray(evals)) return [];
389
+ return evals.filter((e) => e?.configuration?.isBlocking === true || e?.configuration?.isRequired === true).filter((e) => String(e?.configuration?.type?.displayName ?? "").toLowerCase() === "build").filter((e) => !(opts.ignoreHumanPolicies && isHumanReviewPolicy(e))).filter((e) => {
390
+ const status = String(e?.status ?? "").toLowerCase();
391
+ return !GREEN_POLICY_STATUSES.has(status) && !IN_PROGRESS_POLICY_STATUSES.has(status);
392
+ }).map((e) => {
393
+ const context = e.context;
394
+ const preview = context?.buildOutputPreview;
395
+ const failure = {
396
+ buildId: parseBuildId(context?.buildId),
397
+ status: String(e?.status ?? ""),
398
+ previewErrors: Array.isArray(preview?.errors) ? preview.errors.map((error) => error?.message).filter(
399
+ (message) => typeof message === "string" && message.trim() !== ""
400
+ ) : []
401
+ };
402
+ if (typeof context?.buildDefinitionName === "string")
403
+ failure.definitionName = context.buildDefinitionName;
404
+ if (typeof preview?.jobName === "string") failure.jobName = preview.jobName;
405
+ if (typeof preview?.taskName === "string") failure.taskName = preview.taskName;
406
+ return failure;
407
+ });
408
+ }
409
+ function formatBuildPreview(build) {
410
+ const lines = [
411
+ build.definitionName ? `Build definition: ${build.definitionName}` : "",
412
+ `Build policy status: ${build.status}`,
413
+ build.jobName ? `Job: ${build.jobName}` : "",
414
+ build.taskName ? `Task: ${build.taskName}` : ""
415
+ ];
416
+ if (build.previewErrors.length > 0) {
417
+ lines.push("Preview errors:");
418
+ for (const line of truncateTail(build.previewErrors.join("\n"), 20).split("\n"))
419
+ lines.push(line);
420
+ }
421
+ return lines.filter((l) => l.trim() !== "").join("\n");
422
+ }
423
+ function requiredPoliciesGreen(policyListJson, opts = {}) {
424
+ let evals;
425
+ try {
426
+ evals = JSON.parse(policyListJson);
427
+ } catch {
428
+ return {
429
+ green: false,
430
+ retryable: false,
431
+ detail: "az repos pr policy list returned invalid JSON"
432
+ };
433
+ }
434
+ if (!Array.isArray(evals))
435
+ return { green: false, retryable: false, detail: "expected an array of policy evaluations" };
436
+ const allRequired = evals.filter(
437
+ (e) => e?.configuration?.isBlocking === true || e?.configuration?.isRequired === true
438
+ );
439
+ if (allRequired.length === 0)
440
+ return { green: false, retryable: false, detail: "no blocking policies found on this PR" };
441
+ const ignored = opts.ignoreHumanPolicies ? allRequired.filter(isHumanReviewPolicy) : [];
442
+ const required = opts.ignoreHumanPolicies ? allRequired.filter((e) => !isHumanReviewPolicy(e)) : allRequired;
443
+ if (required.length === 0) {
444
+ const names = ignored.map((e) => e.configuration?.type?.displayName ?? "policy").join(", ");
445
+ return {
446
+ green: true,
447
+ retryable: false,
448
+ detail: `only human-review policies on this PR (${names}) \u2014 ignored via ignoreHumanPolicies`
449
+ };
450
+ }
451
+ const bad = required.filter(
452
+ (e) => !GREEN_POLICY_STATUSES.has(String(e.status ?? "").toLowerCase())
453
+ );
454
+ if (bad.length > 0) {
455
+ const names = bad.map((e) => `${e.configuration?.type?.displayName ?? "policy"}: ${String(e.status ?? "?")}`).join("; ");
456
+ const skipped = ignored.length > 0 ? ` (${ignored.length} human policy(ies) ignored)` : "";
457
+ const hasTerminalAutomatedFailure = bad.some(
458
+ (e) => !isHumanReviewPolicy(e) && !IN_PROGRESS_POLICY_STATUSES.has(String(e.status ?? "").toLowerCase())
459
+ );
460
+ return {
461
+ green: false,
462
+ retryable: !hasTerminalAutomatedFailure,
463
+ detail: `PR policies not green \u2014 ${names}${skipped}`
464
+ };
465
+ }
466
+ const greenDetail = `${required.length} required policy(ies) green`;
467
+ if (ignored.length > 0) {
468
+ const names = ignored.map((e) => e.configuration?.type?.displayName ?? "policy").join(", ");
469
+ return {
470
+ green: true,
471
+ retryable: false,
472
+ detail: `${greenDetail}, ${ignored.length} human policy(ies) ignored (${names})`
473
+ };
474
+ }
475
+ return { green: true, retryable: false, detail: greenDetail };
476
+ }
477
+ function quoteWin(s) {
478
+ return /[\s"^&|<>]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
479
+ }
480
+ function buildShellInvocation(args) {
481
+ if (process.platform !== "win32") return { file: args[0], args: args.slice(1) };
482
+ const cmdline = [args[0], ...args.slice(1)].map(quoteWin).join(" ");
483
+ return { file: process.env.ComSpec ?? "cmd.exe", args: ["/d", "/s", "/c", `"${cmdline}"`] };
484
+ }
485
+ var execShell = async (args, cwd, timeoutMs) => {
486
+ const inv = buildShellInvocation(args);
487
+ const r = await execFileOut(inv.file, inv.args, cwd, timeoutMs, {
488
+ windowsVerbatimArguments: true
489
+ });
490
+ if (r.timedOut) throw new Error(`${args[0]} timed out`);
491
+ if (r.code !== 0) {
492
+ const detail = truncateTail([r.stderr, r.stdout].filter((s) => s.trim()).join("\n"), 20);
493
+ throw new Error(`${args.join(" ")} failed (code ${r.code}):
494
+ ${detail}`);
495
+ }
496
+ return r.stdout;
497
+ };
498
+ var BUILD_LOG_TIMEOUT_MS = 12e4;
499
+ var defaultBuildLogExtractor = async (archivePath, destination, cwd, timeoutMs) => {
500
+ const r = await execFileOut("tar", ["-xf", archivePath, "-C", destination], cwd, timeoutMs);
501
+ if (r.timedOut) throw new Error(`tar timed out extracting ${archivePath}`);
502
+ if (r.code !== 0) {
503
+ const detail = truncateTail([r.stderr, r.stdout].filter((s) => s.trim()).join("\n"), 20);
504
+ throw new Error(`tar failed (code ${r.code}): ${brief(detail)}`);
505
+ }
506
+ };
507
+ async function downloadBuildLogs(projectName, buildId, cwd, options = {}) {
508
+ const timeoutMs = options.timeoutMs ?? BUILD_LOG_TIMEOUT_MS;
509
+ const shell = options.shell ?? execShell;
510
+ const extract = options.extract ?? defaultBuildLogExtractor;
511
+ if (options.isAborted?.()) throw new GateAborted();
512
+ const root = options.tempRoot ?? join(tmpdir(), "opencode");
513
+ try {
514
+ mkdirSync(root, { recursive: true });
515
+ } catch {
516
+ }
517
+ let workDir;
518
+ try {
519
+ workDir = mkdtempSync(join(root, `completion-gate-logs-${buildId}-`));
520
+ } catch (err) {
521
+ return {
522
+ buildId,
523
+ error: `could not create artifact directory under ${root}: ${err?.message ?? String(err)}`
524
+ };
525
+ }
526
+ const archivePath = join(workDir, `build-${buildId}-logs.zip`);
527
+ const destination = join(workDir, "extracted");
528
+ logDiag(`build-logs "${projectName}" #${buildId}: downloading to ${archivePath}`);
529
+ try {
530
+ await shell(
531
+ [
532
+ "az",
533
+ "devops",
534
+ "invoke",
535
+ "--detect",
536
+ "true",
537
+ "--area",
538
+ "build",
539
+ "--resource",
540
+ "logs",
541
+ "--route-parameters",
542
+ `project=${projectName}`,
543
+ `buildId=${buildId}`,
544
+ "--api-version",
545
+ "7.1",
546
+ "--http-method",
547
+ "GET",
548
+ "--accept-media-type",
549
+ "application/zip",
550
+ "--out-file",
551
+ archivePath
552
+ ],
553
+ cwd,
554
+ timeoutMs
555
+ );
556
+ } catch (err) {
557
+ logDiag(
558
+ `build-logs "${projectName}" #${buildId}: download failed \u2014 ${brief(String(err?.message ?? err))}`
559
+ );
560
+ return { buildId, error: `download failed: ${err?.message ?? String(err)}` };
561
+ }
562
+ if (!existsSync(archivePath)) {
563
+ logDiag(`build-logs "${projectName}" #${buildId}: az exited zero but wrote no archive file`);
564
+ return { buildId, error: "az devops invoke succeeded but produced no archive file" };
565
+ }
566
+ const result = { buildId, archivePath };
567
+ if (options.isAborted?.()) throw new GateAborted();
568
+ try {
569
+ mkdirSync(destination, { recursive: true });
570
+ await extract(archivePath, destination, cwd, timeoutMs);
571
+ result.extractedPath = destination;
572
+ logDiag(`build-logs "${projectName}" #${buildId}: extracted to ${destination}`);
573
+ } catch (err) {
574
+ result.error = `extraction failed: ${err?.message ?? String(err)}`;
575
+ logDiag(`build-logs "${projectName}" #${buildId}: extraction failed \u2014 ${brief(result.error)}`);
576
+ }
577
+ return result;
578
+ }
579
+ var defaultBuildLogArtifact = (projectName, buildId, cwd, isAborted) => downloadBuildLogs(projectName, buildId, cwd, { isAborted });
580
+ async function runAdoPrAssertion(a, cwd, shell, opts = {}) {
581
+ const sleep = opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
582
+ const now = opts.now ?? (() => Date.now());
583
+ const intervalMs = Math.max(5, a.pollIntervalSeconds) * 1e3;
584
+ const deadline = now() + Math.max(1, a.pollTimeoutMinutes) * 6e4;
585
+ let branch;
586
+ logDiag(`ado-pr "${a.name}": resolving current branch`);
587
+ try {
588
+ branch = (await shell(["git", "-C", cwd, "branch", "--show-current"], cwd, 1e4)).trim();
589
+ } catch (err) {
590
+ return fail(a.name, `could not resolve current branch: ${err?.message ?? String(err)}`);
591
+ }
592
+ if (!branch) return fail(a.name, "not on a branch (detached HEAD?) \u2014 nothing to check a PR for");
593
+ logDiag(
594
+ `ado-pr "${a.name}": branch="${branch}", polling every ${intervalMs / 1e3}s up to ${a.pollTimeoutMinutes} min`
595
+ );
596
+ let round = 0;
597
+ try {
598
+ for (; ; ) {
599
+ if (opts.isAborted?.()) throw new GateAborted();
600
+ round += 1;
601
+ const listJson = await shell(
602
+ [
603
+ "az",
604
+ "repos",
605
+ "pr",
606
+ "list",
607
+ "--source-branch",
608
+ branch,
609
+ "--status",
610
+ "active",
611
+ "--output",
612
+ "json"
613
+ ],
614
+ cwd,
615
+ 12e4
616
+ );
617
+ const pr = pickActivePrDetails(listJson);
618
+ if (!pr.ok) {
619
+ if (pr.reason === "none" && a.skipIfNoPr) {
620
+ logDiag(`ado-pr "${a.name}": no active PR \u2014 skipIfNoPr=true, passing`);
621
+ return pass(a.name);
622
+ }
623
+ return fail(
624
+ a.name,
625
+ pr.reason === "none" ? `no active PR for branch "${branch}" \u2014 open one before finishing` : pr.detail
626
+ );
627
+ }
628
+ logDiag(`ado-pr "${a.name}": round ${round} \u2014 active PR !${pr.prId}, checking policies`);
629
+ const policyJson = await shell(
630
+ ["az", "repos", "pr", "policy", "list", "--id", String(pr.prId), "--output", "json"],
631
+ cwd,
632
+ 12e4
633
+ );
634
+ const g = requiredPoliciesGreen(policyJson, {
635
+ ignoreHumanPolicies: a.ignoreHumanPolicies === true
636
+ });
637
+ if (g.green) {
638
+ logDiag(`ado-pr "${a.name}": PR !${pr.prId} green (${g.detail})`);
639
+ return pass(a.name);
640
+ }
641
+ if (!g.retryable) {
642
+ const baseEvidence = `PR !${pr.prId} has terminal policy failure \u2014 ${g.detail}`;
643
+ const buildFailures = extractTerminalBuildFailures(policyJson, {
644
+ ignoreHumanPolicies: a.ignoreHumanPolicies === true
645
+ });
646
+ const artifactEvidence = [];
647
+ const seenBuildIds = /* @__PURE__ */ new Set();
648
+ for (const build of buildFailures) {
649
+ if (build.buildId !== null) {
650
+ if (seenBuildIds.has(build.buildId)) continue;
651
+ seenBuildIds.add(build.buildId);
652
+ }
653
+ artifactEvidence.push(formatBuildPreview(build));
654
+ if (build.buildId === null) {
655
+ artifactEvidence.push(
656
+ "Build logs unavailable: terminal Build policy has no valid buildId."
657
+ );
658
+ continue;
659
+ }
660
+ if (!pr.projectName) {
661
+ artifactEvidence.push(
662
+ `Build logs unavailable for build ${build.buildId}: active PR payload has no repository project name.`
663
+ );
664
+ continue;
665
+ }
666
+ if (opts.isAborted?.()) throw new GateAborted();
667
+ try {
668
+ const artifact = await (opts.buildLogArtifact ?? defaultBuildLogArtifact)(
669
+ pr.projectName,
670
+ build.buildId,
671
+ cwd,
672
+ opts.isAborted
673
+ );
674
+ if (artifact.extractedPath)
675
+ artifactEvidence.push(`Build logs extracted directory: ${artifact.extractedPath}`);
676
+ if (artifact.archivePath)
677
+ artifactEvidence.push(`Build logs ZIP: ${artifact.archivePath}`);
678
+ if (artifact.error)
679
+ artifactEvidence.push(`Build log artifact error: ${artifact.error}`);
680
+ } catch (err) {
681
+ if (err instanceof GateAborted) throw err;
682
+ artifactEvidence.push(`Build log artifact error: ${err?.message ?? String(err)}`);
683
+ }
684
+ }
685
+ logDiag(
686
+ `ado-pr "${a.name}": PR !${pr.prId} has terminal policy failure \u2014 ${brief(g.detail)}; stopping polling`
687
+ );
688
+ return fail(a.name, [baseEvidence, ...artifactEvidence].filter(Boolean).join("\n"));
689
+ }
690
+ logDiag(`ado-pr "${a.name}": PR !${pr.prId} not green yet \u2014 ${brief(g.detail)}`);
691
+ if (now() + intervalMs >= deadline) {
692
+ return fail(
693
+ a.name,
694
+ `PR !${pr.prId} did not reach green within ${a.pollTimeoutMinutes} min \u2014 ${g.detail}`
695
+ );
696
+ }
697
+ if (opts.isAborted?.()) throw new GateAborted();
698
+ await sleep(intervalMs);
699
+ }
700
+ } catch (err) {
701
+ if (err instanceof GateAborted) throw err;
702
+ return fail(a.name, err?.message ?? String(err));
703
+ }
704
+ }
705
+ function parseVerdict(output) {
706
+ const matches = [...output.matchAll(/VERDICT:\s*\b(PASS|FAIL)\b/gi)];
707
+ const last = matches[matches.length - 1];
708
+ return last ? last[1].toUpperCase() : null;
709
+ }
710
+ function unwrapSdk(res) {
711
+ if (res && typeof res === "object" && ("data" in res || "error" in res)) {
712
+ const r = res;
713
+ if (r.error != null) {
714
+ const e = r.error;
715
+ throw new Error(typeof e === "string" ? e : e?.message ?? JSON.stringify(e));
716
+ }
717
+ return r.data;
718
+ }
719
+ return res;
720
+ }
721
+ function reviewerText(res) {
722
+ const parts = res?.parts;
723
+ if (!Array.isArray(parts)) return "";
724
+ return parts.filter((p) => p?.type === "text").map((p) => String(p.text ?? "")).join("\n");
725
+ }
726
+ function describeSdkError(err) {
727
+ if (err instanceof Error) return err.message;
728
+ if (typeof err === "string") return err;
729
+ try {
730
+ return JSON.stringify(err);
731
+ } catch {
732
+ return String(err);
733
+ }
734
+ }
735
+ async function runReviewAssertion(a, cwd, client, isAborted) {
736
+ if (isAborted?.()) throw new GateAborted();
737
+ if (!client?.session)
738
+ return fail(a.name, "no opencode SDK client available to run the reviewer session");
739
+ logDiag(`review "${a.name}": creating reviewer session in ${cwd}`);
740
+ const prompt = [
741
+ a.prompt ?? "Review the changes on this branch against the task requirements.",
742
+ 'Finish your reply with a final line containing exactly "VERDICT: PASS" or "VERDICT: FAIL" followed by a one-line justification.'
743
+ ].join("\n");
744
+ try {
745
+ const created = unwrapSdk(
746
+ await client.session.create({ query: { directory: cwd } })
747
+ );
748
+ const sessionId = created?.id;
749
+ if (!sessionId)
750
+ return fail(a.name, "could not create reviewer session (no session id in response)");
751
+ logDiag(
752
+ `review "${a.name}": reviewer session ${sessionId} \u2014 prompting agent "${a.agent}" (timeout=${a.timeoutSeconds}s)`
753
+ );
754
+ let timer;
755
+ try {
756
+ const raced = await Promise.race([
757
+ client.session.prompt({
758
+ path: { id: sessionId },
759
+ body: { agent: a.agent, parts: [{ type: "text", text: prompt }] }
760
+ }).then(
761
+ (r) => ({ ok: true, r }),
762
+ (err) => ({ ok: false, err })
763
+ ),
764
+ new Promise((resolve) => {
765
+ timer = setTimeout(() => resolve({ timedOut: true }), a.timeoutSeconds * 1e3);
766
+ })
767
+ ]);
768
+ if ("timedOut" in raced) {
769
+ logDiag(
770
+ `review "${a.name}": TIMED OUT after ${a.timeoutSeconds}s \u2014 aborting reviewer session`
771
+ );
772
+ try {
773
+ await Promise.resolve(client.session.abort?.({ path: { id: sessionId } }));
774
+ } catch {
775
+ }
776
+ return fail(
777
+ a.name,
778
+ `review timed out after ${a.timeoutSeconds}s (reviewer session aborted)`
779
+ );
780
+ }
781
+ if (!raced.ok) {
782
+ return fail(a.name, `reviewer session failed: ${describeSdkError(raced.err)}`);
783
+ }
784
+ const text = reviewerText(unwrapSdk(raced.r));
785
+ const verdict = parseVerdict(text);
786
+ logDiag(`review "${a.name}": verdict=${verdict ?? "none"}`);
787
+ const evidence = truncateTail(text);
788
+ if (verdict === "PASS") return pass(a.name);
789
+ if (verdict === "FAIL") return fail(a.name, `reviewer rejected:
790
+ ${evidence}`);
791
+ return fail(a.name, `reviewer produced no VERDICT line:
792
+ ${evidence}`);
793
+ } finally {
794
+ if (timer) clearTimeout(timer);
795
+ }
796
+ } catch (err) {
797
+ return fail(a.name, `reviewer session failed: ${describeSdkError(err)}`);
798
+ }
799
+ }
800
+ var GateAborted = class extends Error {
801
+ };
802
+ async function evaluateAssertions(assertions, projectRoot, client, isAborted, adoOpts) {
803
+ const results = [];
804
+ for (const a of assertions) {
805
+ if (isAborted?.()) return null;
806
+ let result;
807
+ logDiag(`evaluating assertion "${a.name}" (${a.type})`);
808
+ try {
809
+ if (a.type === "command") {
810
+ result = await runCommandAssertion(a, projectRoot, isAborted);
811
+ } else if (a.type === "ado-pr") {
812
+ result = await runAdoPrAssertion(a, projectRoot, execShell, { ...adoOpts, isAborted });
813
+ } else {
814
+ result = await runReviewAssertion(a, projectRoot, client, isAborted);
815
+ }
816
+ } catch (err) {
817
+ if (err instanceof GateAborted) {
818
+ logDiag(`assertion "${a.name}" aborted mid-run`);
819
+ return null;
820
+ }
821
+ result = fail(a.name, `gate could not run this assertion: ${err?.message ?? String(err)}`);
822
+ }
823
+ results.push(result);
824
+ if (!result.passed) {
825
+ logDiag(
826
+ `assertion "${a.name}" FAILED \u2014 ${brief(result.evidence)} (stopping here, remaining assertions skipped)`
827
+ );
828
+ break;
829
+ }
830
+ logDiag(`assertion "${a.name}" passed`);
831
+ }
832
+ return results;
833
+ }
834
+ function injectFailureText(state, outcome, maxRetries) {
835
+ return [
836
+ `${MARKER} \u2716 Completion gate failed \u2014 "${outcome.name}". Fix these issues, then finish again.`,
837
+ "",
838
+ "```",
839
+ outcome.evidence,
840
+ "```",
841
+ "",
842
+ `(RETRY ${state.retries}/${maxRetries})`
843
+ ].join("\n");
844
+ }
845
+ async function runGateTurnEnd(client, state) {
846
+ const isAborted = () => state.deleted || !state.gateEnabled || process.env.OPENCODE_GATE_DISABLED === "1";
847
+ if (state.lastOutcome === "pass") {
848
+ logDiag(`gate turn-end skipped on ${state.sessionID} \u2014 already green this streak`);
849
+ return;
850
+ }
851
+ const loaded = loadGateConfig(state.directory);
852
+ if (!loaded && !state.extraCommand) {
853
+ logDiag(
854
+ `gate turn-end on ${state.sessionID}: no .opencode/completion-gate.json found from ${state.directory} \u2014 nothing to run`
855
+ );
856
+ return;
857
+ }
858
+ const projectRoot = loaded?.projectRoot ?? state.directory;
859
+ const config = loaded?.config ?? { maxRetries: 3, assertions: [] };
860
+ const sessionAssertion = {
861
+ type: "command",
862
+ name: "session-command",
863
+ run: state.extraCommand ?? "",
864
+ timeoutSeconds: 300
865
+ };
866
+ const assertions = state.extraCommand ? state.gateMode === "command-only" ? [sessionAssertion] : [sessionAssertion, ...config.assertions] : config.assertions;
867
+ logDiag(
868
+ `gate turn-end on ${state.sessionID}: ${loaded ? `config ${loaded.path}` : "command-only without project config"} (${assertions.length} assertion(s), maxRetries=${config.maxRetries}, retries so far=${state.retries})`
869
+ );
870
+ const results = await evaluateAssertions(assertions, projectRoot, client, isAborted);
871
+ if (results === null) {
872
+ logDiag(
873
+ `gate turn-end ABORTED on ${state.sessionID} \u2014 gate was disabled mid-run, staying silent`
874
+ );
875
+ return;
876
+ }
877
+ const last = results[results.length - 1];
878
+ if (!last) return;
879
+ if (last.passed) {
880
+ logDiag(`gate PASSED on ${state.sessionID}: all ${results.length} assertion(s) green`);
881
+ if (isAborted()) {
882
+ logDiag(`gate turn-end ABORTED on ${state.sessionID} \u2014 gate disabled before success notice`);
883
+ return;
884
+ }
885
+ state.lastOutcome = "pass";
886
+ await client.session.promptAsync({
887
+ path: { id: state.sessionID },
888
+ body: {
889
+ parts: [
890
+ {
891
+ type: "text",
892
+ text: `${MARKER} \u2705 Completion gate passed (${results.map((r) => r.name).join(", ")}). You may report done.`
893
+ }
894
+ ]
895
+ }
896
+ }).catch((err) => logDiag(`success prompt error: ${err?.message ?? err}`));
897
+ return;
898
+ }
899
+ if (isAborted()) {
900
+ logDiag(`gate turn-end ABORTED on ${state.sessionID} \u2014 gate disabled before retry injection`);
901
+ return;
902
+ }
903
+ state.lastOutcome = "fail";
904
+ if (state.retries >= config.maxRetries) {
905
+ if (!state.escalated) {
906
+ state.escalated = true;
907
+ await client.tui.showToast({
908
+ body: {
909
+ variant: "error",
910
+ message: `\u2192 Completion gate "${last.name}" still failing after ${config.maxRetries} retries \u2014 manual attention needed`,
911
+ duration: 15e3
912
+ }
913
+ }).catch(() => {
914
+ });
915
+ logDiag(
916
+ `gate ESCALATED on ${state.sessionID}: "${last.name}" still failing after ${config.maxRetries} retries \u2014 manual attention needed`
917
+ );
918
+ }
919
+ return;
920
+ }
921
+ state.retries += 1;
922
+ logDiag(
923
+ `gate FAILED on ${state.sessionID}: "${last.name}" \u2014 retry ${state.retries}/${config.maxRetries}, injecting fix request`
924
+ );
925
+ await client.session.promptAsync({
926
+ path: { id: state.sessionID },
927
+ body: { parts: [{ type: "text", text: injectFailureText(state, last, config.maxRetries) }] }
928
+ }).catch((err) => logDiag(`retry prompt error: ${err?.message ?? err}`));
929
+ }
930
+ var plugin = async ({ client }) => {
931
+ return {
932
+ event: async ({ event }) => {
933
+ try {
934
+ if (event.type === "session.deleted") {
935
+ const info = event.properties?.info;
936
+ if (typeof info?.id === "string" && info.id.trim() !== "") {
937
+ const sessionID = info.id;
938
+ deletedSessionIDs.add(sessionID);
939
+ advanceSessionGeneration(sessionID);
940
+ const state = sessions.get(sessionID);
941
+ if (state) {
942
+ state.deleted = true;
943
+ state.gateEnabled = false;
944
+ }
945
+ sessions.delete(sessionID);
946
+ }
947
+ return;
948
+ }
949
+ if (event.type === "session.created") {
950
+ const info = event.properties.info;
951
+ const validated = validateTopLevelSessionMetadata(info);
952
+ if (!validated) {
953
+ logDiag("session.created ignored: invalid top-level session metadata");
954
+ return;
955
+ }
956
+ deletedSessionIDs.delete(validated.sessionID);
957
+ advanceSessionGeneration(validated.sessionID);
958
+ const created = createGateSessionState(validated.sessionID, validated.directory);
959
+ sessions.set(created.sessionID, created);
960
+ logDiag(`registered session ${created.sessionID} (${created.directory})`);
961
+ const bootstrap = readBootstrapGateCommand();
962
+ if (bootstrap) {
963
+ consumeBootstrapGateCommand();
964
+ created.extraCommand = bootstrap.command;
965
+ created.gateMode = bootstrap.mode;
966
+ created.gateEnabled = true;
967
+ created.retries = 0;
968
+ created.escalated = false;
969
+ created.lastOutcome = null;
970
+ logDiag(
971
+ `gate bootstrap ${bootstrap.mode} custom command registered on ${created.sessionID}`
972
+ );
973
+ await client.tui.showToast({
974
+ body: {
975
+ variant: "info",
976
+ message: `Completion gate armed (${bootstrap.mode}): ${bootstrap.command}`
977
+ }
978
+ }).catch(() => {
979
+ });
980
+ }
981
+ }
982
+ if (event.type === "session.status") {
983
+ const props = event.properties;
984
+ const state = sessions.get(props.sessionID);
985
+ if (!state || !state.gateEnabled || state.busy) return;
986
+ if (props.status?.type !== "idle") return;
987
+ if (process.env.OPENCODE_GATE_DISABLED === "1") return;
988
+ logDiag(`session ${props.sessionID} went idle \u2014 gate turn-end starting`);
989
+ kickGateTurnEnd(client, state, "idle");
990
+ return;
991
+ }
992
+ } catch (err) {
993
+ logDiag(`event error: ${err}`);
994
+ }
995
+ },
996
+ "command.execute.before": async ({ command, sessionID, arguments: commandArguments }, output) => {
997
+ let applied = null;
998
+ try {
999
+ if (command !== "gate") return;
1000
+ const state = await getOrRegisterSession(client, sessionID);
1001
+ if (!state || state.deleted) return;
1002
+ applied = await applyToggle(client, state, commandArguments);
1003
+ output.noReply = true;
1004
+ clearParts(output);
1005
+ if (applied.kind === "enabled") {
1006
+ await warnIfNothingToRun(client, state);
1007
+ kickGateTurnEnd(client, state, "enabled via /gate");
1008
+ }
1009
+ } catch (err) {
1010
+ logDiag(`command.execute.before error: ${err}`);
1011
+ }
1012
+ if (applied !== null && ABORT_COMMAND_TURN) {
1013
+ logDiag(`gate command handled on ${sessionID} \u2014 aborting turn (sentinel)`);
1014
+ throw new Error(applied.notice);
1015
+ }
1016
+ },
1017
+ "chat.message": async ({ sessionID }, output) => {
1018
+ try {
1019
+ const state = sessions.get(sessionID);
1020
+ if (!state || state.deleted) return;
1021
+ if (!Array.isArray(output?.parts) || output.parts.length === 0) return;
1022
+ const textPart = output.parts.find((p) => p?.type === "text");
1023
+ if (!textPart) return;
1024
+ const text = textPart?.text ?? "";
1025
+ if (text.trimStart().startsWith(INTERNAL_MARKER)) {
1026
+ const lines = text.split(/\r?\n/);
1027
+ const directive = lines.shift()?.trim() ?? "";
1028
+ const argument2 = directive.slice(INTERNAL_MARKER.length).trim();
1029
+ if (/^--only\s+/i.test(argument2)) {
1030
+ await applyToggle(client, state, argument2);
1031
+ const remainder = lines.join("\n").replace(/^\n+/, "");
1032
+ if (!remainder) clearParts(output);
1033
+ else textPart.text = remainder;
1034
+ }
1035
+ return;
1036
+ }
1037
+ if (!text.trimStart().startsWith(MARKER)) {
1038
+ state.retries = 0;
1039
+ state.escalated = false;
1040
+ state.lastOutcome = null;
1041
+ return;
1042
+ }
1043
+ const t = TOGGLE_RE.exec(text.trim());
1044
+ const argument = (t?.[1] ?? "").trim();
1045
+ if (!t || INJECTED_FAILURE_RE.test(argument) || INJECTED_SUCCESS_RE.test(argument)) return;
1046
+ const applied = await applyToggle(client, state, argument);
1047
+ if (applied.kind === "enabled") await warnIfNothingToRun(client, state);
1048
+ textPart.text = `${applied.notice} (Plugin-handled; acknowledge briefly, take no other action, call no tools.)`;
1049
+ } catch (err) {
1050
+ logDiag(`chat.message error: ${err}`);
1051
+ }
1052
+ }
1053
+ };
1054
+ };
1055
+ var core_default = plugin;
1056
+
1057
+ // src/plugin.ts
1058
+ var plugin_default = core_default;
1059
+ export {
1060
+ plugin_default as default
1061
+ };