opencode-completion-gate 1.1.1 → 1.3.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/CHANGELOG.md +14 -0
- package/dist/ado-pr.d.ts +34 -0
- package/dist/config.d.ts +35 -0
- package/dist/core.d.ts +12 -243
- package/dist/gate.d.ts +6 -0
- package/dist/index.js +176 -192
- package/dist/plugin.js +361 -358
- package/dist/process.d.ts +11 -0
- package/dist/review.d.ts +3 -0
- package/dist/types.d.ts +100 -0
- package/package.json +2 -2
package/dist/plugin.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
// src/
|
|
2
|
-
import {
|
|
3
|
-
import { join
|
|
4
|
-
import { homedir
|
|
1
|
+
// src/process.ts
|
|
2
|
+
import { appendFileSync } from "fs";
|
|
3
|
+
import { join } from "path";
|
|
4
|
+
import { homedir } from "os";
|
|
5
5
|
import { exec, execFile } from "child_process";
|
|
6
6
|
var BASE_DIR = join(homedir(), ".config", "opencode");
|
|
7
7
|
function logDiag(msg) {
|
|
@@ -21,6 +21,102 @@ function truncateTail(text, maxLines = 50) {
|
|
|
21
21
|
return `[... ${lines.length - maxLines} earlier lines omitted]
|
|
22
22
|
${lines.slice(-maxLines).join("\n")}`;
|
|
23
23
|
}
|
|
24
|
+
function outcomeFromErr(err) {
|
|
25
|
+
if (!err) return 0;
|
|
26
|
+
return typeof err.code === "number" ? err.code : null;
|
|
27
|
+
}
|
|
28
|
+
function runCommand(cmd, cwd, timeoutMs) {
|
|
29
|
+
return new Promise((resolve) => {
|
|
30
|
+
let childTimedOut = false;
|
|
31
|
+
const child = exec(
|
|
32
|
+
cmd,
|
|
33
|
+
{ cwd, windowsHide: true, maxBuffer: 16 * 1024 * 1024 },
|
|
34
|
+
(err, stdout, stderr) => {
|
|
35
|
+
clearTimeout(timer);
|
|
36
|
+
resolve({
|
|
37
|
+
code: outcomeFromErr(err),
|
|
38
|
+
timedOut: Boolean(err && err.killed) || childTimedOut,
|
|
39
|
+
stdout: stdout?.toString() ?? "",
|
|
40
|
+
stderr: stderr?.toString() ?? ""
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
);
|
|
44
|
+
const timer = setTimeout(() => {
|
|
45
|
+
childTimedOut = true;
|
|
46
|
+
try {
|
|
47
|
+
child.kill();
|
|
48
|
+
} catch {
|
|
49
|
+
}
|
|
50
|
+
if (process.platform === "win32" && child.pid) {
|
|
51
|
+
exec(`taskkill /PID ${child.pid} /T /F`, { windowsHide: true }, () => {
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
}, timeoutMs);
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
function execFileOut(file, args, cwd, timeoutMs, spawnOpts) {
|
|
58
|
+
return new Promise((resolve) => {
|
|
59
|
+
execFile(
|
|
60
|
+
file,
|
|
61
|
+
args,
|
|
62
|
+
{ cwd, windowsHide: true, timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024, ...spawnOpts },
|
|
63
|
+
(err, stdout, stderr) => {
|
|
64
|
+
resolve({
|
|
65
|
+
code: outcomeFromErr(err),
|
|
66
|
+
timedOut: Boolean(err && err.killed),
|
|
67
|
+
stdout: stdout?.toString() ?? "",
|
|
68
|
+
stderr: stderr?.toString() ?? ""
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
);
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
function quoteWin(s) {
|
|
75
|
+
return /[\s"^&|<>]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
|
|
76
|
+
}
|
|
77
|
+
function buildShellInvocation(args) {
|
|
78
|
+
if (process.platform !== "win32") return { file: args[0], args: args.slice(1) };
|
|
79
|
+
const cmdline = [args[0], ...args.slice(1)].map(quoteWin).join(" ");
|
|
80
|
+
return { file: process.env.ComSpec ?? "cmd.exe", args: ["/d", "/s", "/c", `"${cmdline}"`] };
|
|
81
|
+
}
|
|
82
|
+
var execShell = async (args, cwd, timeoutMs) => {
|
|
83
|
+
const inv = buildShellInvocation(args);
|
|
84
|
+
const r = await execFileOut(inv.file, inv.args, cwd, timeoutMs, {
|
|
85
|
+
windowsVerbatimArguments: true
|
|
86
|
+
});
|
|
87
|
+
if (r.timedOut) throw new Error(`${args[0]} timed out`);
|
|
88
|
+
if (r.code !== 0) {
|
|
89
|
+
const detail = truncateTail([r.stderr, r.stdout].filter((s) => s.trim()).join("\n"), 20);
|
|
90
|
+
throw new Error(`${args.join(" ")} failed (code ${r.code}):
|
|
91
|
+
${detail}`);
|
|
92
|
+
}
|
|
93
|
+
return r.stdout;
|
|
94
|
+
};
|
|
95
|
+
function describeSdkError(err) {
|
|
96
|
+
if (err instanceof Error) return err.message;
|
|
97
|
+
if (typeof err === "string") return err;
|
|
98
|
+
if (err && typeof err === "object" && "message" in err) {
|
|
99
|
+
const message = err.message;
|
|
100
|
+
if (typeof message === "string") return message;
|
|
101
|
+
}
|
|
102
|
+
try {
|
|
103
|
+
return JSON.stringify(err);
|
|
104
|
+
} catch {
|
|
105
|
+
return String(err);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// src/config.ts
|
|
110
|
+
import { readFileSync, existsSync } from "fs";
|
|
111
|
+
import { join as join2, dirname } from "path";
|
|
112
|
+
var GateAborted = class extends Error {
|
|
113
|
+
};
|
|
114
|
+
function pass(name) {
|
|
115
|
+
return { name, passed: true, evidence: "" };
|
|
116
|
+
}
|
|
117
|
+
function fail(name, evidence) {
|
|
118
|
+
return { name, passed: false, evidence: evidence.trim() };
|
|
119
|
+
}
|
|
24
120
|
function positiveInt(v, fallback) {
|
|
25
121
|
return typeof v === "number" && Number.isFinite(v) && v > 0 ? Math.floor(v) : fallback;
|
|
26
122
|
}
|
|
@@ -73,9 +169,9 @@ function findGateConfigPath(startDir) {
|
|
|
73
169
|
let dir = startDir;
|
|
74
170
|
for (; ; ) {
|
|
75
171
|
try {
|
|
76
|
-
const candidate =
|
|
172
|
+
const candidate = join2(dir, ".opencode", "completion-gate.json");
|
|
77
173
|
if (existsSync(candidate)) return candidate;
|
|
78
|
-
if (existsSync(
|
|
174
|
+
if (existsSync(join2(dir, ".git"))) return null;
|
|
79
175
|
const parent = dirname(dir);
|
|
80
176
|
if (parent === dir) return null;
|
|
81
177
|
dir = parent;
|
|
@@ -96,81 +192,6 @@ function loadGateConfig(startDir) {
|
|
|
96
192
|
if (!config) return null;
|
|
97
193
|
return { path, projectRoot: dirname(dirname(path)), config };
|
|
98
194
|
}
|
|
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
195
|
var BOOTSTRAP_COMMAND_ENV = "OPENCODE_GATE_BOOTSTRAP_COMMAND";
|
|
175
196
|
var BOOTSTRAP_COMMAND_B64_ENV = "OPENCODE_GATE_BOOTSTRAP_COMMAND_B64";
|
|
176
197
|
var BOOTSTRAP_MODE_ENV = "OPENCODE_GATE_BOOTSTRAP_MODE";
|
|
@@ -214,9 +235,6 @@ function consumeBootstrapGateCommand() {
|
|
|
214
235
|
delete process.env[BOOTSTRAP_MODE_ENV];
|
|
215
236
|
delete process.env[BOOTSTRAP_MAX_RETRIES_ENV];
|
|
216
237
|
}
|
|
217
|
-
var TOGGLE_RE = /^\[completion-gate\](?:\s+(.*?))?\s*$/i;
|
|
218
|
-
var INJECTED_FAILURE_RE = /^✖ Completion gate failed — "[^"]+"\. Fix these issues, then finish again\.\n\n```[\s\S]*\n```\n\n\(RETRY \d+\/\d+\)$/;
|
|
219
|
-
var INJECTED_SUCCESS_RE = /^✅ Completion gate passed \([^\n]*\)\. You may report done\.$/;
|
|
220
238
|
function parseOnlyCommand(remainder) {
|
|
221
239
|
if (!/^\s/.test(remainder)) return { command: "", invalidRetry: false };
|
|
222
240
|
let body = remainder.trim();
|
|
@@ -229,175 +247,38 @@ function parseOnlyCommand(remainder) {
|
|
|
229
247
|
if (parsed === null) invalid = true;
|
|
230
248
|
else leading = parsed;
|
|
231
249
|
body = body.slice(leadingMatch[0].length).trim();
|
|
232
|
-
} else if (/^--(?:retries|max-retries)(?:\s*=\s*)?$/i.test(body))
|
|
233
|
-
invalid = true;
|
|
234
|
-
}
|
|
250
|
+
} else if (/^--(?:retries|max-retries)(?:\s*=\s*)?$/i.test(body)) invalid = true;
|
|
235
251
|
const trailingMatch = /\s+--(?:retries|max-retries)(?:\s+|=)(\S+)\s*$/i.exec(body);
|
|
236
252
|
if (trailingMatch) {
|
|
237
253
|
const parsed = parsePositiveIntToken(trailingMatch[1]);
|
|
238
254
|
if (parsed === null) invalid = true;
|
|
239
255
|
else trailing = parsed;
|
|
240
|
-
body = body.slice(0, trailingMatch.index).trim();
|
|
241
|
-
} else if (/\s+--(?:retries|max-retries)(?:\s*=\s*)?$/i.test(body))
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
invalidRetry: invalid
|
|
249
|
-
};
|
|
250
|
-
}
|
|
251
|
-
function effectiveMaxRetries(state, configMaxRetries) {
|
|
252
|
-
if (state.gateMode === "command-only" && state.sessionMaxRetries !== null) {
|
|
253
|
-
return { value: state.sessionMaxRetries, source: "session" };
|
|
254
|
-
}
|
|
255
|
-
return { value: configMaxRetries, source: "config" };
|
|
256
|
-
}
|
|
257
|
-
var sessions = /* @__PURE__ */ new Map();
|
|
258
|
-
var deletedSessionIDs = /* @__PURE__ */ new Set();
|
|
259
|
-
var sessionGenerations = /* @__PURE__ */ new Map();
|
|
260
|
-
function getSessionGeneration(sessionID) {
|
|
261
|
-
return sessionGenerations.get(sessionID) ?? 0;
|
|
262
|
-
}
|
|
263
|
-
function advanceSessionGeneration(sessionID) {
|
|
264
|
-
sessionGenerations.set(sessionID, getSessionGeneration(sessionID) + 1);
|
|
265
|
-
}
|
|
266
|
-
function validateTopLevelSessionMetadata(info, expectedSessionID) {
|
|
267
|
-
if (!info || typeof info !== "object") return null;
|
|
268
|
-
const metadata = info;
|
|
269
|
-
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) {
|
|
270
|
-
return null;
|
|
271
|
-
}
|
|
272
|
-
return { sessionID: metadata.id, directory: metadata.directory };
|
|
273
|
-
}
|
|
274
|
-
function createGateSessionState(sessionID, directory) {
|
|
275
|
-
return {
|
|
276
|
-
sessionID,
|
|
277
|
-
directory,
|
|
278
|
-
gateEnabled: false,
|
|
279
|
-
gateMode: "combined",
|
|
280
|
-
sessionMaxRetries: null,
|
|
281
|
-
retries: 0,
|
|
282
|
-
lastOutcome: null,
|
|
283
|
-
escalated: false,
|
|
284
|
-
busy: false,
|
|
285
|
-
deleted: false
|
|
286
|
-
};
|
|
287
|
-
}
|
|
288
|
-
async function getOrRegisterSession(client, sessionID) {
|
|
289
|
-
const existing = sessions.get(sessionID);
|
|
290
|
-
if (existing) return existing.deleted ? null : existing;
|
|
291
|
-
const lookupSessionID = sessionID;
|
|
292
|
-
const lookupGeneration = getSessionGeneration(lookupSessionID);
|
|
293
|
-
try {
|
|
294
|
-
const info = unwrapSdk(
|
|
295
|
-
await client.session.get({ path: { id: lookupSessionID } })
|
|
296
|
-
);
|
|
297
|
-
const validated = validateTopLevelSessionMetadata(info, lookupSessionID);
|
|
298
|
-
if (!validated) {
|
|
299
|
-
logDiag(
|
|
300
|
-
`lazy registration rejected session ${lookupSessionID}: invalid top-level session metadata`
|
|
301
|
-
);
|
|
302
|
-
return null;
|
|
303
|
-
}
|
|
304
|
-
if (deletedSessionIDs.has(lookupSessionID) || getSessionGeneration(lookupSessionID) !== lookupGeneration) {
|
|
305
|
-
logDiag(
|
|
306
|
-
`lazy registration ignored session ${lookupSessionID}: session was deleted or superseded while lookup was pending`
|
|
307
|
-
);
|
|
308
|
-
return null;
|
|
309
|
-
}
|
|
310
|
-
const state = createGateSessionState(validated.sessionID, validated.directory);
|
|
311
|
-
sessions.set(state.sessionID, state);
|
|
312
|
-
logDiag(`lazily registered session ${state.sessionID} (${state.directory})`);
|
|
313
|
-
return state;
|
|
314
|
-
} catch (err) {
|
|
315
|
-
logDiag(`lazy registration lookup failed for ${sessionID}: ${describeSdkError(err)}`);
|
|
316
|
-
return null;
|
|
317
|
-
}
|
|
318
|
-
}
|
|
319
|
-
async function safeToast(client, message, variant = "info") {
|
|
320
|
-
try {
|
|
321
|
-
await client.tui.showToast({ body: { variant, message } });
|
|
322
|
-
} catch {
|
|
323
|
-
}
|
|
324
|
-
}
|
|
325
|
-
function clearParts(output) {
|
|
326
|
-
if (Array.isArray(output?.parts)) output.parts.length = 0;
|
|
327
|
-
}
|
|
328
|
-
var ABORT_COMMAND_TURN = true;
|
|
329
|
-
async function applyToggle(client, state, rawArgument) {
|
|
330
|
-
const normalized = rawArgument.trim().toLowerCase();
|
|
331
|
-
const arg = normalized || "on";
|
|
332
|
-
if (arg === "status") {
|
|
333
|
-
const loaded = loadGateConfig(state.directory);
|
|
334
|
-
const cap = state.gateMode === "command-only" && state.sessionMaxRetries !== null ? { value: state.sessionMaxRetries, source: "session" } : { value: loaded?.config.maxRetries ?? 3, source: "config" };
|
|
335
|
-
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})`;
|
|
336
|
-
await safeToast(client, notice2);
|
|
337
|
-
return { notice: notice2, kind: "status" };
|
|
338
|
-
}
|
|
339
|
-
if (/^--only/i.test(rawArgument.trim())) {
|
|
340
|
-
const onlyMatch = /^--only(.*)$/i.exec(rawArgument.trim());
|
|
341
|
-
const remainder = onlyMatch?.[1] ?? "";
|
|
342
|
-
const parsed = parseOnlyCommand(remainder);
|
|
343
|
-
if (!parsed.command || parsed.invalidRetry) {
|
|
344
|
-
const notice3 = 'Usage: /gate --only "command" [--retries N]';
|
|
345
|
-
await safeToast(client, notice3, "error");
|
|
346
|
-
return { notice: notice3, kind: "usage" };
|
|
347
|
-
}
|
|
348
|
-
state.extraCommand = parsed.command;
|
|
349
|
-
state.gateMode = "command-only";
|
|
350
|
-
state.sessionMaxRetries = parsed.maxRetries ?? null;
|
|
351
|
-
state.gateEnabled = true;
|
|
352
|
-
state.retries = 0;
|
|
353
|
-
state.escalated = false;
|
|
354
|
-
state.lastOutcome = null;
|
|
355
|
-
const notice2 = parsed.maxRetries !== void 0 ? `Completion gate armed (command-only): ${parsed.command} \xB7 maxRetries=${parsed.maxRetries}` : `Completion gate armed (command-only): ${parsed.command}`;
|
|
356
|
-
await safeToast(client, notice2);
|
|
357
|
-
logDiag(
|
|
358
|
-
`gate command-only custom command registered on ${state.sessionID}` + (parsed.maxRetries !== void 0 ? ` (session maxRetries=${parsed.maxRetries})` : "")
|
|
359
|
-
);
|
|
360
|
-
return { notice: notice2, kind: "enabled" };
|
|
361
|
-
}
|
|
362
|
-
if (arg !== "on" && arg !== "off") {
|
|
363
|
-
state.extraCommand = rawArgument.trim();
|
|
364
|
-
state.gateMode = "combined";
|
|
365
|
-
state.gateEnabled = true;
|
|
366
|
-
state.retries = 0;
|
|
367
|
-
state.escalated = false;
|
|
368
|
-
state.lastOutcome = null;
|
|
369
|
-
const notice2 = `Completion gate armed (combined): ${state.extraCommand}`;
|
|
370
|
-
await safeToast(client, notice2);
|
|
371
|
-
logDiag(`gate custom command registered on ${state.sessionID}`);
|
|
372
|
-
return { notice: notice2, kind: "enabled" };
|
|
373
|
-
}
|
|
374
|
-
state.gateEnabled = arg === "on";
|
|
375
|
-
if (state.gateEnabled) {
|
|
376
|
-
state.retries = 0;
|
|
377
|
-
state.escalated = false;
|
|
378
|
-
state.lastOutcome = null;
|
|
379
|
-
}
|
|
380
|
-
const notice = `Completion gate ${state.gateEnabled ? "enabled" : "disabled"} for this session.`;
|
|
381
|
-
await safeToast(client, notice);
|
|
382
|
-
logDiag(`gate ${arg} on ${state.sessionID}`);
|
|
383
|
-
return { notice, kind: state.gateEnabled ? "enabled" : "disabled" };
|
|
256
|
+
body = body.slice(0, trailingMatch.index).trim();
|
|
257
|
+
} else if (/\s+--(?:retries|max-retries)(?:\s*=\s*)?$/i.test(body)) invalid = true;
|
|
258
|
+
const maxRetries = leading ?? trailing ?? void 0;
|
|
259
|
+
return {
|
|
260
|
+
command: body,
|
|
261
|
+
...maxRetries !== void 0 ? { maxRetries } : {},
|
|
262
|
+
invalidRetry: invalid
|
|
263
|
+
};
|
|
384
264
|
}
|
|
385
|
-
|
|
386
|
-
if (state.
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
logDiag(`gate on ${state.sessionID}: ${msg}`);
|
|
390
|
-
await safeToast(client, msg, "error");
|
|
265
|
+
function effectiveMaxRetries(state, configMaxRetries) {
|
|
266
|
+
if (state.gateMode === "command-only" && state.sessionMaxRetries !== null)
|
|
267
|
+
return { value: state.sessionMaxRetries, source: "session" };
|
|
268
|
+
return { value: configMaxRetries, source: "config" };
|
|
391
269
|
}
|
|
392
|
-
function
|
|
393
|
-
if (
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
state.busy = false;
|
|
399
|
-
});
|
|
270
|
+
function validateTopLevelSessionMetadata(info, expectedSessionID) {
|
|
271
|
+
if (!info || typeof info !== "object") return null;
|
|
272
|
+
const metadata = info;
|
|
273
|
+
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)
|
|
274
|
+
return null;
|
|
275
|
+
return { sessionID: metadata.id, directory: metadata.directory };
|
|
400
276
|
}
|
|
277
|
+
|
|
278
|
+
// src/ado-pr.ts
|
|
279
|
+
import { existsSync as existsSync2, mkdirSync, mkdtempSync } from "fs";
|
|
280
|
+
import { join as join3 } from "path";
|
|
281
|
+
import { tmpdir } from "os";
|
|
401
282
|
function pickActivePrDetails(prListJson) {
|
|
402
283
|
let parsed;
|
|
403
284
|
try {
|
|
@@ -405,25 +286,25 @@ function pickActivePrDetails(prListJson) {
|
|
|
405
286
|
} catch {
|
|
406
287
|
return { ok: false, reason: "unparsable", detail: "az repos pr list returned invalid JSON" };
|
|
407
288
|
}
|
|
408
|
-
if (!Array.isArray(parsed))
|
|
289
|
+
if (!Array.isArray(parsed))
|
|
409
290
|
return { ok: false, reason: "unparsable", detail: "expected an array of PRs" };
|
|
410
|
-
|
|
411
|
-
if (parsed.length === 0) {
|
|
291
|
+
if (parsed.length === 0)
|
|
412
292
|
return { ok: false, reason: "none", detail: "no active PR found for this branch" };
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
293
|
+
const ids = parsed.map((p) => {
|
|
294
|
+
if (!p || typeof p !== "object") return void 0;
|
|
295
|
+
const entry = p;
|
|
296
|
+
return typeof entry.pullRequestId === "number" ? entry.pullRequestId : entry.id;
|
|
297
|
+
}).filter((n) => typeof n === "number");
|
|
298
|
+
if (ids.length !== parsed.length)
|
|
416
299
|
return { ok: false, reason: "unparsable", detail: "PR entries missing numeric pullRequestId" };
|
|
417
|
-
|
|
418
|
-
if (ids.length > 1) {
|
|
300
|
+
if (ids.length > 1)
|
|
419
301
|
return {
|
|
420
302
|
ok: false,
|
|
421
303
|
reason: "multiple",
|
|
422
304
|
detail: `multiple active PRs for this branch: ${ids.join(", ")}`
|
|
423
305
|
};
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
return projectName ? { ok: true, prId: ids[0], projectName } : { ok: true, prId: ids[0] };
|
|
306
|
+
const projectName = parsed[0].repository?.project?.name;
|
|
307
|
+
return typeof projectName === "string" && projectName.trim() ? { ok: true, prId: ids[0], projectName } : { ok: true, prId: ids[0] };
|
|
427
308
|
}
|
|
428
309
|
var GREEN_POLICY_STATUSES = /* @__PURE__ */ new Set(["approved", "succeeded", "notapplicable"]);
|
|
429
310
|
var IN_PROGRESS_POLICY_STATUSES = /* @__PURE__ */ new Set(["queued", "running"]);
|
|
@@ -531,57 +412,36 @@ function requiredPoliciesGreen(policyListJson, opts = {}) {
|
|
|
531
412
|
}
|
|
532
413
|
return { green: true, retryable: false, detail: greenDetail };
|
|
533
414
|
}
|
|
534
|
-
function quoteWin(s) {
|
|
535
|
-
return /[\s"^&|<>]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
|
|
536
|
-
}
|
|
537
|
-
function buildShellInvocation(args) {
|
|
538
|
-
if (process.platform !== "win32") return { file: args[0], args: args.slice(1) };
|
|
539
|
-
const cmdline = [args[0], ...args.slice(1)].map(quoteWin).join(" ");
|
|
540
|
-
return { file: process.env.ComSpec ?? "cmd.exe", args: ["/d", "/s", "/c", `"${cmdline}"`] };
|
|
541
|
-
}
|
|
542
|
-
var execShell = async (args, cwd, timeoutMs) => {
|
|
543
|
-
const inv = buildShellInvocation(args);
|
|
544
|
-
const r = await execFileOut(inv.file, inv.args, cwd, timeoutMs, {
|
|
545
|
-
windowsVerbatimArguments: true
|
|
546
|
-
});
|
|
547
|
-
if (r.timedOut) throw new Error(`${args[0]} timed out`);
|
|
548
|
-
if (r.code !== 0) {
|
|
549
|
-
const detail = truncateTail([r.stderr, r.stdout].filter((s) => s.trim()).join("\n"), 20);
|
|
550
|
-
throw new Error(`${args.join(" ")} failed (code ${r.code}):
|
|
551
|
-
${detail}`);
|
|
552
|
-
}
|
|
553
|
-
return r.stdout;
|
|
554
|
-
};
|
|
555
415
|
var BUILD_LOG_TIMEOUT_MS = 12e4;
|
|
556
416
|
var defaultBuildLogExtractor = async (archivePath, destination, cwd, timeoutMs) => {
|
|
557
417
|
const r = await execFileOut("tar", ["-xf", archivePath, "-C", destination], cwd, timeoutMs);
|
|
558
418
|
if (r.timedOut) throw new Error(`tar timed out extracting ${archivePath}`);
|
|
559
|
-
if (r.code !== 0)
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
419
|
+
if (r.code !== 0)
|
|
420
|
+
throw new Error(
|
|
421
|
+
`tar failed (code ${r.code}): ${brief(truncateTail([r.stderr, r.stdout].filter((s) => s.trim()).join("\n"), 20))}`
|
|
422
|
+
);
|
|
563
423
|
};
|
|
564
424
|
async function downloadBuildLogs(projectName, buildId, cwd, options = {}) {
|
|
565
425
|
const timeoutMs = options.timeoutMs ?? BUILD_LOG_TIMEOUT_MS;
|
|
566
426
|
const shell = options.shell ?? execShell;
|
|
567
427
|
const extract = options.extract ?? defaultBuildLogExtractor;
|
|
568
428
|
if (options.isAborted?.()) throw new GateAborted();
|
|
569
|
-
const root = options.tempRoot ??
|
|
429
|
+
const root = options.tempRoot ?? join3(tmpdir(), "opencode");
|
|
570
430
|
try {
|
|
571
431
|
mkdirSync(root, { recursive: true });
|
|
572
432
|
} catch {
|
|
573
433
|
}
|
|
574
434
|
let workDir;
|
|
575
435
|
try {
|
|
576
|
-
workDir = mkdtempSync(
|
|
436
|
+
workDir = mkdtempSync(join3(root, `completion-gate-logs-${buildId}-`));
|
|
577
437
|
} catch (err) {
|
|
578
438
|
return {
|
|
579
439
|
buildId,
|
|
580
|
-
error: `could not create artifact directory under ${root}: ${
|
|
440
|
+
error: `could not create artifact directory under ${root}: ${describeSdkError(err)}`
|
|
581
441
|
};
|
|
582
442
|
}
|
|
583
|
-
const archivePath =
|
|
584
|
-
const destination =
|
|
443
|
+
const archivePath = join3(workDir, `build-${buildId}-logs.zip`);
|
|
444
|
+
const destination = join3(workDir, "extracted");
|
|
585
445
|
logDiag(`build-logs "${projectName}" #${buildId}: downloading to ${archivePath}`);
|
|
586
446
|
try {
|
|
587
447
|
await shell(
|
|
@@ -612,24 +472,20 @@ async function downloadBuildLogs(projectName, buildId, cwd, options = {}) {
|
|
|
612
472
|
);
|
|
613
473
|
} catch (err) {
|
|
614
474
|
logDiag(
|
|
615
|
-
`build-logs "${projectName}" #${buildId}: download failed \u2014 ${brief(
|
|
475
|
+
`build-logs "${projectName}" #${buildId}: download failed \u2014 ${brief(describeSdkError(err))}`
|
|
616
476
|
);
|
|
617
|
-
return { buildId, error: `download failed: ${
|
|
477
|
+
return { buildId, error: `download failed: ${describeSdkError(err)}` };
|
|
618
478
|
}
|
|
619
|
-
if (!
|
|
620
|
-
logDiag(`build-logs "${projectName}" #${buildId}: az exited zero but wrote no archive file`);
|
|
479
|
+
if (!existsSync2(archivePath))
|
|
621
480
|
return { buildId, error: "az devops invoke succeeded but produced no archive file" };
|
|
622
|
-
}
|
|
623
481
|
const result = { buildId, archivePath };
|
|
624
482
|
if (options.isAborted?.()) throw new GateAborted();
|
|
625
483
|
try {
|
|
626
484
|
mkdirSync(destination, { recursive: true });
|
|
627
485
|
await extract(archivePath, destination, cwd, timeoutMs);
|
|
628
486
|
result.extractedPath = destination;
|
|
629
|
-
logDiag(`build-logs "${projectName}" #${buildId}: extracted to ${destination}`);
|
|
630
487
|
} catch (err) {
|
|
631
|
-
result.error = `extraction failed: ${
|
|
632
|
-
logDiag(`build-logs "${projectName}" #${buildId}: extraction failed \u2014 ${brief(result.error)}`);
|
|
488
|
+
result.error = `extraction failed: ${describeSdkError(err)}`;
|
|
633
489
|
}
|
|
634
490
|
return result;
|
|
635
491
|
}
|
|
@@ -640,21 +496,15 @@ async function runAdoPrAssertion(a, cwd, shell, opts = {}) {
|
|
|
640
496
|
const intervalMs = Math.max(5, a.pollIntervalSeconds) * 1e3;
|
|
641
497
|
const deadline = now() + Math.max(1, a.pollTimeoutMinutes) * 6e4;
|
|
642
498
|
let branch;
|
|
643
|
-
logDiag(`ado-pr "${a.name}": resolving current branch`);
|
|
644
499
|
try {
|
|
645
500
|
branch = (await shell(["git", "-C", cwd, "branch", "--show-current"], cwd, 1e4)).trim();
|
|
646
501
|
} catch (err) {
|
|
647
|
-
return fail(a.name, `could not resolve current branch: ${
|
|
502
|
+
return fail(a.name, `could not resolve current branch: ${describeSdkError(err)}`);
|
|
648
503
|
}
|
|
649
504
|
if (!branch) return fail(a.name, "not on a branch (detached HEAD?) \u2014 nothing to check a PR for");
|
|
650
|
-
logDiag(
|
|
651
|
-
`ado-pr "${a.name}": branch="${branch}", polling every ${intervalMs / 1e3}s up to ${a.pollTimeoutMinutes} min`
|
|
652
|
-
);
|
|
653
|
-
let round = 0;
|
|
654
505
|
try {
|
|
655
506
|
for (; ; ) {
|
|
656
507
|
if (opts.isAborted?.()) throw new GateAborted();
|
|
657
|
-
round += 1;
|
|
658
508
|
const listJson = await shell(
|
|
659
509
|
[
|
|
660
510
|
"az",
|
|
@@ -673,16 +523,12 @@ async function runAdoPrAssertion(a, cwd, shell, opts = {}) {
|
|
|
673
523
|
);
|
|
674
524
|
const pr = pickActivePrDetails(listJson);
|
|
675
525
|
if (!pr.ok) {
|
|
676
|
-
if (pr.reason === "none" && a.skipIfNoPr)
|
|
677
|
-
logDiag(`ado-pr "${a.name}": no active PR \u2014 skipIfNoPr=true, passing`);
|
|
678
|
-
return pass(a.name);
|
|
679
|
-
}
|
|
526
|
+
if (pr.reason === "none" && a.skipIfNoPr) return pass(a.name);
|
|
680
527
|
return fail(
|
|
681
528
|
a.name,
|
|
682
529
|
pr.reason === "none" ? `no active PR for branch "${branch}" \u2014 open one before finishing` : pr.detail
|
|
683
530
|
);
|
|
684
531
|
}
|
|
685
|
-
logDiag(`ado-pr "${a.name}": round ${round} \u2014 active PR !${pr.prId}, checking policies`);
|
|
686
532
|
const policyJson = await shell(
|
|
687
533
|
["az", "repos", "pr", "policy", "list", "--id", String(pr.prId), "--output", "json"],
|
|
688
534
|
cwd,
|
|
@@ -691,18 +537,13 @@ async function runAdoPrAssertion(a, cwd, shell, opts = {}) {
|
|
|
691
537
|
const g = requiredPoliciesGreen(policyJson, {
|
|
692
538
|
ignoreHumanPolicies: a.ignoreHumanPolicies === true
|
|
693
539
|
});
|
|
694
|
-
if (g.green)
|
|
695
|
-
logDiag(`ado-pr "${a.name}": PR !${pr.prId} green (${g.detail})`);
|
|
696
|
-
return pass(a.name);
|
|
697
|
-
}
|
|
540
|
+
if (g.green) return pass(a.name);
|
|
698
541
|
if (!g.retryable) {
|
|
699
|
-
const baseEvidence = `PR !${pr.prId} has terminal policy failure \u2014 ${g.detail}`;
|
|
700
|
-
const buildFailures = extractTerminalBuildFailures(policyJson, {
|
|
701
|
-
ignoreHumanPolicies: a.ignoreHumanPolicies === true
|
|
702
|
-
});
|
|
703
542
|
const artifactEvidence = [];
|
|
704
543
|
const seenBuildIds = /* @__PURE__ */ new Set();
|
|
705
|
-
for (const build of
|
|
544
|
+
for (const build of extractTerminalBuildFailures(policyJson, {
|
|
545
|
+
ignoreHumanPolicies: a.ignoreHumanPolicies === true
|
|
546
|
+
})) {
|
|
706
547
|
if (build.buildId !== null) {
|
|
707
548
|
if (seenBuildIds.has(build.buildId)) continue;
|
|
708
549
|
seenBuildIds.add(build.buildId);
|
|
@@ -736,29 +577,29 @@ async function runAdoPrAssertion(a, cwd, shell, opts = {}) {
|
|
|
736
577
|
artifactEvidence.push(`Build log artifact error: ${artifact.error}`);
|
|
737
578
|
} catch (err) {
|
|
738
579
|
if (err instanceof GateAborted) throw err;
|
|
739
|
-
artifactEvidence.push(`Build log artifact error: ${
|
|
580
|
+
artifactEvidence.push(`Build log artifact error: ${describeSdkError(err)}`);
|
|
740
581
|
}
|
|
741
582
|
}
|
|
742
|
-
|
|
743
|
-
|
|
583
|
+
return fail(
|
|
584
|
+
a.name,
|
|
585
|
+
[`PR !${pr.prId} has terminal policy failure \u2014 ${g.detail}`, ...artifactEvidence].filter(Boolean).join("\n")
|
|
744
586
|
);
|
|
745
|
-
return fail(a.name, [baseEvidence, ...artifactEvidence].filter(Boolean).join("\n"));
|
|
746
587
|
}
|
|
747
|
-
|
|
748
|
-
if (now() + intervalMs >= deadline) {
|
|
588
|
+
if (now() + intervalMs >= deadline)
|
|
749
589
|
return fail(
|
|
750
590
|
a.name,
|
|
751
591
|
`PR !${pr.prId} did not reach green within ${a.pollTimeoutMinutes} min \u2014 ${g.detail}`
|
|
752
592
|
);
|
|
753
|
-
}
|
|
754
593
|
if (opts.isAborted?.()) throw new GateAborted();
|
|
755
594
|
await sleep(intervalMs);
|
|
756
595
|
}
|
|
757
596
|
} catch (err) {
|
|
758
597
|
if (err instanceof GateAborted) throw err;
|
|
759
|
-
return fail(a.name,
|
|
598
|
+
return fail(a.name, describeSdkError(err));
|
|
760
599
|
}
|
|
761
600
|
}
|
|
601
|
+
|
|
602
|
+
// src/review.ts
|
|
762
603
|
function parseVerdict(output) {
|
|
763
604
|
const matches = [...output.matchAll(/VERDICT:\s*\b(PASS|FAIL)\b/gi)];
|
|
764
605
|
const last = matches[matches.length - 1];
|
|
@@ -767,10 +608,10 @@ function parseVerdict(output) {
|
|
|
767
608
|
function unwrapSdk(res) {
|
|
768
609
|
if (res && typeof res === "object" && ("data" in res || "error" in res)) {
|
|
769
610
|
const r = res;
|
|
770
|
-
if (r.error != null)
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
611
|
+
if (r.error != null)
|
|
612
|
+
throw new Error(
|
|
613
|
+
typeof r.error === "string" ? r.error : r.error && typeof r.error === "object" && "message" in r.error ? String(r.error.message) : JSON.stringify(r.error)
|
|
614
|
+
);
|
|
774
615
|
return r.data;
|
|
775
616
|
}
|
|
776
617
|
return res;
|
|
@@ -778,22 +619,14 @@ function unwrapSdk(res) {
|
|
|
778
619
|
function reviewerText(res) {
|
|
779
620
|
const parts = res?.parts;
|
|
780
621
|
if (!Array.isArray(parts)) return "";
|
|
781
|
-
return parts.filter(
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
if (err instanceof Error) return err.message;
|
|
785
|
-
if (typeof err === "string") return err;
|
|
786
|
-
try {
|
|
787
|
-
return JSON.stringify(err);
|
|
788
|
-
} catch {
|
|
789
|
-
return String(err);
|
|
790
|
-
}
|
|
622
|
+
return parts.filter(
|
|
623
|
+
(p) => !!p && typeof p === "object" && p.type === "text"
|
|
624
|
+
).map((p) => String(p.text ?? "")).join("\n");
|
|
791
625
|
}
|
|
792
626
|
async function runReviewAssertion(a, cwd, client, isAborted) {
|
|
793
627
|
if (isAborted?.()) throw new GateAborted();
|
|
794
628
|
if (!client?.session)
|
|
795
629
|
return fail(a.name, "no opencode SDK client available to run the reviewer session");
|
|
796
|
-
logDiag(`review "${a.name}": creating reviewer session in ${cwd}`);
|
|
797
630
|
const prompt = [
|
|
798
631
|
a.prompt ?? "Review the changes on this branch against the task requirements.",
|
|
799
632
|
'Finish your reply with a final line containing exactly "VERDICT: PASS" or "VERDICT: FAIL" followed by a one-line justification.'
|
|
@@ -805,9 +638,6 @@ async function runReviewAssertion(a, cwd, client, isAborted) {
|
|
|
805
638
|
const sessionId = created?.id;
|
|
806
639
|
if (!sessionId)
|
|
807
640
|
return fail(a.name, "could not create reviewer session (no session id in response)");
|
|
808
|
-
logDiag(
|
|
809
|
-
`review "${a.name}": reviewer session ${sessionId} \u2014 prompting agent "${a.agent}" (timeout=${a.timeoutSeconds}s)`
|
|
810
|
-
);
|
|
811
641
|
let timer;
|
|
812
642
|
try {
|
|
813
643
|
const raced = await Promise.race([
|
|
@@ -823,9 +653,6 @@ async function runReviewAssertion(a, cwd, client, isAborted) {
|
|
|
823
653
|
})
|
|
824
654
|
]);
|
|
825
655
|
if ("timedOut" in raced) {
|
|
826
|
-
logDiag(
|
|
827
|
-
`review "${a.name}": TIMED OUT after ${a.timeoutSeconds}s \u2014 aborting reviewer session`
|
|
828
|
-
);
|
|
829
656
|
try {
|
|
830
657
|
await Promise.resolve(client.session.abort?.({ path: { id: sessionId } }));
|
|
831
658
|
} catch {
|
|
@@ -835,9 +662,7 @@ async function runReviewAssertion(a, cwd, client, isAborted) {
|
|
|
835
662
|
`review timed out after ${a.timeoutSeconds}s (reviewer session aborted)`
|
|
836
663
|
);
|
|
837
664
|
}
|
|
838
|
-
if (!raced.ok) {
|
|
839
|
-
return fail(a.name, `reviewer session failed: ${describeSdkError(raced.err)}`);
|
|
840
|
-
}
|
|
665
|
+
if (!raced.ok) return fail(a.name, `reviewer session failed: ${describeSdkError(raced.err)}`);
|
|
841
666
|
const text = reviewerText(unwrapSdk(raced.r));
|
|
842
667
|
const verdict = parseVerdict(text);
|
|
843
668
|
logDiag(`review "${a.name}": verdict=${verdict ?? "none"}`);
|
|
@@ -854,8 +679,179 @@ ${evidence}`);
|
|
|
854
679
|
return fail(a.name, `reviewer session failed: ${describeSdkError(err)}`);
|
|
855
680
|
}
|
|
856
681
|
}
|
|
857
|
-
|
|
858
|
-
|
|
682
|
+
|
|
683
|
+
// src/gate.ts
|
|
684
|
+
var MARKER = "[completion-gate]";
|
|
685
|
+
var INTERNAL_MARKER = "[completion-gate-internal]";
|
|
686
|
+
var TOGGLE_RE = /^\[completion-gate\](?:\s+(.*?))?\s*$/i;
|
|
687
|
+
var INJECTED_FAILURE_RE = /^✖ Completion gate failed — "[^"]+"\. Fix these issues, then finish again\.\n\n```[\s\S]*\n```\n\n\(RETRY \d+\/\d+\)$/;
|
|
688
|
+
var INJECTED_SUCCESS_RE = /^✅ Completion gate passed \([^\n]*\)\. You may report done\.$/;
|
|
689
|
+
var sessions = /* @__PURE__ */ new Map();
|
|
690
|
+
var deletedSessionIDs = /* @__PURE__ */ new Set();
|
|
691
|
+
var sessionGenerations = /* @__PURE__ */ new Map();
|
|
692
|
+
function getSessionGeneration(sessionID) {
|
|
693
|
+
return sessionGenerations.get(sessionID) ?? 0;
|
|
694
|
+
}
|
|
695
|
+
function advanceSessionGeneration(sessionID) {
|
|
696
|
+
sessionGenerations.set(sessionID, getSessionGeneration(sessionID) + 1);
|
|
697
|
+
}
|
|
698
|
+
function createGateSessionState(sessionID, directory) {
|
|
699
|
+
return {
|
|
700
|
+
sessionID,
|
|
701
|
+
directory,
|
|
702
|
+
gateEnabled: false,
|
|
703
|
+
gateMode: "combined",
|
|
704
|
+
sessionMaxRetries: null,
|
|
705
|
+
retries: 0,
|
|
706
|
+
lastOutcome: null,
|
|
707
|
+
escalated: false,
|
|
708
|
+
busy: false,
|
|
709
|
+
deleted: false
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
async function getOrRegisterSession(client, sessionID) {
|
|
713
|
+
const existing = sessions.get(sessionID);
|
|
714
|
+
if (existing) return existing.deleted ? null : existing;
|
|
715
|
+
const lookupSessionID = sessionID;
|
|
716
|
+
const lookupGeneration = getSessionGeneration(lookupSessionID);
|
|
717
|
+
try {
|
|
718
|
+
const info = unwrapSdk2(
|
|
719
|
+
await client.session.get({ path: { id: lookupSessionID } })
|
|
720
|
+
);
|
|
721
|
+
const validated = validateTopLevelSessionMetadata(info, lookupSessionID);
|
|
722
|
+
if (!validated) {
|
|
723
|
+
logDiag(
|
|
724
|
+
`lazy registration rejected session ${lookupSessionID}: invalid top-level session metadata`
|
|
725
|
+
);
|
|
726
|
+
return null;
|
|
727
|
+
}
|
|
728
|
+
if (deletedSessionIDs.has(lookupSessionID) || getSessionGeneration(lookupSessionID) !== lookupGeneration) {
|
|
729
|
+
logDiag(
|
|
730
|
+
`lazy registration ignored session ${lookupSessionID}: session was deleted or superseded while lookup was pending`
|
|
731
|
+
);
|
|
732
|
+
return null;
|
|
733
|
+
}
|
|
734
|
+
const state = createGateSessionState(validated.sessionID, validated.directory);
|
|
735
|
+
sessions.set(state.sessionID, state);
|
|
736
|
+
logDiag(`lazily registered session ${state.sessionID} (${state.directory})`);
|
|
737
|
+
return state;
|
|
738
|
+
} catch (err) {
|
|
739
|
+
logDiag(`lazy registration lookup failed for ${sessionID}: ${describeSdkError(err)}`);
|
|
740
|
+
return null;
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
async function safeToast(client, message, variant = "info") {
|
|
744
|
+
try {
|
|
745
|
+
await client.tui.showToast({ body: { variant, message } });
|
|
746
|
+
} catch {
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
function clearParts(output) {
|
|
750
|
+
if (Array.isArray(output?.parts)) output.parts.length = 0;
|
|
751
|
+
}
|
|
752
|
+
var ABORT_COMMAND_TURN = true;
|
|
753
|
+
async function applyToggle(client, state, rawArgument) {
|
|
754
|
+
const normalized = rawArgument.trim().toLowerCase();
|
|
755
|
+
const arg = normalized || "on";
|
|
756
|
+
if (arg === "status") {
|
|
757
|
+
const loaded = loadGateConfig(state.directory);
|
|
758
|
+
const cap = state.gateMode === "command-only" && state.sessionMaxRetries !== null ? { value: state.sessionMaxRetries, source: "session" } : { value: loaded?.config.maxRetries ?? 3, source: "config" };
|
|
759
|
+
const notice2 = `Completion gate: ${state.gateEnabled ? "ENABLED" : "disabled"} \xB7 retries=${state.retries} \xB7 lastOutcome=${state.lastOutcome ?? "n/a"} \xB7 extraCommand=${state.extraCommand ? "configured" : "none"} \xB7 mode=${state.gateMode} \xB7 maxRetries=${cap.value} (${cap.source})`;
|
|
760
|
+
await safeToast(client, notice2);
|
|
761
|
+
return { notice: notice2, kind: "status" };
|
|
762
|
+
}
|
|
763
|
+
if (/^--only/i.test(rawArgument.trim())) {
|
|
764
|
+
const onlyMatch = /^--only(.*)$/i.exec(rawArgument.trim());
|
|
765
|
+
const remainder = onlyMatch?.[1] ?? "";
|
|
766
|
+
const parsed = parseOnlyCommand(remainder);
|
|
767
|
+
if (!parsed.command || parsed.invalidRetry) {
|
|
768
|
+
const notice3 = 'Usage: /gate --only "command" [--retries N]';
|
|
769
|
+
await safeToast(client, notice3, "error");
|
|
770
|
+
return { notice: notice3, kind: "usage" };
|
|
771
|
+
}
|
|
772
|
+
state.extraCommand = parsed.command;
|
|
773
|
+
state.gateMode = "command-only";
|
|
774
|
+
state.sessionMaxRetries = parsed.maxRetries ?? null;
|
|
775
|
+
state.gateEnabled = true;
|
|
776
|
+
state.retries = 0;
|
|
777
|
+
state.escalated = false;
|
|
778
|
+
state.lastOutcome = null;
|
|
779
|
+
const notice2 = parsed.maxRetries !== void 0 ? `Completion gate armed (command-only): ${parsed.command} \xB7 maxRetries=${parsed.maxRetries}` : `Completion gate armed (command-only): ${parsed.command}`;
|
|
780
|
+
await safeToast(client, notice2);
|
|
781
|
+
logDiag(
|
|
782
|
+
`gate command-only custom command registered on ${state.sessionID}` + (parsed.maxRetries !== void 0 ? ` (session maxRetries=${parsed.maxRetries})` : "")
|
|
783
|
+
);
|
|
784
|
+
return { notice: notice2, kind: "enabled" };
|
|
785
|
+
}
|
|
786
|
+
if (arg !== "on" && arg !== "off") {
|
|
787
|
+
state.extraCommand = rawArgument.trim();
|
|
788
|
+
state.gateMode = "combined";
|
|
789
|
+
state.gateEnabled = true;
|
|
790
|
+
state.retries = 0;
|
|
791
|
+
state.escalated = false;
|
|
792
|
+
state.lastOutcome = null;
|
|
793
|
+
const notice2 = `Completion gate armed (combined): ${state.extraCommand}`;
|
|
794
|
+
await safeToast(client, notice2);
|
|
795
|
+
logDiag(`gate custom command registered on ${state.sessionID}`);
|
|
796
|
+
return { notice: notice2, kind: "enabled" };
|
|
797
|
+
}
|
|
798
|
+
state.gateEnabled = arg === "on";
|
|
799
|
+
if (state.gateEnabled) {
|
|
800
|
+
state.retries = 0;
|
|
801
|
+
state.escalated = false;
|
|
802
|
+
state.lastOutcome = null;
|
|
803
|
+
}
|
|
804
|
+
const notice = `Completion gate ${state.gateEnabled ? "enabled" : "disabled"} for this session.`;
|
|
805
|
+
await safeToast(client, notice);
|
|
806
|
+
logDiag(`gate ${arg} on ${state.sessionID}`);
|
|
807
|
+
return { notice, kind: state.gateEnabled ? "enabled" : "disabled" };
|
|
808
|
+
}
|
|
809
|
+
async function warnIfNothingToRun(client, state) {
|
|
810
|
+
if (state.extraCommand) return;
|
|
811
|
+
if (loadGateConfig(state.directory)) return;
|
|
812
|
+
const msg = `Completion gate enabled but nothing to run: no .opencode/completion-gate.json found from ${state.directory}.`;
|
|
813
|
+
logDiag(`gate on ${state.sessionID}: ${msg}`);
|
|
814
|
+
await safeToast(client, msg, "error");
|
|
815
|
+
}
|
|
816
|
+
function kickGateTurnEnd(client, state, reason) {
|
|
817
|
+
if (state.deleted || !state.gateEnabled || state.busy) return;
|
|
818
|
+
if (process.env.OPENCODE_GATE_DISABLED === "1") return;
|
|
819
|
+
state.busy = true;
|
|
820
|
+
logDiag(`gate kick on ${state.sessionID} (${reason}) \u2014 evaluation starting`);
|
|
821
|
+
runGateTurnEnd(client, state).catch((err) => logDiag(`gate flow error: ${describeSdkError(err)}`)).finally(() => {
|
|
822
|
+
state.busy = false;
|
|
823
|
+
});
|
|
824
|
+
}
|
|
825
|
+
async function runCommandAssertion(a, cwd, isAborted) {
|
|
826
|
+
if (isAborted?.()) throw new GateAborted();
|
|
827
|
+
logDiag(
|
|
828
|
+
`command "${a.name}": running ${JSON.stringify(a.run)} (cwd=${cwd}, timeout=${a.timeoutSeconds}s)`
|
|
829
|
+
);
|
|
830
|
+
const r = await runCommand(a.run, cwd, a.timeoutSeconds * 1e3);
|
|
831
|
+
logDiag(
|
|
832
|
+
r.timedOut ? `command "${a.name}": TIMED OUT after ${a.timeoutSeconds}s` : `command "${a.name}": exit code ${r.code}`
|
|
833
|
+
);
|
|
834
|
+
if (!r.timedOut && r.code === 0) return { name: a.name, passed: true, evidence: "" };
|
|
835
|
+
const why = r.timedOut ? `command timed out after ${a.timeoutSeconds}s` : `exit code ${r.code}`;
|
|
836
|
+
return fail(
|
|
837
|
+
a.name,
|
|
838
|
+
`${why}
|
|
839
|
+
${truncateTail([r.stderr, r.stdout].filter((s) => s.trim()).join("\n---\n"))}`
|
|
840
|
+
);
|
|
841
|
+
}
|
|
842
|
+
function unwrapSdk2(res) {
|
|
843
|
+
if (res && typeof res === "object" && ("data" in res || "error" in res)) {
|
|
844
|
+
const r = res;
|
|
845
|
+
if (r.error != null) {
|
|
846
|
+
const e = r.error;
|
|
847
|
+
throw new Error(
|
|
848
|
+
typeof e === "string" ? e : e && typeof e === "object" && "message" in e ? String(e.message) : JSON.stringify(e)
|
|
849
|
+
);
|
|
850
|
+
}
|
|
851
|
+
return r.data;
|
|
852
|
+
}
|
|
853
|
+
return res;
|
|
854
|
+
}
|
|
859
855
|
async function evaluateAssertions(assertions, projectRoot, client, isAborted, adoOpts) {
|
|
860
856
|
const results = [];
|
|
861
857
|
for (const a of assertions) {
|
|
@@ -875,7 +871,7 @@ async function evaluateAssertions(assertions, projectRoot, client, isAborted, ad
|
|
|
875
871
|
logDiag(`assertion "${a.name}" aborted mid-run`);
|
|
876
872
|
return null;
|
|
877
873
|
}
|
|
878
|
-
result = fail(a.name, `gate could not run this assertion: ${
|
|
874
|
+
result = fail(a.name, `gate could not run this assertion: ${describeSdkError(err)}`);
|
|
879
875
|
}
|
|
880
876
|
results.push(result);
|
|
881
877
|
if (!result.passed) {
|
|
@@ -944,6 +940,7 @@ async function runGateTurnEnd(client, state) {
|
|
|
944
940
|
await client.session.promptAsync({
|
|
945
941
|
path: { id: state.sessionID },
|
|
946
942
|
body: {
|
|
943
|
+
...state.currentAgent ? { agent: state.currentAgent } : {},
|
|
947
944
|
parts: [
|
|
948
945
|
{
|
|
949
946
|
type: "text",
|
|
@@ -951,7 +948,7 @@ async function runGateTurnEnd(client, state) {
|
|
|
951
948
|
}
|
|
952
949
|
]
|
|
953
950
|
}
|
|
954
|
-
}).catch((err) => logDiag(`success prompt error: ${err
|
|
951
|
+
}).catch((err) => logDiag(`success prompt error: ${describeSdkError(err)}`));
|
|
955
952
|
return;
|
|
956
953
|
}
|
|
957
954
|
if (isAborted()) {
|
|
@@ -982,8 +979,11 @@ async function runGateTurnEnd(client, state) {
|
|
|
982
979
|
);
|
|
983
980
|
await client.session.promptAsync({
|
|
984
981
|
path: { id: state.sessionID },
|
|
985
|
-
body: {
|
|
986
|
-
|
|
982
|
+
body: {
|
|
983
|
+
...state.currentAgent ? { agent: state.currentAgent } : {},
|
|
984
|
+
parts: [{ type: "text", text: injectFailureText(state, last, cap.value) }]
|
|
985
|
+
}
|
|
986
|
+
}).catch((err) => logDiag(`retry prompt error: ${describeSdkError(err)}`));
|
|
987
987
|
}
|
|
988
988
|
var plugin = async ({ client }) => {
|
|
989
989
|
return {
|
|
@@ -991,8 +991,9 @@ var plugin = async ({ client }) => {
|
|
|
991
991
|
try {
|
|
992
992
|
if (event.type === "session.deleted") {
|
|
993
993
|
const info = event.properties?.info;
|
|
994
|
-
|
|
995
|
-
|
|
994
|
+
const deletedInfo = info && typeof info === "object" ? info : void 0;
|
|
995
|
+
if (typeof deletedInfo?.id === "string" && deletedInfo.id.trim() !== "") {
|
|
996
|
+
const sessionID = deletedInfo.id;
|
|
996
997
|
deletedSessionIDs.add(sessionID);
|
|
997
998
|
advanceSessionGeneration(sessionID);
|
|
998
999
|
const state = sessions.get(sessionID);
|
|
@@ -1040,6 +1041,7 @@ var plugin = async ({ client }) => {
|
|
|
1040
1041
|
}
|
|
1041
1042
|
if (event.type === "session.status") {
|
|
1042
1043
|
const props = event.properties;
|
|
1044
|
+
if (typeof props.sessionID !== "string") return;
|
|
1043
1045
|
const state = sessions.get(props.sessionID);
|
|
1044
1046
|
if (!state || !state.gateEnabled || state.busy) return;
|
|
1045
1047
|
if (props.status?.type !== "idle") return;
|
|
@@ -1073,10 +1075,11 @@ var plugin = async ({ client }) => {
|
|
|
1073
1075
|
throw new Error(applied.notice);
|
|
1074
1076
|
}
|
|
1075
1077
|
},
|
|
1076
|
-
"chat.message": async ({ sessionID }, output) => {
|
|
1078
|
+
"chat.message": async ({ sessionID, agent }, output) => {
|
|
1077
1079
|
try {
|
|
1078
1080
|
const state = sessions.get(sessionID);
|
|
1079
1081
|
if (!state || state.deleted) return;
|
|
1082
|
+
if (typeof agent === "string" && agent.trim() !== "") state.currentAgent = agent;
|
|
1080
1083
|
if (!Array.isArray(output?.parts) || output.parts.length === 0) return;
|
|
1081
1084
|
const textPart = output.parts.find((p) => p?.type === "text");
|
|
1082
1085
|
if (!textPart) return;
|
|
@@ -1111,10 +1114,10 @@ var plugin = async ({ client }) => {
|
|
|
1111
1114
|
}
|
|
1112
1115
|
};
|
|
1113
1116
|
};
|
|
1114
|
-
var
|
|
1117
|
+
var gate_default = plugin;
|
|
1115
1118
|
|
|
1116
1119
|
// src/plugin.ts
|
|
1117
|
-
var plugin_default =
|
|
1120
|
+
var plugin_default = gate_default;
|
|
1118
1121
|
export {
|
|
1119
1122
|
plugin_default as default
|
|
1120
1123
|
};
|