aiterm-steer-delivery 0.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/CHANGELOG.md +8 -0
- package/LICENSE +22 -0
- package/README.md +75 -0
- package/dist/channel.d.ts +106 -0
- package/dist/channel.js +484 -0
- package/dist/claude-receiver.d.ts +20 -0
- package/dist/claude-receiver.js +171 -0
- package/dist/cli.d.ts +4 -0
- package/dist/cli.js +98 -0
- package/dist/codex-binary.d.ts +22 -0
- package/dist/codex-binary.js +176 -0
- package/dist/codex-hook-state.d.ts +45 -0
- package/dist/codex-hook-state.js +119 -0
- package/dist/codex-hook.d.ts +2 -0
- package/dist/codex-hook.js +13 -0
- package/dist/codex-hooks.d.ts +7 -0
- package/dist/codex-hooks.js +114 -0
- package/dist/codex-receiver.d.ts +20 -0
- package/dist/codex-receiver.js +145 -0
- package/dist/codex-setup.d.ts +35 -0
- package/dist/codex-setup.js +160 -0
- package/dist/cursor-receive.d.ts +9 -0
- package/dist/cursor-receive.js +31 -0
- package/dist/cursor-receiver.d.ts +29 -0
- package/dist/cursor-receiver.js +242 -0
- package/dist/errors.d.ts +17 -0
- package/dist/errors.js +26 -0
- package/dist/files.d.ts +4 -0
- package/dist/files.js +79 -0
- package/dist/hook-main.d.ts +16 -0
- package/dist/hook-main.js +139 -0
- package/dist/hook-setup.d.ts +16 -0
- package/dist/hook-setup.js +222 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +20 -0
- package/dist/process.d.ts +17 -0
- package/dist/process.js +79 -0
- package/dist/profile.d.ts +42 -0
- package/dist/profile.js +14 -0
- package/dist/setup-node.d.ts +1 -0
- package/dist/setup-node.js +16 -0
- package/dist/windows.d.ts +13 -0
- package/dist/windows.js +76 -0
- package/package.json +28 -0
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Node以外の製品(Python等)がsteer配送を使うための入口。結果はstdoutへ1行のJSONで返す。
|
|
3
|
+
// 製品の識別情報はJSONファイル(--profile)で渡す。state_root・config_rootは絶対pathの文字列にする。
|
|
4
|
+
//
|
|
5
|
+
// aiterm-steer-delivery --profile <file> codex parent --client <name> --meta <json>
|
|
6
|
+
// aiterm-steer-delivery --profile <file> codex verify --thread <uuid> [--codex-home <dir>]
|
|
7
|
+
// aiterm-steer-delivery --profile <file> codex submit --thread <uuid> --delivery <uuid> --text-file <file|-> [--codex-home <dir>]
|
|
8
|
+
// aiterm-steer-delivery --profile <file> codex state --thread <uuid> --delivery <uuid> [--codex-home <dir>]
|
|
9
|
+
// aiterm-steer-delivery --profile <file> codex setup <enable|disable|status>
|
|
10
|
+
//
|
|
11
|
+
// codex setupは、Codexのhookから起動する入口(codex-hook.js)と製品の識別情報をhook directoryへ置いて登録する。
|
|
12
|
+
// 失敗は {ok:false, code, message, outcome_unknown} を返し、exit 1。
|
|
13
|
+
import * as fs from "node:fs";
|
|
14
|
+
import * as path from "node:path";
|
|
15
|
+
import { fileURLToPath } from "node:url";
|
|
16
|
+
import { z } from "zod";
|
|
17
|
+
import { codexHookDirectory } from "./profile.js";
|
|
18
|
+
import { realCodexHome } from "./codex-binary.js";
|
|
19
|
+
import { codexParentFromRequest, submitCodexParentAnswer, verifyCodexParent } from "./codex-receiver.js";
|
|
20
|
+
import { codexHookDeliveryState } from "./codex-hook-state.js";
|
|
21
|
+
import { configureCodexSteer } from "./codex-setup.js";
|
|
22
|
+
import { isDirectExecution } from "./hook-main.js";
|
|
23
|
+
const profileFileSchema = z.object({
|
|
24
|
+
id: z.string().regex(/^[a-z0-9-]{1,40}$/), display_name: z.string().min(1), setup_command: z.string().min(1),
|
|
25
|
+
codex_steer_command: z.string().min(1), mcp_server: z.string().min(1), dispatch_tools: z.array(z.string().min(1)),
|
|
26
|
+
state_root: z.string().refine(value => path.isAbsolute(value)), config_root: z.string().refine(value => path.isAbsolute(value)),
|
|
27
|
+
hooks: z.object({ codex: z.string().min(1), claude: z.string().min(1), cursor: z.string().min(1) }).strict(),
|
|
28
|
+
codex_client_name: z.string().min(1), codex_hook_schema: z.string().min(1), backup_suffix: z.string().min(1),
|
|
29
|
+
}).strict();
|
|
30
|
+
export function loadProfile(file) {
|
|
31
|
+
const value = profileFileSchema.parse(JSON.parse(fs.readFileSync(file, "utf8")));
|
|
32
|
+
return { ...value, state_root: () => value.state_root, config_root: () => value.config_root };
|
|
33
|
+
}
|
|
34
|
+
function option(args, name) {
|
|
35
|
+
const index = args.indexOf(name);
|
|
36
|
+
return index >= 0 ? args[index + 1] : undefined;
|
|
37
|
+
}
|
|
38
|
+
function required(args, name) {
|
|
39
|
+
const value = option(args, name);
|
|
40
|
+
if (value === undefined)
|
|
41
|
+
throw Object.assign(new Error(`${name} がありません`), { delivery_code: "CLI_USAGE" });
|
|
42
|
+
return value;
|
|
43
|
+
}
|
|
44
|
+
function parent(args) {
|
|
45
|
+
return { thread_id: z.uuid().parse(required(args, "--thread")), codex_home: path.resolve(option(args, "--codex-home") ?? realCodexHome()) };
|
|
46
|
+
}
|
|
47
|
+
async function readText(source) {
|
|
48
|
+
if (source !== "-")
|
|
49
|
+
return fs.readFileSync(source, "utf8");
|
|
50
|
+
let text = "";
|
|
51
|
+
process.stdin.setEncoding("utf8");
|
|
52
|
+
for await (const chunk of process.stdin)
|
|
53
|
+
text += chunk;
|
|
54
|
+
return text;
|
|
55
|
+
}
|
|
56
|
+
export async function runCli(argv) {
|
|
57
|
+
const profilePath = required(argv, "--profile");
|
|
58
|
+
const profile = loadProfile(profilePath);
|
|
59
|
+
const rest = argv.filter((_, index) => index !== argv.indexOf("--profile") && index !== argv.indexOf("--profile") + 1);
|
|
60
|
+
const [kind, command, ...args] = rest;
|
|
61
|
+
if (kind !== "codex")
|
|
62
|
+
throw Object.assign(new Error("対応するのは codex だけです"), { delivery_code: "CLI_USAGE" });
|
|
63
|
+
switch (command) {
|
|
64
|
+
case "parent": return { parent: codexParentFromRequest(required(args, "--client"), JSON.parse(option(args, "--meta") ?? "null")) };
|
|
65
|
+
case "verify":
|
|
66
|
+
await verifyCodexParent(profile, parent(args));
|
|
67
|
+
return { verified: true };
|
|
68
|
+
case "submit": {
|
|
69
|
+
const target = parent(args);
|
|
70
|
+
const text = await readText(required(args, "--text-file"));
|
|
71
|
+
return await submitCodexParentAnswer(profile, target, z.uuid().parse(required(args, "--delivery")), text);
|
|
72
|
+
}
|
|
73
|
+
case "state": {
|
|
74
|
+
const target = parent(args);
|
|
75
|
+
return { state: codexHookDeliveryState(target.codex_home, target.thread_id, z.uuid().parse(required(args, "--delivery")), codexHookDirectory(profile)) };
|
|
76
|
+
}
|
|
77
|
+
case "setup": {
|
|
78
|
+
const action = z.enum(["enable", "disable", "status"]).parse(args[0] ?? "status");
|
|
79
|
+
// Codexのhookが起動する入口は、hook directoryにある識別情報を読む。
|
|
80
|
+
const directory = codexHookDirectory(profile);
|
|
81
|
+
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
82
|
+
fs.copyFileSync(profilePath, path.join(directory, "profile.json"));
|
|
83
|
+
return await configureCodexSteer(profile, action, { hook: fileURLToPath(new URL("./codex-hook.js", import.meta.url)) });
|
|
84
|
+
}
|
|
85
|
+
default: throw Object.assign(new Error(`未対応のcommandです: ${command}`), { delivery_code: "CLI_USAGE" });
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
if (isDirectExecution(import.meta.url)) {
|
|
89
|
+
try {
|
|
90
|
+
process.stdout.write(JSON.stringify({ ok: true, ...await runCli(process.argv.slice(2)) }) + "\n");
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
const value = error;
|
|
94
|
+
process.stdout.write(JSON.stringify({ ok: false, code: value.delivery_code ?? (typeof value.code === "string" ? value.code : "CLI_FAILED"),
|
|
95
|
+
message: value.message ?? String(error), outcome_unknown: value.outcome_unknown === true }) + "\n");
|
|
96
|
+
process.exitCode = 1;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type ProductProfile } from "./profile.js";
|
|
2
|
+
import type { CodexHookConfig } from "./codex-hook-state.js";
|
|
3
|
+
export declare function realCodexHome(): string;
|
|
4
|
+
/** 通常のCodex CLI。CODEX_BIN、~/.local/bin/codex、PATHの順に探す。 */
|
|
5
|
+
export declare function resolveCodexExecutable(): string | null;
|
|
6
|
+
/**
|
|
7
|
+
* Desktopが同梱するCodex CLI。2026-09のChatGPT.appは`Contents/Resources/codex`から
|
|
8
|
+
* `Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex`へ移した(macbook実測)。
|
|
9
|
+
*/
|
|
10
|
+
export declare function desktopBundledCodex(app: string): string | null;
|
|
11
|
+
/** macOSの公式Codex Desktopが同梱するCLI。署名と版を確かめる。 */
|
|
12
|
+
export declare function findDesktopBinary(): string;
|
|
13
|
+
export declare function findWindowsCodexCache(resources: string, cache: string): string;
|
|
14
|
+
/** Windowsの公式Codex Desktop(MSIX)が展開したCLI。 */
|
|
15
|
+
export declare function findWindowsCodexBinary(): string;
|
|
16
|
+
export type DesktopBinaryFinder = () => string;
|
|
17
|
+
export declare function platformDesktopFinder(): DesktopBinaryFinder;
|
|
18
|
+
export declare function currentCodexDesktopBinary(profile: ProductProfile, config: CodexHookConfig, options?: {
|
|
19
|
+
directory?: string;
|
|
20
|
+
find?: DesktopBinaryFinder;
|
|
21
|
+
exists?: (file: string) => boolean;
|
|
22
|
+
}): Promise<string>;
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
// Codexの実行ファイルとCODEX_HOMEの解決。Desktopが同梱するCLIは更新のたびに場所が変わることがあるので、
|
|
2
|
+
// setupで保存した場所が消えていたら、使う時点で公式Desktopから探し直す。探せなければ理由付きで止め、別のCodexへは切り替えない。
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import * as fs from "node:fs";
|
|
6
|
+
import * as os from "node:os";
|
|
7
|
+
import * as path from "node:path";
|
|
8
|
+
import { CodexDeliveryError, SetupError } from "./errors.js";
|
|
9
|
+
import { writeHookJson } from "./files.js";
|
|
10
|
+
import { codexHookDirectory } from "./profile.js";
|
|
11
|
+
import { windowsPowerShellSync } from "./windows.js";
|
|
12
|
+
const isWin = process.platform === "win32";
|
|
13
|
+
// 実行ファイルの指定誤り。配送の受付前なので、配送のエラーではなく設定のエラーとして返す。
|
|
14
|
+
class ExecutableError extends Error {
|
|
15
|
+
code = 2;
|
|
16
|
+
}
|
|
17
|
+
export function realCodexHome() {
|
|
18
|
+
return process.env.CODEX_HOME || path.join(process.env.HOME ?? os.homedir(), ".codex");
|
|
19
|
+
}
|
|
20
|
+
function isUsableExecutableFile(candidate) {
|
|
21
|
+
try {
|
|
22
|
+
if (!fs.statSync(candidate).isFile())
|
|
23
|
+
return false;
|
|
24
|
+
if (isWin)
|
|
25
|
+
return /\.(?:exe|cmd|bat|com)$/i.test(candidate);
|
|
26
|
+
fs.accessSync(candidate, fs.constants.X_OK);
|
|
27
|
+
return true;
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function isUsableAgentExecutableFile(candidate) {
|
|
34
|
+
if (!isWin)
|
|
35
|
+
return isUsableExecutableFile(candidate);
|
|
36
|
+
if (/^[A-Za-z]:[\\/]/.test(candidate) && /\.(?:exe|com|cmd|bat)$/i.test(candidate))
|
|
37
|
+
return isUsableExecutableFile(candidate);
|
|
38
|
+
try {
|
|
39
|
+
return fs.statSync(candidate).isFile();
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function resolveWindowsCodexShim(candidate) {
|
|
46
|
+
if (!isWin || !/\.(?:cmd|bat)$/i.test(candidate))
|
|
47
|
+
return candidate;
|
|
48
|
+
const packageRoot = path.join(path.dirname(candidate), "node_modules", "@openai", "codex", "node_modules", "@openai");
|
|
49
|
+
try {
|
|
50
|
+
for (const platformPackage of fs.readdirSync(packageRoot).filter((name) => name.startsWith("codex-win32-"))) {
|
|
51
|
+
const vendorRoot = path.join(packageRoot, platformPackage, "vendor");
|
|
52
|
+
for (const target of fs.readdirSync(vendorRoot)) {
|
|
53
|
+
const executable = path.join(vendorRoot, target, "bin", "codex.exe");
|
|
54
|
+
if (isUsableExecutableFile(executable))
|
|
55
|
+
return executable;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
/* 下の明示エラーへ */
|
|
61
|
+
}
|
|
62
|
+
throw new ExecutableError(`CODEX_BIN のnpm shimからWindows native codex.exeを解決できません: ${candidate}。` +
|
|
63
|
+
"@openai/codexを再インストールするか、CODEX_BINへcodex.exeを指定してください");
|
|
64
|
+
}
|
|
65
|
+
/** 通常のCodex CLI。CODEX_BIN、~/.local/bin/codex、PATHの順に探す。 */
|
|
66
|
+
export function resolveCodexExecutable() {
|
|
67
|
+
const home = process.env.HOME ?? os.homedir();
|
|
68
|
+
const fromEnv = process.env.CODEX_BIN;
|
|
69
|
+
if (fromEnv) {
|
|
70
|
+
if (isUsableAgentExecutableFile(fromEnv))
|
|
71
|
+
return resolveWindowsCodexShim(fromEnv);
|
|
72
|
+
throw new ExecutableError(`CODEX_BIN に指定された codex が存在しません: ${fromEnv}`);
|
|
73
|
+
}
|
|
74
|
+
const fallback = path.join(home, ".local", "bin", "codex");
|
|
75
|
+
if (isUsableAgentExecutableFile(fallback))
|
|
76
|
+
return resolveWindowsCodexShim(fallback);
|
|
77
|
+
const w = spawnSync(isWin ? "where" : "which", ["codex"], { encoding: "utf8", timeout: 5000 });
|
|
78
|
+
if (w.status === 0 && (w.stdout ?? "").trim()) {
|
|
79
|
+
const found = w.stdout.trim().split(/\r?\n/).filter(Boolean);
|
|
80
|
+
const ordered = isWin
|
|
81
|
+
? [...found.filter((p) => /\.(?:exe|com|cmd|bat)$/i.test(p)), ...found.filter((p) => !/\.(?:exe|com|cmd|bat)$/i.test(p))]
|
|
82
|
+
: found;
|
|
83
|
+
for (const resolved of ordered) {
|
|
84
|
+
if (isUsableAgentExecutableFile(resolved))
|
|
85
|
+
return resolveWindowsCodexShim(resolved);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
function command(executable, args) {
|
|
91
|
+
const result = spawnSync(executable, args, { encoding: "utf8", timeout: 15_000 });
|
|
92
|
+
if (result.error || result.status !== 0)
|
|
93
|
+
throw new SetupError("codex_steer_setup_failed", `${path.basename(executable)}を実行できません`);
|
|
94
|
+
return result.stdout.trim();
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Desktopが同梱するCodex CLI。2026-09のChatGPT.appは`Contents/Resources/codex`から
|
|
98
|
+
* `Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex`へ移した(macbook実測)。
|
|
99
|
+
*/
|
|
100
|
+
export function desktopBundledCodex(app) {
|
|
101
|
+
const layouts = [
|
|
102
|
+
path.join(app, "Contents", "Resources", "codex-cli", "CodexCLI.app", "Contents", "MacOS", "codex"),
|
|
103
|
+
path.join(app, "Contents", "Resources", "codex"),
|
|
104
|
+
];
|
|
105
|
+
return layouts.find(file => fs.existsSync(file)) ?? null;
|
|
106
|
+
}
|
|
107
|
+
/** macOSの公式Codex Desktopが同梱するCLI。署名と版を確かめる。 */
|
|
108
|
+
export function findDesktopBinary() {
|
|
109
|
+
const search = spawnSync("/usr/bin/mdfind", ["kMDItemCFBundleIdentifier == 'com.openai.codex'"], { encoding: "utf8", timeout: 10_000 });
|
|
110
|
+
const candidates = [...new Set(["/Applications/Codex.app", "/Applications/ChatGPT.app", ...(search.status === 0 ? search.stdout.trim().split("\n") : [])])];
|
|
111
|
+
const found = candidates.flatMap(app => {
|
|
112
|
+
const binary = app ? desktopBundledCodex(app) : null;
|
|
113
|
+
if (!binary)
|
|
114
|
+
return [];
|
|
115
|
+
const result = spawnSync("/usr/libexec/PlistBuddy", ["-c", "Print:CFBundleIdentifier", path.join(app, "Contents", "Info.plist")], { encoding: "utf8", timeout: 5_000 });
|
|
116
|
+
return result.status === 0 && result.stdout.trim() === "com.openai.codex" ? [binary] : [];
|
|
117
|
+
});
|
|
118
|
+
if (found.length !== 1)
|
|
119
|
+
throw new SetupError("codex_desktop_not_identified", "Codex Desktopのインストール先を一つに特定できません");
|
|
120
|
+
const binary = found[0];
|
|
121
|
+
command("/usr/bin/codesign", ["--verify", "--strict", binary]);
|
|
122
|
+
const version = command(binary, ["--version"]);
|
|
123
|
+
const match = /codex-cli (\d+)\.(\d+)\.(\d+)/.exec(version);
|
|
124
|
+
if (!match || (Number(match[1]) === 0 && Number(match[2]) < 154)) {
|
|
125
|
+
throw new SetupError("codex_version_unsupported", "SteerにはCodex CLI 0.154以上を同梱したCodex Desktopが必要です");
|
|
126
|
+
}
|
|
127
|
+
return binary;
|
|
128
|
+
}
|
|
129
|
+
export function findWindowsCodexCache(resources, cache) {
|
|
130
|
+
// Desktopが展開した4実行fileを配布元と照合する。展開・更新はDesktop自身が所有する。
|
|
131
|
+
const names = ["codex.exe", "codex-code-mode-host.exe", "codex-windows-sandbox-setup.exe", "codex-command-runner.exe"];
|
|
132
|
+
const digest = (file) => createHash("sha256").update(fs.readFileSync(file)).digest("hex");
|
|
133
|
+
const expected = names.map(name => digest(path.join(resources, name)));
|
|
134
|
+
const found = (fs.existsSync(cache) ? fs.readdirSync(cache, { withFileTypes: true }) : [])
|
|
135
|
+
.filter(entry => entry.isDirectory() && !entry.isSymbolicLink() && /^[0-9a-f]{16}$/.test(entry.name))
|
|
136
|
+
.filter(entry => names.every((name, index) => {
|
|
137
|
+
const file = path.join(cache, entry.name, name);
|
|
138
|
+
return fs.existsSync(file) && digest(file) === expected[index];
|
|
139
|
+
}));
|
|
140
|
+
if (found.length !== 1)
|
|
141
|
+
throw new SetupError("codex_desktop_runtime_unavailable", "現在のCodex Desktopが展開した実行fileを特定できません。公式Desktopを起動してからsetupを再実行してください。");
|
|
142
|
+
return path.join(cache, found[0].name, "codex.exe");
|
|
143
|
+
}
|
|
144
|
+
/** Windowsの公式Codex Desktop(MSIX)が展開したCLI。 */
|
|
145
|
+
export function findWindowsCodexBinary() {
|
|
146
|
+
const resources = windowsPowerShellSync(`
|
|
147
|
+
$packages = @(Get-AppxPackage -Name OpenAI.Codex)
|
|
148
|
+
if ($packages.Count -ne 1) { throw '公式Codex Desktopを一つに特定できません' }
|
|
149
|
+
Join-Path $packages[0].InstallLocation 'app/resources'`, () => new CodexDeliveryError("CODEX_WINDOWS_OPERATION_FAILED", "WindowsのSteer設定・接続情報を確認できません"));
|
|
150
|
+
const value = findWindowsCodexCache(resources, path.join(process.env.LOCALAPPDATA ?? path.join(os.homedir(), "AppData", "Local"), "OpenAI", "Codex", "bin"));
|
|
151
|
+
const result = spawnSync(value, ["--version"], { encoding: "utf8", windowsHide: true, timeout: 10_000 });
|
|
152
|
+
if (result.error || result.status !== 0)
|
|
153
|
+
throw new SetupError("codex_binary_unavailable", "公式Codex Desktopの実行fileを起動できません。");
|
|
154
|
+
const match = /codex-cli (\d+)\.(\d+)\.(\d+)/.exec(result.stdout ?? "");
|
|
155
|
+
if (result.status !== 0 || !match || (Number(match[1]) === 0 && Number(match[2]) < 154))
|
|
156
|
+
throw new SetupError("codex_version_unsupported", "公式Codex Desktopの対応CLIを確認できません。");
|
|
157
|
+
return value;
|
|
158
|
+
}
|
|
159
|
+
export function platformDesktopFinder() {
|
|
160
|
+
return process.platform === "win32" ? findWindowsCodexBinary : findDesktopBinary;
|
|
161
|
+
}
|
|
162
|
+
export async function currentCodexDesktopBinary(profile, config, options = {}) {
|
|
163
|
+
const exists = options.exists ?? fs.existsSync;
|
|
164
|
+
if (exists(config.binary))
|
|
165
|
+
return config.binary;
|
|
166
|
+
let binary;
|
|
167
|
+
try {
|
|
168
|
+
binary = (options.find ?? platformDesktopFinder())();
|
|
169
|
+
}
|
|
170
|
+
catch (error) {
|
|
171
|
+
throw new CodexDeliveryError("CODEX_DESKTOP_BINARY_MOVED", `Codex Desktopの更新で ${config.binary} が無くなり、新しい場所も特定できません(${error instanceof Error ? error.message : String(error)})。` +
|
|
172
|
+
`Codex Desktopを起動してから ${profile.codex_steer_command} を実行してください`);
|
|
173
|
+
}
|
|
174
|
+
writeHookJson(path.join(options.directory ?? codexHookDirectory(profile), "config.json"), { ...config, binary });
|
|
175
|
+
return binary;
|
|
176
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { type ProductProfile } from "./profile.js";
|
|
3
|
+
import { type RuntimeProcess } from "./process.js";
|
|
4
|
+
import { writeHookJson } from "./files.js";
|
|
5
|
+
export { writeHookJson };
|
|
6
|
+
export declare function codexHookConfigSchema(profile: ProductProfile): z.ZodObject<{
|
|
7
|
+
schema: z.ZodLiteral<string>;
|
|
8
|
+
enabled: z.ZodBoolean;
|
|
9
|
+
codex_home: z.ZodString;
|
|
10
|
+
binary: z.ZodString;
|
|
11
|
+
command: z.ZodString;
|
|
12
|
+
node: z.ZodString;
|
|
13
|
+
hook: z.ZodString;
|
|
14
|
+
stale_processes: z.ZodArray<z.ZodObject<{
|
|
15
|
+
pid: z.ZodNumber;
|
|
16
|
+
started_identity: z.ZodString;
|
|
17
|
+
}, z.core.$strip>>;
|
|
18
|
+
}, z.core.$strict>;
|
|
19
|
+
export type CodexHookConfig = {
|
|
20
|
+
schema: string;
|
|
21
|
+
enabled: boolean;
|
|
22
|
+
codex_home: string;
|
|
23
|
+
binary: string;
|
|
24
|
+
command: string;
|
|
25
|
+
node: string;
|
|
26
|
+
hook: string;
|
|
27
|
+
stale_processes: {
|
|
28
|
+
pid: number;
|
|
29
|
+
started_identity: string;
|
|
30
|
+
}[];
|
|
31
|
+
};
|
|
32
|
+
export declare function readCodexHookConfig(profile: ProductProfile, directory?: string): CodexHookConfig | null;
|
|
33
|
+
export declare function codexInputDirectory(root: string, home: string, thread: string): string;
|
|
34
|
+
export declare const hookInputSchema: z.ZodObject<{
|
|
35
|
+
delivery_id: z.ZodUUID;
|
|
36
|
+
thread_id: z.ZodUUID;
|
|
37
|
+
text_sha256: z.ZodString;
|
|
38
|
+
}, z.core.$strict>;
|
|
39
|
+
export declare function answerDigest(text: string): string;
|
|
40
|
+
export declare function registerCodexHookInput(home: string, thread: string, id: string, text: string, root: string): void;
|
|
41
|
+
export declare function finishCodexHookSubmission(home: string, thread: string, id: string, root: string): void;
|
|
42
|
+
export declare function codexHookDeliveryState(home: string, thread: string, id: string, root: string): "sending" | "unknown" | null;
|
|
43
|
+
export declare function ownedCodexHooks(profile: ProductProfile, response: any, command: string, file: string): any[];
|
|
44
|
+
export declare function assertCodexHooksReady(profile: ProductProfile, response: any, command: string, file: string): void;
|
|
45
|
+
export declare function assertCodexHookParentCurrent(profile: ProductProfile, config: CodexHookConfig, rows?: RuntimeProcess[], pid?: number): void;
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// Codexの設定領域にはhook登録だけを置き、配送の所有情報は製品のhook directoryが保持する。
|
|
2
|
+
// 製品ごとにdirectoryが分かれるので、同じ親threadへ複数の製品が配送しても互いの入力を取り出さない。
|
|
3
|
+
import * as fs from "node:fs";
|
|
4
|
+
import * as path from "node:path";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import { CodexDeliveryError } from "./errors.js";
|
|
8
|
+
import { codexHookDirectory } from "./profile.js";
|
|
9
|
+
import { readRuntimeProcesses } from "./process.js";
|
|
10
|
+
import { writeHookJson } from "./files.js";
|
|
11
|
+
export { writeHookJson };
|
|
12
|
+
const processSchema = z.object({ pid: z.number().int(), started_identity: z.string() });
|
|
13
|
+
export function codexHookConfigSchema(profile) {
|
|
14
|
+
return z.object({
|
|
15
|
+
schema: z.literal(profile.codex_hook_schema), enabled: z.boolean(),
|
|
16
|
+
codex_home: z.string(), binary: z.string(), command: z.string(), node: z.string(), hook: z.string(),
|
|
17
|
+
stale_processes: z.array(processSchema),
|
|
18
|
+
}).strict();
|
|
19
|
+
}
|
|
20
|
+
export function readCodexHookConfig(profile, directory = codexHookDirectory(profile)) {
|
|
21
|
+
try {
|
|
22
|
+
return codexHookConfigSchema(profile).parse(JSON.parse(fs.readFileSync(path.join(directory, "config.json"), "utf8")));
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
if (error.code === "ENOENT")
|
|
26
|
+
return null;
|
|
27
|
+
throw new CodexDeliveryError("CODEX_HOOK_CONFIG_INVALID", `${profile.display_name}のCodex hook設定を読めません`);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export function codexInputDirectory(root, home, thread) {
|
|
31
|
+
z.uuid().parse(thread);
|
|
32
|
+
const hash = createHash("sha256").update(fs.realpathSync(home)).digest("hex");
|
|
33
|
+
return path.join(root, "inputs", hash, thread);
|
|
34
|
+
}
|
|
35
|
+
export const hookInputSchema = z.object({
|
|
36
|
+
delivery_id: z.uuid(), thread_id: z.uuid(), text_sha256: z.string(),
|
|
37
|
+
}).strict();
|
|
38
|
+
export function answerDigest(text) { return createHash("sha256").update(text).digest("hex"); }
|
|
39
|
+
export function registerCodexHookInput(home, thread, id, text, root) {
|
|
40
|
+
const input = hookInputSchema.parse({ delivery_id: id, thread_id: thread, text_sha256: answerDigest(text) });
|
|
41
|
+
const directory = codexInputDirectory(root, home, thread);
|
|
42
|
+
fs.mkdirSync(path.join(directory, "pending"), { recursive: true, mode: 0o700 });
|
|
43
|
+
// 一つの配送IDを別の本文で再使用しない。送信前の所有記録は再送の指示にはしない。
|
|
44
|
+
fs.writeFileSync(path.join(directory, "pending", `${id}.json`), JSON.stringify(input) + "\n", { flag: "wx", mode: 0o600 });
|
|
45
|
+
}
|
|
46
|
+
export function finishCodexHookSubmission(home, thread, id, root) {
|
|
47
|
+
const directory = codexInputDirectory(root, home, thread);
|
|
48
|
+
const file = path.join(directory, "settled", `${id}.json`);
|
|
49
|
+
writeHookJson(file, { delivery_id: id });
|
|
50
|
+
if (!fs.existsSync(path.join(directory, "pending", `${id}.json`)))
|
|
51
|
+
fs.rmSync(file, { force: true });
|
|
52
|
+
}
|
|
53
|
+
export function codexHookDeliveryState(home, thread, id, root) {
|
|
54
|
+
if (!fs.existsSync(path.join(root, "inputs")))
|
|
55
|
+
return null;
|
|
56
|
+
let value;
|
|
57
|
+
// Codex環境が見つからない時も、claimが無い時と同じく追加の状態なしとする(Aitermの挙動)。
|
|
58
|
+
try {
|
|
59
|
+
value = JSON.parse(fs.readFileSync(path.join(codexInputDirectory(root, home, thread), "claims", `${z.uuid().parse(id)}.json`), "utf8"));
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
if (error.code === "ENOENT")
|
|
63
|
+
return null;
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
// 所有権のlinkだけを作った段階では、公式キューからまだ削除していない。
|
|
67
|
+
if (hookInputSchema.safeParse(value).success)
|
|
68
|
+
return null;
|
|
69
|
+
if (value.state === "unknown")
|
|
70
|
+
return "unknown";
|
|
71
|
+
if (value.state === "deleting")
|
|
72
|
+
return readRuntimeProcesses().some(row => row.pid === value.pid && row.started_identity === value.started_identity) ? "sending" : "unknown";
|
|
73
|
+
if (["emitted", "not_in_queue"].includes(value.state))
|
|
74
|
+
return null;
|
|
75
|
+
throw new CodexDeliveryError("CODEX_HOOK_STATE_INVALID", "hookの配送状態を読めません");
|
|
76
|
+
}
|
|
77
|
+
export function ownedCodexHooks(profile, response, command, file) {
|
|
78
|
+
const rows = response?.data;
|
|
79
|
+
if (!Array.isArray(rows) || rows.length !== 1 || !Array.isArray(rows[0]?.hooks) || rows[0]?.errors?.length) {
|
|
80
|
+
throw new CodexDeliveryError("CODEX_HOOK_UNAVAILABLE", "公式APIでCodexのhook設定を読めません");
|
|
81
|
+
}
|
|
82
|
+
const source = fs.realpathSync(file);
|
|
83
|
+
const owned = rows[0].hooks.filter((hook) => hook.command === command && hook.sourcePath === source);
|
|
84
|
+
for (const event of ["postToolUse", "stop"]) {
|
|
85
|
+
const matches = owned.filter((hook) => hook.eventName === event);
|
|
86
|
+
if (matches.length !== 1 || matches[0].async || matches[0].handlerType !== "command") {
|
|
87
|
+
throw new CodexDeliveryError("CODEX_HOOK_UNAVAILABLE", `${profile.display_name}の同期hook登録を確認できません`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (owned.length !== 2)
|
|
91
|
+
throw new CodexDeliveryError("CODEX_HOOK_UNAVAILABLE", `${profile.display_name}のhook登録が重複しています`);
|
|
92
|
+
return owned;
|
|
93
|
+
}
|
|
94
|
+
export function assertCodexHooksReady(profile, response, command, file) {
|
|
95
|
+
if (ownedCodexHooks(profile, response, command, file).some(hook => !hook.enabled || !["trusted", "managed"].includes(hook.trustStatus))) {
|
|
96
|
+
throw new CodexDeliveryError("CODEX_HOOK_UNTRUSTED", `${profile.display_name}のCodex hookが無効または未承認です。${profile.setup_command}を実行してください`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
export function assertCodexHookParentCurrent(profile, config, rows, pid = process.pid) {
|
|
100
|
+
try {
|
|
101
|
+
fs.accessSync(config.node, fs.constants.X_OK);
|
|
102
|
+
fs.accessSync(config.hook, fs.constants.R_OK);
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
throw new CodexDeliveryError("CODEX_HOOK_RUNTIME_UNAVAILABLE", `Codex親hookの実行ファイルを確認できません。${profile.setup_command}を実行してください`);
|
|
106
|
+
}
|
|
107
|
+
if (!config.stale_processes.length)
|
|
108
|
+
return;
|
|
109
|
+
const processes = new Map((rows ?? readRuntimeProcesses()).map(row => [row.pid, row]));
|
|
110
|
+
const seen = new Set();
|
|
111
|
+
let current = processes.get(pid);
|
|
112
|
+
while (current && !seen.has(current.pid)) {
|
|
113
|
+
seen.add(current.pid);
|
|
114
|
+
if (config.stale_processes.some(stale => stale.pid === current.pid && stale.started_identity === current.started_identity)) {
|
|
115
|
+
throw new CodexDeliveryError("CODEX_STEER_RESTART_REQUIRED", "親のCodexはhookの導入前から動いています。完全終了して再起動してください");
|
|
116
|
+
}
|
|
117
|
+
current = processes.get(current.parent_pid);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// CLIで配送を使う製品(Python等)のCodex同期hook入口。hook directory(引数)にある製品の識別情報で動く。
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import { loadProfile } from "./cli.js";
|
|
5
|
+
import { runCodexHookMain } from "./hook-main.js";
|
|
6
|
+
const directory = process.argv[2];
|
|
7
|
+
if (!directory) {
|
|
8
|
+
process.stderr.write("CODEX_PARENT_HOOK_FAILED: hook directoryがありません\n");
|
|
9
|
+
process.exitCode = 1;
|
|
10
|
+
}
|
|
11
|
+
else {
|
|
12
|
+
await runCodexHookMain(loadProfile(path.join(directory, "profile.json")), directory);
|
|
13
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type CodexReceiverRuntime } from "./codex-receiver.js";
|
|
2
|
+
import { type ProductProfile } from "./profile.js";
|
|
3
|
+
export declare function runCodexResultHook(profile: ProductProfile, input: unknown, emit: (value: object) => Promise<void>, options?: {
|
|
4
|
+
directory?: string;
|
|
5
|
+
codex_home?: string;
|
|
6
|
+
runtime?: CodexReceiverRuntime;
|
|
7
|
+
}): Promise<void>;
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// 親の同期hookだけが、公式キューにある自製品の入力を同じターンの入力へ移す。
|
|
2
|
+
// 自製品の所有記録(pending)があり、本文のhashが一致する項目だけを取り出す。利用者や他製品の入力には触れない。
|
|
3
|
+
import * as fs from "node:fs";
|
|
4
|
+
import * as path from "node:path";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { realCodexHome, currentCodexDesktopBinary } from "./codex-binary.js";
|
|
7
|
+
import { withCodexReceiver } from "./codex-receiver.js";
|
|
8
|
+
import { CodexDeliveryError } from "./errors.js";
|
|
9
|
+
import { readRuntimeProcesses } from "./process.js";
|
|
10
|
+
import { codexHookDirectory } from "./profile.js";
|
|
11
|
+
import { answerDigest, codexInputDirectory, hookInputSchema, readCodexHookConfig, writeHookJson } from "./codex-hook-state.js";
|
|
12
|
+
export async function runCodexResultHook(profile, input, emit, options = {}) {
|
|
13
|
+
const event = z.object({ session_id: z.uuid(), turn_id: z.string().min(1),
|
|
14
|
+
hook_event_name: z.enum(["PostToolUse", "Stop"]) }).parse(input);
|
|
15
|
+
const root = options.directory ?? codexHookDirectory(profile);
|
|
16
|
+
const config = readCodexHookConfig(profile, root);
|
|
17
|
+
if (!config?.enabled) {
|
|
18
|
+
await emit({});
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
const home = options.codex_home ?? realCodexHome();
|
|
22
|
+
if (fs.realpathSync(home) !== fs.realpathSync(config.codex_home)) {
|
|
23
|
+
throw new CodexDeliveryError("CODEX_HOOK_HOME_MISMATCH", "hookと配送設定のCodex環境が一致しません");
|
|
24
|
+
}
|
|
25
|
+
const directory = codexInputDirectory(root, home, event.session_id);
|
|
26
|
+
const pending = path.join(directory, "pending");
|
|
27
|
+
if (!fs.existsSync(pending) || !fs.readdirSync(pending).length) {
|
|
28
|
+
await emit({});
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
const claims = path.join(directory, "claims");
|
|
32
|
+
fs.mkdirSync(claims, { recursive: true, mode: 0o700 });
|
|
33
|
+
const taken = [];
|
|
34
|
+
const identity = readRuntimeProcesses().find(row => row.pid === process.pid);
|
|
35
|
+
if (!identity)
|
|
36
|
+
throw new CodexDeliveryError("CODEX_HOOK_PROCESS_UNAVAILABLE", "受信hookのprocessを確認できません");
|
|
37
|
+
try {
|
|
38
|
+
await withCodexReceiver(profile, { thread_id: event.session_id, codex_home: home }, async (request) => {
|
|
39
|
+
// 削除でoffsetが動くため、全ページを読んでから取り出す。
|
|
40
|
+
const entries = [];
|
|
41
|
+
let cursor = null;
|
|
42
|
+
do {
|
|
43
|
+
const page = await request("thread/queue/list", { threadId: event.session_id, cursor, limit: 100 });
|
|
44
|
+
if (!Array.isArray(page?.data) || !(page.nextCursor === null || typeof page.nextCursor === "string")) {
|
|
45
|
+
throw new CodexDeliveryError("CODEX_HOOK_QUEUE_INVALID", "公式キューの一覧応答を認識できません");
|
|
46
|
+
}
|
|
47
|
+
entries.push(...page.data);
|
|
48
|
+
cursor = page.nextCursor;
|
|
49
|
+
} while (cursor);
|
|
50
|
+
const queued = new Set(entries.map(entry => entry.clientUserMessageId));
|
|
51
|
+
// 送信processが終了し、キューに残っていない所有記録を消す。投入中は触らない。
|
|
52
|
+
for (const name of fs.readdirSync(pending)) {
|
|
53
|
+
const ack = path.join(directory, "settled", name);
|
|
54
|
+
if (name.endsWith(".json") && !queued.has(name.slice(0, -5)) && fs.existsSync(ack)) {
|
|
55
|
+
fs.rmSync(path.join(pending, name), { force: true });
|
|
56
|
+
fs.rmSync(ack, { force: true });
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
for (const entry of entries) {
|
|
60
|
+
const id = z.uuid().safeParse(entry.clientUserMessageId);
|
|
61
|
+
if (!id.success)
|
|
62
|
+
continue;
|
|
63
|
+
const source = path.join(pending, `${id.data}.json`);
|
|
64
|
+
let owner;
|
|
65
|
+
try {
|
|
66
|
+
owner = hookInputSchema.parse(JSON.parse(fs.readFileSync(source, "utf8")));
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
if (error.code === "ENOENT")
|
|
70
|
+
continue;
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
const text = entry.input?.length === 1 && entry.input[0].type === "text" ? entry.input[0].text : undefined;
|
|
74
|
+
if (owner.delivery_id !== id.data || owner.thread_id !== event.session_id || typeof text !== "string" || answerDigest(text) !== owner.text_sha256) {
|
|
75
|
+
throw new CodexDeliveryError("CODEX_HOOK_INPUT_CHANGED", `${profile.display_name}の配送記録とキュー本文が一致しません。取り出していません`);
|
|
76
|
+
}
|
|
77
|
+
const file = path.join(claims, `${id.data}.json`);
|
|
78
|
+
// 同時hookが同じ回答を取り出すことを防ぎ、中断したclaimは自動再送しない。
|
|
79
|
+
try {
|
|
80
|
+
fs.linkSync(source, file);
|
|
81
|
+
fs.unlinkSync(source);
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
if (["ENOENT", "EEXIST"].includes(error.code ?? ""))
|
|
85
|
+
continue;
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
fs.rmSync(path.join(directory, "settled", `${id.data}.json`), { force: true });
|
|
89
|
+
const item = { file, delivery_id: id.data, text };
|
|
90
|
+
taken.push(item);
|
|
91
|
+
writeHookJson(file, { ...owner, text, state: "deleting", turn_id: event.turn_id, queued_submission_id: entry.id,
|
|
92
|
+
pid: identity.pid, started_identity: identity.started_identity });
|
|
93
|
+
const result = await request("thread/queue/delete", { threadId: event.session_id, queuedSubmissionId: entry.id });
|
|
94
|
+
if (typeof result?.deleted !== "boolean")
|
|
95
|
+
throw new CodexDeliveryError("CODEX_HOOK_QUEUE_INVALID", "キュー削除の結果を確認できません", true);
|
|
96
|
+
if (!result.deleted) {
|
|
97
|
+
writeHookJson(file, { ...owner, state: "not_in_queue", turn_id: event.turn_id });
|
|
98
|
+
taken.pop();
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}, options.runtime ?? { executable: await currentCodexDesktopBinary(profile, config, { directory: root }), timeout_ms: 5_000 });
|
|
102
|
+
const text = taken.map(item => item.text).join("\n\n");
|
|
103
|
+
await emit(!taken.length ? {} : event.hook_event_name === "Stop"
|
|
104
|
+
? { decision: "block", reason: text }
|
|
105
|
+
: { hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: text } });
|
|
106
|
+
for (const item of taken)
|
|
107
|
+
writeHookJson(item.file, { delivery_id: item.delivery_id, state: "emitted", turn_id: event.turn_id, text: item.text });
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
for (const item of taken)
|
|
111
|
+
writeHookJson(item.file, { delivery_id: item.delivery_id, state: "unknown", turn_id: event.turn_id, text: item.text });
|
|
112
|
+
throw error;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type ProductProfile } from "./profile.js";
|
|
2
|
+
export interface CodexParent {
|
|
3
|
+
thread_id: string;
|
|
4
|
+
codex_home: string;
|
|
5
|
+
}
|
|
6
|
+
/** modelの引数ではなく、CodexがMCP要求へ付けるmetadataだけを宛先にする。 */
|
|
7
|
+
export declare function codexParentFromRequest(clientName: string | undefined, metadata: unknown): CodexParent | null;
|
|
8
|
+
export interface CodexReceiverRuntime {
|
|
9
|
+
executable?: string;
|
|
10
|
+
args?: string[];
|
|
11
|
+
timeout_ms?: number;
|
|
12
|
+
hook_directory?: string;
|
|
13
|
+
}
|
|
14
|
+
export declare function withCodexReceiver<T>(profile: ProductProfile, parent: CodexParent, action: (request: (method: string, params: unknown) => Promise<any>) => Promise<T>, runtime?: CodexReceiverRuntime): Promise<T>;
|
|
15
|
+
/** 送る前に、同じstoreの宛先と公式キューの対応を確認する。本文は保存・表示しない。 */
|
|
16
|
+
export declare function verifyCodexParent(profile: ProductProfile, parent: CodexParent, runtime?: CodexReceiverRuntime): Promise<void>;
|
|
17
|
+
/** 確定した本文を公式キューへ一度だけ入れる。受付IDを返す。受付の成否が不明な失敗はoutcome_unknownで区別する。 */
|
|
18
|
+
export declare function submitCodexParentAnswer(profile: ProductProfile, parent: CodexParent, deliveryId: string, text: string, runtime?: CodexReceiverRuntime): Promise<{
|
|
19
|
+
queued_submission_id: string | null;
|
|
20
|
+
}>;
|