aiterm-steer-delivery 0.3.1 → 0.4.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 CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.0
4
+
5
+ Codexの寝ている会話へ入れた文が、人がその会話を開くまで動かなかったのを直します。今までのAPIの返りは変わりません。
6
+
7
+ - **起きていた事。** Codexが公式キューの文を番にするのは、その会話を載せている(loaded)Codexのprocessだけ。Codexのアプリは、見ている接続が居なくなって動きの無い会話を60秒で下ろす(`thread_unload_delay_secs`。Codex 0.153.0までは30分)。下ろされた会話のキューは、人がその会話を開くまで誰も見ない。番の途中へ入れる道(hook)と、載っている会話の止まっている所へ届く道は、今までどおり通っていた。
8
+ - **`submitCodexParentAnswer`が、入れた後に「寝ていたら起こす見張り」を別のprocessで起こす。** 約15秒後にキューを見直す。
9
+ - 文がもう無い(会話が載っていて受け取った、hookが番の途中へ入れた): 何もしない。
10
+ - 文が残っていて、アプリの会話(`source`が`vscode`)で、最後の番が普通に終わっている(または番が1つも無い): OSの口で`codex://threads/<会話>`を開かせる。アプリが会話を載せ、公式キューが番を始める。アプリの画面はその会話へ切り替わる(macOSは`open -g`で、アプリを前面へは出さない。Windowsは`cmd /c start`、Linuxは`xdg-open`)。Windowsでは、人の画面のあるsessionの時だけ開く(サービスやsshのsessionから開いたリンクは、人の画面のアプリへ届かない)。
11
+ - 番の途中、最後の番が途中で止められている(人が止めた、ほかの製品が作業を別の会話へ移した)、アプリの会話でない(CLIの席)、会話の記録を読めない: 起こさない。途中で止められた会話は、人が次の文を送るまでCodexがキューを動かさない。
12
+ - 同じ会話へ続けて届いた時は、30秒の間は開き直さない。
13
+ - **結果を残す。** `<config_root>/codex-parent-hooks/wake/<配送ID>.json`に3日間。`readCodexWakeResult(profile, deliveryId)`で読める(`delivered`・`running`・`interrupted`・`not_app_thread`・`unknown_state`・`no_opener`・`open_failed`・`woken`・`opened_still_queued`)。受付の返り(`queued_submission_id`)は、見張りの成否で変わらない。
14
+ - **見張りを起こすのは、リンクを開く口のある環境だけ。** macOS、Windows、画面のあるLinux(`DISPLAY`か`WAYLAND_DISPLAY`があり、`codex`のリンクの受け手が登録されている)。サーバーやコンテナでは何も起こさない。止める時は環境変数`AITERM_STEER_CODEX_WAKE=0`。
15
+ - **公開した物。** `wakeCodexParentIfAsleep(profile, parent, deliveryId, options?)`(今すぐ見直して起こす)、`startCodexWakeWatch`、`readCodexWakeResult`、`readCodexTurnTail`、`codexThreadUrl`、`codexThreadOpener`、`codexWakeWatchEnabled`、`codexWakeDirectory`。`CodexReceiverRuntime`に`wake`(`runtime`を渡す呼び出しでは、`true`の時だけ見張りを起こす)。
16
+ - **CLI。** `codex submit`は今までどおりすぐ返り、見張りを残す。`codex state`の返りは、見張りが結果を残した後だけ`wake`が付く(それまでは今までと同じ形)。`codex wake --thread --delivery [--delay-ms]`を足す。
17
+ - **Aitermへ頼む入口。** `codexDeliveryDetailViaAiterm`の返りは、Aiterm(0.58.0以上)が見張りの結果を返した時だけ`wake`が付く。
18
+
3
19
  ## 0.3.1
4
20
 
5
21
  Codexの設定と起動の、2つの弱さを直します。APIと記録の形は変わりません。
