@conveno/cli 0.2.0-rc.8 → 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.
Files changed (32) hide show
  1. package/README.md +3 -5
  2. package/dist/{acp-YHhVx0Ya.js → acp-BUddItzP.js} +39 -7
  3. package/dist/{agy-relay-BS2NeFlh.js → agy-relay-BZ3d_-FS.js} +4 -2
  4. package/dist/{args-CGL-AmNd.js → args-CtyKPZuN.js} +29 -8
  5. package/dist/bin.js +16 -2
  6. package/dist/daemon.js +4 -3139
  7. package/dist/{daemonError-DJ-P55nH.js → daemonError-CDgEtvy7.js} +1 -1
  8. package/dist/dist-BNhTPp5p.js +4509 -0
  9. package/dist/{dist-BRjg9CLd.js → dist-BOwFdixw.js} +23 -50
  10. package/dist/{dist-CcoTmwrf.js → dist-CFsDqevs.js} +94 -56
  11. package/dist/dist-CNdqmI3E.js +1065 -0
  12. package/dist/{dist-BBdba94T.js → dist-CSSvrcKr.js} +1752 -708
  13. package/dist/{dist-B6Sm0MRT.js → dist-D6Xoip5W.js} +203 -62
  14. package/dist/{dist-WTkKRM39.js → dist-DAVtixeC.js} +19 -5
  15. package/dist/dist-DTMnNySx.js +989 -0
  16. package/dist/hook-BA-tI6Oc.js +208 -0
  17. package/dist/hook-entry-BwzBtAnd.js +1346 -0
  18. package/dist/hook-entry-Cgt5ZH1s.js +1 -0
  19. package/dist/{main-DrzHsV5y.js → main-kKnLA7Hj.js} +58 -21
  20. package/dist/{pick-Bi1yJDh6.js → pick-BsMvXuDo.js} +1 -1
  21. package/dist/run-PQBzaHv1.js +8193 -0
  22. package/dist/{runtime-Db_YT5Xg.js → runtime-0FMqklYn.js} +233 -122
  23. package/dist/{uninstall-D9rW_j7H.js → uninstall-DcxkIDpk.js} +556 -82
  24. package/dist/{watch-BrTWYf3Y.js → watch-BIepRTXJ.js} +29 -7
  25. package/package.json +14 -15
  26. package/dist/dist-B1EVHdIM.js +0 -504
  27. package/dist/dist-BlWWt5gx.js +0 -624
  28. package/dist/dist-C6cMQ00I.js +0 -793
  29. package/dist/hook-DxjJDCjz.js +0 -94
  30. package/dist/hook-entry-CrpZz5QW.js +0 -1
  31. package/dist/hook-entry-pHJioNgN.js +0 -2494
  32. package/dist/run-C32oP2c_.js +0 -5550
