@hasna/hooks 0.12.22 → 0.13.0

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.
@@ -14,7 +14,144 @@ import { homedir } from "os";
14
14
  function isNativeSafetyName(name) {
15
15
  return name === "trash-guard" || name === "workspace-repos-guard";
16
16
  }
17
+ var NATIVE_SAFETY_RUNTIME_KEY_SOURCE = String.raw`((s) => {
18
+ const parts = [s.dev, s.ino, s.size, s.mtimeNs, s.ctimeNs, s.birthtimeNs];
19
+ return parts.every((part) => typeof part === "bigint") && parts.slice(1).every((part) => part > 0n) ? parts.join(":") : null;
20
+ })`;
21
+ var NATIVE_SAFETY_TIMEOUT_STATUS = 93;
22
+ var NATIVE_SAFETY_TIMEOUT_MESSAGE = "Native safety guard refused (guard_timeout): verification did not finish within its time budget, so the command did not run. This is a timeout, not a policy decision; one retry is safe. If it repeats, report it and do not bypass the guard.";
23
+ var NATIVE_SAFETY_FAILURE_MESSAGE = "Native safety guard refused: verification or execution failed.";
24
+ var NATIVE_SAFETY_DIGEST_DIR = ".hasna/hooks/native/runtime-digests";
17
25
  var supervisorSource = String.raw`async function supervise(encoded) {
26
+ const fs = require("node:fs");
27
+ const path = require("node:path");
28
+ const crypto = require("node:crypto");
29
+ const cp = require("node:child_process");
30
+ const fail = () => { process.stderr.write("Native safety guard refused: verification or execution failed.\n"); process.exit(2); };
31
+ const timedOut = () => process.exit(${NATIVE_SAFETY_TIMEOUT_STATUS});
32
+ try {
33
+ const b = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
34
+ const uid = process.getuid();
35
+ const ancestry = (directory) => {
36
+ for (let parent = directory;;) {
37
+ const s = fs.lstatSync(parent);
38
+ if (!s.isDirectory() || ![0, uid].includes(s.uid) || (s.mode & 0o022)) throw Error();
39
+ if (parent === path.dirname(parent)) break;
40
+ parent = path.dirname(parent);
41
+ }
42
+ };
43
+ const open = (file, maximum) => {
44
+ if (!path.isAbsolute(file) || fs.realpathSync(file) !== file) throw Error();
45
+ ancestry(path.dirname(file));
46
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
47
+ const s = fs.fstatSync(fd);
48
+ if (!s.isFile() || ![0, uid].includes(s.uid) || (s.mode & 0o022) || s.size > maximum) { fs.closeSync(fd); throw Error(); }
49
+ return fd;
50
+ };
51
+ const check = (file, hash, maximum) => {
52
+ const fd = open(file, maximum);
53
+ try {
54
+ const bytes = fs.readFileSync(fd);
55
+ if (crypto.createHash("sha256").update(bytes).digest("hex") !== hash) throw Error();
56
+ return bytes;
57
+ } finally { fs.closeSync(fd); }
58
+ };
59
+ const keyOf = ${NATIVE_SAFETY_RUNTIME_KEY_SOURCE};
60
+ const schema = "hasna.hooks.native-safety-runtime-digest/v1";
61
+ const digests = path.join(b.home, "${NATIVE_SAFETY_DIGEST_DIR}");
62
+ const entry = path.join(digests, crypto.createHash("sha256").update(b.runtime).digest("hex") + ".json");
63
+ const privateDirectory = () => {
64
+ ancestry(path.dirname(digests));
65
+ const s = fs.lstatSync(digests);
66
+ if (!s.isDirectory() || s.uid !== uid || (s.mode & 0o077)) throw Error();
67
+ };
68
+ const remembered = (key) => {
69
+ try {
70
+ privateDirectory();
71
+ const fd = fs.openSync(entry, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
72
+ try {
73
+ const s = fs.fstatSync(fd);
74
+ if (!s.isFile() || s.uid !== uid || (s.mode & 0o077) || s.nlink !== 1 || s.size > 4096) return false;
75
+ const e = JSON.parse(fs.readFileSync(fd, "utf8"));
76
+ return !!e && Object.keys(e).sort().join() === "key,path,schema,sha256" && e.schema === schema
77
+ && e.path === b.runtime && e.sha256 === b.runtimeSHA256 && e.key === key;
78
+ } finally { fs.closeSync(fd); }
79
+ } catch { return false; }
80
+ };
81
+ const remember = (key) => {
82
+ let temporary;
83
+ try {
84
+ ancestry(path.dirname(digests));
85
+ try { fs.mkdirSync(digests, { mode: 0o700 }); } catch (error) { if (error.code !== "EEXIST") return; }
86
+ privateDirectory();
87
+ temporary = path.join(digests, "." + process.pid + "." + crypto.randomBytes(8).toString("hex") + ".tmp");
88
+ const fd = fs.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
89
+ try { fs.writeFileSync(fd, JSON.stringify({ schema, path: b.runtime, sha256: b.runtimeSHA256, key })); } finally { fs.closeSync(fd); }
90
+ fs.renameSync(temporary, entry);
91
+ temporary = undefined;
92
+ } catch {} finally { if (temporary) try { fs.unlinkSync(temporary); } catch {} }
93
+ };
94
+ const verifyRuntime = () => {
95
+ const fd = open(b.runtime, 200_000_000);
96
+ try {
97
+ const key = keyOf(fs.fstatSync(fd, { bigint: true }));
98
+ if (key !== null && remembered(key)) return;
99
+ const hash = crypto.createHash("sha256"), chunk = Buffer.allocUnsafe(1_048_576);
100
+ for (let total = 0, n; (n = fs.readSync(fd, chunk, 0, chunk.length, null)) > 0;) {
101
+ total += n;
102
+ if (total > 200_000_000) throw Error();
103
+ hash.update(chunk.subarray(0, n));
104
+ }
105
+ if (hash.digest("hex") !== b.runtimeSHA256) throw Error();
106
+ if (key !== null && keyOf(fs.fstatSync(fd, { bigint: true })) === key) remember(key);
107
+ } finally { fs.closeSync(fd); }
108
+ };
109
+ verifyRuntime();
110
+ const bytes = check(b.worker, b.workerSHA256, 256_000);
111
+ const deadline = setTimeout(timedOut, 1500);
112
+ const chunks = []; let size = 0;
113
+ for await (const chunk of process.stdin) {
114
+ size += chunk.length;
115
+ if (size > 1_048_576) throw Error();
116
+ chunks.push(chunk);
117
+ }
118
+ clearTimeout(deadline);
119
+ const input = Buffer.concat(chunks);
120
+ const child = cp.spawnSync(b.runtime, ["--config=/dev/null", "--no-env-file", "--no-macros", "--no-install", "--eval", bytes.toString("utf8"), b.name], {
121
+ input, env: { HOME: b.home, PATH: b.path }, cwd: "/", timeout: 2500, killSignal: "SIGKILL", maxBuffer: 1_048_576,
122
+ });
123
+ if (child.error?.code === "ETIMEDOUT") timedOut();
124
+ if (child.error || child.status !== 0 || child.signal || child.stderr.length) throw Error();
125
+ const result = JSON.parse(child.stdout.toString("utf8"));
126
+ if (!result || Array.isArray(result) || Object.keys(result).length !== 1) throw Error();
127
+ if (result.verdict === null) return;
128
+ const output = result.verdict?.hookSpecificOutput;
129
+ if (!output || Object.keys(result.verdict).length !== 1 || output.hookEventName !== "PreToolUse") throw Error();
130
+ if (output.permissionDecision === "deny") {
131
+ if (Object.keys(output).sort().join() !== "hookEventName,permissionDecision,permissionDecisionReason" || typeof output.permissionDecisionReason !== "string" || !output.permissionDecisionReason.trim()) throw Error();
132
+ } else if (output.permissionDecision === "allow") {
133
+ if (b.name !== "trash-guard" || Object.keys(output).sort().join() !== "hookEventName,permissionDecision,updatedInput" || !output.updatedInput || typeof output.updatedInput.command !== "string" || !output.updatedInput.command.trim()) throw Error();
134
+ } else throw Error();
135
+ process.stdout.write(JSON.stringify(result.verdict));
136
+ } catch { fail(); }
137
+ }`;
138
+ var quote = (value) => "'" + value.replaceAll("'", "'\\''") + "'";
139
+ var program = `(${supervisorSource})(process.argv[1]);`;
140
+ var shell = `cd / || exit 2
141
+ exec 3<&0 || exit 2
142
+ /usr/bin/env -i HOME="$3" PATH="$4" "$2" --config=/dev/null --no-env-file --no-macros --no-install --eval ${quote(program)} "$1" <&3 3<&- 2>/dev/null &
143
+ runner=$!
144
+ exec 3<&-
145
+ (fired=0; trap 'kill "$sleeper" 2>/dev/null; exit "$fired"' TERM; /bin/sleep 6 & sleeper=$!; wait "$sleeper"; fired=3; kill -KILL "$runner" 2>/dev/null; exit 3) &
146
+ watchdog=$!
147
+ wait "$runner" 2>/dev/null; result=$?
148
+ kill "$watchdog" 2>/dev/null; wait "$watchdog" 2>/dev/null; fired=$?
149
+ if [ "$result" -eq 0 ]; then exit 0; fi
150
+ if [ "$result" -eq ${NATIVE_SAFETY_TIMEOUT_STATUS} ] || { [ "$fired" -eq 3 ] && [ "$result" -gt 128 ]; }; then printf '%s\\n' ${quote(NATIVE_SAFETY_TIMEOUT_MESSAGE)} >&2; exit 2; fi
151
+ printf '%s\\n' ${quote(NATIVE_SAFETY_FAILURE_MESSAGE)} >&2; exit 2`;
152
+ var marker = " hasna-native-safety-v1 ";
153
+ var prefix = `/usr/bin/env -i /bin/sh -c ${quote(shell)}${marker}`;
154
+ var previousSupervisorSource = String.raw`async function supervise(encoded) {
18
155
  const fs = require("node:fs");
19
156
  const path = require("node:path");
20
157
  const crypto = require("node:crypto");
@@ -67,11 +204,10 @@ var supervisorSource = String.raw`async function supervise(encoded) {
67
204
  process.stdout.write(JSON.stringify(result.verdict));
68
205
  } catch { fail(); }
