aiterm-steer-delivery 0.2.3 → 0.3.1

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 CHANGED
@@ -1,5 +1,26 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.1
4
+
5
+ Codexの設定と起動の、2つの弱さを直します。APIと記録の形は変わりません。
6
+
7
+ - **登録の間に終わったCodexを、再起動待ちの記録(`stale_processes`)へ残さない。** `configureCodexSteer(profile, "enable", …)`は、登録より前から動いているCodexを再起動待ちとして記録する。ほかの導入が設定のために一時的に起こしたCodex(公式App Serverを起こして止める形)が、止まり切る前のprocessの一覧に載り、記録へ残っていた。承認の確かめの後にもう一度一覧を取り、居なくなった物を外してから保存する。返す状態(`ready`/`restart_required`)も、その同じ一覧で決める。
8
+ - 居ないprocessは、今までも照合で当たらない(pidと開始時刻の組で見る)。記録に残るだけで、配送は止まっていなかった。
9
+ - **Codexを起こす時、PATHにこのprocessのnodeの場所が無ければ足す。** npm版のCodexは、nodeで動く起動役(1行目が`#!/usr/bin/env node`)で、起こす側のPATHにnodeの場所が無いと起きない(exit 127)。素のsshの環境、製品の常駐process、アプリ配下のprocessから`withCodexReceiver`を呼ぶと、`CODEX_RECEIVER_TRANSPORT_FAILED`で断っていた。本文は送られていなかった。
10
+ - `withCodexReceiver`と、Codexの版を確かめる所が、起こす環境のPATHの頭へnodeの場所を足す。既にあれば、並びも中身も変えない。渡した`env`そのものは書き換えない。
11
+ - 同じ形の環境を自分で作る製品のために、`codexSpawnEnv(env?)`を公開する。
12
+ - Desktop同梱のCodex(macOS・Windows)は、元から当たらない。
13
+
14
+ ## 0.3.0
15
+
16
+ Codexの親へ、製品のhookを登録せずに届ける入口を足します。今までのAPIと記録の形は変わりません。
17
+
18
+ - **Aitermの親配送へ頼む入口を公開する。** `verifyCodexParentViaAiterm(parent)`・`submitCodexParentAnswerViaAiterm(parent, deliveryId, text)`・`codexDeliveryStateViaAiterm(parent, deliveryId)`・`codexDeliveryDetailViaAiterm(parent, deliveryId)`・`findAitermDeliveryProvider()`。Aiterm(0.56.0以上)が持つ命令`aiterm-parent-delivery`を探して呼ぶ。届けるのはAitermが登録したhookと公式キューで、製品はCodex用のhookを持たず、Aitermの置き場のfileも書かない。
19
+ - 設定・受付・実際に届いた事を分けて返す。`verify`の`steer`は設定(`enabled`=hookが登録・承認済みで親がhookの導入後に起きている、`disabled`=公式キューだけ)。`submit`は公式キューの受付。届き方は`codexDeliveryDetailViaAiterm`(`hook: "emitted"`と`turn_id`=hookがその番へ本文を入れた、`queued`=今も公式キューにあるか)。
20
+ - 失敗は今までどおり`CodexDeliveryError`(`delivery_code`・`outcome_unknown`)。Aitermの命令が見つからない・古い・返りを読めない時は`AITERM_PROVIDER_UNAVAILABLE`で断り、ほかの届け方へ切り替えない。本文を渡した後に返りを読めなかった時だけ`outcome_unknown`が真になる。
21
+ - 命令は、引数`cli`・環境変数`AITERM_PARENT_DELIVERY_CLI`、`aiterm-setup`が残す`~/.config/aiterm-mcp/delivery-provider.json`、`PATH`の順に探す。明示した場所が使えない時は、別の場所へ移らない。
22
+ - 製品が前に登録したCodexのhookを外す入口は、今までの`configureCodexSteer(profile, "disable", { hook })`。変えていない。
23
+
3
24
  ## 0.2.3
4
25
 
5
26
  - **`discardClaudeHookRequest`を公開する。** 製品が、toolの返りを誤り(`isError`)にする時に、返す前に呼ぶ。その呼び出しの置き場(`<state_root>/claude-parent-hooks/<tool_use_id>/`)を消し、消したかを返す。Claude Codeは誤りの返りで`PostToolUse`を走らせないので、配送の無い呼び出しの片付けが走らず、`request.json`だけの置き場が1日後の見回りまで残っていた(連携元の本番で、引数の検査で断った呼び出しの置き場が残っているのを見た。Claude Code 2.1.291)。
