@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.
package/README.md CHANGED
@@ -10,6 +10,7 @@ Open source hooks library for AI coding agents - Install safety, quality, and au
10
10
  `@hasna/hooks` installs hooks into AI coding agents. A hook is a small program the agent runs at a fixed point: before a shell command, after a file edit, or when a turn ends. Hooks block a mistake, check the work, or automate a step. One CLI installs, lists, updates and removes them.
11
11
 
12
12
  - **Agents.** Claude Code (the default target) and Codex. Compatible OpenCode and Sumi builds are supported for the stop-review hook. Gemini CLI is an install target (`--target gemini`), but the bundled shell guards do not yet recognise Gemini's tool names (`run_shell_command` rather than `Bash`), so do not rely on them there yet. Codewith targets remain for existing setups, but Codewith is deprecated.
13
+ - **Install targets.** `--target` also accepts `qwen`, `muse`, `kimi`, `pi` and `cursor`, each writing that harness's own config with an entry that calls `hooks run <hook> --target <name>`. They are not interchangeable: Muse hands over the final message as a quoted JSON string, which `hooks run --target muse` parses once; Kimi's stop payload carries no assistant text and Kimi blocks with exit 2 and stderr; Pi runs hooks through the `hasna-pi-hooks` bridge and receives no assistant text; Cursor's stop hook can neither block the turn nor carry the assistant text. A hook whose manifest sets `requires_final_message` or `requires_block` is refused at install on a target that cannot honour it, with the measured reason, instead of being installed to do nothing. `opencode` and `sumi` have no generic install path and are refused by name; their stop review is registered through `hooks install stop-review --target <opencode|sumi>`.
13
14
  - **Catalog.** 57 bundled hooks in 10 categories, listed below. You can also install your own hooks from a local directory, a git URL or a manifest URL.
14
15
  - **Safety core.** Guards that:
15
16
  - block destructive git commands (gitguard);
@@ -232,6 +233,41 @@ reinstalling the registration and reviewing the new native trust definition. Uns
232
233
  installation paths are refused before settings are written. Codex also requires
233
234
  trust through `/hooks`; registration alone does not prove interception.
234
235
 
236
+ When verification runs out of time (the six-second watchdog, the 2.5-second
237
+ worker deadline or the 1.5-second input deadline), the guard blocks the call with
238
+ `Native safety guard refused (guard_timeout): …`. The command did not run, and one
239
+ retry is safe. A timeout that repeats means the host is overloaded, or that the
240
+ registration is stale: a runtime that no longer matches its pin is never cached,
241
+ so it is hashed in full on every call and, under load, can time out before it is
242
+ refused. Check with `hooks safety verify` from an operator shell, report it, and do
243
+ not bypass the guard. Every other failure, including a runtime or worker that no
244
+ longer matches its pin, keeps `Native safety guard refused: verification or
245
+ execution failed.`, and a policy refusal is the guard's own reason.
246
+
247
+ After a full hash of the pinned Bun runtime matches, the guard records the
248
+ runtime's exact stat key (device, inode, size, mtime, ctime and birth time) in an
249
+ owner-only entry under `~/.hasna/hooks/native/runtime-digests/`, and later calls
250
+ skip the runtime hash while that key is unchanged. Any write to the runtime
251
+ changes its ctime, so it is hashed in full again. The cache is used only where
252
+ `~/.hasna/hooks/native` already exists, under directories that are not writable
253
+ by group or others. `hooks safety registration-apply`, `hooks safety trust-apply`
254
+ and the Sumi guard record create it; a stateless `hooks safety install` does not,
255
+ and the guard never creates it itself. Without it, every call hashes the runtime
256
+ in full, as before. The worker is still hashed on every call.
257
+
258
+ The Sumi guard record (`~/.hasna/hooks/native/sumi-trash-guard.json`) keeps the
259
+ previous template. Sumi reads that record with its own bundled copy of this SDK,
260
+ and every released copy accepts only that template; a record it cannot parse makes
261
+ it refuse every shell. Every Sumi writer here (`hooks safety provision`, `hooks
262
+ install`, `hooks upgrade`, the package lifecycle script, `hooks safety startup
263
+ registration-apply --target sumi` and `hooks safety install trash-guard --target
264
+ sumi`) therefore writes, and the reader accepts, only that template. Sumi keeps the
265
+ v1 messages and per-call runtime hash for now. This release's Sumi reader also
266
+ accepts only that template, so a Sumi built on it would refuse a new-template
267
+ record. Moving the record needs a later SDK whose Sumi reader accepts the new
268
+ template, and a Sumi build bundling that later SDK running everywhere, before any
269
+ release writes the new template for Sumi.
270
+
235
271
  The same bundled entry also evaluates the `signed-link-guard` for every Bash
