@sjawhar/claude-envoy 4.0.1 → 4.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.
- package/.claude-plugin/plugin.json +1 -1
- package/.omp-plugin/plugin.json +1 -1
- package/README.md +81 -0
- package/bin/envoy-channel.ts +7 -2
- package/dist/codex-hook.js +29834 -0
- package/dist/codex-tool-hook.js +136 -0
- package/dist/dispatch.js +121 -24
- package/dist/envoy-channel.js +16570 -14818
- package/dist/session-hook.js +42 -15
- package/hooks/codex-hook.ts +168 -0
- package/hooks/codex-tool-hook.ts +51 -0
- package/hooks/hook-arguments.ts +23 -0
- package/hooks/session-hook.ts +14 -6
- package/package.json +1 -1
- package/scripts/build.ts +116 -12
- package/src/codex/codex-agent-stream.ts +240 -0
- package/src/codex/codex-cli.ts +280 -0
- package/src/codex/codex-delivery.ts +194 -0
- package/src/codex/codex-inbox.ts +197 -0
- package/src/codex/codex-owner.ts +273 -0
- package/src/codex/codex-server.ts +594 -0
- package/src/codex/codex-session-record.ts +308 -0
- package/src/codex/codex-transcript.ts +373 -0
- package/src/codex/codex-user-turns.ts +107 -0
- package/src/envoy-channel-server.ts +7 -1
- package/src/session-identity.ts +1 -1
package/dist/session-hook.js
CHANGED
|
@@ -14626,7 +14626,7 @@ var dispatchToolSpecs = [
|
|
|
14626
14626
|
verdict: "pass",
|
|
14627
14627
|
commit: "1111111111111111111111111111111111111111"
|
|
14628
14628
|
},
|
|
14629
|
-
description: "Record one result of one check of an issue's Verification document, or retract a result " + "recorded before. A record prints the pull-request body line it implies. Write that line " + "into the pull-request body unchanged: it is the one grammar every writer uses, and it " + "carries no link to Dispatch. " + "Name the check by its block id. Where two Verification documents in reach hold that id, " + "name it by its canonical reference (dispatch://KEY/artifact/verification-md#b-<id>). " + "409 CHECK_AMBIGUOUS names both documents. An id no Verification document of the issue " + "or of an issue above it holds is 400 UNKNOWN_CHECK. " + `${CHECK_PROVED_BY_CI}. ` + "Dispatch reads its result from that run, so a record for it is 409 " + "CHECK_PROVED_BY_CI from every role, which names the check and the run. " + "A pass that counts a failed, a skipped or an excluded case contradicts itself, and is " + "400 RESULT_CONTRADICTS. " + "Dispatch asks GitHub whether the repository of the check's issue holds the commit. A " + "commit that repository does not hold is 400 RESULT_COMMIT_UNKNOWN, which names the " + "commit and that owner/repo. Record the result after the commit is pushed. A repository " + "Dispatch cannot read records the result as before. " + "The result is recorded against the check's own issue, so a child's run of a parent's " + "check appears under that check. A closed issue takes a result only for a check whose " + "when is after_merge or default_branch, the production check after the merge. It refuses " + "every other record with 409 ISSUE_CLOSED, as it refuses every other write. " + RESULT_RETRACT_RULE + " The retraction keeps both records: the result stays readable, and it proves nothing " + "from then on. Record a new result where the check still needs one. A retraction is " + "taken on a closed issue and for a check of any when. Three callers may retract: the " + "session that recorded the result, a session that holds the Dispatch claim of the issue " + "the result was recorded on, and a caller whose credential carries a person. Every other " + "caller is 403 RETRACTION_FORBIDDEN. A result retracted already is 409 RESULT_RETRACTED. " + ISSUE_REFERENCE,
|
|
14629
|
+
description: "Record one result of one check of an issue's Verification document, or retract a result " + "recorded before. A record prints the pull-request body line it implies. Write that line " + "into the pull-request body unchanged: it is the one grammar every writer uses, and it " + "carries no link to Dispatch. " + "Name the check by its block id. Where two Verification documents in reach hold that id, " + "name it by its canonical reference (dispatch://KEY/artifact/verification-md#b-<id>). " + "409 CHECK_AMBIGUOUS names both documents. An id no Verification document of the issue " + "or of an issue above it holds is 400 UNKNOWN_CHECK. " + `${CHECK_PROVED_BY_CI}. ` + "Dispatch reads its result from that run, so a record for it is 409 " + "CHECK_PROVED_BY_CI from every role, which names the check and the run. " + "A pass that counts a failed, a skipped or an excluded case contradicts itself, and is " + "400 RESULT_CONTRADICTS. " + "Dispatch asks GitHub whether the repository of the check's issue holds the commit. A " + "commit that repository does not hold is 400 RESULT_COMMIT_UNKNOWN, which names the " + "commit and that owner/repo. Record the result after the commit is pushed. A repository " + "Dispatch cannot read records the result as before. " + "The result is recorded against the check's own issue, so a child's run of a parent's " + "check appears under that check. A closed issue takes a result only for a check whose " + "when is after_merge or default_branch, the production check after the merge. It refuses " + "every other record with 409 ISSUE_CLOSED, as it refuses every other write. " + "A check a document version rewords while the result is being written is 409 " + "CHECK_CONTENDED, with nothing recorded: run the same command again. " + RESULT_RETRACT_RULE + " The retraction keeps both records: the result stays readable, and it proves nothing " + "from then on. Record a new result where the check still needs one. A retraction is " + "taken on a closed issue and for a check of any when. Three callers may retract: the " + "session that recorded the result, a session that holds the Dispatch claim of the issue " + "the result was recorded on, and a caller whose credential carries a person. Every other " + "caller is 403 RETRACTION_FORBIDDEN. A result retracted already is 409 RESULT_RETRACTED. " + ISSUE_REFERENCE,
|
|
14630
14630
|
arguments: (z) => ({
|
|
14631
14631
|
issue: z.string().describe(ISSUE_REFERENCE).optional(),
|
|
14632
14632
|
check: z.string().describe("The check block's id, or its canonical reference dispatch://KEY/artifact/verification-md#b-<id> when the id is not unique among the issue's Verification document and those of the issues above it.").optional(),
|
|
@@ -24169,14 +24169,22 @@ The result stays readable, and it proves nothing from now on. Record a new resul
|
|
|
24169
24169
|
...defined("excluded", optionalNumber(args, "excluded")),
|
|
24170
24170
|
...defined("screenshots", optionalStringArray(args, "screenshots"))
|
|
24171
24171
|
};
|
|
24172
|
-
|
|
24173
|
-
|
|
24174
|
-
|
|
24175
|
-
|
|
24176
|
-
|
|
24177
|
-
|
|
24178
|
-
|
|
24179
|
-
|
|
24172
|
+
let recorded;
|
|
24173
|
+
try {
|
|
24174
|
+
recorded = await client.recordResult(issue, {
|
|
24175
|
+
actor,
|
|
24176
|
+
check: stringArg(args, "check"),
|
|
24177
|
+
role: stringArg(args, "role"),
|
|
24178
|
+
verdict: stringArg(args, "verdict"),
|
|
24179
|
+
commit: stringArg(args, "commit"),
|
|
24180
|
+
...optional
|
|
24181
|
+
});
|
|
24182
|
+
} catch (error) {
|
|
24183
|
+
if (dispatchAnswered(error, 409) && error.code === "CHECK_CONTENDED") {
|
|
24184
|
+
throw refusalWithCode(error, "the check moved twice while this result was being written, and nothing was recorded: run the same dispatch result command again");
|
|
24185
|
+
}
|
|
24186
|
+
throw error;
|
|
24187
|
+
}
|
|
24180
24188
|
return {
|
|
24181
24189
|
text: `Recorded ${recorded.result.verdict} for check ${recorded.result.check_block_id} of ${recorded.result.check_issue_key} at ${recorded.result.commit_sha}, as ${recorded.result.role}.
|
|
24182
24190
|
|
|
@@ -25361,6 +25369,8 @@ function namedDirectory(harness, env) {
|
|
|
25361
25369
|
return nonEmpty(env[HARNESS_DIRECTORY_VARIABLE[harness]]);
|
|
25362
25370
|
}
|
|
25363
25371
|
function harnessDirectory(harness, env) {
|
|
25372
|
+
if (harness === "codex")
|
|
25373
|
+
return;
|
|
25364
25374
|
for (const plugin of harness === "command" ? PLUGIN_HARNESSES : [harness]) {
|
|
25365
25375
|
if (harness === "command" && plugin === "claude" && env.CLAUDE_CODE_CHILD_SESSION !== "1") {
|
|
25366
25376
|
continue;
|
|
@@ -29704,6 +29714,23 @@ async function pruneStaleSessionRoles(stateDirectory, currentSessionId) {
|
|
|
29704
29714
|
await pruneStateDirectory(join7(stateDirectory, ROLES_DIRECTORY), async (file) => file !== own && await writtenLongAgo(file));
|
|
29705
29715
|
}
|
|
29706
29716
|
|
|
29717
|
+
// hooks/hook-arguments.ts
|
|
29718
|
+
function parseHookArguments(argv) {
|
|
29719
|
+
const at = argv.indexOf("--host");
|
|
29720
|
+
let host = "claude";
|
|
29721
|
+
let rest = argv;
|
|
29722
|
+
if (at >= 0) {
|
|
29723
|
+
const named = argv[at + 1];
|
|
29724
|
+
if (named !== "claude" && named !== "codex") {
|
|
29725
|
+
throw new Error(`session-hook: --host takes claude or codex, not ${JSON.stringify(named)}`);
|
|
29726
|
+
}
|
|
29727
|
+
host = named;
|
|
29728
|
+
rest = [...argv.slice(0, at), ...argv.slice(at + 2)];
|
|
29729
|
+
}
|
|
29730
|
+
const [mode, ...modeArguments] = rest;
|
|
29731
|
+
return { host, mode, modeArguments };
|
|
29732
|
+
}
|
|
29733
|
+
|
|
29707
29734
|
// hooks/session-hook.ts
|
|
29708
29735
|
var OPEN_ASKS_TIMEOUT_MS = 3000;
|
|
29709
29736
|
var OpenAsksInput = object({
|
|
@@ -29719,6 +29746,7 @@ var AnswersInput = object({ session_id: string2().min(1), ...DispatchFirstInput.
|
|
|
29719
29746
|
var ANSWERS_BY_MS = SESSION_ANSWERS_DEADLINE_MS;
|
|
29720
29747
|
var ANSWERS_LEAST_WAIT_MS = 150;
|
|
29721
29748
|
var ANSWERS_SETTLE_MS = 50;
|
|
29749
|
+
var { host: HOST, mode, modeArguments } = parseHookArguments(process.argv.slice(2));
|
|
29722
29750
|
var REFRESH_LOCK = "answers-refresh.lock";
|
|
29723
29751
|
var REFRESH_OUTCOME = "answers-refresh.json";
|
|
29724
29752
|
var REFRESH_POLL_MS = 20;
|
|
@@ -29778,7 +29806,7 @@ function replaceOnce(envFile, prefix, line) {
|
|
|
29778
29806
|
async function openAsks(raw) {
|
|
29779
29807
|
const input = OpenAsksInput.parse(raw);
|
|
29780
29808
|
const envFile = process.env["CLAUDE_ENV_FILE"];
|
|
29781
|
-
const chosen = sessionConfigFile(
|
|
29809
|
+
const chosen = sessionConfigFile(HOST, process.env);
|
|
29782
29810
|
if (envFile) {
|
|
29783
29811
|
appendOnce(envFile, DISPATCH_HOST_LINE);
|
|
29784
29812
|
if (chosen.path !== null) {
|
|
@@ -29846,7 +29874,7 @@ ${formatOpenAsksSummary(snapshot, dispatch.publicUrl ?? dispatch.url)}
|
|
|
29846
29874
|
function dispatchFirst(raw) {
|
|
29847
29875
|
const input = DispatchFirstInput.parse(raw);
|
|
29848
29876
|
const directory = claudeProjectDirectory({ CLAUDE_PROJECT_DIR: process.env["CLAUDE_PROJECT_DIR"] }, input.cwd ?? process.cwd());
|
|
29849
|
-
const chosen = sessionConfigFile(
|
|
29877
|
+
const chosen = sessionConfigFile(HOST, process.env);
|
|
29850
29878
|
if (!sessionDispatchSettings(chosen, process.env, { cwd: directory }).dispatch.enabled)
|
|
29851
29879
|
return;
|
|
29852
29880
|
const pluginRoot = configuredValue(process.env["CLAUDE_PLUGIN_ROOT"]);
|
|
@@ -29920,7 +29948,7 @@ async function refreshedAnswers(session, cwd, dispatchUrl, startedAt, by) {
|
|
|
29920
29948
|
}
|
|
29921
29949
|
const lock = join8(directory, REFRESH_LOCK);
|
|
29922
29950
|
if (!refreshLockHeld(lock)) {
|
|
29923
|
-
Bun.spawn([process.execPath, Bun.main, "answers-refresh", session, cwd], {
|
|
29951
|
+
Bun.spawn([process.execPath, Bun.main, "answers-refresh", session, cwd, "--host", HOST], {
|
|
29924
29952
|
stdin: "ignore",
|
|
29925
29953
|
stdout: "ignore",
|
|
29926
29954
|
stderr: "ignore",
|
|
@@ -29949,7 +29977,7 @@ async function refreshedAnswers(session, cwd, dispatchUrl, startedAt, by) {
|
|
|
29949
29977
|
}
|
|
29950
29978
|
}
|
|
29951
29979
|
async function answersMessage(session, cwd, startedAt, by) {
|
|
29952
|
-
const file = sessionConfigFile(
|
|
29980
|
+
const file = sessionConfigFile(HOST, process.env);
|
|
29953
29981
|
let { dispatch } = sessionDispatchSettings(file, process.env, {
|
|
29954
29982
|
cwd,
|
|
29955
29983
|
commands: "kept",
|
|
@@ -30016,7 +30044,7 @@ async function answersRefresh(session, cwd) {
|
|
|
30016
30044
|
const lock = join8(directory, REFRESH_LOCK);
|
|
30017
30045
|
if (takeRefreshLock(lock)) {
|
|
30018
30046
|
try {
|
|
30019
|
-
const file = sessionConfigFile(
|
|
30047
|
+
const file = sessionConfigFile(HOST, process.env);
|
|
30020
30048
|
const dispatchUrl = sessionDispatchUrl(file, process.env, { cwd }) ?? null;
|
|
30021
30049
|
const { dispatch } = sessionDispatchSettings(file, process.env, { cwd, session });
|
|
30022
30050
|
const read = await readSessionAnswers({
|
|
@@ -30038,7 +30066,6 @@ async function answersRefresh(session, cwd) {
|
|
|
30038
30066
|
}
|
|
30039
30067
|
process.exit(0);
|
|
30040
30068
|
}
|
|
30041
|
-
var [mode, ...modeArguments] = process.argv.slice(2);
|
|
30042
30069
|
if (mode === "answers-refresh") {
|
|
30043
30070
|
const [session, cwd] = modeArguments;
|
|
30044
30071
|
if (session === undefined || cwd === undefined) {
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// The Codex CLI's `SessionStart` and `SessionEnd` hooks for the Envoy plugin:
|
|
2
|
+
// `codex/hooks/hooks.json` runs `dist/codex-hook.js session-start` at a session's first prompt and
|
|
3
|
+
// again after `/new`, and `dist/codex-hook.js session-end` when Codex unloads a thread.
|
|
4
|
+
//
|
|
5
|
+
// At SessionStart it records which session the `codex` process now runs, where the plugin's MCP
|
|
6
|
+
// servers read it (`../src/codex/codex-session-record`): they are that process's children too, but
|
|
7
|
+
// Codex hands them no session id. It writes the record Claude Code's hook writes as well
|
|
8
|
+
// (`sessions/<pid>/session-id`), so the server that owns the process's session
|
|
9
|
+
// (`../src/codex/codex-owner`) follows `/new` to the new id the way it follows a Claude Code
|
|
10
|
+
// `/clear`. Then it tells the model this session's open Dispatch asks and how to run `dispatch`
|
|
11
|
+
// here, as plain output, which Codex adds to the model's context (measured on 0.154.0). The
|
|
12
|
+
// dispatch-first skill and the answers list come from `dist/session-hook.js`, which
|
|
13
|
+
// `codex/hooks/hooks.json` runs beside this. At SessionEnd it leaves the session's ended marker.
|
|
14
|
+
// It always exits 0: a session must start without Envoy.
|
|
15
|
+
|
|
16
|
+
import { rm } from "node:fs/promises"
|
|
17
|
+
import { formatOpenAsksSummary } from "@legion/envoy-client/dispatch-execute"
|
|
18
|
+
import { DispatchClient } from "@legion/envoy-client/dispatch-http"
|
|
19
|
+
import { messageFor } from "@legion/envoy-client/errors"
|
|
20
|
+
import { sessionConfigFile, sessionDispatchSettings } from "@legion/envoy-client/session-settings"
|
|
21
|
+
import { z } from "zod"
|
|
22
|
+
import { configuredValue } from "../src/claude-session"
|
|
23
|
+
import {
|
|
24
|
+
codexEndedFile,
|
|
25
|
+
codexExecutable,
|
|
26
|
+
codexHome,
|
|
27
|
+
codexProcessId,
|
|
28
|
+
codexSessionRecordFile,
|
|
29
|
+
markSessionEnded,
|
|
30
|
+
processStarted,
|
|
31
|
+
pruneCodexSessionRecords,
|
|
32
|
+
readCodexSessionRecord,
|
|
33
|
+
recordOfProcess,
|
|
34
|
+
SHARED_APP_SERVER_NOTE,
|
|
35
|
+
sharedAppServer,
|
|
36
|
+
writeCodexSessionRecord,
|
|
37
|
+
} from "../src/codex/codex-session-record"
|
|
38
|
+
import { sessionHandoffFile, writeSessionHandoff } from "../src/session-identity"
|
|
39
|
+
|
|
40
|
+
/** How long the open-asks read may take before the summary says it is unavailable. */
|
|
41
|
+
const OPEN_ASKS_TIMEOUT_MS = 3_000
|
|
42
|
+
|
|
43
|
+
const SessionStartInput = z.object({
|
|
44
|
+
session_id: z.string().min(1),
|
|
45
|
+
transcript_path: z.string().nullable().optional(),
|
|
46
|
+
cwd: z.string().min(1),
|
|
47
|
+
source: z.string().nullable().optional(),
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
/** What the model is told about running `dispatch` in a Codex session. */
|
|
51
|
+
export const CODEX_DISPATCH_NOTE =
|
|
52
|
+
"This Codex session reaches Dispatch through the `dispatch` tool of the `envoy` MCP server, not a shell command: Codex puts no plugin command on the shell's PATH, and its sandbox keeps shell commands off the network. Wherever a skill shows `dispatch <command> <flags>`, call the `dispatch` tool with `args` set to the words after `dispatch`, as a list, and `stdin` set to what the command would read on standard input (a here-document's text). It runs the same command, as this session, and answers with what the command prints and its exit code."
|
|
53
|
+
|
|
54
|
+
/** What a session that keeps no transcript is told about Envoy. */
|
|
55
|
+
const NO_TRANSCRIPT_NOTE =
|
|
56
|
+
"This Codex session keeps no transcript (a fork such as /side or /btw, or an ephemeral session), so the Envoy plugin does not register it with Envoy: it receives no Envoy messages and does not show on Dispatch's Agents page. Its `dispatch` tool works, acting as this session."
|
|
57
|
+
|
|
58
|
+
const SessionEndInput = z.object({ session_id: z.string().min(1) })
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* `SessionEnd`, which Codex runs when it unloads a thread (`thread_unload_delay`, 60 s by default,
|
|
62
|
+
* after the thread is idle with no subscriber) or at exit: leaves the session's ended marker when the
|
|
63
|
+
* process's record names it, so the server delivers nothing more to it until the next
|
|
64
|
+
* `SessionStart` names the session that follows. It writes a file of its own and never the record,
|
|
65
|
+
* which a `SessionStart` may be writing at that moment. The end of a fork leaves nothing.
|
|
66
|
+
*/
|
|
67
|
+
async function sessionEnd(raw: unknown): Promise<void> {
|
|
68
|
+
const input = SessionEndInput.parse(raw)
|
|
69
|
+
const pluginData = configuredValue(
|
|
70
|
+
process.env["PLUGIN_DATA"] ?? process.env["CLAUDE_PLUGIN_DATA"],
|
|
71
|
+
)
|
|
72
|
+
if (pluginData === undefined) return
|
|
73
|
+
const pid = codexProcessId()
|
|
74
|
+
const file = codexSessionRecordFile(pluginData, pid)
|
|
75
|
+
const record = await readCodexSessionRecord(file)
|
|
76
|
+
if (record === undefined || record.session_id !== input.session_id) return
|
|
77
|
+
if (!recordOfProcess(record, pid)) return
|
|
78
|
+
await markSessionEnded(pluginData, pid, input.session_id)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function sessionStart(raw: unknown): Promise<void> {
|
|
82
|
+
const input = SessionStartInput.parse(raw)
|
|
83
|
+
const pluginData = configuredValue(
|
|
84
|
+
process.env["PLUGIN_DATA"] ?? process.env["CLAUDE_PLUGIN_DATA"],
|
|
85
|
+
)
|
|
86
|
+
if (pluginData === undefined) {
|
|
87
|
+
process.stderr.write("envoy: PLUGIN_DATA is unset, so this session's id was not recorded\n")
|
|
88
|
+
} else {
|
|
89
|
+
const pid = codexProcessId()
|
|
90
|
+
try {
|
|
91
|
+
await pruneCodexSessionRecords(pluginData)
|
|
92
|
+
} catch (error) {
|
|
93
|
+
process.stderr.write(`envoy: could not prune old session records — ${messageFor(error)}\n`)
|
|
94
|
+
}
|
|
95
|
+
try {
|
|
96
|
+
const started = processStarted(pid)
|
|
97
|
+
if (sharedAppServer(pid)) {
|
|
98
|
+
// No record: two sessions of one process would share it (`sharedAppServer`).
|
|
99
|
+
process.stdout.write(`${SHARED_APP_SERVER_NOTE}\n\n`)
|
|
100
|
+
} else if (input.transcript_path === null || input.transcript_path === undefined) {
|
|
101
|
+
// A fork (`/side`, `/btw`) or an ephemeral session (`codex exec --ephemeral`): it keeps no
|
|
102
|
+
// transcript, recording a fork would move its session's registration to it, and Codex
|
|
103
|
+
// refuses `codex queue` for an ephemeral thread, so nothing could reach it.
|
|
104
|
+
process.stdout.write(`${NO_TRANSCRIPT_NOTE}\n\n`)
|
|
105
|
+
} else if (started === undefined) {
|
|
106
|
+
process.stderr.write(
|
|
107
|
+
`envoy: this session was not recorded, because the start of codex process ${pid} cannot be read; it gets no Envoy messages\n`,
|
|
108
|
+
)
|
|
109
|
+
} else {
|
|
110
|
+
// The session again (`/resume`): it has not ended. The marker goes before the record is
|
|
111
|
+
// written, so a server that reads the new record never reads the old marker beside it.
|
|
112
|
+
await rm(codexEndedFile(pluginData, pid, input.session_id), { force: true })
|
|
113
|
+
await writeCodexSessionRecord(codexSessionRecordFile(pluginData, pid), {
|
|
114
|
+
codex_executable: codexExecutable(pid) ?? null,
|
|
115
|
+
codex_home: codexHome(process.env),
|
|
116
|
+
codex_started: started,
|
|
117
|
+
cwd: input.cwd,
|
|
118
|
+
session_id: input.session_id,
|
|
119
|
+
source: input.source ?? null,
|
|
120
|
+
transcript_path: input.transcript_path ?? null,
|
|
121
|
+
})
|
|
122
|
+
await writeSessionHandoff(sessionHandoffFile(pluginData, pid), input.session_id)
|
|
123
|
+
}
|
|
124
|
+
} catch (error) {
|
|
125
|
+
process.stderr.write(`envoy: could not record the session id — ${messageFor(error)}\n`)
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const chosen = sessionConfigFile("codex", process.env)
|
|
130
|
+
const { dispatch, warnings } = sessionDispatchSettings(chosen, process.env, {
|
|
131
|
+
cwd: input.cwd,
|
|
132
|
+
session: input.session_id,
|
|
133
|
+
})
|
|
134
|
+
for (const warning of warnings) process.stdout.write(`envoy: ${warning}\n`)
|
|
135
|
+
if (!dispatch.enabled) {
|
|
136
|
+
if (dispatch.error !== null) {
|
|
137
|
+
process.stdout.write(`Dispatch authored-ask summary unavailable: ${dispatch.error}\n`)
|
|
138
|
+
}
|
|
139
|
+
return
|
|
140
|
+
}
|
|
141
|
+
process.stdout.write(`${CODEX_DISPATCH_NOTE}\n\n`)
|
|
142
|
+
try {
|
|
143
|
+
const snapshot = await new DispatchClient(dispatch.url, dispatch.credential, fetch, {
|
|
144
|
+
signal: AbortSignal.timeout(OPEN_ASKS_TIMEOUT_MS),
|
|
145
|
+
}).openAsks(input.session_id)
|
|
146
|
+
process.stdout.write(
|
|
147
|
+
`Dispatch authored-ask summary:\n${formatOpenAsksSummary(snapshot, dispatch.publicUrl ?? dispatch.url)}\n`,
|
|
148
|
+
)
|
|
149
|
+
} catch (error) {
|
|
150
|
+
process.stdout.write(`Dispatch authored-ask summary unavailable: ${messageFor(error)}\n`)
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (import.meta.main) {
|
|
155
|
+
const [mode] = process.argv.slice(2)
|
|
156
|
+
try {
|
|
157
|
+
if (mode === "session-start") await sessionStart(JSON.parse(await Bun.stdin.text()))
|
|
158
|
+
else if (mode === "session-end") await sessionEnd(JSON.parse(await Bun.stdin.text()))
|
|
159
|
+
else {
|
|
160
|
+
throw new Error(
|
|
161
|
+
`unknown mode ${JSON.stringify(mode)}; codex/hooks/hooks.json names session-start and session-end`,
|
|
162
|
+
)
|
|
163
|
+
}
|
|
164
|
+
} catch (error) {
|
|
165
|
+
process.stderr.write(`envoy: codex-hook: ${messageFor(error)}\n`)
|
|
166
|
+
}
|
|
167
|
+
process.exit(0)
|
|
168
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// The Codex CLI's `PostToolUse` hook for the Envoy plugin: `codex/hooks/hooks.json`
|
|
2
|
+
// runs `dist/codex-tool-hook.js` after every tool call of a Codex session.
|
|
3
|
+
//
|
|
4
|
+
// It takes the messages waiting in the session's inbox (`../src/codex/codex-inbox`), oldest first
|
|
5
|
+
// and as many as fit under Codex's cap on a hook's text (`HOOK_CONTEXT_MAX_BYTES`), and hands them
|
|
6
|
+
// to Codex as the hook's `additionalContext`, which reaches the model in its very next request,
|
|
7
|
+
// inside the running turn (measured on Codex CLI 0.154.0). A message that does not fit, and every
|
|
8
|
+
// one behind it, waits for `codex queue` at the turn's end. With nothing waiting it prints nothing. It runs after every tool call, so it is a bundle of its own and imports only the
|
|
9
|
+
// inbox, which needs nothing but the filesystem; and it exits 0 whatever happens, because a
|
|
10
|
+
// failure here must never fail the tool call it follows.
|
|
11
|
+
|
|
12
|
+
import {
|
|
13
|
+
codexInboxDirectory,
|
|
14
|
+
HOOK_CONTEXT_MAX_BYTES,
|
|
15
|
+
inboxContext,
|
|
16
|
+
takeInbox,
|
|
17
|
+
} from "../src/codex/codex-inbox"
|
|
18
|
+
|
|
19
|
+
async function postToolUse(text: string): Promise<void> {
|
|
20
|
+
const input: unknown = JSON.parse(text)
|
|
21
|
+
const sessionId =
|
|
22
|
+
typeof input === "object" && input !== null
|
|
23
|
+
? (input as { session_id?: unknown }).session_id
|
|
24
|
+
: undefined
|
|
25
|
+
const pluginData = process.env["PLUGIN_DATA"] || process.env["CLAUDE_PLUGIN_DATA"]
|
|
26
|
+
if (typeof sessionId !== "string" || sessionId === "" || !pluginData) return
|
|
27
|
+
// Only what fits under Codex's cap on a hook's text; a longer message waits for `codex queue`.
|
|
28
|
+
const taken = await takeInbox(
|
|
29
|
+
codexInboxDirectory(pluginData, sessionId),
|
|
30
|
+
"hook",
|
|
31
|
+
HOOK_CONTEXT_MAX_BYTES,
|
|
32
|
+
)
|
|
33
|
+
if (taken.length === 0) return
|
|
34
|
+
process.stdout.write(
|
|
35
|
+
JSON.stringify({
|
|
36
|
+
hookSpecificOutput: {
|
|
37
|
+
additionalContext: inboxContext(taken.map(({ item }) => item)),
|
|
38
|
+
hookEventName: "PostToolUse",
|
|
39
|
+
},
|
|
40
|
+
}),
|
|
41
|
+
)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
try {
|
|
45
|
+
await postToolUse(await Bun.stdin.text())
|
|
46
|
+
} catch (error) {
|
|
47
|
+
process.stderr.write(
|
|
48
|
+
`envoy: codex-tool-hook: ${error instanceof Error ? error.message : String(error)}\n`,
|
|
49
|
+
)
|
|
50
|
+
}
|
|
51
|
+
process.exit(0)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `session-hook.js`'s arguments: `<mode> [arguments…] [--host <claude|codex>]`. Claude Code's
|
|
3
|
+
* hooks.json names no host, so it is `claude`; the Codex plugin's names `--host codex`.
|
|
4
|
+
*/
|
|
5
|
+
export function parseHookArguments(argv: readonly string[]): {
|
|
6
|
+
readonly host: "claude" | "codex"
|
|
7
|
+
readonly mode: string | undefined
|
|
8
|
+
readonly modeArguments: readonly string[]
|
|
9
|
+
} {
|
|
10
|
+
const at = argv.indexOf("--host")
|
|
11
|
+
let host: "claude" | "codex" = "claude"
|
|
12
|
+
let rest = argv
|
|
13
|
+
if (at >= 0) {
|
|
14
|
+
const named = argv[at + 1]
|
|
15
|
+
if (named !== "claude" && named !== "codex") {
|
|
16
|
+
throw new Error(`session-hook: --host takes claude or codex, not ${JSON.stringify(named)}`)
|
|
17
|
+
}
|
|
18
|
+
host = named
|
|
19
|
+
rest = [...argv.slice(0, at), ...argv.slice(at + 2)]
|
|
20
|
+
}
|
|
21
|
+
const [mode, ...modeArguments] = rest
|
|
22
|
+
return { host, mode, modeArguments }
|
|
23
|
+
}
|
package/hooks/session-hook.ts
CHANGED
|
@@ -116,6 +116,7 @@ import { z } from "zod"
|
|
|
116
116
|
import { claudeProjectDirectory, configuredValue } from "../src/claude-session"
|
|
117
117
|
import { sessionHandoffFile, writeSessionHandoff } from "../src/session-identity"
|
|
118
118
|
import { recordChosenTitle } from "../src/session-state"
|
|
119
|
+
import { parseHookArguments } from "./hook-arguments"
|
|
119
120
|
|
|
120
121
|
const OPEN_ASKS_TIMEOUT_MS = 3_000
|
|
121
122
|
const OpenAsksInput = z.object({
|
|
@@ -143,6 +144,14 @@ const ANSWERS_LEAST_WAIT_MS = 150
|
|
|
143
144
|
/** How long after the hook's print deadline a read that answered past it may still write
|
|
144
145
|
* `answers.json` for the next hook before the process exits. */
|
|
145
146
|
const ANSWERS_SETTLE_MS = 50
|
|
147
|
+
/**
|
|
148
|
+
* The host whose envoy.json this hook reads, and its mode and the mode's own arguments, from
|
|
149
|
+
* `<mode> [arguments…] [--host <claude|codex>]`. Claude Code's hooks.json names no host, so it is
|
|
150
|
+
* `claude`; the Codex plugin's names `--host codex`, so a Codex session reads the same envoy.json
|
|
151
|
+
* its MCP server and its other hook read (`sessionConfigFile`), and not `$CLAUDE_CONFIG_DIR`'s.
|
|
152
|
+
*/
|
|
153
|
+
const { host: HOST, mode, modeArguments } = parseHookArguments(process.argv.slice(2))
|
|
154
|
+
|
|
146
155
|
/** The refresher's lock, holding its pid, and what it read for the hooks, in the session's
|
|
147
156
|
* Dispatch state directory. */
|
|
148
157
|
const REFRESH_LOCK = "answers-refresh.lock"
|
|
@@ -248,7 +257,7 @@ async function openAsks(raw: unknown): Promise<void> {
|
|
|
248
257
|
const envFile = process.env["CLAUDE_ENV_FILE"]
|
|
249
258
|
// A file location that cannot be worked out hands nothing on: the open-asks summary below says
|
|
250
259
|
// why Dispatch is unavailable.
|
|
251
|
-
const chosen = sessionConfigFile(
|
|
260
|
+
const chosen = sessionConfigFile(HOST, process.env)
|
|
252
261
|
if (envFile) {
|
|
253
262
|
appendOnce(envFile, DISPATCH_HOST_LINE)
|
|
254
263
|
if (chosen.path !== null) {
|
|
@@ -334,7 +343,7 @@ function dispatchFirst(raw: unknown): void {
|
|
|
334
343
|
{ CLAUDE_PROJECT_DIR: process.env["CLAUDE_PROJECT_DIR"] },
|
|
335
344
|
input.cwd ?? process.cwd(),
|
|
336
345
|
)
|
|
337
|
-
const chosen = sessionConfigFile(
|
|
346
|
+
const chosen = sessionConfigFile(HOST, process.env)
|
|
338
347
|
if (!sessionDispatchSettings(chosen, process.env, { cwd: directory }).dispatch.enabled) return
|
|
339
348
|
const pluginRoot = configuredValue(process.env["CLAUDE_PLUGIN_ROOT"])
|
|
340
349
|
if (pluginRoot === undefined) {
|
|
@@ -437,7 +446,7 @@ async function refreshedAnswers(
|
|
|
437
446
|
}
|
|
438
447
|
const lock = join(directory, REFRESH_LOCK)
|
|
439
448
|
if (!refreshLockHeld(lock)) {
|
|
440
|
-
Bun.spawn([process.execPath, Bun.main, "answers-refresh", session, cwd], {
|
|
449
|
+
Bun.spawn([process.execPath, Bun.main, "answers-refresh", session, cwd, "--host", HOST], {
|
|
441
450
|
stdin: "ignore",
|
|
442
451
|
stdout: "ignore",
|
|
443
452
|
stderr: "ignore",
|
|
@@ -480,7 +489,7 @@ async function answersMessage(
|
|
|
480
489
|
startedAt: number,
|
|
481
490
|
by: number,
|
|
482
491
|
): Promise<{ readonly text: string | undefined; readonly notice?: string | undefined }> {
|
|
483
|
-
const file = sessionConfigFile(
|
|
492
|
+
const file = sessionConfigFile(HOST, process.env)
|
|
484
493
|
let { dispatch } = sessionDispatchSettings(file, process.env, {
|
|
485
494
|
cwd,
|
|
486
495
|
commands: "kept",
|
|
@@ -573,7 +582,7 @@ async function answersRefresh(session: string, cwd: string): Promise<never> {
|
|
|
573
582
|
const lock = join(directory, REFRESH_LOCK)
|
|
574
583
|
if (takeRefreshLock(lock)) {
|
|
575
584
|
try {
|
|
576
|
-
const file = sessionConfigFile(
|
|
585
|
+
const file = sessionConfigFile(HOST, process.env)
|
|
577
586
|
// The URL this refresher targets, resolved as the hook resolves the one it compares with and
|
|
578
587
|
// before any command runs: when envoy.json moved on since the hook started this refresher, no
|
|
579
588
|
// hook carries what it read, and when the token command fails, the hook for the same URL
|
|
@@ -600,7 +609,6 @@ async function answersRefresh(session: string, cwd: string): Promise<never> {
|
|
|
600
609
|
process.exit(0)
|
|
601
610
|
}
|
|
602
611
|
|
|
603
|
-
const [mode, ...modeArguments] = process.argv.slice(2)
|
|
604
612
|
if (mode === "answers-refresh") {
|
|
605
613
|
const [session, cwd] = modeArguments
|
|
606
614
|
if (session === undefined || cwd === undefined) {
|
package/package.json
CHANGED
package/scripts/build.ts
CHANGED
|
@@ -40,6 +40,10 @@ export const BUNDLE_ENTRYPOINTS = {
|
|
|
40
40
|
"envoy-channel": "bin/envoy-channel.ts",
|
|
41
41
|
"session-hook": "hooks/session-hook.ts",
|
|
42
42
|
"session-title-hook": "hooks/session-title-hook.ts",
|
|
43
|
+
// The Codex CLI's hooks: `codex-tool-hook` runs after every tool call, so it is a
|
|
44
|
+
// bundle of its own that imports the inbox alone, as `session-title-hook` is for each prompt.
|
|
45
|
+
"codex-hook": "hooks/codex-hook.ts",
|
|
46
|
+
"codex-tool-hook": "hooks/codex-tool-hook.ts",
|
|
43
47
|
dispatch: "../envoy-client/bin/dispatch.ts",
|
|
44
48
|
} as const
|
|
45
49
|
|
|
@@ -399,19 +403,114 @@ async function buildOut(out: string): Promise<void> {
|
|
|
399
403
|
await buildLegionPlugin(join(out, "legion"))
|
|
400
404
|
}
|
|
401
405
|
|
|
406
|
+
/** What the Codex plugin, `@sjawhar/codex-envoy`, takes from `codex/`: its npm
|
|
407
|
+
* manifest, its plugin manifest, its hooks and its README. It is a package of its own because
|
|
408
|
+
* Codex's plugin rules and Claude Code's cannot both hold in one directory: Codex's validator
|
|
409
|
+
* (`validate_plugin.py` of the `plugin-creator` skill Codex installs) refuses a manifest that
|
|
410
|
+
* names its hooks file, so its hooks must sit at `hooks/hooks.json`, which is also where Claude
|
|
411
|
+
* Code reads its own, and an npm install of a plugin reads the package's root, never a
|
|
412
|
+
* subdirectory. Measured on Codex CLI 0.154.0 and Claude Code 2.1.325. */
|
|
413
|
+
const CODEX_SOURCES = [".codex-plugin", "hooks", "package.json", "README.md"] as const
|
|
414
|
+
|
|
415
|
+
/** Each skill Claude Code may not load on its own (`disable-model-invocation: true`) and what
|
|
416
|
+
* Codex shows for it. Codex's validator refuses that field; Codex's own form of it is the skill's
|
|
417
|
+
* `agents/openai.yaml` with `policy.allow_implicit_invocation: false`, which keeps the skill out
|
|
418
|
+
* of the model's context until a person names it as `$<skill>`, and that file needs a display
|
|
419
|
+
* name and a 25-64 character description. A skill that sets the field and is not listed here
|
|
420
|
+
* fails the build, so a new one is described on purpose. */
|
|
421
|
+
export const CODEX_EXPLICIT_SKILLS: Readonly<
|
|
422
|
+
Record<string, { readonly displayName: string; readonly shortDescription: string }>
|
|
423
|
+
> = {
|
|
424
|
+
"thermonuclear-code-quality": {
|
|
425
|
+
displayName: "Thermonuclear Code Quality",
|
|
426
|
+
shortDescription: "Deep maintainability audit of a branch or PR diff",
|
|
427
|
+
},
|
|
428
|
+
"thermonuclear-deep-review": {
|
|
429
|
+
displayName: "Thermonuclear Deep Review",
|
|
430
|
+
shortDescription: "Deep correctness and security review of a diff",
|
|
431
|
+
},
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/** `SKILL.md` as Codex takes it: its `disable-model-invocation` line gone, and, when that line
|
|
435
|
+
* said `true`, the `agents/openai.yaml` that says the same thing in Codex's terms; null for a
|
|
436
|
+
* skill that sets nothing. */
|
|
437
|
+
export function codexSkill(
|
|
438
|
+
name: string,
|
|
439
|
+
source: string,
|
|
440
|
+
): { readonly skill: string; readonly openaiYaml: string | null } {
|
|
441
|
+
const match = /^---\n([\s\S]*?)\n---\n/.exec(source)
|
|
442
|
+
if (match === null) throw new Error(`skill ${name} has no frontmatter`)
|
|
443
|
+
const lines = (match[1] as string).split("\n")
|
|
444
|
+
const field = lines.find((line) => /^disable-model-invocation\s*:/.test(line))
|
|
445
|
+
if (field === undefined) return { skill: source, openaiYaml: null }
|
|
446
|
+
const value = field.slice(field.indexOf(":") + 1).trim()
|
|
447
|
+
if (value !== "true" && value !== "false") {
|
|
448
|
+
throw new Error(`skill ${name} sets disable-model-invocation to ${value}, not true or false`)
|
|
449
|
+
}
|
|
450
|
+
const kept = lines.filter((line) => line !== field)
|
|
451
|
+
const skill = `---\n${kept.join("\n")}\n---\n${source.slice(match[0].length)}`
|
|
452
|
+
if (value === "false") return { skill, openaiYaml: null }
|
|
453
|
+
const shown = CODEX_EXPLICIT_SKILLS[name]
|
|
454
|
+
if (shown === undefined) {
|
|
455
|
+
throw new Error(
|
|
456
|
+
`skill ${name} sets disable-model-invocation: true, so CODEX_EXPLICIT_SKILLS must describe it`,
|
|
457
|
+
)
|
|
458
|
+
}
|
|
459
|
+
const openaiYaml = [
|
|
460
|
+
"interface:",
|
|
461
|
+
` display_name: ${JSON.stringify(shown.displayName)}`,
|
|
462
|
+
` short_description: ${JSON.stringify(shown.shortDescription)}`,
|
|
463
|
+
"policy:",
|
|
464
|
+
" allow_implicit_invocation: false",
|
|
465
|
+
"",
|
|
466
|
+
].join("\n")
|
|
467
|
+
return { skill, openaiYaml }
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/** `out` as the Codex plugin's package: `codex/`'s files, this package's skills as Codex takes
|
|
471
|
+
* them (`codexSkill`), and `dist/` — copied from `dist` when given, the bundles a checked build
|
|
472
|
+
* already holds, else built afresh. */
|
|
473
|
+
export async function buildCodexPlugin(out: string, dist?: string): Promise<void> {
|
|
474
|
+
await mkdir(out, { recursive: true })
|
|
475
|
+
for (const source of CODEX_SOURCES) {
|
|
476
|
+
await cp(join(packageRoot, "codex", source), join(out, source), { recursive: true })
|
|
477
|
+
}
|
|
478
|
+
const skills = join(packageRoot, "skills")
|
|
479
|
+
for (const name of (await readdir(skills)).sort()) {
|
|
480
|
+
const target = join(out, "skills", name)
|
|
481
|
+
await cp(join(skills, name), target, { recursive: true, dereference: true })
|
|
482
|
+
const skillFile = join(target, "SKILL.md")
|
|
483
|
+
const { skill, openaiYaml } = codexSkill(name, await readFile(skillFile, "utf8"))
|
|
484
|
+
await writeFile(skillFile, skill)
|
|
485
|
+
if (openaiYaml !== null) {
|
|
486
|
+
await mkdir(join(target, "agents"), { recursive: true })
|
|
487
|
+
await writeFile(join(target, "agents", "openai.yaml"), openaiYaml)
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
if (dist === undefined) await buildBundles(join(out, "dist"))
|
|
491
|
+
else await cp(dist, join(out, "dist"), { recursive: true })
|
|
492
|
+
}
|
|
493
|
+
|
|
402
494
|
const USAGE =
|
|
403
|
-
"usage: bun scripts/build.ts --out <dir
|
|
404
|
-
"release.yaml's claude_envoy_build builds them
|
|
405
|
-
"to npm."
|
|
495
|
+
"usage: bun scripts/build.ts --out <dir> | --codex-out <dir> [--dist <built dist/>]. dist/ " +
|
|
496
|
+
"and legion/ are generated, never committed: release.yaml's claude_envoy_build builds them " +
|
|
497
|
+
"and packs them into the tarballs it publishes to npm."
|
|
406
498
|
|
|
407
|
-
type Mode =
|
|
499
|
+
type Mode =
|
|
500
|
+
| { readonly kind: "out"; readonly dir: string }
|
|
501
|
+
| { readonly kind: "codex-out"; readonly dir: string; readonly dist?: string }
|
|
408
502
|
|
|
409
|
-
/** The one mode `args` names, or null for none, more than one, an unknown argument, or
|
|
503
|
+
/** The one mode `args` names, or null for none, more than one, an unknown argument, or a flag
|
|
410
504
|
* with no directory after it. */
|
|
411
|
-
function parseMode(args: readonly string[]): Mode | null {
|
|
412
|
-
const
|
|
413
|
-
|
|
414
|
-
|
|
505
|
+
export function parseMode(args: readonly string[]): Mode | null {
|
|
506
|
+
const isValue = (value: string | undefined): value is string =>
|
|
507
|
+
value !== undefined && !value.startsWith("--")
|
|
508
|
+
const [first, second, third, fourth, ...rest] = args
|
|
509
|
+
if (rest.length > 0 || !isValue(second)) return null
|
|
510
|
+
if (first === "--out" && third === undefined) return { kind: "out", dir: second }
|
|
511
|
+
if (first !== "--codex-out") return null
|
|
512
|
+
if (third === undefined) return { kind: "codex-out", dir: second }
|
|
513
|
+
if (third === "--dist" && isValue(fourth)) return { kind: "codex-out", dir: second, dist: fourth }
|
|
415
514
|
return null
|
|
416
515
|
}
|
|
417
516
|
|
|
@@ -426,9 +525,14 @@ if (import.meta.main) {
|
|
|
426
525
|
}
|
|
427
526
|
const refusal = await outRefusal(mode.dir)
|
|
428
527
|
if (refusal !== null) {
|
|
429
|
-
process.stderr.write(`refusing
|
|
528
|
+
process.stderr.write(`refusing --${mode.kind}: ${refusal}\n`)
|
|
430
529
|
process.exit(1)
|
|
431
530
|
}
|
|
432
|
-
|
|
433
|
-
|
|
531
|
+
if (mode.kind === "out") {
|
|
532
|
+
await buildOut(mode.dir)
|
|
533
|
+
process.stdout.write(`built the Claude Envoy plugin into ${resolve(mode.dir)}\n`)
|
|
534
|
+
} else {
|
|
535
|
+
await buildCodexPlugin(mode.dir, mode.dist)
|
|
536
|
+
process.stdout.write(`built the Codex Envoy plugin into ${resolve(mode.dir)}\n`)
|
|
537
|
+
}
|
|
434
538
|
}
|