69
206
  }`;
70
- var quote = (value) => "'" + value.replaceAll("'", "'\\''") + "'";
71
- var program = `(${supervisorSource})(process.argv[1]);`;
72
- var shell = `cd / || exit 2
207
+ var previousProgram = `(${previousSupervisorSource})(process.argv[1]);`;
208
+ var previousShell = `cd / || exit 2
73
209
  exec 3<&0 || exit 2
74
- /usr/bin/env -i HOME="$3" PATH="$4" "$2" --config=/dev/null --no-env-file --no-macros --no-install --eval ${quote(program)} "$1" <&3 3<&- 2>/dev/null &
210
+ /usr/bin/env -i HOME="$3" PATH="$4" "$2" --config=/dev/null --no-env-file --no-macros --no-install --eval ${quote(previousProgram)} "$1" <&3 3<&- 2>/dev/null &
75
211
  runner=$!
76
212
  exec 3<&-
77
213
  (trap 'kill "$sleeper" 2>/dev/null; exit 0' TERM; /bin/sleep 6 & sleeper=$!; wait "$sleeper"; kill -KILL "$runner" 2>/dev/null) &
@@ -79,25 +215,39 @@ watchdog=$!
79
215
  wait "$runner"; result=$?
80
216
  kill "$watchdog" 2>/dev/null; wait "$watchdog" 2>/dev/null
81
217
  if [ "$result" -ne 0 ]; then printf '%s\\n' 'Native safety guard refused: verification or execution failed.' >&2; exit 2; fi`;