package/README.ja.md CHANGED
@@ -147,6 +147,22 @@ Claude Code は `claudeParentFromRequest`/`bindClaudeParentDelivery`/`submit
147
147
 
148
148
  Claude Code は、ツールの返りが誤り(`isError`)の時に `PostToolUse` の hook を走らせません。誤りで返す時は、返す前に `discardClaudeHookRequest(clientName, request.params._meta, claudeHookRoot(PROFILE))` を呼び、その呼び出しの置き場を消します。配送を結んだ置き場は消しません。呼ばなくても、残った置き場は1日後に次の依頼の hook が消します。
149
149
 
150
+ **Codex の親へ、製品の hook を登録せずに届ける**(Aiterm の親配送へ頼む):
151
+
152
+ Aiterm(0.56.0 以上)を導入済みの端末では、製品は Codex 用の hook を持たずに、確定した本文を Aiterm へ渡せます。Aiterm が登録した hook と公式キューで届きます。製品は Aiterm の置き場のファイルを書きません。
153
+
154
+ ```js
155
+ const parent = steer.codexParentFromRequest(clientName, request.params._meta);
156
+ const { steer: mode } = await steer.verifyCodexParentViaAiterm(parent); // "enabled" | "disabled"
157
+ await steer.submitCodexParentAnswerViaAiterm(parent, randomUUID(), text); // 配送IDは本文ごとに新しいUUID
158
+ await steer.codexDeliveryDetailViaAiterm(parent, deliveryId); // { state, hook, turn_id, queued }
159
+ ```
160
+
161
+ - 3つを分けて返します。`verify` の `steer` は設定の話です(`enabled` = Aiterm の hook が登録・承認済みで、親が hook の導入後に起きている。`disabled` = 公式キューだけで、ターンが終わってから届く)。`submit` の返りは公式キューの受付です。実際に届いたかは `codexDeliveryDetailViaAiterm` で読みます(`hook: "emitted"` と `turn_id` = Aiterm の hook がそのターンへ本文を入れた。`queued` = 今も公式キューに残っているか)。
162
+ - 失敗は今までどおり `CodexDeliveryError` です(`delivery_code`・`outcome_unknown`)。Aiterm が返した理由をそのまま写します。Aiterm の命令が見つからない・古い・返りを読めない時は `AITERM_PROVIDER_UNAVAILABLE` で、ほかの届け方へは切り替えません。同じ配送IDをもう一度渡すと `PARENT_DELIVERY_DUPLICATE` で断ります。
163
+ - Aiterm の命令(`aiterm-parent-delivery`)は、引数 `cli`・環境変数 `AITERM_PARENT_DELIVERY_CLI`、`aiterm-setup` が残す `~/.config/aiterm-mcp/delivery-provider.json`、`PATH` の順に探します。`findAitermDeliveryProvider()` で見つかった場所を確かめられます。
164
+ - 製品が前に登録した Codex の hook は、`configureCodexSteer(PROFILE, "disable", { hook })` で外します。後ろにある他の hook の承認は新しい位置へ写します。
165
+
150
166
  **同じ会話へ何通も送る**(channel。例: Peertable がルームの発言を親へ届ける):
151
167
 
152
168
  ```js
package/README.md CHANGED
@@ -147,6 +147,22 @@ Claude Code and Cursor follow the same shape with `claudeParentFromRequest` / `b
147
147
 
148
148
  Claude Code does not run the `PostToolUse` hook when a tool result is an error (`isError`). When you return an error, call `discardClaudeHookRequest(clientName, request.params._meta, claudeHookRoot(PROFILE))` before returning, to remove that call's request directory. A directory with a bound delivery is kept. If you do not call it, the next request's hook removes the leftover after one day.
149
149
 
150
+ **Deliver to a Codex parent without registering product hooks** (ask Aiterm's parent delivery):
151
+
152
+ On a machine with Aiterm (0.56.0 or later) installed, a product can hand a final answer to Aiterm instead of owning Codex hooks. Aiterm's registered hooks and the official queue deliver it. The product never writes Aiterm's files.
153
+
154
+ ```js
155
+ const parent = steer.codexParentFromRequest(clientName, request.params._meta);
156
+ const { steer: mode } = await steer.verifyCodexParentViaAiterm(parent); // "enabled" | "disabled"
157
+ await steer.submitCodexParentAnswerViaAiterm(parent, randomUUID(), text); // a fresh UUID per message
158
+ await steer.codexDeliveryDetailViaAiterm(parent, deliveryId); // { state, hook, turn_id, queued }
159
+ ```
160
+
161
+ - Three things are reported separately. `steer` from `verify` is about configuration (`enabled`: Aiterm's hooks are registered and trusted, and the parent started after they were installed; `disabled`: official queue only, so the text arrives after the turn ends). The result of `submit` is the queue's acceptance. Actual arrival is read with `codexDeliveryDetailViaAiterm` (`hook: "emitted"` with `turn_id`: Aiterm's hook put the text into that turn; `queued`: whether it is still in the official queue).
162
+ - Failures are `CodexDeliveryError` as before (`delivery_code`, `outcome_unknown`), carrying the reason Aiterm returned. When Aiterm's command is missing, too old, or returns something unreadable, the error is `AITERM_PROVIDER_UNAVAILABLE`; there is no fallback to another route. Reusing a delivery id is refused with `PARENT_DELIVERY_DUPLICATE`.
163
+ - Aiterm's command (`aiterm-parent-delivery`) is located from the `cli` option or `AITERM_PARENT_DELIVERY_CLI`, then `~/.config/aiterm-mcp/delivery-provider.json` written by `aiterm-setup`, then `PATH`. `findAitermDeliveryProvider()` shows what was found.
164
+ - Remove Codex hooks a product registered earlier with `configureCodexSteer(PROFILE, "disable", { hook })`. Trust for other hooks that move is copied to their new positions.
165
+
150
166
  **Many messages to one conversation** (channels, e.g. Peertable's room messages to the parent):
151
167
 
152
168
  ```js
