aiterm-steer-delivery 0.1.3 → 0.1.5

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,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.5
4
+
5
+ - Steerの導入で「再起動が要るCodex」を数える時、別のCODEX_HOMEで動くCodex(同じ端末の他の利用者やBot)まで数えていた(紅蓮氏の報告)。Linuxではprocessの環境からCODEX_HOME(無ければHOME/.codex)を読み、hookを入れた場所のものだけを数える。macOS・Windowsは他processの環境を読めないので、今までどおり数える。
6
+
7
+ ## 0.1.4
8
+
9
+ - CodexのSteerのhookを外した後、自製品のhookが居た位置の承認記録(`hooks.state`の`trusted_hash`・`enabled`)が`config.toml`に残っていた(ラプンツェル氏の報告)。他のhookが入らずに空いた位置の記録を消す。別のfileや他の位置の記録は触らない。記録の後片付けが公式APIの都合でできなくても、hookの解除そのものは止めない。
10
+
3
11
  ## 0.1.3
4
12
 
5
13
  - Codex CLIをsymlink経由で起動した形(`node <symlinkのpath>`)も、再起動待ちとして照合する。
@@ -19,6 +19,10 @@ export type CodexHookPlan = {
19
19
  next: any;
20
20
  changed: boolean;
21
21
  moves: CodexHookMove[];
22
+ owned: {
23
+ event: string;
24
+ at: [number, number];
25
+ }[];
22
26
  };
23
27
  /** 自製品のhookを置換・解除した後のhooks.jsonと、他のhookの位置の動きを計算する(書き込まない)。 */
24
28
  export declare function planCodexParentHooks(file: string, command: string | null, previousCommand?: string): CodexHookPlan;
@@ -48,7 +52,14 @@ export type CodexSteerRuntime = {
48
52
  prepareDirectory: (directory: string) => void;
49
53
  /** Windowsでhookを起動するPowerShell 7の絶対path。 */
50
54
  powershell: () => string;
55
+ /** processが使うCODEX_HOME。読めなければnull(その時は再起動待ちに数える)。 */
56
+ codexHomeOf: (pid: number) => string | null;
51
57
  };
58
+ /**
59
+ * processの環境変数からCODEX_HOME(無ければHOME/.codex)を読む。Linuxの /proc だけで読める。
60
+ * macOSとWindowsは他processの環境を読めないのでnull。
61
+ */
62
+ export declare function processCodexHome(pid: number, platform?: NodeJS.Platform, read?: (file: string) => Buffer): string | null;
52
63
  export declare function verifyCodexHookRegistration(profile: ProductProfile, config: CodexHookConfig, approve: boolean, directory?: string): Promise<void>;
53
64
  /** hookは製品が同梱するCodex hook入口(パッケージのrunCodexResultHookを呼ぶ小さなファイル)の絶対path。 */
