hookloom 1.0.1 → 1.2.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.
@@ -0,0 +1,132 @@
1
+ // src/events.ts
2
+ /**
3
+ * What each harness does with each lifecycle event, as published at https://code.claude.com/docs/en/hooks and https://learn.chatgpt.com/docs/hooks.
4
+ */
5
+ const harnesses = ["claude", "codex"];
6
+ const general = {
7
+ decides: false,
8
+ evaluatesIf: false,
9
+ defaultTimeoutSeconds: 600,
10
+ maxTimeoutSeconds: 600,
11
+ registeredByPlugin: true
12
+ };
13
+ function matching(matchField) {
14
+ return {
15
+ ...general,
16
+ matchField
17
+ };
18
+ }
19
+ function toolEvent(matchField) {
20
+ return {
21
+ ...matching(matchField),
22
+ evaluatesIf: true
23
+ };
24
+ }
25
+ function deciding(contract) {
26
+ return {
27
+ ...contract,
28
+ decides: true
29
+ };
30
+ }
31
+ const CLAUDE_SESSION_END_SECONDS = 1.5;
32
+ const CLAUDE_PROMPT_SECONDS = 30;
33
+ const CLAUDE_DISPLAY_SECONDS = 10;
34
+ const CODEX_SHUTDOWN_DEFAULT_SECONDS = 1;
35
+ const CODEX_SHUTDOWN_MAX_SECONDS = 3;
36
+ const claude = {
37
+ SessionStart: matching("source"),
38
+ Setup: matching("trigger"),
39
+ UserPromptSubmit: deciding({
40
+ ...general,
41
+ defaultTimeoutSeconds: CLAUDE_PROMPT_SECONDS
42
+ }),
43
+ UserPromptExpansion: deciding(matching("command_name")),
44
+ PreSkillShellCommand: deciding(toolEvent("tool_name")),
45
+ PreToolUse: deciding(toolEvent("tool_name")),
46
+ PermissionRequest: deciding(toolEvent("tool_name")),
47
+ PermissionDenied: deciding(toolEvent("tool_name")),
48
+ PostToolUse: toolEvent("tool_name"),
49
+ PostToolUseFailure: toolEvent("tool_name"),
50
+ PostToolBatch: deciding(general),
51
+ Notification: matching("notification_type"),
52
+ MessageDisplay: {
53
+ ...general,
54
+ defaultTimeoutSeconds: CLAUDE_DISPLAY_SECONDS
55
+ },
56
+ SubagentStart: matching("agent_type"),
57
+ SubagentStop: deciding(matching("agent_type")),
58
+ TaskCreated: deciding(general),
59
+ TaskCompleted: deciding(general),
60
+ Stop: deciding(general),
61
+ StopFailure: matching("error"),
62
+ TeammateIdle: deciding(general),
63
+ InstructionsLoaded: matching("load_reason"),
64
+ ConfigChange: deciding(matching("source")),
65
+ CwdChanged: general,
66
+ DirectoryAdded: matching("source"),
67
+ FileChanged: {
68
+ ...matching("file_path"),
69
+ registeredByPlugin: false
70
+ },
71
+ WorktreeCreate: deciding({
72
+ ...general,
73
+ registeredByPlugin: false
74
+ }),
75
+ WorktreeRemove: deciding({
76
+ ...general,
77
+ registeredByPlugin: false
78
+ }),
79
+ PreCompact: deciding(matching("trigger")),
80
+ PostCompact: matching("trigger"),
81
+ PreModelSwitch: deciding({
82
+ ...matching("to_model"),
83
+ defaultTimeoutSeconds: CLAUDE_PROMPT_SECONDS
84
+ }),
85
+ PostModelSwitch: {
86
+ ...matching("to_model"),
87
+ defaultTimeoutSeconds: CLAUDE_PROMPT_SECONDS
88
+ },
89
+ Elicitation: deciding(matching("mcp_server_name")),
90
+ ElicitationResult: deciding(matching("mcp_server_name")),
91
+ SessionEnd: {
92
+ ...matching("reason"),
93
+ defaultTimeoutSeconds: CLAUDE_SESSION_END_SECONDS,
94
+ maxTimeoutSeconds: CLAUDE_SESSION_END_SECONDS
95
+ }
96
+ };
97
+ const codexShutdown = {
98
+ ...general,
99
+ defaultTimeoutSeconds: CODEX_SHUTDOWN_DEFAULT_SECONDS,
100
+ maxTimeoutSeconds: CODEX_SHUTDOWN_MAX_SECONDS
101
+ };
102
+ const contracts = {
103
+ claude,
104
+ codex: {
105
+ SessionStart: matching("source"),
106
+ UserPromptSubmit: deciding(general),
107
+ PreToolUse: deciding(matching("tool_name")),
108
+ PermissionRequest: deciding(matching("tool_name")),
109
+ PostToolUse: matching("tool_name"),
110
+ PreModelRequest: deciding(general),
111
+ PostModelRequest: general,
112
+ PreCompact: deciding(matching("trigger")),
113
+ PostCompact: matching("trigger"),
114
+ SubagentStart: matching("agent_type"),
115
+ SubagentStop: deciding(matching("agent_type")),
116
+ Stop: deciding(general),
117
+ Interrupt: codexShutdown,
118
+ SessionEnd: {
119
+ ...codexShutdown,
120
+ matchField: "reason"
121
+ }
122
+ }
123
+ };
124
+ /** Every event the harness documents, in the order of its contract table. */
125
+ function eventNames(harness) {
126
+ return Object.keys(contracts[harness]);
127
+ }
128
+ /** The contract of an event, or `undefined` when the harness has no such event. */
129
+ function eventContract(harness, event) {
130
+ return Object.hasOwn(contracts[harness], event) ? contracts[harness][event] : void 0;
131
+ }
132
+ export { eventNames as n, harnesses as r, eventContract as t };
@@ -0,0 +1,24 @@
1
+ import { a as stringField } from "../shell-4WSaabze.mjs";
2
+ import { a as shellCommand, i as main, n as context, o as toolOutput } from "../hook-DIS0wk_5.mjs";
3
+ // src/examples/blocked-fetch.ts
4
+ /**
5
+ * After a page fetch is refused or blocked, reminds the agent to try a browser before reporting the page unreadable. Never blocks.
6
+ */
7
+ const STRONG = /Unable to verify if domain .{0,200}? is safe to fetch|is not safe to fetch|Just a moment\.\.\.|Attention Required! \| Cloudflare|Enable JavaScript and cookies to continue|Checking your browser before accessing|cf-chl-bypass/isu;
8
+ const WEAK = /HTTP\/[\d.]+ (?:401|403|429)\b|\bstatus(?: code)?[: ]+(?:401|403|429)\b|Request failed with status code (?:401|403|429)|\b(?:403|401|429)\b[ :]+(?:Forbidden|Unauthori[sz]ed|Too Many Requests)|Access Denied|Request blocked|captcha|robot or human/iu;
9
+ const FETCHING_COMMAND = /(?:^|[\s;&|(])(?:curl|wget|http|https)\s/u;
10
+ const BROWSER_TOOL = /playwright|browser|chrome/iu;
11
+ const ADVICE = "A page fetch was refused or blocked. Try an available browser tool before reporting the page unreadable. If the browser also meets a login, paywall or bot wall, name the block and ask the user for a way in. Never put a credential in a URL or in code passed to the browser.";
12
+ function blocked(tool, command, output) {
13
+ if (BROWSER_TOOL.test(tool)) return false;
14
+ if (STRONG.test(output)) return true;
15
+ if (tool === "WebFetch") return WEAK.test(output);
16
+ return tool === "Bash" && command !== void 0 && FETCHING_COMMAND.test(command) && WEAK.test(output);
17
+ }
18
+ const hook = (input) => {
19
+ const tool = stringField(input, "tool_name");
20
+ return tool !== void 0 && blocked(tool, shellCommand(input), toolOutput(input)) ? context("PostToolUse", ADVICE) : void 0;
21
+ };
22
+ // src/examples/bin/blocked-fetch.ts
23
+ await main(hook);
24
+ export {};
@@ -0,0 +1,106 @@
1
+ import { closeSync, existsSync, fstatSync, openSync, readSync } from "node:fs";
2
+ import { a as stringField, n as isRecord } from "../shell-4WSaabze.mjs";
3
+ import { t as withoutHarnessMessages } from "../prompt-text-A_jEvJei.mjs";
4
+ import { i as main } from "../hook-DIS0wk_5.mjs";
5
+ // src/examples/transcript.ts
6
+ /**
7
+ * Reads a Claude Code transcript: which records are the user's own requests, and which are the harness's.
8
+ */
9
+ const BLOCK_BYTES = 1048576;
10
+ const FEEDBACK_PREFIX = "Stop hook feedback:";
11
+ /** A transcript's lines, newest first, read backwards in blocks so the cost follows what is consumed rather than the file's size. */
12
+ function* linesFromEnd(path, blockBytes = BLOCK_BYTES) {
13
+ const descriptor = openSync(path, "r");
14
+ try {
15
+ let position = fstatSync(descriptor).size;
16
+ let tail = Buffer.alloc(0);
17
+ while (position > 0) {
18
+ const size = Math.min(blockBytes, position);
19
+ position -= size;
20
+ const block = Buffer.alloc(size);
21
+ readSync(descriptor, block, 0, size, position);
22
+ const joined = Buffer.concat([block, tail]);
23
+ let end = joined.length;
24
+ for (let newline = joined.lastIndexOf("\n"); newline !== -1; newline = joined.subarray(0, end).lastIndexOf("\n")) {
25
+ yield joined.toString("utf8", newline + 1, end);
26
+ end = newline;
27
+ }
28
+ tail = joined.subarray(0, end);
29
+ }
30
+ yield tail.toString("utf8");
31
+ } finally {
32
+ closeSync(descriptor);
33
+ }
34
+ }
35
+ function isList(value) {
36
+ return Array.isArray(value);
37
+ }
38
+ function contentOf(record) {
39
+ const message = record["message"];
40
+ return isRecord(message) ? message["content"] : void 0;
41
+ }
42
+ /** The blocks of a record's message content. */
43
+ function blocks(record) {
44
+ const content = contentOf(record);
45
+ return isList(content) ? content.filter((block) => isRecord(block)) : [];
46
+ }
47
+ function textOf(record) {
48
+ if (record["type"] !== "user") return "";
49
+ const content = contentOf(record);
50
+ if (typeof content === "string") return content;
51
+ return blocks(record).flatMap((block) => block["type"] === "text" && typeof block["text"] === "string" ? [block["text"]] : []).join("\n");
52
+ }
53
+ /** What the user asked in a record, or an empty string for tool results, records the harness or another agent wrote and text that is only harness wrappers: the test for whether a record starts the user's turn. */
54
+ function userRequest(record) {
55
+ const origin = record["origin"];
56
+ const fromAnotherAgent = isRecord(origin) && origin["kind"] !== "human";
57
+ if (record["isMeta"] === true || record["isCompactSummary"] === true || fromAnotherAgent || blocks(record).some((block) => block["type"] === "tool_result")) return "";
58
+ return withoutHarnessMessages(textOf(record));
59
+ }
60
+ /** A Stop hook's blocking feedback held by a record, or an empty string. */
61
+ function stopHookFeedback(record) {
62
+ const text = textOf(record);
63
+ return text.startsWith(FEEDBACK_PREFIX) ? text : "";
64
+ }
65
+ // src/examples/browser-close.ts
66
+ /**
67
+ * A Claude Code Stop hook: when a turn used the Playwright browser and left it open, asks once for it to be closed. An open browser holds the shared browser profile, which blocks other sessions.
68
+ */
69
+ const BROWSER_TOOL = /^mcp__.*playwright.*__browser_/u;
70
+ const CLOSE_SUFFIX = "__browser_close";
71
+ const REASON = "This turn used the Playwright browser and left it open. An open browser holds the shared browser profile and blocks other sessions' browsers. If you are done with it, close it with the browser_close tool and end the turn. If the next step of this task needs the same page, say so in one line and end the turn; this reminder is not repeated.";
72
+ function parsed(line) {
73
+ try {
74
+ const value = JSON.parse(line);
75
+ return isRecord(value) ? value : void 0;
76
+ } catch {
77
+ return;
78
+ }
79
+ }
80
+ /** The tools called since the user's last request or this hook's last reminder, whichever is later, oldest first. */
81
+ function toolsThisTurn(transcript) {
82
+ const newestFirst = [];
83
+ for (const line of linesFromEnd(transcript)) {
84
+ const record = parsed(line);
85
+ if (record === void 0) continue;
86
+ if (userRequest(record) !== "" || stopHookFeedback(record).includes("This turn used the Playwright browser and left it open. An open browser holds the shared browser profile and blocks other sessions' browsers. If you are done with it, close it with the browser_close tool and end the turn. If the next step of this task needs the same page, say so in one line and end the turn; this reminder is not repeated.")) break;
87
+ if (record["type"] === "assistant") newestFirst.push(blocks(record).flatMap((block) => block["type"] === "tool_use" && typeof block["name"] === "string" ? [block["name"]] : []));
88
+ }
89
+ return newestFirst.toReversed().flat();
90
+ }
91
+ /** Whether a browser tool was called after the last close, or with no close at all. */
92
+ function leftOpen(tools) {
93
+ const used = tools.findLastIndex((name) => BROWSER_TOOL.test(name) && !name.endsWith(CLOSE_SUFFIX));
94
+ return used !== -1 && !tools.slice(used + 1).some((name) => BROWSER_TOOL.test(name) && name.endsWith(CLOSE_SUFFIX));
95
+ }
96
+ const hook = (input) => {
97
+ const transcript = stringField(input, "transcript_path");
98
+ if (input["stop_hook_active"] === true || input["hook_event_name"] !== "Stop" || transcript === void 0 || !existsSync(transcript)) return void 0;
99
+ return leftOpen(toolsThisTurn(transcript)) ? {
100
+ decision: "block",
101
+ reason: REASON
102
+ } : void 0;
103
+ };
104
+ // src/examples/bin/browser-close.ts
105
+ await main(hook);
106
+ export {};