82
- var prefix = `/usr/bin/env -i /bin/sh -c ${quote(shell)} hasna-native-safety-v1 `;
218
+ var previousPrefix = `/usr/bin/env -i /bin/sh -c ${quote(previousShell)}${marker}`;
83
219
  function validateBinding(b) {
84
220
  if (!b || !isNativeSafetyName(b.name) || ![b.runtime, b.worker, b.home].every((p) => typeof p === "string" && isAbsolute(p) && !/[\0\r\n]/.test(p)) || ![b.runtimeSHA256, b.workerSHA256].every((h) => /^[0-9a-f]{64}$/.test(h)) || typeof b.path !== "string" || b.path.split(":").some((p) => !isAbsolute(p) || /[\0\r\n]/.test(p)))
85
221
  throw new Error("Invalid native safety binding");
86
222
  }
87
- function buildNativeSafetyCommand(binding) {
223
+ function commandWith(head, binding) {
88
224
  validateBinding(binding);
89
225
  const encoded = Buffer.from(JSON.stringify(binding)).toString("base64url");
90
- return prefix + [encoded, binding.runtime, binding.home, binding.path].map(quote).join(" ");
226
+ return head + [encoded, binding.runtime, binding.home, binding.path].map(quote).join(" ");
227
+ }
228
+ function buildPreviousNativeSafetyCommand(binding) {
229
+ return commandWith(previousPrefix, binding);
230
+ }
231
+ function managedPrefix(command) {
232
+ if (command.startsWith(prefix))
233
+ return prefix;
234
+ if (command.startsWith(previousPrefix))
235
+ return previousPrefix;
236
+ return;
237
+ }
238
+ function isPreviousNativeSafetyCommand(command) {
239
+ return command.startsWith(previousPrefix) && nativeSafetyCommandBinding(command) !== undefined;
91
240
  }
92
241
  function nativeSafetyCommandBinding(command) {
93
- if (!command.startsWith(prefix))
242
+ const head = managedPrefix(command);
243
+ if (!head)
94
244
  return;
95
- const encoded = command.slice(prefix.length).match(/^'([A-Za-z0-9_-]+)' /)?.[1];
245
+ const encoded = command.slice(head.length).match(/^'([A-Za-z0-9_-]+)' /)?.[1];
96
246
  if (!encoded || encoded.length > 16384)
97
247
  return;
98
248
  try {
99
249
  const binding = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
100
- return buildNativeSafetyCommand(binding) === command ? binding : undefined;
250
+ return commandWith(head, binding) === command ? binding : undefined;
101
251
  } catch {
102
252
  return;
103
253
  }
@@ -126,7 +276,7 @@ function pinEligibleFile(file, maximum, executable = false) {
126
276
  closeSync(fd);
127
277
  }
128
278
  }
129
- function installedNativeSafetyCommand(name) {
279
+ function installedNativeSafetyBinding(name) {
130
280
  const home = realpathSync(homedir());
131
281
  const runtime = realpathSync(process.execPath);
132
282
  const candidates = [join(import.meta.dir, "../../bin/native-safety-entry.js"), join(import.meta.dir, "../bin/native-safety-entry.js"), join(import.meta.dir, "native-safety-entry.js")];
@@ -134,7 +284,10 @@ function installedNativeSafetyCommand(name) {
134
284
  if (!worker)
135
285
  throw new Error("Bundled native safety runner is missing; build or reinstall @hasna/hooks before installing its guards.");
136
286
  const canonicalWorker = realpathSync(worker);
137
- return buildNativeSafetyCommand({ name, runtime, runtimeSHA256: pinEligibleFile(runtime, 200000000, true), worker: canonicalWorker, workerSHA256: pinEligibleFile(canonicalWorker, 256000), home, path: `${dirname(runtime)}:${join(home, ".bun/bin")}:/usr/local/bin:/usr/bin:/bin` });
287
+ return { name, runtime, runtimeSHA256: pinEligibleFile(runtime, 200000000, true), worker: canonicalWorker, workerSHA256: pinEligibleFile(canonicalWorker, 256000), home, path: `${dirname(runtime)}:${join(home, ".bun/bin")}:/usr/local/bin:/usr/bin:/bin` };
288
+ }
289
+ function installedSumiNativeSafetyCommand() {
290
+ return buildPreviousNativeSafetyCommand(installedNativeSafetyBinding("trash-guard"));
138
291
  }
139
292
 
140
293
  // src/native-safety.ts
@@ -191,6 +344,12 @@ function parseRecord(text, home) {
191
344
  throw new NativeSafetyError("binding_invalid");
192
345
  return record;
193
346
  }
347
+ function parseSumiRecord(text, home) {
348
+ const record = parseRecord(text, home);
349
+ if (!isPreviousNativeSafetyCommand(record.command))
350
+ throw new NativeSafetyError("binding_invalid");
351
+ return record;
352
+ }
194
353
  function syncDirectory(path) {
195
354
  const fd = openSync2(path, constants2.O_RDONLY | constants2.O_DIRECTORY | constants2.O_NOFOLLOW);
196
355
  try {
@@ -208,7 +367,7 @@ function readNativeSafetyRegistration(home = homedir2()) {
208
367
  try {
209
368
  home = canonicalHome(home);
210
369
  const path = join2(home, ".hasna/hooks/native", filename), text = readOwned(path);
211
- return { record: parseRecord(text, home), sha256: hash(text), path, text };
370
+ return { record: parseSumiRecord(text, home), sha256: hash(text), path, text };
212
371
  } catch (error) {
213
372
  if (error instanceof NativeSafetyError)
214
373
  throw error;
@@ -234,8 +393,8 @@ function nativeSafetyBindingIntegrityReason(home = homedir2()) {
234
393
  }
235
394
  function registerNativeSafety(options = {}) {
236
395
  const home = canonicalHome(options.home ?? homedir2());
237
- const text = nativeSafetyRecordText(options.command ?? installedNativeSafetyCommand("trash-guard"));
238
- parseRecord(text, home);
396
+ const text = nativeSafetyRecordText(options.command ?? installedSumiNativeSafetyCommand());
397
+ parseSumiRecord(text, home);
239
398
  for (const dir of [join2(home, ".hasna"), join2(home, ".hasna/hooks"), join2(home, ".hasna/hooks/native")]) {
240
399
  try {
241
400
  mkdirSync(dir, { mode: 448 });
@@ -429,14 +588,14 @@ async function verifyNativeSafetyExecutionRegistration(home = homedir2()) {
429
588
  return { path: before.path, sha256: before.sha256 };
430
589
  }
431
590
  export {
432
- verifyNativeSafetyRegistration,
433
- verifyNativeSafetyExecutionRegistration,
434
- verifyNativeSafetyCommand,
435
- registerNativeSafety,
436
- readNativeSafetyRegistration,
437
- nativeSafetyRecordText,
438
- nativeSafetyBindingIntegrityReason,
439
- evaluateNativeSafetyForExecution,
591
+ NativeSafetyError,
440
592
  evaluateNativeSafety,
441
- NativeSafetyError
593
+ evaluateNativeSafetyForExecution,
594
+ nativeSafetyBindingIntegrityReason,
595
+ nativeSafetyRecordText,
596
+ readNativeSafetyRegistration,
597
+ registerNativeSafety,
598
+ verifyNativeSafetyCommand,
599
+ verifyNativeSafetyExecutionRegistration,
600
+ verifyNativeSafetyRegistration
442
601
  };
@@ -160,9 +160,19 @@ function isSumiStopReviewEnvelope(v) {
160
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
161
  return false;
162
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))
163
+ if (!keys(runtime, [...FLAGS, "stopReason", "continuationCount"], ["agentPauseAdmission"]) || !FLAGS.every((key) => typeof runtime[key] === "boolean") || !STOP_REASONS.includes(runtime.stopReason) || !count(runtime.continuationCount))
164
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)))
165
+ if (runtime.agentPauseAdmission !== undefined && runtime.agentPauseAdmission !== "parent_final_cas")
166
+ return false;
167
+ if (v.goal !== undefined && v.goal !== null && (!record(v.goal) || !keys(v.goal, ["id", "objective", "status"], ["statusSource", "pauseReason", "activationEpoch"]) || !identifier(v.goal.id) || !text(v.goal.objective) || !GOAL_STATUSES.includes(v.goal.status)))
168
+ return false;
169
+ if (record(v.goal)) {
170
+ const pauseFacts = [v.goal.statusSource, v.goal.pauseReason, v.goal.activationEpoch];
171
+ const hasPauseFact = pauseFacts.some((fact) => fact !== undefined);
172
+ const exactPauseFacts = v.goal.status === "paused" && v.goal.statusSource === "agent" && v.goal.pauseReason === "agent" && count(v.goal.activationEpoch);
173
+ if (hasPauseFact !== (runtime.agentPauseAdmission !== undefined) || hasPauseFact && !exactPauseFacts)
174
+ return false;
175
+ } else if (runtime.agentPauseAdmission !== undefined)
166
176
  return false;
167
177
  return v.goalAvailability === undefined || ["known", "unavailable"].includes(v.goalAvailability);
168
178
  }
@@ -375,10 +385,10 @@ var opencode_stop_plugin_default = {
375
385
  server: async (input, options) => createOpenCodeStopReviewPlugin(options).server(input)
376
386
  };
377
387
  export {
378
- isOpenCodeStopReviewCapability,
379
- opencode_stop_plugin_default as default,
380
- createOpenCodeStopReviewPlugin,
381
- OPENCODE_STOP_PLUGIN_SCHEMA,
388
+ OPENCODE_STOP_HOOK,
382
389
  OPENCODE_STOP_PLUGIN_ID,
383
- OPENCODE_STOP_HOOK
390
+ OPENCODE_STOP_PLUGIN_SCHEMA,
391
+ createOpenCodeStopReviewPlugin,
392
+ opencode_stop_plugin_default as default,
393
+ isOpenCodeStopReviewCapability
384
394
  };
package/dist/sdk/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- // node_modules/@hasna/contracts/dist/client/transport.js
2
+ // ../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";
@@ -311,11 +311,14 @@ function readCredentialFile(path, apiKeyKeys, pointerKey) {
311
311
  return values[0] === undefined ? null : { apiKey: values[0] };
312
312
  }
313
313
  var CREDENTIAL_SHAPED_KEY = /(?:^|_)(?:API_KEY|KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH)(?:_|$)/;
314
- function appConfigDiskValue(name, env, keys) {
314
+ function appConfigDiskValue(name, env, keys, profile = null) {
315
+ if (profile !== null && !SAFE_PROFILE.test(profile)) {
316
+ throw new CredentialResolutionError(name, "The selected configuration profile is invalid.", ["profile"]);
317
+ }
315
318
  const wanted = keys.filter((key) => !CREDENTIAL_SHAPED_KEY.test(key));
316
319
  if (wanted.length === 0)
317
320
  return null;
318
- for (const path of credentialDiskSources(name, env)) {
321
+ for (const path of profileDiskSources(name, env, profile)) {
319
322
  const parsed = readAppConfigFile(path);
320
323
  if (!parsed)
321
324
  continue;
@@ -839,7 +842,16 @@ class ClientTransportConfigurationError extends Error {
839
842
  this.sources = Object.freeze([...sources]);
840
843
  }
841
844
  }
842
- function resolveClientTransportSnapshot(name, env = process.env, options = {}) {
845
+
846
+ class ClientCredentialMissingError extends ClientTransportConfigurationError {
847
+ authorityConfigured;
848
+ constructor(name, message, sources, authorityConfigured) {
849
+ super(name, message, sources);
850
+ this.authorityConfigured = authorityConfigured;
851
+ this.name = "ClientCredentialMissingError";
852
+ }
853
+ }
854
+ function resolveClientAuthoritySnapshot(name, env = process.env, options = {}) {
843
855
  env = snapshotClientEnvironment(name, env);
844
856
  const keys = clientTransportEnvKeys(name);
845
857
  const definedUrlEntries = keys.apiUrlKeys.filter((key) => Object.prototype.hasOwnProperty.call(env, key) && env[key] !== undefined).map((key) => ({ key, raw: String(env[key]) }));
@@ -852,12 +864,20 @@ function resolveClientTransportSnapshot(name, env = process.env, options = {}) {
852
864
  throw new ClientTransportConfigurationError(name, `${controlledUrl.key} contains ASCII control characters.`, [controlledUrl.key]);
853
865
  }
854
866
  const usableUrlEntries = definedUrlEntries.map((entry) => ({ key: entry.key, value: entry.raw.trim() }));
855
- if (usableUrlEntries.length > 1 && new Set(usableUrlEntries.map((entry) => entry.value)).size > 1) {
856
- throw new ClientTransportConfigurationError(name, `${usableUrlEntries.map((entry) => entry.key).join(" and ")} disagree; client authority aliases must be identical or only one may be set.`, usableUrlEntries.map((entry) => entry.key));
867
+ const normalizedAuthority = (entry) => {
868
+ try {
869
+ return toV1BaseUrl(entry.value);
870
+ } catch {
871
+ throw new ClientTransportConfigurationError(name, `Invalid API URL from ${entry.key}; use an absolute HTTPS URL or exact loopback HTTP authority without credentials, query or fragment.`, [entry.key]);
872
+ }
873
+ };
874
+ if (usableUrlEntries.length > 1 && new Set(usableUrlEntries.map(normalizedAuthority)).size > 1) {
875
+ throw new ClientTransportConfigurationError(name, `${usableUrlEntries.map((entry) => entry.key).join(" and ")} disagree; client authority aliases must select the same versioned API authority or only one may be set.`, usableUrlEntries.map((entry) => entry.key));
857
876
  }
858
877
  const envUrlHit = usableUrlEntries[0] ?? null;
859
878
  const keychainUrlHit = keychainConfigValue(name, env, options.credentials?.keychain);
860
- const diskConfigUrlHit = appConfigDiskValue(name, env, keys.apiUrlKeys);
879
+ const profile = options.bindUnpairedCredentialsToFleet ? options.credentials?.profile?.trim() || env.HASNA_PROFILE?.trim() || null : null;
880
+ const diskConfigUrlHit = appConfigDiskValue(name, env, keys.apiUrlKeys, profile);
861
881
  if (diskConfigUrlHit?.unusable) {
862
882
  throw new ClientTransportConfigurationError(name, `${diskConfigUrlHit.key} in ${diskConfigUrlHit.path} is declared but blank or malformed; public clients require a valid HTTPS service authority.`, [diskConfigUrlHit.path]);
863
883
  }
@@ -867,10 +887,23 @@ function resolveClientTransportSnapshot(name, env = process.env, options = {}) {
867
887
  ...diskConfigUrlHit ? [{ key: diskConfigUrlHit.path, value: diskConfigUrlHit.value.trim() }] : []
868
888
  ];
869
889
  const configuredUrl = urlCandidates[0] ?? null;
870
- const divergentUrls = urlCandidates.filter((candidate) => candidate.value !== configuredUrl?.value);
890
+ const normalizedUrls = urlCandidates.map(normalizedAuthority);
891
+ const divergentUrls = urlCandidates.filter((_, index) => normalizedUrls[index] !== normalizedUrls[0]);
871
892
  if (configuredUrl && divergentUrls.length > 0) {
872
893
  throw new ClientTransportConfigurationError(name, `${configuredUrl.key} and ${divergentUrls.map((candidate) => candidate.key).join(" and ")} select different service authorities; refusing to send a credential written for one authority to the other.`, urlCandidates.map((candidate) => candidate.key));
873
894
  }
895
+ if (configuredUrl && options.bindUnpairedCredentialsToFleet) {
896
+ try {
897
+ toV1BaseUrl(configuredUrl.value);
898
+ } catch (error) {
899
+ throw new ClientTransportConfigurationError(name, `Invalid API URL from ${configuredUrl.key}: ${error instanceof Error ? error.message : String(error)}`, [configuredUrl.key]);
900
+ }
901
+ }
902
+ return { keys, configuredUrl, envUrlHit, keychainUrlHit, diskConfigUrlHit };
903
+ }
904
+ function resolveClientTransportSnapshot(name, env = process.env, options = {}) {
905
+ env = snapshotClientEnvironment(name, env);
906
+ const { keys, configuredUrl, envUrlHit, keychainUrlHit, diskConfigUrlHit } = resolveClientAuthoritySnapshot(name, env, options);
874
907
  const warnings = [];
875
908
  if (configuredUrl && !envUrlHit) {
876
909
  warnings.push(`No ${keys.apiUrlKeys[0]} in the environment; the server URL in ${configuredUrl.key} was used, so this client connects to the server. ` + `Keep that entry aligned with the intended service authority.`);
@@ -880,7 +913,10 @@ function resolveClientTransportSnapshot(name, env = process.env, options = {}) {
880
913
  const diskHint = credentialDiskSourcesForMessage(name, env);
881
914
  const lead = configuredUrl ? `${configuredUrl.key} selects the HTTP server for '${name}', but no API key could be resolved` : `${keys.apiUrlKeys[0]} is not set and no API key could be resolved for '${name}'; a credential is required before the default fleet gateway authority applies`;
882
915
  warnings.push(`${lead}; refusing to create an unauthenticated client \u2014 public clients never fall back to SQLite or another local store. ` + `Looked in the Keychain (macOS only), then for a credential file at ${diskHint}, then for ${keys.apiKeyKeys[0]} in the environment.`);
883
- throw new ClientTransportConfigurationError(name, warnings.join(" "), [configuredUrl?.key ?? keys.apiUrlKeys[0]]);
916
+ const sources = [configuredUrl?.key ?? keys.apiUrlKeys[0]];
917
+ if (options.bindUnpairedCredentialsToFleet)
918
+ throw new ClientCredentialMissingError(name, warnings.join(" "), sources, configuredUrl !== null);
919
+ throw new ClientTransportConfigurationError(name, warnings.join(" "), sources);
884
920
  }
885
921
  if (credential.warning)
886
922
  warnings.push(credential.warning);
@@ -903,6 +939,14 @@ function resolveClientTransportSnapshot(name, env = process.env, options = {}) {
903
939
  const message = error instanceof Error ? error.message : String(error);
904
940
  throw new ClientTransportConfigurationError(name, `Invalid API URL from ${apiUrlSource}: ${message}`, [apiUrlSource]);
905
941
  }
942
+ if (options.bindUnpairedCredentialsToFleet && baseUrl !== toV1BaseUrl(defaultFleetGatewayBaseUrl(name))) {
943
+ const pairedDisk = diskConfigUrlHit?.path === credential.source && (credential.tier === "disk" || credential.tier === "profile" || credential.tier === "pointer");
944
+ const pairedKeychain = credential.tier === "keychain" && keychainUrlHit?.source === credential.source.replace(".api-key@", ".api-url@");
945
+ const deliberatePair = envUrlHit !== null && (credential.tier === "argument" || credential.tier === "override");
946
+ if (!pairedDisk && !pairedKeychain && !deliberatePair) {
947
+ throw new ClientTransportConfigurationError(name, "An unpaired legacy credential is bound to the fleet gateway. Configure a stored authority/credential pair or an explicit API key override for the intended authority; no credential was sent.");
948
+ }
949
+ }
906
950
  return {
907
951
  resolution: {
908
952
  transport: "http",
@@ -1464,12 +1508,12 @@ function createHooksClient(options = {}) {
1464
1508
  return new HooksClient(authority, { fetch: options.fetch });
1465
1509
  }
1466
1510
  export {
1467
- resolveHooksSdkAuthority,
1468
- hooksRegistryOrigin,
1469
- hooksRegistryApiClientFor,
1470
- createHooksRegistryApiClient,
1471
- createHooksClient,
1472
- ApiError as HooksRegistryApiError,
1511
+ HooksClient,
1473
1512
  HooksRegistryApiClient,
1474
- HooksClient
1513
+ ApiError as HooksRegistryApiError,
1514
+ createHooksClient,
1515
+ createHooksRegistryApiClient,
1516
+ hooksRegistryApiClientFor,
1517
+ hooksRegistryOrigin,
1518
+ resolveHooksSdkAuthority
1475
1519
  };
package/dist/storage.js CHANGED
@@ -166,7 +166,7 @@ function up(db) {
166
166
  db.exec(idx);
167
167
  }
168
168
  }
169
- var init_001_initial = __esm(() => {
169
+ var init__001_initial = __esm(() => {
170
170
  init_schema();
171
171
  });
172
172
 
@@ -195,7 +195,7 @@ function up2(db) {
195
195
  throw err;
196
196
  }
197
197
  }
198
- var init_002_session_events = __esm(() => {
198
+ var init__002_session_events = __esm(() => {
199
199
  init_schema();
200
200
  });
201
201
 
@@ -224,7 +224,7 @@ function up3(db) {
224
224
  throw err;
225
225
  }
226
226
  }
227
- var init_003_user_prompt_submit_event = __esm(() => {
227
+ var init__003_user_prompt_submit_event = __esm(() => {
228
228
  init_schema();
229
229
  });
230
230
 
@@ -248,7 +248,7 @@ var CREATE_HOOKS_TABLE = `
248
248
  last_verified_at TEXT
249
249
  )
250
250
  `, CREATE_HOOKS_INDEXES;
251
- var init_004_hooks_table = __esm(() => {
251
+ var init__004_hooks_table = __esm(() => {
252
252
  CREATE_HOOKS_INDEXES = [
253
253
  `CREATE INDEX IF NOT EXISTS idx_hooks_name ON hooks (name)`
254
254
  ];
@@ -279,7 +279,7 @@ function up5(db) {
279
279
  throw err;
280
280
  }
281
281
  }
282
- var init_005_subagent_start_event = __esm(() => {
282
+ var init__005_subagent_start_event = __esm(() => {
283
283
  init_schema();
284
284
  });
285
285
 
@@ -311,11 +311,11 @@ function runMigrations(db) {
311
311
  }
312
312
  var MIGRATIONS;
313
313
  var init_migrations = __esm(() => {
314
- init_001_initial();
315
- init_002_session_events();
316
- init_003_user_prompt_submit_event();
317
- init_004_hooks_table();
318
- init_005_subagent_start_event();
314
+ init__001_initial();
315
+ init__002_session_events();
316
+ init__003_user_prompt_submit_event();
317
+ init__004_hooks_table();
318
+ init__005_subagent_start_event();
319
319
  MIGRATIONS = [
320
320
  { version: "001_initial", up },
321
321
  { version: "002_session_events", up: up2 },
@@ -1047,29 +1047,29 @@ function coerceForSqlite(value) {
1047
1047
  return String(value);
1048
1048
  }
1049
1049
  export {
1050
- storageSync,
1051
- storagePush,
1052
- storagePull,
1053
- runStorageMigrations,
1054
- resolveTables,
1055
- parseStorageTables,
1056
- getSyncMetaAll,
1057
- getStorageStatus,
1058
- getStoragePg,
1059
- getStorageDatabaseUrl,
1060
- getStorageDatabaseEnvName,
1061
- getStorageDatabaseEnv,
1062
- getStorageBackend,
1063
- STORAGE_TABLES,
1064
- STORAGE_DATABASE_ENV,
1065
- STORAGE_BACKEND_ENV,
1066
- STORAGE_BACKENDS,
1067
- RETIRED_STORAGE_MODE_ENV,
1068
- PgAdapterAsync,
1069
- PG_MIGRATIONS,
1070
- HOOKS_STORAGE_TABLES,
1071
- HOOKS_STORAGE_FALLBACK_ENV,
1072
- HOOKS_STORAGE_ENV,
1050
+ HOOKS_STORAGE_BACKEND_ENV,
1073
1051
  HOOKS_STORAGE_BACKEND_FALLBACK_ENV,
1074
- HOOKS_STORAGE_BACKEND_ENV
1052
+ HOOKS_STORAGE_ENV,
1053
+ HOOKS_STORAGE_FALLBACK_ENV,
1054
+ HOOKS_STORAGE_TABLES,
1055
+ PG_MIGRATIONS,
1056
+ PgAdapterAsync,
1057
+ RETIRED_STORAGE_MODE_ENV,
1058
+ STORAGE_BACKENDS,
1059
+ STORAGE_BACKEND_ENV,
1060
+ STORAGE_DATABASE_ENV,
1061
+ STORAGE_TABLES,
1062
+ getStorageBackend,
1063
+ getStorageDatabaseEnv,
1064
+ getStorageDatabaseEnvName,
1065
+ getStorageDatabaseUrl,
1066
+ getStoragePg,
1067
+ getStorageStatus,
1068
+ getSyncMetaAll,
1069
+ parseStorageTables,
1070
+ resolveTables,
1071
+ runStorageMigrations,
1072
+ storagePull,
1073
+ storagePush,
1074
+ storageSync
1075
1075
  };
@@ -156,13 +156,30 @@ var count = (v) => Number.isSafeInteger(v) && v >= 0;
156
156
  var className = (v) => CLASSES.includes(v);
157
157
  var digest = (v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v);
158
158
  var pathForm = (v) => typeof v === "string" && isAbsolute(v) && normalize(v) === v && Buffer.byteLength(v) <= 4096 && !/[\u0000-\u001f\u007f]/.test(v);
159
+ var sumiStopCapability = (v) => {
160
+ if (!record(v) || !keys(v, ["schema", "admission", "harness"], ["agentPauseAdmission"]) || v.schema !== "hooks.stop-review.v1" || v.admission !== "parent_final_cas" || v.harness !== "sumi")
161
+ return null;
162
+ if (v.agentPauseAdmission === undefined)
163
+ return "legacy";
164
+ return v.agentPauseAdmission === "parent_final_cas" ? "agent_pause" : null;
165
+ };
159
166
  function isSumiStopReviewEnvelope(v) {
160
167
  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
168
  return false;
162
169
  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))
170
+ if (!keys(runtime, [...FLAGS, "stopReason", "continuationCount"], ["agentPauseAdmission"]) || !FLAGS.every((key) => typeof runtime[key] === "boolean") || !STOP_REASONS.includes(runtime.stopReason) || !count(runtime.continuationCount))
171
+ return false;
172
+ if (runtime.agentPauseAdmission !== undefined && runtime.agentPauseAdmission !== "parent_final_cas")
164
173
  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)))
174
+ if (v.goal !== undefined && v.goal !== null && (!record(v.goal) || !keys(v.goal, ["id", "objective", "status"], ["statusSource", "pauseReason", "activationEpoch"]) || !identifier(v.goal.id) || !text(v.goal.objective) || !GOAL_STATUSES.includes(v.goal.status)))
175
+ return false;
176
+ if (record(v.goal)) {
177
+ const pauseFacts = [v.goal.statusSource, v.goal.pauseReason, v.goal.activationEpoch];
178
+ const hasPauseFact = pauseFacts.some((fact) => fact !== undefined);
179
+ const exactPauseFacts = v.goal.status === "paused" && v.goal.statusSource === "agent" && v.goal.pauseReason === "agent" && count(v.goal.activationEpoch);
180
+ if (hasPauseFact !== (runtime.agentPauseAdmission !== undefined) || hasPauseFact && !exactPauseFacts)
181
+ return false;
182
+ } else if (runtime.agentPauseAdmission !== undefined)
166
183
  return false;
167
184
  return v.goalAvailability === undefined || ["known", "unavailable"].includes(v.goalAvailability);
168
185
  }
@@ -352,13 +369,15 @@ function createSumiStopReviewPlugin(options, dependencies = {}) {
352
369
  id: "local.hasna-hooks-stop-review",
353
370
  async setup(ctx) {
354
371
  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")
372
+ if (sumiStopCapability(capability) === null || typeof ctx.session.hook !== "function")
356
373
  throw new Error("sumi_stop_review_native_capability_unavailable");
357
374
  if (registered.has(ctx.session))
358
375
  return;
359
376
  await ctx.session.hook("stop", async (event) => {
360
377
  if (!record(event) || event.result !== undefined || !isSumiStopReviewEnvelope(event.envelope))
361
378
  return;
379
+ if (event.envelope.runtime.agentPauseAdmission === "parent_final_cas" && sumiStopCapability(ctx.session.stopReview) !== "agent_pause")
380
+ return;
362
381
  const envelope = structuredClone(event.envelope);
363
382
  const result = await requestParentStopReview(envelope, "sumi", { hooksCommand: command, hooksCommandSha256: commandHash, runtimeCommand: runtime, runtimeCommandSha256: runtimeHash, timeoutMs }, { ...dependencies, run });
364
383
  if (event.result === undefined && JSON.stringify(event.envelope) === JSON.stringify(envelope))
@@ -369,12 +388,12 @@ function createSumiStopReviewPlugin(options, dependencies = {}) {
369
388
  };
370
389
  }
371
390
  export {
372
- verifySumiStopReviewCommand,
373
- runSumiStopReviewCommand,
374
- requestParentStopReview,
375
- parentStopReviewPins,
376
- isSumiStopReviewResult,
377
- isSumiStopReviewEnvelope,
391
+ createSumiStopReviewPlugin,
378
392
  isParentStopReviewResult,
379
- createSumiStopReviewPlugin
393
+ isSumiStopReviewEnvelope,
394
+ isSumiStopReviewResult,
395
+ parentStopReviewPins,
396
+ requestParentStopReview,
397
+ runSumiStopReviewCommand,
398
+ verifySumiStopReviewCommand
380
399
  };