54
65
  export declare function configureCodexSteer(profile: ProductProfile, action: CodexSteerAction | undefined, overrides: Partial<CodexSteerRuntime> & {
@@ -45,6 +45,7 @@ export function planCodexParentHooks(file, command, previousCommand) {
45
45
  throw new SetupError("codex_hook_config_invalid", "Codexのhooks設定を読めません");
46
46
  const hooks = { ...current.hooks };
47
47
  const moves = [];
48
+ const ownedAt = [];
48
49
  for (const event of ["PostToolUse", "Stop"]) {
49
50
  const groups = hooks[event] ?? [];
50
51
  if (!Array.isArray(groups) || groups.some(group => !object(group) || !Array.isArray(group.hooks)))
@@ -52,7 +53,9 @@ export function planCodexParentHooks(file, command, previousCommand) {
52
53
  const owned = (hook) => hook?.type === "command" && ((command !== null && hook.command === command) || (!!previousCommand && hook.command === previousCommand));
53
54
  const before = new Map();
54
55
  groups.forEach((group, g) => group.hooks.forEach((hook, h) => { if (!owned(hook))
55
- before.set(hook, [g, h]); }));
56
+ before.set(hook, [g, h]);
57
+ else
58
+ ownedAt.push({ event, at: [g, h] }); }));
56
59
  // 既存の位置で置換する。末尾へ移すと同じ設定の再導入でも変更扱いになり、
57
60
  // 稼働中のCodexへ不要な再起動を要求してしまう。
58
61
  hooks[event] = [];
@@ -79,7 +82,7 @@ export function planCodexParentHooks(file, command, previousCommand) {
79
82
  delete hooks[event];
80
83
  }
81
84
  const next = { ...current, hooks };
82
- return { target, current, next, changed: !isDeepStrictEqual(current, next), moves };
85
+ return { target, current, next, changed: !isDeepStrictEqual(current, next), moves, owned: ownedAt };
83
86
  }
84
87
  export function writeCodexHookPlan(profile, plan) {
85
88
  if (!plan.changed)
@@ -102,8 +105,17 @@ const snake = (event) => event.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCas
102
105
  export async function applyCodexHookPlan(profile, plan, codexHome, executable) {
103
106
  if (!plan.changed)
104
107
  return false;
105
- if (!plan.moves.length)
106
- return writeCodexHookPlan(profile, plan);
108
+ // 他のhookが動かず、自製品のhookを外すだけの時は、書き換えてから空いた位置の承認を消す。
109
+ // 承認の後片付けが公式APIの都合でできなくても、hookの解除そのものは止めない。
110
+ if (!plan.moves.length) {
111
+ writeCodexHookPlan(profile, plan);
112
+ if (plan.owned.length) {
113
+ await cleanVacatedTrust(profile, plan, codexHome, executable).catch(error => {
114
+ process.stderr.write(`${profile.id}: 外したhookの承認記録を消せませんでした(${error instanceof Error ? error.message : String(error)})\n`);
115
+ });
116
+ }
117
+ return true;
118
+ }
107
119
  return withCodexReceiver(profile, { thread_id: "00000000-0000-4000-8000-000000000000", codex_home: codexHome }, async (request) => {
108
120
  const listed = await request("hooks/list", { cwds: [codexHome] });
109
121
  const source = fs.realpathSync(plan.target);
@@ -129,12 +141,67 @@ export async function applyCodexHookPlan(profile, plan, codexHome, executable) {
129
141
  const used = new Set();
130
142
  for (const event of ["PostToolUse", "Stop"])
131
143
  (plan.next.hooks?.[event] ?? []).forEach((group, g) => group.hooks.forEach((_, h) => used.add(key(event, [g, h]))));
132
- const vacated = plan.moves.map(move => key(move.event, move.from)).filter(old => !used.has(old) && state[old] !== undefined);
144
+ const vacated = [...plan.moves.map(move => key(move.event, move.from)), ...plan.owned.map(item => key(item.event, item.at))]
145
+ .filter((old, index, all) => all.indexOf(old) === index && !used.has(old) && state[old] !== undefined);
133
146
  if (vacated.length)
134
147
  await request("config/batchWrite", { edits: vacated.map(old => ({ keyPath: `hooks.state.${JSON.stringify(old)}`, value: null, mergeStrategy: "replace" })), filePath: configFile });
135
148
  return true;
136
149
  }, executable ? { executable } : {});
137
150
  }
151
+ /** hooks.jsonを書き換えた後、自製品のhookが居た位置で空いたものの承認記録を消す。 */
152
+ async function cleanVacatedTrust(profile, plan, codexHome, executable) {
153
+ await withCodexReceiver(profile, { thread_id: "00000000-0000-4000-8000-000000000000", codex_home: codexHome }, async (request) => {
154
+ const source = fs.realpathSync(plan.target);
155
+ const prefix = `${source}`;
156
+ const key = (event, [g, h]) => `${prefix}:${snake(event)}:${g}:${h}`;
157
+ const state = (await request("config/read", { includeLayers: false }))?.config?.hooks?.state ?? {};
158
+ const used = new Set();
159
+ for (const event of ["PostToolUse", "Stop"])
160
+ (plan.next.hooks?.[event] ?? []).forEach((group, g) => group.hooks.forEach((_, h) => used.add(key(event, [g, h]))));
161
+ // 鍵のfile部分はCodexの表記(hooks/listのkey)に合わせる。記録にある鍵のうち、同じfileを指すものだけを対象にする。
162
+ const vacated = Object.keys(state).filter(stored => plan.owned.some(item => stored.endsWith(`:${snake(item.event)}:${item.at[0]}:${item.at[1]}`)
163
+ && samePath(stored.split(":").slice(0, -3).join(":"), source)) && !used.has(key(...parseSuffix(stored))));
164
+ if (vacated.length)
165
+ await request("config/batchWrite", { edits: vacated.map(old => ({ keyPath: `hooks.state.${JSON.stringify(old)}`, value: null, mergeStrategy: "replace" })), filePath: path.join(codexHome, "config.toml") });
166
+ }, executable ? { executable } : {});
167
+ }
168
+ function parseSuffix(stored) {
169
+ const parts = stored.split(":");
170
+ const h = Number(parts.pop()), g = Number(parts.pop()), event = parts.pop();
171
+ return [event === "post_tool_use" ? "PostToolUse" : event === "stop" ? "Stop" : event, [g, h]];
172
+ }
173
+ function samePath(a, b) {
174
+ if (a === b)
175
+ return true;
176
+ try {
177
+ return fs.realpathSync(a) === fs.realpathSync(b);
178
+ }
179
+ catch {
180
+ return process.platform === "win32" && a.toLowerCase() === b.toLowerCase();
181
+ }
182
+ }
183
+ /**
184
+ * processの環境変数からCODEX_HOME(無ければHOME/.codex)を読む。Linuxの /proc だけで読める。
185
+ * macOSとWindowsは他processの環境を読めないのでnull。
186
+ */
187
+ export function processCodexHome(pid, platform = process.platform, read = file => fs.readFileSync(file)) {
188
+ if (platform !== "linux")
189
+ return null;
190
+ let raw;
191
+ try {
192
+ raw = read(`/proc/${pid}/environ`);
193
+ }
194
+ catch {
195
+ return null;
196
+ }
197
+ const env = new Map(raw.toString("utf8").split("\0").filter(Boolean).map(entry => {
198
+ const index = entry.indexOf("=");
199
+ return [entry.slice(0, index), entry.slice(index + 1)];
200
+ }));
201
+ // Linuxのprocessの値なので、どのOSで試験してもPOSIXの規則で組み立てる。
202
+ const home = env.get("CODEX_HOME") || (env.get("HOME") ? path.posix.join(env.get("HOME"), ".codex") : null);
203
+ return home ? path.posix.resolve(home) : null;
204
+ }
138
205
  export async function verifyCodexHookRegistration(profile, config, approve, directory = codexHookDirectory(profile)) {
139
206
  fs.accessSync(config.node, fs.constants.X_OK);
140
207
  fs.accessSync(config.hook, fs.constants.R_OK);
@@ -165,7 +232,7 @@ export async function configureCodexSteer(profile, action = "status", overrides)
165
232
  node: process.execPath, findBinary: () => findSteerBinary(),
166
233
  processes: readRuntimeProcesses, legacy: () => null,
167
234
  disableLegacy: async () => ({ status: "disabled" }), verify: (config, approve) => verifyCodexHookRegistration(profile, config, approve, directory),
168
- prepareDirectory: () => undefined, powershell: () => resolveWindowsPowerShell7(), ...overrides };
235
+ prepareDirectory: () => undefined, powershell: () => resolveWindowsPowerShell7(), codexHomeOf: pid => processCodexHome(pid), ...overrides };
169
236
  const previous = readCodexHookConfig(profile, runtime.directory);
170
237
  const legacy = runtime.legacy();
171
238
  const file = path.join(action === "disable" && previous ? previous.codex_home : runtime.codex_home, "hooks.json");
@@ -219,6 +286,11 @@ export async function configureCodexSteer(profile, action = "status", overrides)
219
286
  || command.startsWith(candidate + " ") || command.startsWith(`"${candidate}" `)
220
287
  || command.endsWith(" " + candidate) || command.includes(` ${candidate} `) || command.includes(` "${candidate}"`);
221
288
  }) || roots.some(root => normalize(row.command).includes(root + (runtime.platform === "win32" ? "\\" : "/"))))
