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.
@@ -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 };
@@ -0,0 +1,123 @@
1
+ import { posix } from "node:path";
2
+ import { a as stringField, o as toolInput, t as splitCommand } from "./shell-4WSaabze.mjs";
3
+ // src/dispatch/permission-rule.ts
4
+ /**
5
+ * Evaluates the permission rule a handler's `if` field holds against a tool call, following https://code.claude.com/docs/en/permissions and the hook-specific behaviour at https://code.claude.com/docs/en/hooks.
6
+ */
7
+ const COMMAND_TOOLS = /* @__PURE__ */ new Set([
8
+ "Bash",
9
+ "Monitor",
10
+ "PowerShell"
11
+ ]);
12
+ const FILE_TOOLS = /* @__PURE__ */ new Map([["Edit", /* @__PURE__ */ new Set([
13
+ "Edit",
14
+ "Write",
15
+ "NotebookEdit",
16
+ "MultiEdit"
17
+ ])], ["Read", /* @__PURE__ */ new Set(["Read"])]]);
18
+ const PATH_RULES_NEVER_MATCHED = /* @__PURE__ */ new Set([
19
+ "Write",
20
+ "NotebookEdit",
21
+ "MultiEdit",
22
+ "Glob",
23
+ "Grep"
24
+ ]);
25
+ const PARAMETER = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*)$/u;
26
+ function parsePermissionRule(rule) {
27
+ const match = /^([^()\s]+)(?:\((.*)\))?$/su.exec(rule);
28
+ const tool = match?.[1];
29
+ if (tool === void 0) return void 0;
30
+ const specifier = match?.[2];
31
+ return specifier === void 0 || specifier === "*" ? { tool } : {
32
+ tool,
33
+ specifier
34
+ };
35
+ }
36
+ /** Why a rule cannot be evaluated, or `undefined` when it can. */
37
+ function permissionRuleProblem(rule) {
38
+ const parsed = parsePermissionRule(rule);
39
+ if (parsed === void 0) return `${JSON.stringify(rule)} is not a permission rule`;
40
+ const { tool, specifier } = parsed;
41
+ if (specifier === void 0 || COMMAND_TOOLS.has(tool) || FILE_TOOLS.has(tool)) return void 0;
42
+ if (PATH_RULES_NEVER_MATCHED.has(tool)) return `Claude Code never matches a ${tool}(...) path rule; write an Edit or Read rule`;
43
+ if (tool.startsWith("mcp__")) return "Claude Code skips an MCP rule that has parentheses";
44
+ if (!PARAMETER.test(specifier)) return `cannot evaluate the specifier of a ${tool} rule`;
45
+ }
46
+ function escaped(text) {
47
+ return text.replaceAll(/[.*+?^${}()|[\]\\]/gu, "\\$&");
48
+ }
49
+ /** Whether `text` matches a pattern in which `*` stands for any text. */
50
+ function wildcard(pattern, text) {
51
+ return new RegExp(`^${pattern.split("*").map(escaped).join(".*")}$`, "su").test(text);
52
+ }
53
+ function commandMatches(specifier, command) {
54
+ const pattern = specifier.endsWith(":*") ? `${specifier.slice(0, -2)} *` : specifier;
55
+ return command === (pattern.endsWith(" *") && pattern.indexOf("*") === pattern.length - 1 ? pattern.slice(0, -2) : void 0) || wildcard(pattern, command);
56
+ }
57
+ function commandRuleMatches(specifier, command) {
58
+ const split = splitCommand(command);
59
+ if (split === void 0) return true;
60
+ const namesMoreThanTheProgram = specifier.replace(/(?: \*|:\*)$/u, "").includes(" ");
61
+ if (split.expands && namesMoreThanTheProgram) return true;
62
+ return split.commands.some((simple) => commandMatches(specifier, simple));
63
+ }
64
+ function globSource(pattern) {
65
+ return pattern.split(/(\*\*\/|\*\*|\*|\?)/u).map((part) => {
66
+ if (part === "**/") return "(?:[^/]*/)*";
67
+ if (part === "**") return ".*";
68
+ if (part === "*") return "[^/]*";
69
+ return part === "?" ? "[^/]" : escaped(part);
70
+ }).join("");
71
+ }
72
+ function posixPath(path) {
73
+ return path.replaceAll("\\", "/").replace(/^([A-Za-z]):/u, (_drive, letter) => `/${letter.toLowerCase()}`);
74
+ }
75
+ function pathMatches(specifier, path, directories) {
76
+ const target = posix.resolve(posixPath(directories.cwd), posixPath(path));
77
+ let anchor = posixPath(directories.cwd);
78
+ let pattern = specifier;
79
+ if (specifier.startsWith("//")) {
80
+ anchor = "";
81
+ pattern = specifier.slice(2);
82
+ } else if (specifier.startsWith("~/")) {
83
+ anchor = posixPath(directories.home);
84
+ pattern = specifier.slice(2);
85
+ } else if (specifier.startsWith("/")) {
86
+ anchor = posixPath(directories.settings);
87
+ pattern = specifier.slice(1);
88
+ } else if (specifier.startsWith("./")) pattern = specifier.slice(2);
89
+ const anyDepth = !specifier.startsWith("./") && !specifier.startsWith("/") && !specifier.startsWith("~/") && !pattern.includes("/") ? "(?:[^/]*/)*" : "";
90
+ const prefix = escaped(anchor.replace(/\/$/u, ""));
91
+ return new RegExp(`^${prefix}/${anyDepth}${globSource(pattern.replace(/\/$/u, ""))}(?:/.*)?$`, "su").test(target);
92
+ }
93
+ function parameterMatches(specifier, payload, tool) {
94
+ const match = PARAMETER.exec(specifier);
95
+ const [name, expected] = [match?.[1], match?.[2]?.trim()];
96
+ if (name === void 0 || expected === void 0) return false;
97
+ const input = toolInput(payload);
98
+ if (tool === "WebFetch" && name === "domain") {
99
+ const url = input["url"];
100
+ return typeof url === "string" && URL.canParse(url) && wildcard(expected, new URL(url).hostname);
101
+ }
102
+ const value = input[name];
103
+ return (typeof value === "string" || typeof value === "number" || typeof value === "boolean") && wildcard(expected, String(value));
104
+ }
105
+ /** Whether a tool call satisfies a rule. A payload that describes no tool call satisfies none. */
106
+ function permissionRuleMatches(rule, payload, directories) {
107
+ const tool = stringField(payload, "tool_name");
108
+ if (tool === void 0) return false;
109
+ const covered = FILE_TOOLS.get(rule.tool);
110
+ const named = rule.tool.includes("*") ? wildcard(rule.tool, tool) : tool === rule.tool;
111
+ if (rule.specifier === void 0) return named;
112
+ const input = toolInput(payload);
113
+ if (COMMAND_TOOLS.has(rule.tool)) {
114
+ const command = input["command"];
115
+ return named && typeof command === "string" && commandRuleMatches(rule.specifier, command);
116
+ }
117
+ if (covered !== void 0) {
118
+ const path = input["file_path"] ?? input["notebook_path"];
119
+ return covered.has(tool) && typeof path === "string" && pathMatches(rule.specifier, path, directories);
120
+ }
121
+ return named && parameterMatches(rule.specifier, payload, tool);
122
+ }
123
+ export { permissionRuleMatches as n, permissionRuleProblem as r, parsePermissionRule as t };
@@ -0,0 +1,254 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import { dirname, resolve } from "node:path";
4
+ import { n as isRecord, t as splitCommand } from "./shell-4WSaabze.mjs";
5
+ import { t as atomicWrite } from "./files-CBn-xAo2.mjs";
6
+ // src/examples/private-references.ts
7
+ /**
8
+ * Finds text going into a public GitHub repository that names a private one.
9
+ *
10
+ * A reference is a GitHub URL or SSH address, `owner/repo#N`, or a bare `owner/repo` whose owner is one of the signed-in user's own accounts (a bare pair with any other owner is too easily a path or a phrase). A repository is private only when the GitHub API says so; one it cannot see is unknown and never blocks, and text counts as going to a public repository only on the same evidence.
11
+ */
12
+ /** The variable that lets a deliberate reference through when written before the command. */
13
+ const ESCAPE = "PRIVATE_REF_OK";
14
+ const LOOKUP_TIMEOUT_MILLISECONDS = 2e4;
15
+ const URL_REFERENCE = /github\.com[/:]([\w.-]+)\/([\w.-]+)/gu;
16
+ const NUMBERED_REFERENCE = /(?<![\w/.:@-])([\w.-]+)\/([\w.-]+)(?=#\d+)/gu;
17
+ const WRITING = /* @__PURE__ */ new Set([
18
+ "issue create",
19
+ "issue edit",
20
+ "issue comment",
21
+ "issue close",
22
+ "pr create",
23
+ "pr edit",
24
+ "pr comment",
25
+ "pr review",
26
+ "pr close",
27
+ "pr merge",
28
+ "release create",
29
+ "release edit"
30
+ ]);
31
+ const API_VALUE_FLAGS = /* @__PURE__ */ new Set([
32
+ "-X",
33
+ "--method",
34
+ "-H",
35
+ "--header",
36
+ "-f",
37
+ "--raw-field",
38
+ "-F",
39
+ "--field",
40
+ "--input",
41
+ "-q",
42
+ "--jq",
43
+ "-t",
44
+ "--template",
45
+ "--hostname",
46
+ "--cache",
47
+ "-p",
48
+ "--preview"
49
+ ]);
50
+ const API_BODY_FLAGS = /* @__PURE__ */ new Set([
51
+ "-f",
52
+ "--raw-field",
53
+ "-F",
54
+ "--field",
55
+ "--input"
56
+ ]);
57
+ const BODY_FILE_FLAGS = /* @__PURE__ */ new Set([
58
+ "-F",
59
+ "--body-file",
60
+ "--file"
61
+ ]);
62
+ const ENDPOINT = /^\/?repos\/([^/{}]+)\/([^/{}]+)(?:\/|$)/u;
63
+ const gh = (args) => {
64
+ try {
65
+ return execFileSync("gh", [...args], {
66
+ encoding: "utf8",
67
+ timeout: LOOKUP_TIMEOUT_MILLISECONDS,
68
+ stdio: [
69
+ "ignore",
70
+ "pipe",
71
+ "ignore"
72
+ ]
73
+ });
74
+ } catch {
75
+ return;
76
+ }
77
+ };
78
+ /** The user's account names and each repository's visibility, read through `gh` and cached on disk. */
79
+ var Lookups = class {
80
+ run;
81
+ file;
82
+ now;
83
+ constructor(run, file, now = Date.now) {
84
+ this.run = run;
85
+ this.file = file;
86
+ this.now = now;
87
+ }
88
+ /** The signed-in user's login and organisations in lower case; none when `gh` cannot say. */
89
+ owners() {
90
+ const known = this.recall("owners");
91
+ if (Array.isArray(known)) return known.map(String);
92
+ const login = this.run([
93
+ "api",
94
+ "user",
95
+ "--jq",
96
+ ".login"
97
+ ]);
98
+ if (login === void 0) return [];
99
+ const organisations = this.run([
100
+ "api",
101
+ "user/orgs",
102
+ "--paginate",
103
+ "--jq",
104
+ ".[].login"
105
+ ]) ?? "";
106
+ const owners = [...new Set([login, ...organisations.split("\n")].map((name) => name.trim().toLowerCase()).filter((name) => name !== ""))].toSorted();
107
+ this.remember("owners", owners);
108
+ return owners;
109
+ }
110
+ visibility(repository) {
111
+ const key = `repository:${repository}`;
112
+ const known = this.recall(key);
113
+ if (known === "private" || known === "public") return known;
114
+ const answer = this.run([
115
+ "api",
116
+ `repos/${repository}`,
117
+ "--jq",
118
+ ".private"
119
+ ])?.trim();
120
+ if (answer !== "true" && answer !== "false") return "unknown";
121
+ const visibility = answer === "true" ? "private" : "public";
122
+ this.remember(key, visibility);
123
+ return visibility;
124
+ }
125
+ load() {
126
+ try {
127
+ const value = JSON.parse(readFileSync(this.file, "utf8"));
128
+ return isRecord(value) ? value : {};
129
+ } catch {
130
+ return {};
131
+ }
132
+ }
133
+ recall(key) {
134
+ const entry = this.load()[key];
135
+ return isRecord(entry) && typeof entry["at"] === "number" && this.now() - entry["at"] < 36e5 ? entry["value"] : void 0;
136
+ }
137
+ remember(key, value) {
138
+ try {
139
+ atomicWrite(this.file, JSON.stringify({
140
+ ...this.load(),
141
+ [key]: {
142
+ at: this.now(),
143
+ value
144
+ }
145
+ }));
146
+ } catch {}
147
+ }
148
+ };
149
+ function slug(owner, name) {
150
+ return `${owner}/${name.replace(/\.+$/u, "").replace(/\.git$/u, "").replace(/\.+$/u, "")}`.toLowerCase();
151
+ }
152
+ function escaped(text) {
153
+ return text.replaceAll(/[.*+?^${}()|[\]\\]/gu, "\\$&");
154
+ }
155
+ /** The repositories a text names, as lower-case `owner/name`, in order and once each. */
156
+ function references(text, owners) {
157
+ const own = owners.length === 0 ? [] : [new RegExp(`(?<![\\w/.:@-])(${owners.map(escaped).join("|")})/([\\w.-]*\\w)`, "giu")];
158
+ const found = [
159
+ URL_REFERENCE,
160
+ NUMBERED_REFERENCE,
161
+ ...own
162
+ ].flatMap((pattern) => [...text.matchAll(pattern)].map((match) => slug(match[1] ?? "", match[2] ?? "")));
163
+ return [...new Set(found.filter((repository) => !repository.endsWith("/")))];
164
+ }
165
+ /** The private repositories `added` names that `previous` did not, when `target` is public. */
166
+ function addedPrivateReferences(change, lookups) {
167
+ const owners = lookups.owners();
168
+ const already = new Set(references(change.previous, owners));
169
+ const added = references(change.added, owners).filter((repository) => !already.has(repository));
170
+ if (added.length === 0 || lookups.visibility(change.target.toLowerCase()) !== "public") return [];
171
+ return added.filter((repository) => lookups.visibility(repository) === "private");
172
+ }
173
+ const SSH_ADDRESS = /^git@(?:ssh\.)?github\.com[\w.-]*:(.+)$/u;
174
+ /** `owner/name` from the address of a GitHub repository. */
175
+ function repositoryOfAddress(address) {
176
+ const short = SSH_ADDRESS.exec(address)?.[1];
177
+ const url = short === void 0 && URL.canParse(address) ? new URL(address) : void 0;
178
+ const [owner, name] = (short ?? (url?.hostname.endsWith("github.com") === true ? url.pathname : "")).split("/").filter((part) => part !== "");
179
+ return owner === void 0 || name === void 0 ? void 0 : slug(owner, name);
180
+ }
181
+ /** `owner/name` of the GitHub repository whose working tree holds a directory, from its `origin` remote. */
182
+ function originRepository(directory) {
183
+ try {
184
+ return repositoryOfAddress(execFileSync("git", [
185
+ "-C",
186
+ directory,
187
+ "remote",
188
+ "get-url",
189
+ "origin"
190
+ ], {
191
+ encoding: "utf8",
192
+ timeout: LOOKUP_TIMEOUT_MILLISECONDS,
193
+ stdio: [
194
+ "ignore",
195
+ "pipe",
196
+ "ignore"
197
+ ]
198
+ }).trim());
199
+ } catch {
200
+ return;
201
+ }
202
+ }
203
+ function flagValue(words, flags) {
204
+ const index = words.findIndex((word) => flags.has(word) || word.startsWith("--") && flags.has(word.split("=", 1)[0] ?? "") && word.includes("="));
205
+ const word = words[index];
206
+ if (word === void 0) return void 0;
207
+ return word.includes("=") ? word.slice(word.indexOf("=") + 1) : words[index + 1];
208
+ }
209
+ function apiTarget(words) {
210
+ let endpoint;
211
+ for (let index = 0; index < words.length; index += 1) {
212
+ const word = words[index] ?? "";
213
+ if (API_VALUE_FLAGS.has(word)) index += 1;
214
+ else if (!word.startsWith("-")) endpoint ??= word;
215
+ }
216
+ const match = (flagValue(words, /* @__PURE__ */ new Set(["-X", "--method"]))?.toUpperCase() ?? (words.some((word) => API_BODY_FLAGS.has(word)) ? "POST" : "GET")) === "GET" ? null : ENDPOINT.exec(endpoint ?? "");
217
+ return match === null ? void 0 : slug(match[1] ?? "", match[2] ?? "");
218
+ }
219
+ function fileText(path) {
220
+ try {
221
+ return readFileSync(path, "utf8");
222
+ } catch {
223
+ return "";
224
+ }
225
+ }
226
+ function writeOf(words, cwd) {
227
+ const [program, ...rest] = words;
228
+ const here = (directory) => originRepository(resolve(cwd, directory));
229
+ if (program === "git") return rest.slice(0, rest.indexOf("commit") + 1).includes("commit") ? here(flagValue(rest.slice(0, rest.indexOf("commit")), /* @__PURE__ */ new Set(["-C"])) ?? ".") : void 0;
230
+ if (program !== "gh") return void 0;
231
+ if (rest[0] === "api") return apiTarget(rest.slice(1));
232
+ if (!WRITING.has(rest.slice(0, 2).join(" "))) return void 0;
233
+ const named = flagValue(rest, /* @__PURE__ */ new Set(["-R", "--repo"]));
234
+ return named?.includes("/") === true ? named.toLowerCase() : here(".");
235
+ }
236
+ /** The commands of a command line that write text to GitHub or a commit, leaving out any that opt out. */
237
+ function repositoryWrites(command, cwd) {
238
+ const split = splitCommand(command);
239
+ if (split === void 0) return [];
240
+ return split.words.flatMap((words, position) => {
241
+ const target = (split.prefixes[position] ?? []).some((word) => word.startsWith(`PRIVATE_REF_OK=`) && !["", "0"].includes(word.slice(15))) ? void 0 : writeOf(words, cwd);
242
+ if (target === void 0) return [];
243
+ return [{
244
+ target,
245
+ files: words.flatMap((word, index) => BODY_FILE_FLAGS.has(word) ? [fileText(resolve(cwd, words[index + 1] ?? ""))] : []).join("\n")
246
+ }];
247
+ });
248
+ }
249
+ /** The nearest directory of a path that exists, which decides the repository of a file not yet written. */
250
+ function existingDirectory(path, exists) {
251
+ const parent = dirname(path);
252
+ return exists(parent) || parent === dirname(parent) ? parent : existingDirectory(parent, exists);
253
+ }
254
+ export { gh as a, existingDirectory as i, Lookups as n, originRepository as o, addedPrivateReferences as r, repositoryWrites as s, ESCAPE as t };
@@ -0,0 +1,29 @@
1
+ // src/dispatch/prompt-text.ts
2
+ /**
3
+ * Separates what a person wrote in a prompt from what the harness put there: other sessions' messages, background-task notices and the harness's own wrappers arrive through the same field as typing.
4
+ */
5
+ const MESSAGE_BLOCK = /<(?<tag>agent-message|teammate-message|cross-session-message|task-notification)(?=[\s/>])[^>\n]*>(?:[^\n]*?<\/\k<tag>>|[\s\S]*?^[ \t]*<\/\k<tag>>)/gmu;
6
+ const NOTICE_BLOCK = /<(?<tag>system-reminder|codex_internal_context)(?=[\s/>])[^>]*>[\s\S]*?<\/\k<tag>>|<artifact-content-authored-by-others\s*\/>/gu;
7
+ const CROSS_SESSION_NOTICE = /^\[Cross-session idle notice\](?:[\s\S]*?This is an automated notice from that session's harness[^\n]*|[^\n]*)|^\[Cross-session delivery notice\][^\n]*$/gmu;
8
+ const HARNESS_LINES = new RegExp([
9
+ "^Another Claude session sent a message(?: while you were working)?:[ \\t]*$",
10
+ "^This came from another Claude session\\b[^\\n]*\\bnot typed by your user\\b[^\\n]*$",
11
+ "^That \"[^\\n]*?\" is an agent working inside this same session\\b[^\\n]*$",
12
+ "^\\[SYSTEM NOTIFICATION - NOT USER INPUT\\][ \\t]*(?:\\n(?:This is an automated background-task event|Do NOT interpret this as|No human input has been received)[^\\n]*)*",
13
+ "^Goal check-in: «(?:[\\s\\S]*?^Check on their progress[^\\n]*|[^\\n]*)",
14
+ "^\\[Earlier usage-limit notes no longer apply\\.[^\\n]*$",
15
+ "^\\[Request interrupted by user[^\\n]*$",
16
+ "^This session is being continued from another machine\\. Application state may have changed\\.[^\\n]*$"
17
+ ].join("|"), "gmu");
18
+ const HARNESS_PROMPT = /^\s*(?:Stop hook feedback:|Base directory for this skill:|This session is being continued from a previous conversation|The summarized conversation included Artifact content)/u;
19
+ /** The prompt without other sessions' messages and the harness's notices, keeping the user's commands and attachments; empty when nothing of the user's is left. */
20
+ function withoutHarnessMessages(prompt) {
21
+ const stripped = [
22
+ MESSAGE_BLOCK,
23
+ NOTICE_BLOCK,
24
+ CROSS_SESSION_NOTICE,
25
+ HARNESS_LINES
26
+ ].reduce((text, pattern) => text.replaceAll(pattern, " "), prompt);
27
+ return HARNESS_PROMPT.test(stripped) ? "" : stripped.trim();
28
+ }
29
+ export { withoutHarnessMessages as t };