@hasna/hooks 0.12.9 → 0.12.14
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/README.md +69 -6
- package/bin/hooks/stop-review.js +1235 -0
- package/bin/hooks-mcp.js +298 -85
- package/bin/index.js +3309 -1086
- package/bin/native-readiness-entry.js +5 -1
- package/bin/native-safety-entry.js +27 -25
- package/bin/native-safety-worker.cjs +27 -25
- package/bin/serve.js +1362 -70
- package/dist/db/remote-storage.d.ts +7 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.js +1665 -257
- package/dist/lib/codex-safety-check.d.ts +1 -1
- package/dist/lib/hosted-registry.d.ts +70 -0
- package/dist/lib/legacy-registry-artifact.d.ts +23 -0
- package/dist/lib/manifest.d.ts +7 -0
- package/dist/lib/native-safety.d.ts +1 -0
- package/dist/lib/native-target.d.ts +7 -0
- package/dist/lib/opencode-stop-plugin.d.ts +55 -0
- package/dist/lib/registry-artifact.d.ts +36 -0
- package/dist/lib/registry.d.ts +4 -0
- package/dist/lib/stop-review-context.d.ts +12 -0
- package/dist/lib/store.d.ts +4 -0
- package/dist/lib/sumi-stop-plugin.d.ts +129 -0
- package/dist/lib/sync.d.ts +10 -0
- package/dist/lib/transport.d.ts +1 -1
- package/dist/native-readiness.d.ts +1 -1
- package/dist/native-readiness.js +5 -1
- package/dist/openapi.d.ts +160 -16
- package/dist/opencode-stop-plugin.js +384 -0
- package/dist/registry-auth.d.ts +5 -0
- package/dist/registry-http.d.ts +4 -0
- package/dist/sdk/generated.d.ts +32 -12
- package/dist/sdk/index.d.ts +28 -5
- package/dist/sdk/index.js +49 -24
- package/dist/sdk/registry-client.d.ts +1 -1
- package/dist/serve.d.ts +4 -4
- package/dist/storage.js +33 -2
- package/dist/sumi-stop-plugin.js +380 -0
- package/hooks/hook-scanoutput/src/hook.ts +33 -3
- package/hooks/hook-stop-review/README.md +109 -0
- package/hooks/hook-stop-review/manifest.json +10 -0
- package/hooks/hook-stop-review/package.json +11 -0
- package/hooks/hook-stop-review/src/hook.ts +59 -0
- package/hooks/hook-stop-review/src/index.ts +3 -0
- package/hooks/hook-stop-review/src/jev.ts +121 -0
- package/hooks/hook-stop-review/src/native.ts +246 -0
- package/hooks/hook-stop-review/src/policy.ts +145 -0
- package/hooks/hook-stop-review/src/runtime.ts +309 -0
- package/hooks/hook-stop-review/src/types.ts +121 -0
- package/hooks/hook-trash-guard/src/hook.ts +96 -0
- package/hooks/hook-workspace-repos-guard/src/hook.ts +231 -3
- package/hooks/local-executors.ts +841 -0
- package/package.json +22 -4
- package/scripts/build-bundled-hooks.ts +40 -0
- package/scripts/validate-bundled-hooks.ts +78 -0
- package/scripts/validate-opencode-stop-plugin.ts +42 -0
- package/scripts/validate-package.ts +9 -0
- package/scripts/validate-sumi-stop-plugin.ts +47 -0
|
@@ -0,0 +1,1235 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// @bun
|
|
3
|
+
|
|
4
|
+
// hooks/hook-stop-review/src/hook.ts
|
|
5
|
+
import { homedir as homedir2 } from "os";
|
|
6
|
+
import { join as join4 } from "path";
|
|
7
|
+
|
|
8
|
+
// hooks/hook-stop-review/src/native.ts
|
|
9
|
+
import { createHash } from "crypto";
|
|
10
|
+
import { constants, closeSync, fstatSync, openSync, readSync, realpathSync, statSync } from "fs";
|
|
11
|
+
import { isAbsolute, join } from "path";
|
|
12
|
+
var object = (x) => !!x && typeof x === "object" && !Array.isArray(x);
|
|
13
|
+
var id = (x) => typeof x === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(x);
|
|
14
|
+
var text = (x, max = Infinity) => typeof x === "string" && x.trim().length > 0 && Buffer.byteLength(x) <= max;
|
|
15
|
+
var digest = (x) => createHash("sha256").update(JSON.stringify(x)).digest("hex");
|
|
16
|
+
var unavailable = (reason) => ({ ok: false, reason });
|
|
17
|
+
function readNativeTranscript(path, windowBytes = 2000000) {
|
|
18
|
+
if (!isAbsolute(path) || !path.endsWith(".jsonl"))
|
|
19
|
+
throw new Error("unsupported_transcript_path");
|
|
20
|
+
if (!Number.isSafeInteger(windowBytes) || windowBytes < 1)
|
|
21
|
+
throw new Error("invalid_transcript_window");
|
|
22
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
23
|
+
try {
|
|
24
|
+
const before = fstatSync(fd);
|
|
25
|
+
if (!before.isFile() || before.uid !== process.getuid?.() || (before.mode & 18) !== 0 || before.size < 1)
|
|
26
|
+
throw new Error("unsafe_transcript");
|
|
27
|
+
const headerSize = Math.min(before.size, windowBytes);
|
|
28
|
+
const tailSize = Math.min(before.size, windowBytes);
|
|
29
|
+
const header = Buffer.alloc(headerSize), tail = Buffer.alloc(tailSize);
|
|
30
|
+
if (readSync(fd, header, 0, headerSize, 0) !== headerSize || readSync(fd, tail, 0, tailSize, before.size - tailSize) !== tailSize)
|
|
31
|
+
throw new Error("transcript_changed");
|
|
32
|
+
const after = fstatSync(fd);
|
|
33
|
+
if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ino !== after.ino)
|
|
34
|
+
throw new Error("transcript_changed");
|
|
35
|
+
if (tail.at(-1) !== 10)
|
|
36
|
+
throw new Error("incomplete_transcript");
|
|
37
|
+
const complete = tailSize === before.size;
|
|
38
|
+
const start = complete ? 0 : tail.indexOf(10) + 1;
|
|
39
|
+
if (!complete && start === 0)
|
|
40
|
+
return { header: header.toString("utf8"), tail: "", complete };
|
|
41
|
+
const tailText = new TextDecoder("utf-8", { fatal: true }).decode(tail.subarray(start));
|
|
42
|
+
return { header: header.toString("utf8"), tail: tailText, complete };
|
|
43
|
+
} finally {
|
|
44
|
+
closeSync(fd);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
function records(window) {
|
|
48
|
+
const lines = window.tail.trimEnd() ? window.tail.trimEnd().split(`
|
|
49
|
+
`) : [];
|
|
50
|
+
return lines.map((line) => {
|
|
51
|
+
const value = JSON.parse(line);
|
|
52
|
+
if (!object(value))
|
|
53
|
+
throw new Error("unsupported_transcript_format");
|
|
54
|
+
return value;
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
function parseCodexPrompt(window, sessionId, expectedTurn) {
|
|
58
|
+
const headerEnd = window.header.indexOf(`
|
|
59
|
+
`);
|
|
60
|
+
if (headerEnd < 0)
|
|
61
|
+
throw new Error("unsupported_transcript_header");
|
|
62
|
+
const header = JSON.parse(window.header.slice(0, headerEnd));
|
|
63
|
+
if (!object(header) || header.type !== "session_meta" || !object(header.payload) || header.payload.id !== sessionId || header.payload.parent_thread_id)
|
|
64
|
+
throw new Error("transcript_identity_mismatch");
|
|
65
|
+
let turn, prompt, promptIdentity, interrupted = false;
|
|
66
|
+
for (const row of records(window)) {
|
|
67
|
+
const payload = row.payload;
|
|
68
|
+
if (!object(payload))
|
|
69
|
+
continue;
|
|
70
|
+
if (row.type === "turn_context" && id(payload.turn_id)) {
|
|
71
|
+
turn = payload.turn_id;
|
|
72
|
+
}
|
|
73
|
+
if (row.type === "event_msg" && payload.type === "task_started" && id(payload.turn_id)) {
|
|
74
|
+
turn = payload.turn_id;
|
|
75
|
+
}
|
|
76
|
+
if (row.type === "event_msg" && payload.type === "user_message") {
|
|
77
|
+
if (!text(payload.message))
|
|
78
|
+
throw new Error("unsupported_user_prompt");
|
|
79
|
+
if (Array.isArray(payload.images) && payload.images.length || Array.isArray(payload.local_images) && payload.local_images.length)
|
|
80
|
+
throw new Error("unsupported_user_prompt");
|
|
81
|
+
prompt = payload.message;
|
|
82
|
+
promptIdentity = [row.ordinal, row.timestamp, payload.client_id, prompt];
|
|
83
|
+
interrupted = false;
|
|
84
|
+
}
|
|
85
|
+
if (row.type === "event_msg" && ["turn_aborted", "error"].includes(String(payload.type)))
|
|
86
|
+
interrupted = true;
|
|
87
|
+
}
|
|
88
|
+
if (turn !== expectedTurn || !prompt)
|
|
89
|
+
throw new Error("missing_current_user_prompt");
|
|
90
|
+
return { prompt, turnId: expectedTurn, revision: digest([sessionId, expectedTurn, promptIdentity]), interrupted };
|
|
91
|
+
}
|
|
92
|
+
function parseClaudePrompt(window, sessionId) {
|
|
93
|
+
const rows = records(window), byId = new Map;
|
|
94
|
+
let leaf;
|
|
95
|
+
for (const row of rows) {
|
|
96
|
+
if (!id(row.uuid))
|
|
97
|
+
continue;
|
|
98
|
+
if (row.sessionId !== sessionId)
|
|
99
|
+
throw new Error("transcript_identity_mismatch");
|
|
100
|
+
if (byId.has(row.uuid))
|
|
101
|
+
throw new Error("duplicate_transcript_uuid");
|
|
102
|
+
byId.set(row.uuid, row);
|
|
103
|
+
if (["user", "assistant"].includes(String(row.type)) && row.isSidechain !== true && !row.teamName && row.isMeta !== true)
|
|
104
|
+
leaf = row;
|
|
105
|
+
}
|
|
106
|
+
const visited = new Set;
|
|
107
|
+
while (leaf && id(leaf.uuid) && !visited.has(leaf.uuid)) {
|
|
108
|
+
visited.add(leaf.uuid);
|
|
109
|
+
if (leaf.type === "user" && leaf.isMeta !== true && leaf.isSidechain !== true && !leaf.teamName && leaf.isCompactSummary !== true && object(leaf.message)) {
|
|
110
|
+
const content = leaf.message.content;
|
|
111
|
+
let prompt;
|
|
112
|
+
if (typeof content === "string")
|
|
113
|
+
prompt = content;
|
|
114
|
+
else if (Array.isArray(content) && content.length && content.every((part) => object(part) && part.type === "text" && typeof part.text === "string"))
|
|
115
|
+
prompt = content.map((part) => part.text).join(`
|
|
116
|
+
`);
|
|
117
|
+
else if (!Array.isArray(content) || !content.every((part) => object(part) && part.type === "tool_result"))
|
|
118
|
+
throw new Error("unsupported_user_prompt");
|
|
119
|
+
if (prompt !== undefined) {
|
|
120
|
+
if (!text(prompt))
|
|
121
|
+
throw new Error("unsupported_user_prompt");
|
|
122
|
+
return { prompt, turnId: leaf.uuid, revision: digest([sessionId, leaf.uuid, prompt]), interrupted: /^\[Request interrupted by user/.test(prompt) };
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (leaf.parentUuid === null)
|
|
126
|
+
break;
|
|
127
|
+
if (!id(leaf.parentUuid))
|
|
128
|
+
throw new Error("unsupported_transcript_parent");
|
|
129
|
+
leaf = byId.get(leaf.parentUuid);
|
|
130
|
+
}
|
|
131
|
+
throw new Error("missing_current_user_prompt");
|
|
132
|
+
}
|
|
133
|
+
function requestsStop(prompt) {
|
|
134
|
+
return /^(?:\s*(?:please\s+)?(?:stop|pause|cancel|quit|exit|abort|hold\s+on|wait|don't\s+continue|do\s+not\s+continue|nu\s+continua|opre\u0219te|opreste)\b|\s*\/(?:stop|pause|cancel|exit|quit|clear|goal)\b)/i.test(prompt);
|
|
135
|
+
}
|
|
136
|
+
var nativeGoalRevision = Symbol("nativeGoalRevision");
|
|
137
|
+
function goalFreshness(goal) {
|
|
138
|
+
if (goal === undefined)
|
|
139
|
+
return { state: "unreadable" };
|
|
140
|
+
if (goal === null)
|
|
141
|
+
return { state: "absent" };
|
|
142
|
+
const revision = goal[nativeGoalRevision];
|
|
143
|
+
if (typeof revision !== "string")
|
|
144
|
+
throw new Error("native_goal_revision_unavailable");
|
|
145
|
+
return { state: "present", revision, id: goal.id, objective: goal.objective, status: goal.status };
|
|
146
|
+
}
|
|
147
|
+
async function prepareNativeStop(raw, options) {
|
|
148
|
+
if (!object(raw) || raw.hook_event_name !== "Stop" || !id(raw.session_id) || typeof raw.stop_hook_active !== "boolean" || !text(raw.last_assistant_message) || typeof raw.transcript_path !== "string")
|
|
149
|
+
return unavailable("invalid_native_input");
|
|
150
|
+
if (raw.stop_hook_active)
|
|
151
|
+
return unavailable("recursion_guard");
|
|
152
|
+
for (const key of ["background_tasks", "session_crons"]) {
|
|
153
|
+
if (raw[key] !== undefined && (!Array.isArray(raw[key]) || raw[key].length > 0))
|
|
154
|
+
return unavailable("native_background_work");
|
|
155
|
+
}
|
|
156
|
+
if (options.harness === "codex" && !id(raw.turn_id))
|
|
157
|
+
return unavailable("missing_native_turn");
|
|
158
|
+
const { session_id: sessionId, transcript_path: path, last_assistant_message: assistant } = raw;
|
|
159
|
+
const readPrompt = async () => {
|
|
160
|
+
let windowBytes = 2000000;
|
|
161
|
+
for (;; ) {
|
|
162
|
+
const window = options.readTranscript ? await options.readTranscript(path) : readNativeTranscript(path, windowBytes);
|
|
163
|
+
try {
|
|
164
|
+
return options.harness === "codex" ? parseCodexPrompt(window, sessionId, raw.turn_id) : parseClaudePrompt(window, sessionId);
|
|
165
|
+
} catch (error) {
|
|
166
|
+
if (options.readTranscript || window.complete || !(error instanceof Error) || !["missing_current_user_prompt", "unsupported_transcript_header", "unsupported_transcript_parent"].includes(error.message))
|
|
167
|
+
throw error;
|
|
168
|
+
windowBytes *= 2;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
const snapshot = async () => {
|
|
173
|
+
const prompt = await readPrompt();
|
|
174
|
+
const goal = options.harness === "codex" ? await options.readGoal?.(sessionId) : undefined;
|
|
175
|
+
return { prompt, goal, revision: digest([prompt.revision, options.harness === "codex" ? goalFreshness(goal) : "optional-goal-unavailable", assistant]) };
|
|
176
|
+
};
|
|
177
|
+
try {
|
|
178
|
+
const current = await snapshot();
|
|
179
|
+
if (current.prompt.interrupted || requestsStop(current.prompt.prompt))
|
|
180
|
+
return unavailable("user_stop");
|
|
181
|
+
const goal = current.goal;
|
|
182
|
+
const envelope = {
|
|
183
|
+
schema: "hooks.stop-review.v1",
|
|
184
|
+
sessionId,
|
|
185
|
+
turnId: current.prompt.turnId,
|
|
186
|
+
inputRevision: current.revision,
|
|
187
|
+
capturedAt: new Date((options.now ?? Date.now)()).toISOString(),
|
|
188
|
+
lastUserPrompt: current.prompt.prompt,
|
|
189
|
+
lastAssistantMessage: assistant,
|
|
190
|
+
goal,
|
|
191
|
+
...options.harness === "claude" ? { goalAvailability: "unavailable" } : {},
|
|
192
|
+
runtime: {
|
|
193
|
+
stopReason: "end_turn",
|
|
194
|
+
userRequestedStop: false,
|
|
195
|
+
terminal: goal?.status === "complete" || goal?.status === "cancelled",
|
|
196
|
+
paused: goal?.status === "paused",
|
|
197
|
+
budgetExhausted: goal?.status === "budget_limited",
|
|
198
|
+
usageLimited: goal?.status === "usage_limited",
|
|
199
|
+
awaitingApproval: false,
|
|
200
|
+
nativeContinuationAllowed: true,
|
|
201
|
+
stopHookActive: false,
|
|
202
|
+
continuationCount: 0
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
return { ok: true, envelope, isCurrent: async (candidate) => {
|
|
206
|
+
if (candidate.sessionId !== sessionId || candidate.turnId !== envelope.turnId || candidate.inputRevision !== envelope.inputRevision)
|
|
207
|
+
return false;
|
|
208
|
+
try {
|
|
209
|
+
const latest = await snapshot();
|
|
210
|
+
return (options.harness !== "codex" || latest.goal !== undefined) && latest.revision === envelope.inputRevision && !latest.prompt.interrupted && !requestsStop(latest.prompt.prompt);
|
|
211
|
+
} catch {
|
|
212
|
+
return false;
|
|
213
|
+
}
|
|
214
|
+
} };
|
|
215
|
+
} catch {
|
|
216
|
+
return unavailable("native_context_unavailable");
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
async function nativeStopOutput(result, prepared) {
|
|
220
|
+
if (result.admission !== undefined || result.action !== "continue" || result.sessionId !== prepared.envelope.sessionId || result.turnId !== prepared.envelope.turnId || result.inputRevision !== prepared.envelope.inputRevision || !text(result.continuationPrompt, 4096) || !await prepared.isCurrent(prepared.envelope))
|
|
221
|
+
return {};
|
|
222
|
+
return { decision: "block", reason: result.continuationPrompt };
|
|
223
|
+
}
|
|
224
|
+
function codexGoalFromResponse(value, sessionId) {
|
|
225
|
+
if (!object(value) || !("goal" in value))
|
|
226
|
+
return;
|
|
227
|
+
if (value.goal === null)
|
|
228
|
+
return null;
|
|
229
|
+
const goal = value.goal;
|
|
230
|
+
if (!object(goal) || goal.threadId !== sessionId || !text(goal.objective))
|
|
231
|
+
return;
|
|
232
|
+
const statuses = { active: "active", paused: "paused", blocked: "blocked", usageLimited: "usage_limited", budgetLimited: "budget_limited", complete: "complete" };
|
|
233
|
+
const status = statuses[String(goal.status)];
|
|
234
|
+
if (!status || typeof goal.tokensUsed !== "number" || !Number.isFinite(goal.tokensUsed) || goal.tokensUsed < 0 || !(goal.tokenBudget === null || Number.isSafeInteger(goal.tokenBudget) && goal.tokenBudget >= 0))
|
|
235
|
+
return;
|
|
236
|
+
if (!Number.isSafeInteger(goal.createdAt) || goal.createdAt < 0 || !Number.isSafeInteger(goal.updatedAt) || goal.updatedAt < goal.createdAt)
|
|
237
|
+
return;
|
|
238
|
+
const projected = { id: sessionId, objective: goal.objective, status: goal.tokenBudget !== null && goal.tokensUsed >= goal.tokenBudget ? "budget_limited" : status };
|
|
239
|
+
Object.defineProperty(projected, nativeGoalRevision, { value: digest([goal.createdAt, goal.updatedAt, goal.tokenBudget, goal.tokensUsed]), enumerable: false });
|
|
240
|
+
return projected;
|
|
241
|
+
}
|
|
242
|
+
async function readCodexGoal(sessionId, options) {
|
|
243
|
+
if (!id(sessionId) || !isAbsolute(options.codexHome))
|
|
244
|
+
return;
|
|
245
|
+
const path = options.socketPath ?? join(options.codexHome, "app-server-control", "app-server-control.sock");
|
|
246
|
+
try {
|
|
247
|
+
const physical = realpathSync(path), socket = statSync(physical);
|
|
248
|
+
if (!socket.isSocket() || socket.uid !== process.getuid?.() || (socket.mode & 63) !== 0)
|
|
249
|
+
return;
|
|
250
|
+
return await new Promise((resolve) => {
|
|
251
|
+
let done = false;
|
|
252
|
+
const ws = new WebSocket(`ws+unix://${physical}:/`);
|
|
253
|
+
const finish = (goal) => {
|
|
254
|
+
if (done)
|
|
255
|
+
return;
|
|
256
|
+
done = true;
|
|
257
|
+
clearTimeout(timer);
|
|
258
|
+
try {
|
|
259
|
+
ws.close();
|
|
260
|
+
} catch {}
|
|
261
|
+
resolve(goal);
|
|
262
|
+
};
|
|
263
|
+
const timer = setTimeout(() => finish(undefined), Math.min(options.timeoutMs ?? 350, 350));
|
|
264
|
+
ws.onopen = () => ws.send(JSON.stringify({ id: 1, method: "initialize", params: { clientInfo: { name: "hooks-stop-review", version: "1" }, capabilities: { experimentalApi: true } } }));
|
|
265
|
+
ws.onmessage = (event) => {
|
|
266
|
+
if (typeof event.data !== "string")
|
|
267
|
+
return finish(undefined);
|
|
268
|
+
try {
|
|
269
|
+
const reply = JSON.parse(event.data);
|
|
270
|
+
if (!object(reply))
|
|
271
|
+
return finish(undefined);
|
|
272
|
+
if (reply.id === 1) {
|
|
273
|
+
if (reply.error || !object(reply.result))
|
|
274
|
+
return finish(undefined);
|
|
275
|
+
ws.send(JSON.stringify({ method: "initialized" }));
|
|
276
|
+
ws.send(JSON.stringify({ id: 2, method: "thread/goal/get", params: { threadId: sessionId } }));
|
|
277
|
+
} else if (reply.id === 2)
|
|
278
|
+
finish(reply.error ? undefined : codexGoalFromResponse(reply.result, sessionId));
|
|
279
|
+
} catch {
|
|
280
|
+
finish(undefined);
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
ws.onerror = () => finish(undefined);
|
|
284
|
+
ws.onclose = () => finish(undefined);
|
|
285
|
+
});
|
|
286
|
+
} catch {
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
async function runNativeStop(raw, options, review) {
|
|
291
|
+
const prepared = await prepareNativeStop(raw, options);
|
|
292
|
+
if (!prepared.ok)
|
|
293
|
+
return { output: {}, reason: prepared.reason };
|
|
294
|
+
try {
|
|
295
|
+
const result = await review(prepared.envelope, prepared.isCurrent);
|
|
296
|
+
const output = await nativeStopOutput(result, prepared);
|
|
297
|
+
return { output, reason: result.action === "continue" && !output.decision ? "stale_input" : result.reason };
|
|
298
|
+
} catch {
|
|
299
|
+
return { output: {}, reason: "native_review_unavailable" };
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// hooks/hook-stop-review/src/runtime.ts
|
|
304
|
+
import { spawn } from "child_process";
|
|
305
|
+
import { createHash as createHash2 } from "crypto";
|
|
306
|
+
import { closeSync as closeSync2, constants as constants2, fstatSync as fstatSync2, fsyncSync, lstatSync, mkdirSync, openSync as openSync2, readFileSync, realpathSync as realpathSync2, writeFileSync } from "fs";
|
|
307
|
+
import { isAbsolute as isAbsolute2, join as join3 } from "path";
|
|
308
|
+
|
|
309
|
+
// src/lib/app-home.ts
|
|
310
|
+
import { existsSync } from "fs";
|
|
311
|
+
import { homedir } from "os";
|
|
312
|
+
import { join as join2, resolve } from "path";
|
|
313
|
+
import { homedir as pathsResolverHomedir } from "os";
|
|
314
|
+
import { join as pathsResolverJoin } from "path";
|
|
315
|
+
var PATHS_RESOLVER_KIND_ENV = {
|
|
316
|
+
config: "HASNA_CONFIG_HOME",
|
|
317
|
+
data: "HASNA_DATA_HOME",
|
|
318
|
+
state: "HASNA_STATE_HOME",
|
|
319
|
+
cache: "HASNA_CACHE_HOME"
|
|
320
|
+
};
|
|
321
|
+
var PATHS_RESOLVER_APP_SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
322
|
+
function pathsResolverAssertApp(app) {
|
|
323
|
+
if (typeof app !== "string" || app.length === 0) {
|
|
324
|
+
throw new TypeError("paths: app must be a non-empty string");
|
|
325
|
+
}
|
|
326
|
+
if (!PATHS_RESOLVER_APP_SLUG_RE.test(app)) {
|
|
327
|
+
throw new TypeError(`paths: invalid app slug "${app}" \u2014 expected lowercase kebab-case ([a-z0-9]+(-[a-z0-9]+)*)`);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
function pathsResolverAssertKind(kind) {
|
|
331
|
+
if (!Object.keys(PATHS_RESOLVER_KIND_ENV).includes(kind)) {
|
|
332
|
+
throw new TypeError(`paths: invalid path kind "${kind}" \u2014 expected one of ${Object.keys(PATHS_RESOLVER_KIND_ENV).join(", ")}`);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
function pathsResolverBaseDir(kind, options) {
|
|
336
|
+
pathsResolverAssertKind(kind);
|
|
337
|
+
const env = options.env ?? process.env;
|
|
338
|
+
const override = env[PATHS_RESOLVER_KIND_ENV[kind]];
|
|
339
|
+
if (typeof override === "string" && override.length > 0)
|
|
340
|
+
return override;
|
|
341
|
+
const home = options.home ?? pathsResolverHomedir();
|
|
342
|
+
const platform = options.platform ?? process.platform;
|
|
343
|
+
if (platform === "darwin") {
|
|
344
|
+
switch (kind) {
|
|
345
|
+
case "config":
|
|
346
|
+
case "data":
|
|
347
|
+
return pathsResolverJoin(home, "Library", "Application Support", "Hasna");
|
|
348
|
+
case "cache":
|
|
349
|
+
return pathsResolverJoin(home, "Library", "Caches", "Hasna");
|
|
350
|
+
case "state":
|
|
351
|
+
return pathsResolverJoin(home, "Library", "Logs", "Hasna");
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
switch (kind) {
|
|
355
|
+
case "config":
|
|
356
|
+
return pathsResolverJoin(home, ".config", "hasna");
|
|
357
|
+
case "data":
|
|
358
|
+
return pathsResolverJoin(home, ".local", "share", "hasna");
|
|
359
|
+
case "state":
|
|
360
|
+
return pathsResolverJoin(home, ".local", "state", "hasna");
|
|
361
|
+
case "cache":
|
|
362
|
+
return pathsResolverJoin(home, ".cache", "hasna");
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
function pathsResolverResolve(kind, options) {
|
|
366
|
+
pathsResolverAssertApp(options.app);
|
|
367
|
+
const appSegment = options.internal === true ? pathsResolverJoin("internal", options.app) : options.app;
|
|
368
|
+
return pathsResolverJoin(pathsResolverBaseDir(kind, options), appSegment);
|
|
369
|
+
}
|
|
370
|
+
function dataDir(options) {
|
|
371
|
+
return pathsResolverResolve("data", options);
|
|
372
|
+
}
|
|
373
|
+
var STORE_MARKER = "hooks.db";
|
|
374
|
+
function getHomeDir(env = process.env) {
|
|
375
|
+
return env.HOME || env.USERPROFILE || homedir();
|
|
376
|
+
}
|
|
377
|
+
function getResolverDataRoot(env = process.env) {
|
|
378
|
+
return dataDir({ app: "hooks", home: getHomeDir(env), env });
|
|
379
|
+
}
|
|
380
|
+
function getLegacyDataRoot(env = process.env) {
|
|
381
|
+
return join2(getHomeDir(env), ".hasna", "hooks");
|
|
382
|
+
}
|
|
383
|
+
function adoptResolverDataRoot(resolved, env = process.env) {
|
|
384
|
+
const dataOverride = env.HASNA_DATA_HOME;
|
|
385
|
+
if (typeof dataOverride === "string" && dataOverride.trim().length > 0)
|
|
386
|
+
return true;
|
|
387
|
+
return existsSync(join2(resolved, STORE_MARKER));
|
|
388
|
+
}
|
|
389
|
+
function getExplicitDataDir(env = process.env) {
|
|
390
|
+
const dir = env.HASNA_HOOKS_DATA_DIR ?? env.HOOKS_DATA_DIR;
|
|
391
|
+
if (typeof dir === "string" && dir.trim().length > 0)
|
|
392
|
+
return dir.trim();
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
function getExactDataRoot(env = process.env) {
|
|
396
|
+
const dir = env.HASNA_HOOKS_HOME?.trim() || env.HOOKS_HOME?.trim();
|
|
397
|
+
if (dir)
|
|
398
|
+
return resolve(dir);
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
401
|
+
function getEffectiveDataRoot(env = process.env) {
|
|
402
|
+
const explicit = getExplicitDataDir(env);
|
|
403
|
+
if (explicit)
|
|
404
|
+
return explicit;
|
|
405
|
+
const exact = getExactDataRoot(env);
|
|
406
|
+
if (exact)
|
|
407
|
+
return exact;
|
|
408
|
+
const resolved = getResolverDataRoot(env);
|
|
409
|
+
return adoptResolverDataRoot(resolved, env) ? resolve(resolved) : getLegacyDataRoot(env);
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
// src/lib/stop-review-context.ts
|
|
413
|
+
var APPS = ["hooks", "instructions", "secrets"];
|
|
414
|
+
var REFUSED = "HOOKS_CLIENT_CONTEXT_REFUSED";
|
|
415
|
+
var LOCAL_FLAGS = [
|
|
416
|
+
["HASNA_INSTRUCTIONS_LOCAL", "HOOKS_CLIENT_INSTRUCTIONS_LOCAL", "INSTRUCTIONS_LOCAL"],
|
|
417
|
+
["HASNA_CONFIGS_LOCAL", "HOOKS_CLIENT_CONFIGS_LOCAL", "CONFIGS_LOCAL"],
|
|
418
|
+
["HASNA_SECRETS_LOCAL", "HOOKS_CLIENT_SECRETS_LOCAL", "SECRETS_LOCAL"]
|
|
419
|
+
];
|
|
420
|
+
var HOOK_CLIENT_CONFIG_PROJECTIONS = [
|
|
421
|
+
["HASNA_HOME", "HOOKS_CLIENT_HOME"],
|
|
422
|
+
["HASNA_CONFIG_HOME", "HOOKS_CLIENT_CONFIG_HOME"],
|
|
423
|
+
["HASNA_PROFILE", "HOOKS_CLIENT_PROFILE"],
|
|
424
|
+
["HASNA_STATION", "HOOKS_CLIENT_STATION"],
|
|
425
|
+
...APPS.map((app) => [`HASNA_${app.toUpperCase()}_API_KEY_REF`, `HOOKS_CLIENT_${app.toUpperCase()}_API_KEY_REF`]),
|
|
426
|
+
...LOCAL_FLAGS.map(([name, alias]) => [name, alias])
|
|
427
|
+
];
|
|
428
|
+
var AUTHORITY_PROJECTIONS = APPS.map((app) => ({
|
|
429
|
+
app,
|
|
430
|
+
name: `HASNA_${app.toUpperCase()}_API_URL`,
|
|
431
|
+
legacy: `${app.toUpperCase()}_API_URL`,
|
|
432
|
+
alias: `HOOKS_CLIENT_${app.toUpperCase()}_AUTHORITY`
|
|
433
|
+
}));
|
|
434
|
+
function isCanonicalAuthority(value, app) {
|
|
435
|
+
if (/[\u0000-\u001f\u007f]/.test(value))
|
|
436
|
+
return false;
|
|
437
|
+
const trimmed = value.trim();
|
|
438
|
+
return ["", ":443"].some((port) => ["", "/", "/v1", "/v1/"].some((suffix) => trimmed === `https://api.hasna.com${port}/${app}${suffix}`));
|
|
439
|
+
}
|
|
440
|
+
function projectStopReviewClientContext(source, extra = {}) {
|
|
441
|
+
const out = {};
|
|
442
|
+
const values = (names) => names.flatMap((name) => [source[name], extra[name]]).filter((value) => value !== undefined);
|
|
443
|
+
let refused = values([REFUSED]).some((value) => value.trim() === "1");
|
|
444
|
+
for (const [name, alias] of HOOK_CLIENT_CONFIG_PROJECTIONS) {
|
|
445
|
+
const value = source[name] ?? extra[name] ?? extra[alias] ?? source[alias];
|
|
446
|
+
if (value !== undefined)
|
|
447
|
+
out[alias] = value;
|
|
448
|
+
}
|
|
449
|
+
for (const names of LOCAL_FLAGS) {
|
|
450
|
+
if (values(names).some((value) => value.trim() === "1")) {
|
|
451
|
+
out[names[1]] = "1";
|
|
452
|
+
refused = true;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
if (values(["HASNA_HOOKS_LOCAL", "HOOKS_LOCAL"]).some((value) => value.trim() !== ""))
|
|
456
|
+
refused = true;
|
|
457
|
+
if (values(["HASNA_SECRETS_LOCAL_VAULT", "HASNA_SECRETS_DB_PATH", "OPEN_SECRETS_DB"]).some((value) => value !== ""))
|
|
458
|
+
refused = true;
|
|
459
|
+
for (const { app, name, legacy, alias } of AUTHORITY_PROJECTIONS) {
|
|
460
|
+
const declared = values([name, legacy, alias]);
|
|
461
|
+
if (declared.some((value) => !isCanonicalAuthority(value, app)))
|
|
462
|
+
refused = true;
|
|
463
|
+
else if (declared.length)
|
|
464
|
+
out[alias] = `https://api.hasna.com/${app}`;
|
|
465
|
+
const prefix = app.toUpperCase();
|
|
466
|
+
if (values([`HASNA_${prefix}_API_KEY_OVERRIDE`]).length)
|
|
467
|
+
refused = true;
|
|
468
|
+
const deliberate = out[`HOOKS_CLIENT_${prefix}_API_KEY_REF`]?.trim() || out.HOOKS_CLIENT_PROFILE?.trim();
|
|
469
|
+
if (!deliberate && values([`HASNA_${prefix}_API_KEY`, `${prefix}_API_KEY`]).length)
|
|
470
|
+
refused = true;
|
|
471
|
+
}
|
|
472
|
+
if (refused)
|
|
473
|
+
out[REFUSED] = "1";
|
|
474
|
+
return out;
|
|
475
|
+
}
|
|
476
|
+
function stopReviewClientContextRefused(source) {
|
|
477
|
+
return projectStopReviewClientContext(source)[REFUSED] === "1";
|
|
478
|
+
}
|
|
479
|
+
function restoreStopReviewClientContext(source) {
|
|
480
|
+
const projected = projectStopReviewClientContext(source);
|
|
481
|
+
const out = {};
|
|
482
|
+
for (const [name, alias] of HOOK_CLIENT_CONFIG_PROJECTIONS)
|
|
483
|
+
if (projected[alias] !== undefined)
|
|
484
|
+
out[name] = projected[alias];
|
|
485
|
+
for (const { name, alias } of AUTHORITY_PROJECTIONS)
|
|
486
|
+
if (projected[alias] !== undefined)
|
|
487
|
+
out[name] = projected[alias];
|
|
488
|
+
return out;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
// src/lib/native-child-env.ts
|
|
492
|
+
var INHERITED = new Set([
|
|
493
|
+
"PATH",
|
|
494
|
+
"USER",
|
|
495
|
+
"LOGNAME",
|
|
496
|
+
"LANG",
|
|
497
|
+
"TMPDIR",
|
|
498
|
+
"XDG_CONFIG_HOME",
|
|
499
|
+
"XDG_CONFIG_DIRS",
|
|
500
|
+
"XDG_DATA_HOME",
|
|
501
|
+
"XDG_DATA_DIRS",
|
|
502
|
+
"XDG_CACHE_HOME",
|
|
503
|
+
"XDG_STATE_HOME",
|
|
504
|
+
"XDG_RUNTIME_DIR"
|
|
505
|
+
]);
|
|
506
|
+
var REFUSED_PREFIXES = ["LD_", "DYLD_", "NODE_", "BUN_", "BASH_FUNC_"];
|
|
507
|
+
var REFUSED2 = new Set(["BASH_ENV", "ENV", "GLIBC_TUNABLES", "GCONV_PATH", "LOCPATH"]);
|
|
508
|
+
function isRefusedNativeChildEnvName(name) {
|
|
509
|
+
return REFUSED2.has(name) || REFUSED_PREFIXES.some((prefix) => name.startsWith(prefix));
|
|
510
|
+
}
|
|
511
|
+
function nativeChildEnv(source, explicit = {}, inherit = () => false) {
|
|
512
|
+
const env = {};
|
|
513
|
+
for (const [name, value] of Object.entries(source)) {
|
|
514
|
+
if (typeof value !== "string" || isRefusedNativeChildEnvName(name))
|
|
515
|
+
continue;
|
|
516
|
+
if (INHERITED.has(name) || /^LC_[A-Z]+$/.test(name) || inherit(name))
|
|
517
|
+
env[name] = value;
|
|
518
|
+
}
|
|
519
|
+
for (const [name, value] of Object.entries(explicit)) {
|
|
520
|
+
if (isRefusedNativeChildEnvName(name))
|
|
521
|
+
throw new Error(`A native child environment cannot set ${name}.`);
|
|
522
|
+
if (value === undefined)
|
|
523
|
+
delete env[name];
|
|
524
|
+
else
|
|
525
|
+
env[name] = value;
|
|
526
|
+
}
|
|
527
|
+
return env;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
// hooks/hook-stop-review/src/types.ts
|
|
531
|
+
var STOP_CLASSES = [
|
|
532
|
+
"complete",
|
|
533
|
+
"actionable_remaining",
|
|
534
|
+
"blocked_permission",
|
|
535
|
+
"blocked_external",
|
|
536
|
+
"blocked_environment",
|
|
537
|
+
"needs_user_input",
|
|
538
|
+
"uncertain"
|
|
539
|
+
];
|
|
540
|
+
|
|
541
|
+
// hooks/hook-stop-review/src/jev.ts
|
|
542
|
+
var TYPESAFE_SYSTEMONE_URL = "https://api.typesafe.ai/v1/systemone";
|
|
543
|
+
var MAX_RESPONSE_BYTES = 16384;
|
|
544
|
+
var isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
545
|
+
var probability = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
|
|
546
|
+
var tokenCount = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
547
|
+
function buildJevRequest(envelope, options) {
|
|
548
|
+
return {
|
|
549
|
+
model: options.model,
|
|
550
|
+
state: {
|
|
551
|
+
last_user_prompt: envelope.lastUserPrompt,
|
|
552
|
+
last_assistant_message: envelope.lastAssistantMessage,
|
|
553
|
+
goal: envelope.goal ? { objective: envelope.goal.objective, status: envelope.goal.status } : null,
|
|
554
|
+
runtime_stop_reason: envelope.runtime.stopReason
|
|
555
|
+
},
|
|
556
|
+
questions: options.instruction.questions
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
function parseJevAssessment(value) {
|
|
560
|
+
if (!isRecord(value) || typeof value.model !== "string" || !/^jev-[a-zA-Z0-9._-]{1,100}$/.test(value.model) || !isRecord(value.answers) || !isRecord(value.usage))
|
|
561
|
+
return null;
|
|
562
|
+
const { disposition, actionable, boundary } = value.answers;
|
|
563
|
+
if (Object.keys(value.answers).sort().join(",") !== "actionable,boundary,disposition" || !isRecord(disposition) || disposition.type !== "choice" || !STOP_CLASSES.includes(disposition.choice) || !probability(disposition.confidence) || !isRecord(disposition.probabilities) || !isRecord(actionable) || actionable.type !== "noul" || !probability(actionable.noul) || !isRecord(boundary) || boundary.type !== "noul" || !probability(boundary.noul) || !tokenCount(value.usage.input_tokens) || !tokenCount(value.usage.output_tokens))
|
|
564
|
+
return null;
|
|
565
|
+
const probabilities = disposition.probabilities;
|
|
566
|
+
if (Object.keys(probabilities).length !== STOP_CLASSES.length || !STOP_CLASSES.every((key) => Object.hasOwn(probabilities, key) && probability(probabilities[key])))
|
|
567
|
+
return null;
|
|
568
|
+
const sum = STOP_CLASSES.reduce((total, key) => total + probabilities[key], 0);
|
|
569
|
+
const selected = probabilities[disposition.choice];
|
|
570
|
+
if (Math.abs(sum - 1) > 0.04 || STOP_CLASSES.some((key) => probabilities[key] > selected + 0.01))
|
|
571
|
+
return null;
|
|
572
|
+
return {
|
|
573
|
+
classification: disposition.choice,
|
|
574
|
+
confidence: disposition.confidence,
|
|
575
|
+
probabilities,
|
|
576
|
+
actionableProbability: actionable.noul,
|
|
577
|
+
boundaryProbability: boundary.noul,
|
|
578
|
+
model: value.model,
|
|
579
|
+
inputTokens: value.usage.input_tokens,
|
|
580
|
+
outputTokens: value.usage.output_tokens
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
async function evaluateJev(envelope, options) {
|
|
584
|
+
if (!options.apiKey?.trim())
|
|
585
|
+
return { ok: false, reason: "credential_unavailable" };
|
|
586
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(options.model))
|
|
587
|
+
return { ok: false, reason: "invalid_configuration" };
|
|
588
|
+
const timeoutMs = options.timeoutMs ?? 8000;
|
|
589
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 15000)
|
|
590
|
+
return { ok: false, reason: "invalid_configuration" };
|
|
591
|
+
const body = JSON.stringify(buildJevRequest(envelope, options));
|
|
592
|
+
const controller = new AbortController;
|
|
593
|
+
let timedOut = false;
|
|
594
|
+
let timer;
|
|
595
|
+
const deadline = new Promise((resolve2) => {
|
|
596
|
+
timer = setTimeout(() => {
|
|
597
|
+
timedOut = true;
|
|
598
|
+
controller.abort();
|
|
599
|
+
resolve2({ ok: false, reason: "request_timeout" });
|
|
600
|
+
}, timeoutMs);
|
|
601
|
+
});
|
|
602
|
+
const request = async () => {
|
|
603
|
+
try {
|
|
604
|
+
const response = await (options.fetch ?? globalThis.fetch)(TYPESAFE_SYSTEMONE_URL, {
|
|
605
|
+
method: "POST",
|
|
606
|
+
redirect: "error",
|
|
607
|
+
signal: controller.signal,
|
|
608
|
+
headers: { Authorization: `Bearer ${options.apiKey}`, "Content-Type": "application/json", "User-Agent": "hooks-stop-review/1" },
|
|
609
|
+
body
|
|
610
|
+
});
|
|
611
|
+
if (response.redirected || response.url && response.url !== TYPESAFE_SYSTEMONE_URL) {
|
|
612
|
+
await response.body?.cancel().catch(() => {});
|
|
613
|
+
return { ok: false, reason: "provider_unavailable" };
|
|
614
|
+
}
|
|
615
|
+
if (!response.ok) {
|
|
616
|
+
await response.body?.cancel().catch(() => {});
|
|
617
|
+
const httpStatus = response.status;
|
|
618
|
+
const reason = httpStatus === 401 || httpStatus === 403 ? "credential_rejected" : httpStatus === 429 ? "provider_rate_limited" : httpStatus === 529 ? "provider_overloaded" : httpStatus >= 400 && httpStatus < 500 ? "provider_request_refused" : "provider_unavailable";
|
|
619
|
+
return { ok: false, reason, httpStatus };
|
|
620
|
+
}
|
|
621
|
+
const declared = Number(response.headers.get("content-length"));
|
|
622
|
+
if (Number.isFinite(declared) && declared > MAX_RESPONSE_BYTES) {
|
|
623
|
+
await response.body?.cancel().catch(() => {});
|
|
624
|
+
return { ok: false, reason: "response_too_large" };
|
|
625
|
+
}
|
|
626
|
+
if (!response.body)
|
|
627
|
+
return { ok: false, reason: "invalid_provider_response" };
|
|
628
|
+
const reader = response.body.getReader();
|
|
629
|
+
const chunks = [];
|
|
630
|
+
let bytes = 0;
|
|
631
|
+
try {
|
|
632
|
+
while (true) {
|
|
633
|
+
const part = await reader.read();
|
|
634
|
+
if (part.done)
|
|
635
|
+
break;
|
|
636
|
+
bytes += part.value.byteLength;
|
|
637
|
+
if (bytes > MAX_RESPONSE_BYTES) {
|
|
638
|
+
await reader.cancel().catch(() => {});
|
|
639
|
+
return { ok: false, reason: "response_too_large" };
|
|
640
|
+
}
|
|
641
|
+
chunks.push(part.value);
|
|
642
|
+
}
|
|
643
|
+
} finally {
|
|
644
|
+
reader.releaseLock();
|
|
645
|
+
}
|
|
646
|
+
let decoded;
|
|
647
|
+
try {
|
|
648
|
+
decoded = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
649
|
+
} catch {
|
|
650
|
+
return { ok: false, reason: "invalid_provider_response" };
|
|
651
|
+
}
|
|
652
|
+
const assessment = parseJevAssessment(decoded);
|
|
653
|
+
return assessment ? { ok: true, assessment } : { ok: false, reason: "invalid_provider_response" };
|
|
654
|
+
} catch {
|
|
655
|
+
return { ok: false, reason: timedOut ? "request_timeout" : "provider_unavailable" };
|
|
656
|
+
}
|
|
657
|
+
};
|
|
658
|
+
try {
|
|
659
|
+
return await Promise.race([request(), deadline]);
|
|
660
|
+
} finally {
|
|
661
|
+
clearTimeout(timer);
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
// hooks/hook-stop-review/src/policy.ts
|
|
666
|
+
var record = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
667
|
+
var identifier = (value) => typeof value === "string" && /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/.test(value);
|
|
668
|
+
var text2 = (value, max = Infinity) => typeof value === "string" && value.trim().length > 0 && Buffer.byteLength(value) <= max;
|
|
669
|
+
var runtimeFlags = ["userRequestedStop", "terminal", "paused", "budgetExhausted", "usageLimited", "awaitingApproval", "nativeContinuationAllowed", "stopHookActive"];
|
|
670
|
+
var goalStatuses = ["active", "complete", "paused", "cancelled", "blocked", "budget_limited", "usage_limited", "unknown"];
|
|
671
|
+
var stopReasons = ["end_turn", "user_stop", "cancelled", "error", "approval_wait", "budget_limit", "usage_limit", "unknown"];
|
|
672
|
+
var MIN_CERTAINTY = 0.9;
|
|
673
|
+
var MAX_NEGATIVE = 0.1;
|
|
674
|
+
function isStopReviewEnvelope(value) {
|
|
675
|
+
if (!record(value) || value.schema !== "hooks.stop-review.v1" || !identifier(value.sessionId) || !identifier(value.turnId) || !identifier(value.inputRevision) || typeof value.capturedAt !== "string" || !Number.isFinite(Date.parse(value.capturedAt)) || !text2(value.lastUserPrompt) || !text2(value.lastAssistantMessage) || !record(value.runtime))
|
|
676
|
+
return false;
|
|
677
|
+
const runtime = value.runtime;
|
|
678
|
+
if (!runtimeFlags.every((key) => typeof runtime[key] === "boolean") || !stopReasons.includes(runtime.stopReason) || !Number.isSafeInteger(runtime.continuationCount) || runtime.continuationCount < 0)
|
|
679
|
+
return false;
|
|
680
|
+
if (value.goal !== undefined && value.goal !== null && (!record(value.goal) || !identifier(value.goal.id) || !text2(value.goal.objective) || !goalStatuses.includes(value.goal.status)))
|
|
681
|
+
return false;
|
|
682
|
+
if (value.goalAvailability !== undefined && !["known", "unavailable"].includes(value.goalAvailability))
|
|
683
|
+
return false;
|
|
684
|
+
return true;
|
|
685
|
+
}
|
|
686
|
+
function isStopReviewInstruction(value) {
|
|
687
|
+
if (!(record(value) && identifier(value.sourceId) && Number.isSafeInteger(value.version) && value.version > 0 && typeof value.digest === "string" && /^(sha256:)?[a-f0-9]{64}$/.test(value.digest) && text2(value.continuationPrompt, 4096) && record(value.questions)))
|
|
688
|
+
return false;
|
|
689
|
+
const q = value.questions;
|
|
690
|
+
if (Object.keys(q).sort().join(",") !== "actionable,boundary,disposition" || !record(q.disposition) || q.disposition.type !== "choice" || !text2(q.disposition.instructions, 16000) || !record(q.disposition.criteria))
|
|
691
|
+
return false;
|
|
692
|
+
const criteria = q.disposition.criteria;
|
|
693
|
+
if (Object.keys(q.disposition).sort().join(",") !== "criteria,instructions,type" || Object.keys(criteria).length !== STOP_CLASSES.length || !STOP_CLASSES.every((key) => text2(criteria[key], 4096)))
|
|
694
|
+
return false;
|
|
695
|
+
return [q.actionable, q.boundary].every((n) => record(n) && n.type === "noul" && text2(n.instructions, 8192) && Object.keys(n).sort().join(",") === "criteria,instructions,type" && record(n.criteria) && Object.keys(n.criteria).sort().join(",") === "false,true" && text2(n.criteria.true, 4096) && text2(n.criteria.false, 4096));
|
|
696
|
+
}
|
|
697
|
+
function stopPolicyGate(envelope, now, maxContinuations = 1, options = {}) {
|
|
698
|
+
const runtime = envelope.runtime;
|
|
699
|
+
if (runtime.userRequestedStop || ["user_stop", "cancelled"].includes(runtime.stopReason))
|
|
700
|
+
return "user_stop";
|
|
701
|
+
if (runtime.terminal)
|
|
702
|
+
return "terminal";
|
|
703
|
+
if (runtime.paused)
|
|
704
|
+
return "paused";
|
|
705
|
+
if (runtime.budgetExhausted || runtime.stopReason === "budget_limit")
|
|
706
|
+
return "budget_limit";
|
|
707
|
+
if (runtime.usageLimited || runtime.stopReason === "usage_limit")
|
|
708
|
+
return "usage_limit";
|
|
709
|
+
if (runtime.awaitingApproval || runtime.stopReason === "approval_wait")
|
|
710
|
+
return "approval_wait";
|
|
711
|
+
if (!runtime.nativeContinuationAllowed)
|
|
712
|
+
return "native_continuation_unavailable";
|
|
713
|
+
if (runtime.stopReason === "error")
|
|
714
|
+
return "runtime_failure";
|
|
715
|
+
if (runtime.stopReason !== "end_turn" || envelope.goal === undefined && envelope.goalAvailability !== "unavailable" || envelope.goal?.status === "unknown")
|
|
716
|
+
return "unknown_runtime";
|
|
717
|
+
if (envelope.goal && envelope.goal.status !== "active")
|
|
718
|
+
return "goal_not_active";
|
|
719
|
+
if (runtime.stopHookActive || runtime.continuationCount > maxContinuations || runtime.continuationCount === maxContinuations && !options.assessmentOnlyAtCap)
|
|
720
|
+
return "recursion_guard";
|
|
721
|
+
const age = now - Date.parse(envelope.capturedAt);
|
|
722
|
+
if (!Number.isFinite(now) || age > 120000 || age < -30000)
|
|
723
|
+
return "stale_input";
|
|
724
|
+
return null;
|
|
725
|
+
}
|
|
726
|
+
async function reviewStop(input, options) {
|
|
727
|
+
return assessStop(input, options, options.isCurrent);
|
|
728
|
+
}
|
|
729
|
+
async function recommendStop(input, options) {
|
|
730
|
+
if (options.admission?.mode !== "parent_final_cas" || !["sumi", "opencode"].includes(options.admission.harness)) {
|
|
731
|
+
return { schema: "hooks.stop-review-result.v1", action: "unavailable", reason: "invalid_configuration" };
|
|
732
|
+
}
|
|
733
|
+
const result = await assessStop(input, options, undefined, options.admission);
|
|
734
|
+
const settlement = isStopReviewEnvelope(input) && input.goal?.status === "active" ? settlementFor(result) : "none";
|
|
735
|
+
return { ...result, admission: { mode: "parent_final_cas", harness: options.admission.harness, settlement } };
|
|
736
|
+
}
|
|
737
|
+
function settlementFor(result) {
|
|
738
|
+
const a = result.assessment;
|
|
739
|
+
if (result.action !== "allow_stop" || result.reason !== "classified_stop" || !a || a.confidence < MIN_CERTAINTY || a.probabilities[a.classification] < MIN_CERTAINTY || a.actionableProbability > MAX_NEGATIVE)
|
|
740
|
+
return "none";
|
|
741
|
+
if (a.classification === "complete" && a.boundaryProbability <= MAX_NEGATIVE)
|
|
742
|
+
return "complete";
|
|
743
|
+
if (["blocked_permission", "blocked_external", "blocked_environment", "needs_user_input"].includes(a.classification) && a.boundaryProbability >= MIN_CERTAINTY)
|
|
744
|
+
return "blocked";
|
|
745
|
+
return "none";
|
|
746
|
+
}
|
|
747
|
+
async function assessStop(input, options, isCurrent, admission) {
|
|
748
|
+
const empty = (reason) => ({ schema: "hooks.stop-review-result.v1", action: "allow_stop", reason });
|
|
749
|
+
if (!isStopReviewEnvelope(input))
|
|
750
|
+
return empty("invalid_input");
|
|
751
|
+
const envelope = structuredClone(input);
|
|
752
|
+
const base = {
|
|
753
|
+
schema: "hooks.stop-review-result.v1",
|
|
754
|
+
sessionId: envelope.sessionId,
|
|
755
|
+
turnId: envelope.turnId,
|
|
756
|
+
inputRevision: envelope.inputRevision
|
|
757
|
+
};
|
|
758
|
+
const stop = (reason) => ({ ...base, action: "allow_stop", reason });
|
|
759
|
+
const max = options.maxContinuations ?? 1;
|
|
760
|
+
if (!Number.isInteger(max) || max < 1 || max > 3)
|
|
761
|
+
return stop("invalid_configuration");
|
|
762
|
+
const now = options.now ?? Date.now;
|
|
763
|
+
const parentGuarded = admission?.mode === "parent_final_cas" && ["sumi", "opencode"].includes(admission.harness);
|
|
764
|
+
const gateOptions = { assessmentOnlyAtCap: parentGuarded };
|
|
765
|
+
const gate = stopPolicyGate(envelope, now(), max, gateOptions);
|
|
766
|
+
if (gate)
|
|
767
|
+
return stop(gate);
|
|
768
|
+
if (!isStopReviewInstruction(options.instruction))
|
|
769
|
+
return stop("instruction_unavailable");
|
|
770
|
+
if (options.externalContentApproved !== true)
|
|
771
|
+
return stop("external_content_unapproved");
|
|
772
|
+
const current = async () => {
|
|
773
|
+
let timer;
|
|
774
|
+
try {
|
|
775
|
+
return await Promise.race([
|
|
776
|
+
Promise.resolve().then(() => typeof isCurrent === "function" && isCurrent(structuredClone(envelope))).then((value) => value === true).catch(() => false),
|
|
777
|
+
new Promise((resolve2) => {
|
|
778
|
+
timer = setTimeout(() => resolve2(false), 500);
|
|
779
|
+
})
|
|
780
|
+
]);
|
|
781
|
+
} finally {
|
|
782
|
+
clearTimeout(timer);
|
|
783
|
+
}
|
|
784
|
+
};
|
|
785
|
+
if (!parentGuarded && !await current())
|
|
786
|
+
return stop("stale_input");
|
|
787
|
+
let assessed;
|
|
788
|
+
try {
|
|
789
|
+
assessed = await (options.evaluate ?? evaluateJev)(envelope, options);
|
|
790
|
+
} catch {
|
|
791
|
+
return { ...base, action: "unavailable", reason: "provider_unavailable" };
|
|
792
|
+
}
|
|
793
|
+
if (!parentGuarded && !await current() || stopPolicyGate(envelope, now(), max, gateOptions))
|
|
794
|
+
return stop("stale_input");
|
|
795
|
+
if (!record(assessed) || typeof assessed.ok !== "boolean")
|
|
796
|
+
return { ...base, action: "unavailable", reason: "invalid_provider_response" };
|
|
797
|
+
if (!assessed.ok)
|
|
798
|
+
return { ...base, action: "unavailable", reason: assessed.reason, ...assessed.httpStatus === undefined ? {} : { httpStatus: assessed.httpStatus } };
|
|
799
|
+
const assessment = assessed.assessment;
|
|
800
|
+
if (!record(assessment))
|
|
801
|
+
return { ...base, action: "unavailable", reason: "invalid_provider_response" };
|
|
802
|
+
const checked = parseJevAssessment({ model: assessment.model, answers: {
|
|
803
|
+
disposition: { type: "choice", choice: assessment.classification, confidence: assessment.confidence, probabilities: assessment.probabilities },
|
|
804
|
+
actionable: { type: "noul", noul: assessment.actionableProbability },
|
|
805
|
+
boundary: { type: "noul", noul: assessment.boundaryProbability }
|
|
806
|
+
}, usage: { input_tokens: assessment.inputTokens, output_tokens: assessment.outputTokens } });
|
|
807
|
+
if (!checked)
|
|
808
|
+
return { ...base, action: "unavailable", reason: "invalid_provider_response" };
|
|
809
|
+
const provenance = { sourceId: options.instruction.sourceId, version: options.instruction.version, digest: options.instruction.digest };
|
|
810
|
+
const result = { ...base, assessment, classification: assessment.classification, instruction: provenance };
|
|
811
|
+
if (assessment.classification !== "actionable_remaining") {
|
|
812
|
+
return { ...result, action: "allow_stop", reason: assessment.classification === "uncertain" ? "classification_uncertain" : "classified_stop" };
|
|
813
|
+
}
|
|
814
|
+
if (envelope.runtime.continuationCount >= max)
|
|
815
|
+
return { ...result, action: "allow_stop", reason: "continuation_limit" };
|
|
816
|
+
if (assessment.confidence < MIN_CERTAINTY || assessment.probabilities.actionable_remaining < MIN_CERTAINTY || assessment.actionableProbability < MIN_CERTAINTY || assessment.boundaryProbability > MAX_NEGATIVE) {
|
|
817
|
+
return { ...result, action: "allow_stop", reason: "classification_uncertain" };
|
|
818
|
+
}
|
|
819
|
+
return { ...result, action: "continue", reason: "actionable_remaining", continuationPrompt: options.instruction.continuationPrompt };
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
// hooks/hook-stop-review/src/runtime.ts
|
|
823
|
+
var record2 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
824
|
+
var sha256 = (value) => createHash2("sha256").update(value).digest("hex");
|
|
825
|
+
var safePath = (value) => typeof value === "string" && isAbsolute2(value) && value.length <= 4096 && !/[\u0000-\u001f]/.test(value);
|
|
826
|
+
function parseRuntimeConfiguration(value) {
|
|
827
|
+
if (!record2(value) || value.schema !== "hooks.stop-review-runtime.v1" || value.enabled !== true || typeof value.model !== "string" || !/^jev-[a-zA-Z0-9._-]{1,100}$/.test(value.model) || !record2(value.instruction) || typeof value.instruction.id !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/.test(value.instruction.id) || !Number.isSafeInteger(value.instruction.version) || value.instruction.version < 1 || typeof value.instruction.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(value.instruction.sha256) || !record2(value.commands) || !safePath(value.commands.instructions) || !safePath(value.commands.secrets) || typeof value.secretsReference !== "string" || value.secretsReference.length > 256 || !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9_.-]*){1,12}$/.test(value.secretsReference))
|
|
828
|
+
return null;
|
|
829
|
+
const allowed = ["schema", "enabled", "model", "instruction", "commands", "secretsReference", "harness", "codexHome", "codexSocketPath"];
|
|
830
|
+
if (!Object.keys(value).every((key) => allowed.includes(key)) || Object.keys(value.instruction).sort().join(",") !== "id,sha256,version" || Object.keys(value.commands).sort().join(",") !== "instructions,secrets" || value.harness !== undefined && !["codex", "claude", "sumi", "opencode"].includes(value.harness) || value.codexHome !== undefined && !safePath(value.codexHome) || value.codexSocketPath !== undefined && !safePath(value.codexSocketPath))
|
|
831
|
+
return null;
|
|
832
|
+
return value;
|
|
833
|
+
}
|
|
834
|
+
function readPrivateConfiguration(path) {
|
|
835
|
+
if (!safePath(path))
|
|
836
|
+
return null;
|
|
837
|
+
let fd;
|
|
838
|
+
try {
|
|
839
|
+
fd = openSync2(path, constants2.O_RDONLY | constants2.O_NOFOLLOW);
|
|
840
|
+
const stat = fstatSync2(fd);
|
|
841
|
+
if (!stat.isFile() || stat.size > 16384 || (stat.mode & 18) !== 0 || process.getuid && stat.uid !== process.getuid())
|
|
842
|
+
return null;
|
|
843
|
+
return JSON.parse(readFileSync(fd, "utf8"));
|
|
844
|
+
} catch {
|
|
845
|
+
return null;
|
|
846
|
+
} finally {
|
|
847
|
+
if (fd !== undefined)
|
|
848
|
+
closeSync2(fd);
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
function loadNativeRuntimeConfiguration(env = process.env) {
|
|
852
|
+
const path = env.HOOKS_STOP_REVIEW_CONFIG ?? join3(getEffectiveDataRoot(env), "config", "stop-review.json");
|
|
853
|
+
return parseRuntimeConfiguration(readPrivateConfiguration(path));
|
|
854
|
+
}
|
|
855
|
+
var runRuntimeCommand = (invocation) => new Promise((resolve2) => {
|
|
856
|
+
let settled = false;
|
|
857
|
+
let bytes = 0;
|
|
858
|
+
let errorBytes = 0;
|
|
859
|
+
const chunks = [];
|
|
860
|
+
let timer;
|
|
861
|
+
let child;
|
|
862
|
+
const finish = (result) => {
|
|
863
|
+
if (settled)
|
|
864
|
+
return;
|
|
865
|
+
settled = true;
|
|
866
|
+
clearTimeout(timer);
|
|
867
|
+
resolve2(result);
|
|
868
|
+
};
|
|
869
|
+
const abort = () => {
|
|
870
|
+
if (settled)
|
|
871
|
+
return;
|
|
872
|
+
try {
|
|
873
|
+
if (child?.pid && process.platform !== "win32")
|
|
874
|
+
process.kill(-child.pid, "SIGKILL");
|
|
875
|
+
else
|
|
876
|
+
child?.kill("SIGKILL");
|
|
877
|
+
} catch {}
|
|
878
|
+
child?.stdin?.destroy();
|
|
879
|
+
child?.stdout?.destroy();
|
|
880
|
+
child?.stderr?.destroy();
|
|
881
|
+
finish({ ok: false });
|
|
882
|
+
};
|
|
883
|
+
try {
|
|
884
|
+
const command = realpathSync2(invocation.command);
|
|
885
|
+
const stat = lstatSync(command);
|
|
886
|
+
if (!stat.isFile() || (stat.mode & 18) !== 0 || process.getuid && ![0, process.getuid()].includes(stat.uid))
|
|
887
|
+
return finish({ ok: false });
|
|
888
|
+
child = spawn(command, invocation.args, {
|
|
889
|
+
shell: false,
|
|
890
|
+
detached: process.platform !== "win32",
|
|
891
|
+
cwd: getHomeDir(invocation.env),
|
|
892
|
+
env: invocation.env,
|
|
893
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
894
|
+
});
|
|
895
|
+
timer = setTimeout(abort, invocation.timeoutMs);
|
|
896
|
+
child.stdout.on("data", (chunk) => {
|
|
897
|
+
bytes += chunk.length;
|
|
898
|
+
if (bytes > invocation.maxOutputBytes)
|
|
899
|
+
abort();
|
|
900
|
+
else
|
|
901
|
+
chunks.push(Buffer.from(chunk));
|
|
902
|
+
});
|
|
903
|
+
child.stderr.on("data", (chunk) => {
|
|
904
|
+
errorBytes += chunk.length;
|
|
905
|
+
if (errorBytes > 4096)
|
|
906
|
+
abort();
|
|
907
|
+
});
|
|
908
|
+
child.stdin.on("error", abort);
|
|
909
|
+
child.on("error", () => finish({ ok: false }));
|
|
910
|
+
child.on("close", (code) => finish({ ok: code === 0, exitCode: code, ...code === 0 ? { stdout: Buffer.concat(chunks).toString("utf8") } : {} }));
|
|
911
|
+
child.stdin.end(invocation.input ?? "");
|
|
912
|
+
} catch {
|
|
913
|
+
finish({ ok: false });
|
|
914
|
+
}
|
|
915
|
+
});
|
|
916
|
+
function helperEnvironment(env, app) {
|
|
917
|
+
const restored = { ...env, ...restoreStopReviewClientContext(env) };
|
|
918
|
+
return nativeChildEnv(restored, { HOME: getHomeDir(env), NO_COLOR: "1" }, (name) => ["HASNA_HOME", "HASNA_CONFIG_HOME", "HASNA_PROFILE", "HASNA_STATION", "HASNA_HOOKS_HOME", "HOOKS_HOME", "HASNA_HOOKS_DATA_DIR", "HOOKS_DATA_DIR", "HASNA_DATA_HOME", "HOOKS_STOP_REVIEW_CONFIG"].includes(name) || name === "HASNA_SECRETS_API_KEY_REF" || name === "HASNA_SECRETS_API_URL" || name.startsWith(`HASNA_${app.toUpperCase()}_`) || app === "instructions" && name.startsWith("HASNA_CONFIGS_"));
|
|
919
|
+
}
|
|
920
|
+
function instructionFromContent(content, config) {
|
|
921
|
+
try {
|
|
922
|
+
if (sha256(content) !== config.instruction.sha256)
|
|
923
|
+
return null;
|
|
924
|
+
const body = JSON.parse(content);
|
|
925
|
+
if (!record2(body) || body.schema !== "hooks.stop-review-instructions.v1" || Object.keys(body).sort().join(",") !== "continuationPrompt,questions,schema")
|
|
926
|
+
return null;
|
|
927
|
+
const instruction = {
|
|
928
|
+
sourceId: config.instruction.id,
|
|
929
|
+
version: config.instruction.version,
|
|
930
|
+
digest: config.instruction.sha256,
|
|
931
|
+
questions: body.questions,
|
|
932
|
+
continuationPrompt: body.continuationPrompt,
|
|
933
|
+
sourceContent: content
|
|
934
|
+
};
|
|
935
|
+
return isStopReviewInstruction(instruction) ? instruction : null;
|
|
936
|
+
} catch {
|
|
937
|
+
return null;
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
async function loadPinnedInstruction(config, env, run = runRuntimeCommand) {
|
|
941
|
+
if (stopReviewClientContextRefused(env))
|
|
942
|
+
return null;
|
|
943
|
+
const result = await run({
|
|
944
|
+
command: config.commands.instructions,
|
|
945
|
+
args: ["show", config.instruction.id, "--format", "json"],
|
|
946
|
+
timeoutMs: 4000,
|
|
947
|
+
maxOutputBytes: 65536,
|
|
948
|
+
env: helperEnvironment(env, "instructions")
|
|
949
|
+
});
|
|
950
|
+
if (!result.ok || typeof result.stdout !== "string")
|
|
951
|
+
return null;
|
|
952
|
+
try {
|
|
953
|
+
const row = JSON.parse(result.stdout);
|
|
954
|
+
if (!record2(row) || row.id !== config.instruction.id || row.version !== config.instruction.version || row.category !== "rules" || typeof row.content !== "string" || sha256(row.content) !== config.instruction.sha256)
|
|
955
|
+
return null;
|
|
956
|
+
return instructionFromContent(row.content, config);
|
|
957
|
+
} catch {
|
|
958
|
+
return null;
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
async function scanStopReviewContent(envelope, instruction, config, env, run = runRuntimeCommand) {
|
|
962
|
+
if (stopReviewClientContextRefused(env))
|
|
963
|
+
return false;
|
|
964
|
+
const input = JSON.stringify(buildJevRequest(envelope, { model: config.model, instruction }));
|
|
965
|
+
const bytes = Buffer.byteLength(input);
|
|
966
|
+
const result = await run({
|
|
967
|
+
command: config.commands.secrets,
|
|
968
|
+
args: ["scan", "input", "-", "--max-bytes", String(bytes), "--timeout-ms", "1500", "--json"],
|
|
969
|
+
input,
|
|
970
|
+
timeoutMs: 2500,
|
|
971
|
+
maxOutputBytes: 32768,
|
|
972
|
+
env: helperEnvironment(env, "secrets")
|
|
973
|
+
});
|
|
974
|
+
if (!result.ok || typeof result.stdout !== "string")
|
|
975
|
+
return false;
|
|
976
|
+
try {
|
|
977
|
+
const receipt = JSON.parse(result.stdout);
|
|
978
|
+
return record2(receipt) && receipt.schema === "open-secrets.exposure-scan.v1" && receipt.findingCount === 0 && receipt.truncated === false && Array.isArray(receipt.findings) && receipt.findings.length === 0 && record2(receipt.stats) && receipt.stats.filesScanned === 1 && receipt.stats.filesSkipped === 0 && receipt.stats.bytesScanned === bytes && Array.isArray(receipt.stats.errors) && receipt.stats.errors.length === 0;
|
|
979
|
+
} catch {
|
|
980
|
+
return false;
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
function claimStopReviewTurn(envelope, env = process.env, requestHash, instructionDigest, admission, nativeTarget) {
|
|
984
|
+
let fd;
|
|
985
|
+
try {
|
|
986
|
+
const root = getEffectiveDataRoot(env);
|
|
987
|
+
const directory = join3(root, "state", "stop-review", "turn-claims");
|
|
988
|
+
mkdirSync(directory, { recursive: true, mode: 448 });
|
|
989
|
+
if (realpathSync2(directory) !== directory)
|
|
990
|
+
return "unavailable";
|
|
991
|
+
const stat = lstatSync(directory);
|
|
992
|
+
if (!stat.isDirectory() || (stat.mode & 63) !== 0 || process.getuid && stat.uid !== process.getuid())
|
|
993
|
+
return "unavailable";
|
|
994
|
+
const key = sha256(`${envelope.sessionId}\x00${envelope.turnId}`);
|
|
995
|
+
fd = openSync2(join3(directory, `${key}.json`), constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL | constants2.O_NOFOLLOW, 384);
|
|
996
|
+
const body = JSON.stringify({
|
|
997
|
+
schema: "hooks.stop-review-claim.v1",
|
|
998
|
+
sessionHash: sha256(envelope.sessionId),
|
|
999
|
+
turnHash: sha256(envelope.turnId),
|
|
1000
|
+
revisionHash: sha256(envelope.inputRevision),
|
|
1001
|
+
requestHash,
|
|
1002
|
+
instructionDigest,
|
|
1003
|
+
admissionMode: admission ? `${admission.harness}:parent_final_cas` : "native",
|
|
1004
|
+
nativeTarget,
|
|
1005
|
+
createdAt: new Date().toISOString()
|
|
1006
|
+
}) + `
|
|
1007
|
+
`;
|
|
1008
|
+
writeFileSync(fd, body);
|
|
1009
|
+
fsyncSync(fd);
|
|
1010
|
+
return "claimed";
|
|
1011
|
+
} catch (error) {
|
|
1012
|
+
return error.code === "EEXIST" ? "already_claimed" : "unavailable";
|
|
1013
|
+
} finally {
|
|
1014
|
+
if (fd !== undefined)
|
|
1015
|
+
closeSync2(fd);
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
function providerClaimMatches(envelope, requestHash, instructionDigest, env, admission, nativeTarget) {
|
|
1019
|
+
const path = join3(getEffectiveDataRoot(env), "state", "stop-review", "turn-claims", `${sha256(`${envelope.sessionId}\x00${envelope.turnId}`)}.json`);
|
|
1020
|
+
const claim = readPrivateConfiguration(path);
|
|
1021
|
+
return record2(claim) && claim.schema === "hooks.stop-review-claim.v1" && claim.sessionHash === sha256(envelope.sessionId) && claim.turnHash === sha256(envelope.turnId) && claim.revisionHash === sha256(envelope.inputRevision) && claim.requestHash === requestHash && claim.instructionDigest === instructionDigest && claim.nativeTarget === nativeTarget && claim.admissionMode === (admission ? `${admission.harness}:parent_final_cas` : "native");
|
|
1022
|
+
}
|
|
1023
|
+
async function runJevProviderChild(raw, env = process.env) {
|
|
1024
|
+
if (!record2(raw) || raw.schema !== "hooks.stop-review-provider.v1" || !isStopReviewEnvelope(raw.envelope) || typeof raw.instructionContent !== "string")
|
|
1025
|
+
return { ok: false, reason: "invalid_input" };
|
|
1026
|
+
const config = loadNativeRuntimeConfiguration(env);
|
|
1027
|
+
if (!config)
|
|
1028
|
+
return { ok: false, reason: "invalid_configuration" };
|
|
1029
|
+
if (!["codex", "claude", "sumi", "opencode"].includes(raw.nativeTarget) || config.harness !== undefined && config.harness !== raw.nativeTarget)
|
|
1030
|
+
return { ok: false, reason: "invalid_configuration" };
|
|
1031
|
+
const nativeTarget = raw.nativeTarget;
|
|
1032
|
+
if (raw.admission !== undefined && (!record2(raw.admission) || raw.admission.mode !== "parent_final_cas" || !["sumi", "opencode"].includes(raw.admission.harness) || Object.keys(raw.admission).sort().join(",") !== "harness,mode" || nativeTarget !== raw.admission.harness))
|
|
1033
|
+
return { ok: false, reason: "invalid_configuration" };
|
|
1034
|
+
const admission = raw.admission;
|
|
1035
|
+
const gate = stopPolicyGate(raw.envelope, Date.now(), 1, { assessmentOnlyAtCap: !!admission });
|
|
1036
|
+
if (gate)
|
|
1037
|
+
return { ok: false, reason: gate };
|
|
1038
|
+
const instruction = instructionFromContent(raw.instructionContent, config);
|
|
1039
|
+
if (!instruction)
|
|
1040
|
+
return { ok: false, reason: "instruction_unavailable" };
|
|
1041
|
+
const requestHash = sha256(JSON.stringify(buildJevRequest(raw.envelope, { model: config.model, instruction })));
|
|
1042
|
+
if (!providerClaimMatches(raw.envelope, requestHash, instruction.digest, env, admission, nativeTarget))
|
|
1043
|
+
return { ok: false, reason: "claim_unavailable" };
|
|
1044
|
+
return evaluateJev(raw.envelope, { apiKey: env.TYPESAFE_API_KEY, model: config.model, instruction, timeoutMs: 8000 });
|
|
1045
|
+
}
|
|
1046
|
+
async function evaluateThroughSecrets(envelope, instruction, config, env, entrypoint, run = runRuntimeCommand, admission, nativeTarget) {
|
|
1047
|
+
if (stopReviewClientContextRefused(env))
|
|
1048
|
+
return { ok: false, reason: "invalid_configuration" };
|
|
1049
|
+
if (!safePath(entrypoint))
|
|
1050
|
+
return { ok: false, reason: "invalid_configuration" };
|
|
1051
|
+
let canonical;
|
|
1052
|
+
try {
|
|
1053
|
+
canonical = realpathSync2(entrypoint);
|
|
1054
|
+
const stat = lstatSync(canonical);
|
|
1055
|
+
if (!stat.isFile() || (stat.mode & 18) !== 0 || process.getuid && ![0, process.getuid()].includes(stat.uid))
|
|
1056
|
+
return { ok: false, reason: "invalid_configuration" };
|
|
1057
|
+
} catch {
|
|
1058
|
+
return { ok: false, reason: "invalid_configuration" };
|
|
1059
|
+
}
|
|
1060
|
+
const result = await run({
|
|
1061
|
+
command: config.commands.secrets,
|
|
1062
|
+
args: [
|
|
1063
|
+
"exec",
|
|
1064
|
+
config.secretsReference,
|
|
1065
|
+
"--as",
|
|
1066
|
+
"TYPESAFE_API_KEY",
|
|
1067
|
+
"--",
|
|
1068
|
+
process.execPath,
|
|
1069
|
+
"--config=/dev/null",
|
|
1070
|
+
"--no-env-file",
|
|
1071
|
+
"--no-macros",
|
|
1072
|
+
"--no-install",
|
|
1073
|
+
canonical,
|
|
1074
|
+
"--assess-envelope"
|
|
1075
|
+
],
|
|
1076
|
+
input: JSON.stringify({ schema: "hooks.stop-review-provider.v1", envelope, instructionContent: instruction.sourceContent, admission, nativeTarget }),
|
|
1077
|
+
timeoutMs: 1e4,
|
|
1078
|
+
maxOutputBytes: 16384,
|
|
1079
|
+
env: helperEnvironment(env, "secrets")
|
|
1080
|
+
});
|
|
1081
|
+
if (!result.ok || !result.stdout)
|
|
1082
|
+
return { ok: false, reason: "provider_unavailable" };
|
|
1083
|
+
try {
|
|
1084
|
+
const value = JSON.parse(result.stdout);
|
|
1085
|
+
if (!record2(value))
|
|
1086
|
+
return { ok: false, reason: "invalid_provider_response" };
|
|
1087
|
+
if (value.ok === true && record2(value.assessment)) {
|
|
1088
|
+
const a = value.assessment;
|
|
1089
|
+
const assessment = parseJevAssessment({ model: a.model, answers: {
|
|
1090
|
+
disposition: { type: "choice", choice: a.classification, confidence: a.confidence, probabilities: a.probabilities },
|
|
1091
|
+
actionable: { type: "noul", noul: a.actionableProbability },
|
|
1092
|
+
boundary: { type: "noul", noul: a.boundaryProbability }
|
|
1093
|
+
}, usage: { input_tokens: a.inputTokens, output_tokens: a.outputTokens } });
|
|
1094
|
+
return assessment ? { ok: true, assessment } : { ok: false, reason: "invalid_provider_response" };
|
|
1095
|
+
}
|
|
1096
|
+
const allowed = ["credential_unavailable", "invalid_configuration", "instruction_unavailable", "claim_unavailable", "invalid_input", "request_too_large", "response_too_large", "request_timeout", "provider_unavailable", "invalid_provider_response", "credential_rejected", "provider_rate_limited", "provider_request_refused", "provider_overloaded"];
|
|
1097
|
+
if (value.ok !== false || !allowed.includes(value.reason))
|
|
1098
|
+
return { ok: false, reason: "invalid_provider_response" };
|
|
1099
|
+
return {
|
|
1100
|
+
ok: false,
|
|
1101
|
+
reason: value.reason,
|
|
1102
|
+
...Number.isInteger(value.httpStatus) && value.httpStatus >= 100 && value.httpStatus <= 599 ? { httpStatus: value.httpStatus } : {}
|
|
1103
|
+
};
|
|
1104
|
+
} catch {
|
|
1105
|
+
return { ok: false, reason: "invalid_provider_response" };
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
async function reviewNativeEnvelope(envelope, isCurrent, env = process.env, entrypoint = process.argv[1], nativeTarget) {
|
|
1109
|
+
return reviewRuntimeEnvelope(envelope, env, entrypoint, nativeTarget, isCurrent);
|
|
1110
|
+
}
|
|
1111
|
+
async function reviewParentGuardedEnvelope(raw, env = process.env, entrypoint = process.argv[1], nativeTarget = "sumi") {
|
|
1112
|
+
const result = await reviewRuntimeEnvelope(raw, env, entrypoint, nativeTarget);
|
|
1113
|
+
return { ...result, admission: result.admission ?? { mode: "parent_final_cas", harness: nativeTarget, settlement: "none" } };
|
|
1114
|
+
}
|
|
1115
|
+
async function reviewRuntimeEnvelope(raw, env, entrypoint, nativeTarget, isCurrent) {
|
|
1116
|
+
if (!isStopReviewEnvelope(raw))
|
|
1117
|
+
return { schema: "hooks.stop-review-result.v1", action: "unavailable", reason: "invalid_input" };
|
|
1118
|
+
const envelope = structuredClone(raw);
|
|
1119
|
+
const base = { schema: "hooks.stop-review-result.v1", sessionId: envelope.sessionId, turnId: envelope.turnId, inputRevision: envelope.inputRevision };
|
|
1120
|
+
const unavailable2 = (reason) => ({ ...base, action: "unavailable", reason });
|
|
1121
|
+
const gate = stopPolicyGate(envelope, Date.now(), 1, { assessmentOnlyAtCap: !isCurrent });
|
|
1122
|
+
if (gate)
|
|
1123
|
+
return { ...base, action: "allow_stop", reason: gate };
|
|
1124
|
+
const config = loadNativeRuntimeConfiguration(env);
|
|
1125
|
+
if (!config)
|
|
1126
|
+
return unavailable2("invalid_configuration");
|
|
1127
|
+
if (!nativeTarget || config.harness !== undefined && config.harness !== nativeTarget)
|
|
1128
|
+
return unavailable2("invalid_configuration");
|
|
1129
|
+
if (!isCurrent && nativeTarget !== "sumi" && nativeTarget !== "opencode")
|
|
1130
|
+
return unavailable2("invalid_configuration");
|
|
1131
|
+
if (!safePath(entrypoint))
|
|
1132
|
+
return unavailable2("invalid_configuration");
|
|
1133
|
+
const instruction = await loadPinnedInstruction(config, env);
|
|
1134
|
+
if (!instruction)
|
|
1135
|
+
return unavailable2("instruction_unavailable");
|
|
1136
|
+
if (!await scanStopReviewContent(envelope, instruction, config, env))
|
|
1137
|
+
return unavailable2("content_scan_failed");
|
|
1138
|
+
const requestHash = sha256(JSON.stringify(buildJevRequest(envelope, { model: config.model, instruction })));
|
|
1139
|
+
const admission = isCurrent ? undefined : { mode: "parent_final_cas", harness: nativeTarget };
|
|
1140
|
+
const claimed = claimStopReviewTurn(envelope, env, requestHash, instruction.digest, admission, nativeTarget);
|
|
1141
|
+
if (claimed !== "claimed")
|
|
1142
|
+
return unavailable2(claimed === "already_claimed" ? "turn_already_reviewed" : "claim_unavailable");
|
|
1143
|
+
const options = {
|
|
1144
|
+
model: config.model,
|
|
1145
|
+
instruction,
|
|
1146
|
+
externalContentApproved: true,
|
|
1147
|
+
timeoutMs: 8000,
|
|
1148
|
+
evaluate: () => evaluateThroughSecrets(envelope, instruction, config, env, entrypoint, runRuntimeCommand, admission, nativeTarget)
|
|
1149
|
+
};
|
|
1150
|
+
return isCurrent ? reviewStop(envelope, { ...options, isCurrent }) : recommendStop(envelope, { ...options, admission });
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
// hooks/hook-stop-review/src/hook.ts
|
|
1154
|
+
function readHookInput(stream = process.stdin) {
|
|
1155
|
+
return new Promise((resolve2) => {
|
|
1156
|
+
const chunks = [];
|
|
1157
|
+
let done = false;
|
|
1158
|
+
const finish = (value) => {
|
|
1159
|
+
if (done)
|
|
1160
|
+
return;
|
|
1161
|
+
done = true;
|
|
1162
|
+
clearTimeout(timer);
|
|
1163
|
+
stream.removeListener("data", onData);
|
|
1164
|
+
stream.removeListener("end", onEnd);
|
|
1165
|
+
stream.removeListener("error", onError);
|
|
1166
|
+
stream.pause();
|
|
1167
|
+
resolve2(value);
|
|
1168
|
+
};
|
|
1169
|
+
const onData = (chunk) => {
|
|
1170
|
+
chunks.push(Buffer.from(chunk));
|
|
1171
|
+
};
|
|
1172
|
+
const onEnd = () => {
|
|
1173
|
+
try {
|
|
1174
|
+
finish(JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
|
1175
|
+
} catch {
|
|
1176
|
+
finish();
|
|
1177
|
+
}
|
|
1178
|
+
};
|
|
1179
|
+
const onError = () => finish();
|
|
1180
|
+
const timer = setTimeout(() => finish(), 1000);
|
|
1181
|
+
stream.on("data", onData);
|
|
1182
|
+
stream.on("end", onEnd);
|
|
1183
|
+
stream.on("error", onError);
|
|
1184
|
+
});
|
|
1185
|
+
}
|
|
1186
|
+
async function main(argv = process.argv.slice(2), env = process.env) {
|
|
1187
|
+
if (argv.length === 1 && argv[0] === "--assess-envelope") {
|
|
1188
|
+
try {
|
|
1189
|
+
process.stdout.write(JSON.stringify(await runJevProviderChild(await readHookInput(), env)) + `
|
|
1190
|
+
`);
|
|
1191
|
+
} catch {
|
|
1192
|
+
process.stdout.write(JSON.stringify({ ok: false, reason: "provider_unavailable" }) + `
|
|
1193
|
+
`);
|
|
1194
|
+
}
|
|
1195
|
+
return;
|
|
1196
|
+
}
|
|
1197
|
+
let output = {}, reason = "invalid_configuration";
|
|
1198
|
+
try {
|
|
1199
|
+
const config = loadNativeRuntimeConfiguration(env);
|
|
1200
|
+
const selected = (argv.length === 2 || argv.length === 3 && argv[2] === "--envelope" && ["sumi", "opencode"].includes(argv[1])) && argv[0] === "--harness" ? argv[1] : argv.length === 0 ? config?.harness : undefined;
|
|
1201
|
+
if ((selected === "sumi" || selected === "opencode") && config && (!config.harness || config.harness === selected) && env.HOOKS_STOP_REVIEW_DISABLED !== "1") {
|
|
1202
|
+
const recommendation = await reviewParentGuardedEnvelope(await readHookInput(), env, undefined, selected);
|
|
1203
|
+
process.stderr.write(JSON.stringify({ hook: "stop-review", reason: recommendation.reason, recommendationOnly: true }) + `
|
|
1204
|
+
`);
|
|
1205
|
+
process.stdout.write(JSON.stringify(recommendation) + `
|
|
1206
|
+
`);
|
|
1207
|
+
return;
|
|
1208
|
+
}
|
|
1209
|
+
if (config && env.HOOKS_STOP_REVIEW_DISABLED !== "1" && ["codex", "claude"].includes(String(selected)) && (!config.harness || config.harness === selected)) {
|
|
1210
|
+
const harness = selected;
|
|
1211
|
+
const raw = await readHookInput();
|
|
1212
|
+
const result = await runNativeStop(raw, {
|
|
1213
|
+
harness,
|
|
1214
|
+
readGoal: (sessionId) => readCodexGoal(sessionId, {
|
|
1215
|
+
codexHome: config.codexHome ?? env.CODEX_HOME ?? join4(env.HOME || homedir2(), ".codex"),
|
|
1216
|
+
socketPath: config.codexSocketPath
|
|
1217
|
+
})
|
|
1218
|
+
}, (envelope, isCurrent) => reviewNativeEnvelope(envelope, isCurrent, env, undefined, harness));
|
|
1219
|
+
output = result.output;
|
|
1220
|
+
reason = result.reason;
|
|
1221
|
+
}
|
|
1222
|
+
} catch {
|
|
1223
|
+
reason = "native_review_unavailable";
|
|
1224
|
+
}
|
|
1225
|
+
process.stderr.write(JSON.stringify({ hook: "stop-review", reason: /^[a-z_]{1,64}$/.test(reason) ? reason : "native_review_unavailable", continued: output.decision === "block" }) + `
|
|
1226
|
+
`);
|
|
1227
|
+
process.stdout.write(JSON.stringify(output) + `
|
|
1228
|
+
`);
|
|
1229
|
+
}
|
|
1230
|
+
if (import.meta.main)
|
|
1231
|
+
await main();
|
|
1232
|
+
export {
|
|
1233
|
+
readHookInput,
|
|
1234
|
+
main
|
|
1235
|
+
};
|