289
+ // 別のCODEX_HOMEで動くCodex(同じ端末の他の利用者やBot)は、このhookを読まないので再起動を求めない。
290
+ .filter(row => {
291
+ const home = runtime.codexHomeOf(row.pid);
292
+ return home === null || samePath(home, runtime.codex_home);
293
+ })
222
294
  .map(({ pid, started_identity }) => ({ pid, started_identity }))
223
295
  : previous.stale_processes;
224
296
  const config = { schema: profile.codex_hook_schema, enabled: true,
package/dist/index.d.ts CHANGED
@@ -8,7 +8,7 @@ export { realCodexHome, resolveCodexExecutable, desktopBundledCodex, findDesktop
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 { codexHookCommand, mergeCodexParentHooks, planCodexParentHooks, writeCodexHookPlan, applyCodexHookPlan, verifyCodexHookRegistration, configureCodexSteer, type CodexHookMove, type CodexHookPlan, type CodexSteerAction, type CodexSteerResult, type CodexSteerRuntime, } from "./codex-setup.js";
11
+ export { codexHookCommand, processCodexHome, mergeCodexParentHooks, planCodexParentHooks, writeCodexHookPlan, applyCodexHookPlan, verifyCodexHookRegistration, configureCodexSteer, type CodexHookMove, type CodexHookPlan, type CodexSteerAction, type CodexSteerResult, type CodexSteerRuntime, } from "./codex-setup.js";
12
12
  export { claudeParentSchema, prepareClaudeHookRequest, claudeParentFromRequest, verifyClaudeParent, bindClaudeParentDelivery, closeClaudeParentSession, submitClaudeParentAnswer, runClaudeResultHook, type ClaudeParent, } from "./claude-receiver.js";
13
13
  export { cursorParentSchema, isCursorMcpClient, cursorHooksFile, cursorParentHooksRegistered, verifyCursorParent, cursorParentFromRequest, prepareCursorDelivery, submitCursorParentAnswer, handleCursorHook, receiveCursorAnswer, type CursorParent, type CursorReceiveResult, } from "./cursor-receiver.js";
14
14
  export { cursorReceiveProcess, runCursorReceive, type WaitProcess } from "./cursor-receive.js";
package/dist/index.js CHANGED
@@ -10,7 +10,7 @@ export { realCodexHome, resolveCodexExecutable, desktopBundledCodex, findDesktop
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 { codexHookCommand, mergeCodexParentHooks, planCodexParentHooks, writeCodexHookPlan, applyCodexHookPlan, verifyCodexHookRegistration, configureCodexSteer, } from "./codex-setup.js";
13
+ export { codexHookCommand, processCodexHome, mergeCodexParentHooks, planCodexParentHooks, writeCodexHookPlan, applyCodexHookPlan, verifyCodexHookRegistration, configureCodexSteer, } from "./codex-setup.js";
14
14
  export { claudeParentSchema, prepareClaudeHookRequest, claudeParentFromRequest, verifyClaudeParent, bindClaudeParentDelivery, closeClaudeParentSession, submitClaudeParentAnswer, runClaudeResultHook, } from "./claude-receiver.js";
15
15
  export { cursorParentSchema, isCursorMcpClient, cursorHooksFile, cursorParentHooksRegistered, verifyCursorParent, cursorParentFromRequest, prepareCursorDelivery, submitCursorParentAnswer, handleCursorHook, receiveCursorAnswer, } from "./cursor-receiver.js";
16
16
  export { cursorReceiveProcess, runCursorReceive } from "./cursor-receive.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-steer-delivery",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
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",