@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,145 @@
|
|
|
1
|
+
import { evaluateJev, parseJevAssessment } from "./jev";
|
|
2
|
+
import { STOP_CLASSES } from "./types";
|
|
3
|
+
import type { ParentStopReviewAdmission, StopRecommendationOptions, StopReviewEnvelope, StopReviewInstruction, StopReviewOptions, StopReviewReason, StopReviewResult } from "./types";
|
|
4
|
+
|
|
5
|
+
const record = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
6
|
+
const identifier = (value: unknown): value is string => typeof value === "string" && /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/.test(value);
|
|
7
|
+
const text = (value: unknown, max = Infinity): value is string => typeof value === "string" && value.trim().length > 0 && Buffer.byteLength(value) <= max;
|
|
8
|
+
const runtimeFlags = ["userRequestedStop", "terminal", "paused", "budgetExhausted", "usageLimited", "awaitingApproval", "nativeContinuationAllowed", "stopHookActive"] as const;
|
|
9
|
+
const goalStatuses = ["active", "complete", "paused", "cancelled", "blocked", "budget_limited", "usage_limited", "unknown"];
|
|
10
|
+
const stopReasons = ["end_turn", "user_stop", "cancelled", "error", "approval_wait", "budget_limit", "usage_limit", "unknown"];
|
|
11
|
+
const MIN_CERTAINTY = 0.9;
|
|
12
|
+
const MAX_NEGATIVE = 0.1;
|
|
13
|
+
|
|
14
|
+
export function isStopReviewEnvelope(value: unknown): value is StopReviewEnvelope {
|
|
15
|
+
if (!record(value) || value.schema !== "hooks.stop-review.v1" || !identifier(value.sessionId) ||
|
|
16
|
+
!identifier(value.turnId) || !identifier(value.inputRevision) || typeof value.capturedAt !== "string" ||
|
|
17
|
+
!Number.isFinite(Date.parse(value.capturedAt)) || !text(value.lastUserPrompt) ||
|
|
18
|
+
!text(value.lastAssistantMessage) || !record(value.runtime)) return false;
|
|
19
|
+
const runtime = value.runtime;
|
|
20
|
+
if (!runtimeFlags.every((key) => typeof runtime[key] === "boolean") ||
|
|
21
|
+
!stopReasons.includes(runtime.stopReason as string) || !Number.isSafeInteger(runtime.continuationCount) ||
|
|
22
|
+
(runtime.continuationCount as number) < 0) return false;
|
|
23
|
+
if (value.goal !== undefined && value.goal !== null && (!record(value.goal) || !identifier(value.goal.id) ||
|
|
24
|
+
!text(value.goal.objective) || !goalStatuses.includes(value.goal.status as string))) return false;
|
|
25
|
+
if (value.goalAvailability !== undefined && !["known", "unavailable"].includes(value.goalAvailability as string)) return false;
|
|
26
|
+
return true;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function isStopReviewInstruction(value: unknown): value is StopReviewInstruction {
|
|
30
|
+
if (!(record(value) && identifier(value.sourceId) && Number.isSafeInteger(value.version) && (value.version as number) > 0 &&
|
|
31
|
+
typeof value.digest === "string" && /^(sha256:)?[a-f0-9]{64}$/.test(value.digest) &&
|
|
32
|
+
text(value.continuationPrompt, 4_096) && record(value.questions))) return false;
|
|
33
|
+
const q = value.questions;
|
|
34
|
+
if (Object.keys(q).sort().join(",") !== "actionable,boundary,disposition" || !record(q.disposition) ||
|
|
35
|
+
q.disposition.type !== "choice" || !text(q.disposition.instructions, 16_000) || !record(q.disposition.criteria)) return false;
|
|
36
|
+
const criteria = q.disposition.criteria;
|
|
37
|
+
if (Object.keys(q.disposition).sort().join(",") !== "criteria,instructions,type" ||
|
|
38
|
+
Object.keys(criteria).length !== STOP_CLASSES.length || !STOP_CLASSES.every((key) => text(criteria[key], 4_096))) return false;
|
|
39
|
+
return [q.actionable, q.boundary].every((n) => record(n) && n.type === "noul" && text(n.instructions, 8_192) &&
|
|
40
|
+
Object.keys(n).sort().join(",") === "criteria,instructions,type" &&
|
|
41
|
+
record(n.criteria) && Object.keys(n.criteria).sort().join(",") === "false,true" && text(n.criteria.true, 4_096) && text(n.criteria.false, 4_096));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function stopPolicyGate(envelope: StopReviewEnvelope, now: number, maxContinuations = 1,
|
|
45
|
+
options: { assessmentOnlyAtCap?: boolean } = {}): StopReviewReason | null {
|
|
46
|
+
const runtime = envelope.runtime;
|
|
47
|
+
if (runtime.userRequestedStop || ["user_stop", "cancelled"].includes(runtime.stopReason)) return "user_stop";
|
|
48
|
+
if (runtime.terminal) return "terminal";
|
|
49
|
+
if (runtime.paused) return "paused";
|
|
50
|
+
if (runtime.budgetExhausted || runtime.stopReason === "budget_limit") return "budget_limit";
|
|
51
|
+
if (runtime.usageLimited || runtime.stopReason === "usage_limit") return "usage_limit";
|
|
52
|
+
if (runtime.awaitingApproval || runtime.stopReason === "approval_wait") return "approval_wait";
|
|
53
|
+
if (!runtime.nativeContinuationAllowed) return "native_continuation_unavailable";
|
|
54
|
+
if (runtime.stopReason === "error") return "runtime_failure";
|
|
55
|
+
if (runtime.stopReason !== "end_turn" || (envelope.goal === undefined && envelope.goalAvailability !== "unavailable") || envelope.goal?.status === "unknown") return "unknown_runtime";
|
|
56
|
+
if (envelope.goal && envelope.goal.status !== "active") return "goal_not_active";
|
|
57
|
+
if (runtime.stopHookActive || runtime.continuationCount > maxContinuations ||
|
|
58
|
+
(runtime.continuationCount === maxContinuations && !options.assessmentOnlyAtCap)) return "recursion_guard";
|
|
59
|
+
const age = now - Date.parse(envelope.capturedAt);
|
|
60
|
+
if (!Number.isFinite(now) || age > 120_000 || age < -30_000) return "stale_input";
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The only authority is the native runtime; this function never delivers a prompt or resumes a goal. */
|
|
65
|
+
export async function reviewStop(input: unknown, options: StopReviewOptions): Promise<StopReviewResult> {
|
|
66
|
+
return assessStop(input, options, options.isCurrent);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The parent owns all live-state reads and final atomic admission; the child only recommends. */
|
|
70
|
+
export async function recommendStop(input: unknown, options: StopRecommendationOptions): Promise<StopReviewResult> {
|
|
71
|
+
if (options.admission?.mode !== "parent_final_cas" || !["sumi", "opencode"].includes(options.admission.harness)) {
|
|
72
|
+
return { schema: "hooks.stop-review-result.v1", action: "unavailable", reason: "invalid_configuration" };
|
|
73
|
+
}
|
|
74
|
+
const result = await assessStop(input, options, undefined, options.admission);
|
|
75
|
+
const settlement = isStopReviewEnvelope(input) && input.goal?.status === "active" ? settlementFor(result) : "none";
|
|
76
|
+
return { ...result, admission: { mode: "parent_final_cas", harness: options.admission.harness, settlement } };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Certification is narrower than allowing a stop; the native parent owns actual goal settlement. */
|
|
80
|
+
export function settlementFor(result: StopReviewResult): "complete" | "blocked" | "none" {
|
|
81
|
+
const a = result.assessment;
|
|
82
|
+
if (result.action !== "allow_stop" || result.reason !== "classified_stop" || !a ||
|
|
83
|
+
a.confidence < MIN_CERTAINTY || a.probabilities[a.classification] < MIN_CERTAINTY || a.actionableProbability > MAX_NEGATIVE) return "none";
|
|
84
|
+
if (a.classification === "complete" && a.boundaryProbability <= MAX_NEGATIVE) return "complete";
|
|
85
|
+
if (["blocked_permission", "blocked_external", "blocked_environment", "needs_user_input"].includes(a.classification) &&
|
|
86
|
+
a.boundaryProbability >= MIN_CERTAINTY) return "blocked";
|
|
87
|
+
return "none";
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function assessStop(input: unknown, options: StopReviewOptions | StopRecommendationOptions,
|
|
91
|
+
isCurrent?: StopReviewOptions["isCurrent"], admission?: ParentStopReviewAdmission): Promise<StopReviewResult> {
|
|
92
|
+
const empty = (reason: StopReviewReason): StopReviewResult => ({ schema: "hooks.stop-review-result.v1", action: "allow_stop", reason });
|
|
93
|
+
if (!isStopReviewEnvelope(input)) return empty("invalid_input");
|
|
94
|
+
const envelope = structuredClone(input);
|
|
95
|
+
const base = {
|
|
96
|
+
schema: "hooks.stop-review-result.v1" as const,
|
|
97
|
+
sessionId: envelope.sessionId, turnId: envelope.turnId, inputRevision: envelope.inputRevision,
|
|
98
|
+
};
|
|
99
|
+
const stop = (reason: StopReviewReason): StopReviewResult => ({ ...base, action: "allow_stop", reason });
|
|
100
|
+
const max = options.maxContinuations ?? 1;
|
|
101
|
+
if (!Number.isInteger(max) || max < 1 || max > 3) return stop("invalid_configuration");
|
|
102
|
+
const now = options.now ?? Date.now;
|
|
103
|
+
const parentGuarded = admission?.mode === "parent_final_cas" && ["sumi", "opencode"].includes(admission.harness);
|
|
104
|
+
const gateOptions = { assessmentOnlyAtCap: parentGuarded };
|
|
105
|
+
const gate = stopPolicyGate(envelope, now(), max, gateOptions);
|
|
106
|
+
if (gate) return stop(gate);
|
|
107
|
+
if (!isStopReviewInstruction(options.instruction)) return stop("instruction_unavailable");
|
|
108
|
+
if (options.externalContentApproved !== true) return stop("external_content_unapproved");
|
|
109
|
+
const current = async () => {
|
|
110
|
+
let timer: ReturnType<typeof setTimeout>;
|
|
111
|
+
try {
|
|
112
|
+
return await Promise.race([
|
|
113
|
+
Promise.resolve().then(() => typeof isCurrent === "function" && isCurrent(structuredClone(envelope))).then((value) => value === true).catch(() => false),
|
|
114
|
+
new Promise<boolean>((resolve) => { timer = setTimeout(() => resolve(false), 500); }),
|
|
115
|
+
]);
|
|
116
|
+
} finally { clearTimeout(timer!); }
|
|
117
|
+
};
|
|
118
|
+
if (!parentGuarded && !await current()) return stop("stale_input");
|
|
119
|
+
let assessed;
|
|
120
|
+
try { assessed = await (options.evaluate ?? evaluateJev)(envelope, options); }
|
|
121
|
+
catch { return { ...base, action: "unavailable", reason: "provider_unavailable" }; }
|
|
122
|
+
// Capture can change while HTTP is outstanding. Never apply a decision to a new turn/context/goal.
|
|
123
|
+
if ((!parentGuarded && !await current()) || stopPolicyGate(envelope, now(), max, gateOptions)) return stop("stale_input");
|
|
124
|
+
if (!record(assessed) || typeof assessed.ok !== "boolean") return { ...base, action: "unavailable", reason: "invalid_provider_response" };
|
|
125
|
+
if (!assessed.ok) return { ...base, action: "unavailable", reason: assessed.reason, ...(assessed.httpStatus === undefined ? {} : { httpStatus: assessed.httpStatus }) };
|
|
126
|
+
const assessment = assessed.assessment;
|
|
127
|
+
if (!record(assessment)) return { ...base, action: "unavailable", reason: "invalid_provider_response" };
|
|
128
|
+
// Even an alternate process transport must satisfy the same provider response contract.
|
|
129
|
+
const checked = parseJevAssessment({ model: assessment.model, answers: {
|
|
130
|
+
disposition: { type: "choice", choice: assessment.classification, confidence: assessment.confidence, probabilities: assessment.probabilities },
|
|
131
|
+
actionable: { type: "noul", noul: assessment.actionableProbability }, boundary: { type: "noul", noul: assessment.boundaryProbability },
|
|
132
|
+
}, usage: { input_tokens: assessment.inputTokens, output_tokens: assessment.outputTokens } });
|
|
133
|
+
if (!checked) return { ...base, action: "unavailable", reason: "invalid_provider_response" };
|
|
134
|
+
const provenance = { sourceId: options.instruction.sourceId, version: options.instruction.version, digest: options.instruction.digest };
|
|
135
|
+
const result = { ...base, assessment, classification: assessment.classification, instruction: provenance };
|
|
136
|
+
if (assessment.classification !== "actionable_remaining") {
|
|
137
|
+
return { ...result, action: "allow_stop", reason: assessment.classification === "uncertain" ? "classification_uncertain" : "classified_stop" };
|
|
138
|
+
}
|
|
139
|
+
if (envelope.runtime.continuationCount >= max) return { ...result, action: "allow_stop", reason: "continuation_limit" };
|
|
140
|
+
if (assessment.confidence < MIN_CERTAINTY || assessment.probabilities.actionable_remaining < MIN_CERTAINTY ||
|
|
141
|
+
assessment.actionableProbability < MIN_CERTAINTY || assessment.boundaryProbability > MAX_NEGATIVE) {
|
|
142
|
+
return { ...result, action: "allow_stop", reason: "classification_uncertain" };
|
|
143
|
+
}
|
|
144
|
+
return { ...result, action: "continue", reason: "actionable_remaining", continuationPrompt: options.instruction.continuationPrompt };
|
|
145
|
+
}
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { isAbsolute, join } from "node:path";
|
|
5
|
+
import { getEffectiveDataRoot, getHomeDir } from "../../../src/lib/app-home";
|
|
6
|
+
import { restoreStopReviewClientContext, stopReviewClientContextRefused } from "../../../src/lib/stop-review-context";
|
|
7
|
+
import { nativeChildEnv } from "../../../src/lib/native-child-env";
|
|
8
|
+
import { buildJevRequest, evaluateJev, parseJevAssessment } from "./jev";
|
|
9
|
+
import { isStopReviewEnvelope, isStopReviewInstruction, recommendStop, reviewStop, stopPolicyGate } from "./policy";
|
|
10
|
+
import type { JevResult, ParentStopReviewAdmission, StopReviewEnvelope, StopReviewInstruction, StopReviewNativeTarget, StopReviewResult } from "./types";
|
|
11
|
+
|
|
12
|
+
export interface StopReviewRuntimeConfiguration {
|
|
13
|
+
schema: "hooks.stop-review-runtime.v1";
|
|
14
|
+
enabled: true;
|
|
15
|
+
model: string;
|
|
16
|
+
instruction: { id: string; version: number; sha256: string };
|
|
17
|
+
commands: { instructions: string; secrets: string };
|
|
18
|
+
secretsReference: string;
|
|
19
|
+
harness?: "codex" | "claude" | "sumi" | "opencode";
|
|
20
|
+
codexHome?: string;
|
|
21
|
+
codexSocketPath?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface RuntimeCommand {
|
|
25
|
+
command: string;
|
|
26
|
+
args: string[];
|
|
27
|
+
input?: string;
|
|
28
|
+
timeoutMs: number;
|
|
29
|
+
maxOutputBytes: number;
|
|
30
|
+
env: NodeJS.ProcessEnv;
|
|
31
|
+
}
|
|
32
|
+
export interface RuntimeCommandResult { ok: boolean; stdout?: string; exitCode?: number | null; }
|
|
33
|
+
export type RuntimeCommandRunner = (command: RuntimeCommand) => Promise<RuntimeCommandResult>;
|
|
34
|
+
const record = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
|
|
35
|
+
const sha256 = (value: string | Buffer) => createHash("sha256").update(value).digest("hex");
|
|
36
|
+
const safePath = (value: unknown): value is string => typeof value === "string" && isAbsolute(value) && value.length <= 4096 && !/[\u0000-\u001f]/.test(value);
|
|
37
|
+
|
|
38
|
+
export function parseRuntimeConfiguration(value: unknown): StopReviewRuntimeConfiguration | null {
|
|
39
|
+
if (!record(value) || value.schema !== "hooks.stop-review-runtime.v1" || value.enabled !== true ||
|
|
40
|
+
typeof value.model !== "string" || !/^jev-[a-zA-Z0-9._-]{1,100}$/.test(value.model) ||
|
|
41
|
+
!record(value.instruction) || typeof value.instruction.id !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/.test(value.instruction.id) ||
|
|
42
|
+
!Number.isSafeInteger(value.instruction.version) || (value.instruction.version as number) < 1 ||
|
|
43
|
+
typeof value.instruction.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(value.instruction.sha256) ||
|
|
44
|
+
!record(value.commands) || !safePath(value.commands.instructions) || !safePath(value.commands.secrets) ||
|
|
45
|
+
typeof value.secretsReference !== "string" || value.secretsReference.length > 256 ||
|
|
46
|
+
!/^[a-zA-Z0-9][a-zA-Z0-9_.-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9_.-]*){1,12}$/.test(value.secretsReference)) return null;
|
|
47
|
+
const allowed = ["schema", "enabled", "model", "instruction", "commands", "secretsReference", "harness", "codexHome", "codexSocketPath"];
|
|
48
|
+
if (!Object.keys(value).every((key) => allowed.includes(key)) ||
|
|
49
|
+
Object.keys(value.instruction).sort().join(",") !== "id,sha256,version" ||
|
|
50
|
+
Object.keys(value.commands).sort().join(",") !== "instructions,secrets" ||
|
|
51
|
+
(value.harness !== undefined && !["codex", "claude", "sumi", "opencode"].includes(value.harness as string)) ||
|
|
52
|
+
(value.codexHome !== undefined && !safePath(value.codexHome)) ||
|
|
53
|
+
(value.codexSocketPath !== undefined && !safePath(value.codexSocketPath))) return null;
|
|
54
|
+
return value as unknown as StopReviewRuntimeConfiguration;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function readPrivateConfiguration(path: string): unknown {
|
|
58
|
+
if (!safePath(path)) return null;
|
|
59
|
+
let fd: number | undefined;
|
|
60
|
+
try {
|
|
61
|
+
fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
62
|
+
const stat = fstatSync(fd);
|
|
63
|
+
if (!stat.isFile() || stat.size > 16_384 || (stat.mode & 0o022) !== 0 ||
|
|
64
|
+
(process.getuid && stat.uid !== process.getuid())) return null;
|
|
65
|
+
return JSON.parse(readFileSync(fd, "utf8"));
|
|
66
|
+
} catch { return null; }
|
|
67
|
+
finally { if (fd !== undefined) closeSync(fd); }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function loadNativeRuntimeConfiguration(env: NodeJS.ProcessEnv = process.env): StopReviewRuntimeConfiguration | null {
|
|
71
|
+
const path = env.HOOKS_STOP_REVIEW_CONFIG ?? join(getEffectiveDataRoot(env), "config", "stop-review.json");
|
|
72
|
+
return parseRuntimeConfiguration(readPrivateConfiguration(path));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Only this invocation's newly created helper process group may be bounded. */
|
|
76
|
+
export const runRuntimeCommand: RuntimeCommandRunner = (invocation) => new Promise((resolve) => {
|
|
77
|
+
let settled = false;
|
|
78
|
+
let bytes = 0;
|
|
79
|
+
let errorBytes = 0;
|
|
80
|
+
const chunks: Buffer[] = [];
|
|
81
|
+
let timer: ReturnType<typeof setTimeout>;
|
|
82
|
+
let child: ReturnType<typeof spawn> | undefined;
|
|
83
|
+
const finish = (result: RuntimeCommandResult) => {
|
|
84
|
+
if (settled) return;
|
|
85
|
+
settled = true; clearTimeout(timer);
|
|
86
|
+
resolve(result);
|
|
87
|
+
};
|
|
88
|
+
const abort = () => {
|
|
89
|
+
if (settled) return;
|
|
90
|
+
try {
|
|
91
|
+
if (child?.pid && process.platform !== "win32") process.kill(-child.pid, "SIGKILL");
|
|
92
|
+
else child?.kill("SIGKILL");
|
|
93
|
+
} catch { /* This helper may already have exited. Never discover or signal another process. */ }
|
|
94
|
+
child?.stdin?.destroy(); child?.stdout?.destroy(); child?.stderr?.destroy();
|
|
95
|
+
finish({ ok: false });
|
|
96
|
+
};
|
|
97
|
+
try {
|
|
98
|
+
const command = realpathSync(invocation.command);
|
|
99
|
+
const stat = lstatSync(command);
|
|
100
|
+
if (!stat.isFile() || (stat.mode & 0o022) !== 0 || (process.getuid && ![0, process.getuid()].includes(stat.uid))) return finish({ ok: false });
|
|
101
|
+
child = spawn(command, invocation.args, { shell: false, detached: process.platform !== "win32",
|
|
102
|
+
cwd: getHomeDir(invocation.env), env: invocation.env, stdio: ["pipe", "pipe", "pipe"] });
|
|
103
|
+
timer = setTimeout(abort, invocation.timeoutMs);
|
|
104
|
+
child.stdout!.on("data", (chunk: Buffer) => {
|
|
105
|
+
bytes += chunk.length;
|
|
106
|
+
if (bytes > invocation.maxOutputBytes) abort(); else chunks.push(Buffer.from(chunk));
|
|
107
|
+
});
|
|
108
|
+
child.stderr!.on("data", (chunk: Buffer) => { errorBytes += chunk.length; if (errorBytes > 4096) abort(); });
|
|
109
|
+
child.stdin!.on("error", abort);
|
|
110
|
+
child.on("error", () => finish({ ok: false }));
|
|
111
|
+
child.on("close", (code) => finish({ ok: code === 0, exitCode: code, ...(code === 0 ? { stdout: Buffer.concat(chunks).toString("utf8") } : {}) }));
|
|
112
|
+
child.stdin!.end(invocation.input ?? "");
|
|
113
|
+
} catch { finish({ ok: false }); }
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
function helperEnvironment(env: NodeJS.ProcessEnv, app: "instructions" | "secrets"): NodeJS.ProcessEnv {
|
|
117
|
+
// buildHookEnv exposes non-secret aliases to hook code. Restore only the
|
|
118
|
+
// owning resolver's exact selectors when invoking a trusted app consumer.
|
|
119
|
+
// Keep an explicit direct selector (even a blank one) rather than falling
|
|
120
|
+
// back to another profile/reference carried by an older alias.
|
|
121
|
+
const restored = { ...env, ...restoreStopReviewClientContext(env) };
|
|
122
|
+
return nativeChildEnv(restored, { HOME: getHomeDir(env), NO_COLOR: "1" }, (name) =>
|
|
123
|
+
["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) ||
|
|
124
|
+
// Instructions' reference resolver bootstraps through Secrets. Preserve a
|
|
125
|
+
// declared Secrets reference too, including its terminal refusal semantics.
|
|
126
|
+
name === "HASNA_SECRETS_API_KEY_REF" || name === "HASNA_SECRETS_API_URL" ||
|
|
127
|
+
name.startsWith(`HASNA_${app.toUpperCase()}_`) || (app === "instructions" && name.startsWith("HASNA_CONFIGS_")));
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export type PinnedStopReviewInstruction = StopReviewInstruction & { sourceContent: string };
|
|
131
|
+
|
|
132
|
+
function instructionFromContent(content: string, config: StopReviewRuntimeConfiguration): PinnedStopReviewInstruction | null {
|
|
133
|
+
try {
|
|
134
|
+
if (sha256(content) !== config.instruction.sha256) return null;
|
|
135
|
+
const body = JSON.parse(content);
|
|
136
|
+
if (!record(body) || body.schema !== "hooks.stop-review-instructions.v1" ||
|
|
137
|
+
Object.keys(body).sort().join(",") !== "continuationPrompt,questions,schema") return null;
|
|
138
|
+
const instruction = { sourceId: config.instruction.id, version: config.instruction.version, digest: config.instruction.sha256,
|
|
139
|
+
questions: body.questions, continuationPrompt: body.continuationPrompt, sourceContent: content };
|
|
140
|
+
return isStopReviewInstruction(instruction) ? instruction as PinnedStopReviewInstruction : null;
|
|
141
|
+
} catch { return null; }
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export async function loadPinnedInstruction(config: StopReviewRuntimeConfiguration, env: NodeJS.ProcessEnv,
|
|
145
|
+
run: RuntimeCommandRunner = runRuntimeCommand): Promise<PinnedStopReviewInstruction | null> {
|
|
146
|
+
// A local-mode request is a refusal, never silently stripped to select a different store.
|
|
147
|
+
if (stopReviewClientContextRefused(env)) return null;
|
|
148
|
+
const result = await run({ command: config.commands.instructions, args: ["show", config.instruction.id, "--format", "json"],
|
|
149
|
+
timeoutMs: 4000, maxOutputBytes: 65_536, env: helperEnvironment(env, "instructions") });
|
|
150
|
+
if (!result.ok || typeof result.stdout !== "string") return null;
|
|
151
|
+
try {
|
|
152
|
+
const row = JSON.parse(result.stdout);
|
|
153
|
+
if (!record(row) || row.id !== config.instruction.id || row.version !== config.instruction.version ||
|
|
154
|
+
row.category !== "rules" || typeof row.content !== "string" || sha256(row.content) !== config.instruction.sha256) return null;
|
|
155
|
+
return instructionFromContent(row.content, config);
|
|
156
|
+
} catch { return null; }
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export async function scanStopReviewContent(envelope: StopReviewEnvelope, instruction: StopReviewInstruction,
|
|
160
|
+
config: StopReviewRuntimeConfiguration, env: NodeJS.ProcessEnv, run: RuntimeCommandRunner = runRuntimeCommand): Promise<boolean> {
|
|
161
|
+
if (stopReviewClientContextRefused(env)) return false;
|
|
162
|
+
const input = JSON.stringify(buildJevRequest(envelope, { model: config.model, instruction }));
|
|
163
|
+
const bytes = Buffer.byteLength(input);
|
|
164
|
+
const result = await run({ command: config.commands.secrets,
|
|
165
|
+
args: ["scan", "input", "-", "--max-bytes", String(bytes), "--timeout-ms", "1500", "--json"],
|
|
166
|
+
input, timeoutMs: 2500, maxOutputBytes: 32_768, env: helperEnvironment(env, "secrets") });
|
|
167
|
+
if (!result.ok || typeof result.stdout !== "string") return false;
|
|
168
|
+
try {
|
|
169
|
+
const receipt = JSON.parse(result.stdout);
|
|
170
|
+
return record(receipt) && receipt.schema === "open-secrets.exposure-scan.v1" && receipt.findingCount === 0 &&
|
|
171
|
+
receipt.truncated === false && Array.isArray(receipt.findings) && receipt.findings.length === 0 && record(receipt.stats) &&
|
|
172
|
+
receipt.stats.filesScanned === 1 && receipt.stats.filesSkipped === 0 && receipt.stats.bytesScanned === bytes &&
|
|
173
|
+
Array.isArray(receipt.stats.errors) && receipt.stats.errors.length === 0;
|
|
174
|
+
} catch { return false; }
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Append-only metadata. No prompt, goal objective, transcript or credential is persisted here. */
|
|
178
|
+
export function claimStopReviewTurn(envelope: StopReviewEnvelope, env: NodeJS.ProcessEnv = process.env,
|
|
179
|
+
requestHash?: string, instructionDigest?: string, admission?: ParentStopReviewAdmission,
|
|
180
|
+
nativeTarget?: StopReviewNativeTarget): "claimed" | "already_claimed" | "unavailable" {
|
|
181
|
+
let fd: number | undefined;
|
|
182
|
+
try {
|
|
183
|
+
const root = getEffectiveDataRoot(env);
|
|
184
|
+
const directory = join(root, "state", "stop-review", "turn-claims");
|
|
185
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
186
|
+
// Refuse a redirected or shared claim directory; never clean up a conflicting claim.
|
|
187
|
+
if (realpathSync(directory) !== directory) return "unavailable";
|
|
188
|
+
const stat = lstatSync(directory);
|
|
189
|
+
if (!stat.isDirectory() || (stat.mode & 0o077) !== 0 || (process.getuid && stat.uid !== process.getuid())) return "unavailable";
|
|
190
|
+
const key = sha256(`${envelope.sessionId}\0${envelope.turnId}`);
|
|
191
|
+
fd = openSync(join(directory, `${key}.json`), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
192
|
+
const body = JSON.stringify({ schema: "hooks.stop-review-claim.v1", sessionHash: sha256(envelope.sessionId),
|
|
193
|
+
turnHash: sha256(envelope.turnId), revisionHash: sha256(envelope.inputRevision), requestHash, instructionDigest,
|
|
194
|
+
admissionMode: admission ? `${admission.harness}:parent_final_cas` : "native",
|
|
195
|
+
nativeTarget,
|
|
196
|
+
createdAt: new Date().toISOString() }) + "\n";
|
|
197
|
+
writeFileSync(fd, body); fsyncSync(fd);
|
|
198
|
+
return "claimed";
|
|
199
|
+
} catch (error) { return (error as NodeJS.ErrnoException).code === "EEXIST" ? "already_claimed" : "unavailable"; }
|
|
200
|
+
finally { if (fd !== undefined) closeSync(fd); }
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function providerClaimMatches(envelope: StopReviewEnvelope, requestHash: string, instructionDigest: string, env: NodeJS.ProcessEnv,
|
|
204
|
+
admission: ParentStopReviewAdmission | undefined, nativeTarget: StopReviewNativeTarget): boolean {
|
|
205
|
+
const path = join(getEffectiveDataRoot(env), "state", "stop-review", "turn-claims", `${sha256(`${envelope.sessionId}\0${envelope.turnId}`)}.json`);
|
|
206
|
+
const claim = readPrivateConfiguration(path);
|
|
207
|
+
return record(claim) && claim.schema === "hooks.stop-review-claim.v1" && claim.sessionHash === sha256(envelope.sessionId) &&
|
|
208
|
+
claim.turnHash === sha256(envelope.turnId) && claim.revisionHash === sha256(envelope.inputRevision) &&
|
|
209
|
+
claim.requestHash === requestHash && claim.instructionDigest === instructionDigest &&
|
|
210
|
+
claim.nativeTarget === nativeTarget &&
|
|
211
|
+
claim.admissionMode === (admission ? `${admission.harness}:parent_final_cas` : "native");
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Provider-only child. It cannot inject a prompt or change native goal/session state. */
|
|
215
|
+
export async function runJevProviderChild(raw: unknown, env: NodeJS.ProcessEnv = process.env): Promise<JevResult> {
|
|
216
|
+
if (!record(raw) || raw.schema !== "hooks.stop-review-provider.v1" || !isStopReviewEnvelope(raw.envelope) ||
|
|
217
|
+
typeof raw.instructionContent !== "string") return { ok: false, reason: "invalid_input" };
|
|
218
|
+
const config = loadNativeRuntimeConfiguration(env);
|
|
219
|
+
if (!config) return { ok: false, reason: "invalid_configuration" };
|
|
220
|
+
if (!["codex", "claude", "sumi", "opencode"].includes(raw.nativeTarget as string) ||
|
|
221
|
+
(config.harness !== undefined && config.harness !== raw.nativeTarget)) return { ok: false, reason: "invalid_configuration" };
|
|
222
|
+
const nativeTarget = raw.nativeTarget as StopReviewNativeTarget;
|
|
223
|
+
if (raw.admission !== undefined && (!record(raw.admission) || raw.admission.mode !== "parent_final_cas" ||
|
|
224
|
+
!["sumi", "opencode"].includes(raw.admission.harness as string) || Object.keys(raw.admission).sort().join(",") !== "harness,mode" ||
|
|
225
|
+
nativeTarget !== raw.admission.harness)) return { ok: false, reason: "invalid_configuration" };
|
|
226
|
+
const admission = raw.admission as ParentStopReviewAdmission | undefined;
|
|
227
|
+
const gate = stopPolicyGate(raw.envelope, Date.now(), 1, { assessmentOnlyAtCap: !!admission });
|
|
228
|
+
if (gate) return { ok: false, reason: gate };
|
|
229
|
+
const instruction = instructionFromContent(raw.instructionContent, config);
|
|
230
|
+
if (!instruction) return { ok: false, reason: "instruction_unavailable" };
|
|
231
|
+
const requestHash = sha256(JSON.stringify(buildJevRequest(raw.envelope, { model: config.model, instruction })));
|
|
232
|
+
if (!providerClaimMatches(raw.envelope, requestHash, instruction.digest, env, admission, nativeTarget)) return { ok: false, reason: "claim_unavailable" };
|
|
233
|
+
return evaluateJev(raw.envelope, { apiKey: env.TYPESAFE_API_KEY, model: config.model, instruction, timeoutMs: 8000 });
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export async function evaluateThroughSecrets(envelope: StopReviewEnvelope, instruction: PinnedStopReviewInstruction,
|
|
237
|
+
config: StopReviewRuntimeConfiguration, env: NodeJS.ProcessEnv, entrypoint: string,
|
|
238
|
+
run: RuntimeCommandRunner = runRuntimeCommand, admission?: ParentStopReviewAdmission,
|
|
239
|
+
nativeTarget?: StopReviewNativeTarget): Promise<JevResult> {
|
|
240
|
+
if (stopReviewClientContextRefused(env)) return { ok: false, reason: "invalid_configuration" };
|
|
241
|
+
if (!safePath(entrypoint)) return { ok: false, reason: "invalid_configuration" };
|
|
242
|
+
let canonical: string;
|
|
243
|
+
try {
|
|
244
|
+
canonical = realpathSync(entrypoint);
|
|
245
|
+
const stat = lstatSync(canonical);
|
|
246
|
+
if (!stat.isFile() || (stat.mode & 0o022) !== 0 || (process.getuid && ![0, process.getuid()].includes(stat.uid))) return { ok: false, reason: "invalid_configuration" };
|
|
247
|
+
} catch { return { ok: false, reason: "invalid_configuration" }; }
|
|
248
|
+
const result = await run({ command: config.commands.secrets,
|
|
249
|
+
args: ["exec", config.secretsReference, "--as", "TYPESAFE_API_KEY", "--", process.execPath,
|
|
250
|
+
"--config=/dev/null", "--no-env-file", "--no-macros", "--no-install", canonical, "--assess-envelope"],
|
|
251
|
+
input: JSON.stringify({ schema: "hooks.stop-review-provider.v1", envelope, instructionContent: instruction.sourceContent, admission, nativeTarget }),
|
|
252
|
+
timeoutMs: 10_000, maxOutputBytes: 16_384, env: helperEnvironment(env, "secrets") });
|
|
253
|
+
if (!result.ok || !result.stdout) return { ok: false, reason: "provider_unavailable" };
|
|
254
|
+
try {
|
|
255
|
+
const value = JSON.parse(result.stdout);
|
|
256
|
+
if (!record(value)) return { ok: false, reason: "invalid_provider_response" };
|
|
257
|
+
if (value.ok === true && record(value.assessment)) {
|
|
258
|
+
const a = value.assessment;
|
|
259
|
+
const assessment = parseJevAssessment({ model: a.model, answers: {
|
|
260
|
+
disposition: { type: "choice", choice: a.classification, confidence: a.confidence, probabilities: a.probabilities },
|
|
261
|
+
actionable: { type: "noul", noul: a.actionableProbability }, boundary: { type: "noul", noul: a.boundaryProbability },
|
|
262
|
+
}, usage: { input_tokens: a.inputTokens, output_tokens: a.outputTokens } });
|
|
263
|
+
return assessment ? { ok: true, assessment } : { ok: false, reason: "invalid_provider_response" };
|
|
264
|
+
}
|
|
265
|
+
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"];
|
|
266
|
+
if (value.ok !== false || !allowed.includes(value.reason as string)) return { ok: false, reason: "invalid_provider_response" };
|
|
267
|
+
return { ok: false, reason: value.reason as StopReviewResult["reason"],
|
|
268
|
+
...(Number.isInteger(value.httpStatus) && (value.httpStatus as number) >= 100 && (value.httpStatus as number) <= 599 ? { httpStatus: value.httpStatus as number } : {}) };
|
|
269
|
+
} catch { return { ok: false, reason: "invalid_provider_response" }; }
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
export async function reviewNativeEnvelope(envelope: StopReviewEnvelope,
|
|
273
|
+
isCurrent: (expected: StopReviewEnvelope) => boolean | Promise<boolean>,
|
|
274
|
+
env: NodeJS.ProcessEnv = process.env, entrypoint = process.argv[1], nativeTarget?: "codex" | "claude"): Promise<StopReviewResult> {
|
|
275
|
+
return reviewRuntimeEnvelope(envelope, env, entrypoint, nativeTarget, isCurrent);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** The native parent checks freshness inside its durable continuation-admission transaction. */
|
|
279
|
+
export async function reviewParentGuardedEnvelope(raw: unknown, env: NodeJS.ProcessEnv = process.env,
|
|
280
|
+
entrypoint = process.argv[1], nativeTarget: ParentStopReviewAdmission["harness"] = "sumi"): Promise<StopReviewResult> {
|
|
281
|
+
const result = await reviewRuntimeEnvelope(raw, env, entrypoint, nativeTarget);
|
|
282
|
+
return { ...result, admission: result.admission ?? { mode: "parent_final_cas", harness: nativeTarget, settlement: "none" } };
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
async function reviewRuntimeEnvelope(raw: unknown, env: NodeJS.ProcessEnv, entrypoint: string | undefined,
|
|
286
|
+
nativeTarget: StopReviewNativeTarget | undefined, isCurrent?: (expected: StopReviewEnvelope) => boolean | Promise<boolean>): Promise<StopReviewResult> {
|
|
287
|
+
if (!isStopReviewEnvelope(raw)) return { schema: "hooks.stop-review-result.v1", action: "unavailable", reason: "invalid_input" };
|
|
288
|
+
const envelope = structuredClone(raw);
|
|
289
|
+
const base = { schema: "hooks.stop-review-result.v1" as const, sessionId: envelope.sessionId, turnId: envelope.turnId, inputRevision: envelope.inputRevision };
|
|
290
|
+
const unavailable = (reason: StopReviewResult["reason"]): StopReviewResult => ({ ...base, action: "unavailable", reason });
|
|
291
|
+
const gate = stopPolicyGate(envelope, Date.now(), 1, { assessmentOnlyAtCap: !isCurrent });
|
|
292
|
+
if (gate) return { ...base, action: "allow_stop", reason: gate };
|
|
293
|
+
const config = loadNativeRuntimeConfiguration(env);
|
|
294
|
+
if (!config) return unavailable("invalid_configuration");
|
|
295
|
+
if (!nativeTarget || (config.harness !== undefined && config.harness !== nativeTarget)) return unavailable("invalid_configuration");
|
|
296
|
+
if (!isCurrent && nativeTarget !== "sumi" && nativeTarget !== "opencode") return unavailable("invalid_configuration");
|
|
297
|
+
if (!safePath(entrypoint)) return unavailable("invalid_configuration");
|
|
298
|
+
const instruction = await loadPinnedInstruction(config, env);
|
|
299
|
+
if (!instruction) return unavailable("instruction_unavailable");
|
|
300
|
+
if (!await scanStopReviewContent(envelope, instruction, config, env)) return unavailable("content_scan_failed");
|
|
301
|
+
const requestHash = sha256(JSON.stringify(buildJevRequest(envelope, { model: config.model, instruction })));
|
|
302
|
+
const admission: ParentStopReviewAdmission | undefined = isCurrent ? undefined : { mode: "parent_final_cas", harness: nativeTarget as ParentStopReviewAdmission["harness"] };
|
|
303
|
+
const claimed = claimStopReviewTurn(envelope, env, requestHash, instruction.digest, admission, nativeTarget);
|
|
304
|
+
if (claimed !== "claimed") return unavailable(claimed === "already_claimed" ? "turn_already_reviewed" : "claim_unavailable");
|
|
305
|
+
const options = { model: config.model, instruction, externalContentApproved: true, timeoutMs: 8000,
|
|
306
|
+
evaluate: () => evaluateThroughSecrets(envelope, instruction, config, env, entrypoint, runRuntimeCommand, admission, nativeTarget) };
|
|
307
|
+
return isCurrent ? reviewStop(envelope, { ...options, isCurrent })
|
|
308
|
+
: recommendStop(envelope, { ...options, admission: admission! });
|
|
309
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/** Runtime facts come from the harness adapter, never from transcript/model text. */
|
|
2
|
+
export interface StopReviewEnvelope {
|
|
3
|
+
schema: "hooks.stop-review.v1";
|
|
4
|
+
sessionId: string;
|
|
5
|
+
turnId: string;
|
|
6
|
+
inputRevision: string;
|
|
7
|
+
capturedAt: string;
|
|
8
|
+
lastUserPrompt: string;
|
|
9
|
+
lastAssistantMessage: string;
|
|
10
|
+
/** null = confirmed absent/not applicable; undefined = adapter could not establish goal state. */
|
|
11
|
+
goal?: {
|
|
12
|
+
id: string;
|
|
13
|
+
objective: string;
|
|
14
|
+
status: "active" | "complete" | "paused" | "cancelled" | "blocked" | "budget_limited" | "usage_limited" | "unknown";
|
|
15
|
+
} | null;
|
|
16
|
+
/** A native adapter can establish that this harness has no goal API; transcript text cannot set this. */
|
|
17
|
+
goalAvailability?: "known" | "unavailable";
|
|
18
|
+
runtime: {
|
|
19
|
+
stopReason: "end_turn" | "user_stop" | "cancelled" | "error" | "approval_wait" | "budget_limit" | "usage_limit" | "unknown";
|
|
20
|
+
userRequestedStop: boolean;
|
|
21
|
+
terminal: boolean;
|
|
22
|
+
paused: boolean;
|
|
23
|
+
budgetExhausted: boolean;
|
|
24
|
+
usageLimited: boolean;
|
|
25
|
+
awaitingApproval: boolean;
|
|
26
|
+
nativeContinuationAllowed: boolean;
|
|
27
|
+
stopHookActive: boolean;
|
|
28
|
+
continuationCount: number;
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export const STOP_CLASSES = [
|
|
33
|
+
"complete", "actionable_remaining", "blocked_permission", "blocked_external",
|
|
34
|
+
"blocked_environment", "needs_user_input", "uncertain",
|
|
35
|
+
] as const;
|
|
36
|
+
export type StopClassification = (typeof STOP_CLASSES)[number];
|
|
37
|
+
|
|
38
|
+
/** Managed Instructions content is supplied by the owning adapter/resolver. */
|
|
39
|
+
export interface StopReviewInstruction {
|
|
40
|
+
sourceId: string;
|
|
41
|
+
version: number;
|
|
42
|
+
digest: string;
|
|
43
|
+
questions: {
|
|
44
|
+
disposition: { type: "choice"; instructions: string; criteria: Record<StopClassification, string> };
|
|
45
|
+
actionable: { type: "noul"; instructions: string; criteria: { true: string; false: string } };
|
|
46
|
+
boundary: { type: "noul"; instructions: string; criteria: { true: string; false: string } };
|
|
47
|
+
};
|
|
48
|
+
continuationPrompt: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface JevAssessment {
|
|
52
|
+
classification: StopClassification;
|
|
53
|
+
confidence: number;
|
|
54
|
+
probabilities: Record<StopClassification, number>;
|
|
55
|
+
actionableProbability: number;
|
|
56
|
+
boundaryProbability: number;
|
|
57
|
+
model: string;
|
|
58
|
+
inputTokens: number;
|
|
59
|
+
outputTokens: number;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export type StopReviewReason =
|
|
63
|
+
| "invalid_input" | "user_stop" | "terminal" | "paused" | "budget_limit" | "usage_limit"
|
|
64
|
+
| "approval_wait" | "native_continuation_unavailable" | "runtime_failure" | "unknown_runtime"
|
|
65
|
+
| "goal_not_active" | "recursion_guard" | "continuation_limit" | "stale_input" | "instruction_unavailable"
|
|
66
|
+
| "external_content_unapproved" | "credential_unavailable" | "invalid_configuration"
|
|
67
|
+
| "request_too_large" | "response_too_large" | "request_timeout" | "provider_unavailable"
|
|
68
|
+
| "credential_rejected" | "provider_rate_limited" | "provider_request_refused" | "provider_overloaded"
|
|
69
|
+
| "content_scan_failed" | "turn_already_reviewed" | "claim_unavailable"
|
|
70
|
+
| "invalid_provider_response" | "classification_uncertain" | "classified_stop" | "actionable_remaining";
|
|
71
|
+
|
|
72
|
+
export interface StopReviewResult {
|
|
73
|
+
schema: "hooks.stop-review-result.v1";
|
|
74
|
+
action: "allow_stop" | "continue" | "unavailable";
|
|
75
|
+
reason: StopReviewReason;
|
|
76
|
+
sessionId?: string;
|
|
77
|
+
turnId?: string;
|
|
78
|
+
inputRevision?: string;
|
|
79
|
+
classification?: StopClassification;
|
|
80
|
+
assessment?: JevAssessment;
|
|
81
|
+
instruction?: { sourceId: string; version: number; digest: string };
|
|
82
|
+
continuationPrompt?: string;
|
|
83
|
+
httpStatus?: number;
|
|
84
|
+
/** A recommendation only; the named parent must perform its final native transaction guard. */
|
|
85
|
+
admission?: ParentStopReviewAdmission & { settlement: "complete" | "blocked" | "none" };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export type JevResult = { ok: true; assessment: JevAssessment } | { ok: false; reason: StopReviewReason; httpStatus?: number };
|
|
89
|
+
|
|
90
|
+
/** Only the HTTP call is used; runtime-specific fetch helpers are not required. */
|
|
91
|
+
export type JevFetch = (...args: Parameters<typeof globalThis.fetch>) => ReturnType<typeof globalThis.fetch>;
|
|
92
|
+
|
|
93
|
+
export interface JevOptions {
|
|
94
|
+
apiKey?: string;
|
|
95
|
+
model: string;
|
|
96
|
+
instruction: StopReviewInstruction;
|
|
97
|
+
timeoutMs?: number;
|
|
98
|
+
fetch?: JevFetch;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export interface StopReviewOptions extends JevOptions {
|
|
102
|
+
/** Set only after the owning consumer's disclosure/credential-content checks. */
|
|
103
|
+
externalContentApproved: boolean;
|
|
104
|
+
/** Required before and after evaluation; final native delivery must also compare this revision. */
|
|
105
|
+
isCurrent: (envelope: StopReviewEnvelope) => boolean | Promise<boolean>;
|
|
106
|
+
now?: () => number;
|
|
107
|
+
maxContinuations?: number;
|
|
108
|
+
/** Owning runtime can broker the one request through Secrets; every answer is still validated. */
|
|
109
|
+
evaluate?: (envelope: StopReviewEnvelope, options: JevOptions) => Promise<JevResult>;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export interface ParentStopReviewAdmission {
|
|
113
|
+
mode: "parent_final_cas";
|
|
114
|
+
harness: "sumi" | "opencode";
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export type StopReviewNativeTarget = "codex" | "claude" | "sumi" | "opencode";
|
|
118
|
+
|
|
119
|
+
export type StopRecommendationOptions = Omit<StopReviewOptions, "isCurrent"> & {
|
|
120
|
+
admission: ParentStopReviewAdmission;
|
|
121
|
+
};
|