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.
Files changed (44) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/LICENSE +22 -0
  3. package/README.md +75 -0
  4. package/dist/channel.d.ts +106 -0
  5. package/dist/channel.js +484 -0
  6. package/dist/claude-receiver.d.ts +20 -0
  7. package/dist/claude-receiver.js +171 -0
  8. package/dist/cli.d.ts +4 -0
  9. package/dist/cli.js +98 -0
  10. package/dist/codex-binary.d.ts +22 -0
  11. package/dist/codex-binary.js +176 -0
  12. package/dist/codex-hook-state.d.ts +45 -0
  13. package/dist/codex-hook-state.js +119 -0
  14. package/dist/codex-hook.d.ts +2 -0
  15. package/dist/codex-hook.js +13 -0
  16. package/dist/codex-hooks.d.ts +7 -0
  17. package/dist/codex-hooks.js +114 -0
  18. package/dist/codex-receiver.d.ts +20 -0
  19. package/dist/codex-receiver.js +145 -0
  20. package/dist/codex-setup.d.ts +35 -0
  21. package/dist/codex-setup.js +160 -0
  22. package/dist/cursor-receive.d.ts +9 -0
  23. package/dist/cursor-receive.js +31 -0
  24. package/dist/cursor-receiver.d.ts +29 -0
  25. package/dist/cursor-receiver.js +242 -0
  26. package/dist/errors.d.ts +17 -0
  27. package/dist/errors.js +26 -0
  28. package/dist/files.d.ts +4 -0
  29. package/dist/files.js +79 -0
  30. package/dist/hook-main.d.ts +16 -0
  31. package/dist/hook-main.js +139 -0
  32. package/dist/hook-setup.d.ts +16 -0
  33. package/dist/hook-setup.js +222 -0
  34. package/dist/index.d.ts +18 -0
  35. package/dist/index.js +20 -0
  36. package/dist/process.d.ts +17 -0
  37. package/dist/process.js +79 -0
  38. package/dist/profile.d.ts +42 -0
  39. package/dist/profile.js +14 -0
  40. package/dist/setup-node.d.ts +1 -0
  41. package/dist/setup-node.js +16 -0
  42. package/dist/windows.d.ts +13 -0
  43. package/dist/windows.js +76 -0
  44. package/package.json +28 -0