package/README.md CHANGED
@@ -40,7 +40,7 @@ This package is the delivery [Aiterm](https://github.com/kitepon/aiterm-mcp) use
40
40
 
41
41
  | Parent | How the parent is identified | How text arrives |
42
42
  | --- | --- | --- |
43
- | Codex | `_meta.threadId` of the MCP request | Official App Server queue (`thread/queue/add`). With Steer enabled, your sync `PostToolUse`/`Stop` hooks pull it into the running turn; otherwise the official queue delivers it at the next turn boundary. |
43
+ | Codex | `_meta.threadId` of the MCP request | Official App Server queue (`thread/queue/add`). With Steer enabled, your sync `PostToolUse`/`Stop` hooks pull it into the running turn; otherwise the official queue delivers it at the next turn boundary. A conversation the Codex app has put to sleep is woken by asking the app to open it (see [Sleeping Codex conversations](#sleeping-codex-conversations)). |
44
44
  | Claude Code | Your `PreToolUse` hook record + `_meta["claudecode/toolUseId"]` | An `asyncRewake` hook writes the text to stderr and exits 2, waking the session (or steering into the running turn). |
45
45
  | Cursor (Desktop and CLI) | Your hook binds the id in your tool result to the real `conversation_id` | `additional_context` on the next tool return while busy; a background receiver process while idle. |
46
46
  | Others (Grok, …) | — | A background receiver process (`wait_process`). |
@@ -163,6 +163,20 @@ await steer.codexDeliveryDetailViaAiterm(parent, deliveryId); // {
163
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
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
165
 
166
+ #### Sleeping Codex conversations
167
+
168
+ Codex starts a queued message only in a conversation that some running Codex process has loaded. The Codex app unloads a conversation 60 seconds after nobody is viewing it (`thread_unload_delay_secs`), and from then on its queue is not looked at until the conversation is opened again. Without help, a reply sent to such a conversation waits until a person opens it.
169
+
170
+ `submitCodexParentAnswer` therefore starts a small watcher in a separate process after the queue accepts the text. About 15 seconds later the watcher looks at the queue again:
171
+
172
+ - The text is gone: the conversation was loaded and took it (or your hook steered it into the running turn). Nothing else happens.
173
+ - The text is still queued, the conversation belongs to the app (`source` is `vscode`), and its last turn ended normally (or it has no turn yet): the watcher asks the OS to open `codex://threads/<id>`. The app loads the conversation and the official queue starts the turn. The app's window switches to that conversation; on macOS the app is not brought to the front.
174
+ - The conversation is in the middle of a turn, its last turn was interrupted (a person stopped it, or another tool moved the work elsewhere), or it is not an app conversation (a CLI session): the watcher leaves it alone. Codex itself holds the queue of an interrupted conversation until a person sends the next message.
175
+
176
+ The outcome is saved under `<config_root>/codex-parent-hooks/wake/<delivery id>.json` for three days and can be read with `readCodexWakeResult(PROFILE, deliveryId)`: `delivered`, `running`, `interrupted`, `not_app_thread`, `unknown_state`, `no_opener`, `open_failed`, `woken`, or `opened_still_queued`. The acceptance returned by `submitCodexParentAnswer` does not depend on the watcher.
177
+
178
+ The watcher runs only where a link can be opened: macOS, Windows, and Linux with a display and a registered `codex` link handler. On Windows the link is opened only from an interactive session (a link opened from a service or an SSH session never reaches the app on the desktop; the outcome is `no_opener`). On servers and in containers nothing is started. Set `AITERM_STEER_CODEX_WAKE=0` to turn it off. To check and wake right now from your own process, call `wakeCodexParentIfAsleep(PROFILE, parent, deliveryId, { delay_ms: 0 })`.
179
+
166
180
  **Many messages to one conversation** (channels, e.g. Peertable's room messages to the parent):
167
181
 
168
182
  ```js
@@ -219,16 +233,19 @@ Known limit: Claude Code sessions that carry an `agent_id` (started with `--agen
219
233
 
220
234
  ## Non-Node products
221
235
 
222
- `aiterm-steer-delivery --profile <profile.json> codex <parent|verify|submit|state|setup>` prints one JSON line. `state_root` and `config_root` are absolute paths in the JSON profile. `codex setup enable` registers the package's own Codex hook entry for your profile.
236
+ `aiterm-steer-delivery --profile <profile.json> codex <parent|verify|submit|state|wake|setup>` prints one JSON line. `state_root` and `config_root` are absolute paths in the JSON profile. `codex setup enable` registers the package's own Codex hook entry for your profile.
223
237
 
224
238
  ```sh
225
239
  aiterm-steer-delivery --profile profile.json codex parent --client <name> --meta <json>
226
240
  aiterm-steer-delivery --profile profile.json codex verify --thread <uuid> [--codex-home <dir>]
227
241
  aiterm-steer-delivery --profile profile.json codex submit --thread <uuid> --delivery <uuid> --text-file <file|-> [--codex-home <dir>]
228
242
  aiterm-steer-delivery --profile profile.json codex state --thread <uuid> --delivery <uuid> [--codex-home <dir>]
243
+ aiterm-steer-delivery --profile profile.json codex wake --thread <uuid> --delivery <uuid> [--delay-ms <n>] [--codex-home <dir>]
229
244
  aiterm-steer-delivery --profile profile.json codex setup <enable|disable|status>
230
245
  ```
231
246
 
247
+ `codex submit` starts the watcher described in [Sleeping Codex conversations](#sleeping-codex-conversations); the command returns as soon as the queue accepts the text. `codex state` also returns `wake` once the watcher has saved its outcome. `codex wake` checks and wakes right now.
248
+
232
249
  Success is `{"ok":true,...}`. Failure is `{"ok":false,"code":...,"message":...,"outcome_unknown":...}` with exit code 1.
233
250
 
234
251
  ## Development
@@ -1,4 +1,5 @@
1
1
  import type { CodexParent, CodexParentThread } from "./codex-receiver.js";
2
+ import type { CodexWakeResult } from "./codex-wake.js";
2
3
  export declare const AITERM_PARENT_DELIVERY_SCHEMA = "aiterm.parent-delivery.v1";
3
4
  export declare const AITERM_DELIVERY_PROVIDER_SCHEMA = "aiterm.delivery-provider.v1";
4
5
  export type AitermDeliveryProvider = {
@@ -47,6 +48,8 @@ export type AitermDeliveryDetail = {
47
48
  /** 今も公式キューに残っているか。確かめられなかった時はnull。 */
48
49
  queued: boolean | null;
49
50
  queue_error?: string;
51
+ /** 寝ている会話を起こす見張りの結果(Aiterm 0.58.0以上)。見張りが終わるまで、または起こさない環境では付かない。 */
52
+ wake?: CodexWakeResult;
50
53
  };
51
54
  /** 届き方の事実を読む。受け付けた事と、実際に番へ入った事を分けて返す。 */
52
55
  export declare function codexDeliveryDetailViaAiterm(parent: CodexParent, deliveryId: string, options?: AitermProviderOptions): Promise<AitermDeliveryDetail>;
@@ -121,7 +121,8 @@ export async function codexDeliveryDetailViaAiterm(parent, deliveryId, options =
121
121
  z.uuid().parse(deliveryId);
122
122
  const value = await callAiterm(["codex", "state", ...target(parent), "--delivery", deliveryId], null, options, false);
123
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 } : {}) };
124
+ ...(typeof value.queue_error === "string" ? { queue_error: value.queue_error } : {}),
125
+ ...(value.wake !== null && typeof value.wake === "object" ? { wake: value.wake } : {}) };
125
126
  }
126
127
  /** 送る途中の状態だけを返す(`codexHookDeliveryState`と同じ値)。 */
127
128
  export async function codexDeliveryStateViaAiterm(parent, deliveryId, options = {}) {
package/dist/cli.js CHANGED
@@ -5,7 +5,8 @@
5
5
  // aiterm-steer-delivery --profile <file> codex parent --client <name> --meta <json>
6
6
  // aiterm-steer-delivery --profile <file> codex verify --thread <uuid> [--codex-home <dir>] → thread{thread_id,cwd,source}
7
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>]
8
+ // aiterm-steer-delivery --profile <file> codex state --thread <uuid> --delivery <uuid> [--codex-home <dir>] → state と、見張りが終わっていれば wake(寝ている会話を起こした結果)
9
+ // aiterm-steer-delivery --profile <file> codex wake --thread <uuid> --delivery <uuid> [--delay-ms <n>] [--codex-home <dir>] → wake(今すぐ見直して、寝ていれば起こす)
9
10
  // aiterm-steer-delivery --profile <file> codex setup <enable|disable|status>
10
11
  //
11
12
  // codex setupは、Codexのhookから起動する入口(codex-hook.js)と製品の識別情報をhook directoryへ置いて登録する。
@@ -18,6 +19,7 @@ import { codexHookDirectory } from "./profile.js";
18
19
  import { realCodexHome } from "./codex-binary.js";
19
20
  import { codexParentFromRequest, submitCodexParentAnswer, verifyCodexParent } from "./codex-receiver.js";
20
21
  import { codexHookDeliveryState } from "./codex-hook-state.js";
22
+ import { readCodexWakeResult, wakeCodexParentIfAsleep } from "./codex-wake.js";
21
23
  import { configureCodexSteer } from "./codex-setup.js";
22
24
  import { isDirectExecution } from "./hook-main.js";
23
25
  const profileFileSchema = z.object({
@@ -70,7 +72,13 @@ export async function runCli(argv) {
70
72
  }
71
73
  case "state": {
72
74
  const target = parent(args);
73
- return { state: codexHookDeliveryState(target.codex_home, target.thread_id, z.uuid().parse(required(args, "--delivery")), codexHookDirectory(profile)) };
75
+ const delivery = z.uuid().parse(required(args, "--delivery"));
76
+ const wake = readCodexWakeResult(profile, delivery);
77
+ return { state: codexHookDeliveryState(target.codex_home, target.thread_id, delivery, codexHookDirectory(profile)), ...(wake ? { wake } : {}) };
78
+ }
79
+ case "wake": {
80
+ const delay = option(args, "--delay-ms");
81
+ return { wake: await wakeCodexParentIfAsleep(profile, parent(args), z.uuid().parse(required(args, "--delivery")), { delay_ms: delay === undefined ? 0 : z.coerce.number().int().min(0).parse(delay) }) };
74
82
  }
75
83
  case "setup": {
76
84
  const action = z.enum(["enable", "disable", "status"]).parse(args[0] ?? "status");
@@ -15,6 +15,11 @@ export interface CodexReceiverRuntime {
15
15
  * PATHにこのprocessのnodeの場所が無い時は、頭へ足す(nodeで動くCodexの起動役を起こすため)。
16
16
  */
17
17
  env?: NodeJS.ProcessEnv;
18
+ /**
19
+ * キューへ入れた後に、寝ている会話を起こす見張りを起こすか。省略すると、`runtime`を渡さない呼び出し(製品の本番の道)でだけ起こす。
20
+ * `runtime`を渡す呼び出し(試験のfixture)では、trueを渡した時だけ起こす。
21
+ */
22
+ wake?: boolean;
18
23
  }
19
24
  export declare function withCodexReceiver<T>(profile: ProductProfile, parent: CodexParent, action: (request: (method: string, params: unknown) => Promise<any>) => Promise<T>, runtime?: CodexReceiverRuntime): Promise<T>;
20
25
  export interface CodexParentThread {
@@ -24,7 +29,10 @@ export interface CodexParentThread {
24
29
  }
25
30
  /** 送る前に、同じstoreの宛先と公式キューの対応を確認する。本文は保存・表示しない。確認したthreadのcwdとsourceを返す。 */
26
31
  export declare function verifyCodexParent(profile: ProductProfile, parent: CodexParent, runtime?: CodexReceiverRuntime): Promise<CodexParentThread>;
27
- /** 確定した本文を公式キューへ一度だけ入れる。受付IDを返す。受付の成否が不明な失敗はoutcome_unknownで区別する。 */
32
+ /**
33
+ * 確定した本文を公式キューへ一度だけ入れる。受付IDを返す。受付の成否が不明な失敗はoutcome_unknownで区別する。
34
+ * 入れた後、寝ている会話を起こす見張りを別のprocessで起こす(`startCodexWakeWatch`)。見張りの成否は、受付の結果を変えない。
35
+ */
28
36
  export declare function submitCodexParentAnswer(profile: ProductProfile, parent: CodexParent, deliveryId: string, text: string, runtime?: CodexReceiverRuntime): Promise<{
29
37
  queued_submission_id: string | null;
30
38
  }>;
@@ -1,5 +1,6 @@
1
1
  // Codex親への配送。公式App Serverのキュー(thread/queue/add)へ一度だけ入れる。
2
2
  // 親が作業中なら製品の同期hook(PostToolUse/Stop)が同じturnへ取り込み、idleなら公式キューが通常の入力として届ける。
3
+ // 公式キューが番にするのは、どこかのCodexのprocessに載っている会話だけ。寝ている会話は、入れた後の見張り(codex-wake)が起こす。
3
4
  import { spawn } from "node:child_process";
4
5
  import { createInterface } from "node:readline";
5
6
  import * as path from "node:path";
@@ -7,6 +8,7 @@ import { CodexDeliveryError } from "./errors.js";
7
8
  import { codexHookDirectory } from "./profile.js";
8
9
  import { codexSpawnEnv, currentCodexDesktopBinary, realCodexHome, resolveCodexExecutable } from "./codex-binary.js";
9
10
  import { finishCodexHookSubmission, assertCodexHookParentCurrent, assertCodexHooksReady, readCodexHookConfig, registerCodexHookInput } from "./codex-hook-state.js";
11
+ import { startCodexWakeWatch } from "./codex-wake.js";
10
12
  /** modelの引数ではなく、CodexがMCP要求へ付けるmetadataだけを宛先にする。 */
11
13
  export function codexParentFromRequest(clientName, metadata) {
12
14
  if (clientName !== "codex-mcp-client")
@@ -120,14 +122,18 @@ export async function verifyCodexParent(profile, parent, runtime) {
120
122
  return { thread_id: parent.thread_id, cwd: typeof response.thread.cwd === "string" ? response.thread.cwd : null, source: response.thread.source ?? null };
121
123
  }, runtime);
122
124
  }
123
- /** 確定した本文を公式キューへ一度だけ入れる。受付IDを返す。受付の成否が不明な失敗はoutcome_unknownで区別する。 */
125
+ /**
126
+ * 確定した本文を公式キューへ一度だけ入れる。受付IDを返す。受付の成否が不明な失敗はoutcome_unknownで区別する。
127
+ * 入れた後、寝ている会話を起こす見張りを別のprocessで起こす(`startCodexWakeWatch`)。見張りの成否は、受付の結果を変えない。
128
+ */
124
129
  export async function submitCodexParentAnswer(profile, parent, deliveryId, text, runtime) {
125
130
  const root = runtime ? runtime.hook_directory : codexHookDirectory(profile);
126
131
  const hook = root && readCodexHookConfig(profile, root)?.enabled;
127
132
  if (hook)
128
133
  registerCodexHookInput(parent.codex_home, parent.thread_id, deliveryId, text, root);
134
+ let accepted;
129
135
  try {
130
- return await withCodexReceiver(profile, parent, async (request) => {
136
+ accepted = await withCodexReceiver(profile, parent, async (request) => {
131
137
  const result = await request("thread/queue/add", {
132
138
  threadId: parent.thread_id,
133
139
  input: [{ type: "text", text, text_elements: [] }],
@@ -143,4 +149,7 @@ export async function submitCodexParentAnswer(profile, parent, deliveryId, text,
143
149
  if (hook)
144
150
  finishCodexHookSubmission(parent.codex_home, parent.thread_id, deliveryId, root);
145
151
  }
152
+ if (runtime?.wake ?? !runtime)
153
+ startCodexWakeWatch(profile, parent, deliveryId);
154
+ return accepted;
146
155
  }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ // 寝ている会話を起こす見張りの入口。配送を呼んだprocessが、渡す中身を環境変数に入れて起こす。
3
+ import { runCodexWakeMain } from "./codex-wake.js";
4
+ await runCodexWakeMain();
@@ -0,0 +1,95 @@
1
+ import { type ProductProfile } from "./profile.js";
2
+ import { type CodexParent, type CodexReceiverRuntime } from "./codex-receiver.js";
3
+ /** 会話の記録(rollout)の末尾から読んだ、最後の番の状態。 */
4
+ export type CodexTurnTail = "running" | "completed" | "interrupted" | "none" | "unknown";
5
+ /**
6
+ * 記録の末尾から、最後の番の境を読む。task_started=走っている、task_complete=普通に終わった、turn_aborted=途中で止められた。
7
+ * 番が1つも無ければ none。末尾16MiBに境が無い・読めない時は unknown(起こさない側へ倒す)。
8
+ */
9
+ export declare function readCodexTurnTail(file: string): CodexTurnTail;
10
+ export declare function codexThreadUrl(threadId: string): string;
11
+ export interface CodexThreadOpener {
12
+ (url: string): {
13
+ ok: boolean;
14
+ detail?: string;
15
+ };
16
+ }
17
+ /**
18
+ * Windowsで、このprocessが人の画面のあるsessionで動いているか。サービスやsshのsession(番号0)から開いたリンクは、人の画面のアプリへ届かない。
19
+ * sessionの番号を読めない時(PowerShell 7が無い)は、画面のあるsessionにだけ入る環境変数`SESSIONNAME`で見る。
20
+ */
21
+ export declare function windowsInteractiveSession(env?: NodeJS.ProcessEnv, sessionId?: () => string): boolean;
22
+ /**
23
+ * OSの口で、Codexのアプリにリンクを開かせる関数を返す。口の無い環境ではnull。
24
+ * macOSは`open -g`(アプリを前面へ出さない)、Windowsは`cmd /c start`(人の画面のあるsessionの時だけ)。
25
+ * Linuxは、画面のあるsessionで、リンクの受け手が登録されている時だけ`xdg-open`。
26
+ */
27
+ export declare function codexThreadOpener(platform?: NodeJS.Platform, env?: NodeJS.ProcessEnv, interactive?: () => boolean): CodexThreadOpener | null;
28
+ export type CodexWakeOutcome =
29
+ /** 見直した時にはキューに無かった。会話が載っていて受け取ったか、hookが番の途中へ入れた。 */
30
+ "delivered"
31
+ /** 番の途中。hookか、番の終わりの公式キューが渡す。 */
32
+ | "running"
33
+ /** 最後の番が途中で止められている。人が次の文を送るまでCodexはキューを動かさない。起こさない。 */
34
+ | "interrupted"
35
+ /** アプリの会話でない(CLIの席など)。リンクで開く相手が無い。 */
36
+ | "not_app_thread"
37
+ /** 会話の記録から番の状態を読めなかった。起こさない。 */
38
+ | "unknown_state"
39
+ /** この環境に、リンクを開く口が無い。 */
40
+ | "no_opener"
41
+ /** リンクを開く命令が失敗した。 */
42
+ | "open_failed"
43
+ /** リンクを開き、キューが動いた(この文が出た、または前に並んでいた文が出た)。 */
44
+ | "woken"
45
+ /** リンクを開いたが、待った間にキューが動かなかった。 */
46
+ | "opened_still_queued";
47
+ export interface CodexWakeResult {
48
+ delivery_id: string;
49
+ thread_id: string;
50
+ outcome: CodexWakeOutcome;
51
+ /** 番の状態を読んだ時の値。読む前に決まった時はnull。 */
52
+ turn: CodexTurnTail | null;
53
+ checked_at: string;
54
+ opened_at: string | null;
55
+ detail?: string;
56
+ }
57
+ export interface CodexWakeOptions {
58
+ /** 入れてから見直すまで。載っている会話は、Codexが10秒以内に番にする。 */
59
+ delay_ms?: number;
60
+ /** リンクを開いた後、キューが動くのを待つ長さ。 */
61
+ confirm_ms?: number;
62
+ /** 同じ会話を、ほかの配送が開いたばかりの時に、重ねて開かない長さ。 */
63
+ reopen_guard_ms?: number;
64
+ runtime?: CodexReceiverRuntime;
65
+ /** nullは「口が無い」。省略すると、この環境の口を使う。 */
66
+ open?: CodexThreadOpener | null;
67
+ sleep?: (ms: number) => Promise<void>;
68
+ /** 結果を残す場所。省略すると製品のhook directoryの`wake`。 */
69
+ directory?: string;
70
+ }
71
+ export declare function codexWakeDirectory(profile: ProductProfile): string;
72
+ /** 配送の後に残した結果を読む。無ければnull。 */
73
+ export declare function readCodexWakeResult(profile: ProductProfile, deliveryId: string, directory?: string): CodexWakeResult | null;
74
+ /**
75
+ * 入れた文がまだキューにあり、会話が寝ている時に、アプリにその会話を開かせる。結果を返し、`directory`へ残す。
76
+ * 起こすのは、アプリの会話(sourceがvscode)で、最後の番が普通に終わっている(または番が1つも無い)時だけ。
77
+ */
78
+ export declare function wakeCodexParentIfAsleep(profile: ProductProfile, parent: CodexParent, deliveryId: string, options?: CodexWakeOptions): Promise<CodexWakeResult>;
79
+ /** 見張りを別のprocessで起こすかどうか。口の無い環境(画面の無いLinuxなど)では、何も起こさない。 */
80
+ export declare function codexWakeWatchEnabled(platform?: NodeJS.Platform, env?: NodeJS.ProcessEnv): boolean;
81
+ export declare const CODEX_WAKE_PAYLOAD_ENV = "AITERM_STEER_CODEX_WAKE_PAYLOAD";
82
+ /** 見張りのprocessへ渡す、関数を含まない製品の識別情報。 */
83
+ export declare function serializeWakeProfile(profile: ProductProfile): Record<string, unknown>;
84
+ /**
85
+ * 配送を呼んだprocessとは別に、見張りを1つ起こす。呼んだprocessがすぐ終わっても(製品のCLI)、見直しと起こしは最後まで走る。
86
+ * 起こせなかった時も投げない。文はもうキューに入っていて、今までどおり会話が開かれた時に届く。
87
+ */
88
+ export declare function startCodexWakeWatch(profile: ProductProfile, parent: CodexParent, deliveryId: string, options?: {
89
+ platform?: NodeJS.Platform;
90
+ env?: NodeJS.ProcessEnv;
91
+ entry?: string;
92
+ delay_ms?: number;
93
+ }): boolean;
94
+ /** 見張りのprocessの本体。結果は製品のhook directoryの`wake`に残す。 */
95
+ export declare function runCodexWakeMain(raw?: string | undefined): Promise<void>;
@@ -0,0 +1,301 @@
1
+ // 寝ているCodexの会話を起こす。
2
+ // 公式キューを番にするのは、その会話を載せている(loaded)Codexのprocessだけ。Codexのアプリは、見ている接続が居なくなった会話を
3
+ // 60秒で下ろす(thread_unload_delay_secs)。下ろされた会話のキューは、人がその会話を開くまで誰も見ない。
4
+ // 入れた少し後にキューを見直し、番が普通に終わって寝ている会話なら、OSの口で`codex://threads/<id>`を開かせて、アプリに載せさせる。
5
+ // 走っている会話(hookが入れる)、途中で止められた会話(人が止めた・ほかの製品が乗り換えた)、アプリの会話でない物(CLIの席)は起こさない。
6
+ import * as fs from "node:fs";
7
+ import * as path from "node:path";
8
+ import { spawn, spawnSync } from "node:child_process";
9
+ import { fileURLToPath } from "node:url";
10
+ import { z } from "zod";
11
+ import { codexHookDirectory } from "./profile.js";
12
+ import { withCodexReceiver } from "./codex-receiver.js";
13
+ import { writeHookJson } from "./files.js";
14
+ import { windowsPowerShellSync } from "./windows.js";
15
+ const TAIL_FIRST_BYTES = 256 * 1024;
16
+ const TAIL_MAX_BYTES = 16 * 1024 * 1024;
17
+ /**
18
+ * 記録の末尾から、最後の番の境を読む。task_started=走っている、task_complete=普通に終わった、turn_aborted=途中で止められた。
19
+ * 番が1つも無ければ none。末尾16MiBに境が無い・読めない時は unknown(起こさない側へ倒す)。
20
+ */
21
+ export function readCodexTurnTail(file) {
22
+ let fd;
23
+ try {
24
+ fd = fs.openSync(file, "r");
25
+ }
26
+ catch {
27
+ return "unknown";
28
+ }
29
+ try {
30
+ const size = fs.fstatSync(fd).size;
31
+ for (let bytes = TAIL_FIRST_BYTES;; bytes *= 4) {
32
+ const length = Math.min(size, bytes);
33
+ const start = size - length;
34
+ const buffer = Buffer.alloc(length);
35
+ fs.readSync(fd, buffer, 0, length, start);
36
+ const lines = buffer.toString("utf8").split("\n");
37
+ // 途中から読んだ時、先頭は行の切れ端。
38
+ if (start > 0)
39
+ lines.shift();
40
+ for (let index = lines.length - 1; index >= 0; index--) {
41
+ const line = lines[index];
42
+ if (!line.includes("task_started") && !line.includes("task_complete") && !line.includes("turn_aborted"))
43
+ continue;
44
+ let row;
45
+ try {
46
+ row = JSON.parse(line);
47
+ }
48
+ catch {
49
+ continue;
50
+ }
51
+ if (row?.type !== "event_msg")
52
+ continue;
53
+ if (row.payload?.type === "task_started")
54
+ return "running";
55
+ if (row.payload?.type === "task_complete")
56
+ return "completed";
57
+ if (row.payload?.type === "turn_aborted")
58
+ return "interrupted";
59
+ }
60
+ if (start === 0)
61
+ return "none";
62
+ if (length >= TAIL_MAX_BYTES)
63
+ return "unknown";
64
+ }
65
+ }
66
+ catch {
67
+ return "unknown";
68
+ }
69
+ finally {
70
+ fs.closeSync(fd);
71
+ }
72
+ }
73
+ export function codexThreadUrl(threadId) {
74
+ return `codex://threads/${encodeURIComponent(z.uuid().parse(threadId))}`;
75
+ }
76
+ /**
77
+ * Windowsで、このprocessが人の画面のあるsessionで動いているか。サービスやsshのsession(番号0)から開いたリンクは、人の画面のアプリへ届かない。
78
+ * sessionの番号を読めない時(PowerShell 7が無い)は、画面のあるsessionにだけ入る環境変数`SESSIONNAME`で見る。
79
+ */
80
+ export function windowsInteractiveSession(env = process.env, sessionId = () => windowsPowerShellSync("(Get-Process -Id $PID).SessionId", () => new Error("session id unavailable"), 10_000)) {
81
+ try {
82
+ const id = Number(sessionId());
83
+ if (Number.isInteger(id))
84
+ return id > 0;
85
+ }
86
+ catch { /* 下の環境変数で見る */ }
87
+ return Boolean(env.SESSIONNAME);
88
+ }
89
+ /**
90
+ * OSの口で、Codexのアプリにリンクを開かせる関数を返す。口の無い環境ではnull。
91
+ * macOSは`open -g`(アプリを前面へ出さない)、Windowsは`cmd /c start`(人の画面のあるsessionの時だけ)。
92
+ * Linuxは、画面のあるsessionで、リンクの受け手が登録されている時だけ`xdg-open`。
93
+ */
94
+ export function codexThreadOpener(platform = process.platform, env = process.env, interactive = () => windowsInteractiveSession(env)) {
95
+ const run = (command, args) => () => {
96
+ const result = spawnSync(command, args, { encoding: "utf8", timeout: 15_000, windowsHide: true, stdio: ["ignore", "ignore", "pipe"], env });
97
+ if (result.error)
98
+ return { ok: false, detail: result.error.code ?? result.error.message };
99
+ return result.status === 0 ? { ok: true } : { ok: false, detail: `exit=${result.status} ${String(result.stderr ?? "").trim().slice(0, 200)}`.trim() };
100
+ };
101
+ if (platform === "darwin")
102
+ return url => run("open", ["-g", url])();
103
+ if (platform === "win32")
104
+ return interactive() ? url => run("cmd.exe", ["/d", "/c", "start", "", url])() : null;
105
+ if (platform === "linux") {
106
+ if (!env.DISPLAY && !env.WAYLAND_DISPLAY)
107
+ return null;
108
+ const handler = spawnSync("xdg-mime", ["query", "default", "x-scheme-handler/codex"], { encoding: "utf8", timeout: 5_000, stdio: ["ignore", "pipe", "ignore"], env });
109
+ if (handler.error || handler.status !== 0 || !String(handler.stdout ?? "").trim())
110
+ return null;
111
+ return url => run("xdg-open", [url])();
112
+ }
113
+ return null;
114
+ }
115
+ export function codexWakeDirectory(profile) {
116
+ return path.join(codexHookDirectory(profile), "wake");
117
+ }
118
+ const RECORD_KEEP_MS = 3 * 24 * 60 * 60 * 1000;
119
+ function pruneWakeRecords(directory, now) {
120
+ for (const folder of [directory, path.join(directory, "threads")]) {
121
+ let names;
122
+ try {
123
+ names = fs.readdirSync(folder);
124
+ }
125
+ catch {
126
+ continue;
127
+ }
128
+ for (const name of names) {
129
+ if (!name.endsWith(".json"))
130
+ continue;
131
+ const file = path.join(folder, name);
132
+ try {
133
+ if (now - fs.statSync(file).mtimeMs > RECORD_KEEP_MS)
134
+ fs.rmSync(file, { force: true });
135
+ }
136
+ catch { /* ほかの見張りが先に消した */ }
137
+ }
138
+ }
139
+ }
140
+ /** 配送の後に残した結果を読む。無ければnull。 */
141
+ export function readCodexWakeResult(profile, deliveryId, directory = codexWakeDirectory(profile)) {
142
+ try {
143
+ return JSON.parse(fs.readFileSync(path.join(directory, `${z.uuid().parse(deliveryId)}.json`), "utf8"));
144
+ }
145
+ catch (error) {
146
+ if (error.code === "ENOENT")
147
+ return null;
148
+ throw error;
149
+ }
150
+ }
151
+ /**
152
+ * 入れた文がまだキューにあり、会話が寝ている時に、アプリにその会話を開かせる。結果を返し、`directory`へ残す。
153
+ * 起こすのは、アプリの会話(sourceがvscode)で、最後の番が普通に終わっている(または番が1つも無い)時だけ。
154
+ */
155
+ export async function wakeCodexParentIfAsleep(profile, parent, deliveryId, options = {}) {
156
+ const sleep = options.sleep ?? ((ms) => new Promise(resolve => setTimeout(resolve, ms)));
157
+ const directory = options.directory ?? codexWakeDirectory(profile);
158
+ const result = { delivery_id: z.uuid().parse(deliveryId), thread_id: z.uuid().parse(parent.thread_id),
159
+ outcome: "delivered", turn: null, checked_at: "", opened_at: null };
160
+ await sleep(options.delay_ms ?? 15_000);
161
+ await withCodexReceiver(profile, parent, async (request) => {
162
+ const queue = async () => {
163
+ const ids = [];
164
+ let mine = false;
165
+ let cursor = null;
166
+ do {
167
+ const page = await request("thread/queue/list", { threadId: parent.thread_id, cursor, limit: 100 });
168
+ for (const entry of Array.isArray(page?.data) ? page.data : []) {
169
+ ids.push(String(entry?.id));
170
+ if (entry?.clientUserMessageId === deliveryId)
171
+ mine = true;
172
+ }
173
+ cursor = typeof page?.nextCursor === "string" ? page.nextCursor : null;
174
+ } while (cursor);
175
+ return { ids, mine };
176
+ };
177
+ const before = await queue();
178
+ result.checked_at = new Date().toISOString();
179
+ if (!before.mine) {
180
+ result.outcome = "delivered";
181
+ return;
182
+ }
183
+ const thread = (await request("thread/read", { threadId: parent.thread_id, includeTurns: false }))?.thread;
184
+ if (thread?.source !== "vscode") {
185
+ result.outcome = "not_app_thread";
186
+ return;
187
+ }
188
+ result.turn = typeof thread.path === "string" && thread.path ? readCodexTurnTail(thread.path) : "unknown";
189
+ if (result.turn === "running") {
190
+ result.outcome = "running";
191
+ return;
192
+ }
193
+ if (result.turn === "interrupted") {
194
+ result.outcome = "interrupted";
195
+ return;
196
+ }
197
+ if (result.turn === "unknown") {
198
+ result.outcome = "unknown_state";
199
+ return;
200
+ }
201
+ const open = options.open === undefined ? codexThreadOpener() : options.open;
202
+ if (!open) {
203
+ result.outcome = "no_opener";
204
+ return;
205
+ }
206
+ // 同じ会話へ何通か続けて届いた時、1通ごとにアプリの画面を切り替えない。
207
+ const stamp = path.join(directory, "threads", `${parent.thread_id}.json`);
208
+ let recent = false;
209
+ try {
210
+ recent = Date.now() - fs.statSync(stamp).mtimeMs < (options.reopen_guard_ms ?? 30_000);
211
+ }
212
+ catch { /* まだ誰も開いていない */ }
213
+ if (!recent) {
214
+ writeHookJson(stamp, { thread_id: parent.thread_id, delivery_id: deliveryId });
215
+ const opened = open(codexThreadUrl(parent.thread_id));
216
+ if (!opened.ok) {
217
+ result.outcome = "open_failed";
218
+ if (opened.detail)
219
+ result.detail = opened.detail;
220
+ return;
221
+ }
222
+ }
223
+ result.opened_at = new Date().toISOString();
224
+ // キューは先頭から番になる。前に並んでいた文が出た時も、会話は起きている。
225
+ const deadline = Date.now() + (options.confirm_ms ?? 30_000);
226
+ for (;;) {
227
+ await sleep(2_000);
228
+ const after = await queue();
229
+ if (!after.mine || after.ids[0] !== before.ids[0] || after.ids.length < before.ids.length) {
230
+ result.outcome = "woken";
231
+ return;
232
+ }
233
+ if (Date.now() >= deadline) {
234
+ result.outcome = "opened_still_queued";
235
+ return;
236
+ }
237
+ }
238
+ }, options.runtime);
239
+ try {
240
+ writeHookJson(path.join(directory, `${result.delivery_id}.json`), result);
241
+ pruneWakeRecords(directory, Date.now());
242
+ }
243
+ catch { /* 結果を残せなくても、起こした事は変わらない */ }
244
+ return result;
245
+ }
246
+ /** 見張りを別のprocessで起こすかどうか。口の無い環境(画面の無いLinuxなど)では、何も起こさない。 */
247
+ export function codexWakeWatchEnabled(platform = process.platform, env = process.env) {
248
+ if (env.AITERM_STEER_CODEX_WAKE === "0")
249
+ return false;
250
+ if (platform === "darwin" || platform === "win32")
251
+ return true;
252
+ return platform === "linux" && Boolean(env.DISPLAY || env.WAYLAND_DISPLAY);
253
+ }
254
+ export const CODEX_WAKE_PAYLOAD_ENV = "AITERM_STEER_CODEX_WAKE_PAYLOAD";
255
+ /** 見張りのprocessへ渡す、関数を含まない製品の識別情報。 */
256
+ export function serializeWakeProfile(profile) {
257
+ const { state_root, config_root, channels: _channels, ...rest } = profile;
258
+ return { ...rest, dispatch_tools: [...profile.dispatch_tools], state_root: state_root(), config_root: config_root() };
259
+ }
260
+ /**
261
+ * 配送を呼んだprocessとは別に、見張りを1つ起こす。呼んだprocessがすぐ終わっても(製品のCLI)、見直しと起こしは最後まで走る。
262
+ * 起こせなかった時も投げない。文はもうキューに入っていて、今までどおり会話が開かれた時に届く。
263
+ */
264
+ export function startCodexWakeWatch(profile, parent, deliveryId, options = {}) {
265
+ const env = options.env ?? process.env;
266
+ if (!codexWakeWatchEnabled(options.platform, env))
267
+ return false;
268
+ try {
269
+ const entry = options.entry ?? fileURLToPath(new URL("./codex-wake-main.js", import.meta.url));
270
+ if (!fs.existsSync(entry))
271
+ return false;
272
+ const payload = JSON.stringify({ profile: serializeWakeProfile(profile), parent, delivery_id: deliveryId,
273
+ ...(options.delay_ms === undefined ? {} : { delay_ms: options.delay_ms }) });
274
+ const child = spawn(process.execPath, [entry], { detached: true, stdio: "ignore", windowsHide: true, env: { ...env, [CODEX_WAKE_PAYLOAD_ENV]: payload } });
275
+ child.on("error", () => { });
276
+ child.unref();
277
+ return true;
278
+ }
279
+ catch {
280
+ return false;
281
+ }
282
+ }
283
+ const payloadSchema = z.object({
284
+ profile: z.object({ state_root: z.string(), config_root: z.string() }).passthrough(),
285
+ parent: z.object({ thread_id: z.uuid(), codex_home: z.string() }).strict(),
286
+ delivery_id: z.uuid(),
287
+ delay_ms: z.number().int().min(0).optional(),
288
+ }).strict();
289
+ /** 見張りのprocessの本体。結果は製品のhook directoryの`wake`に残す。 */
290
+ export async function runCodexWakeMain(raw = process.env[CODEX_WAKE_PAYLOAD_ENV]) {
291
+ try {
292
+ const payload = payloadSchema.parse(JSON.parse(raw ?? ""));
293
+ const { state_root, config_root, ...rest } = payload.profile;
294
+ const profile = { ...rest, state_root: () => state_root, config_root: () => config_root };
295
+ await wakeCodexParentIfAsleep(profile, payload.parent, payload.delivery_id, payload.delay_ms === undefined ? {} : { delay_ms: payload.delay_ms });
296
+ }
297
+ catch (error) {
298
+ process.stderr.write(`CODEX_WAKE_FAILED: ${error instanceof Error ? error.message : String(error)}\n`);
299
+ process.exitCode = 1;
300
+ }
301
+ }
package/dist/index.d.ts CHANGED
@@ -8,6 +8,7 @@ export { realCodexHome, resolveCodexExecutable, codexSpawnEnv, desktopBundledCod
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 { readCodexTurnTail, codexThreadUrl, codexThreadOpener, windowsInteractiveSession, codexWakeDirectory, readCodexWakeResult, wakeCodexParentIfAsleep, codexWakeWatchEnabled, startCodexWakeWatch, runCodexWakeMain, serializeWakeProfile, CODEX_WAKE_PAYLOAD_ENV, type CodexTurnTail, type CodexThreadOpener, type CodexWakeOutcome, type CodexWakeResult, type CodexWakeOptions, } from "./codex-wake.js";
11
12
  export { findAitermDeliveryProvider, verifyCodexParentViaAiterm, submitCodexParentAnswerViaAiterm, codexDeliveryStateViaAiterm, codexDeliveryDetailViaAiterm, AITERM_PARENT_DELIVERY_SCHEMA, AITERM_DELIVERY_PROVIDER_SCHEMA, type AitermDeliveryProvider, type AitermProviderOptions, type AitermDeliveryDetail, } from "./aiterm-provider.js";
12
13
  export { codexHookCommand, processCodexHome, mergeCodexParentHooks, planCodexParentHooks, writeCodexHookPlan, applyCodexHookPlan, verifyCodexHookRegistration, configureCodexSteer, type CodexHookMove, type CodexHookPlan, type CodexSteerAction, type CodexSteerResult, type CodexSteerRuntime, } from "./codex-setup.js";
13
14
  export { claudeParentSchema, prepareClaudeHookRequest, claudeParentFromRequest, verifyClaudeParent, bindClaudeParentDelivery, closeClaudeParentSession, submitClaudeParentAnswer, runClaudeResultHook, discardClaudeHookRequest, type ClaudeParent, } from "./claude-receiver.js";
package/dist/index.js CHANGED
@@ -10,6 +10,7 @@ export { realCodexHome, resolveCodexExecutable, codexSpawnEnv, desktopBundledCod
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 { readCodexTurnTail, codexThreadUrl, codexThreadOpener, windowsInteractiveSession, codexWakeDirectory, readCodexWakeResult, wakeCodexParentIfAsleep, codexWakeWatchEnabled, startCodexWakeWatch, runCodexWakeMain, serializeWakeProfile, CODEX_WAKE_PAYLOAD_ENV, } from "./codex-wake.js";
13
14
  export { findAitermDeliveryProvider, verifyCodexParentViaAiterm, submitCodexParentAnswerViaAiterm, codexDeliveryStateViaAiterm, codexDeliveryDetailViaAiterm, AITERM_PARENT_DELIVERY_SCHEMA, AITERM_DELIVERY_PROVIDER_SCHEMA, } from "./aiterm-provider.js";
14
15
  export { codexHookCommand, processCodexHome, mergeCodexParentHooks, planCodexParentHooks, writeCodexHookPlan, applyCodexHookPlan, verifyCodexHookRegistration, configureCodexSteer, } from "./codex-setup.js";
15
16
  export { claudeParentSchema, prepareClaudeHookRequest, claudeParentFromRequest, verifyClaudeParent, bindClaudeParentDelivery, closeClaudeParentSession, submitClaudeParentAnswer, runClaudeResultHook, discardClaudeHookRequest, } from "./claude-receiver.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-steer-delivery",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
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",