@hasna/hooks 0.12.10 → 0.12.16

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.
Files changed (57) hide show
  1. package/README.md +69 -6
  2. package/bin/hooks/stop-review.js +1235 -0
  3. package/bin/hooks-mcp.js +298 -85
  4. package/bin/index.js +3348 -1086
  5. package/bin/native-readiness-entry.js +5 -1
  6. package/bin/native-safety-entry.js +27 -25
  7. package/bin/native-safety-worker.cjs +27 -25
  8. package/bin/serve.js +1362 -70
  9. package/dist/db/remote-storage.d.ts +7 -1
  10. package/dist/index.d.ts +4 -1
  11. package/dist/index.js +1665 -257
  12. package/dist/lib/codex-safety-check.d.ts +1 -1
  13. package/dist/lib/hosted-registry.d.ts +70 -0
  14. package/dist/lib/legacy-registry-artifact.d.ts +23 -0
  15. package/dist/lib/manifest.d.ts +7 -0
  16. package/dist/lib/native-safety.d.ts +1 -0
  17. package/dist/lib/native-target.d.ts +7 -0
  18. package/dist/lib/opencode-stop-plugin.d.ts +55 -0
  19. package/dist/lib/registry-artifact.d.ts +36 -0
  20. package/dist/lib/registry.d.ts +4 -0
  21. package/dist/lib/stop-review-context.d.ts +12 -0
  22. package/dist/lib/store.d.ts +4 -0
  23. package/dist/lib/sumi-stop-plugin.d.ts +129 -0
  24. package/dist/lib/sync.d.ts +10 -0
  25. package/dist/lib/transport.d.ts +1 -1
  26. package/dist/native-readiness.d.ts +1 -1
  27. package/dist/native-readiness.js +5 -1
  28. package/dist/openapi.d.ts +160 -16
  29. package/dist/opencode-stop-plugin.js +384 -0
  30. package/dist/registry-auth.d.ts +5 -0
  31. package/dist/registry-http.d.ts +4 -0
  32. package/dist/sdk/generated.d.ts +32 -12
  33. package/dist/sdk/index.d.ts +28 -5
  34. package/dist/sdk/index.js +49 -24
  35. package/dist/sdk/registry-client.d.ts +1 -1
  36. package/dist/serve.d.ts +4 -4
  37. package/dist/storage.js +33 -2
  38. package/dist/sumi-stop-plugin.js +380 -0
  39. package/hooks/hook-stop-review/README.md +109 -0
  40. package/hooks/hook-stop-review/manifest.json +10 -0
  41. package/hooks/hook-stop-review/package.json +11 -0
  42. package/hooks/hook-stop-review/src/hook.ts +59 -0
  43. package/hooks/hook-stop-review/src/index.ts +3 -0
  44. package/hooks/hook-stop-review/src/jev.ts +121 -0
  45. package/hooks/hook-stop-review/src/native.ts +246 -0
  46. package/hooks/hook-stop-review/src/policy.ts +145 -0
  47. package/hooks/hook-stop-review/src/runtime.ts +309 -0
  48. package/hooks/hook-stop-review/src/types.ts +121 -0
  49. package/hooks/hook-trash-guard/src/hook.ts +96 -0
  50. package/hooks/hook-workspace-repos-guard/src/hook.ts +116 -3
  51. package/hooks/local-executors.ts +841 -0
  52. package/package.json +22 -4
  53. package/scripts/build-bundled-hooks.ts +40 -0
  54. package/scripts/validate-bundled-hooks.ts +78 -0
  55. package/scripts/validate-opencode-stop-plugin.ts +42 -0
  56. package/scripts/validate-package.ts +9 -0
  57. package/scripts/validate-sumi-stop-plugin.ts +47 -0