@@ -0,0 +1,208 @@
1
+ import { appendFileSync } from "node:fs";
2
+ import { ut as hookLogLine, w as appendHookLog } from "./dist-CSSvrcKr.js";
3
+ import { n as connectOpts } from "./ctx-tYftvhz_.js";
4
+ // src/hook.ts
5
+ /**
6
+ * Time allowed for the hook's own process-table query. Only the fallback runs it: the usual way to
7
+ * find the host CLI is to ask the daemon (`session.hostOf`). When the query fails or runs out, the
8
+ * hook falls back to its direct parent as the host.
9
+ */
10
+ const HOOK_ANCESTRY_TIMEOUT_MS = 1200;
11
+ const NOTHING = {
12
+ stdout: "",
13
+ exitCode: 0
14
+ };
15
+ /**
16
+ * The pid of the CLI that runs this hook, or undefined when there is nothing to deliver to.
17
+ * The daemon walks the process chain (it keeps a warm query helper on Windows) and answers at once
18
+ * when no session of this CLI is online, so the hook reads no process table in either case. When
19
+ * the daemon cannot answer (an older daemon, a table it may not read), the hook reads the table
20
+ * itself, as it always did, and `complete: false` keeps the direct-parent fallback.
21
+ */
22
+ async function findHostPid(ctx, client, cli, local) {
23
+ if (ctx.hostLookup) {
24
+ const { ppid, launcherPaths } = ctx.hostLookup;
25
+ const r = await client["session.hostOf"]({
26
+ cli,
27
+ ppid,
28
+ launcherPaths
29
+ }).catch(() => void 0);
30
+ if (r && !r.online) return void 0;
31
+ if (r?.complete) return r.hostPid;
32
+ }
33
+ return (await local()).hostPid;
34
+ }
35
+ /**
36
+ * One line of the timing log: `<iso time> cli=<cli> event=<event> ms=<n> proc_ms=<n> timeout=<yes|no>`.
37
+ * `ms` is the time inside `runHook`; `proc_ms` also counts process start-up (what the CLI's own
38
+ * hook limit sees). `timeout=yes` means the hook ran past its limit and was cut off.
39
+ */
40
+ function timingLine(cli, event, ms, procMs, timedOut) {
41
+ return `${(/* @__PURE__ */ new Date()).toISOString()} cli=${cli} event=${event} ms=${ms}${procMs === void 0 ? "" : ` proc_ms=${procMs}`} timeout=${timedOut ? "yes" : "no"}\n`;
42
+ }
43
+ /**
44
+ * The client with its answers noted in `trace`: the session a lookup resolved to, the messages
45
+ * handed over, the turn state recorded. The hook sees the same client.
46
+ */
47
+ function traced(client, trace) {
48
+ return new Proxy(client, { get(target, prop, receiver) {
49
+ const value = Reflect.get(target, prop, receiver);
50
+ if (typeof prop !== "string" || !prop.includes(".") || typeof value !== "function") return value;
51
+ return async (...args) => {
52
+ let r;
53
+ try {
54
+ r = await value.apply(target, args);
55
+ } catch (e) {
56
+ const code = e?.code;
57
+ trace.error = `error ${typeof code === "number" || typeof code === "string" ? code : "unknown"}`;
58
+ throw e;
59
+ }
60
+ const out = r;
61
+ const count = Array.isArray(out?.messages) ? out.messages.length : 0;
62
+ if ((prop === "session.bind" || prop === "session.byHost") && out?.session?.name) trace.session = out.session.name;
63
+ else if (prop === "turn.start") trace.turn = "busy";
64
+ else if (prop === "turn.end") {
65
+ trace.delivered += count;
66
+ trace.turn = count > 0 ? "busy" : "idle";
67
+ } else if (prop === "message.deliver" || prop === "turn.wake") trace.delivered += count;
68
+ return r;
69
+ };
70
+ } });
71
+ }
72
+ /** The CLI's own conversation id in a hook's input, whichever way that CLI spells it. */
73
+ function conversationIn(input) {
74
+ if (typeof input !== "object" || input === null) return void 0;
75
+ const o = input;
76
+ for (const key of [
77
+ "session_id",
78
+ "sessionId",
79
+ "sessionID",
80
+ "conversationId"
81
+ ]) {
82
+ const v = o[key];
83
+ if (typeof v === "string" && v !== "") return v;
84
+ }
85
+ }
86
+ /** After a timeout, the hook gets this many more timeouts' worth of time to finish recording. */
87
+ const FINISH_GRACE_FACTOR = 2;
88
+ /**
89
+ * Every CLI kills a hook 5 s after it starts (`HOOK_TIMEOUT_SECONDS` in each adapter). The budget
90
+ * and the finish grace together stay under this, so the process ends by itself with its outcome
91
+ * logged instead of being killed mid-write. The rest is left for process start-up.
92
+ */
93
+ const HOOK_TOTAL_MAX_MS = 4800;
94
+ /** How long a timed-out hook may keep running to record its turn: capped so budget + grace fits. */
95
+ const finishGraceMs = (timeoutMs) => Math.max(0, Math.min(timeoutMs * FINISH_GRACE_FACTOR, HOOK_TOTAL_MAX_MS - timeoutMs));
96
+ /** How long before the hook's timeout its messages count as too late to print. */
97
+ const DEADLINE_MARGIN_MS = 300;
98
+ /**
99
+ * `conveno hook <cli> <event>`: reads the CLI's hook JSON on stdin and prints what the adapter
100
+ * returns. Never starts a daemon. A hook that fails or stalls must not hold the CLI up, so an
101
+ * ordinary hook gives up after the context's timeout (2 s), never writes to stderr and exits 0.
102
+ *
103
+ * Listener events (the adapter's `listenEvents`) are the exception: they run in the background,
104
+ * wait without the 2 s budget until a message arrives or their CLI goes away, and may exit 2 with
105
+ * the message on stderr (Claude Code's `asyncRewake`). They stop on their own when the host CLI
106
+ * exits, the session goes offline, or a newer listener replaces them.
107
+ */
108
+ async function runHook(ctx, argv) {
109
+ const [cli, event] = argv;
110
+ const adapter = ctx.adapters.find((a) => a.cli === cli);
111
+ if (!adapter || !event) return 0;
112
+ const listener = adapter.listenEvents?.includes(event) === true;
113
+ const deadline = listener ? void 0 : Date.now() + ctx.hookTimeoutMs - DEADLINE_MARGIN_MS;
114
+ const started = Date.now();
115
+ const t0 = ctx.timingLog && !listener ? started : void 0;
116
+ const trace = { delivered: 0 };
117
+ let conversation;
118
+ let timedOut = false;
119
+ let workDone = false;
120
+ let hostMs;
121
+ let hostResolved = false;
122
+ let hostMissing = false;
123
+ let client;
124
+ let timer;
125
+ const early = ctx.hostLookup ? void 0 : ctx.ancestry(HOOK_ANCESTRY_TIMEOUT_MS);
126
+ const work = (async () => {
127
+ const readInput = async () => {
128
+ try {
129
+ const raw = await ctx.readStdin();
130
+ return raw.trim() === "" ? {} : JSON.parse(raw);
131
+ } catch {
132
+ return {};
133
+ }
134
+ };
135
+ const [input, connected] = await Promise.all([readInput(), ctx.connect(connectOpts(ctx, false))]);
136
+ client = ctx.hookLog ? traced(connected, trace) : connected;
137
+ if (ctx.hookLog) conversation = conversationIn(input);
138
+ let hostPid;
139
+ const resolveHostPid = () => {
140
+ hostPid ??= (async () => {
141
+ const t = Date.now();
142
+ try {
143
+ const pid = await findHostPid(ctx, connected, adapter.cli, () => early ?? ctx.ancestry(HOOK_ANCESTRY_TIMEOUT_MS));
144
+ if (pid === void 0) hostMissing = true;
145
+ return pid;
146
+ } finally {
147
+ hostMs = Date.now() - t;
148
+ hostResolved = true;
149
+ }
150
+ })();
151
+ return hostPid;
152
+ };
153
+ const out = await adapter.hook(event, input, {
154
+ client,
155
+ resolveHostPid,
156
+ ...ctx.hostLookup ? { ppid: ctx.hostLookup.ppid } : {},
157
+ cli: adapter.cli,
158
+ isAlive: ctx.isAlive,
159
+ ...deadline === void 0 ? {} : { deadline }
160
+ });
161
+ if (hostResolved && hostMissing) await adapter.hookWithoutSession?.(event, input).catch(() => {});
162
+ return out;
163
+ })();
164
+ work.then(() => {
165
+ workDone = true;
166
+ }, () => {
167
+ workDone = true;
168
+ });
169
+ const timeout = listener ? new Promise(() => void 0) : new Promise((resolve) => {
170
+ timer = setTimeout(() => {
171
+ timedOut = true;
172
+ resolve(NOTHING);
173
+ }, ctx.hookTimeoutMs);
174
+ });
175
+ let code = 0;
176
+ try {
177
+ const out = await Promise.race([work, timeout]);
178
+ if (out === NOTHING && !listener) await Promise.race([work.catch(() => void 0), new Promise((r) => setTimeout(r, finishGraceMs(ctx.hookTimeoutMs)))]);
179
+ if (out.stdout) ctx.out(out.stdout.endsWith("\n") ? out.stdout : `${out.stdout}\n`);
180
+ if (listener && out.stderr) ctx.err(out.stderr.endsWith("\n") ? out.stderr : `${out.stderr}\n`);
181
+ if (listener) code = out.exitCode;
182
+ } catch {} finally {
183
+ if (ctx.hookLog) {
184
+ const done = trace.error ?? (trace.delivered > 0 ? `delivered ${trace.delivered}` : trace.turn ?? "nothing");
185
+ const result = timedOut ? workDone ? `${done} late` : "timeout" : done;
186
+ appendHookLog(ctx.hookLog, hookLogLine({
187
+ cli: adapter.cli,
188
+ event,
189
+ conversationId: conversation,
190
+ session: trace.session,
191
+ result,
192
+ hostMs,
193
+ ms: Date.now() - started
194
+ }));
195
+ }
196
+ if (t0 !== void 0 && ctx.timingLog) {
197
+ const up = ctx.uptimeMs?.();
198
+ try {
199
+ appendFileSync(ctx.timingLog, timingLine(adapter.cli, event, Date.now() - t0, up === void 0 ? void 0 : Math.round(up), timedOut));
200
+ } catch {}
201
+ }
202
+ if (timer) clearTimeout(timer);
203
+ work.catch(() => void 0);
204
+ await Promise.race([client?.close().catch(() => void 0), new Promise((r) => setTimeout(r, 100))]);
205
+ }
206
+ return code;
207
+ }
208
+ export { runHook as t };