@@ -0,0 +1,54 @@
1
+ import type { CodexParent, CodexParentThread } from "./codex-receiver.js";
2
+ export declare const AITERM_PARENT_DELIVERY_SCHEMA = "aiterm.parent-delivery.v1";
3
+ export declare const AITERM_DELIVERY_PROVIDER_SCHEMA = "aiterm.delivery-provider.v1";
4
+ export type AitermDeliveryProvider = {
5
+ /** 命令を動かすnodeの絶対path。 */
6
+ node: string;
7
+ /** aiterm-parent-deliveryの本体(.js)の絶対path。 */
8
+ cli: string;
9
+ /** 記録にあるAitermの版。記録以外から見つけた時はnull。 */
10
+ version: string | null;
11
+ /** 見つけた道。explicit=引数か環境変数、record=aiterm-setupの記録、path=PATH。 */
12
+ source: "explicit" | "record" | "path";
13
+ };
14
+ export type AitermProviderOptions = {
15
+ /** aiterm-parent-deliveryの本体の絶対path。省略時は環境変数 AITERM_PARENT_DELIVERY_CLI、記録、PATHの順に探す。 */
16
+ cli?: string;
17
+ /** 命令を動かすnode。省略時は記録のnode、無ければこのprocessのnode。 */
18
+ node?: string;
19
+ /** 探す時と命令を起こす時の環境。省略時はこのprocessの環境。 */
20
+ env?: NodeJS.ProcessEnv;
21
+ /** 記録を探すhome。省略時は環境のHOME。 */
22
+ home?: string;
23
+ /** 命令1回の上限。省略時は90秒。 */
24
+ timeout_ms?: number;
25
+ };
26
+ /** Aitermの命令を探す。見つからなければnull。何も起こさず、何も書かない。 */
27
+ export declare function findAitermDeliveryProvider(options?: AitermProviderOptions): AitermDeliveryProvider | null;
28
+ /**
29
+ * 親を確かめる。steerは設定の話で、enabled=Aitermのhookが登録・承認済みで親がhookの導入後に起きている(動いている番へ同じ番で渡せる)、
30
+ * disabled=公式キューだけ(番が終わってから届く)。届いた事は言わない。
31
+ */
32
+ export declare function verifyCodexParentViaAiterm(parent: CodexParent, options?: AitermProviderOptions): Promise<{
33
+ thread: CodexParentThread;
34
+ steer: "enabled" | "disabled";
35
+ }>;
36
+ /** 確定した本文を、Aitermの親配送へ一度だけ頼む。deliveryIdは本文ごとに新しいUUID。受け付けたか分からない失敗はoutcome_unknownで区別する。 */
37
+ export declare function submitCodexParentAnswerViaAiterm(parent: CodexParent, deliveryId: string, text: string, options?: AitermProviderOptions): Promise<{
38
+ queued_submission_id: string | null;
39
+ }>;
40
+ export type AitermDeliveryDetail = {
41
+ /** 送る途中の状態。sending=hookが取り出している最中、unknown=取り出しの結果が分からない、null=どちらでもない。 */
42
+ state: "sending" | "unknown" | null;
43
+ /** Aitermのhookの記録。pending=受け付けて未投入、emitted=turn_idの番へ入れた、not_in_queue=公式キューが先に会話へ渡した、null=記録なし。 */
44
+ hook: "pending" | "sending" | "emitted" | "not_in_queue" | "unknown" | null;
45
+ /** hookが本文を入れた番(hookがemittedの時だけ)。 */
46
+ turn_id: string | null;
47
+ /** 今も公式キューに残っているか。確かめられなかった時はnull。 */
48
+ queued: boolean | null;
49
+ queue_error?: string;
50
+ };
51
+ /** 届き方の事実を読む。受け付けた事と、実際に番へ入った事を分けて返す。 */
52
+ export declare function codexDeliveryDetailViaAiterm(parent: CodexParent, deliveryId: string, options?: AitermProviderOptions): Promise<AitermDeliveryDetail>;
53
+ /** 送る途中の状態だけを返す(`codexHookDeliveryState`と同じ値)。 */
54
+ export declare function codexDeliveryStateViaAiterm(parent: CodexParent, deliveryId: string, options?: AitermProviderOptions): Promise<"sending" | "unknown" | null>;
@@ -0,0 +1,129 @@
1
+ // Aitermの親配送へ頼む。製品は自分のhookを登録せず、確定した回答と親の指定をAitermへ渡す。
2
+ // 渡す相手は、Aitermが持つ命令 aiterm-parent-delivery(Aiterm 0.56.0以上)。Aitermが登録したhookと公式キューで届ける。
3
+ // Aitermの置き場のfileは、この入口からは書かない。読むのは、命令の場所の記録(aiterm-setupが残す delivery-provider.json)だけ。
4
+ import { spawn } from "node:child_process";
5
+ import * as fs from "node:fs";
6
+ import * as os from "node:os";
7
+ import * as path from "node:path";
8
+ import { z } from "zod";
9
+ import { CodexDeliveryError } from "./errors.js";
10
+ export const AITERM_PARENT_DELIVERY_SCHEMA = "aiterm.parent-delivery.v1";
11
+ export const AITERM_DELIVERY_PROVIDER_SCHEMA = "aiterm.delivery-provider.v1";
12
+ const recordSchema = z.object({
13
+ schema: z.literal(AITERM_DELIVERY_PROVIDER_SCHEMA), version: z.string().min(1),
14
+ node: z.string().refine(value => path.isAbsolute(value)), cli: z.string().refine(value => path.isAbsolute(value)),
15
+ }).strict();
16
+ const isFile = (file) => { try {
17
+ return fs.statSync(file).isFile();
18
+ }
19
+ catch {
20
+ return false;
21
+ } };
22
+ /** Aitermの命令を探す。見つからなければnull。何も起こさず、何も書かない。 */
23
+ export function findAitermDeliveryProvider(options = {}) {
24
+ const env = options.env ?? process.env;
25
+ const explicit = options.cli ?? env.AITERM_PARENT_DELIVERY_CLI;
26
+ if (explicit) {
27
+ // 明示した場所が使えない時に、別の場所へ黙って移らない。
28
+ return path.isAbsolute(explicit) && isFile(explicit) ? { node: options.node ?? process.execPath, cli: explicit, version: null, source: "explicit" } : null;
29
+ }
30
+ const home = options.home ?? env.HOME ?? os.homedir();
31
+ try {
32
+ const record = recordSchema.parse(JSON.parse(fs.readFileSync(path.join(home, ".config", "aiterm-mcp", "delivery-provider.json"), "utf8")));
33
+ const node = options.node ?? record.node;
34
+ if (isFile(record.cli) && isFile(node))
35
+ return { node, cli: record.cli, version: record.version, source: "record" };
36
+ }
37
+ catch { /* 記録が無い・読めない・古い時は、PATHを探す */ }
38
+ for (const directory of (env.PATH ?? env.Path ?? "").split(path.delimiter).filter(Boolean)) {
39
+ if (process.platform === "win32") {
40
+ // npmのshim(.cmd)と同じ場所のnode_modulesに本体がある。
41
+ const cli = path.join(directory, "node_modules", "aiterm-mcp", "dist", "parent-delivery-cli.js");
42
+ if (isFile(path.join(directory, "aiterm-parent-delivery.cmd")) && isFile(cli))
43
+ return { node: options.node ?? process.execPath, cli, version: null, source: "path" };
44
+ continue;
45
+ }
46
+ const shim = path.join(directory, "aiterm-parent-delivery");
47
+ if (!isFile(shim))
48
+ continue;
49
+ try {
50
+ return { node: options.node ?? process.execPath, cli: fs.realpathSync(shim), version: null, source: "path" };
51
+ }
52
+ catch { /* 壊れたlinkは飛ばす */ }
53
+ }
54
+ return null;
55
+ }
56
+ const unavailable = (message, outcomeUnknown = false) => new CodexDeliveryError("AITERM_PROVIDER_UNAVAILABLE", message, outcomeUnknown);
57
+ /** 命令を1回起こし、stdoutの最後の1行のJSONを返す。sendsは、本文を渡す呼び出しか(返りを読めなかった時、受け付けたか分からないと数える)。 */
58
+ async function callAiterm(args, input, options, sends) {
59
+ const provider = findAitermDeliveryProvider(options);
60
+ if (!provider) {
61
+ throw unavailable("Aitermの配送の入口(aiterm-parent-delivery)が見つかりません。Aiterm 0.56.0以上を導入し、aiterm-setupを実行してください。本文は送っていません");
62
+ }
63
+ const result = await new Promise(resolve => {
64
+ let stdout = "";
65
+ let started = false;
66
+ let settled = false;
67
+ const finish = (failure) => { if (settled)
68
+ return; settled = true; clearTimeout(timer); resolve({ stdout, started, failure }); };
69
+ const child = spawn(provider.node, [provider.cli, ...args], { stdio: ["pipe", "pipe", "ignore"], env: options.env ?? process.env, windowsHide: true });
70
+ const timer = setTimeout(() => { child.kill("SIGKILL"); finish("時間内に返りがありません"); }, options.timeout_ms ?? 90_000);
71
+ child.once("spawn", () => { started = true; });
72
+ child.once("error", (error) => finish(`起動できません(${error.code ?? "unknown"})`));
73
+ child.stdout.setEncoding("utf8").on("data", chunk => { stdout += chunk; });
74
+ child.stdin.on("error", () => { });
75
+ child.once("close", () => finish(null));
76
+ child.stdin.end(input ?? "");
77
+ });
78
+ if (result.failure)
79
+ throw unavailable(`Aitermの配送の入口を呼べません: ${result.failure}`, sends && result.started);
80
+ let value;
81
+ try {
82
+ value = JSON.parse(result.stdout.split("\n").filter(Boolean).at(-1) ?? "");
83
+ }
84
+ catch {
85
+ throw unavailable("Aitermの配送の入口が、読めない返りを出しました", sends);
86
+ }
87
+ if (value?.schema !== AITERM_PARENT_DELIVERY_SCHEMA || typeof value.ok !== "boolean") {
88
+ throw unavailable("Aitermの配送の入口の返りの形が合いません。Aitermを更新してください", sends);
89
+ }
90
+ if (!value.ok) {
91
+ const code = typeof value.code === "string" ? value.code : "AITERM_PROVIDER_FAILED";
92
+ const message = typeof value.message === "string" ? value.message : "Aitermが配送を断りました";
93
+ // Aitermの文面は「理由の符号: 文」の形で来る。符号を二重に付けない。
94
+ throw new CodexDeliveryError(code, message.startsWith(`${code}: `) ? message.slice(code.length + 2) : message, value.outcome_unknown === true);
95
+ }
96
+ return value;
97
+ }
98
+ const target = (parent) => ["--thread", parent.thread_id, "--codex-home", parent.codex_home];
99
+ /**
100
+ * 親を確かめる。steerは設定の話で、enabled=Aitermのhookが登録・承認済みで親がhookの導入後に起きている(動いている番へ同じ番で渡せる)、
101
+ * disabled=公式キューだけ(番が終わってから届く)。届いた事は言わない。
102
+ */
103
+ export async function verifyCodexParentViaAiterm(parent, options = {}) {
104
+ const value = await callAiterm(["codex", "verify", ...target(parent)], null, options, false);
105
+ if (value.verified !== true || typeof value.thread?.thread_id !== "string" || !["enabled", "disabled"].includes(value.steer)) {
106
+ throw unavailable("Aitermの配送の入口の返りの形が合いません。Aitermを更新してください");
107
+ }
108
+ return { thread: value.thread, steer: value.steer };
109
+ }
110
+ /** 確定した本文を、Aitermの親配送へ一度だけ頼む。deliveryIdは本文ごとに新しいUUID。受け付けたか分からない失敗はoutcome_unknownで区別する。 */
111
+ export async function submitCodexParentAnswerViaAiterm(parent, deliveryId, text, options = {}) {
112
+ z.uuid().parse(deliveryId);
113
+ const value = await callAiterm(["codex", "submit", ...target(parent), "--delivery", deliveryId, "--text-file", "-"], text, options, true);
114
+ if (!(value.queued_submission_id === null || typeof value.queued_submission_id === "string")) {
115
+ throw unavailable("Aitermの配送の入口の返りの形が合いません。Aitermを更新してください", true);
116
+ }
117
+ return { queued_submission_id: value.queued_submission_id };
118
+ }
119
+ /** 届き方の事実を読む。受け付けた事と、実際に番へ入った事を分けて返す。 */
120
+ export async function codexDeliveryDetailViaAiterm(parent, deliveryId, options = {}) {
121
+ z.uuid().parse(deliveryId);
122
+ const value = await callAiterm(["codex", "state", ...target(parent), "--delivery", deliveryId], null, options, false);
123
+ return { state: value.state ?? null, hook: value.hook ?? null, turn_id: value.turn_id ?? null, queued: value.queued ?? null,
124
+ ...(typeof value.queue_error === "string" ? { queue_error: value.queue_error } : {}) };
125
+ }
126
+ /** 送る途中の状態だけを返す(`codexHookDeliveryState`と同じ値)。 */
127
+ export async function codexDeliveryStateViaAiterm(parent, deliveryId, options = {}) {
128
+ return (await codexDeliveryDetailViaAiterm(parent, deliveryId, options)).state;
129
+ }
@@ -3,6 +3,12 @@ import type { CodexHookConfig } from "./codex-hook-state.js";
3
3
  export declare function realCodexHome(): string;