@@ -0,0 +1,109 @@
1
+ # Stop review
2
+
3
+ Review a coding agent's normal end-of-turn against the latest user request, last
4
+ assistant reply and current native goal. Jev supplies typed classification; the
5
+ harness and this hook retain control of whether continuation is permitted.
6
+
7
+ The native adapter supplies `StopReviewEnvelope` to `reviewStop`. A missing or
8
+ unknown runtime fact, explicit stop, terminal/paused/blocked goal, budget/usage
9
+ limit, approval wait, runtime failure or recursive invocation allows the stop
10
+ without inference. `goal: null` means the adapter confirmed no applicable native
11
+ goal; an omitted goal means its state could not be established.
12
+ A harness with no native goal API can explicitly report `goalAvailability:
13
+ "unavailable"`; this capability fact comes from the native adapter.
14
+
15
+ For an eligible event, one request to `https://api.typesafe.ai/v1/systemone` asks
16
+ for a stop classification and independent actionable-work/boundary probabilities.
17
+ The HTTP client uses `TYPESAFE_API_KEY` supplied by the owning consumer, a fixed
18
+ HTTPS origin, no redirects or retries, an 8-second default deadline (15-second
19
+ maximum) and a 16 KiB typed-response limit. Complete selected input fields are
20
+ sent without truncation or a byte-based context ceiling. Jev enforces its own
21
+ token limits; a provider refusal makes the review unavailable and cannot trigger
22
+ continuation. For `jev-1.13.0`, the documented limits are 64k tokens per request
23
+ and 32k tokens for state plus the longest question; see
24
+ <https://docs.typesafe.ai/models>. Credentials must be
25
+ projected through a supported secret consumer; never embed values or a private
26
+ organization's vault reference in the published hook.
27
+
28
+ The installed entry reads an owner-protected Hooks configuration from
29
+ `<effective Hooks home>/config/stop-review.json`, or the explicit absolute
30
+ `HOOKS_STOP_REVIEW_CONFIG` override. The schema is
31
+ `hooks.stop-review-runtime.v1`: `enabled: true`, a selected `model`, the exact
32
+ `instruction` `{id, version, sha256}`, absolute installed CLI paths in
33
+ `commands` `{instructions, secrets}`, and a `secretsReference`. The optional
34
+ `harness`, `codexHome` and `codexSocketPath` fields select native integration.
35
+ This configuration contains references, never a provider key. Resolve CLI and
36
+ app-home paths through the installed packages when provisioning a station.
37
+
38
+ The runtime loads the exact hosted Instructions record with the installed
39
+ Instructions client, then scans the complete outgoing request through Secrets
40
+ stdin. A scan must complete with no findings, skips, truncation or errors. It
41
+ claims the native turn once using append-only, owner-only metadata with no
42
+ prompt text. Only then does `secrets exec` project `TYPESAFE_API_KEY` into the
43
+ same retained hook entry's restricted `--assess-envelope` child. That child
44
+ verifies the pinned source and request digest against the claim. It cannot
45
+ inject a continuation or modify the native session. The parent validates its
46
+ typed result and rechecks native freshness before delivery.
47
+
48
+ Managed Instructions supplies the classification instructions and exact
49
+ continuation text, with source ID, version and digest. There is no model-generated
50
+ command or continuation prompt. The adapter must perform its credential-content
51
+ and disclosure checks before setting `externalContentApproved`.
52
+
53
+ Continuation requires `actionable_remaining`, choice confidence and winning
54
+ probability of at least 0.9, actionable probability of at least 0.9 and boundary
55
+ probability of at most 0.1. These conservative initial thresholds need calibration
56
+ on labeled target-domain cases before a production rollout. Choice confidence
57
+ and winning probability are distinct signals. All other classifications or
58
+ provider failures allow the native stop; a failure is recorded as unavailable,
59
+ never as completion or a successful classification.
60
+
61
+ For Codex and Claude, the adapter's `isCurrent` check runs before and after
62
+ evaluation and rereads immediately before returning native Stop output. This
63
+ uses the harness's own Stop callback and cancellation semantics; it does not
64
+ claim a separate transaction-level compare-and-swap. No transcript is edited and
65
+ no out-of-band resume command is sent. The default permits one continuation per
66
+ original user turn; a reviewed consumer may configure at most three. The model
67
+ cannot reopen a terminal goal, clear a real blocker or bypass an owner boundary.
68
+
69
+ Sumi and OpenCode use a separate recommendation-only mode marked
70
+ `admission: {mode: "parent_final_cas", harness, settlement}`. Their native parent
71
+ checks the current user, assistant turn, model, inbox and full goal epoch inside
72
+ the durable continuation-admission transaction. The child cannot claim to read
73
+ that live state. After the single permitted continuation, a new settled turn may
74
+ receive a terminal assessment; an actionable result at that cap returns
75
+ `continuation_limit` and can never request another continuation.
76
+ Only an actual active goal in the captured snapshot is eligible for a
77
+ `complete` or `blocked` settlement certificate; other results certify `none`.
78
+ Certification requires confidence and winning probability at least 0.9 and
79
+ actionable probability at most 0.1. Completion additionally requires boundary
80
+ probability at most 0.1; blocked settlement requires at least 0.9. Allowing a
81
+ native stop alone never certifies goal completion. Terminal settlement needs
82
+ separate calibration; these conservative gates may leave completed work
83
+ uncertified. The explicit target and admission mode are bound into each claim
84
+ and provider request. They come from the trusted entry arguments, never the
85
+ transcript. A shared station configuration can omit `harness`; setting it
86
+ narrows the permitted target.
87
+
88
+ OpenCode transport and installation are owned by this package, not copied into
89
+ a harness adapter. The `./opencode-stop-plugin` export is self-contained and
90
+ requires the host's frozen `experimental_stop_review` capability for
91
+ `experimental.session.stop`. The plugin pins the retained CLI and runtime,
92
+ refuses unknown envelope fields, strips provider credentials from its child
93
+ environment and never replaces another plugin's verdict. Use the package's
94
+ `hooks install stop-review --target opencode` plan/apply/verify workflow;
95
+ registration is distinct from native consumer adoption.
96
+
97
+ This payload does not delete, rewrite or prune session history, start a model
98
+ session, or signal an existing coding-agent session or process. It may bound
99
+ only its own newly spawned helper process group. Preserve native transcripts
100
+ and execution receipts through their owning interfaces.
101
+
102
+ Run the deterministic, network-free tests with:
103
+
104
+ ```sh
105
+ bun test hooks/hook-stop-review/src/policy.test.ts hooks/hook-stop-review/src/jev.test.ts hooks/hook-stop-review/src/runtime.test.ts
106
+ ```
107
+
108
+ API contract: <https://docs.typesafe.ai/api>. Judgments and confidence semantics:
109
+ <https://docs.typesafe.ai/primitives/choice> and <https://docs.typesafe.ai/confidence>.
@@ -0,0 +1,10 @@
1
+ {
2
+ "name": "stop-review",
3
+ "version": "0.1.0",
4
+ "description": "Review turn completion against the latest user request and active goal",
5
+ "events": ["Stop"],
6
+ "nativeTargetDispatch": true,
7
+ "script": "src/hook.ts",
8
+ "script_kind": "file",
9
+ "timeout_ms": 20000
10
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "hook-stop-review",
3
+ "version": "0.1.0",
4
+ "description": "Review premature coding-agent stops with typed Jev classification and native runtime guards",
5
+ "type": "module",
6
+ "main": "./src/hook.ts",
7
+ "private": true,
8
+ "scripts": { "typecheck": "tsc --noEmit" },
9
+ "author": "Hasna",
10
+ "license": "Apache-2.0"
11
+ }
@@ -0,0 +1,59 @@
1
+ #!/usr/bin/env bun
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { readCodexGoal, runNativeStop, type NativeHarness } from "./native";
5
+ import { loadNativeRuntimeConfiguration, reviewNativeEnvelope, runJevProviderChild, reviewParentGuardedEnvelope } from "./runtime";
6
+
7
+ /** Only reads this newly invoked hook's stdin; no parent session/process is controlled. */
8
+ export function readHookInput(stream: NodeJS.ReadableStream = process.stdin): Promise<unknown> {
9
+ return new Promise((resolve) => {
10
+ const chunks: Buffer[] = [];
11
+ let done = false;
12
+ const finish = (value?: unknown) => {
13
+ if (done) return; done = true; clearTimeout(timer);
14
+ stream.removeListener("data", onData); stream.removeListener("end", onEnd); stream.removeListener("error", onError);
15
+ stream.pause(); resolve(value);
16
+ };
17
+ const onData = (chunk: Buffer | string) => { chunks.push(Buffer.from(chunk)); };
18
+ const onEnd = () => { try { finish(JSON.parse(Buffer.concat(chunks).toString("utf8"))); } catch { finish(); } };
19
+ const onError = () => finish();
20
+ const timer = setTimeout(() => finish(), 1000);
21
+ stream.on("data", onData); stream.on("end", onEnd); stream.on("error", onError);
22
+ });
23
+ }
24
+
25
+ export async function main(argv = process.argv.slice(2), env = process.env): Promise<void> {
26
+ if (argv.length === 1 && argv[0] === "--assess-envelope") {
27
+ try { process.stdout.write(JSON.stringify(await runJevProviderChild(await readHookInput(), env)) + "\n"); }
28
+ catch { process.stdout.write(JSON.stringify({ ok: false, reason: "provider_unavailable" }) + "\n"); }
29
+ return;
30
+ }
31
+ let output: Record<string, string> = {}, reason = "invalid_configuration";
32
+ try {
33
+ const config = loadNativeRuntimeConfiguration(env);
34
+ 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;
35
+ if ((selected === "sumi" || selected === "opencode") && config && (!config.harness || config.harness === selected) && env.HOOKS_STOP_REVIEW_DISABLED !== "1") {
36
+ const recommendation = await reviewParentGuardedEnvelope(await readHookInput(), env, undefined, selected);
37
+ process.stderr.write(JSON.stringify({ hook: "stop-review", reason: recommendation.reason, recommendationOnly: true }) + "\n");
38
+ process.stdout.write(JSON.stringify(recommendation) + "\n");
39
+ return;
40
+ }
41
+ if (config && env.HOOKS_STOP_REVIEW_DISABLED !== "1" && ["codex", "claude"].includes(String(selected)) && (!config.harness || config.harness === selected)) {
42
+ const harness = selected as NativeHarness;
43
+ const raw = await readHookInput();
44
+ const result = await runNativeStop(raw, {
45
+ harness,
46
+ readGoal: (sessionId) => readCodexGoal(sessionId, {
47
+ codexHome: config.codexHome ?? env.CODEX_HOME ?? join(env.HOME || homedir(), ".codex"),
48
+ socketPath: config.codexSocketPath,
49
+ }),
50
+ }, (envelope, isCurrent) => reviewNativeEnvelope(envelope, isCurrent, env, undefined, harness));
51
+ output = result.output; reason = result.reason;
52
+ }
53
+ } catch { reason = "native_review_unavailable"; }
54
+ // Fixed machine reasons only. Never expose transcript, provider response, credentials, or paths.
55
+ process.stderr.write(JSON.stringify({ hook: "stop-review", reason: /^[a-z_]{1,64}$/.test(reason) ? reason : "native_review_unavailable", continued: output.decision === "block" }) + "\n");
56
+ process.stdout.write(JSON.stringify(output) + "\n");
57
+ }
58
+
59
+ if (import.meta.main) await main();
@@ -0,0 +1,3 @@
1
+ export * from "./types";
2
+ export * from "./policy";
3
+ export * from "./jev";
@@ -0,0 +1,121 @@
1
+ import { STOP_CLASSES, type JevAssessment, type JevOptions, type JevResult, type StopReviewEnvelope } from "./types";
2
+
3
+ export const TYPESAFE_SYSTEMONE_URL = "https://api.typesafe.ai/v1/systemone";
4
+ export const MAX_RESPONSE_BYTES = 16_384;
5
+
6
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
7
+ value !== null && typeof value === "object" && !Array.isArray(value);
8
+ const probability = (value: unknown): value is number =>
9
+ typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
10
+ const tokenCount = (value: unknown): value is number =>
11
+ typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
12
+
13
+ /** Deliberately typed output: no model-authored continuation instructions or executable text. */
14
+ export function buildJevRequest(envelope: StopReviewEnvelope, options: JevOptions): object {
15
+ return {
16
+ model: options.model,
17
+ state: {
18
+ last_user_prompt: envelope.lastUserPrompt,
19
+ last_assistant_message: envelope.lastAssistantMessage,
20
+ goal: envelope.goal ? { objective: envelope.goal.objective, status: envelope.goal.status } : null,
21
+ runtime_stop_reason: envelope.runtime.stopReason,
22
+ },
23
+ questions: options.instruction.questions,
24
+ };
25
+ }
26
+
27
+ export function parseJevAssessment(value: unknown): JevAssessment | null {
28
+ if (!isRecord(value) || typeof value.model !== "string" || !/^jev-[a-zA-Z0-9._-]{1,100}$/.test(value.model) ||
29
+ !isRecord(value.answers) || !isRecord(value.usage)) return null;
30
+ const { disposition, actionable, boundary } = value.answers;
31
+ if (Object.keys(value.answers).sort().join(",") !== "actionable,boundary,disposition" ||
32
+ !isRecord(disposition) || disposition.type !== "choice" ||
33
+ !STOP_CLASSES.includes(disposition.choice as never) || !probability(disposition.confidence) ||
34
+ !isRecord(disposition.probabilities) || !isRecord(actionable) || actionable.type !== "noul" ||
35
+ !probability(actionable.noul) || !isRecord(boundary) || boundary.type !== "noul" ||
36
+ !probability(boundary.noul) || !tokenCount(value.usage.input_tokens) || !tokenCount(value.usage.output_tokens)) return null;
37
+ const probabilities = disposition.probabilities;
38
+ if (Object.keys(probabilities).length !== STOP_CLASSES.length ||
39
+ !STOP_CLASSES.every((key) => Object.hasOwn(probabilities, key) && probability(probabilities[key]))) return null;
40
+ // Providers round probabilities; tolerate only the bounded rounding error for this fixed rubric.
41
+ const sum = STOP_CLASSES.reduce((total, key) => total + (probabilities[key] as number), 0);
42
+ const selected = probabilities[disposition.choice as string] as number;
43
+ // Confidence measures distribution concentration, not the selected option's probability.
44
+ if (Math.abs(sum - 1) > 0.04 || STOP_CLASSES.some((key) => (probabilities[key] as number) > selected + 0.01)) return null;
45
+ return {
46
+ classification: disposition.choice as JevAssessment["classification"], confidence: disposition.confidence,
47
+ probabilities: probabilities as JevAssessment["probabilities"], actionableProbability: actionable.noul,
48
+ boundaryProbability: boundary.noul, model: value.model,
49
+ inputTokens: value.usage.input_tokens, outputTokens: value.usage.output_tokens,
50
+ };
51
+ }
52
+
53
+ /** One request, fixed HTTPS origin, no redirects/retries, bounded response and duration. */
54
+ export async function evaluateJev(envelope: StopReviewEnvelope, options: JevOptions): Promise<JevResult> {
55
+ if (!options.apiKey?.trim()) return { ok: false, reason: "credential_unavailable" };
56
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(options.model)) return { ok: false, reason: "invalid_configuration" };
57
+ const timeoutMs = options.timeoutMs ?? 8_000;
58
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 15_000) return { ok: false, reason: "invalid_configuration" };
59
+ const body = JSON.stringify(buildJevRequest(envelope, options));
60
+ // The provider owns its tokenizer and actual context limits. A UTF-8 byte cap
61
+ // is not a token limit: send the complete selected state, never truncate it.
62
+ const controller = new AbortController();
63
+ let timedOut = false;
64
+ let timer: ReturnType<typeof setTimeout>;
65
+ const deadline = new Promise<JevResult>((resolve) => {
66
+ timer = setTimeout(() => { timedOut = true; controller.abort(); resolve({ ok: false, reason: "request_timeout" }); }, timeoutMs);
67
+ });
68
+ const request = async (): Promise<JevResult> => {
69
+ try {
70
+ const response = await (options.fetch ?? globalThis.fetch)(TYPESAFE_SYSTEMONE_URL, {
71
+ method: "POST", redirect: "error", signal: controller.signal,
72
+ headers: { Authorization: `Bearer ${options.apiKey}`, "Content-Type": "application/json", "User-Agent": "hooks-stop-review/1" },
73
+ body,
74
+ });
75
+ if (response.redirected || (response.url && response.url !== TYPESAFE_SYSTEMONE_URL)) {
76
+ await response.body?.cancel().catch(() => {});
77
+ return { ok: false, reason: "provider_unavailable" };
78
+ }
79
+ if (!response.ok) {
80
+ await response.body?.cancel().catch(() => {});
81
+ const httpStatus = response.status;
82
+ const reason = httpStatus === 401 || httpStatus === 403 ? "credential_rejected"
83
+ : httpStatus === 429 ? "provider_rate_limited"
84
+ : httpStatus === 529 ? "provider_overloaded"
85
+ : httpStatus >= 400 && httpStatus < 500 ? "provider_request_refused" : "provider_unavailable";
86
+ return { ok: false, reason, httpStatus };
87
+ }
88
+ const declared = Number(response.headers.get("content-length"));
89
+ if (Number.isFinite(declared) && declared > MAX_RESPONSE_BYTES) {
90
+ await response.body?.cancel().catch(() => {});
91
+ return { ok: false, reason: "response_too_large" };
92
+ }
93
+ if (!response.body) return { ok: false, reason: "invalid_provider_response" };
94
+ const reader = response.body.getReader();
95
+ const chunks: Uint8Array[] = [];
96
+ let bytes = 0;
97
+ try {
98
+ while (true) {
99
+ const part = await reader.read();
100
+ if (part.done) break;
101
+ bytes += part.value.byteLength;
102
+ if (bytes > MAX_RESPONSE_BYTES) {
103
+ await reader.cancel().catch(() => {});
104
+ return { ok: false, reason: "response_too_large" };
105
+ }
106
+ chunks.push(part.value);
107
+ }
108
+ } finally { reader.releaseLock(); }
109
+ let decoded: unknown;
110
+ try { decoded = JSON.parse(Buffer.concat(chunks).toString("utf8")); }
111
+ catch { return { ok: false, reason: "invalid_provider_response" }; }
112
+ const assessment = parseJevAssessment(decoded);
113
+ return assessment ? { ok: true, assessment } : { ok: false, reason: "invalid_provider_response" };
114
+ } catch {
115
+ // Never serialize provider errors: their bodies/headers may echo credentials or private input.
116
+ return { ok: false, reason: timedOut ? "request_timeout" : "provider_unavailable" };
117
+ }
118
+ };
119
+ try { return await Promise.race([request(), deadline]); }
120
+ finally { clearTimeout(timer!); }
121
+ }
@@ -0,0 +1,246 @@
1
+ import { createHash } from "node:crypto";
2
+ import { constants, closeSync, fstatSync, openSync, readSync, realpathSync, statSync } from "node:fs";
3
+ import { isAbsolute, join } from "node:path";
4
+ import type { StopReviewEnvelope, StopReviewResult } from "./types";
5
+
6
+ export type NativeHarness = "codex" | "claude";
7
+ type ObjectValue = Record<string, unknown>;
8
+ const object = (x: unknown): x is ObjectValue => !!x && typeof x === "object" && !Array.isArray(x);
9
+ const id = (x: unknown): x is string => typeof x === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(x);
10
+ const text = (x: unknown, max = Infinity): x is string => typeof x === "string" && x.trim().length > 0 && Buffer.byteLength(x) <= max;
11
+ const digest = (x: unknown) => createHash("sha256").update(JSON.stringify(x)).digest("hex");
12
+ const unavailable = (reason: string) => ({ ok: false as const, reason });
13
+
14
+ /** A read-only window; the native adapter expands it when the owner turn is older. */
15
+ export interface TranscriptWindow { header: string; tail: string; complete: boolean }
16
+ export function readNativeTranscript(path: string, windowBytes = 2_000_000): TranscriptWindow {
17
+ if (!isAbsolute(path) || !path.endsWith(".jsonl")) throw new Error("unsupported_transcript_path");
18
+ if (!Number.isSafeInteger(windowBytes) || windowBytes < 1) throw new Error("invalid_transcript_window");
19
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
20
+ try {
21
+ const before = fstatSync(fd);
22
+ if (!before.isFile() || before.uid !== process.getuid?.() || (before.mode & 0o022) !== 0 || before.size < 1) throw new Error("unsafe_transcript");
23
+ const headerSize = Math.min(before.size, windowBytes);
24
+ const tailSize = Math.min(before.size, windowBytes);
25
+ const header = Buffer.alloc(headerSize), tail = Buffer.alloc(tailSize);
26
+ if (readSync(fd, header, 0, headerSize, 0) !== headerSize || readSync(fd, tail, 0, tailSize, before.size - tailSize) !== tailSize) throw new Error("transcript_changed");
27
+ const after = fstatSync(fd);
28
+ if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ino !== after.ino) throw new Error("transcript_changed");
29
+ // A partial final JSONL record is not a safe freshness observation.
30
+ if (tail.at(-1) !== 10) throw new Error("incomplete_transcript");
31
+ const complete = tailSize === before.size;
32
+ const start = complete ? 0 : tail.indexOf(10) + 1;
33
+ if (!complete && start === 0) return { header: header.toString("utf8"), tail: "", complete };
34
+ const tailText = new TextDecoder("utf-8", { fatal: true }).decode(tail.subarray(start));
35
+ return { header: header.toString("utf8"), tail: tailText, complete };
36
+ } finally { closeSync(fd); }
37
+ }
38
+
39
+ function records(window: TranscriptWindow): ObjectValue[] {
40
+ const lines = window.tail.trimEnd() ? window.tail.trimEnd().split("\n") : [];
41
+ return lines.map((line) => { const value: unknown = JSON.parse(line); if (!object(value)) throw new Error("unsupported_transcript_format"); return value; });
42
+ }
43
+
44
+ interface PromptSnapshot { prompt: string; turnId: string; revision: string; interrupted: boolean }
45
+ /** Codex rust-v0.161.0: RolloutLine + SessionMeta + TurnContextItem + EventMsg::UserMessage. */
46
+ export function parseCodexPrompt(window: TranscriptWindow, sessionId: string, expectedTurn: string): PromptSnapshot {
47
+ const headerEnd = window.header.indexOf("\n");
48
+ if (headerEnd < 0) throw new Error("unsupported_transcript_header");
49
+ const header: unknown = JSON.parse(window.header.slice(0, headerEnd));
50
+ if (!object(header) || header.type !== "session_meta" || !object(header.payload) || header.payload.id !== sessionId || header.payload.parent_thread_id) throw new Error("transcript_identity_mismatch");
51
+ let turn: string | undefined, prompt: string | undefined, promptIdentity: unknown, interrupted = false;
52
+ for (const row of records(window)) {
53
+ const payload = row.payload;
54
+ if (!object(payload)) continue;
55
+ if (row.type === "turn_context" && id(payload.turn_id)) { turn = payload.turn_id; }
56
+ if (row.type === "event_msg" && payload.type === "task_started" && id(payload.turn_id)) { turn = payload.turn_id; }
57
+ if (row.type === "event_msg" && payload.type === "user_message") {
58
+ if (!text(payload.message)) throw new Error("unsupported_user_prompt");
59
+ // Do not replace an attachment-bearing prompt with an incomplete text-only interpretation.
60
+ if ((Array.isArray(payload.images) && payload.images.length) || (Array.isArray(payload.local_images) && payload.local_images.length)) throw new Error("unsupported_user_prompt");
61
+ prompt = payload.message; promptIdentity = [row.ordinal, row.timestamp, payload.client_id, prompt]; interrupted = false;
62
+ }
63
+ if (row.type === "event_msg" && ["turn_aborted", "error"].includes(String(payload.type))) interrupted = true;
64
+ }
65
+ if (turn !== expectedTurn || !prompt) throw new Error("missing_current_user_prompt");
66
+ return { prompt, turnId: expectedTurn, revision: digest([sessionId, expectedTurn, promptIdentity]), interrupted };
67
+ }
68
+
69
+ /** Claude SDK get_session_messages parent-chain semantics; synthetic/meta/sidechain input is never owner input. */
70
+ export function parseClaudePrompt(window: TranscriptWindow, sessionId: string): PromptSnapshot {
71
+ const rows = records(window), byId = new Map<string, ObjectValue>();
72
+ let leaf: ObjectValue | undefined;
73
+ for (const row of rows) {
74
+ if (!id(row.uuid)) continue;
75
+ if (row.sessionId !== sessionId) throw new Error("transcript_identity_mismatch");
76
+ if (byId.has(row.uuid)) throw new Error("duplicate_transcript_uuid");
77
+ byId.set(row.uuid, row);
78
+ if (["user", "assistant"].includes(String(row.type)) && row.isSidechain !== true && !row.teamName && row.isMeta !== true) leaf = row;
79
+ }
80
+ const visited = new Set<string>();
81
+ while (leaf && id(leaf.uuid) && !visited.has(leaf.uuid)) {
82
+ visited.add(leaf.uuid);
83
+ if (leaf.type === "user" && leaf.isMeta !== true && leaf.isSidechain !== true && !leaf.teamName && leaf.isCompactSummary !== true && object(leaf.message)) {
84
+ const content = leaf.message.content;
85
+ let prompt: string | undefined;
86
+ if (typeof content === "string") prompt = content;
87
+ else if (Array.isArray(content) && content.length && content.every((part) => object(part) && part.type === "text" && typeof part.text === "string")) prompt = content.map((part) => part.text).join("\n");
88
+ // Tool-result user entries are part of the preceding turn, not a fresh owner prompt.
89
+ else if (!Array.isArray(content) || !content.every((part) => object(part) && part.type === "tool_result")) throw new Error("unsupported_user_prompt");
90
+ if (prompt !== undefined) {
91
+ if (!text(prompt)) throw new Error("unsupported_user_prompt");
92
+ return { prompt, turnId: leaf.uuid, revision: digest([sessionId, leaf.uuid, prompt]), interrupted: /^\[Request interrupted by user/.test(prompt) };
93
+ }
94
+ }
95
+ if (leaf.parentUuid === null) break;
96
+ if (!id(leaf.parentUuid)) throw new Error("unsupported_transcript_parent");
97
+ leaf = byId.get(leaf.parentUuid);
98
+ }
99
+ throw new Error("missing_current_user_prompt");
100
+ }
101
+
102
+ /** Conservative text gate supplements native Interrupt/StopFailure separation; text never grants authority. */
103
+ export function requestsStop(prompt: string): boolean {
104
+ 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ște|opreste)\b|\s*\/(?:stop|pause|cancel|exit|quit|clear|goal)\b)/i.test(prompt);
105
+ }
106
+
107
+ export type NativeGoal = StopReviewEnvelope["goal"];
108
+ // Native generation evidence stays off enumerable envelopes/provider requests.
109
+ const nativeGoalRevision = Symbol("nativeGoalRevision");
110
+ type VerifiedNativeGoal = NonNullable<NativeGoal> & { [nativeGoalRevision]: string };
111
+ function goalFreshness(goal: NativeGoal): unknown {
112
+ if (goal === undefined) return { state: "unreadable" };
113
+ if (goal === null) return { state: "absent" };
114
+ const revision = (goal as VerifiedNativeGoal)[nativeGoalRevision];
115
+ if (typeof revision !== "string") throw new Error("native_goal_revision_unavailable");
116
+ return { state: "present", revision, id: goal.id, objective: goal.objective, status: goal.status };
117
+ }
118
+ export interface NativeAdapterOptions {
119
+ harness: NativeHarness;
120
+ readTranscript?: (path: string) => TranscriptWindow | Promise<TranscriptWindow>;
121
+ /** undefined = unreadable; null = native getter confirms absent. Never opens/resumes a session. */
122
+ readGoal?: (sessionId: string) => Promise<NativeGoal>;
123
+ now?: () => number;
124
+ }
125
+ export interface PreparedNativeStop {
126
+ ok: true;
127
+ envelope: StopReviewEnvelope;
128
+ isCurrent: (envelope: StopReviewEnvelope) => Promise<boolean>;
129
+ }
130
+ export async function prepareNativeStop(raw: unknown, options: NativeAdapterOptions): Promise<PreparedNativeStop | { ok: false; reason: string }> {
131
+ 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") return unavailable("invalid_native_input");
132
+ if (raw.stop_hook_active) return unavailable("recursion_guard");
133
+ for (const key of ["background_tasks", "session_crons"]) {
134
+ if (raw[key] !== undefined && (!Array.isArray(raw[key]) || raw[key].length > 0)) return unavailable("native_background_work");
135
+ }
136
+ if (options.harness === "codex" && !id(raw.turn_id)) return unavailable("missing_native_turn");
137
+ // Stop is the normal completion callback. Interrupt/StopFailure/SubagentStop are never admitted.
138
+ const sessionId = raw.session_id, path = raw.transcript_path, assistant = raw.last_assistant_message;
139
+ const readPrompt = async () => {
140
+ let windowBytes = 2_000_000;
141
+ for (;;) {
142
+ const window = options.readTranscript ? await options.readTranscript(path) : readNativeTranscript(path, windowBytes);
143
+ try {
144
+ return options.harness === "codex" ? parseCodexPrompt(window, sessionId, raw.turn_id as string) : parseClaudePrompt(window, sessionId);
145
+ } catch (error) {
146
+ // A bounded source read must not become an artificial context ceiling.
147
+ // Expand only an incomplete native window; malformed or foreign history
148
+ // still fails closed. Custom readers own their own completeness contract.
149
+ if (options.readTranscript || window.complete || !(error instanceof Error) ||
150
+ !["missing_current_user_prompt", "unsupported_transcript_header", "unsupported_transcript_parent"].includes(error.message)) throw error;
151
+ windowBytes *= 2;
152
+ }
153
+ }
154
+ };
155
+ const snapshot = async () => {
156
+ const prompt = await readPrompt();
157
+ const goal = options.harness === "codex" ? await options.readGoal?.(sessionId) : undefined;
158
+ return { prompt, goal, revision: digest([prompt.revision, options.harness === "codex" ? goalFreshness(goal) : "optional-goal-unavailable", assistant]) };
159
+ };
160
+ try {
161
+ const current = await snapshot();
162
+ if (current.prompt.interrupted || requestsStop(current.prompt.prompt)) return unavailable("user_stop");
163
+ const goal = current.goal;
164
+ const envelope: StopReviewEnvelope = {
165
+ schema: "hooks.stop-review.v1", sessionId, turnId: current.prompt.turnId,
166
+ inputRevision: current.revision, capturedAt: new Date((options.now ?? Date.now)()).toISOString(),
167
+ lastUserPrompt: current.prompt.prompt, lastAssistantMessage: assistant, goal,
168
+ // Claude exposes no supported /goal getter. Its Stop callback still supplies native lifecycle authority.
169
+ ...(options.harness === "claude" ? { goalAvailability: "unavailable" as const } : {}),
170
+ runtime: { stopReason: "end_turn", userRequestedStop: false, terminal: goal?.status === "complete" || goal?.status === "cancelled",
171
+ paused: goal?.status === "paused", budgetExhausted: goal?.status === "budget_limited", usageLimited: goal?.status === "usage_limited",
172
+ awaitingApproval: false, nativeContinuationAllowed: true, stopHookActive: false, continuationCount: 0 },
173
+ };
174
+ return { ok: true, envelope, isCurrent: async (candidate) => {
175
+ if (candidate.sessionId !== sessionId || candidate.turnId !== envelope.turnId || candidate.inputRevision !== envelope.inputRevision) return false;
176
+ try { const latest = await snapshot(); return (options.harness !== "codex" || latest.goal !== undefined) && latest.revision === envelope.inputRevision && !latest.prompt.interrupted && !requestsStop(latest.prompt.prompt); } catch { return false; }
177
+ } };
178
+ } catch { return unavailable("native_context_unavailable"); }
179
+ }
180
+
181
+ /** Call after evaluation and immediately before stdout. The native runtime owns final cancellation arbitration. */
182
+ export async function nativeStopOutput(result: StopReviewResult, prepared: PreparedNativeStop): Promise<Record<string, string>> {
183
+ if ((result as StopReviewResult & { admission?: unknown }).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)) return {};
184
+ return { decision: "block", reason: result.continuationPrompt };
185
+ }
186
+
187
+ /** Codex 0.161 native JSON-RPC goal projection. Wrong thread, unknown status, and exhausted budgets fail closed. */
188
+ export function codexGoalFromResponse(value: unknown, sessionId: string): NativeGoal {
189
+ if (!object(value) || !("goal" in value)) return undefined;
190
+ if (value.goal === null) return null;
191
+ const goal = value.goal;
192
+ if (!object(goal) || goal.threadId !== sessionId || !text(goal.objective)) return undefined;
193
+ const statuses: Record<string, NonNullable<NativeGoal>["status"]> = { active: "active", paused: "paused", blocked: "blocked", usageLimited: "usage_limited", budgetLimited: "budget_limited", complete: "complete" };
194
+ const status = statuses[String(goal.status)];
195
+ if (!status || typeof goal.tokensUsed !== "number" || !Number.isFinite(goal.tokensUsed) || goal.tokensUsed < 0 || !(goal.tokenBudget === null || (Number.isSafeInteger(goal.tokenBudget) && (goal.tokenBudget as number) >= 0))) return undefined;
196
+ if (!Number.isSafeInteger(goal.createdAt) || (goal.createdAt as number) < 0 || !Number.isSafeInteger(goal.updatedAt) || (goal.updatedAt as number) < (goal.createdAt as number)) return undefined;
197
+ const projected: NonNullable<NativeGoal> = { id: sessionId, objective: goal.objective, status: goal.tokenBudget !== null && goal.tokensUsed >= (goal.tokenBudget as number) ? "budget_limited" : status };
198
+ Object.defineProperty(projected, nativeGoalRevision, { value: digest([goal.createdAt, goal.updatedAt, goal.tokenBudget, goal.tokensUsed]), enumerable: false });
199
+ return projected;
200
+ }
201
+
202
+ /** Existing native daemon only. Path is the rust-v0.161.0 owning resolver's CODEX_HOME-relative control socket. */
203
+ export async function readCodexGoal(sessionId: string, options: { codexHome: string; socketPath?: string; timeoutMs?: number }): Promise<NativeGoal> {
204
+ if (!id(sessionId) || !isAbsolute(options.codexHome)) return undefined;
205
+ const path = options.socketPath ?? join(options.codexHome, "app-server-control", "app-server-control.sock");
206
+ try {
207
+ const physical = realpathSync(path), socket = statSync(physical);
208
+ if (!socket.isSocket() || socket.uid !== process.getuid?.() || (socket.mode & 0o077) !== 0) return undefined;
209
+ // Bun's WebSocket supports ws+unix transport; no TCP endpoint, proxy subprocess, or daemon launch.
210
+ return await new Promise<NativeGoal>((resolve) => {
211
+ let done = false;
212
+ const ws = new WebSocket(`ws+unix://${physical}:/`);
213
+ const finish = (goal: NativeGoal) => { if (done) return; done = true; clearTimeout(timer); try { ws.close(); } catch {} resolve(goal); };
214
+ const timer = setTimeout(() => finish(undefined), Math.min(options.timeoutMs ?? 350, 350));
215
+ ws.onopen = () => ws.send(JSON.stringify({ id: 1, method: "initialize", params: { clientInfo: { name: "hooks-stop-review", version: "1" }, capabilities: { experimentalApi: true } } }));
216
+ ws.onmessage = (event) => {
217
+ if (typeof event.data !== "string") return finish(undefined);
218
+ try {
219
+ const reply: unknown = JSON.parse(event.data);
220
+ if (!object(reply)) return finish(undefined);
221
+ if (reply.id === 1) {
222
+ if (reply.error || !object(reply.result)) return finish(undefined);
223
+ ws.send(JSON.stringify({ method: "initialized" }));
224
+ ws.send(JSON.stringify({ id: 2, method: "thread/goal/get", params: { threadId: sessionId } }));
225
+ } else if (reply.id === 2) finish(reply.error ? undefined : codexGoalFromResponse(reply.result, sessionId));
226
+ } catch { finish(undefined); }
227
+ };
228
+ ws.onerror = () => finish(undefined);
229
+ ws.onclose = () => finish(undefined);
230
+ });
231
+ } catch { return undefined; }
232
+ }
233
+
234
+ export async function runNativeStop(
235
+ raw: unknown,
236
+ options: NativeAdapterOptions,
237
+ review: (envelope: StopReviewEnvelope, isCurrent: PreparedNativeStop["isCurrent"]) => Promise<StopReviewResult>,
238
+ ): Promise<{ output: Record<string, string>; reason: string }> {
239
+ const prepared = await prepareNativeStop(raw, options);
240
+ if (!prepared.ok) return { output: {}, reason: prepared.reason };
241
+ try {
242
+ const result = await review(prepared.envelope, prepared.isCurrent);
243
+ const output = await nativeStopOutput(result, prepared);
244
+ return { output, reason: result.action === "continue" && !output.decision ? "stale_input" : result.reason };
245
+ } catch { return { output: {}, reason: "native_review_unavailable" }; }
246
+ }