@hasna/hooks 0.12.10 → 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.
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 +3309 -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
package/dist/sdk/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- // ../../node_modules/.bun/@hasna+contracts@1.2.2+944b86d8024e79fa/node_modules/@hasna/contracts/dist/client/transport.js
2
+ // node_modules/@hasna/contracts/dist/client/transport.js
3
3
  import { isIP } from "net";
4
4
  import { spawnSync } from "child_process";
5
5
  import { closeSync as closeSync2, fstatSync as fstatSync2, openSync as openSync2, readFileSync as readFileSync2 } from "fs";
@@ -1268,55 +1268,69 @@ class HooksRegistryApiClient {
1268
1268
  }
1269
1269
  return data;
1270
1270
  }
1271
- async getCatalog(init) {
1272
- return this.request("GET", `/api/v1/catalog`, {
1271
+ async getHealth(init) {
1272
+ return this.request("GET", `/health`, {
1273
1273
  body: undefined,
1274
1274
  query: undefined,
1275
1275
  init
1276
1276
  });
1277
1277
  }
1278
- async putHook(body, init) {
1279
- return this.request("PUT", `/api/v1/hooks`, {
1280
- body,
1278
+ async getOpenApi(init) {
1279
+ return this.request("GET", `/openapi.json`, {
1280
+ body: undefined,
1281
1281
  query: undefined,
1282
1282
  init
1283
1283
  });
1284
1284
  }
1285
- async getHookArtifact(name, version, init) {
1286
- return this.request("GET", `/api/v1/hooks/${encodeURIComponent(String(name))}/${encodeURIComponent(String(version))}`, {
1285
+ async getReady(init) {
1286
+ return this.request("GET", `/ready`, {
1287
1287
  body: undefined,
1288
1288
  query: undefined,
1289
1289
  init
1290
1290
  });
1291
1291
  }
1292
- async getLock(init) {
1293
- return this.request("GET", `/api/v1/lock`, {
1292
+ async getCatalog(init) {
1293
+ return this.request("GET", `/v1/catalog`, {
1294
1294
  body: undefined,
1295
1295
  query: undefined,
1296
1296
  init
1297
1297
  });
1298
1298
  }
1299
- async getHealth(init) {
1300
- return this.request("GET", `/health`, {
1301
- body: undefined,
1299
+ async putHook(body, init) {
1300
+ return this.request("PUT", `/v1/hooks`, {
1301
+ body,
1302
1302
  query: undefined,
1303
1303
  init
1304
1304
  });
1305
1305
  }
1306
- async getOpenApi(init) {
1307
- return this.request("GET", `/openapi.json`, {
1306
+ async getHookArtifact(name, version, init) {
1307
+ return this.request("GET", `/v1/hooks/${encodeURIComponent(String(name))}/${encodeURIComponent(String(version))}`, {
1308
1308
  body: undefined,
1309
1309
  query: undefined,
1310
1310
  init
1311
1311
  });
1312
1312
  }
1313
- async getReady(init) {
1314
- return this.request("GET", `/ready`, {
1313
+ async getLock(query, init) {
1314
+ return this.request("GET", `/v1/lock`, {
1315
+ body: undefined,
1316
+ query,
1317
+ init
1318
+ });
1319
+ }
1320
+ async getSelection(profile, init) {
1321
+ return this.request("GET", `/v1/selections/${encodeURIComponent(String(profile))}`, {
1315
1322
  body: undefined,
1316
1323
  query: undefined,
1317
1324
  init
1318
1325
  });
1319
1326
  }
1327
+ async putSelection(profile, body, init) {
1328
+ return this.request("PUT", `/v1/selections/${encodeURIComponent(String(profile))}`, {
1329
+ body,
1330
+ query: undefined,
1331
+ init
1332
+ });
1333
+ }
1320
1334
  async getVersion(init) {
1321
1335
  return this.request("GET", `/version`, {
1322
1336
  body: undefined,
@@ -1395,32 +1409,43 @@ class HooksClient {
1395
1409
  return await this.getJson("/health");
1396
1410
  }
1397
1411
  async catalog() {
1398
- const body = await this.getJson("/api/v1/catalog");
1412
+ const body = await this.getJson("/v1/catalog");
1399
1413
  if (!body || !Array.isArray(body.hooks)) {
1400
1414
  throw new Error(`hooks registry catalog at ${this.origin} is malformed: missing hooks array`);
1401
1415
  }
1402
1416
  return body.hooks;
1403
1417
  }
1404
- async lock() {
1405
- const body = await this.getJson("/api/v1/lock");
1418
+ async lock(profile) {
1419
+ const body = await this.getJson("/v1/lock" + (profile ? "?profile=" + encodeURIComponent(profile) : ""));
1406
1420
  if (!body || typeof body.hooks !== "object" || body.hooks === null || Array.isArray(body.hooks)) {
1407
1421
  throw new Error(`hooks registry lock at ${this.origin} is malformed: missing hooks map`);
1408
1422
  }
1409
1423
  return body;
1410
1424
  }
1411
1425
  async artifact(name, version) {
1412
- const res = await this.request(`/api/v1/hooks/${encodeURIComponent(name)}/${encodeURIComponent(version)}`);
1426
+ const res = await this.request(`/v1/hooks/${encodeURIComponent(name)}/${encodeURIComponent(version)}`);
1413
1427
  const body = await res.json();
1414
1428
  if (!body || typeof body !== "object" || !body.manifest || typeof body.script !== "string") {
1415
1429
  throw new Error(`artifact for '${name}@${version}' from ${this.origin} is malformed`);
1416
1430
  }
1417
- return { ...body, sha256: res.headers.get("x-hook-sha256") };
1431
+ return { ...body, sha256: res.headers.get("x-hook-sha256"), bundle_sha256: res.headers.get("x-hook-bundle-sha256") };
1418
1432
  }
1419
- async request(path) {
1433
+ async publish(artifact) {
1434
+ return (await this.request("/v1/hooks", { method: "PUT", body: JSON.stringify(artifact) })).json();
1435
+ }
1436
+ async selection(profile) {
1437
+ return this.getJson("/v1/selections/" + encodeURIComponent(profile));
1438
+ }
1439
+ async select(profile, expectedRevision, hooks) {
1440
+ return (await this.request("/v1/selections/" + encodeURIComponent(profile), { method: "PUT", body: JSON.stringify({ expected_revision: expectedRevision, hooks }) })).json();
1441
+ }
1442
+ async request(path, init = {}) {
1420
1443
  const authority = await resolveHooksRequestAuthority(this.#authority);
1421
1444
  const url = `${authority.origin}${path.startsWith("/") ? path : `/${path}`}`;
1422
1445
  const res = await this.#fetch(url, {
1423
- headers: { accept: "application/json", "x-api-key": authority.apiKey },
1446
+ ...init,
1447
+ headers: { accept: "application/json", "content-type": "application/json", "x-api-key": authority.apiKey },
1448
+ signal: AbortSignal.timeout(15000),
1424
1449
  redirect: "manual"
1425
1450
  });
1426
1451
  if (!res.ok) {
@@ -36,7 +36,7 @@ import { HooksRegistryApiClient } from "./generated.js";
36
36
  type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
37
37
  /** The fields a resolver-backed client exposes for diagnostics. Never a value. */
38
38
  export interface HooksRegistryApiClientAuthority {
39
- /** Registry origin WITHOUT `/v1`; the registry routes hang off `<origin>/api/v1`. */
39
+ /** Registry origin WITHOUT `/v1`; the registry routes hang off `<origin>/v1`. */
40
40
  readonly authorityOrigin: string;
41
41
  /** WHERE the credential came from (env NAME, Keychain reference, file PATH). Never a value. */
42
42
  readonly apiKeySource: string | null;
package/dist/serve.d.ts CHANGED
@@ -1,9 +1,8 @@
1
1
  #!/usr/bin/env bun
2
2
  /**
3
- * hooks serve — the local registry HTTP API.
4
- *
5
- * Catalog and artifact reads are open; publishing (PUT) requires the API key.
6
- * The published set is hooks.lock, the same pin file the client syncs from.
3
+ * hooks serve — the hosted immutable registry and explicit self-host surface.
4
+ * Canonical hosted routes authenticate every operation and use PostgreSQL.
5
+ * Explicit local self-hosting retains the legacy catalog and pin-file API.
7
6
  */
8
7
  export declare const DEFAULT_SERVE_PORT = 39428;
9
8
  export declare const SERVE_HOST = "127.0.0.1";
@@ -27,6 +26,7 @@ export interface ArtifactPayload {
27
26
  script_kind?: "inline" | "file";
28
27
  args?: string[];
29
28
  timeout_ms?: number;
29
+ nativeTargetDispatch?: boolean;
30
30
  };
31
31
  script: string;
32
32
  }
package/dist/storage.js CHANGED
@@ -673,8 +673,39 @@ function wantsSslFor(connectionString) {
673
673
 
674
674
  class PgAdapterAsync {
675
675
  pool;
676
- constructor(connectionString) {
677
- this.pool = new pg.Pool({ connectionString, ssl: sslConfigFor(connectionString) });
676
+ constructor(connectionString, options = {}) {
677
+ const timeout = options.timeoutMs;
678
+ this.pool = new pg.Pool({ connectionString, ssl: sslConfigFor(connectionString), ...timeout ? { connectionTimeoutMillis: timeout, query_timeout: timeout, statement_timeout: timeout } : {} });
679
+ }
680
+ async readOnlyAll(sql, ...params) {
681
+ const client = await this.pool.connect();
682
+ try {
683
+ await client.query("BEGIN READ ONLY");
684
+ return (await client.query(translatePlaceholders(sql), normalizeParams(params))).rows;
685
+ } finally {
686
+ try {
687
+ await client.query("ROLLBACK");
688
+ } finally {
689
+ client.release();
690
+ }
691
+ }
692
+ }
693
+ async transaction(operation) {
694
+ const client = await this.pool.connect();
695
+ try {
696
+ await client.query("BEGIN");
697
+ const result = await operation({
698
+ run: async (sql, ...params) => ({ changes: (await client.query(translatePlaceholders(sql), normalizeParams(params))).rowCount ?? 0 }),
699
+ all: async (sql, ...params) => (await client.query(translatePlaceholders(sql), normalizeParams(params))).rows
700
+ });
701
+ await client.query("COMMIT");
702
+ return result;
703
+ } catch (error) {
704
+ await client.query("ROLLBACK");
705
+ throw error;
706
+ } finally {
707
+ client.release();
708
+ }
678
709
  }
679
710
  async run(sql, ...params) {
680
711
  const result = await this.pool.query(translatePlaceholders(sql), normalizeParams(params));
@@ -0,0 +1,380 @@
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 isSumiStopReviewResult(v, envelope) {
170
+ return isParentStopReviewResult(v, envelope, "sumi");
171
+ }
172
+ function isParentStopReviewResult(v, envelope, harness) {
173
+ 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))
174
+ return false;
175
+ if (v.httpStatus !== undefined && (!Number.isInteger(v.httpStatus) || v.httpStatus < 100 || v.httpStatus > 599))
176
+ return false;
177
+ if (v.classification !== undefined && !className(v.classification))
178
+ return false;
179
+ 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)))
180
+ return false;
181
+ const assessment = v.assessment;
182
+ if (assessment !== undefined) {
183
+ 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))
184
+ return false;
185
+ const total = CLASSES.reduce((sum, key) => sum + assessment.probabilities[key], 0);
186
+ if (Math.abs(total - 1) > 0.02)
187
+ return false;
188
+ }
189
+ if (v.continuationPrompt !== undefined && !text(v.continuationPrompt, 4096))
190
+ return false;
191
+ if (v.action === "continue") {
192
+ return v.reason === "actionable_remaining" && v.classification === "actionable_remaining" && assessment !== undefined && v.instruction !== undefined && text(v.continuationPrompt, 4096) && v.admission.settlement === "none";
193
+ }
194
+ if (v.continuationPrompt !== undefined)
195
+ return false;
196
+ if (v.admission.settlement !== "none")
197
+ 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));
198
+ return true;
199
+ }
200
+ function verifySumiStopReviewCommand(command, expected) {
201
+ let fd;
202
+ try {
203
+ if (!pathForm(command) || !digest(expected) || realpathSync(command) !== command)
204
+ return false;
205
+ const owners = [0, process.getuid?.()];
206
+ for (let path = dirname(command);; path = dirname(path)) {
207
+ const stat = lstatSync(path);
208
+ if (!stat.isDirectory() || !owners.includes(stat.uid) || (stat.mode & 18) !== 0)
209
+ return false;
210
+ if (path === dirname(path))
211
+ break;
212
+ }
213
+ fd = openSync(command, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
214
+ const before = fstatSync(fd);
215
+ if (!before.isFile() || !owners.includes(before.uid) || (before.mode & 18) !== 0 || (before.mode & 64) === 0 || before.size < 1 || before.size > 268435456)
216
+ return false;
217
+ const bytes = readFileSync(fd), after = fstatSync(fd), target = lstatSync(command);
218
+ 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;
219
+ } catch {
220
+ return false;
221
+ } finally {
222
+ if (fd !== undefined)
223
+ closeSync(fd);
224
+ }
225
+ }
226
+ var runSumiStopReviewCommand = (invocation) => new Promise((resolve) => {
227
+ let done = false, exited = false, stdoutBytes = 0, stderrBytes = 0;
228
+ const chunks = [];
229
+ let timer;
230
+ let child;
231
+ const finish = (result) => {
232
+ if (done)
233
+ return;
234
+ done = true;
235
+ clearTimeout(timer);
236
+ resolve(result);
237
+ };
238
+ const abort = () => {
239
+ if (done)
240
+ return;
241
+ if (child && !exited && child.exitCode === null && child.signalCode === null) {
242
+ try {
243
+ child.kill("SIGKILL");
244
+ } catch {}
245
+ }
246
+ child?.stdin?.destroy();
247
+ child?.stdout?.destroy();
248
+ child?.stderr?.destroy();
249
+ finish({ ok: false });
250
+ };
251
+ try {
252
+ child = spawn(invocation.command, invocation.args, { shell: false, detached: false, cwd: invocation.env.HOME, env: invocation.env, stdio: ["pipe", "pipe", "pipe"] });
253
+ timer = setTimeout(abort, invocation.timeoutMs);
254
+ child.once("exit", () => {
255
+ exited = true;
256
+ });
257
+ child.once("error", abort);
258
+ child.stdin.once("error", abort);
259
+ child.stdout.once("error", abort);
260
+ child.stderr.once("error", abort);
261
+ child.stdout.on("data", (chunk) => {
262
+ stdoutBytes += chunk.length;
263
+ if (stdoutBytes > invocation.maxOutputBytes)
264
+ abort();
265
+ else if (!done)
266
+ chunks.push(Buffer.from(chunk));
267
+ });
268
+ child.stderr.on("data", (chunk) => {
269
+ stderrBytes += chunk.length;
270
+ if (stderrBytes > 4096)
271
+ abort();
272
+ });
273
+ child.once("close", (code) => {
274
+ if (code !== 0)
275
+ return finish({ ok: false });
276
+ try {
277
+ finish({ ok: true, stdout: new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)) });
278
+ } catch {
279
+ finish({ ok: false });
280
+ }
281
+ });
282
+ child.stdin.end(invocation.input);
283
+ } catch {
284
+ abort();
285
+ }
286
+ });
287
+ async function requestParentStopReview(envelope, harness, pins, dependencies = {}) {
288
+ const unavailable = (reason) => ({
289
+ schema: "hooks.stop-review-result.v1",
290
+ action: "unavailable",
291
+ reason,
292
+ sessionId: envelope.sessionId,
293
+ turnId: envelope.turnId,
294
+ inputRevision: envelope.inputRevision,
295
+ admission: { mode: "parent_final_cas", harness, settlement: "none" }
296
+ });
297
+ let result = unavailable("native_review_unavailable");
298
+ try {
299
+ const source = (dependencies.environment ?? (() => process.env))();
300
+ if (source.HOOKS_STOP_REVIEW_DISABLED?.trim() === "1" || stopReviewClientContextRefused(source))
301
+ result = unavailable("invalid_configuration");
302
+ else if (!verifySumiStopReviewCommand(pins.hooksCommand, pins.hooksCommandSha256) || !verifySumiStopReviewCommand(pins.runtimeCommand, pins.runtimeCommandSha256))
303
+ result = unavailable("native_command_pin_mismatch");
304
+ else {
305
+ const input = JSON.stringify(envelope) + `
306
+ `;
307
+ {
308
+ const home = source.HOME || source.USERPROFILE || homedir();
309
+ if (!pathForm(home))
310
+ throw new Error(`${harness}_stop_review_invalid_home`);
311
+ const context = projectStopReviewClientContext(source);
312
+ const env = nativeChildEnv(source, { HOME: home, NO_COLOR: "1", ...context, ...restoreStopReviewClientContext(context) }, (name) => CONFIG_ENV.has(name));
313
+ const output = await (dependencies.run ?? runSumiStopReviewCommand)({
314
+ command: pins.runtimeCommand,
315
+ args: ["--config=/dev/null", "--no-env-file", "--no-macros", "--no-install", pins.hooksCommand, "run", "stop-review", "--target", harness],
316
+ input,
317
+ env,
318
+ timeoutMs: pins.timeoutMs,
319
+ maxOutputBytes: MAX_OUTPUT
320
+ });
321
+ if (output.ok && typeof output.stdout === "string" && Buffer.byteLength(output.stdout) <= MAX_OUTPUT) {
322
+ const parsed = JSON.parse(output.stdout);
323
+ result = isParentStopReviewResult(parsed, envelope, harness) ? parsed : unavailable("invalid_provider_response");
324
+ }
325
+ }
326
+ }
327
+ } catch {}
328
+ return result;
329
+ }
330
+ function parentStopReviewPins(options, harness, maxTimeoutMs = 45000) {
331
+ if (!record(options) || !pathForm(options.hooksCommand) || !digest(options.hooksCommandSha256) || !pathForm(options.runtimeCommand) || !digest(options.runtimeCommandSha256))
332
+ throw new Error(`${harness}_stop_review_invalid_command_pin`);
333
+ const timeoutMs = options.timeoutMs ?? 30000;
334
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > maxTimeoutMs)
335
+ throw new Error(`${harness}_stop_review_invalid_timeout`);
336
+ return {
337
+ hooksCommand: options.hooksCommand,
338
+ hooksCommandSha256: options.hooksCommandSha256,
339
+ runtimeCommand: options.runtimeCommand,
340
+ runtimeCommandSha256: options.runtimeCommandSha256,
341
+ timeoutMs
342
+ };
343
+ }
344
+ function createSumiStopReviewPlugin(options, dependencies = {}) {
345
+ const pins = parentStopReviewPins(options, "sumi");
346
+ const timeoutMs = pins.timeoutMs;
347
+ const { hooksCommand: command, hooksCommandSha256: commandHash } = pins;
348
+ const { runtimeCommand: runtime, runtimeCommandSha256: runtimeHash } = pins;
349
+ const registered = new WeakSet;
350
+ const run = dependencies.run ?? runSumiStopReviewCommand;
351
+ return {
352
+ id: "local.hasna-hooks-stop-review",
353
+ async setup(ctx) {
354
+ const capability = ctx?.session?.stopReview;
355
+ if (!record(capability) || capability.schema !== "hooks.stop-review.v1" || capability.admission !== "parent_final_cas" || capability.harness !== "sumi" || typeof ctx.session.hook !== "function")
356
+ throw new Error("sumi_stop_review_native_capability_unavailable");
357
+ if (registered.has(ctx.session))
358
+ return;
359
+ await ctx.session.hook("stop", async (event) => {
360
+ if (!record(event) || event.result !== undefined || !isSumiStopReviewEnvelope(event.envelope))
361
+ return;
362
+ const envelope = structuredClone(event.envelope);
363
+ const result = await requestParentStopReview(envelope, "sumi", { hooksCommand: command, hooksCommandSha256: commandHash, runtimeCommand: runtime, runtimeCommandSha256: runtimeHash, timeoutMs }, { ...dependencies, run });
364
+ if (event.result === undefined && JSON.stringify(event.envelope) === JSON.stringify(envelope))
365
+ event.result = result;
366
+ });
367
+ registered.add(ctx.session);
368
+ }
369
+ };
370
+ }
371
+ export {
372
+ verifySumiStopReviewCommand,
373
+ runSumiStopReviewCommand,
374
+ requestParentStopReview,
375
+ parentStopReviewPins,
376
+ isSumiStopReviewResult,
377
+ isSumiStopReviewEnvelope,
378
+ isParentStopReviewResult,
379
+ createSumiStopReviewPlugin
380
+ };