@@ -0,0 +1,79 @@
1
+ // OSのprocess表。PIDの再利用を見分けるため、開始時刻(started_identity)と組にして扱う。
2
+ import { spawnSync } from "node:child_process";
3
+ import { createHash } from "node:crypto";
4
+ import { resolveWindowsPowerShell7 } from "./windows.js";
5
+ const isWin = process.platform === "win32";
6
+ class ProcessTableError extends Error {
7
+ code = 2;
8
+ }
9
+ export function processIdentity(process) {
10
+ return {
11
+ pid: process.pid, process_group_id: process.process_group_id,
12
+ started_identity: process.started_identity, argv_digest: process.argv_digest,
13
+ };
14
+ }
15
+ export function parseCpuTime(value) {
16
+ const match = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+(?:\.\d+)?)$/.exec(value);
17
+ if (!match)
18
+ throw new ProcessTableError("process CPU時間の形式を認識できません");
19
+ return Number(match[1] ?? 0) * 86400 + Number(match[2] ?? 0) * 3600
20
+ + Number(match[3]) * 60 + Number(match[4]);
21
+ }
22
+ export function parsePosixProcessTable(text) {
23
+ return text.split("\n").filter(line => line.trim()).map(line => {
24
+ const match = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\S+\s+\S+\s+\d+\s+\S+\s+\d+)\s+(\S+)\s+(.+)$/.exec(line);
25
+ if (!match)
26
+ throw new ProcessTableError("process一覧の形式を認識できません");
27
+ const command = match[7].trim();
28
+ return {
29
+ pid: Number(match[1]), parent_pid: Number(match[2]), process_group_id: Number(match[3]),
30
+ stopped: match[4].includes("T"),
31
+ started_identity: match[5].trim(), cpu_seconds: parseCpuTime(match[6]), command,
32
+ argv_digest: createHash("sha256").update(command).digest("hex"),
33
+ };
34
+ });
35
+ }
36
+ export function readRuntimeProcesses() {
37
+ if (!isWin) {
38
+ const result = spawnSync("/bin/ps", ["-axww", "-o", "pid=,ppid=,pgid=,stat=,lstart=,time=,command="], {
39
+ encoding: "utf8", env: { ...process.env, LC_ALL: "C" }, timeout: 10000, maxBuffer: 16 * 1024 * 1024,
40
+ });
41
+ if (result.error || result.status !== 0)
42
+ throw new ProcessTableError("OSのprocess一覧を取得できません");
43
+ return parsePosixProcessTable(result.stdout);
44
+ }
45
+ const script = [
46
+ "$ErrorActionPreference='Stop'",
47
+ "[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false)",
48
+ "@(Get-CimInstance Win32_Process | Where-Object { $null -ne $_.CreationDate -and $null -ne $_.CommandLine } | ForEach-Object {",
49
+ "[ordered]@{ pid=[int]$_.ProcessId; parent_pid=[int]$_.ParentProcessId; executable=[string]$_.ExecutablePath; started_identity=$_.CreationDate.ToUniversalTime().ToString('o'); command=$_.CommandLine; cpu_seconds=([double]$_.KernelModeTime+[double]$_.UserModeTime)/10000000 }",
50
+ "}) | ConvertTo-Json -Compress",
51
+ ].join("\n");
52
+ const result = spawnSync(resolveWindowsPowerShell7(), ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], {
53
+ encoding: "utf8", timeout: 15000, maxBuffer: 16 * 1024 * 1024, windowsHide: true,
54
+ });
55
+ if (result.error || result.status !== 0)
56
+ throw new ProcessTableError("Windowsのnative process一覧を取得できません");
57
+ let rows;
58
+ try {
59
+ rows = JSON.parse(result.stdout);
60
+ }
61
+ catch {
62
+ throw new ProcessTableError("Windows process一覧のJSONを読めません");
63
+ }
64
+ if (!Array.isArray(rows))
65
+ throw new ProcessTableError("Windows process一覧が配列ではありません");
66
+ return rows.map(row => {
67
+ if (!row || !Number.isSafeInteger(row.pid) || !Number.isSafeInteger(row.parent_pid)
68
+ || typeof row.command !== "string" || !Number.isFinite(row.cpu_seconds)
69
+ || typeof row.started_identity !== "string" || !Number.isFinite(Date.parse(row.started_identity)))
70
+ throw new ProcessTableError("Windows process一覧のfieldが不正です");
71
+ const command = row.command.trim();
72
+ return {
73
+ pid: row.pid, parent_pid: row.parent_pid, process_group_id: null, stopped: null,
74
+ executable: row.executable,
75
+ started_identity: new Date(row.started_identity).toISOString(),
76
+ command, cpu_seconds: row.cpu_seconds, argv_digest: createHash("sha256").update(command).digest("hex"),
77
+ };
78
+ });
79
+ }
@@ -0,0 +1,42 @@
1
+ export interface ProductProfile {
2
+ /** 製品ID。stateのschema名やhookの見分けに使う(例: "aiterm")。 */
3
+ id: string;
4
+ /** 利用者へのエラー文に出す製品名(例: "Aiterm")。 */
5
+ display_name: string;
6
+ /** 利用者に実行を案内するsetupの入口(例: "aiterm-setup")。 */
7
+ setup_command: string;
8
+ /** CodexのSteerを有効にするsetupの入口(例: "aiterm-setup --codex-steer enable")。 */
9
+ codex_steer_command: string;
10
+ /** 親に登録されたMCP server名(例: "aiterm")。Claudeのmatcherと、Cursorのtool名の正規化に使う。 */
11
+ mcp_server: string;
12
+ /** 親への配送を伴うMCP tool。Claudeのhookはこのtoolだけに付き、Cursorはこのtoolの結果から配送IDを読む。 */
13
+ dispatch_tools: readonly string[];
14
+ /** Claude・Cursorの受信記録を置く、per-userの実行時state。 */
15
+ state_root: () => string;
16
+ /** Codexのhook設定と所有記録を置く、per-userの永続設定。 */
17
+ config_root: () => string;
18
+ /** 製品が同梱するhook入口のファイル名。所有するhookの見分けに使い、製品同士で重ならない名前にする。 */
19
+ hooks: {
20
+ codex: string;
21
+ claude: string;
22
+ cursor: string;
23
+ };
24
+ /** Codex App Serverへ名乗るclient名。 */
25
+ codex_client_name: string;
26
+ /** Codex hook設定のschema名。 */
27
+ codex_hook_schema: string;
28
+ /** 設定ファイルを書き換える前に残す控えの接尾辞(例: ".aiterm-backup")。 */
29
+ backup_suffix: string;
30
+ /**
31
+ * 同じ会話へ何通も送る製品(長く続く受信)の設定。無ければ依頼ごとの単発配送だけを使う。
32
+ * claude_expiry_notice: Claudeの待機がhookの期限(24時間)に近づいた時に、親を起こして待機を張り直すための短い文。
33
+ * 省略すると、期限では親を起こさずに待機を終える(次のturn終了で張り直す)。
34
+ */
35
+ channels?: {
36
+ claude_expiry_notice?: string;
37
+ };
38
+ }
39
+ export declare function codexHookDirectory(profile: ProductProfile): string;
40
+ export declare function claudeHookRoot(profile: ProductProfile): string;
41
+ export declare function cursorHookRoot(profile: ProductProfile): string;
42
+ export declare function channelRoot(profile: ProductProfile): string;
@@ -0,0 +1,14 @@
1
+ // 製品ごとに一度だけ作る識別情報。配送の仕組みは全製品で同じで、ここに置くのは名前と置き場だけ。
2
+ import * as path from "node:path";
3
+ export function codexHookDirectory(profile) {
4
+ return path.join(profile.config_root(), "codex-parent-hooks");
5
+ }
6
+ export function claudeHookRoot(profile) {
7
+ return path.join(profile.state_root(), "claude-parent-hooks");
8
+ }
9
+ export function cursorHookRoot(profile) {
10
+ return path.join(profile.state_root(), "cursor-parent-hooks");
11
+ }
12
+ export function channelRoot(profile) {
13
+ return path.join(profile.state_root(), "steer-channels");
14
+ }
@@ -0,0 +1 @@
1
+ export declare function setupNodeExecutable(executable?: string): string;
@@ -0,0 +1,16 @@
1
+ import { accessSync, constants } from "node:fs";
2
+ import { SetupError } from "./errors.js";
3
+ // HomebrewのCellar実体は更新で消える。保存する起動先には同じformulaのoptを使う。
4
+ export function setupNodeExecutable(executable = process.execPath) {
5
+ const brew = /^(.*)\/Cellar\/(node(?:@\d+)?)\/[^/]+\/bin\/node$/.exec(executable);
6
+ if (!brew)
7
+ return executable;
8
+ const node = `${brew[1]}/opt/${brew[2]}/bin/node`;
9
+ try {
10
+ accessSync(node, constants.X_OK);
11
+ }
12
+ catch {
13
+ throw new SetupError("node_runtime_unavailable", "HomebrewのNode起動先を実行できません。Nodeの導入状態を確認してください");
14
+ }
15
+ return node;
16
+ }
@@ -0,0 +1,13 @@
1
+ export declare const WINDOWS_POWERSHELL_7_COMMAND = "pwsh.exe";
2
+ export declare const WINDOWS_POWERSHELL_7_INSTALL = "winget install --id Microsoft.PowerShell --source winget";
3
+ export type WindowsPowerShellProbe = (command: string, args: readonly string[]) => {
4
+ status: number | null;
5
+ stdout?: string | null;
6
+ error?: NodeJS.ErrnoException;
7
+ };
8
+ export declare function resolveWindowsPowerShell7(probe?: WindowsPowerShellProbe): string;
9
+ export declare const quotePowerShell: (value: string) => string;
10
+ /** PowerShell 7でscriptを実行し、stdoutを返す。失敗の詳細はonFailureが製品のエラーへ変える。 */
11
+ export declare function windowsPowerShellSync(script: string, onFailure: () => Error, timeout?: number): string;
12
+ /** Start-Process -ArgumentListへそのまま渡せる、CommandLineToArgvWの規則で引用した引数列。 */
13
+ export declare function windowsStartProcessArgumentList(args: string[]): string;
@@ -0,0 +1,76 @@
1
+ // WindowsのPowerShell 7と引数の引用。5.1/cmdへは切り替えず、見つからなければ理由付きで止める。
2
+ import { execFileSync, spawnSync } from "node:child_process";
3
+ import * as path from "node:path";
4
+ export const WINDOWS_POWERSHELL_7_COMMAND = "pwsh.exe";
5
+ export const WINDOWS_POWERSHELL_7_INSTALL = "winget install --id Microsoft.PowerShell --source winget";
6
+ class PowerShellError extends Error {
7
+ code = 2;
8
+ }
9
+ const defaultProbe = (command, args) => spawnSync(command, [...args], {
10
+ encoding: "utf8", timeout: 5000, maxBuffer: 16 * 1024, windowsHide: true,
11
+ });
12
+ let resolvedDefault = null;
13
+ export function resolveWindowsPowerShell7(probe = defaultProbe) {
14
+ if (probe === defaultProbe && resolvedDefault !== null)
15
+ return resolvedDefault;
16
+ const located = probe("where.exe", [WINDOWS_POWERSHELL_7_COMMAND]);
17
+ const resolved = located.stdout?.split(/\r?\n/u)
18
+ .find(candidate => path.win32.isAbsolute(candidate)
19
+ && path.win32.basename(candidate).toLowerCase() === WINDOWS_POWERSHELL_7_COMMAND)
20
+ ?? path.win32.join(process.env.ProgramFiles ?? "C:\\Program Files", "PowerShell", "7", WINDOWS_POWERSHELL_7_COMMAND);
21
+ const fail = () => {
22
+ throw new PowerShellError(`PowerShell 7が必要です。Microsoft公式経路で導入してください: ${WINDOWS_POWERSHELL_7_INSTALL}`);
23
+ };
24
+ const executable = resolved;
25
+ const version = probe(executable, ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command",
26
+ '[ordered]@{ edition = $PSVersionTable.PSEdition; major = $PSVersionTable.PSVersion.Major } | ConvertTo-Json -Compress']);
27
+ let identity = null;
28
+ try {
29
+ identity = JSON.parse(version.stdout?.trim() ?? "");
30
+ }
31
+ catch { /* typed failure below */ }
32
+ if (version.status !== 0 || identity?.edition !== "Core"
33
+ || !Number.isInteger(identity.major) || Number(identity.major) < 7)
34
+ fail();
35
+ if (probe === defaultProbe)
36
+ resolvedDefault = executable;
37
+ return executable;
38
+ }
39
+ export const quotePowerShell = (value) => `'${value.replace(/'/g, "''")}'`;
40
+ /** PowerShell 7でscriptを実行し、stdoutを返す。失敗の詳細はonFailureが製品のエラーへ変える。 */
41
+ export function windowsPowerShellSync(script, onFailure, timeout = 15_000) {
42
+ const source = "$ErrorActionPreference = 'Stop'\n[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)\n" + script;
43
+ try {
44
+ return execFileSync(resolveWindowsPowerShell7(), ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand",
45
+ Buffer.from(source, "utf16le").toString("base64")], {
46
+ encoding: "utf8", windowsHide: true, timeout, maxBuffer: 16 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"],
47
+ }).trim();
48
+ }
49
+ catch {
50
+ throw onFailure();
51
+ }
52
+ }
53
+ function quoteWindowsProcessArgument(value) {
54
+ if (value !== "" && !/[\s"]/u.test(value))
55
+ return value;
56
+ let quoted = '"';
57
+ let backslashes = 0;
58
+ for (const char of value) {
59
+ if (char === "\\") {
60
+ backslashes += 1;
61
+ }
62
+ else if (char === '"') {
63
+ quoted += "\\".repeat(backslashes * 2 + 1) + '"';
64
+ backslashes = 0;
65
+ }
66
+ else {
67
+ quoted += "\\".repeat(backslashes) + char;
68
+ backslashes = 0;
69
+ }
70
+ }
71
+ return quoted + "\\".repeat(backslashes * 2) + '"';
72
+ }
73
+ /** Start-Process -ArgumentListへそのまま渡せる、CommandLineToArgvWの規則で引用した引数列。 */
74
+ export function windowsStartProcessArgumentList(args) {
75
+ return args.map(quoteWindowsProcessArgument).join(" ");
76
+ }
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "aiterm-steer-delivery",
3
+ "version": "0.1.0",
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
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": { "name": "Quo", "url": "https://kitepon.dev" },
8
+ "repository": { "type": "git", "url": "git+https://github.com/kitepon/aiterm-steer-delivery.git" },
9
+ "homepage": "https://github.com/kitepon/aiterm-steer-delivery#readme",
10
+ "bugs": "https://github.com/kitepon/aiterm-steer-delivery/issues",
11
+ "keywords": ["mcp", "codex", "claude-code", "cursor", "steer", "hooks", "aiterm", "ai-agents"],
12
+ "engines": { "node": ">=18" },
13
+ "main": "./dist/index.js",
14
+ "types": "./dist/index.d.ts",
15
+ "exports": {
16
+ ".": { "types": "./dist/index.d.ts", "default": "./dist/index.js" },
17
+ "./package.json": "./package.json"
18
+ },
19
+ "bin": { "aiterm-steer-delivery": "dist/cli.js" },
20
+ "files": ["dist/**/*.js", "dist/**/*.d.ts", "README.md", "CHANGELOG.md", "LICENSE"],
21
+ "scripts": {
22
+ "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc",
23
+ "test": "npm run build && node --test test/*.test.mjs",
24
+ "prepublishOnly": "npm run build"
25
+ },
26
+ "dependencies": { "zod": "^4.4.3" },
27
+ "devDependencies": { "@types/node": "^25.9.1", "typescript": "^6.0.3" }
28
+ }