@instruction.md/agents 0.0.0-stage → 0.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/dist/hook.js ADDED
@@ -0,0 +1,406 @@
1
+ // src/hook.ts
2
+ import { spawn } from "node:child_process";
3
+ import { mkdirSync, readdirSync, readFileSync, statSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";
4
+ import { hostname } from "node:os";
5
+ import { isAbsolute, join, relative } from "node:path";
6
+
7
+ // package.json
8
+ var version = "0.2.0";
9
+
10
+ // src/hook.ts
11
+ import {
12
+ capBlock,
13
+ contextBlock,
14
+ DEFAULT_MAX_INJECT_CHARS,
15
+ DEFAULT_URL,
16
+ fetchCurrent,
17
+ findFollow,
18
+ FollowConfigError,
19
+ followAt,
20
+ followerReader,
21
+ httpReader,
22
+ keysOf,
23
+ labelOf,
24
+ readState,
25
+ sha256,
26
+ updateBlock,
27
+ writeState
28
+ } from "instruction.md/cli";
29
+ import { HOOK_HOST_IDS, PROFILES, untag, writeClaude } from "./hosts.js";
30
+ var HOOK_HOSTS = ["claude-code", "codex"];
31
+ var APPLY_NOTE = "applied-note";
32
+ function applyDetached(root, hosts) {
33
+ const script = process.argv[1];
34
+ if (!script || !/instruction-agents(\.js)?$|main\.(js|ts)$/.test(script)) return;
35
+ try {
36
+ const p = spawn(process.execPath, [...process.execArgv, script, "apply", "--if-changed", "--quiet", "--note", "--host", hosts.join(","), "--dir", root], { cwd: root, detached: true, stdio: "ignore", env: process.env });
37
+ p.on("error", () => {
38
+ });
39
+ p.unref();
40
+ } catch {
41
+ }
42
+ }
43
+ var ver = (c) => c.version ? `v${c.version}` : c.versionId;
44
+ function whereFrom(found, cwd) {
45
+ const file = join(found.dir, "current.md");
46
+ if (!found.root || !cwd) return file;
47
+ const inside = relative(found.root, cwd);
48
+ if (inside.startsWith("..") || isAbsolute(inside)) return file;
49
+ return relative(cwd, file) || file;
50
+ }
51
+ var GIVEN = "given";
52
+ var markerOf = (dir, sid, digest) => join(dir, GIVEN, `${sha256(sid).slice(7, 23)}-${digest.replace(/^sha256:/, "").slice(0, 16)}`);
53
+ var TWIN_MS = 3e4;
54
+ function claimGiven(dir, sid, digest, o) {
55
+ const file = markerOf(dir, sid, digest);
56
+ try {
57
+ mkdirSync(join(dir, GIVEN), { recursive: true });
58
+ } catch {
59
+ return { give: true, at: o.now };
60
+ }
61
+ try {
62
+ writeFileSync(file, "", { flag: "wx" });
63
+ try {
64
+ utimesSync(file, o.now / 1e3, o.now / 1e3);
65
+ } catch {
66
+ }
67
+ return { give: true, at: o.now };
68
+ } catch (e) {
69
+ if (e.code !== "EEXIST") return { give: true, at: o.now };
70
+ }
71
+ let at = 0;
72
+ try {
73
+ at = statSync(file).mtimeMs;
74
+ } catch {
75
+ return { give: true, at: o.now };
76
+ }
77
+ const again = o.wiped ? o.now - at >= TWIN_MS : o.since !== void 0 && at < o.since - 2e3;
78
+ if (!again) return { give: false, at };
79
+ try {
80
+ utimesSync(file, o.now / 1e3, o.now / 1e3);
81
+ } catch {
82
+ }
83
+ return { give: true, at: o.now };
84
+ }
85
+ function pruneGiven(dir, now) {
86
+ let names = [];
87
+ try {
88
+ names = readdirSync(join(dir, GIVEN));
89
+ } catch {
90
+ return;
91
+ }
92
+ for (const n of names) {
93
+ try {
94
+ const f = join(dir, GIVEN, n);
95
+ if (now - statSync(f).mtimeMs > 14 * 864e5) unlinkSync(f);
96
+ } catch {
97
+ }
98
+ }
99
+ }
100
+ function within(p, ms) {
101
+ return Promise.race([p, new Promise((ok) => {
102
+ const t = setTimeout(() => ok(null), ms);
103
+ t.unref?.();
104
+ })]);
105
+ }
106
+ async function runHook(host, event, o = {}) {
107
+ const n = PROFILES[host].read(event);
108
+ return writeClaude(await follow(n, o), n);
109
+ }
110
+ async function runHostHook(host, event, o = {}) {
111
+ const p = PROFILES[host];
112
+ if (!p) throw new Error(`unknown host ${host}`);
113
+ const n = p.read(event, o.event);
114
+ const cap = p.maxChars?.(n);
115
+ const a = await follow(n, { ...o, ...cap !== void 0 ? { maxChars: Math.min(cap, o.maxChars ?? cap) } : {}, tagFree: p.tagFree });
116
+ return p.write(a, n);
117
+ }
118
+ async function follow(n, o = {}) {
119
+ const now = o.now ?? Date.now;
120
+ const started = now();
121
+ if (!n.phase) return null;
122
+ const start = n.phase === "start" || n.phase === "subagent";
123
+ let found;
124
+ try {
125
+ found = o.follow ? followAt(o.follow, { ...o.requireSignature ? { requireSignature: true } : {} }) : findFollow(o.dir ?? n.cwd ?? process.cwd());
126
+ } catch (e) {
127
+ return start ? { notice: `instruction.md: ${e instanceof FollowConfigError ? e.message : String(e)}` } : null;
128
+ }
129
+ if (!found) return null;
130
+ if (o.requireSignature) found.config.requireSignature = true;
131
+ const sid = n.session ?? "default";
132
+ if (n.phase === "reset") {
133
+ forget(found.dir, sid, now());
134
+ return null;
135
+ }
136
+ const r = await fetchCurrent(found, { deadlineMs: o.deadlineMs ?? 1500, now, reader: o.reader ? () => o.reader(found) : null });
137
+ if (n.phase === "refresh") return null;
138
+ const cur = r.current;
139
+ const label = cur?.label ?? labelOf(found.config.follow);
140
+ const out = {};
141
+ const say = (s) => {
142
+ out.notice = out.notice ? `${out.notice}
143
+ ${s}` : s;
144
+ };
145
+ const shape = (block) => o.tagFree ? untag(block) : block;
146
+ if (!cur) {
147
+ const why = r.hold?.reason ?? r.error ?? "nothing was read";
148
+ if (o.failClosed) {
149
+ const reason = `instruction.md: this project follows ${label}, and no copy of it could be read (${why}).`;
150
+ return start ? { stop: reason } : { block: reason };
151
+ }
152
+ return start ? { notice: `instruction.md: couldn't read ${label} (${why}); this session goes on without it` } : null;
153
+ }
154
+ const max = o.maxChars ?? found.config.maxInjectChars ?? DEFAULT_MAX_INJECT_CHARS;
155
+ const where = whereFrom(found, n.cwd);
156
+ const state = readState(found.dir);
157
+ const sessions = { ...state?.sessions ?? {} };
158
+ const prev = sessions[sid];
159
+ const at = new Date(now()).toISOString();
160
+ const held = r.hold?.versionId ?? (r.hold ? r.hold.reason : void 0);
161
+ const source = n.source ?? "";
162
+ const wiped = n.phase === "start" && (["clear", "compact", "fork"].includes(source) || n.session === void 0);
163
+ const again = n.phase === "start" && (wiped || source === "resume");
164
+ let give;
165
+ if (n.phase === "subagent" || wiped || !prev) give = "whole";
166
+ else if (prev.digest !== cur.digest) give = "update";
167
+ else give = again ? "whole" : null;
168
+ let givenAt;
169
+ if (give && n.phase !== "subagent") {
170
+ const c = claimGiven(found.dir, sid, cur.digest, { since: prev?.givenAt, wiped: again, now: now() });
171
+ givenAt = Math.max(c.at, prev?.givenAt ?? 0);
172
+ if (!c.give) give = null;
173
+ }
174
+ if (give === "update" && prev) {
175
+ out.context = shape(capBlock(updateBlock(prev, cur), max, where));
176
+ say(`instruction.md: ${label} ${prev.version ? `v${prev.version}` : "earlier version"} → ${ver(cur)}${cur.verified ? " (signature verified)" : ""}`);
177
+ } else if (give) {
178
+ out.context = shape(capBlock(contextBlock(cur), max, where));
179
+ if (start && r.source === "stale" && r.error) say(`instruction.md: ${label} couldn't be read now (${r.error}); using the last good copy, ${ver(cur)}`);
180
+ }
181
+ if (r.hold && held && prev?.held !== held) say(`instruction.md: a newer version of ${label} is held (${r.hold.reason}); keeping ${ver(cur)}`);
182
+ const hosts = found.config.apply ?? [];
183
+ if (found.root && hosts.length && n.phase !== "subagent") {
184
+ const note = join(found.dir, APPLY_NOTE);
185
+ try {
186
+ const t = readFileSync(note, "utf8").trim();
187
+ unlinkSync(note);
188
+ if (t) say(`instruction.md: ${t}`);
189
+ } catch {
190
+ }
191
+ if (n.phase === "start") {
192
+ let appliedFor;
193
+ try {
194
+ appliedFor = JSON.parse(readFileSync(join(found.dir, "applied.json"), "utf8")).versionId;
195
+ } catch {
196
+ }
197
+ if (appliedFor !== cur.versionId) (o.applyInBackground ?? applyDetached)(found.root, hosts);
198
+ }
199
+ }
200
+ if (o.take && found.config.deploymentId && !found.config.converse && (n.phase === "start" || n.phase === "check") && now() - started < 1500) {
201
+ const got = await within(o.take(found.config.deploymentId, found).catch(() => []), 800);
202
+ const lines = (got || []).flatMap((m) => {
203
+ if (m.control === "interrupt") return [`${m.by ?? "A person"} asks you to stop what you are doing now, say where you are, and wait for them.`];
204
+ return m.text ? [`${m.by ?? "A person"} wrote to you through instruction.md:
205
+ ${m.text}`] : [];
206
+ });
207
+ if (lines.length) {
208
+ const block = `<messages from="instruction.md">
209
+ ${lines.join("\n\n")}
210
+ </messages>`;
211
+ out.context = out.context ? `${out.context}
212
+
213
+ ${block}` : block;
214
+ say(`instruction.md: ${lines.length === 1 ? "a message" : `${lines.length} messages`} from your team handed to the agent`);
215
+ }
216
+ }
217
+ if (n.phase !== "subagent" && state) {
218
+ if (start) pruneGiven(found.dir, now());
219
+ const rec = { ...prev ?? {}, digest: cur.digest, version: cur.version, at, ...givenAt !== void 0 ? { givenAt } : {}, ...held ? { held } : {} };
220
+ sessions[sid] = rec;
221
+ if (o.report && rec.reported !== cur.versionId && now() - started < (o.reportBudgetMs ?? 1200)) {
222
+ const ok = await within(o.report(cur, sid, found).catch(() => false), 600);
223
+ if (ok) sessions[sid] = { ...rec, reported: cur.versionId };
224
+ }
225
+ try {
226
+ writeState(found.dir, { ...state, sessions }, now());
227
+ } catch {
228
+ }
229
+ }
230
+ return out.context || out.notice ? out : null;
231
+ }
232
+ function forget(dir, sid, now) {
233
+ const state = readState(dir);
234
+ if (state?.sessions?.[sid]) {
235
+ const sessions = { ...state.sessions };
236
+ delete sessions[sid];
237
+ try {
238
+ writeState(dir, { ...state, sessions }, now);
239
+ } catch {
240
+ }
241
+ }
242
+ const prefix = `${sha256(sid).slice(7, 23)}-`;
243
+ let names = [];
244
+ try {
245
+ names = readdirSync(join(dir, GIVEN));
246
+ } catch {
247
+ return;
248
+ }
249
+ for (const f of names) if (f.startsWith(prefix)) {
250
+ try {
251
+ unlinkSync(join(dir, GIVEN, f));
252
+ } catch {
253
+ }
254
+ }
255
+ }
256
+ async function readStdin(timeoutMs = 1e3) {
257
+ if (process.stdin.isTTY) return "";
258
+ return new Promise((done) => {
259
+ let data = "";
260
+ const t = setTimeout(() => {
261
+ process.stdin.pause();
262
+ done(data);
263
+ }, timeoutMs);
264
+ process.stdin.setEncoding("utf8");
265
+ process.stdin.on("data", (c) => {
266
+ data += c;
267
+ });
268
+ process.stdin.on("end", () => {
269
+ clearTimeout(t);
270
+ done(data);
271
+ });
272
+ process.stdin.on("error", () => {
273
+ clearTimeout(t);
274
+ done(data);
275
+ });
276
+ });
277
+ }
278
+ function take(args, flag) {
279
+ const i = args.indexOf(flag);
280
+ if (i < 0) return void 0;
281
+ const v = args[i + 1];
282
+ args.splice(i, 2);
283
+ return v;
284
+ }
285
+ function has(args, flag) {
286
+ const i = args.indexOf(flag);
287
+ if (i < 0) return false;
288
+ args.splice(i, 1);
289
+ return true;
290
+ }
291
+ var HOOK_USAGE = `usage: instruction-agents hook ${HOOK_HOST_IDS.join("|")}|auto [--event NAME] [--fail-closed] [--dir D] [--follow URI [--require-signature]] [--url U]`;
292
+ function hostOf(event, env) {
293
+ return appOf(event, env) === "codex" ? "codex" : "claude-code";
294
+ }
295
+ function appOf(event, env, hint) {
296
+ const has2 = (k) => typeof env[k] === "string" && env[k] !== "";
297
+ const path = typeof event.transcript_path === "string" ? event.transcript_path : "";
298
+ if (has2("QWEN_PROJECT_DIR") || has2("QWEN_SESSION_ID")) return "qwen-code";
299
+ if (has2("GEMINI_SESSION_ID") || has2("GEMINI_PROJECT_DIR") || has2("GEMINI_CLI")) return "gemini-cli";
300
+ if (has2("CURSOR_VERSION") || has2("CURSOR_TRACE_ID")) return "cursor";
301
+ if (has2("FACTORY_PROJECT_DIR")) return "droid";
302
+ if (has2("DEVIN_PROJECT_DIR")) return "devin";
303
+ if (has2("CRUSH_PROJECT_DIR")) return "crush";
304
+ if (has2("COPILOT_HOOK_DEPTH")) return "copilot";
305
+ if (has2("JUNIE_EXTENSION_ROOT")) return "junie";
306
+ if (typeof event.conversationId === "string") return "antigravity";
307
+ if (typeof event.hookName === "string") return "cline";
308
+ if (typeof event.event === "string" && event.hook_event_name === void 0) return "goose";
309
+ if (/[\\/]rollout-[^\\/]*\.jsonl$/.test(path) || typeof event.turn_id === "string") return "codex";
310
+ if (/[\\/]\.claude[\\/]projects[\\/]/.test(path) || has2("CLAUDE_PROJECT_DIR")) return "claude-code";
311
+ if (has2("PLUGIN_ROOT")) return "codex";
312
+ return hint ?? "claude-code";
313
+ }
314
+ async function cmdHook(args) {
315
+ const failClosed = has(args, "--fail-closed");
316
+ const requireSignature = has(args, "--require-signature");
317
+ const dir = take(args, "--dir");
318
+ const follow2 = take(args, "--follow");
319
+ const url = take(args, "--url");
320
+ const deadline = take(args, "--deadline");
321
+ const eventName = take(args, "--event");
322
+ const asked = args.shift();
323
+ if (!asked || !(HOOK_HOST_IDS.includes(asked) || asked === "auto")) {
324
+ console.error(HOOK_USAGE);
325
+ return 1;
326
+ }
327
+ let event = {};
328
+ try {
329
+ const raw = await readStdin();
330
+ event = raw.trim() ? JSON.parse(raw) : {};
331
+ } catch {
332
+ event = {};
333
+ }
334
+ const app = appOf(event, process.env, asked === "auto" ? void 0 : asked);
335
+ const own = PROFILES[app];
336
+ const host = asked !== "auto" ? asked : own && own.read(event, eventName).phase ? app : hostOf(event, process.env);
337
+ let client = null;
338
+ let connected = false;
339
+ const addressOf = (found) => url ?? found.config.url ?? process.env.INSTRUCTION_MD_URL ?? DEFAULT_URL;
340
+ const connection = async (found) => {
341
+ if (connected) return client;
342
+ connected = true;
343
+ const { registryConnection } = await import("instruction.md/cli/registry");
344
+ process.env.INSTRUCTION_MD_CLIENT_NAME ??= `instruction-md-cli hook (${app})`;
345
+ client = await registryConnection(["--url", addressOf(found)]).catch(() => null);
346
+ return client;
347
+ };
348
+ const reader = async (found) => {
349
+ const authorKeys = keysOf(found);
350
+ const policy = { ...found.config.requireSignature ? { requireSignature: true } : {}, ...authorKeys?.length ? { authorKeys } : {} };
351
+ const c = await connection(found);
352
+ return c ? followerReader(c.client, policy) : httpReader(addressOf(found), policy);
353
+ };
354
+ const report = async (cur, _sid, found) => {
355
+ const client2 = await connection(found);
356
+ if (!client2) return false;
357
+ const id = /^instruction:\/\/(ins_[0-9A-Z]{26})/i.exec(cur.canonical ?? "")?.[1];
358
+ if (!id) return false;
359
+ const c = client2.client;
360
+ const call = async (name, a) => await c.callTool({ name, arguments: a });
361
+ const withHost = async (name, a) => {
362
+ const refused = (r3) => r3.isError && /host/i.test(r3.content?.[0]?.text ?? "");
363
+ let r2 = await call(name, { ...a, host: app });
364
+ if (refused(r2) && app !== "other") r2 = await call(name, { ...a, host: "other" });
365
+ return refused(r2) ? call(name, a) : r2;
366
+ };
367
+ const selector = /@([^/?#]+)$/.exec(cur.uri)?.[1];
368
+ const target = selector && !/^(v\d+|ver_[0-9A-Z]+)$/i.test(selector) ? selector : void 0;
369
+ const consumer = { name: `instruction.md hook (${app}) on ${hostname()}`, kind: app, version };
370
+ const made = await withHost("instructions_bindings_create", { instructionId: id, mode: "follow", consumer, ...target ? { target } : {} });
371
+ const bindingId = made.structuredContent?.binding?.id;
372
+ if (made.isError || !bindingId) return false;
373
+ const r = await withHost("instructions_bindings_report", { bindingId, versionId: cur.versionId, deliveredDigest: cur.digest, client: { name: "instruction.md hook", version } });
374
+ return !r.isError;
375
+ };
376
+ try {
377
+ const take2 = async (deploymentId, found) => {
378
+ const c = await connection(found);
379
+ if (!c) return [];
380
+ const r = await c.client.callTool({ name: "deployments_messages_list", arguments: { deploymentId, take: true } });
381
+ if (r.isError) return [];
382
+ return (r.structuredContent?.entries ?? []).map((e) => ({ ...e.body?.text ? { text: e.body.text } : {}, ...e.body?.control ? { control: e.body.control } : {}, ...e.author?.name ? { by: e.author.name } : {} }));
383
+ };
384
+ const out = await runHostHook(host, event, { failClosed, ...dir ? { dir } : {}, ...follow2 ? { follow: follow2 } : {}, requireSignature, ...deadline ? { deadlineMs: Number(deadline) } : {}, ...eventName ? { event: eventName } : {}, reader, report, take: take2 });
385
+ if (typeof out === "string") process.stdout.write(out.endsWith("\n") ? out : `${out}
386
+ `);
387
+ else if (out) process.stdout.write(`${JSON.stringify(out)}
388
+ `);
389
+ } catch (e) {
390
+ console.error(`instruction-agents hook: ${e instanceof Error ? e.message : String(e)}`);
391
+ }
392
+ return 0;
393
+ }
394
+ export {
395
+ APPLY_NOTE,
396
+ HOOK_HOSTS,
397
+ HOOK_USAGE,
398
+ appOf,
399
+ claimGiven,
400
+ cmdHook,
401
+ follow,
402
+ hostOf,
403
+ pruneGiven,
404
+ runHook,
405
+ runHostHook
406
+ };
package/dist/hosts.js ADDED
@@ -0,0 +1,151 @@
1
+ // src/hosts.ts
2
+ var str = (v) => typeof v === "string" && v !== "" ? v : void 0;
3
+ var first = (v) => Array.isArray(v) ? str(v[0]) : void 0;
4
+ function phaseOf(events, e, flagEvent) {
5
+ const event = flagEvent ?? str(e.hook_event_name) ?? str(e.hookEventName) ?? str(e.hookName) ?? str(e.event) ?? str(e.eventName) ?? "";
6
+ return { event, phase: events[event] ?? null };
7
+ }
8
+ function readClaude(events) {
9
+ return (e, flagEvent) => {
10
+ const { event, phase } = phaseOf(events, e, flagEvent);
11
+ return { phase, event, session: str(e.session_id), source: str(e.source), cwd: str(e.cwd) };
12
+ };
13
+ }
14
+ function writeClaude(a, n) {
15
+ if (!a) return null;
16
+ if (a.stop) return { continue: false, stopReason: a.stop, systemMessage: a.stop };
17
+ if (a.block) return { decision: "block", reason: a.block };
18
+ const out = {};
19
+ if (a.notice) out.systemMessage = a.notice;
20
+ if (a.context) out.hookSpecificOutput = { hookEventName: n.event, additionalContext: a.context };
21
+ return Object.keys(out).length ? out : null;
22
+ }
23
+ var CLAUDE_EVENTS = { SessionStart: "start", SubagentStart: "subagent", UserPromptSubmit: "check", PostToolUse: "check", PostToolBatch: "check" };
24
+ function claudeLike(id, label, extra = {}, events = CLAUDE_EVENTS) {
25
+ return { id, label, events, read: readClaude(events), write: writeClaude, ...extra };
26
+ }
27
+ var PROFILES = {
28
+ "claude-code": claudeLike("claude-code", "Claude Code"),
29
+ codex: claudeLike("codex", "Codex"),
30
+ // (Qwen Code v0.28: Claude's names and answer; SessionStart's sources include compact; `<` `>` in a hook's context
31
+ // are escaped — packages/core/src/hooks/types.ts — so the blocks go without tags)
32
+ "qwen-code": claudeLike("qwen-code", "Qwen Code", { tagFree: true }),
33
+ // (Factory Droid 1.14: SessionStart (startup|resume|clear|compact) and UserPromptSubmit take hookSpecificOutput's
34
+ // additionalContext — docs.factory.ai/reference/hooks-reference)
35
+ droid: claudeLike("droid", "Factory Droid"),
36
+ // (Devin: SessionStart (startup|resume) and UserPromptSubmit take hookSpecificOutput's additionalContext; it reads
37
+ // .claude/settings.json's hooks too — research §3.6)
38
+ devin: claudeLike("devin", "Devin"),
39
+ // (Gemini CLI v0.69: Claude's answer under its own events — BeforeAgent after a prompt, AfterTool after a tool,
40
+ // PreCompress before compaction; SessionStart sources startup|resume|clear; `<` `>` escaped — types.ts)
41
+ "gemini-cli": claudeLike("gemini-cli", "Gemini CLI", { tagFree: true }, { SessionStart: "start", BeforeAgent: "check", AfterTool: "check", PreCompress: "reset" }),
42
+ // (Junie CLI, EAP: its SessionStart ignores context; PostToolUse takes hookSpecificOutput's additionalContext —
43
+ // research §3.13; UserPromptSubmit's context is undocumented, so it is answered as Claude Code's, harmless if ignored)
44
+ junie: claudeLike("junie", "Junie", { unverified: "UserPromptSubmit context undocumented; SessionStart ignores context" }, { PostToolUse: "check", UserPromptSubmit: "check" }),
45
+ // (Crush v0.101: context only on tool events; SessionStart and TurnStart are observe-only; Claude's payload and answer
46
+ // are accepted — docs/hooks/README.md "Claude Code compatibility")
47
+ crush: claudeLike("crush", "Crush", {}, { PreToolUse: "check", PostToolUse: "check", PostToolUseFailure: "check" }),
48
+ // GitHub Copilot CLI 1.0.114 (docs.github.com …/cli-hooks-reference, research §3.2): camelCase events with camelCase
49
+ // payloads (sessionId), PascalCase ones with VS Code's snake_case; a top-level `additionalContext`, consumed at
50
+ // sessionStart and postToolUse (joined across hooks, capped at 10 KB there); userPromptSubmitted's is disputed (the
51
+ // reference drops it, the changelog of 1.0.65/1.0.111 says it reaches the model): answered, harmless if dropped.
52
+ // preCompact is a notification: the session's record goes, so the next event gives the text whole.
53
+ copilot: {
54
+ id: "copilot",
55
+ label: "GitHub Copilot",
56
+ events: { sessionStart: "start", SessionStart: "start", subagentStart: "subagent", SubagentStart: "subagent", userPromptSubmitted: "check", UserPromptSubmit: "check", postToolUse: "check", PostToolUse: "check", preCompact: "reset", PreCompact: "reset" },
57
+ read(e, flagEvent) {
58
+ const { event, phase } = phaseOf(this.events, e, flagEvent);
59
+ return { phase, event, session: str(e.sessionId) ?? str(e.session_id), source: str(e.source), cwd: str(e.cwd) };
60
+ },
61
+ write: (a) => a?.context ? { additionalContext: a.context } : null,
62
+ // (10 KB at postToolUse, in bytes: room kept for text that isn't ASCII)
63
+ maxChars: (n) => /^post/i.test(n.event) ? 7e3 : void 0,
64
+ unverified: "userPromptSubmitted additionalContext disputed (reference vs changelog)"
65
+ },
66
+ // Cursor 2026.11.13 (cursor.com/docs/hooks, research §3.7): `{"version":1,"hooks":{…}}`; conversation_id is the
67
+ // session; `additional_context` at sessionStart and postToolUse. Forum reports say neither reaches the model in some
68
+ // builds (sessionStart runs before the composer exists), so `watch --out .cursor/rules/instruction-md.mdc --rule` is
69
+ // the start path that doesn't depend on it.
70
+ cursor: {
71
+ id: "cursor",
72
+ label: "Cursor",
73
+ events: { sessionStart: "start", postToolUse: "check", postToolUseFailure: "check", preCompact: "reset" },
74
+ read(e, flagEvent) {
75
+ const { event, phase } = phaseOf(this.events, e, flagEvent);
76
+ return { phase, event, session: str(e.conversation_id) ?? str(e.session_id), source: str(e.source), cwd: first(e.workspace_roots) ?? str(e.cwd) };
77
+ },
78
+ write: (a) => a?.context ? { additional_context: a.context } : null,
79
+ unverified: "additional_context reported not to reach the model in some builds (forum)"
80
+ },
81
+ // Antigravity (antigravity.google/docs/hooks, research §3.3): `.agents/hooks.json` keyed by a hook's name;
82
+ // PreInvocation fires before every model call; camelCase input (conversationId, workspacePaths); the answer
83
+ // `injectSteps: [{systemMessage: {systemMessage}}]`, an out-of-band system instruction. Whether stdin names the event
84
+ // is unverified: the command names it (`--event`).
85
+ antigravity: {
86
+ id: "antigravity",
87
+ label: "Antigravity",
88
+ events: { SessionStart: "start", PreInvocation: "check" },
89
+ read(e, flagEvent) {
90
+ const { event, phase } = phaseOf(this.events, e, flagEvent);
91
+ return { phase, event, session: str(e.conversationId) ?? str(e.sessionId) ?? str(e.session_id), cwd: first(e.workspacePaths) ?? str(e.cwd) };
92
+ },
93
+ write: (a) => a?.context ? { injectSteps: [{ systemMessage: { systemMessage: a.context } }] } : null,
94
+ unverified: "injectSteps shape from the docs; stdin's event name"
95
+ },
96
+ // Kiro (kiro.dev/docs/hooks, research §3.9): a command action's stdout, exit 0, is added to the agent's context at
97
+ // SessionStart (agentSpawn) and Prompt Submit: plain text, nothing at all when there is nothing to add. What its stdin
98
+ // carries is unverified: the command names the event (`--event`).
99
+ kiro: {
100
+ id: "kiro",
101
+ label: "Kiro",
102
+ events: { SessionStart: "start", agentSpawn: "start", PromptSubmit: "check", UserPromptSubmit: "check", userPromptSubmit: "check" },
103
+ read(e, flagEvent) {
104
+ const { event, phase } = phaseOf(this.events, e, flagEvent);
105
+ return { phase, event, session: str(e.session_id) ?? str(e.sessionId) ?? str(e.conversationId), cwd: str(e.cwd) };
106
+ },
107
+ write: (a) => a?.context ? a.context : null,
108
+ unverified: "stdin fields; hook file keys"
109
+ },
110
+ // Cline v4.1.26 (.clinerules/hooks/README.md): executables named after the event in .clinerules/hooks/; stdin hookName,
111
+ // taskId, workspaceRoots; every hook answers `{cancel, contextModification?, errorMessage?}` (up to 50 KB).
112
+ cline: {
113
+ id: "cline",
114
+ label: "Cline",
115
+ events: { TaskStart: "start", TaskResume: "start", UserPromptSubmit: "check", PostToolUse: "check", PreCompact: "reset" },
116
+ read(e, flagEvent) {
117
+ const { event, phase } = phaseOf(this.events, e, flagEvent);
118
+ return { phase, event, session: str(e.taskId), source: event === "TaskResume" ? "resume" : void 0, cwd: first(e.workspaceRoots) };
119
+ },
120
+ write: (a) => a?.block || a?.stop ? { cancel: true, errorMessage: a.block ?? a.stop } : a?.context ? { cancel: false, contextModification: a.context } : { cancel: false }
121
+ },
122
+ // Goose 1.60 (research §3.12): its hooks observe and can't add context; GOOSE_MOIM_MESSAGE_FILE re-reads a file every
123
+ // turn. The hook, run by our plugin as an Open Plugin, keeps .instruction/current.md fresh and says nothing.
124
+ goose: {
125
+ id: "goose",
126
+ label: "Goose",
127
+ events: {},
128
+ read(e, flagEvent) {
129
+ const event = flagEvent ?? str(e.event) ?? "";
130
+ return { phase: "refresh", event, session: str(e.session_id), cwd: str(e.cwd) };
131
+ },
132
+ write: () => null
133
+ }
134
+ };
135
+ var HOOK_HOST_IDS = Object.keys(PROFILES);
136
+ function untag(block) {
137
+ const attrs = (s) => Object.fromEntries([...s.matchAll(/([a-z]+)="([^"]*)"/g)].map((m) => [m[1], m[2].replace(/&quot;/g, '"').replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&")]));
138
+ return block.replace(/^<instruction-update ([^>]*)>$/m, (_, s) => {
139
+ const a = attrs(s);
140
+ return `--- instruction ${a.uri ?? ""}: ${a.from ?? "?"} → ${a.to ?? "?"} (${a.digest ?? ""}) ---`;
141
+ }).replace(/^<instruction ([^>]*)>$/m, (_, s) => {
142
+ const a = attrs(s);
143
+ return `--- instruction ${a.uri ?? ""} ${a.version ?? ""} (${a.digest ?? ""}) ---`;
144
+ }).replace(/^<\/instruction(-update)?>$/m, "--- end of the instruction ---");
145
+ }
146
+ export {
147
+ HOOK_HOST_IDS,
148
+ PROFILES,
149
+ untag,
150
+ writeClaude
151
+ };