236
272
  and Monitor command (Claude Code's `Monitor` tool runs a shell command and
237
273
  streams its stdout to the model), under either capability name (`trash-guard`
@@ -492,10 +492,10 @@ async function main(argv = process.argv.slice(2), env = process.env, io = proces
492
492
  if (import.meta.main)
493
493
  await main();
494
494
  export {
495
- withBudget,
496
- scratchpadRunner,
497
- rootStation,
498
- resolveScratchpadScript,
495
+ main,
499
496
  readHookInput,
500
- main
497
+ resolveScratchpadScript,
498
+ rootStation,
499
+ scratchpadRunner,
500
+ withBudget
501
501
  };
@@ -702,14 +702,28 @@ var goalStatuses = ["active", "complete", "paused", "cancelled", "blocked", "bud
702
702
  var stopReasons = ["end_turn", "user_stop", "cancelled", "error", "approval_wait", "budget_limit", "usage_limit", "unknown"];
703
703
  var MIN_CERTAINTY = 0.9;
704
704
  var MAX_NEGATIVE = 0.1;
705
+ function hasTruthfulSumiAgentPause(envelope, admission) {
706
+ const goal = envelope.goal;
707
+ return admission?.mode === "parent_final_cas" && admission.harness === "sumi" && goal?.status === "paused" && goal.statusSource === "agent" && goal.pauseReason === "agent" && Number.isSafeInteger(goal.activationEpoch) && goal.activationEpoch >= 0 && envelope.runtime.paused === true && envelope.runtime.agentPauseAdmission === "parent_final_cas";
708
+ }
705
709
  function isStopReviewEnvelope(value) {
706
710
  if (!record(value) || value.schema !== "hooks.stop-review.v1" || !identifier(value.sessionId) || !identifier(value.turnId) || !identifier(value.inputRevision) || typeof value.capturedAt !== "string" || !Number.isFinite(Date.parse(value.capturedAt)) || !text2(value.lastUserPrompt) || !text2(value.lastAssistantMessage) || !record(value.runtime))
707
711
  return false;
708
712
  const runtime = value.runtime;
709
713
  if (!runtimeFlags.every((key) => typeof runtime[key] === "boolean") || !stopReasons.includes(runtime.stopReason) || !Number.isSafeInteger(runtime.continuationCount) || runtime.continuationCount < 0)
710
714
  return false;
715
+ if (runtime.agentPauseAdmission !== undefined && runtime.agentPauseAdmission !== "parent_final_cas")
716
+ return false;
711
717
  if (value.goal !== undefined && value.goal !== null && (!record(value.goal) || !identifier(value.goal.id) || !text2(value.goal.objective) || !goalStatuses.includes(value.goal.status)))
712
718
  return false;
719
+ if (record(value.goal)) {
720
+ const pauseFacts = [value.goal.statusSource, value.goal.pauseReason, value.goal.activationEpoch];
721
+ const hasPauseFact = pauseFacts.some((fact) => fact !== undefined);
722
+ const exactPauseFacts = value.goal.status === "paused" && value.goal.statusSource === "agent" && value.goal.pauseReason === "agent" && Number.isSafeInteger(value.goal.activationEpoch) && value.goal.activationEpoch >= 0;
723
+ if (hasPauseFact !== (runtime.agentPauseAdmission !== undefined) || hasPauseFact && !exactPauseFacts)
724
+ return false;
725
+ } else if (runtime.agentPauseAdmission !== undefined)
726
+ return false;
713
727
  if (value.goalAvailability !== undefined && !["known", "unavailable"].includes(value.goalAvailability))
714
728
  return false;
715
729
  return true;
@@ -727,11 +741,12 @@ function isStopReviewInstruction(value) {
727
741
  }
728
742
  function stopPolicyGate(envelope, now, maxContinuations = 1, options = {}) {
729
743
  const runtime = envelope.runtime;
744
+ const agentPause = hasTruthfulSumiAgentPause(envelope, options.admission);
730
745
  if (runtime.userRequestedStop || ["user_stop", "cancelled"].includes(runtime.stopReason))
731
746
  return "user_stop";
732
747
  if (runtime.terminal)
733
748
  return "terminal";
734
- if (runtime.paused)
749
+ if (runtime.paused && !agentPause)
735
750
  return "paused";
736
751
  if (runtime.budgetExhausted || runtime.stopReason === "budget_limit")
737
752
  return "budget_limit";
@@ -745,7 +760,7 @@ function stopPolicyGate(envelope, now, maxContinuations = 1, options = {}) {
745
760
  return "runtime_failure";
746
761
  if (runtime.stopReason !== "end_turn" || envelope.goal === undefined && envelope.goalAvailability !== "unavailable" || envelope.goal?.status === "unknown")
747
762
  return "unknown_runtime";
748
- if (envelope.goal && envelope.goal.status !== "active")
763
+ if (envelope.goal && envelope.goal.status !== "active" && !agentPause)
749
764
  return "goal_not_active";
750
765
  if (runtime.stopHookActive || runtime.continuationCount > maxContinuations || runtime.continuationCount === maxContinuations && !options.assessmentOnlyAtCap)
751
766
  return "recursion_guard";
@@ -792,7 +807,7 @@ async function assessStop(input, options, isCurrent, admission) {
792
807
  return stop("invalid_configuration");
793
808
  const now = options.now ?? Date.now;
794
809
  const parentGuarded = admission?.mode === "parent_final_cas" && ["sumi", "opencode"].includes(admission.harness);
795
- const gateOptions = { assessmentOnlyAtCap: parentGuarded };
810
+ const gateOptions = { assessmentOnlyAtCap: parentGuarded, admission };
796
811
  const gate = stopPolicyGate(envelope, now(), max, gateOptions);
797
812
  if (gate)
798
813
  return stop(gate);
@@ -1063,7 +1078,7 @@ async function runJevProviderChild(raw, env = process.env) {
1063
1078
  if (raw.admission !== undefined && (!record2(raw.admission) || raw.admission.mode !== "parent_final_cas" || !["sumi", "opencode"].includes(raw.admission.harness) || Object.keys(raw.admission).sort().join(",") !== "harness,mode" || nativeTarget !== raw.admission.harness))
1064
1079
  return { ok: false, reason: "invalid_configuration" };
1065
1080
  const admission = raw.admission;
1066
- const gate = stopPolicyGate(raw.envelope, Date.now(), 1, { assessmentOnlyAtCap: !!admission });
1081
+ const gate = stopPolicyGate(raw.envelope, Date.now(), 1, { assessmentOnlyAtCap: !!admission, admission });
1067
1082
  if (gate)
1068
1083
  return { ok: false, reason: gate };
1069
1084
  const instruction = instructionFromContent(raw.instructionContent, config);
@@ -1149,7 +1164,8 @@ async function reviewRuntimeEnvelope(raw, env, entrypoint, nativeTarget, isCurre
1149
1164
  const envelope = structuredClone(raw);
1150
1165
  const base = { schema: "hooks.stop-review-result.v1", sessionId: envelope.sessionId, turnId: envelope.turnId, inputRevision: envelope.inputRevision };
1151
1166
  const unavailable2 = (reason) => ({ ...base, action: "unavailable", reason });
1152
- const gate = stopPolicyGate(envelope, Date.now(), 1, { assessmentOnlyAtCap: !isCurrent });
1167
+ const admission = isCurrent || !nativeTarget || !["sumi", "opencode"].includes(nativeTarget) ? undefined : { mode: "parent_final_cas", harness: nativeTarget };
1168
+ const gate = stopPolicyGate(envelope, Date.now(), 1, { assessmentOnlyAtCap: !isCurrent, admission });
1153
1169
  if (gate)
1154
1170
  return { ...base, action: "allow_stop", reason: gate };
1155
1171
  const config = loadNativeRuntimeConfiguration(env);
@@ -1167,7 +1183,6 @@ async function reviewRuntimeEnvelope(raw, env, entrypoint, nativeTarget, isCurre
1167
1183
  if (!await scanStopReviewContent(envelope, instruction, config, env))
1168
1184
  return unavailable2("content_scan_failed");
1169
1185
  const requestHash = sha256(JSON.stringify(buildJevRequest(envelope, { model: config.model, instruction })));
1170
- const admission = isCurrent ? undefined : { mode: "parent_final_cas", harness: nativeTarget };
1171
1186
  const claimed = claimStopReviewTurn(envelope, env, requestHash, instruction.digest, admission, nativeTarget);
1172
1187
  if (claimed !== "claimed")
1173
1188
  return unavailable2(claimed === "already_claimed" ? "turn_already_reviewed" : "claim_unavailable");
@@ -1261,6 +1276,6 @@ async function main(argv = process.argv.slice(2), env = process.env) {
1261
1276
  if (import.meta.main)
1262
1277
  await main();
1263
1278
  export {
1264
- readHookInput,
1265
- main
1279
+ main,
1280
+ readHookInput
1266
1281
  };