@conveno/cli 0.2.0-rc.9 → 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/README.md +3 -5
- package/dist/{acp-BVk6rmXR.js → acp-BUddItzP.js} +39 -7
- package/dist/{agy-relay-D8eZcLuc.js → agy-relay-BZ3d_-FS.js} +4 -2
- package/dist/{args-B3Cj2Ie4.js → args-CtyKPZuN.js} +29 -8
- package/dist/bin.js +16 -2
- package/dist/daemon.js +4 -3139
- package/dist/{daemonError-C05GqdhQ.js → daemonError-CDgEtvy7.js} +1 -1
- package/dist/dist-BNhTPp5p.js +4509 -0
- package/dist/{dist-BRjg9CLd.js → dist-BOwFdixw.js} +23 -50
- package/dist/{dist-DaIpdMke.js → dist-CFsDqevs.js} +51 -9
- package/dist/dist-CNdqmI3E.js +1065 -0
- package/dist/{dist-STNJjbNH.js → dist-CSSvrcKr.js} +1516 -599
- package/dist/{dist-BjdBeCHy.js → dist-D6Xoip5W.js} +63 -17
- package/dist/{dist-D_O_JLLq.js → dist-DAVtixeC.js} +19 -5
- package/dist/{dist-MK-cK1JY.js → dist-DTMnNySx.js} +39 -19
- package/dist/{hook-CDF1A8AY.js → hook-BA-tI6Oc.js} +101 -7
- package/dist/hook-entry-BwzBtAnd.js +1346 -0
- package/dist/hook-entry-Cgt5ZH1s.js +1 -0
- package/dist/{main-Kv31Qxro.js → main-kKnLA7Hj.js} +58 -21
- package/dist/{pick-DLp6w_-z.js → pick-BsMvXuDo.js} +1 -1
- package/dist/run-PQBzaHv1.js +8193 -0
- package/dist/{runtime-xjPzIGmp.js → runtime-0FMqklYn.js} +171 -119
- package/dist/{uninstall-8AHErPRN.js → uninstall-DcxkIDpk.js} +356 -56
- package/dist/{watch-D0KIPowJ.js → watch-BIepRTXJ.js} +29 -7
- package/package.json +14 -15
- package/dist/dist-CVdpCNJo.js +0 -793
- package/dist/dist-DzpERiRx.js +0 -624
- package/dist/hook-entry-BTJK7aO0.js +0 -2500
- package/dist/hook-entry-D6zup0QV.js +0 -1
- package/dist/run-BPtFUGtu.js +0 -5609
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { readFile, readdir } from "node:fs/promises";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
-
import { $
|
|
3
|
+
import { $ as endTurnContinuation, At as needsQuoting, C as agentCommand, E as askedMarker, G as dataDir, Nt as ownSession, On as uninstallLauncher, Pt as parseCliVersion, Ut as planLauncher, X as dropFromList, Z as editJson, gt as isObject, hn as sameJson, tt as existedBefore, wt as loadJson, yt as late, z as compareVersions, zt as pendingHookContext } from "./dist-CSSvrcKr.js";
|
|
4
4
|
// ../adapters/antigravity/dist/index.js
|
|
5
5
|
const SERVER_NAME = "conveno";
|
|
6
6
|
/** The name of our entry in hooks.json. Antigravity keys hooks by an arbitrary name. */
|
|
@@ -345,13 +345,13 @@ async function plan(env, opts = {}) {
|
|
|
345
345
|
});
|
|
346
346
|
const setFile = await loadJson(p.settings);
|
|
347
347
|
const allow = allowList(setFile.value, p.settings);
|
|
348
|
-
const hasRule = allow?.includes(
|
|
348
|
+
const hasRule = allow?.includes(PERMISSION_RULE) ?? false;
|
|
349
349
|
const relay = relayRule(env);
|
|
350
350
|
const hadRelay = allow?.includes(relay) ?? false;
|
|
351
351
|
const known = await relayRuleKnown(env);
|
|
352
352
|
const others = otherRelayRules(env);
|
|
353
353
|
const hadOther = allow?.some((r) => typeof r === "string" && others.has(r)) ?? false;
|
|
354
|
-
const wantRelay = known === void 0 ? hadRelay : (opts.accept?.includes(
|
|
354
|
+
const wantRelay = known === void 0 ? hadRelay : (opts.accept?.includes(RELAY_OPTION) === true || hadRelay || hadOther) && known;
|
|
355
355
|
const stale = dropFromList(allow, ["permissions", "allow"], (r) => known !== void 0 && isOurRelayRule(r) && !(wantRelay && r === relay), { keepEmpty: true });
|
|
356
356
|
const missing = [...hasRule ? [] : [PERMISSION_RULE], ...wantRelay && !hadRelay ? [relay] : []];
|
|
357
357
|
if (missing.length > 0 || stale.length > 0) {
|
|
@@ -407,7 +407,7 @@ async function plan(env, opts = {}) {
|
|
|
407
407
|
before: setFile.raw,
|
|
408
408
|
after: editJson(setFile, ruleEdits),
|
|
409
409
|
description: [
|
|
410
|
-
missing.includes(
|
|
410
|
+
missing.includes(PERMISSION_RULE) ? `Allow the agent to call Conveno's tools (${PERMISSION_RULE}) without asking. They only exchange messages between your own sessions.` : void 0,
|
|
411
411
|
addsRelay ? `Allow the agent to start Conveno's relay (${relay}) without asking, so it can wake an idle conversation.` : void 0,
|
|
412
412
|
stale.length > 0 ? "Remove the old rule that started Conveno's relay without asking." : void 0
|
|
413
413
|
].filter(Boolean).join(" ")
|
|
@@ -513,7 +513,7 @@ async function uninstallPlan(env, baseline) {
|
|
|
513
513
|
description: `Remove the "${SERVER_NAME}" MCP server.`
|
|
514
514
|
});
|
|
515
515
|
const setFile = await loadJson(p.settings);
|
|
516
|
-
const drops = dropFromList(allowList(setFile.value, p.settings), ["permissions", "allow"], (r) => r ===
|
|
516
|
+
const drops = dropFromList(allowList(setFile.value, p.settings), ["permissions", "allow"], (r) => r === PERMISSION_RULE || isOurRelayRule(r), { keepEmpty: existedBefore(baseline?.get(p.settings), ["permissions", "allow"]) });
|
|
517
517
|
if (drops.length > 0) {
|
|
518
518
|
const alone = drops.length === 1 && drops[0]?.path.length === 2;
|
|
519
519
|
const only = Object.keys(setFile.value.permissions).length === 1 && !existedBefore(baseline?.get(p.settings), ["permissions"]);
|
|
@@ -554,23 +554,63 @@ async function uninstallPlan(env, baseline) {
|
|
|
554
554
|
}
|
|
555
555
|
const UUID = /^[0-9a-fA-F-]{8,64}$/;
|
|
556
556
|
/**
|
|
557
|
-
* The
|
|
558
|
-
* (`session.
|
|
559
|
-
*
|
|
557
|
+
* The hook's context with its conversation id, which the daemon binds to the window's session
|
|
558
|
+
* (`session.bind`): that is how `conveno agy-relay` finds its session, and the window's session
|
|
559
|
+
* follows `/new` and `/resume`. A session start or a model call may move the window to the
|
|
560
|
+
* conversation; a Stop of any other conversation than the current one is ignored.
|
|
560
561
|
*/
|
|
561
|
-
|
|
562
|
+
function withConversation(input, ctx, turnStart) {
|
|
563
|
+
const id = isObject(input) ? input.conversationId : void 0;
|
|
564
|
+
if (typeof id !== "string" || !UUID.test(id)) return ctx;
|
|
565
|
+
return {
|
|
566
|
+
...ctx,
|
|
567
|
+
cli: ctx.cli ?? "antigravity",
|
|
568
|
+
nativeId: id,
|
|
569
|
+
turnStart
|
|
570
|
+
};
|
|
571
|
+
}
|
|
572
|
+
/** The session that owns this hook, or null when none does or on any failure. Never throws. */
|
|
573
|
+
async function sessionOf(ctx) {
|
|
562
574
|
try {
|
|
563
|
-
|
|
564
|
-
const id = isObject(input) ? input.conversationId : void 0;
|
|
565
|
-
if (!session || typeof id !== "string" || !UUID.test(id) || session.nativeId === id) return session;
|
|
566
|
-
return (await ctx.client["session.setNative"]({
|
|
567
|
-
sessionId: session.id,
|
|
568
|
-
nativeId: id
|
|
569
|
-
})).session;
|
|
575
|
+
return await ownSession(ctx);
|
|
570
576
|
} catch {
|
|
571
577
|
return null;
|
|
572
578
|
}
|
|
573
579
|
}
|
|
580
|
+
/** The folder the hook says the agent works in: the first of `workspacePaths`, else `cwd`. */
|
|
581
|
+
function workspaceOf(input) {
|
|
582
|
+
if (!isObject(input)) return void 0;
|
|
583
|
+
const paths = input.workspacePaths;
|
|
584
|
+
const first = Array.isArray(paths) ? paths[0] : void 0;
|
|
585
|
+
const dir = typeof first === "string" && first !== "" ? first : input.cwd;
|
|
586
|
+
return typeof dir === "string" && dir !== "" ? dir : void 0;
|
|
587
|
+
}
|
|
588
|
+
/**
|
|
589
|
+
* Is the transcript in the Antigravity desktop app's product folder (`antigravity/`), not the CLI's
|
|
590
|
+
* (`antigravity-cli/`) or the IDE's (`antigravity-ide/`)? A second signal next to the process chain.
|
|
591
|
+
*/
|
|
592
|
+
function appTranscript(input) {
|
|
593
|
+
const t = isObject(input) ? input.transcriptPath : void 0;
|
|
594
|
+
return typeof t === "string" && t.split(/[\\/]/).includes("antigravity");
|
|
595
|
+
}
|
|
596
|
+
/**
|
|
597
|
+
* The desktop app starts Conveno in its install folder; a hook knows the workspace. Tell the daemon
|
|
598
|
+
* when an app session works elsewhere, and the row moves there. A CLI row is never sent: it already
|
|
599
|
+
* runs in the folder the user opened. Never throws.
|
|
600
|
+
*/
|
|
601
|
+
async function followWorkspace(input, ctx, session) {
|
|
602
|
+
const app = session.variant === "app" || appTranscript(input);
|
|
603
|
+
const dir = workspaceOf(input);
|
|
604
|
+
if (!app || dir === void 0) return;
|
|
605
|
+
if (session.variant === "app" && dir === session.cwd) return;
|
|
606
|
+
try {
|
|
607
|
+
await ctx.client["session.setCwd"]({
|
|
608
|
+
sessionId: session.id,
|
|
609
|
+
cwd: dir,
|
|
610
|
+
...session.variant === "app" ? {} : { variant: "app" }
|
|
611
|
+
});
|
|
612
|
+
} catch {}
|
|
613
|
+
}
|
|
574
614
|
/** What the Stop hook asks once per turn while no relay is connected. */
|
|
575
615
|
/** The relay request is asked once per Conveno session (a one-shot `agy -p` run counts each retry as a new turn). */
|
|
576
616
|
const relayAsk = askedMarker("agy-relay-asked");
|
|
@@ -592,7 +632,9 @@ const isHookEvent = (e) => HOOK_EVENTS.includes(e);
|
|
|
592
632
|
*/
|
|
593
633
|
async function hook(event, input, ctx) {
|
|
594
634
|
if (!isHookEvent(event)) return EMPTY;
|
|
595
|
-
|
|
635
|
+
ctx = withConversation(input, ctx, event !== "Stop");
|
|
636
|
+
const session = await sessionOf(ctx);
|
|
637
|
+
if (session !== null) await followWorkspace(input, ctx, session);
|
|
596
638
|
if (event === "Stop") {
|
|
597
639
|
const stop = isObject(input) ? input : {};
|
|
598
640
|
const completed = (stop.terminationReason === void 0 || stop.terminationReason === "NO_TOOL_CALL") && (stop.error === void 0 || stop.error === "");
|
|
@@ -617,6 +659,9 @@ async function hook(event, input, ctx) {
|
|
|
617
659
|
exitCode: 0
|
|
618
660
|
};
|
|
619
661
|
}
|
|
662
|
+
if (event === "PreInvocation" && session !== null && session.status !== "busy") try {
|
|
663
|
+
await ctx.client["turn.start"]({ sessionId: session.id });
|
|
664
|
+
} catch {}
|
|
620
665
|
const text = await pendingHookContext(ctx);
|
|
621
666
|
if (text === null) return EMPTY;
|
|
622
667
|
return {
|
|
@@ -636,6 +681,7 @@ const antigravityAdapter = {
|
|
|
636
681
|
detect,
|
|
637
682
|
plan,
|
|
638
683
|
optional: [relayOption],
|
|
684
|
+
doctorNotes: async () => ["The Antigravity app shares the CLI's settings, so Conveno is set up in both. App sessions show as \"Antigravity app\"."],
|
|
639
685
|
uninstallPlan,
|
|
640
686
|
hook
|
|
641
687
|
};
|
|
@@ -3,7 +3,7 @@ import { mkdir, open, readFile, rm, stat } from "node:fs/promises";
|
|
|
3
3
|
import { createConnection } from "node:net";
|
|
4
4
|
import { homedir } from "node:os";
|
|
5
5
|
import { dirname, join } from "node:path";
|
|
6
|
-
import {
|
|
6
|
+
import { G as dataDir, Jn as PROTOCOL_VERSION, K as dataPaths, Qn as RpcResponse, R as clientProof, W as daemonProof, Wn as EventPayload, Zn as RpcErrorCode, _r as socketPathTooLongMessage, a as ConvenoError, ar as ipcMethods, ir as encodeFrame, jt as newAuthNonce, nr as createLineDecoder, or as isSocketPathTooLong, qt as proofsMatch, rr as defaultSocketPath } from "./dist-CSSvrcKr.js";
|
|
7
7
|
// ../client/dist/index.js
|
|
8
8
|
const DEFAULT_REQUEST_TIMEOUT_MS = 5e3;
|
|
9
9
|
const DEFAULT_START_TIMEOUT_MS = 1e4;
|
|
@@ -12,11 +12,13 @@ const CLIENT_METHODS = [
|
|
|
12
12
|
"session.register",
|
|
13
13
|
"session.heartbeat",
|
|
14
14
|
"session.unregister",
|
|
15
|
+
"session.remove",
|
|
15
16
|
"session.rename",
|
|
16
17
|
"session.setStatus",
|
|
17
18
|
"session.byHost",
|
|
18
19
|
"session.hostOf",
|
|
19
20
|
"session.setNative",
|
|
21
|
+
"session.bind",
|
|
20
22
|
"turn.start",
|
|
21
23
|
"turn.end",
|
|
22
24
|
"turn.wake",
|
|
@@ -24,11 +26,14 @@ const CLIENT_METHODS = [
|
|
|
24
26
|
"session.list",
|
|
25
27
|
"orchestrator.claim",
|
|
26
28
|
"orchestrator.clear",
|
|
29
|
+
"permission.ask",
|
|
30
|
+
"permission.answer",
|
|
27
31
|
"message.send",
|
|
28
32
|
"message.inbox",
|
|
29
33
|
"message.deliver",
|
|
30
34
|
"message.ack",
|
|
31
35
|
"message.requeue",
|
|
36
|
+
"message.recent",
|
|
32
37
|
"owner.send",
|
|
33
38
|
"events.subscribe",
|
|
34
39
|
"relay.status",
|
|
@@ -52,6 +57,7 @@ const NOT_REPLAYABLE = /* @__PURE__ */ new Set([
|
|
|
52
57
|
"daemon.shutdown",
|
|
53
58
|
"turn.end",
|
|
54
59
|
"turn.wake",
|
|
60
|
+
"permission.ask",
|
|
55
61
|
"devices.pair",
|
|
56
62
|
"devices.pairConfirm",
|
|
57
63
|
"devices.revoke",
|
|
@@ -146,6 +152,8 @@ var Connection = class {
|
|
|
146
152
|
pending = /* @__PURE__ */ new Map();
|
|
147
153
|
decoder = createLineDecoder();
|
|
148
154
|
closed = false;
|
|
155
|
+
/** The daemon's version, from its `hello` answer. */
|
|
156
|
+
daemonVersion;
|
|
149
157
|
constructor(socket, timeoutMs, onEvent = () => {}) {
|
|
150
158
|
this.socket = socket;
|
|
151
159
|
this.timeoutMs = timeoutMs;
|
|
@@ -182,14 +190,14 @@ var Connection = class {
|
|
|
182
190
|
p.reject(e);
|
|
183
191
|
}
|
|
184
192
|
}
|
|
185
|
-
call(method, params) {
|
|
193
|
+
call(method, params, timeoutMs = this.timeoutMs) {
|
|
186
194
|
if (this.closed) return Promise.reject(new ConnectionLost("Connection to the Conveno daemon is closed.", false));
|
|
187
195
|
const id = this.nextId++;
|
|
188
196
|
return new Promise((resolve, reject) => {
|
|
189
197
|
const timer = setTimeout(() => {
|
|
190
198
|
this.pending.delete(id);
|
|
191
|
-
reject(new ClientError(`Request ${method} timed out after ${
|
|
192
|
-
},
|
|
199
|
+
reject(new ClientError(`Request ${method} timed out after ${timeoutMs} ms. Check that the daemon is running with "conveno daemon status".`, { kind: "connection" }));
|
|
200
|
+
}, timeoutMs);
|
|
193
201
|
this.pending.set(id, {
|
|
194
202
|
resolve,
|
|
195
203
|
reject,
|
|
@@ -253,6 +261,7 @@ async function handshake(socketPath, tokenPath, kind, timeoutMs, onEvent) {
|
|
|
253
261
|
});
|
|
254
262
|
if (!proofsMatch(hello.proof, daemonProof(token, nonce))) throw new ClientError(`The process on ${socketPath} is not the Conveno daemon. Stop it, or remove the socket, and try again.`, { kind: "not_daemon" });
|
|
255
263
|
await typedCall(conn, "auth", { proof: clientProof(token, hello.challenge) });
|
|
264
|
+
conn.daemonVersion = hello.daemonVersion;
|
|
256
265
|
return conn;
|
|
257
266
|
} catch (e) {
|
|
258
267
|
await conn.close();
|
|
@@ -392,8 +401,9 @@ var Link = class {
|
|
|
392
401
|
if (this.closed) throw new ClientError("The Conveno client is closed.");
|
|
393
402
|
const used = this.conn;
|
|
394
403
|
let result;
|
|
404
|
+
const wait = method === "permission.ask" ? wire.timeoutMs + 1e4 : void 0;
|
|
395
405
|
try {
|
|
396
|
-
result = await used.call(method, wire);
|
|
406
|
+
result = await used.call(method, wire, wait);
|
|
397
407
|
} catch (e) {
|
|
398
408
|
if (!(e instanceof ConnectionLost) || this.closed) throw plainError(e, this.socketPath);
|
|
399
409
|
if (e.sent && NOT_REPLAYABLE.has(method)) {
|
|
@@ -467,6 +477,10 @@ async function connect(opts) {
|
|
|
467
477
|
onEvent: (handler) => link.onEvent(handler),
|
|
468
478
|
close: () => link.close()
|
|
469
479
|
};
|
|
480
|
+
Object.defineProperty(client, "daemonVersion", {
|
|
481
|
+
get: () => link.conn.daemonVersion,
|
|
482
|
+
enumerable: true
|
|
483
|
+
});
|
|
470
484
|
for (const method of CLIENT_METHODS) client[method] = (params) => link.call(method, params);
|
|
471
485
|
return client;
|
|
472
486
|
}
|
|
@@ -2,7 +2,7 @@ import { execFile, spawn } from "node:child_process";
|
|
|
2
2
|
import { readFileSync, statSync } from "node:fs";
|
|
3
3
|
import { readFile } from "node:fs/promises";
|
|
4
4
|
import { join } from "node:path";
|
|
5
|
-
import {
|
|
5
|
+
import { $ as endTurnContinuation, Gt as planSpawn, Nt as ownSession, Pt as parseCliVersion, Wt as planProgram, it as findOnPath, xn as startTurnContext, zt as pendingHookContext } from "./dist-CSSvrcKr.js";
|
|
6
6
|
import { n as cs, t as Za } from "./toml-patch-DGzVRdd1.js";
|
|
7
7
|
// ../adapters/codex/dist/index.js
|
|
8
8
|
const SERVER_NAME = "conveno";
|
|
@@ -95,6 +95,7 @@ const EVENT_NAME = {
|
|
|
95
95
|
session_start: "SessionStart",
|
|
96
96
|
user_prompt_submit: "UserPromptSubmit",
|
|
97
97
|
stop: "Stop",
|
|
98
|
+
session_end: "SessionEnd",
|
|
98
99
|
permission_request: "PermissionRequest"
|
|
99
100
|
};
|
|
100
101
|
/** A hook key is `<file>:<event>:<group>:<handler>`; null for any other shape. */
|
|
@@ -354,12 +355,16 @@ function renameHooks(toml, rename) {
|
|
|
354
355
|
const HOOK_EVENTS = [
|
|
355
356
|
"SessionStart",
|
|
356
357
|
"UserPromptSubmit",
|
|
357
|
-
"Stop"
|
|
358
|
+
"Stop",
|
|
359
|
+
"SessionEnd"
|
|
358
360
|
];
|
|
359
361
|
/** Older versions also installed a PermissionRequest hook; uninstall still removes it. */
|
|
360
362
|
const LEGACY_HOOK_EVENTS = ["PermissionRequest"];
|
|
361
363
|
/** Seconds. The hook gives up after 2 s on its own; this leaves room for Node startup. Same as Claude. */
|
|
362
364
|
const HOOK_TIMEOUT_SECONDS = 5;
|
|
365
|
+
/** Codex runs SessionEnd while a thread unloads and caps it at 3 s (default 1 s). */
|
|
366
|
+
const SESSION_END_TIMEOUT_SECONDS = 3;
|
|
367
|
+
const timeoutFor = (event) => event === "SessionEnd" ? SESSION_END_TIMEOUT_SECONDS : HOOK_TIMEOUT_SECONDS;
|
|
363
368
|
const codexDir = (env) => env.env.CODEX_HOME || join(env.home, ".codex");
|
|
364
369
|
const configPath = (env) => join(codexDir(env), "config.toml");
|
|
365
370
|
const hooksPath = (env) => join(codexDir(env), "hooks.json");
|
|
@@ -471,7 +476,7 @@ async function planHooks(env) {
|
|
|
471
476
|
next[event] = withOursReplaced(groups, event, { hooks: [{
|
|
472
477
|
type: "command",
|
|
473
478
|
command,
|
|
474
|
-
timeout:
|
|
479
|
+
timeout: timeoutFor(event)
|
|
475
480
|
}] });
|
|
476
481
|
}
|
|
477
482
|
if (!changed) return [];
|
|
@@ -491,7 +496,7 @@ async function planHooks(env) {
|
|
|
491
496
|
...doc,
|
|
492
497
|
hooks: next
|
|
493
498
|
}),
|
|
494
|
-
description: `Add SessionStart, UserPromptSubmit and
|
|
499
|
+
description: `Add SessionStart, UserPromptSubmit, Stop and SessionEnd hooks that deliver Conveno messages on the next turn and at the end of a turn, and take a closed window offline. Codex asks you to trust new hooks: review them with /hooks.`
|
|
495
500
|
}];
|
|
496
501
|
}
|
|
497
502
|
async function uninstallHooks(env) {
|
|
@@ -522,7 +527,7 @@ async function uninstallHooks(env) {
|
|
|
522
527
|
path,
|
|
523
528
|
before,
|
|
524
529
|
after: json(after),
|
|
525
|
-
description: "Remove the Conveno SessionStart, UserPromptSubmit, and
|
|
530
|
+
description: "Remove the Conveno SessionStart, UserPromptSubmit, Stop, and SessionEnd hooks."
|
|
526
531
|
}];
|
|
527
532
|
}
|
|
528
533
|
function serverSpec(env, existing) {
|
|
@@ -607,7 +612,8 @@ const EMPTY = {
|
|
|
607
612
|
* continuation would otherwise wait for the user. Conveno's wake limit bounds the chain.
|
|
608
613
|
*/
|
|
609
614
|
async function hook(event, input, ctx) {
|
|
610
|
-
|
|
615
|
+
ctx = withThread(input, ctx, event);
|
|
616
|
+
if (event === "SessionEnd") return retireThread(ctx);
|
|
611
617
|
if (event === "Stop") {
|
|
612
618
|
const reason = await endTurnContinuation(ctx);
|
|
613
619
|
if (reason === null) return EMPTY;
|
|
@@ -631,23 +637,36 @@ async function hook(event, input, ctx) {
|
|
|
631
637
|
};
|
|
632
638
|
}
|
|
633
639
|
/**
|
|
634
|
-
* The
|
|
635
|
-
*
|
|
636
|
-
*
|
|
637
|
-
*
|
|
640
|
+
* The thread unloaded (its window closed, or the TUI left it 60 s ago). If it is the session's
|
|
641
|
+
* current conversation, the session departs: the thread's MCP may outlive it (Windows, when Codex
|
|
642
|
+
* cannot kill the process tree) and would keep the row online. A thread the window already left
|
|
643
|
+
* binds to nothing (`turnStart` is false), so the window's session stays. No delivery.
|
|
638
644
|
*/
|
|
639
|
-
async function
|
|
640
|
-
|
|
641
|
-
if (typeof threadId !== "string" || threadId === "") return;
|
|
645
|
+
async function retireThread(ctx) {
|
|
646
|
+
if (ctx.nativeId === void 0) return EMPTY;
|
|
642
647
|
try {
|
|
643
648
|
const session = await ownSession(ctx);
|
|
644
|
-
if (
|
|
645
|
-
const call = ctx.client["session.setNative"];
|
|
646
|
-
if (typeof call === "function") await call({
|
|
647
|
-
sessionId: session.id,
|
|
648
|
-
nativeId: threadId
|
|
649
|
-
});
|
|
649
|
+
if (session) await ctx.client["session.unregister"]({ sessionId: session.id });
|
|
650
650
|
} catch {}
|
|
651
|
+
return EMPTY;
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* The hook's `session_id` is the Codex thread id, the id `codex queue --thread` takes. Codex
|
|
655
|
+
* threads can share one app-server process, so the host pid alone may not tell windows apart: the
|
|
656
|
+
* daemon binds the thread to the window's session (`session.bind`), and wakes the session by it.
|
|
657
|
+
* A session start or a prompt may move the window to the thread; a Stop of any other thread than
|
|
658
|
+
* the session's current one is ignored. With several windows on one process the daemon may not
|
|
659
|
+
* know which one the hook is in; the thread's own MCP server binds it on its first tool call.
|
|
660
|
+
*/
|
|
661
|
+
function withThread(input, ctx, event) {
|
|
662
|
+
const threadId = asObject(input).session_id;
|
|
663
|
+
if (typeof threadId !== "string" || threadId === "") return ctx;
|
|
664
|
+
return {
|
|
665
|
+
...ctx,
|
|
666
|
+
cli: ctx.cli ?? "codex",
|
|
667
|
+
nativeId: threadId,
|
|
668
|
+
turnStart: event === "SessionStart" || event === "UserPromptSubmit"
|
|
669
|
+
};
|
|
651
670
|
}
|
|
652
671
|
/** How long `codex queue` may take (it probes the shared local app-server) before we give up. */
|
|
653
672
|
const QUEUE_TIMEOUT_MS = 2e4;
|
|
@@ -859,6 +878,7 @@ const STATE_EVENTS = {
|
|
|
859
878
|
SessionStart: "session_start",
|
|
860
879
|
UserPromptSubmit: "user_prompt_submit",
|
|
861
880
|
Stop: "stop",
|
|
881
|
+
SessionEnd: "session_end",
|
|
862
882
|
PermissionRequest: "permission_request"
|
|
863
883
|
};
|
|
864
884
|
/**
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { appendFileSync } from "node:fs";
|
|
2
|
+
import { ut as hookLogLine, w as appendHookLog } from "./dist-CSSvrcKr.js";
|
|
2
3
|
import { n as connectOpts } from "./ctx-tYftvhz_.js";
|
|
3
4
|
// src/hook.ts
|
|
4
5
|
/**
|
|
@@ -39,8 +40,59 @@ async function findHostPid(ctx, client, cli, local) {
|
|
|
39
40
|
function timingLine(cli, event, ms, procMs, timedOut) {
|
|
40
41
|
return `${(/* @__PURE__ */ new Date()).toISOString()} cli=${cli} event=${event} ms=${ms}${procMs === void 0 ? "" : ` proc_ms=${procMs}`} timeout=${timedOut ? "yes" : "no"}\n`;
|
|
41
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
|
+
}
|
|
42
86
|
/** After a timeout, the hook gets this many more timeouts' worth of time to finish recording. */
|
|
43
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));
|
|
44
96
|
/** How long before the hook's timeout its messages count as too late to print. */
|
|
45
97
|
const DEADLINE_MARGIN_MS = 300;
|
|
46
98
|
/**
|
|
@@ -59,8 +111,15 @@ async function runHook(ctx, argv) {
|
|
|
59
111
|
if (!adapter || !event) return 0;
|
|
60
112
|
const listener = adapter.listenEvents?.includes(event) === true;
|
|
61
113
|
const deadline = listener ? void 0 : Date.now() + ctx.hookTimeoutMs - DEADLINE_MARGIN_MS;
|
|
62
|
-
const
|
|
114
|
+
const started = Date.now();
|
|
115
|
+
const t0 = ctx.timingLog && !listener ? started : void 0;
|
|
116
|
+
const trace = { delivered: 0 };
|
|
117
|
+
let conversation;
|
|
63
118
|
let timedOut = false;
|
|
119
|
+
let workDone = false;
|
|
120
|
+
let hostMs;
|
|
121
|
+
let hostResolved = false;
|
|
122
|
+
let hostMissing = false;
|
|
64
123
|
let client;
|
|
65
124
|
let timer;
|
|
66
125
|
const early = ctx.hostLookup ? void 0 : ctx.ancestry(HOOK_ANCESTRY_TIMEOUT_MS);
|
|
@@ -74,17 +133,39 @@ async function runHook(ctx, argv) {
|
|
|
74
133
|
}
|
|
75
134
|
};
|
|
76
135
|
const [input, connected] = await Promise.all([readInput(), ctx.connect(connectOpts(ctx, false))]);
|
|
77
|
-
client = connected;
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
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, {
|
|
81
154
|
client,
|
|
82
|
-
|
|
155
|
+
resolveHostPid,
|
|
156
|
+
...ctx.hostLookup ? { ppid: ctx.hostLookup.ppid } : {},
|
|
83
157
|
cli: adapter.cli,
|
|
84
158
|
isAlive: ctx.isAlive,
|
|
85
159
|
...deadline === void 0 ? {} : { deadline }
|
|
86
160
|
});
|
|
161
|
+
if (hostResolved && hostMissing) await adapter.hookWithoutSession?.(event, input).catch(() => {});
|
|
162
|
+
return out;
|
|
87
163
|
})();
|
|
164
|
+
work.then(() => {
|
|
165
|
+
workDone = true;
|
|
166
|
+
}, () => {
|
|
167
|
+
workDone = true;
|
|
168
|
+
});
|
|
88
169
|
const timeout = listener ? new Promise(() => void 0) : new Promise((resolve) => {
|
|
89
170
|
timer = setTimeout(() => {
|
|
90
171
|
timedOut = true;
|
|
@@ -94,11 +175,24 @@ async function runHook(ctx, argv) {
|
|
|
94
175
|
let code = 0;
|
|
95
176
|
try {
|
|
96
177
|
const out = await Promise.race([work, timeout]);
|
|
97
|
-
if (out === NOTHING && !listener) await Promise.race([work.catch(() => void 0), new Promise((r) => setTimeout(r, ctx.hookTimeoutMs
|
|
178
|
+
if (out === NOTHING && !listener) await Promise.race([work.catch(() => void 0), new Promise((r) => setTimeout(r, finishGraceMs(ctx.hookTimeoutMs)))]);
|
|
98
179
|
if (out.stdout) ctx.out(out.stdout.endsWith("\n") ? out.stdout : `${out.stdout}\n`);
|
|
99
180
|
if (listener && out.stderr) ctx.err(out.stderr.endsWith("\n") ? out.stderr : `${out.stderr}\n`);
|
|
100
181
|
if (listener) code = out.exitCode;
|
|
101
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
|
+
}
|
|
102
196
|
if (t0 !== void 0 && ctx.timingLog) {
|
|
103
197
|
const up = ctx.uptimeMs?.();
|
|
104
198
|
try {
|