@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,384 @@
1
+ // src/lib/sumi-stop-plugin.ts
2
+ import { spawn } from "node:child_process";
3
+ import { createHash } from "node:crypto";
4
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, realpathSync } from "node:fs";
5
+ import { homedir } from "node:os";
6
+ import { dirname, isAbsolute, normalize } from "node:path";
7
+
8
+ // src/lib/native-child-env.ts
9
+ var INHERITED = new Set([
10
+ "PATH",
11
+ "USER",
12
+ "LOGNAME",
13
+ "LANG",
14
+ "TMPDIR",
15
+ "XDG_CONFIG_HOME",
16
+ "XDG_CONFIG_DIRS",
17
+ "XDG_DATA_HOME",
18
+ "XDG_DATA_DIRS",
19
+ "XDG_CACHE_HOME",
20
+ "XDG_STATE_HOME",
21
+ "XDG_RUNTIME_DIR"
22
+ ]);
23
+ var REFUSED_PREFIXES = ["LD_", "DYLD_", "NODE_", "BUN_", "BASH_FUNC_"];
24
+ var REFUSED = new Set(["BASH_ENV", "ENV", "GLIBC_TUNABLES", "GCONV_PATH", "LOCPATH"]);
25
+ function isRefusedNativeChildEnvName(name) {
26
+ return REFUSED.has(name) || REFUSED_PREFIXES.some((prefix) => name.startsWith(prefix));
27
+ }
28
+ function nativeChildEnv(source, explicit = {}, inherit = () => false) {
29
+ const env = {};
30
+ for (const [name, value] of Object.entries(source)) {
31
+ if (typeof value !== "string" || isRefusedNativeChildEnvName(name))
32
+ continue;
33
+ if (INHERITED.has(name) || /^LC_[A-Z]+$/.test(name) || inherit(name))
34
+ env[name] = value;
35
+ }
36
+ for (const [name, value] of Object.entries(explicit)) {
37
+ if (isRefusedNativeChildEnvName(name))
38
+ throw new Error(`A native child environment cannot set ${name}.`);
39
+ if (value === undefined)
40
+ delete env[name];
41
+ else
42
+ env[name] = value;
43
+ }
44
+ return env;
45
+ }
46
+
47
+ // src/lib/stop-review-context.ts
48
+ var APPS = ["hooks", "instructions", "secrets"];
49
+ var REFUSED2 = "HOOKS_CLIENT_CONTEXT_REFUSED";
50
+ var LOCAL_FLAGS = [
51
+ ["HASNA_INSTRUCTIONS_LOCAL", "HOOKS_CLIENT_INSTRUCTIONS_LOCAL", "INSTRUCTIONS_LOCAL"],
52
+ ["HASNA_CONFIGS_LOCAL", "HOOKS_CLIENT_CONFIGS_LOCAL", "CONFIGS_LOCAL"],
53
+ ["HASNA_SECRETS_LOCAL", "HOOKS_CLIENT_SECRETS_LOCAL", "SECRETS_LOCAL"]
54
+ ];
55
+ var HOOK_CLIENT_CONFIG_PROJECTIONS = [
56
+ ["HASNA_HOME", "HOOKS_CLIENT_HOME"],
57
+ ["HASNA_CONFIG_HOME", "HOOKS_CLIENT_CONFIG_HOME"],
58
+ ["HASNA_PROFILE", "HOOKS_CLIENT_PROFILE"],
59
+ ["HASNA_STATION", "HOOKS_CLIENT_STATION"],
60
+ ...APPS.map((app) => [`HASNA_${app.toUpperCase()}_API_KEY_REF`, `HOOKS_CLIENT_${app.toUpperCase()}_API_KEY_REF`]),
61
+ ...LOCAL_FLAGS.map(([name, alias]) => [name, alias])
62
+ ];
63
+ var AUTHORITY_PROJECTIONS = APPS.map((app) => ({
64
+ app,
65
+ name: `HASNA_${app.toUpperCase()}_API_URL`,
66
+ legacy: `${app.toUpperCase()}_API_URL`,
67
+ alias: `HOOKS_CLIENT_${app.toUpperCase()}_AUTHORITY`
68
+ }));
69
+ function isCanonicalAuthority(value, app) {
70
+ if (/[\u0000-\u001f\u007f]/.test(value))
71
+ return false;
72
+ const trimmed = value.trim();
73
+ return ["", ":443"].some((port) => ["", "/", "/v1", "/v1/"].some((suffix) => trimmed === `https://api.hasna.com${port}/${app}${suffix}`));
74
+ }
75
+ function projectStopReviewClientContext(source, extra = {}) {
76
+ const out = {};
77
+ const values = (names) => names.flatMap((name) => [source[name], extra[name]]).filter((value) => value !== undefined);
78
+ let refused = values([REFUSED2]).some((value) => value.trim() === "1");
79
+ for (const [name, alias] of HOOK_CLIENT_CONFIG_PROJECTIONS) {
80
+ const value = source[name] ?? extra[name] ?? extra[alias] ?? source[alias];
81
+ if (value !== undefined)
82
+ out[alias] = value;
83
+ }
84
+ for (const names of LOCAL_FLAGS) {
85
+ if (values(names).some((value) => value.trim() === "1")) {
86
+ out[names[1]] = "1";
87
+ refused = true;
88
+ }
89
+ }
90
+ if (values(["HASNA_HOOKS_LOCAL", "HOOKS_LOCAL"]).some((value) => value.trim() !== ""))
91
+ refused = true;
92
+ if (values(["HASNA_SECRETS_LOCAL_VAULT", "HASNA_SECRETS_DB_PATH", "OPEN_SECRETS_DB"]).some((value) => value !== ""))
93
+ refused = true;
94
+ for (const { app, name, legacy, alias } of AUTHORITY_PROJECTIONS) {
95
+ const declared = values([name, legacy, alias]);
96
+ if (declared.some((value) => !isCanonicalAuthority(value, app)))
97
+ refused = true;
98
+ else if (declared.length)
99
+ out[alias] = `https://api.hasna.com/${app}`;
100
+ const prefix = app.toUpperCase();
101
+ if (values([`HASNA_${prefix}_API_KEY_OVERRIDE`]).length)
102
+ refused = true;
103
+ const deliberate = out[`HOOKS_CLIENT_${prefix}_API_KEY_REF`]?.trim() || out.HOOKS_CLIENT_PROFILE?.trim();
104
+ if (!deliberate && values([`HASNA_${prefix}_API_KEY`, `${prefix}_API_KEY`]).length)
105
+ refused = true;
106
+ }
107
+ if (refused)
108
+ out[REFUSED2] = "1";
109
+ return out;
110
+ }
111
+ function stopReviewClientContextRefused(source) {
112
+ return projectStopReviewClientContext(source)[REFUSED2] === "1";
113
+ }
114
+ function restoreStopReviewClientContext(source) {
115
+ const projected = projectStopReviewClientContext(source);
116
+ const out = {};
117
+ for (const [name, alias] of HOOK_CLIENT_CONFIG_PROJECTIONS)
118
+ if (projected[alias] !== undefined)
119
+ out[name] = projected[alias];
120
+ for (const { name, alias } of AUTHORITY_PROJECTIONS)
121
+ if (projected[alias] !== undefined)
122
+ out[name] = projected[alias];
123
+ return out;
124
+ }
125
+
126
+ // src/lib/sumi-stop-plugin.ts
127
+ var MAX_OUTPUT = 16384;
128
+ var CLASSES = ["complete", "actionable_remaining", "blocked_permission", "blocked_external", "blocked_environment", "needs_user_input", "uncertain"];
129
+ var FLAGS = ["userRequestedStop", "terminal", "paused", "budgetExhausted", "usageLimited", "awaitingApproval", "nativeContinuationAllowed", "stopHookActive"];
130
+ var GOAL_STATUSES = ["active", "complete", "paused", "cancelled", "blocked", "budget_limited", "usage_limited", "unknown"];
131
+ var STOP_REASONS = ["end_turn", "user_stop", "cancelled", "error", "approval_wait", "budget_limit", "usage_limit", "unknown"];
132
+ var CONFIG_ENV = new Set([
133
+ "HASNA_HOME",
134
+ "HASNA_CONFIG_HOME",
135
+ "HASNA_DATA_HOME",
136
+ "HASNA_PROFILE",
137
+ "HASNA_HOOKS_HOME",
138
+ "HOOKS_HOME",
139
+ "HASNA_HOOKS_DATA_DIR",
140
+ "HOOKS_DATA_DIR",
141
+ "HOOKS_STOP_REVIEW_CONFIG",
142
+ "HOOKS_STOP_REVIEW_DISABLED",
143
+ "HASNA_HOOKS_API_URL",
144
+ "HASNA_HOOKS_API_KEY_REF",
145
+ "HASNA_INSTRUCTIONS_API_URL",
146
+ "HASNA_INSTRUCTIONS_API_KEY_REF",
147
+ "HASNA_SECRETS_API_URL",
148
+ "HASNA_SECRETS_API_KEY_REF"
149
+ ]);
150
+ var record = (v) => !!v && typeof v === "object" && !Array.isArray(v);
151
+ var keys = (v, required, optional = []) => required.every((key) => Object.hasOwn(v, key)) && Object.keys(v).every((key) => required.includes(key) || optional.includes(key));
152
+ var identifier = (v) => typeof v === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(v);
153
+ var text = (v, max = Infinity) => typeof v === "string" && v.trim().length > 0 && Buffer.byteLength(v) <= max;
154
+ var probability = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
155
+ var count = (v) => Number.isSafeInteger(v) && v >= 0;
156
+ var className = (v) => CLASSES.includes(v);
157
+ var digest = (v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v);
158
+ var pathForm = (v) => typeof v === "string" && isAbsolute(v) && normalize(v) === v && Buffer.byteLength(v) <= 4096 && !/[\u0000-\u001f\u007f]/.test(v);
159
+ function isSumiStopReviewEnvelope(v) {
160
+ if (!record(v) || !keys(v, ["schema", "sessionId", "turnId", "inputRevision", "capturedAt", "lastUserPrompt", "lastAssistantMessage", "runtime"], ["goal", "goalAvailability"]) || v.schema !== "hooks.stop-review.v1" || !identifier(v.sessionId) || !identifier(v.turnId) || !identifier(v.inputRevision) || typeof v.capturedAt !== "string" || !Number.isFinite(Date.parse(v.capturedAt)) || !text(v.lastUserPrompt) || !text(v.lastAssistantMessage) || !record(v.runtime))
161
+ return false;
162
+ const runtime = v.runtime;
163
+ if (!keys(runtime, [...FLAGS, "stopReason", "continuationCount"]) || !FLAGS.every((key) => typeof runtime[key] === "boolean") || !STOP_REASONS.includes(runtime.stopReason) || !count(runtime.continuationCount))
164
+ return false;
165
+ if (v.goal !== undefined && v.goal !== null && (!record(v.goal) || !keys(v.goal, ["id", "objective", "status"]) || !identifier(v.goal.id) || !text(v.goal.objective) || !GOAL_STATUSES.includes(v.goal.status)))
166
+ return false;
167
+ return v.goalAvailability === undefined || ["known", "unavailable"].includes(v.goalAvailability);
168
+ }
169
+ function isParentStopReviewResult(v, envelope, harness) {
170
+ if (!record(v) || !keys(v, ["schema", "action", "reason", "sessionId", "turnId", "inputRevision", "admission"], ["classification", "assessment", "instruction", "continuationPrompt", "httpStatus"]) || v.schema !== "hooks.stop-review-result.v1" || !["allow_stop", "continue", "unavailable"].includes(v.action) || typeof v.reason !== "string" || !/^[a-z_]{1,64}$/.test(v.reason) || v.sessionId !== envelope.sessionId || v.turnId !== envelope.turnId || v.inputRevision !== envelope.inputRevision || !record(v.admission) || !keys(v.admission, ["mode", "harness", "settlement"]) || v.admission.mode !== "parent_final_cas" || v.admission.harness !== harness || !["complete", "blocked", "none"].includes(v.admission.settlement))
171
+ return false;
172
+ if (v.httpStatus !== undefined && (!Number.isInteger(v.httpStatus) || v.httpStatus < 100 || v.httpStatus > 599))
173
+ return false;
174
+ if (v.classification !== undefined && !className(v.classification))
175
+ return false;
176
+ if (v.instruction !== undefined && (!record(v.instruction) || !keys(v.instruction, ["sourceId", "version", "digest"]) || !identifier(v.instruction.sourceId) || !count(v.instruction.version) || v.instruction.version === 0 || typeof v.instruction.digest !== "string" || !/^(sha256:)?[a-f0-9]{64}$/.test(v.instruction.digest)))
177
+ return false;
178
+ const assessment = v.assessment;
179
+ if (assessment !== undefined) {
180
+ if (!record(assessment) || !keys(assessment, ["classification", "confidence", "probabilities", "actionableProbability", "boundaryProbability", "model", "inputTokens", "outputTokens"]) || !className(assessment.classification) || assessment.classification !== v.classification || !probability(assessment.confidence) || !probability(assessment.actionableProbability) || !probability(assessment.boundaryProbability) || !record(assessment.probabilities) || !keys(assessment.probabilities, [...CLASSES]) || !CLASSES.every((key) => probability(assessment.probabilities[key])) || !identifier(assessment.model) || !count(assessment.inputTokens) || !count(assessment.outputTokens))
181
+ return false;
182
+ const total = CLASSES.reduce((sum, key) => sum + assessment.probabilities[key], 0);
183
+ if (Math.abs(total - 1) > 0.02)
184
+ return false;
185
+ }
186
+ if (v.continuationPrompt !== undefined && !text(v.continuationPrompt, 4096))
187
+ return false;
188
+ if (v.action === "continue") {
189
+ return v.reason === "actionable_remaining" && v.classification === "actionable_remaining" && assessment !== undefined && v.instruction !== undefined && text(v.continuationPrompt, 4096) && v.admission.settlement === "none";
190
+ }
191
+ if (v.continuationPrompt !== undefined)
192
+ return false;
193
+ if (v.admission.settlement !== "none")
194
+ return v.action === "allow_stop" && v.reason === "classified_stop" && assessment !== undefined && v.instruction !== undefined && envelope.goal?.status === "active" && (v.admission.settlement === "complete" ? v.classification === "complete" : ["blocked_permission", "blocked_external", "blocked_environment", "needs_user_input"].includes(v.classification));
195
+ return true;
196
+ }
197
+ function verifySumiStopReviewCommand(command, expected) {
198
+ let fd;
199
+ try {
200
+ if (!pathForm(command) || !digest(expected) || realpathSync(command) !== command)
201
+ return false;
202
+ const owners = [0, process.getuid?.()];
203
+ for (let path = dirname(command);; path = dirname(path)) {
204
+ const stat = lstatSync(path);
205
+ if (!stat.isDirectory() || !owners.includes(stat.uid) || (stat.mode & 18) !== 0)
206
+ return false;
207
+ if (path === dirname(path))
208
+ break;
209
+ }
210
+ fd = openSync(command, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
211
+ const before = fstatSync(fd);
212
+ if (!before.isFile() || !owners.includes(before.uid) || (before.mode & 18) !== 0 || (before.mode & 64) === 0 || before.size < 1 || before.size > 268435456)
213
+ return false;
214
+ const bytes = readFileSync(fd), after = fstatSync(fd), target = lstatSync(command);
215
+ return bytes.length === before.size && before.size === after.size && before.ino === after.ino && before.mtimeMs === after.mtimeMs && before.mode === after.mode && target.isFile() && target.ino === before.ino && target.dev === before.dev && target.size === before.size && target.mtimeMs === before.mtimeMs && realpathSync(command) === command && createHash("sha256").update(bytes).digest("hex") === expected;
216
+ } catch {
217
+ return false;
218
+ } finally {
219
+ if (fd !== undefined)
220
+ closeSync(fd);
221
+ }
222
+ }
223
+ var runSumiStopReviewCommand = (invocation) => new Promise((resolve) => {
224
+ let done = false, exited = false, stdoutBytes = 0, stderrBytes = 0;
225
+ const chunks = [];
226
+ let timer;
227
+ let child;
228
+ const finish = (result) => {
229
+ if (done)
230
+ return;
231
+ done = true;
232
+ clearTimeout(timer);
233
+ resolve(result);
234
+ };
235
+ const abort = () => {
236
+ if (done)
237
+ return;
238
+ if (child && !exited && child.exitCode === null && child.signalCode === null) {
239
+ try {
240
+ child.kill("SIGKILL");
241
+ } catch {}
242
+ }
243
+ child?.stdin?.destroy();
244
+ child?.stdout?.destroy();
245
+ child?.stderr?.destroy();
246
+ finish({ ok: false });
247
+ };
248
+ try {
249
+ child = spawn(invocation.command, invocation.args, { shell: false, detached: false, cwd: invocation.env.HOME, env: invocation.env, stdio: ["pipe", "pipe", "pipe"] });
250
+ timer = setTimeout(abort, invocation.timeoutMs);
251
+ child.once("exit", () => {
252
+ exited = true;
253
+ });
254
+ child.once("error", abort);
255
+ child.stdin.once("error", abort);
256
+ child.stdout.once("error", abort);
257
+ child.stderr.once("error", abort);
258
+ child.stdout.on("data", (chunk) => {
259
+ stdoutBytes += chunk.length;
260
+ if (stdoutBytes > invocation.maxOutputBytes)
261
+ abort();
262
+ else if (!done)
263
+ chunks.push(Buffer.from(chunk));
264
+ });
265
+ child.stderr.on("data", (chunk) => {
266
+ stderrBytes += chunk.length;
267
+ if (stderrBytes > 4096)
268
+ abort();
269
+ });
270
+ child.once("close", (code) => {
271
+ if (code !== 0)
272
+ return finish({ ok: false });
273
+ try {
274
+ finish({ ok: true, stdout: new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)) });
275
+ } catch {
276
+ finish({ ok: false });
277
+ }
278
+ });
279
+ child.stdin.end(invocation.input);
280
+ } catch {
281
+ abort();
282
+ }
283
+ });
284
+ async function requestParentStopReview(envelope, harness, pins, dependencies = {}) {
285
+ const unavailable = (reason) => ({
286
+ schema: "hooks.stop-review-result.v1",
287
+ action: "unavailable",
288
+ reason,
289
+ sessionId: envelope.sessionId,
290
+ turnId: envelope.turnId,
291
+ inputRevision: envelope.inputRevision,
292
+ admission: { mode: "parent_final_cas", harness, settlement: "none" }
293
+ });
294
+ let result = unavailable("native_review_unavailable");
295
+ try {
296
+ const source = (dependencies.environment ?? (() => process.env))();
297
+ if (source.HOOKS_STOP_REVIEW_DISABLED?.trim() === "1" || stopReviewClientContextRefused(source))
298
+ result = unavailable("invalid_configuration");
299
+ else if (!verifySumiStopReviewCommand(pins.hooksCommand, pins.hooksCommandSha256) || !verifySumiStopReviewCommand(pins.runtimeCommand, pins.runtimeCommandSha256))
300
+ result = unavailable("native_command_pin_mismatch");
301
+ else {
302
+ const input = JSON.stringify(envelope) + `
303
+ `;
304
+ {
305
+ const home = source.HOME || source.USERPROFILE || homedir();
306
+ if (!pathForm(home))
307
+ throw new Error(`${harness}_stop_review_invalid_home`);
308
+ const context = projectStopReviewClientContext(source);
309
+ const env = nativeChildEnv(source, { HOME: home, NO_COLOR: "1", ...context, ...restoreStopReviewClientContext(context) }, (name) => CONFIG_ENV.has(name));
310
+ const output = await (dependencies.run ?? runSumiStopReviewCommand)({
311
+ command: pins.runtimeCommand,
312
+ args: ["--config=/dev/null", "--no-env-file", "--no-macros", "--no-install", pins.hooksCommand, "run", "stop-review", "--target", harness],
313
+ input,
314
+ env,
315
+ timeoutMs: pins.timeoutMs,
316
+ maxOutputBytes: MAX_OUTPUT
317
+ });
318
+ if (output.ok && typeof output.stdout === "string" && Buffer.byteLength(output.stdout) <= MAX_OUTPUT) {
319
+ const parsed = JSON.parse(output.stdout);
320
+ result = isParentStopReviewResult(parsed, envelope, harness) ? parsed : unavailable("invalid_provider_response");
321
+ }
322
+ }
323
+ }
324
+ } catch {}
325
+ return result;
326
+ }
327
+ function parentStopReviewPins(options, harness, maxTimeoutMs = 45000) {
328
+ if (!record(options) || !pathForm(options.hooksCommand) || !digest(options.hooksCommandSha256) || !pathForm(options.runtimeCommand) || !digest(options.runtimeCommandSha256))
329
+ throw new Error(`${harness}_stop_review_invalid_command_pin`);
330
+ const timeoutMs = options.timeoutMs ?? 30000;
331
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > maxTimeoutMs)
332
+ throw new Error(`${harness}_stop_review_invalid_timeout`);
333
+ return {
334
+ hooksCommand: options.hooksCommand,
335
+ hooksCommandSha256: options.hooksCommandSha256,
336
+ runtimeCommand: options.runtimeCommand,
337
+ runtimeCommandSha256: options.runtimeCommandSha256,
338
+ timeoutMs
339
+ };
340
+ }
341
+
342
+ // src/lib/opencode-stop-plugin.ts
343
+ var OPENCODE_STOP_PLUGIN_ID = "hasna-hooks-stop-review";
344
+ var OPENCODE_STOP_PLUGIN_SCHEMA = "hasna.hooks.opencode-stop-plugin.v1";
345
+ var OPENCODE_STOP_HOOK = "experimental.session.stop";
346
+ var MAX_TIMEOUT_MS = 40000;
347
+ var record2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
348
+ var OPTION_KEYS = ["hooksCommand", "hooksCommandSha256", "runtimeCommand", "runtimeCommandSha256", "schema", "timeoutMs", "plugin", "pluginSha256"];
349
+ function isOpenCodeStopReviewCapability(v) {
350
+ return record2(v) && Object.isFrozen(v) && Object.keys(v).sort().join(",") === "admission,harness,hook,maxContinuations,schema" && v.schema === "hooks.stop-review.v1" && v.admission === "parent_final_cas" && v.harness === "opencode" && v.hook === OPENCODE_STOP_HOOK && v.maxContinuations === 1;
351
+ }
352
+ function createOpenCodeStopReviewPlugin(options, dependencies = {}) {
353
+ if (!record2(options) || !Object.keys(options).every((key) => OPTION_KEYS.includes(key)) || options.schema !== undefined && options.schema !== OPENCODE_STOP_PLUGIN_SCHEMA)
354
+ throw new Error("opencode_stop_review_invalid_options");
355
+ const pins = parentStopReviewPins(options, "opencode", MAX_TIMEOUT_MS);
356
+ return {
357
+ id: OPENCODE_STOP_PLUGIN_ID,
358
+ async server(input) {
359
+ if (!isOpenCodeStopReviewCapability(input?.experimental_stop_review))
360
+ throw new Error("opencode_stop_review_native_capability_unavailable");
361
+ return {
362
+ async[OPENCODE_STOP_HOOK](envelope, output) {
363
+ if (!record2(output) || output.recommendation !== undefined || !isSumiStopReviewEnvelope(envelope))
364
+ return;
365
+ const result = await requestParentStopReview(structuredClone(envelope), "opencode", pins, dependencies);
366
+ if (output.recommendation === undefined)
367
+ output.recommendation = result;
368
+ }
369
+ };
370
+ }
371
+ };
372
+ }
373
+ var opencode_stop_plugin_default = {
374
+ id: OPENCODE_STOP_PLUGIN_ID,
375
+ server: async (input, options) => createOpenCodeStopReviewPlugin(options).server(input)
376
+ };
377
+ export {
378
+ isOpenCodeStopReviewCapability,
379
+ opencode_stop_plugin_default as default,
380
+ createOpenCodeStopReviewPlugin,
381
+ OPENCODE_STOP_PLUGIN_SCHEMA,
382
+ OPENCODE_STOP_PLUGIN_ID,
383
+ OPENCODE_STOP_HOOK
384
+ };
@@ -0,0 +1,5 @@
1
+ import { type ApiKeyVerifier, type KeyStatusResolver } from "@hasna/contracts/auth";
2
+ /** Reuse the shared issuer's signature, scope and lifecycle contract. */
3
+ export declare function createRegistryVerifier(signingSecret: string, keyStatus: KeyStatusResolver): ApiKeyVerifier;
4
+ export declare function hasRegistrySigningConfiguration(): boolean;
5
+ export declare function authenticateRegistryRequest(request: Request, verifier?: ApiKeyVerifier): Promise<void>;
@@ -0,0 +1,4 @@
1
+ import { HostedRegistry } from "./lib/hosted-registry.js";
2
+ export declare function registryReady(): Promise<boolean>;
3
+ /** The canonical, authenticated hosted surface. No local catalog or disk-store fallback. */
4
+ export declare function handleRegistryRequest(request: Request, key: string | undefined, registry?: HostedRegistry): Promise<Response>;
@@ -9,6 +9,7 @@ export interface HooksCatalogEntry {
9
9
  "name": string;
10
10
  "version": string;
11
11
  "sha256": string;
12
+ "bundle_sha256"?: string;
12
13
  "events": Array<string>;
13
14
  "description": string;
14
15
  "source": string;
@@ -20,20 +21,24 @@ export interface HooksCatalog {
20
21
  export interface HooksLockEntry {
21
22
  "version": string;
22
23
  "sha256": string;
24
+ "bundle_sha256"?: string;
23
25
  "source": string;
24
26
  "pinned"?: boolean;
25
27
  "versions"?: Array<string>;
26
28
  }
27
29
  export interface HooksLock {
30
+ "profile"?: string;
31
+ "revision"?: number;
28
32
  "hooks": Record<string, HooksLockEntry>;
29
33
  }
30
34
  export interface HooksManifest {
35
+ "nativeTargetDispatch"?: boolean;
31
36
  "name": string;
32
37
  "version": string;
33
38
  "description"?: string;
34
39
  "events": Array<string>;
35
- "script": string;
36
- "script_kind"?: "inline" | "file";
40
+ "script": "hook.js";
41
+ "script_kind": "file";
37
42
  "args"?: Array<string>;
38
43
  "timeout_ms"?: number;
39
44
  }
@@ -45,15 +50,24 @@ export interface HooksError {
45
50
  "error": string;
46
51
  }
47
52
  export interface HooksPublishRequest {
48
- "name": string;
49
- "version"?: string;
53
+ "manifest": HooksManifest;
54
+ "script": string;
55
+ }
56
+ export interface HooksSelectionRequest {
57
+ "expected_revision": number;
58
+ "hooks": Record<string, {
59
+ "version": string;
60
+ "bundle_sha256": string;
61
+ }>;
50
62
  }
51
63
  export interface HooksPublishResponse {
52
64
  "ok": boolean;
65
+ "idempotent"?: boolean;
53
66
  "hook": {
54
67
  "name": string;
55
68
  "version": string;
56
69
  "sha256": string;
70
+ "bundle_sha256"?: string;
57
71
  };
58
72
  }
59
73
  export interface HooksRegistryApiClientOptions {
@@ -78,20 +92,26 @@ export declare class HooksRegistryApiClient {
78
92
  private readonly baseHeaders;
79
93
  constructor(options: HooksRegistryApiClientOptions);
80
94
  private request;
95
+ /** Liveness probe */
96
+ getHealth(init?: RequestInit): Promise<HooksHealth>;
97
+ /** This OpenAPI document */
98
+ getOpenApi(init?: RequestInit): Promise<Record<string, unknown>>;
99
+ /** Readiness probe — hosted registry tables are readable */
100
+ getReady(init?: RequestInit): Promise<HooksHealth>;
81
101
  /** List the full hook catalog with versions and sha256 */
82
102
  getCatalog(init?: RequestInit): Promise<HooksCatalog>;
83
- /** Publish/retrust a hook (requires the API key) */
103
+ /** Publish an immutable executable artifact (requires the API key) */
84
104
  putHook(body: HooksPublishRequest, init?: RequestInit): Promise<HooksPublishResponse>;
85
105
  /** Fetch one hook's manifest and script */
86
106
  getHookArtifact(name: string, version: string, init?: RequestInit): Promise<HooksArtifact>;
87
107
  /** Read the published hooks.lock with per-hook versions */
88
- getLock(init?: RequestInit): Promise<HooksLock>;
89
- /** Liveness probe */
90
- getHealth(init?: RequestInit): Promise<HooksHealth>;
91
- /** This OpenAPI document */
92
- getOpenApi(init?: RequestInit): Promise<Record<string, unknown>>;
93
- /** Readiness probe — the hooks.lock store is readable */
94
- getReady(init?: RequestInit): Promise<HooksHealth>;
108
+ getLock(query?: {
109
+ "profile"?: string;
110
+ }, init?: RequestInit): Promise<HooksLock>;
111
+ /** Read one exact hosted selection profile */
112
+ getSelection(profile: string, init?: RequestInit): Promise<HooksLock>;
113
+ /** Append a selection revision under its exact predecessor guard */
114
+ putSelection(profile: string, body: HooksSelectionRequest, init?: RequestInit): Promise<HooksLock>;
95
115
  /** Package version */
96
116
  getVersion(init?: RequestInit): Promise<HooksVersion>;
97
117
  }
@@ -18,6 +18,8 @@
18
18
  */
19
19
  import { hooksRegistryOrigin, type HooksRemoteAuthority } from "../lib/transport.js";
20
20
  import type { HooksCredentialOptions, HooksLocalOptInEnv } from "../lib/resolver-types.js";
21
+ import type { RegistryArtifact, RegistrySelection } from "../lib/registry-artifact.js";
22
+ export type { RegistryArtifact, RegistrySelection } from "../lib/registry-artifact.js";
21
23
  import { type HooksClientOptions } from "./authority.js";
22
24
  export type { HooksRemoteAuthority, HooksCredentialOptions, HooksLocalOptInEnv };
23
25
  export { hooksRegistryOrigin };
@@ -27,27 +29,31 @@ export { HooksRegistryApiClient, ApiError as HooksRegistryApiError } from "./gen
27
29
  export type { HooksRegistryApiClientOptions, HooksHealth, HooksVersion, HooksCatalogEntry, HooksCatalog, HooksLockEntry, HooksLock, HooksManifest, HooksArtifact, HooksError, HooksPublishRequest, HooksPublishResponse, } from "./generated.js";
28
30
  export { createHooksRegistryApiClient, hooksRegistryApiClientFor, } from "./registry-client.js";
29
31
  export type { HooksRegistryApiClientAuthority, ResolvedHooksRegistryApiClient, } from "./registry-client.js";
30
- /** One row of `GET /api/v1/catalog` — the registry's latest version of a hook. */
32
+ /** One row of `GET /v1/catalog` — the registry's latest version of a hook. */
31
33
  export interface HooksRegistryCatalogEntry {
32
34
  name: string;
33
35
  version: string;
34
36
  sha256: string;
37
+ bundle_sha256?: string;
35
38
  events: string[];
36
39
  description: string;
37
40
  source: string;
38
41
  versions: string[];
39
42
  }
40
- /** One pin of `GET /api/v1/lock` — the exact version the registry wants clients on. */
43
+ /** One pin of `GET /v1/lock` — the exact version the registry wants clients on. */
41
44
  export interface HooksRegistryLockEntry {
42
45
  version: string;
43
46
  sha256: string;
47
+ bundle_sha256?: string;
44
48
  source?: string;
45
49
  versions?: string[];
46
50
  }
47
51
  export interface HooksRegistryLock {
52
+ profile?: string;
53
+ revision?: number;
48
54
  hooks: Record<string, HooksRegistryLockEntry>;
49
55
  }
50
- /** `GET /api/v1/hooks/:name/:version` — a versioned artifact (manifest + script). */
56
+ /** `GET /v1/hooks/:name/:version` — a versioned artifact (manifest + script). */
51
57
  export interface HooksRegistryArtifact {
52
58
  manifest: {
53
59
  name: string;
@@ -58,10 +64,12 @@ export interface HooksRegistryArtifact {
58
64
  script_kind?: "inline" | "file";
59
65
  args?: string[];
60
66
  timeout_ms?: number;
67
+ nativeTargetDispatch?: boolean;
61
68
  };
62
69
  script: string;
63
70
  /** The registry's `x-hook-sha256` header for the served row, when present. */
64
71
  sha256: string | null;
72
+ bundle_sha256?: string | null;
65
73
  }
66
74
  /**
67
75
  * Hosted registry client. Holds the authority binding privately and resolves
@@ -75,7 +83,7 @@ export interface HooksRegistryArtifact {
75
83
  */
76
84
  export declare class HooksClient {
77
85
  #private;
78
- /** Registry origin WITHOUT `/v1` — the registry routes hang off `<origin>/api/v1`. */
86
+ /** Registry origin WITHOUT `/v1` — the registry routes hang off `<origin>/v1`. */
79
87
  readonly origin: string;
80
88
  /** The resolver's `<origin>/v1` authority, for diagnostics. */
81
89
  readonly v1BaseUrl: string;
@@ -93,8 +101,23 @@ export declare class HooksClient {
93
101
  name: string;
94
102
  }>;
95
103
  catalog(): Promise<HooksRegistryCatalogEntry[]>;
96
- lock(): Promise<HooksRegistryLock>;
104
+ lock(profile?: string): Promise<HooksRegistryLock>;
97
105
  artifact(name: string, version: string): Promise<HooksRegistryArtifact>;
106
+ publish(artifact: RegistryArtifact): Promise<{
107
+ ok: boolean;
108
+ idempotent: boolean;
109
+ hook: {
110
+ name: string;
111
+ version: string;
112
+ sha256: string;
113
+ bundle_sha256: string;
114
+ };
115
+ }>;
116
+ selection(profile: string): Promise<RegistrySelection>;
117
+ select(profile: string, expectedRevision: number, hooks: Record<string, {
118
+ version: string;
119
+ bundle_sha256: string;
120
+ }>): Promise<RegistrySelection>;
98
121
  private request;
99
122
  private getJson;
100
123
  }