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.
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +12 -0
- package/dist/{check-DiQUS1CB.mjs → check-CRZ6Rgdo.mjs} +3 -2
- package/dist/check-ySa9Ce1V.mjs +1 -0
- package/dist/cli.mjs +204 -22
- package/dist/command-line-OrJYMqHx.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/dash-guard.mjs +907 -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-DR7G3z1u.mjs → schema-EYih4WFo.mjs} +1 -1
- package/dist/{schema-78xAlSN_.mjs → schemas-B4KRDIno.mjs} +1 -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-C4-tOQXQ.mjs +0 -1
- package/dist/command-line-ByzwzoIt.mjs +0 -109
|
@@ -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 {};
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { a as stringField, o as toolInput } from "../shell-4WSaabze.mjs";
|
|
4
|
+
import { n as cacheDirectory } from "../files-CBn-xAo2.mjs";
|
|
5
|
+
import { a as shellCommand, i as main, r as deny } from "../hook-DIS0wk_5.mjs";
|
|
6
|
+
import { a as gh, i as existingDirectory, n as Lookups, o as originRepository, r as addedPrivateReferences, s as repositoryWrites, t as ESCAPE } from "../private-references-CUZqASjK.mjs";
|
|
7
|
+
// src/examples/private-reference-guard.ts
|
|
8
|
+
/**
|
|
9
|
+
* Before a tool call, refuses to put the name of a private repository into a public one, through a file edit, a commit message or a `gh` write. Prefixing the command with `PRIVATE_REF_OK=1` lets a deliberate reference through.
|
|
10
|
+
*/
|
|
11
|
+
function previousContent(path) {
|
|
12
|
+
try {
|
|
13
|
+
return readFileSync(path, "utf8");
|
|
14
|
+
} catch {
|
|
15
|
+
return "";
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function fileChange(tool, input) {
|
|
19
|
+
const path = input["file_path"] ?? input["notebook_path"];
|
|
20
|
+
if (typeof path !== "string") return void 0;
|
|
21
|
+
const text = (name) => typeof input[name] === "string" ? input[name] : "";
|
|
22
|
+
if (tool === "Write") return {
|
|
23
|
+
path,
|
|
24
|
+
previous: previousContent(path),
|
|
25
|
+
added: text("content")
|
|
26
|
+
};
|
|
27
|
+
if (tool === "Edit") return {
|
|
28
|
+
path,
|
|
29
|
+
previous: text("old_string"),
|
|
30
|
+
added: text("new_string")
|
|
31
|
+
};
|
|
32
|
+
return tool === "NotebookEdit" ? {
|
|
33
|
+
path,
|
|
34
|
+
previous: "",
|
|
35
|
+
added: text("new_source")
|
|
36
|
+
} : void 0;
|
|
37
|
+
}
|
|
38
|
+
function changes(input) {
|
|
39
|
+
const cwd = stringField(input, "cwd") ?? process.cwd();
|
|
40
|
+
const command = shellCommand(input);
|
|
41
|
+
if (stringField(input, "tool_name") === "Bash" && command !== void 0) return repositoryWrites(command, cwd).map(({ target, files }) => ({
|
|
42
|
+
target,
|
|
43
|
+
added: `${files}\n${command}`,
|
|
44
|
+
previous: ""
|
|
45
|
+
}));
|
|
46
|
+
const change = fileChange(stringField(input, "tool_name") ?? "", toolInput(input));
|
|
47
|
+
if (change === void 0) return [];
|
|
48
|
+
const target = originRepository(existingDirectory(change.path, (directory) => existsSync(directory) && statSync(directory).isDirectory()));
|
|
49
|
+
return target === void 0 ? [] : [{
|
|
50
|
+
target,
|
|
51
|
+
added: change.added,
|
|
52
|
+
previous: change.previous
|
|
53
|
+
}];
|
|
54
|
+
}
|
|
55
|
+
function explanation(repositories, target) {
|
|
56
|
+
const plural = repositories.length === 1 ? "is a private repository" : "are private repositories";
|
|
57
|
+
return `It adds a reference to ${repositories.join(", ")}, which ${plural}, to ${target}, which is public. A public repository, issue, pull request or commit must not name a private one: the name alone tells a reader the project exists. Describe the work without the repository's name or link, or put the text where it belongs in the private repository. If naming it is deliberate, run the command again with \`${ESCAPE}=1\` in front.`;
|
|
58
|
+
}
|
|
59
|
+
/** The refusal for a tool call that would leak a private repository's name, using the given lookups. */
|
|
60
|
+
function guard(input, lookups) {
|
|
61
|
+
for (const change of changes(input)) {
|
|
62
|
+
const added = addedPrivateReferences(change, lookups);
|
|
63
|
+
if (added.length > 0) return deny(explanation(added, change.target));
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const hook = (input) => guard(input, new Lookups(gh, join(cacheDirectory(process.env), "examples", "repository-visibility.json")));
|
|
67
|
+
// src/examples/bin/private-reference-guard.ts
|
|
68
|
+
await main(hook);
|
|
69
|
+
export {};
|
|
@@ -0,0 +1,44 @@
|
|
|
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/repository-metadata.ts
|
|
3
|
+
/**
|
|
4
|
+
* After a repository is created, forked, renamed or transferred, reminds the agent to set its description and topics, with the exact commands.
|
|
5
|
+
*/
|
|
6
|
+
const TRANSFER_ROUTE = /^\/?repos\/([\w.-]+\/[\w.-]+)\/transfer$/u;
|
|
7
|
+
const REPOSITORY_URL = /https:\/\/github\.com\/([\w.-]+\/[\w.-]+)/u;
|
|
8
|
+
const FAILURE = /\b(?:HTTP [45]\d\d|GraphQL: [^\n]*?(?:Could not|Name already exists)|failed to |error:)/iu;
|
|
9
|
+
const CHANGES = /* @__PURE__ */ new Map([
|
|
10
|
+
["create", "created"],
|
|
11
|
+
["fork", "forked"],
|
|
12
|
+
["rename", "renamed"]
|
|
13
|
+
]);
|
|
14
|
+
function changeOf(words, output) {
|
|
15
|
+
if (words[0]?.split("/").at(-1) !== "gh") return void 0;
|
|
16
|
+
const [group, action, ...rest] = words.slice(1).filter((word) => !word.startsWith("-"));
|
|
17
|
+
const what = group === "repo" ? CHANGES.get(action ?? "") : void 0;
|
|
18
|
+
if (what !== void 0) return {
|
|
19
|
+
what,
|
|
20
|
+
repository: REPOSITORY_URL.exec(output)?.[1] ?? "OWNER/REPO"
|
|
21
|
+
};
|
|
22
|
+
if (group !== "api") return void 0;
|
|
23
|
+
const moved = [action ?? "", ...rest].map((word) => TRANSFER_ROUTE.exec(word)?.[1]).find((slug) => slug !== void 0);
|
|
24
|
+
return moved === void 0 ? void 0 : {
|
|
25
|
+
what: "transferred",
|
|
26
|
+
repository: moved
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
/** What a successful command did to a repository. Commands are read as parsed words, so text that only mentions one does not count. */
|
|
30
|
+
function repositoryChange(command, output) {
|
|
31
|
+
if (FAILURE.test(output)) return void 0;
|
|
32
|
+
return commandWords(command).map((words) => changeOf(words, output)).find((change) => change !== void 0);
|
|
33
|
+
}
|
|
34
|
+
function advice({ what, repository }) {
|
|
35
|
+
return `The repository ${repository} was ${what}. Set its description and topics now, and again whenever its purpose or name changes: \`gh repo edit ${repository} --description '<what it is and who it is for, in one sentence>' --add-topic <topic> --add-topic <topic>\`, then read them back with \`gh repo view ${repository} --json description,repositoryTopics\`. A repository without both is unfinished.`;
|
|
36
|
+
}
|
|
37
|
+
const hook = (input) => {
|
|
38
|
+
const command = shellCommand(input);
|
|
39
|
+
const change = command === void 0 ? void 0 : repositoryChange(command, toolOutput(input));
|
|
40
|
+
return change === void 0 ? void 0 : context("PostToolUse", advice(change));
|
|
41
|
+
};
|
|
42
|
+
// src/examples/bin/repository-metadata.ts
|
|
43
|
+
await main(hook);
|
|
44
|
+
export {};
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { mkdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { basename, dirname, join } from "node:path";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
// src/paths.ts
|
|
6
|
+
/**
|
|
7
|
+
* Where hookloom keeps a user's registry and its own disposable state.
|
|
8
|
+
*/
|
|
9
|
+
function base(env, windows, xdg, fallback) {
|
|
10
|
+
const chosen = process.platform === "win32" ? env[windows] : env[xdg];
|
|
11
|
+
return chosen === void 0 || chosen === "" ? join(homedir(), ...fallback) : chosen;
|
|
12
|
+
}
|
|
13
|
+
/** The user's hookloom directory in their configuration directory. */
|
|
14
|
+
function configurationDirectory(env) {
|
|
15
|
+
return join(base(env, "APPDATA", "XDG_CONFIG_HOME", [".config"]), "hookloom");
|
|
16
|
+
}
|
|
17
|
+
/** The registry file: `HOOKLOOM_REGISTRY` when set, otherwise `registry.json` in the configuration directory. */
|
|
18
|
+
function registryPath(env) {
|
|
19
|
+
return env["HOOKLOOM_REGISTRY"] ?? join(configurationDirectory(env), "registry.json");
|
|
20
|
+
}
|
|
21
|
+
/** Cached results and session state, all of which may be deleted at any time: `HOOKLOOM_CACHE_DIR` overrides it. */
|
|
22
|
+
function cacheDirectory(env) {
|
|
23
|
+
return env["HOOKLOOM_CACHE_DIR"] ?? join(base(env, "LOCALAPPDATA", "XDG_CACHE_HOME", [".cache"]), "hookloom");
|
|
24
|
+
}
|
|
25
|
+
/** The directory of Claude Code's user settings. */
|
|
26
|
+
function claudeDirectory(env) {
|
|
27
|
+
return env["CLAUDE_CONFIG_DIR"] ?? join(homedir(), ".claude");
|
|
28
|
+
}
|
|
29
|
+
// src/files.ts
|
|
30
|
+
/**
|
|
31
|
+
* File writes that a concurrent reader never sees half done.
|
|
32
|
+
*/
|
|
33
|
+
const OWNER_ONLY = 384;
|
|
34
|
+
const PERMISSION_BITS = 511;
|
|
35
|
+
/** Replaces a file in one step, keeping its permissions; a new file is readable by its owner only. */
|
|
36
|
+
function atomicWrite(path, content) {
|
|
37
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
38
|
+
const existing = statSync(path, { throwIfNoEntry: false });
|
|
39
|
+
const temporary = join(dirname(path), `.${basename(path)}.${randomUUID()}`);
|
|
40
|
+
try {
|
|
41
|
+
writeFileSync(temporary, content, {
|
|
42
|
+
mode: existing === void 0 ? OWNER_ONLY : existing.mode & PERMISSION_BITS,
|
|
43
|
+
flush: true
|
|
44
|
+
});
|
|
45
|
+
renameSync(temporary, path);
|
|
46
|
+
} finally {
|
|
47
|
+
rmSync(temporary, { force: true });
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
export { registryPath as a, configurationDirectory as i, cacheDirectory as n, claudeDirectory as r, atomicWrite as t };
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { text } from "node:stream/consumers";
|
|
2
|
+
import { i as parsePayload, o as toolInput, t as splitCommand } from "./shell-4WSaabze.mjs";
|
|
3
|
+
import { r as harnesses } from "./events-CHsq0Cl4.mjs";
|
|
4
|
+
// src/examples/hook.ts
|
|
5
|
+
/**
|
|
6
|
+
* What every example hook shares: reading its input, answering in the harness's output format and reading a tool call.
|
|
7
|
+
*/
|
|
8
|
+
/** Adds text to the conversation after an event. */
|
|
9
|
+
function context(event, additionalContext) {
|
|
10
|
+
return { hookSpecificOutput: {
|
|
11
|
+
hookEventName: event,
|
|
12
|
+
additionalContext
|
|
13
|
+
} };
|
|
14
|
+
}
|
|
15
|
+
/** Refuses a tool call before it runs, telling the agent why. */
|
|
16
|
+
function deny(reason) {
|
|
17
|
+
return { hookSpecificOutput: {
|
|
18
|
+
hookEventName: "PreToolUse",
|
|
19
|
+
permissionDecision: "deny",
|
|
20
|
+
permissionDecisionReason: reason
|
|
21
|
+
} };
|
|
22
|
+
}
|
|
23
|
+
/** The shell command of a tool call, or `undefined` when the call runs none. */
|
|
24
|
+
function shellCommand(input) {
|
|
25
|
+
const { command } = toolInput(input);
|
|
26
|
+
return typeof command === "string" ? command : void 0;
|
|
27
|
+
}
|
|
28
|
+
/** The words of every simple command a command line runs; none when it cannot be split. */
|
|
29
|
+
function commandWords(command) {
|
|
30
|
+
return splitCommand(command)?.words ?? [];
|
|
31
|
+
}
|
|
32
|
+
/** The text a tool returned, whether the harness reports it whole or as separate output and error streams. */
|
|
33
|
+
function toolOutput(input) {
|
|
34
|
+
const response = input["tool_response"];
|
|
35
|
+
if (typeof response === "string") return response;
|
|
36
|
+
if (response === void 0 || response === null) return "";
|
|
37
|
+
return JSON.stringify(response);
|
|
38
|
+
}
|
|
39
|
+
/** Runs a hook as the program a registry names: `<hook>.mjs <claude|codex>` with the event's input on standard input. */
|
|
40
|
+
async function main(hook) {
|
|
41
|
+
try {
|
|
42
|
+
const harness = harnesses.find((name) => name === process.argv[2]);
|
|
43
|
+
if (harness === void 0) throw new Error(`expected one of ${harnesses.join(", ")} as the argument`);
|
|
44
|
+
const answer = await hook(parsePayload(await text(process.stdin)), harness);
|
|
45
|
+
if (answer !== void 0) process.stdout.write(`${JSON.stringify(answer)}\n`);
|
|
46
|
+
} catch (error) {
|
|
47
|
+
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
48
|
+
process.exitCode = 1;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
export { shellCommand as a, main as i, context as n, toolOutput as o, deny as r, commandWords as t };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { mkdirSync, rmSync } from "node:fs";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
// src/lock.ts
|
|
4
|
+
/**
|
|
5
|
+
* One holder at a time: a directory is created in a single step on every platform, so whoever creates it holds the lock.
|
|
6
|
+
*/
|
|
7
|
+
var LockedError = class extends Error {};
|
|
8
|
+
function withLock(path, work) {
|
|
9
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
10
|
+
try {
|
|
11
|
+
mkdirSync(path);
|
|
12
|
+
} catch (error) {
|
|
13
|
+
if (!(error instanceof Error && "code" in error && error.code === "EEXIST")) throw error;
|
|
14
|
+
throw new LockedError(`another hookloom holds this lock; if none is running, remove ${path}`);
|
|
15
|
+
}
|
|
16
|
+
try {
|
|
17
|
+
return work();
|
|
18
|
+
} finally {
|
|
19
|
+
rmSync(path, { recursive: true });
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export { withLock as n, LockedError as t };
|