hookloom 1.0.0 → 1.1.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/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +12 -0
- package/dist/{check-D6B_qnUy.mjs → check-CRZ6Rgdo.mjs} +3 -2
- package/dist/check-ySa9Ce1V.mjs +1 -0
- package/dist/cli.mjs +213 -41
- package/dist/command-line-BjI01lOI.mjs +62 -0
- package/dist/dispatcher.mjs +34 -80
- package/dist/events-CHsq0Cl4.mjs +132 -0
- package/dist/examples/blocked-fetch.mjs +24 -0
- package/dist/examples/browser-close.mjs +106 -0
- package/dist/examples/default-branch-health.mjs +214 -0
- package/dist/examples/github-rate-limit.mjs +31 -0
- package/dist/examples/issue-comment-guard.mjs +157 -0
- package/dist/examples/private-reference-guard.mjs +69 -0
- package/dist/examples/repository-metadata.mjs +44 -0
- package/dist/files-CBn-xAo2.mjs +50 -0
- package/dist/hook-DIS0wk_5.mjs +51 -0
- package/dist/lock-8b6urUtv.mjs +22 -0
- package/dist/permission-rule-BVXyOtut.mjs +123 -0
- package/dist/private-references-CUZqASjK.mjs +254 -0
- package/dist/prompt-text-A_jEvJei.mjs +29 -0
- package/dist/schema-Dl9EJYyt.mjs +112 -0
- package/dist/{schema-Bvs-uwjo.mjs → schema-EYih4WFo.mjs} +1 -1
- package/dist/{schema-ChV-yJDT.mjs → schemas-B4KRDIno.mjs} +9 -239
- package/dist/{permission-rule-DXm-Jvfg.mjs → shell-4WSaabze.mjs} +12 -123
- package/dist/state-Db3zojdV.mjs +51 -0
- package/package.json +1 -1
- package/dist/check-nhb0tW8i.mjs +0 -1
- package/dist/command-line-BBETAyPT.mjs +0 -109
|
@@ -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 {};
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { n as readRecord, o as writeRecord, t as digest } from "../state-Db3zojdV.mjs";
|
|
4
|
+
import { a as stringField } from "../shell-4WSaabze.mjs";
|
|
5
|
+
import { n as withLock, t as LockedError } from "../lock-8b6urUtv.mjs";
|
|
6
|
+
import { c as number, f as string, l as object, n as array, p as union } from "../schemas-B4KRDIno.mjs";
|
|
7
|
+
import { n as cacheDirectory } from "../files-CBn-xAo2.mjs";
|
|
8
|
+
import { i as main, n as context } from "../hook-DIS0wk_5.mjs";
|
|
9
|
+
import { o as originRepository } from "../private-references-CUZqASjK.mjs";
|
|
10
|
+
// src/examples/pressure.ts
|
|
11
|
+
/**
|
|
12
|
+
* Throttles a notice by how much it matters: pressure runs from 0 to 1, derived from a hook's own measurements, and the higher it is the sooner a session is told again.
|
|
13
|
+
*/
|
|
14
|
+
const MILLISECONDS_PER_MINUTE = 6e4;
|
|
15
|
+
const MINUTES_PER_HOUR = 60;
|
|
16
|
+
const HOURS_PER_DAY = 24;
|
|
17
|
+
const HOURS_SHOWN_AS_HOURS = 48;
|
|
18
|
+
/** The wait between notices: `longest` at no pressure, shrinking evenly to `shortest` at full pressure. */
|
|
19
|
+
function noticeInterval(pressure, shortest, longest) {
|
|
20
|
+
return shortest + (longest - shortest) * (1 - pressure);
|
|
21
|
+
}
|
|
22
|
+
/** How long something has waited, judged against how often it usually changes: a half when it has waited one typical gap, rising towards 1. */
|
|
23
|
+
function agePressure(age, typicalGap) {
|
|
24
|
+
return age + typicalGap > 0 ? age / (age + typicalGap) : 0;
|
|
25
|
+
}
|
|
26
|
+
/** A compact elapsed time: minutes, then hours and minutes, then days and hours. */
|
|
27
|
+
function elapsed(milliseconds) {
|
|
28
|
+
const minutes = Math.floor(milliseconds / MILLISECONDS_PER_MINUTE);
|
|
29
|
+
if (minutes < MINUTES_PER_HOUR) return `${String(minutes)}m`;
|
|
30
|
+
const hours = Math.floor(minutes / MINUTES_PER_HOUR);
|
|
31
|
+
const twoDigits = (value) => String(value).padStart(2, "0");
|
|
32
|
+
if (hours < HOURS_SHOWN_AS_HOURS) return `${String(hours)}h${twoDigits(minutes % MINUTES_PER_HOUR)}m`;
|
|
33
|
+
return `${String(Math.floor(hours / HOURS_PER_DAY))}d${twoDigits(hours % HOURS_PER_DAY)}h`;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Whether a session is due a notice. One about the same findings waits at least `sameFindingsFloor`; a changed one is told as soon as the pressure allows.
|
|
37
|
+
*/
|
|
38
|
+
function due(told, notice, limits) {
|
|
39
|
+
if (told === void 0) return true;
|
|
40
|
+
const since = notice.now - told.at;
|
|
41
|
+
if (told.fingerprint === notice.fingerprint && since < limits.sameFindingsFloor) return false;
|
|
42
|
+
return since >= noticeInterval(notice.pressure, limits.shortest, limits.longest);
|
|
43
|
+
}
|
|
44
|
+
// src/examples/default-branch-health.ts
|
|
45
|
+
/**
|
|
46
|
+
* On a prompt, warns the agent when the default branch of the GitHub repository it is working in is red, with urgency set by how long it has been red against how often commits usually land there.
|
|
47
|
+
*/
|
|
48
|
+
/**
|
|
49
|
+
* GitHub is asked about a repository at most this often, whatever the number of sessions, and a session at full pressure is told no more often.
|
|
50
|
+
*/
|
|
51
|
+
const QUERY_INTERVAL_MILLISECONDS = 3e5;
|
|
52
|
+
const ROUTINE_INTERVAL_MILLISECONDS = 18e5;
|
|
53
|
+
const SAME_FINDINGS_FLOOR_MILLISECONDS = 36e5;
|
|
54
|
+
const LOOKUP_TIMEOUT_MILLISECONDS = 4e3;
|
|
55
|
+
const RUNS_PER_PAGE = 100;
|
|
56
|
+
const URGENT_PRESSURE = .5;
|
|
57
|
+
const RED = /* @__PURE__ */ new Set([
|
|
58
|
+
"failure",
|
|
59
|
+
"timed_out",
|
|
60
|
+
"startup_failure"
|
|
61
|
+
]);
|
|
62
|
+
const GREEN = "success";
|
|
63
|
+
const run = object({
|
|
64
|
+
workflow_id: number(),
|
|
65
|
+
name: string(),
|
|
66
|
+
html_url: string(),
|
|
67
|
+
id: number(),
|
|
68
|
+
head_sha: string(),
|
|
69
|
+
created_at: string(),
|
|
70
|
+
conclusion: string()
|
|
71
|
+
});
|
|
72
|
+
function redStreaks(runs) {
|
|
73
|
+
const workflows = /* @__PURE__ */ new Map();
|
|
74
|
+
for (const entry of runs) workflows.set(entry.workflow_id, [...workflows.get(entry.workflow_id) ?? [], entry]);
|
|
75
|
+
return [...workflows.values()].flatMap((ofWorkflow) => {
|
|
76
|
+
const decisive = ofWorkflow.filter(({ conclusion }) => conclusion === GREEN || RED.has(conclusion));
|
|
77
|
+
const green = decisive.findIndex(({ conclusion }) => conclusion === GREEN);
|
|
78
|
+
const streak = green === -1 ? decisive : decisive.slice(0, green);
|
|
79
|
+
const [newest] = streak;
|
|
80
|
+
const oldest = streak.at(-1);
|
|
81
|
+
return newest === void 0 || oldest === void 0 ? [] : [{
|
|
82
|
+
newest,
|
|
83
|
+
since: Date.parse(oldest.created_at),
|
|
84
|
+
atLeast: green === -1
|
|
85
|
+
}];
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
function typicalGap(runs, fallback) {
|
|
89
|
+
const times = [...new Map(runs.toReversed().map((entry) => [entry.head_sha, Date.parse(entry.created_at)])).values()].toSorted((left, right) => left - right);
|
|
90
|
+
const sorted = times.slice(1).flatMap((time, index) => {
|
|
91
|
+
const gap = time - (times[index] ?? time);
|
|
92
|
+
return gap > 0 ? [gap] : [];
|
|
93
|
+
}).toSorted((left, right) => left - right);
|
|
94
|
+
const lower = sorted[Math.floor((sorted.length - 1) / 2)];
|
|
95
|
+
const upper = sorted[Math.ceil((sorted.length - 1) / 2)];
|
|
96
|
+
return lower === void 0 || upper === void 0 ? fallback : (lower + upper) / 2;
|
|
97
|
+
}
|
|
98
|
+
/** The workflow that has been red longest, with its pressure, or `undefined` when the branch is green. */
|
|
99
|
+
function assess(runs, now) {
|
|
100
|
+
const streaks = redStreaks(runs);
|
|
101
|
+
const [worst] = streaks.toSorted((left, right) => left.since - right.since);
|
|
102
|
+
if (worst === void 0) return void 0;
|
|
103
|
+
const redFor = Math.max(0, now - worst.since);
|
|
104
|
+
const landed = new Set(runs.filter((entry) => Date.parse(entry.created_at) >= worst.since).map((entry) => entry.head_sha));
|
|
105
|
+
return {
|
|
106
|
+
workflow: worst.newest.name,
|
|
107
|
+
run: worst.newest.id,
|
|
108
|
+
redFor,
|
|
109
|
+
atLeast: worst.atLeast,
|
|
110
|
+
pressure: agePressure(redFor, typicalGap(runs, redFor)),
|
|
111
|
+
commitsOnRed: landed.size,
|
|
112
|
+
redWorkflows: streaks.length
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
function notice(repository, branch, health) {
|
|
116
|
+
const { pressure, commitsOnRed, redWorkflows } = health;
|
|
117
|
+
const tier = pressure < URGENT_PRESSURE ? "Fix it before building on it." : commitsOnRed > 1 ? "URGENT: other work is landing on a red base, so fix it before continuing." : "URGENT: it has been red longer than this repository usually goes between commits, so fix it before continuing.";
|
|
118
|
+
const stacked = commitsOnRed > 1 ? `, ${String(commitsOnRed)} commits landed since` : "";
|
|
119
|
+
const more = redWorkflows > 1 ? ` (${String(redWorkflows)} workflows red, longest shown)` : "";
|
|
120
|
+
const percent = new Intl.NumberFormat("en-GB", { style: "percent" }).format(pressure);
|
|
121
|
+
return `Default branch ${repository}@${branch} is red: ${health.workflow} has failed for ${health.atLeast ? "at least " : ""}${elapsed(health.redFor)}${stacked}, pressure ${percent}${more}. ${tier} Check for an existing fix first (\`gh pr list --repo ${repository} --state open\`), read the failure with \`gh run view ${String(health.run)} --repo ${repository} --log-failed\`, and fix it through the normal pull request cycle in a worktree. If the repository is not yours to change, tell the user instead.`;
|
|
122
|
+
}
|
|
123
|
+
const api = (path) => JSON.parse(execFileSync("gh", ["api", path], {
|
|
124
|
+
encoding: "utf8",
|
|
125
|
+
timeout: LOOKUP_TIMEOUT_MILLISECONDS,
|
|
126
|
+
stdio: [
|
|
127
|
+
"ignore",
|
|
128
|
+
"pipe",
|
|
129
|
+
"pipe"
|
|
130
|
+
]
|
|
131
|
+
}));
|
|
132
|
+
const listed = object({
|
|
133
|
+
fetchedAt: number(),
|
|
134
|
+
branch: string(),
|
|
135
|
+
runs: array(run)
|
|
136
|
+
});
|
|
137
|
+
const stored = union([listed, object({
|
|
138
|
+
fetchedAt: number(),
|
|
139
|
+
error: string()
|
|
140
|
+
})]);
|
|
141
|
+
function query(repository, read, now) {
|
|
142
|
+
const { default_branch: branch } = object({ default_branch: string() }).parse(read(`repos/${repository}`));
|
|
143
|
+
const listing = read(`repos/${repository}/actions/runs?branch=${encodeURIComponent(branch)}&event=push&status=completed&per_page=${String(RUNS_PER_PAGE)}`);
|
|
144
|
+
return {
|
|
145
|
+
fetchedAt: now,
|
|
146
|
+
branch,
|
|
147
|
+
runs: object({ workflow_runs: array(run) }).parse(listing).workflow_runs
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
function readState(repository, read, file, now) {
|
|
151
|
+
const cached = stored.safeParse(readRecord(file));
|
|
152
|
+
let state = cached.success && now - cached.data.fetchedAt < 3e5 ? cached.data : void 0;
|
|
153
|
+
if (state === void 0) {
|
|
154
|
+
try {
|
|
155
|
+
state = query(repository, read, now);
|
|
156
|
+
} catch (error) {
|
|
157
|
+
state = {
|
|
158
|
+
fetchedAt: now,
|
|
159
|
+
error: error instanceof Error ? error.message : String(error)
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
writeRecord(file, state);
|
|
163
|
+
}
|
|
164
|
+
if ("error" in state) throw new Error(`could not read CI state for ${repository}: ${state.error}`);
|
|
165
|
+
return state;
|
|
166
|
+
}
|
|
167
|
+
/** The warning due to this session about the repository it is working in, if any. */
|
|
168
|
+
function warning(input, world) {
|
|
169
|
+
const session = stringField(input, "session_id");
|
|
170
|
+
const cwd = stringField(input, "cwd");
|
|
171
|
+
const repository = cwd === void 0 ? void 0 : originRepository(cwd);
|
|
172
|
+
if (session === void 0 || repository === void 0) return void 0;
|
|
173
|
+
const key = digest(repository);
|
|
174
|
+
const { branch, runs } = readState(repository, world.api, join(world.directory, `${key}.json`), world.now);
|
|
175
|
+
const health = assess(runs, world.now);
|
|
176
|
+
if (health === void 0) return void 0;
|
|
177
|
+
const told = join(world.directory, `${digest([session, repository])}.json`);
|
|
178
|
+
const previous = object({
|
|
179
|
+
at: number(),
|
|
180
|
+
fingerprint: string()
|
|
181
|
+
}).safeParse(readRecord(told));
|
|
182
|
+
const current = {
|
|
183
|
+
fingerprint: `${health.workflow}|${String(health.run)}`,
|
|
184
|
+
pressure: health.pressure,
|
|
185
|
+
now: world.now
|
|
186
|
+
};
|
|
187
|
+
const limits = {
|
|
188
|
+
shortest: QUERY_INTERVAL_MILLISECONDS,
|
|
189
|
+
longest: ROUTINE_INTERVAL_MILLISECONDS,
|
|
190
|
+
sameFindingsFloor: SAME_FINDINGS_FLOOR_MILLISECONDS
|
|
191
|
+
};
|
|
192
|
+
if (!due(previous.success ? previous.data : void 0, current, limits)) return void 0;
|
|
193
|
+
writeRecord(told, {
|
|
194
|
+
at: world.now,
|
|
195
|
+
fingerprint: current.fingerprint
|
|
196
|
+
});
|
|
197
|
+
return context("UserPromptSubmit", notice(repository, branch, health));
|
|
198
|
+
}
|
|
199
|
+
const hook = (input) => {
|
|
200
|
+
const directory = join(cacheDirectory(process.env), "examples", "default-branch-health");
|
|
201
|
+
try {
|
|
202
|
+
return withLock(join(directory, "lock"), () => warning(input, {
|
|
203
|
+
api,
|
|
204
|
+
directory,
|
|
205
|
+
now: Date.now()
|
|
206
|
+
}));
|
|
207
|
+
} catch (error) {
|
|
208
|
+
if (error instanceof LockedError) return void 0;
|
|
209
|
+
throw error;
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
// src/examples/bin/default-branch-health.ts
|
|
213
|
+
await main(hook);
|
|
214
|
+
export {};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { a as shellCommand, i as main, n as context, o as toolOutput, t as commandWords } from "../hook-DIS0wk_5.mjs";
|
|
2
|
+
// src/examples/github-rate-limit.ts
|
|
3
|
+
/**
|
|
4
|
+
* After a `gh` command is refused for a rate limit, points the agent at the REST route. `gh`'s own subcommands spend the GraphQL budget, which can be empty while the REST budget still has room.
|
|
5
|
+
*/
|
|
6
|
+
const RATE_LIMIT = /API rate limit (?:already )?exceeded|secondary rate limit|rate limit exceeded/iu;
|
|
7
|
+
const GRAPHQL_REFUSAL = /GraphQL:[^\n]*?rate limit/iu;
|
|
8
|
+
const CHECK = "`gh api rate_limit -q '.resources|{core,graphql,search}'`";
|
|
9
|
+
/** The first `gh` subcommand of a command line and whether it called the REST API, or `undefined` when this is not a `gh` rate-limit failure. */
|
|
10
|
+
function rateLimited(command, output) {
|
|
11
|
+
if (!RATE_LIMIT.test(output)) return void 0;
|
|
12
|
+
const call = commandWords(command).find((words) => words[0]?.split("/").at(-1) === "gh");
|
|
13
|
+
const subcommand = call?.[1];
|
|
14
|
+
if (subcommand === void 0) return void 0;
|
|
15
|
+
return {
|
|
16
|
+
subcommand,
|
|
17
|
+
rest: !GRAPHQL_REFUSAL.test(output) && subcommand === "api" && call?.[2] !== "graphql"
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
function advice(subcommand, rest) {
|
|
21
|
+
if (rest) return `\`gh api\` hit a rate limit on a REST route. Read the budgets and reset times with ${CHECK}; when \`core\` is spent, wait for its \`reset\` rather than retrying in a loop, and do independent work meanwhile.`;
|
|
22
|
+
return `${subcommand === "api" ? "the GraphQL query that `gh api graphql` sends" : `\`gh ${subcommand}\``} was refused for a rate limit. The REST core budget is separate from GraphQL, so retry the same operation through a REST endpoint with \`gh api\` now instead of waiting or repeating the failing command: first read the budgets with ${CHECK}. Typical routes: issue or pull request read \`gh api repos/OWNER/REPO/issues/N\` or \`.../pulls/N\`; create \`gh api repos/OWNER/REPO/issues -f title=... -F body=@file\`; comments \`gh api repos/OWNER/REPO/issues/N/comments\`; checks \`gh api repos/OWNER/REPO/commits/SHA/check-runs\`; list \`gh api 'repos/OWNER/REPO/pulls?state=open' -q '.[].number'\`. Operations only GraphQL offers (sub-issues, issue fields, review-thread resolution, Projects) have no REST route: for those wait for the GraphQL \`reset\` and do other work meanwhile.`;
|
|
23
|
+
}
|
|
24
|
+
const hook = (input) => {
|
|
25
|
+
const command = shellCommand(input);
|
|
26
|
+
const found = command === void 0 ? void 0 : rateLimited(command, toolOutput(input).replaceAll("\\n", "\n"));
|
|
27
|
+
return found === void 0 ? void 0 : context("PostToolUse", advice(found.subcommand, found.rest));
|
|
28
|
+
};
|
|
29
|
+
// src/examples/bin/github-rate-limit.ts
|
|
30
|
+
await main(hook);
|
|
31
|
+
export {};
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { a as stringField, t as splitCommand } from "../shell-4WSaabze.mjs";
|
|
3
|
+
import { f as string, l as object, r as boolean } from "../schemas-B4KRDIno.mjs";
|
|
4
|
+
import { a as shellCommand, i as main, r as deny } from "../hook-DIS0wk_5.mjs";
|
|
5
|
+
// src/examples/issue-comment-guard.ts
|
|
6
|
+
/**
|
|
7
|
+
* Before a shell command, refuses a new comment on a GitHub issue the signed-in user wrote when no other person has commented: a decision or requirement for such an issue belongs in its body, which stays the one statement of what is asked for. Prefixing the command with `ISSUE_COMMENT_OK=1` lets a real reply or status note through. A lookup that fails allows the command, since the comment needs the same access.
|
|
8
|
+
*/
|
|
9
|
+
const ESCAPE = "ISSUE_COMMENT_OK";
|
|
10
|
+
const LOOKUP_TIMEOUT_MILLISECONDS = 2e4;
|
|
11
|
+
const COMMENT_VALUE_FLAGS = /* @__PURE__ */ new Set([
|
|
12
|
+
"-R",
|
|
13
|
+
"--repo",
|
|
14
|
+
"-b",
|
|
15
|
+
"--body",
|
|
16
|
+
"-F",
|
|
17
|
+
"--body-file"
|
|
18
|
+
]);
|
|
19
|
+
const API_VALUE_FLAGS = /* @__PURE__ */ new Set([
|
|
20
|
+
"-X",
|
|
21
|
+
"--method",
|
|
22
|
+
"-H",
|
|
23
|
+
"--header",
|
|
24
|
+
"-f",
|
|
25
|
+
"--raw-field",
|
|
26
|
+
"-F",
|
|
27
|
+
"--field",
|
|
28
|
+
"--input",
|
|
29
|
+
"-q",
|
|
30
|
+
"--jq",
|
|
31
|
+
"-t",
|
|
32
|
+
"--template",
|
|
33
|
+
"--hostname",
|
|
34
|
+
"--cache",
|
|
35
|
+
"-p",
|
|
36
|
+
"--preview"
|
|
37
|
+
]);
|
|
38
|
+
const API_BODY_FLAGS = /* @__PURE__ */ new Set([
|
|
39
|
+
"-f",
|
|
40
|
+
"--raw-field",
|
|
41
|
+
"-F",
|
|
42
|
+
"--field",
|
|
43
|
+
"--input"
|
|
44
|
+
]);
|
|
45
|
+
const ISSUE_URL = /github\.com\/([^/\s]+\/[^/\s]+)\/(?:issues|pull)\/(\d+)/u;
|
|
46
|
+
const COMMENTS_ENDPOINT = /^\/?repos\/([^/]+)\/([^/]+)\/issues\/(\d+)\/comments\/?$/u;
|
|
47
|
+
function targetOf(number, repository) {
|
|
48
|
+
return repository === void 0 ? { number } : {
|
|
49
|
+
repository,
|
|
50
|
+
number
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
function commentTarget(words) {
|
|
54
|
+
if (words.includes("--edit-last")) return void 0;
|
|
55
|
+
let repository;
|
|
56
|
+
let named;
|
|
57
|
+
for (let index = 0; index < words.length; index += 1) {
|
|
58
|
+
const word = words[index] ?? "";
|
|
59
|
+
if (COMMENT_VALUE_FLAGS.has(word)) {
|
|
60
|
+
if (word === "-R" || word === "--repo") repository = words[index + 1];
|
|
61
|
+
index += 1;
|
|
62
|
+
} else if (word.startsWith("--repo=")) repository = word.slice(7);
|
|
63
|
+
else if (!word.startsWith("-")) named ??= word;
|
|
64
|
+
}
|
|
65
|
+
if (named === void 0) return void 0;
|
|
66
|
+
if (/^\d+$/u.test(named)) return targetOf(Number(named), repository);
|
|
67
|
+
const url = ISSUE_URL.exec(named);
|
|
68
|
+
return url === null ? void 0 : targetOf(Number(url[2]), url[1]);
|
|
69
|
+
}
|
|
70
|
+
function apiTarget(words) {
|
|
71
|
+
let endpoint;
|
|
72
|
+
let method;
|
|
73
|
+
for (let index = 0; index < words.length; index += 1) {
|
|
74
|
+
const word = words[index] ?? "";
|
|
75
|
+
if (word === "-X" || word === "--method") method = words[index + 1];
|
|
76
|
+
else if (word.startsWith("--method=")) method = word.slice(9);
|
|
77
|
+
if (API_VALUE_FLAGS.has(word)) index += 1;
|
|
78
|
+
else if (!word.startsWith("-")) endpoint ??= word;
|
|
79
|
+
}
|
|
80
|
+
const match = (method?.toUpperCase() ?? (words.some((word) => API_BODY_FLAGS.has(word)) ? "POST" : "GET")) === "POST" ? COMMENTS_ENDPOINT.exec(endpoint ?? "") : null;
|
|
81
|
+
if (match === null) return void 0;
|
|
82
|
+
const [, owner = "", name = "", number = ""] = match;
|
|
83
|
+
return targetOf(Number(number), owner.includes("{") || name.includes("{") ? void 0 : `${owner}/${name}`);
|
|
84
|
+
}
|
|
85
|
+
/** The issues a command line comments on, leaving out any command that opts out. */
|
|
86
|
+
function commentTargets(command) {
|
|
87
|
+
const split = splitCommand(command);
|
|
88
|
+
if (split === void 0) return [];
|
|
89
|
+
return split.words.flatMap((words, position) => {
|
|
90
|
+
const optedOut = (split.prefixes[position] ?? []).some((word) => word.startsWith(`${ESCAPE}=`) && !["", "0"].includes(word.slice(17)));
|
|
91
|
+
const [program, group, action] = words;
|
|
92
|
+
if (optedOut || program !== "gh") return [];
|
|
93
|
+
if (group === "issue" && action === "comment") return commentTarget(words.slice("gh issue comment".split(" ").length)) ?? [];
|
|
94
|
+
return group === "api" ? apiTarget(words.slice("gh api".split(" ").length)) ?? [] : [];
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
/** Whether the comment would be a requirement posted to the user's own issue with no discussion yet. Automated comments are not discussion. */
|
|
98
|
+
function unanswered({ pullRequest, author, currentUser, commenters }) {
|
|
99
|
+
return !pullRequest && author === currentUser && !commenters.some(({ login, type }) => login !== currentUser && type !== "Bot");
|
|
100
|
+
}
|
|
101
|
+
const issue = object({
|
|
102
|
+
login: string(),
|
|
103
|
+
pr: boolean()
|
|
104
|
+
});
|
|
105
|
+
const commenter = object({
|
|
106
|
+
login: string(),
|
|
107
|
+
type: string()
|
|
108
|
+
});
|
|
109
|
+
const lookUp = (target, cwd) => {
|
|
110
|
+
const gh = (...args) => execFileSync("gh", args, {
|
|
111
|
+
cwd,
|
|
112
|
+
encoding: "utf8",
|
|
113
|
+
timeout: LOOKUP_TIMEOUT_MILLISECONDS,
|
|
114
|
+
stdio: [
|
|
115
|
+
"ignore",
|
|
116
|
+
"pipe",
|
|
117
|
+
"ignore"
|
|
118
|
+
]
|
|
119
|
+
}).trim();
|
|
120
|
+
try {
|
|
121
|
+
const repository = target.repository ?? gh("repo", "view", "--json", "nameWithOwner", "-q", ".nameWithOwner");
|
|
122
|
+
const route = `repos/${repository}/issues/${String(target.number)}`;
|
|
123
|
+
const found = issue.parse(JSON.parse(gh("api", route, "--jq", "{login: .user.login, pr: (.pull_request != null)}")));
|
|
124
|
+
const comments = gh("api", "--paginate", `${route}/comments`, "--jq", ".[] | {login: .user.login, type: .user.type}");
|
|
125
|
+
return {
|
|
126
|
+
repository,
|
|
127
|
+
number: target.number,
|
|
128
|
+
currentUser: gh("api", "user", "--jq", ".login"),
|
|
129
|
+
author: found.login,
|
|
130
|
+
pullRequest: found.pr,
|
|
131
|
+
commenters: comments.split("\n").filter((line) => line !== "").map((line) => commenter.parse(JSON.parse(line)))
|
|
132
|
+
};
|
|
133
|
+
} catch {
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
function refusal(denied) {
|
|
138
|
+
const named = denied.map(({ repository, number }) => `${repository}#${String(number)}`).join(", ");
|
|
139
|
+
const [first] = denied;
|
|
140
|
+
const where = first === void 0 ? "" : `${String(first.number)} -R ${first.repository}`;
|
|
141
|
+
return `It comments on ${named}, an issue you wrote that nobody else has commented on, so there is no discussion thread yet. A decision or requirement for such an issue belongs in its body, not in a comment. Fetch the body (\`gh issue view ${where} --json body -q .body\`), add the content as a section, and save it with \`gh issue edit ${where} --body-file <file>\`. If this is a reply, a status note or a closing note the body cannot carry, run it again with \`${ESCAPE}=1\` in front.`;
|
|
142
|
+
}
|
|
143
|
+
/** The refusal for a tool call that would comment on an undiscussed issue of the user's own. */
|
|
144
|
+
function guard(input, look) {
|
|
145
|
+
const command = shellCommand(input);
|
|
146
|
+
if (command === void 0) return void 0;
|
|
147
|
+
const cwd = stringField(input, "cwd") ?? process.cwd();
|
|
148
|
+
const denied = commentTargets(command).flatMap((target) => {
|
|
149
|
+
const facts = look(target, cwd);
|
|
150
|
+
return facts !== void 0 && unanswered(facts) ? [facts] : [];
|
|
151
|
+
});
|
|
152
|
+
return denied.length === 0 ? void 0 : deny(refusal(denied));
|
|
153
|
+
}
|
|
154
|
+
const hook = (input) => guard(input, lookUp);
|
|
155
|
+
// src/examples/bin/issue-comment-guard.ts
|
|
156
|
+
await main(hook);
|
|
157
|
+
export {};
|