4
4
  /** 通常のCodex CLI。CODEX_BIN、~/.local/bin/codex、PATHの順に探す。 */
5
5
  export declare function resolveCodexExecutable(): string | null;
6
+ /**
7
+ * Codexを起こす時の環境。npm版のCodexは、nodeで動く起動役(1行目が`#!/usr/bin/env node`)で、起こす側のPATHにnodeの場所が
8
+ * 無いと起きない(exit 127。素のsshの環境、製品の常駐process、アプリ配下のprocessはPATHが細い事がある)。
9
+ * このprocessを動かしているnodeの場所を、PATHに無い時だけ頭へ足した写しを返す。既にあれば、並びも中身も変えない。
10
+ */
11
+ export declare function codexSpawnEnv(env?: NodeJS.ProcessEnv, node?: string, platform?: NodeJS.Platform): NodeJS.ProcessEnv;
6
12
  /**
7
13
  * Desktopが同梱するCodex CLI。2026-09のChatGPT.appは`Contents/Resources/codex`から
8
14
  * `Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex`へ移した(macbook実測)。
@@ -87,8 +87,23 @@ export function resolveCodexExecutable() {
87
87
  }
88
88
  return null;
89
89
  }
90
+ /**
91
+ * Codexを起こす時の環境。npm版のCodexは、nodeで動く起動役(1行目が`#!/usr/bin/env node`)で、起こす側のPATHにnodeの場所が
92
+ * 無いと起きない(exit 127。素のsshの環境、製品の常駐process、アプリ配下のprocessはPATHが細い事がある)。
93
+ * このprocessを動かしているnodeの場所を、PATHに無い時だけ頭へ足した写しを返す。既にあれば、並びも中身も変えない。
94
+ */
95
+ export function codexSpawnEnv(env = process.env, node = process.execPath, platform = process.platform) {
96
+ const windows = platform === "win32";
97
+ // Windowsの環境変数名は大文字小文字を区別しない(`Path`で入っている事が多い)。
98
+ const key = Object.keys(env).find(name => windows ? name.toLowerCase() === "path" : name === "PATH") ?? "PATH";
99
+ const delimiter = windows ? ";" : ":";
100
+ const directory = (windows ? path.win32 : path.posix).dirname(node);
101
+ const current = env[key] ?? "";
102
+ const listed = current.split(delimiter).some(part => windows ? part.toLowerCase() === directory.toLowerCase() : part === directory);
103
+ return listed ? env : { ...env, [key]: current ? `${directory}${delimiter}${current}` : directory };
104
+ }
90
105
  function command(executable, args) {
91
- const result = spawnSync(executable, args, { encoding: "utf8", timeout: 15_000 });
106
+ const result = spawnSync(executable, args, { encoding: "utf8", timeout: 15_000, env: codexSpawnEnv() });
92
107
  if (result.error || result.status !== 0)
93
108
  throw new SetupError("codex_steer_setup_failed", `${path.basename(executable)}を実行できません`);
94
109
  return result.stdout.trim();
@@ -158,7 +173,7 @@ Join-Path $packages[0].InstallLocation 'app/resources'`, () => new CodexDelivery
158
173
  }
159
174
  /** CLIが対応する最低版(公式キューとhookの取込み)。 */
160
175
  function assertSteerVersion(executable, subject) {
161
- const result = spawnSync(executable, ["--version"], { encoding: "utf8", windowsHide: true, timeout: 15_000 });
176
+ const result = spawnSync(executable, ["--version"], { encoding: "utf8", windowsHide: true, timeout: 15_000, env: codexSpawnEnv() });
162
177
  if (result.error || result.status !== 0)
163
178
  throw new SetupError("codex_binary_unavailable", `${subject}を起動できません`);
164
179
  const match = /codex-cli (\d+)\.(\d+)\.(\d+)/.exec(result.stdout ?? "");
@@ -10,7 +10,10 @@ export interface CodexReceiverRuntime {
10
10
  args?: string[];
11
11
  timeout_ms?: number;
12
12
  hook_directory?: string;
13
- /** App Serverを起こす環境。省略すると、このprocessの環境。`CODEX_HOME`は常に`parent.codex_home`で上書きする。 */
13
+ /**
14
+ * App Serverを起こす環境。省略すると、このprocessの環境。`CODEX_HOME`は常に`parent.codex_home`で上書きする。
15
+ * PATHにこのprocessのnodeの場所が無い時は、頭へ足す(nodeで動くCodexの起動役を起こすため)。
16
+ */
14
17
  env?: NodeJS.ProcessEnv;
15
18
  }
16
19
  export declare function withCodexReceiver<T>(profile: ProductProfile, parent: CodexParent, action: (request: (method: string, params: unknown) => Promise<any>) => Promise<T>, runtime?: CodexReceiverRuntime): Promise<T>;
@@ -5,7 +5,7 @@ import { createInterface } from "node:readline";
5
5
  import * as path from "node:path";
6
6
  import { CodexDeliveryError } from "./errors.js";
7
7
  import { codexHookDirectory } from "./profile.js";
8
- import { currentCodexDesktopBinary, realCodexHome, resolveCodexExecutable } from "./codex-binary.js";
8
+ import { codexSpawnEnv, currentCodexDesktopBinary, realCodexHome, resolveCodexExecutable } from "./codex-binary.js";
9
9
  import { finishCodexHookSubmission, assertCodexHookParentCurrent, assertCodexHooksReady, readCodexHookConfig, registerCodexHookInput } from "./codex-hook-state.js";
10
10
  /** modelの引数ではなく、CodexがMCP要求へ付けるmetadataだけを宛先にする。 */
11
11
  export function codexParentFromRequest(clientName, metadata) {
@@ -24,7 +24,7 @@ export async function withCodexReceiver(profile, parent, action, runtime = {}) {
24
24
  throw new CodexDeliveryError("CODEX_RECEIVER_UNAVAILABLE", "Codexの実行ファイルを確認できません");
25
25
  const child = spawn(executable, runtime.args ?? ["app-server", "--listen", "stdio://"], {
26
26
  stdio: ["pipe", "pipe", "ignore"],
27
- env: { ...(runtime.env ?? process.env), CODEX_HOME: parent.codex_home },
27
+ env: { ...codexSpawnEnv(runtime.env ?? process.env), CODEX_HOME: parent.codex_home },
28
28
  windowsHide: true,
29
29
  });
30
30
  const pending = new Map();
@@ -296,9 +296,13 @@ export async function configureCodexSteer(profile, action = "status", overrides)
296
296
  const config = { schema: profile.codex_hook_schema, enabled: true,
297
297
  codex_home: runtime.codex_home, binary, command, node, hook: runtime.hook, stale_processes: stale };
298
298
  await runtime.verify(config, true);
299
+ // 登録の間に終わったprocessは、起き直しを待つ相手から外す。ほかの導入が設定のために一時的に起こしたCodex
300
+ // (公式App Serverを起こして止める形)が、止まり切る前の一覧に載る事がある(BellTeamの起動、2026-10-07)。
301
+ const alive = runtime.processes();
302
+ const saved = { ...config, stale_processes: config.stale_processes.filter(stale => alive.some(row => row.pid === stale.pid && row.started_identity === stale.started_identity)) };
299
303
  // 解除が中断しても、次のenableで移行を続行できるよう所有情報を先に保存する。
300
- save(config);
304
+ save(saved);
301
305
  if (legacy?.enabled)
302
306
  await runtime.disableLegacy();
303
- return needsRestart(config) ? { status: "restart_required", reason_code: "codex_restart_required" } : { status: "ready" };
307
+ return saved.stale_processes.length ? { status: "restart_required", reason_code: "codex_restart_required" } : { status: "ready" };
304
308
  }
package/dist/index.d.ts CHANGED
@@ -4,10 +4,11 @@ export { writeJson0600, writeHookJson, waitForFileState, withoutBom } from "./fi
4
4
  export { readRuntimeProcesses, parsePosixProcessTable, hookOwnerProcess, type RuntimeProcess, type NativeProcessIdentity } from "./process.js";
5
5
  export { resolveWindowsPowerShell7, quotePowerShell, windowsPowerShellSync, windowsStartProcessArgumentList } from "./windows.js";
6
6
  export { setupNodeExecutable } from "./setup-node.js";
7
- export { realCodexHome, resolveCodexExecutable, desktopBundledCodex, findDesktopBinary, findWindowsCodexCache, findWindowsCodexBinary, findLinuxDesktopBinary, findCliBinary, findSteerBinary, platformDesktopFinder, currentCodexDesktopBinary, type DesktopBinaryFinder, } from "./codex-binary.js";
7
+ export { realCodexHome, resolveCodexExecutable, codexSpawnEnv, desktopBundledCodex, findDesktopBinary, findWindowsCodexCache, findWindowsCodexBinary, findLinuxDesktopBinary, findCliBinary, findSteerBinary, platformDesktopFinder, currentCodexDesktopBinary, type DesktopBinaryFinder, } from "./codex-binary.js";
8
8
  export { codexHookConfigSchema, readCodexHookConfig, codexInputDirectory, hookInputSchema, answerDigest, registerCodexHookInput, finishCodexHookSubmission, codexHookDeliveryState, ownedCodexHooks, assertCodexHooksReady, assertCodexHookParentCurrent, type CodexHookConfig, } from "./codex-hook-state.js";
9
9
  export { codexParentFromRequest, withCodexReceiver, verifyCodexParent, submitCodexParentAnswer, type CodexParent, type CodexParentThread, type CodexReceiverRuntime, } from "./codex-receiver.js";
10
10
  export { runCodexResultHook } from "./codex-hooks.js";
11
+ export { findAitermDeliveryProvider, verifyCodexParentViaAiterm, submitCodexParentAnswerViaAiterm, codexDeliveryStateViaAiterm, codexDeliveryDetailViaAiterm, AITERM_PARENT_DELIVERY_SCHEMA, AITERM_DELIVERY_PROVIDER_SCHEMA, type AitermDeliveryProvider, type AitermProviderOptions, type AitermDeliveryDetail, } from "./aiterm-provider.js";
11
12
  export { codexHookCommand, processCodexHome, mergeCodexParentHooks, planCodexParentHooks, writeCodexHookPlan, applyCodexHookPlan, verifyCodexHookRegistration, configureCodexSteer, type CodexHookMove, type CodexHookPlan, type CodexSteerAction, type CodexSteerResult, type CodexSteerRuntime, } from "./codex-setup.js";
12
13
  export { claudeParentSchema, prepareClaudeHookRequest, claudeParentFromRequest, verifyClaudeParent, bindClaudeParentDelivery, closeClaudeParentSession, submitClaudeParentAnswer, runClaudeResultHook, discardClaudeHookRequest, type ClaudeParent, } from "./claude-receiver.js";
13
14
  export { sendClaudeInbox, type ClaudeInboxTarget, type ClaudeInboxSendOptions, type ClaudeInboxSendResult, } from "./claude-inbox.js";
package/dist/index.js CHANGED
@@ -6,10 +6,11 @@ export { writeJson0600, writeHookJson, waitForFileState, withoutBom } from "./fi
6
6
  export { readRuntimeProcesses, parsePosixProcessTable, hookOwnerProcess } from "./process.js";
7
7
  export { resolveWindowsPowerShell7, quotePowerShell, windowsPowerShellSync, windowsStartProcessArgumentList } from "./windows.js";
8
8
  export { setupNodeExecutable } from "./setup-node.js";
9
- export { realCodexHome, resolveCodexExecutable, desktopBundledCodex, findDesktopBinary, findWindowsCodexCache, findWindowsCodexBinary, findLinuxDesktopBinary, findCliBinary, findSteerBinary, platformDesktopFinder, currentCodexDesktopBinary, } from "./codex-binary.js";
9
+ export { realCodexHome, resolveCodexExecutable, codexSpawnEnv, desktopBundledCodex, findDesktopBinary, findWindowsCodexCache, findWindowsCodexBinary, findLinuxDesktopBinary, findCliBinary, findSteerBinary, platformDesktopFinder, currentCodexDesktopBinary, } from "./codex-binary.js";
10
10
  export { codexHookConfigSchema, readCodexHookConfig, codexInputDirectory, hookInputSchema, answerDigest, registerCodexHookInput, finishCodexHookSubmission, codexHookDeliveryState, ownedCodexHooks, assertCodexHooksReady, assertCodexHookParentCurrent, } from "./codex-hook-state.js";
11
11
  export { codexParentFromRequest, withCodexReceiver, verifyCodexParent, submitCodexParentAnswer, } from "./codex-receiver.js";
12
12
  export { runCodexResultHook } from "./codex-hooks.js";
13
+ export { findAitermDeliveryProvider, verifyCodexParentViaAiterm, submitCodexParentAnswerViaAiterm, codexDeliveryStateViaAiterm, codexDeliveryDetailViaAiterm, AITERM_PARENT_DELIVERY_SCHEMA, AITERM_DELIVERY_PROVIDER_SCHEMA, } from "./aiterm-provider.js";
13
14
  export { codexHookCommand, processCodexHome, mergeCodexParentHooks, planCodexParentHooks, writeCodexHookPlan, applyCodexHookPlan, verifyCodexHookRegistration, configureCodexSteer, } from "./codex-setup.js";
14
15
  export { claudeParentSchema, prepareClaudeHookRequest, claudeParentFromRequest, verifyClaudeParent, bindClaudeParentDelivery, closeClaudeParentSession, submitClaudeParentAnswer, runClaudeResultHook, discardClaudeHookRequest, } from "./claude-receiver.js";
15
16
  export { sendClaudeInbox, } from "./claude-inbox.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-steer-delivery",
3
- "version": "0.2.3",
3
+ "version": "0.3.1",
4
4
  "description": "Aiterm's steer delivery as a library: deliver text to the parent AI session that called your MCP tool — steered into the running turn when it is busy, delivered normally when it is idle. Codex (official queue + sync hooks), Claude Code (asyncRewake hooks), Cursor (hooks + background receiver).",
5
5
  "type": "module",
6
6
  "license": "MIT",