aiterm-mcp 0.7.1 → 0.8.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/README.ja.md +137 -63
- package/README.md +136 -62
- package/dist/core.js +273 -44
- package/dist/index.js +30 -7
- package/dist/rtk.js +53 -18
- package/package.json +5 -2
package/dist/core.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* トークン削減して受け取る。SSH/docker は専用機能にせず send(id, "ssh host") で中に入る(ネスト)。
|
|
6
6
|
* セッションは tmux サーバ常駐ゆえ、本プロセスが毎回終了しても次回 read で再接続できる。
|
|
7
7
|
*
|
|
8
|
-
* 設計: docs/
|
|
8
|
+
* 設計: docs/01_design-plan.md / docs/02_mcp-plan.md。出力削減は rag/ の RTK を移植。
|
|
9
9
|
*/
|
|
10
10
|
import { spawnSync } from "node:child_process";
|
|
11
11
|
import * as fs from "node:fs";
|
|
@@ -31,14 +31,26 @@ export const DEFAULT_TIMEOUT = 10.0;
|
|
|
31
31
|
const POLL = 0.25;
|
|
32
32
|
const STABLE_POLLS = 2; // 連続でログサイズ不変ならば静止とみなす回数
|
|
33
33
|
const SHELLS = new Set(["bash", "sh", "zsh", "fish", "dash"]);
|
|
34
|
+
// mark の sentinel は POSIX シェル構文(; と "$?")に依存する。これらの非 POSIX 対話シェルが
|
|
35
|
+
// 前面のときは "$?" が正しく展開されず sentinel が壊れるので mark を拒否する(B8)。ssh/docker で
|
|
36
|
+
// リモート POSIX シェルに入っている場合は前面が "ssh"/"docker" 等で本集合に含まれず=許可される。
|
|
37
|
+
const NON_POSIX_MARK_SHELLS = new Set(["fish", "csh", "tcsh"]);
|
|
38
|
+
// mark:true が付ける完了 sentinel の検出正規表現。printf の実出力は rc=<数字>、コマンド行の
|
|
39
|
+
// エコーは rc=%d(リテラル)。数字アンカーでエコーに免疫化し、部分一致による早期誤完了を防ぐ(B1)。
|
|
40
|
+
// send の printf 書式(`rc=%d`)と対で保守すること。
|
|
41
|
+
const MARK_DONE_RE = /<<<AITERM_DONE rc=[0-9]+>>>/;
|
|
34
42
|
// 出力削減(RTK の CAP 思想を移植)
|
|
35
43
|
const MAX_LINES_BEFORE_ELIDE = 60;
|
|
36
44
|
const HEAD_LINES = 30;
|
|
37
45
|
const TAIL_LINES = 20;
|
|
38
46
|
const DEDUP_MIN_RUN = 3; // 同一行がこれ以上連続したら 1 行+件数に畳む
|
|
47
|
+
const MAX_FULL_BYTES = 8 * 1024 * 1024; // full/range 読取で一度にメモリへ載せる上限(B7)
|
|
39
48
|
// 安全: send 前に弾く破壊的コマンド(外部システム境界の防御)
|
|
40
49
|
const DESTRUCTIVE = [
|
|
41
|
-
|
|
50
|
+
// rm -rf の危険な対象形(best-effort・force で越えられる)。先頭の任意クオート ['"]? で
|
|
51
|
+
// `rm -rf "/"` / `'/'` / `"~"` を捕捉。`\.\/\*`=./*(相対 glob)、`\.\.?\/?\s*$`=. / .. / ./ / ../
|
|
52
|
+
// (カレント/親そのもの)。`./build` 等の相対サブディレクトリは末尾でないので非該当(過剰ブロック回避)。
|
|
53
|
+
/\brm\s+-[rfRF]*[rf][rfRF]*\s+['"]?(\/|~|\$HOME|\.\/\*|\.\.?\/?\s*$|\*\s*$)/i,
|
|
42
54
|
/\bmkfs(\.\w+)?\b/i,
|
|
43
55
|
/\bdd\b[^\n]*\bof=\/dev\//i,
|
|
44
56
|
/>\s*\/dev\/(sd|nvme|hd|mmcblk)/i,
|
|
@@ -50,7 +62,8 @@ const DESTRUCTIVE = [
|
|
|
50
62
|
/\bgit\s+reset\s+--hard\b/i,
|
|
51
63
|
];
|
|
52
64
|
// CSI/OSC/ESC エスケープ・制御文字
|
|
53
|
-
|
|
65
|
+
// CSI / OSC(BEL or ST 終端) / DCS・PM・APC・SOS(ESC P/^/_/X … BEL or ST 終端。ペイロード本文ごと除去=B10) / 残る2文字エスケープ
|
|
66
|
+
const ANSI_RE = /\x1b\[[0-9;?]*[ -\/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[P^_X][\s\S]*?(?:\x07|\x1b\\)|\x1b[@-_]/g;
|
|
54
67
|
const CTRL_RE = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g; // \t(09) \n(0a) は残す
|
|
55
68
|
const PASTE_MARKERS_RE = /\x1b\[20[01]~/g;
|
|
56
69
|
// よく使う制御キーの別名(tmux のキー名へ)
|
|
@@ -189,6 +202,10 @@ function offsetpath(name) {
|
|
|
189
202
|
function lastcmdpath(name) {
|
|
190
203
|
return path.join(SOCKDIR, name + ".lastcmd");
|
|
191
204
|
}
|
|
205
|
+
// mark:true 送信中フラグ。存在すれば waitCompletion が sentinel 完了検出(MARK_DONE_RE)を有効化する。
|
|
206
|
+
function markpath(name) {
|
|
207
|
+
return path.join(SOCKDIR, name + ".mark");
|
|
208
|
+
}
|
|
192
209
|
function readOffset(name) {
|
|
193
210
|
try {
|
|
194
211
|
const n = parseInt(fs.readFileSync(offsetpath(name), "utf8").trim(), 10);
|
|
@@ -337,16 +354,35 @@ async function settleWinLog(name) {
|
|
|
337
354
|
await sleep(POLL * 1000);
|
|
338
355
|
}
|
|
339
356
|
}
|
|
340
|
-
/** 完了境界: dead / until 一致 / (出力静止 ∧ シェル復帰)=quiescent / (ネスト中+until無しで出力静止)=nested(未確定・早期返却) / timeout。 */
|
|
341
|
-
async function waitCompletion(name,
|
|
357
|
+
/** 完了境界: dead / mark sentinel 一致 / until 一致 / (出力静止 ∧ シェル復帰)=quiescent / (ネスト中+until/mark無しで出力静止)=nested(未確定・早期返却) / timeout。 */
|
|
358
|
+
async function waitCompletion(name, untilStr, untilRegex, timeout) {
|
|
342
359
|
// 締切は単調時計で測る。Date.now() は NTP 補正やサスペンドで巻き戻り、長時間待ちで誤判定する(Python は time.monotonic)。
|
|
343
360
|
const deadline = performance.now() + timeout * 1000;
|
|
344
361
|
const start = readOffset(name);
|
|
345
362
|
let lastSize = null;
|
|
346
363
|
let stable = 0;
|
|
347
|
-
|
|
364
|
+
// until は既定でリテラル部分一致(`$ ` や `[sudo]` 等がメタ化して永遠に待つ footgun を避ける・B4)。
|
|
365
|
+
// untilRegex:true のときだけ正規表現として解釈し、不正パターンは明示エラーにする(B13 の until 部分)。
|
|
366
|
+
let until = null;
|
|
367
|
+
if (untilStr) {
|
|
368
|
+
if (untilRegex) {
|
|
369
|
+
let re;
|
|
370
|
+
try {
|
|
371
|
+
re = new RegExp(untilStr);
|
|
372
|
+
}
|
|
373
|
+
catch (e) {
|
|
374
|
+
throw new AitermError(`until 正規表現が不正です: ${JSON.stringify(untilStr)}(${e.message})`, 2);
|
|
375
|
+
}
|
|
376
|
+
until = (s) => re.test(s);
|
|
377
|
+
}
|
|
378
|
+
else {
|
|
379
|
+
until = (s) => s.includes(untilStr);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
// mark:true 送信中なら sentinel 完了検出を有効化する。エコー(rc=%d)でなく実出力(rc=<数字>)だけに
|
|
383
|
+
// 一致する数字アンカー MARK_DONE_RE を使うため、until のようにエコー部分一致で早期誤完了しない(B1)。
|
|
384
|
+
const markActive = fs.existsSync(markpath(name));
|
|
348
385
|
for (;;) {
|
|
349
|
-
const alive = sessionExists(name);
|
|
350
386
|
let size = 0;
|
|
351
387
|
try {
|
|
352
388
|
size = fs.statSync(logpath(name)).size;
|
|
@@ -354,13 +390,49 @@ async function waitCompletion(name, untilRe, timeout) {
|
|
|
354
390
|
catch {
|
|
355
391
|
size = 0;
|
|
356
392
|
}
|
|
357
|
-
if (until && size > start) {
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
393
|
+
if ((until || markActive) && size > start) {
|
|
394
|
+
// 増分 [start, size] だけを fd で読む(毎 poll で全ファイルを読む O(n^2) を避ける・B6)。
|
|
395
|
+
let neu = "";
|
|
396
|
+
let fd;
|
|
397
|
+
try {
|
|
398
|
+
fd = fs.openSync(logpath(name), "r");
|
|
399
|
+
const len = size - start;
|
|
400
|
+
const buf = Buffer.alloc(len);
|
|
401
|
+
const n = fs.readSync(fd, buf, 0, len, start);
|
|
402
|
+
neu = stripControl(buf.subarray(0, Math.max(0, n)).toString("utf8"));
|
|
403
|
+
}
|
|
404
|
+
catch {
|
|
405
|
+
neu = ""; // close 等でログが消えた: 次周回の !alive/statSync で決着させる
|
|
406
|
+
}
|
|
407
|
+
finally {
|
|
408
|
+
if (fd !== undefined) {
|
|
409
|
+
try {
|
|
410
|
+
fs.closeSync(fd);
|
|
411
|
+
}
|
|
412
|
+
catch {
|
|
413
|
+
/* noop */
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
// mark を until より先に判定(sentinel は確証つき完了。until はユーザ指定でエコー誤爆余地あり)。
|
|
418
|
+
if (markActive && MARK_DONE_RE.test(neu)) {
|
|
419
|
+
try {
|
|
420
|
+
fs.unlinkSync(markpath(name)); // 同一 sentinel での再発火を防ぐ
|
|
421
|
+
}
|
|
422
|
+
catch {
|
|
423
|
+
/* noop */
|
|
424
|
+
}
|
|
425
|
+
if (isWin)
|
|
426
|
+
await settleWinLog(name);
|
|
427
|
+
return [true, "mark"];
|
|
428
|
+
}
|
|
429
|
+
if (until && until(neu))
|
|
361
430
|
return [true, "until"];
|
|
362
431
|
}
|
|
363
|
-
|
|
432
|
+
// 出力が伸びている間は生存確認(tmux has-session の spawn)を省く=伸長は生存の証(B6)。
|
|
433
|
+
// 静止時のみ has-session を叩いて dead を判定する。dead 検出は最大 1 poll 遅れるだけ。
|
|
434
|
+
const growing = lastSize !== null && size > lastSize;
|
|
435
|
+
if (!growing && !sessionExists(name)) {
|
|
364
436
|
if (isWin)
|
|
365
437
|
await settleWinLog(name);
|
|
366
438
|
return [true, "dead"];
|
|
@@ -375,10 +447,11 @@ async function waitCompletion(name, untilRe, timeout) {
|
|
|
375
447
|
return [true, "quiescent"]; // 出力静止 ∧ シェル復帰 = 確証つき完了
|
|
376
448
|
}
|
|
377
449
|
// ネスト中(前面が ssh/docker/REPL 等でシェル集合外)は quiescence の「シェル復帰」条件を
|
|
378
|
-
// 原理的に満たせない。until
|
|
379
|
-
//
|
|
450
|
+
// 原理的に満たせない。until も mark も無ければこれ以上待っても確証は増えない(until/dead/
|
|
451
|
+
// quiescent/mark のいずれも発火し得ない)ので、出力静止時点で「未確定」のまま早期返却する。
|
|
452
|
+
// markActive のときは sentinel を待つべく早期返却せず、非シェル前面(sleep 等)でも待ち続ける。
|
|
380
453
|
// fg==="" は前面コマンド取得失敗=ネスト断定不可なので早期返却せず従来どおり timeout まで待つ。
|
|
381
|
-
if (!until && fg !== "") {
|
|
454
|
+
if (!until && !markActive && fg !== "") {
|
|
382
455
|
if (isWin)
|
|
383
456
|
await settleWinLog(name);
|
|
384
457
|
return [false, "nested"];
|
|
@@ -394,10 +467,10 @@ async function waitCompletion(name, untilRe, timeout) {
|
|
|
394
467
|
await sleep(POLL * 1000);
|
|
395
468
|
}
|
|
396
469
|
}
|
|
397
|
-
// 完了ステータス → is_complete 表記。確証のある層のみ True(until/dead/quiescent)。
|
|
470
|
+
// 完了ステータス → is_complete 表記。確証のある層のみ True(mark/until/dead/quiescent)。
|
|
398
471
|
// timeout と nested(ネスト中・出力静止だが確証なし)は False。nested は until/mark を促す注記を添える。
|
|
399
472
|
function completionSuffix(status) {
|
|
400
|
-
const complete = status === "until" || status === "dead" || status === "quiescent";
|
|
473
|
+
const complete = status === "mark" || status === "until" || status === "dead" || status === "quiescent";
|
|
401
474
|
let s = ` [is_complete=${complete ? "True" : "False"} via ${status}]`;
|
|
402
475
|
if (status === "nested")
|
|
403
476
|
s +=
|
|
@@ -453,7 +526,18 @@ export function openSession(name, shell = "bash") {
|
|
|
453
526
|
nm = nonceName();
|
|
454
527
|
assertSessionName(nm);
|
|
455
528
|
}
|
|
456
|
-
|
|
529
|
+
// 新規セッションの .log は必ず truncate する。"a"(追記)だと外部 kill / killAll / クラッシュで
|
|
530
|
+
// 同名 session だけ消えて .log が残った場合、offset=0 と相まって旧出力を新規として返す(B5)。
|
|
531
|
+
// break は new-session 成功後にのみ到達=作りたての空 session ゆえ切り詰めは安全。lastcmd/mark 残骸も掃除。
|
|
532
|
+
fs.writeFileSync(logpath(nm), "");
|
|
533
|
+
for (const p of [lastcmdpath(nm), markpath(nm)]) {
|
|
534
|
+
try {
|
|
535
|
+
fs.unlinkSync(p);
|
|
536
|
+
}
|
|
537
|
+
catch {
|
|
538
|
+
/* noop */
|
|
539
|
+
}
|
|
540
|
+
}
|
|
457
541
|
// pipe-pane の引数は tmux 内部の /bin/sh -c で再解釈される(argv ではない)。パスは単一引用符で包み、
|
|
458
542
|
// パス自身の ' は '\'' イディオムでエスケープする(名前は検証済みだが、Windows ユーザー名 O'Brien 等が
|
|
459
543
|
// 一時パスに ' を持ち込み redirect を壊すのを防ぐ。空白対策も兼ねる)。Windows は WSL から見える /mnt/c 形へ。
|
|
@@ -463,6 +547,12 @@ export function openSession(name, shell = "bash") {
|
|
|
463
547
|
if (pr.code !== 0) {
|
|
464
548
|
// 配管に失敗した session は pty_read が永遠に空を返す=成功を装わない。作った session を片付けて明示エラー。
|
|
465
549
|
tmux("kill-session", "-t", nm);
|
|
550
|
+
try {
|
|
551
|
+
fs.unlinkSync(logpath(nm)); // B14: 直前に作った空 .log も残さない
|
|
552
|
+
}
|
|
553
|
+
catch {
|
|
554
|
+
/* noop */
|
|
555
|
+
}
|
|
466
556
|
throw new AitermError("tmux pipe-pane 失敗(出力ログを配管できないため session を破棄): " + pr.stderr.trim(), 2);
|
|
467
557
|
}
|
|
468
558
|
writeOffset(nm, 0);
|
|
@@ -484,11 +574,37 @@ export function send(name, text, o = {}) {
|
|
|
484
574
|
}
|
|
485
575
|
}
|
|
486
576
|
}
|
|
577
|
+
if (o.mark) {
|
|
578
|
+
// mark の sentinel は POSIX シェル構文。前面が fish/csh/tcsh 等の非 POSIX 対話シェルだと "$?" が
|
|
579
|
+
// 壊れて sentinel が成立しない。黙って壊れた完了検出を作らず、明示エラーで until を促す(B8)。
|
|
580
|
+
const fg = paneCurrentCommand(name);
|
|
581
|
+
if (NON_POSIX_MARK_SHELLS.has(fg)) {
|
|
582
|
+
throw new AitermError(`mark は POSIX シェル(bash/sh/zsh/dash)前提です。前面が ${fg} のため sentinel の "$?" が` +
|
|
583
|
+
`正しく展開されません。until で完了パターンを指定してください。`, 2);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
487
586
|
writeLastcmd(name, text); // read rtk の reducer 分類用(書換/mark 前の素のコマンド)
|
|
488
587
|
if (o.rtk)
|
|
489
588
|
text = rtkRewrite(text);
|
|
490
|
-
if (o.mark)
|
|
589
|
+
if (o.mark) {
|
|
590
|
+
// 実出力は rc=<数字>、この行のエコーは rc=%d(リテラル)。MARK_DONE_RE は数字アンカーで後者に免疫。
|
|
491
591
|
text = text + `; printf '\\n<<<AITERM_DONE rc=%d>>>\\n' "$?"`;
|
|
592
|
+
try {
|
|
593
|
+
fs.writeFileSync(markpath(name), "1"); // waitCompletion に sentinel 完了検出を有効化させる
|
|
594
|
+
}
|
|
595
|
+
catch {
|
|
596
|
+
/* noop(フラグ書けなくても until/quiescence 経路は生きる) */
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
else {
|
|
600
|
+
// 非 mark 送信は、未消化の古い mark 完了待ちを無効化する(前コマンドの sentinel を待ち続けない)。
|
|
601
|
+
try {
|
|
602
|
+
fs.unlinkSync(markpath(name));
|
|
603
|
+
}
|
|
604
|
+
catch {
|
|
605
|
+
/* noop */
|
|
606
|
+
}
|
|
607
|
+
}
|
|
492
608
|
tmux("send-keys", "-t", name, "-l", "--", text);
|
|
493
609
|
if (enter)
|
|
494
610
|
tmux("send-keys", "-t", name, "Enter");
|
|
@@ -503,50 +619,121 @@ export function sendKey(name, key) {
|
|
|
503
619
|
tmux("send-keys", "-t", name, k);
|
|
504
620
|
return `sent key ${k} to ${name}`;
|
|
505
621
|
}
|
|
622
|
+
// end 以下で最大の UTF-8 文字境界を返す(B3)。末尾が不完全なマルチバイト列なら、その開始位置まで
|
|
623
|
+
// 戻す。pipe-pane が多バイト文字の途中でフラッシュした瞬間の増分読みで先頭/末尾が U+FFFD 化するのを防ぐ。
|
|
624
|
+
export function utf8SafeEnd(buf, end) {
|
|
625
|
+
if (end <= 0)
|
|
626
|
+
return 0;
|
|
627
|
+
const isCont = (b) => (b & 0xc0) === 0x80; // 継続バイト 10xxxxxx
|
|
628
|
+
let i = end - 1;
|
|
629
|
+
let steps = 0;
|
|
630
|
+
while (i >= 0 && isCont(buf[i]) && steps < 3) {
|
|
631
|
+
i--;
|
|
632
|
+
steps++;
|
|
633
|
+
}
|
|
634
|
+
if (i < 0)
|
|
635
|
+
return end; // 継続バイトのみの異常列: そのまま
|
|
636
|
+
const lead = buf[i];
|
|
637
|
+
let need;
|
|
638
|
+
if (lead < 0x80)
|
|
639
|
+
need = 1;
|
|
640
|
+
else if ((lead & 0xe0) === 0xc0)
|
|
641
|
+
need = 2;
|
|
642
|
+
else if ((lead & 0xf0) === 0xe0)
|
|
643
|
+
need = 3;
|
|
644
|
+
else if ((lead & 0xf8) === 0xf0)
|
|
645
|
+
need = 4;
|
|
646
|
+
else
|
|
647
|
+
return end; // 不正な先行バイト: そのまま(stripControl 等に委ねる)
|
|
648
|
+
return end - i >= need ? end : i; // 末尾文字が完結していれば end、不完全なら開始位置まで戻す
|
|
649
|
+
}
|
|
506
650
|
export async function readOutput(name, o = {}) {
|
|
507
651
|
assertSessionName(name);
|
|
508
652
|
const timeout = o.timeout ?? DEFAULT_TIMEOUT;
|
|
509
653
|
if (!sessionExists(name) && !fs.existsSync(logpath(name)))
|
|
510
654
|
throw new AitermError(`session '${name}' が無い`, 2);
|
|
655
|
+
// wait は screen より先に処理する。従来 screen は wait ブロックの手前で return し、screen+wait で
|
|
656
|
+
// 完了検出が黙殺されていた(B11)。先に待ってから最終スクリーンを撮る=TUI の描画完了後に読める。
|
|
657
|
+
let status = null;
|
|
658
|
+
if (o.wait) {
|
|
659
|
+
const [, st] = await waitCompletion(name, o.until ?? null, o.untilRegex ?? false, timeout);
|
|
660
|
+
status = st;
|
|
661
|
+
}
|
|
511
662
|
if (o.screen) {
|
|
512
663
|
const rawTxt = captureScreen(name, o.lines || 0);
|
|
513
664
|
if (o.raw)
|
|
514
665
|
return rawTxt;
|
|
515
666
|
const [body, meta] = reduceOutput(rawTxt, name, true);
|
|
516
|
-
return body + "\n" + meta;
|
|
517
|
-
}
|
|
518
|
-
let status = null;
|
|
519
|
-
if (o.wait) {
|
|
520
|
-
const [, st] = await waitCompletion(name, o.until ?? null, timeout);
|
|
521
|
-
status = st;
|
|
667
|
+
return body + "\n" + meta + (status ? completionSuffix(status) : "");
|
|
522
668
|
}
|
|
523
|
-
|
|
669
|
+
// ログ全体を毎回メモリに載せず、必要な範囲だけ fd で読む(B7)。size は statSync で取る。
|
|
670
|
+
let size = 0;
|
|
524
671
|
try {
|
|
525
|
-
|
|
672
|
+
size = fs.statSync(logpath(name)).size;
|
|
526
673
|
}
|
|
527
674
|
catch {
|
|
528
|
-
|
|
675
|
+
size = 0;
|
|
529
676
|
}
|
|
677
|
+
const readRange = (from, to) => {
|
|
678
|
+
const len = Math.max(0, to - from);
|
|
679
|
+
if (len === 0)
|
|
680
|
+
return Buffer.alloc(0);
|
|
681
|
+
let fd;
|
|
682
|
+
try {
|
|
683
|
+
fd = fs.openSync(logpath(name), "r");
|
|
684
|
+
const buf = Buffer.alloc(len);
|
|
685
|
+
const n = fs.readSync(fd, buf, 0, len, from);
|
|
686
|
+
return n === len ? buf : buf.subarray(0, Math.max(0, n));
|
|
687
|
+
}
|
|
688
|
+
catch {
|
|
689
|
+
return Buffer.alloc(0);
|
|
690
|
+
}
|
|
691
|
+
finally {
|
|
692
|
+
if (fd !== undefined) {
|
|
693
|
+
try {
|
|
694
|
+
fs.closeSync(fd);
|
|
695
|
+
}
|
|
696
|
+
catch {
|
|
697
|
+
/* noop */
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
};
|
|
530
702
|
let text;
|
|
703
|
+
let nextOffset = size; // 既定/full は offset を末尾へ
|
|
531
704
|
if (o.full || o.range) {
|
|
532
|
-
|
|
705
|
+
// full/range は全体が対象だが、巨大ログは末尾 MAX_FULL_BYTES に制限してメモリを守る(B7)。
|
|
706
|
+
let from = 0;
|
|
707
|
+
if (size > MAX_FULL_BYTES)
|
|
708
|
+
from = size - MAX_FULL_BYTES;
|
|
709
|
+
text = readRange(from, size).toString("utf8");
|
|
710
|
+
if (from > 0)
|
|
711
|
+
text = `[… 先頭 ${from} バイトを省略(ログがサイズ上限を超過。close で破棄されます)…]\n` + text;
|
|
533
712
|
if (o.range) {
|
|
534
713
|
const [lo, hi] = o.range;
|
|
535
714
|
text = text.split("\n").slice(lo, hi ?? undefined).join("\n");
|
|
536
715
|
}
|
|
716
|
+
else if (o.lines) {
|
|
717
|
+
// full + lines は末尾 N 行にする(従来は full 経路で lines を黙殺していた footgun・B11)。
|
|
718
|
+
text = text.split("\n").slice(-o.lines).join("\n");
|
|
719
|
+
}
|
|
537
720
|
}
|
|
538
721
|
else {
|
|
539
722
|
let off = readOffset(name);
|
|
540
723
|
// WSL 再起動等でログが作り直されると、Windows 側に残った旧 offset が新ログ長を超え、
|
|
541
|
-
//
|
|
542
|
-
if (off >
|
|
724
|
+
// 空を返して「何も読めない」状態になる。末尾越えは先頭から読み直す(POSIX では no-op)。
|
|
725
|
+
if (off > size)
|
|
543
726
|
off = 0;
|
|
544
|
-
|
|
727
|
+
const buf = readRange(off, size); // 増分のみをメモリに載せる
|
|
728
|
+
// 末尾の不完全マルチバイト列は次回へ持ち越す(B3)。off は前回この分岐が safeEnd を書くので先頭は割れない。
|
|
729
|
+
const safeLen = utf8SafeEnd(buf, buf.length);
|
|
730
|
+
text = buf.subarray(0, safeLen).toString("utf8");
|
|
731
|
+
nextOffset = off + safeLen;
|
|
545
732
|
if (o.lines)
|
|
546
733
|
text = text.split("\n").slice(-o.lines).join("\n");
|
|
547
734
|
}
|
|
548
735
|
if (!o.range)
|
|
549
|
-
writeOffset(name,
|
|
736
|
+
writeOffset(name, nextOffset);
|
|
550
737
|
if (o.raw)
|
|
551
738
|
return text.endsWith("\n") ? text : text + "\n";
|
|
552
739
|
if (o.rtk) {
|
|
@@ -578,7 +765,7 @@ export function listSessions() {
|
|
|
578
765
|
export function closeSession(name) {
|
|
579
766
|
assertSessionName(name);
|
|
580
767
|
tmux("kill-session", "-t", name);
|
|
581
|
-
for (const p of [logpath(name), offsetpath(name), lastcmdpath(name)]) {
|
|
768
|
+
for (const p of [logpath(name), offsetpath(name), lastcmdpath(name), markpath(name)]) {
|
|
582
769
|
try {
|
|
583
770
|
fs.unlinkSync(p);
|
|
584
771
|
}
|
|
@@ -590,6 +777,22 @@ export function closeSession(name) {
|
|
|
590
777
|
}
|
|
591
778
|
export function killAll() {
|
|
592
779
|
tmux("kill-server");
|
|
780
|
+
// B9: SOCKDIR 内の .log/.offset/.lastcmd/.mark 残骸も掃除する(残すと B5 の stale-log 復活の温床)。
|
|
781
|
+
try {
|
|
782
|
+
for (const f of fs.readdirSync(SOCKDIR)) {
|
|
783
|
+
if (/\.(log|offset|lastcmd|mark)$/.test(f)) {
|
|
784
|
+
try {
|
|
785
|
+
fs.unlinkSync(path.join(SOCKDIR, f));
|
|
786
|
+
}
|
|
787
|
+
catch {
|
|
788
|
+
/* noop */
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
catch {
|
|
794
|
+
/* SOCKDIR 不在等は無視 */
|
|
795
|
+
}
|
|
593
796
|
return "killed all sessions on this socket";
|
|
594
797
|
}
|
|
595
798
|
function resolveAgentBin(kind) {
|
|
@@ -598,8 +801,14 @@ function resolveAgentBin(kind) {
|
|
|
598
801
|
? ["CODEX_BIN", [".local", "bin", "codex"], "codex"]
|
|
599
802
|
: ["GROK_BIN", [".grok", "bin", "grok"], "grok"];
|
|
600
803
|
const fromEnv = process.env[envVar];
|
|
601
|
-
if (fromEnv)
|
|
602
|
-
|
|
804
|
+
if (fromEnv) {
|
|
805
|
+
// 明示指定 env は実在を検証する。存在しないパスを黙って返すと、session を作って
|
|
806
|
+
// `'/typo' ...` を送信し bash が command not found を出すだけで openAgent は「起動した」と
|
|
807
|
+
// 偽成功を返す(既定パス/PATH 経路は検証するのに env だけ無検証だった非対称の解消・A3)。
|
|
808
|
+
if (fs.existsSync(fromEnv))
|
|
809
|
+
return fromEnv;
|
|
810
|
+
throw new AitermError(`${envVar} に指定された ${name} が存在しません: ${fromEnv}`, 2);
|
|
811
|
+
}
|
|
603
812
|
const cand = path.join(home, ...rel);
|
|
604
813
|
if (fs.existsSync(cand))
|
|
605
814
|
return cand;
|
|
@@ -654,9 +863,16 @@ export function openAgent(kind, opts = {}) {
|
|
|
654
863
|
const where = kind === "codex" ? "~/.local/bin/codex" : "~/.grok/bin/grok";
|
|
655
864
|
throw new AitermError(`${label} の CLI が見つかりません(${where} か PATH が必要)`, 2);
|
|
656
865
|
}
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
866
|
+
// cwd 検証(session を作る前に。cd 失敗はシェル内で静かに死に「起動した」と偽成功を返すため)。
|
|
867
|
+
let cwd = null;
|
|
868
|
+
if (opts.cwd != null) {
|
|
869
|
+
if (!opts.cwd.trim()) {
|
|
870
|
+
throw new AitermError("cwd が空文字です(省略するか有効なディレクトリを指定してください)", 2); // A6
|
|
871
|
+
}
|
|
872
|
+
if (opts.cwd.startsWith("~")) {
|
|
873
|
+
// statSync は ~ を展開しない。「存在しません」でなく展開されない旨を正直に伝える(A6)。
|
|
874
|
+
throw new AitermError(`cwd の ~ は展開されません。絶対パスで指定してください: ${opts.cwd}`, 2);
|
|
875
|
+
}
|
|
660
876
|
let st = null;
|
|
661
877
|
try {
|
|
662
878
|
st = fs.statSync(opts.cwd);
|
|
@@ -667,12 +883,23 @@ export function openAgent(kind, opts = {}) {
|
|
|
667
883
|
if (!st || !st.isDirectory()) {
|
|
668
884
|
throw new AitermError(`cwd '${opts.cwd}' がディレクトリとして存在しません`, 2);
|
|
669
885
|
}
|
|
670
|
-
|
|
886
|
+
cwd = opts.cwd;
|
|
887
|
+
}
|
|
888
|
+
// Windows は起動コマンドが WSL 内 bash で走る(tmux ブリッジ)。bin/cwd を /mnt/c/... 形へ変換して
|
|
889
|
+
// 渡す(ログの toWslPath と対称・A1)。前提: Windows 側に CLI を導入(resolveAgentBin が Windows
|
|
890
|
+
// パスで解決)。toWslPath は session を作る前に呼ぶ=変換失敗(非ドライブパス)で残骸 session を残さない。
|
|
891
|
+
// 未検証リスク: npm グローバル導入の codex.cmd/.bat シムや WSL interop 上の対話 TUI 描画は実 Windows
|
|
892
|
+
// でしか確認できない(CI 非対象。docs/03_audit-sweep-2026-07.md 参照)。
|
|
893
|
+
const binForCmd = isWin ? toWslPath(bin) : bin;
|
|
894
|
+
const cwdForCmd = cwd && isWin ? toWslPath(cwd) : cwd;
|
|
671
895
|
const [sid, hint] = openSession(opts.session_name ?? null, "bash");
|
|
672
|
-
const cmd = buildAgentCmd(kind,
|
|
673
|
-
const full =
|
|
896
|
+
const cmd = buildAgentCmd(kind, binForCmd, effort, opts.prompt ?? null);
|
|
897
|
+
const full = cwdForCmd ? `cd ${shq(cwdForCmd)} && ${cmd}` : cmd;
|
|
674
898
|
try {
|
|
675
|
-
|
|
899
|
+
// force:true で送る。起動骨格は `bin '...'` の固定形で、prompt/cwd/effort は shq でクオート済みの
|
|
900
|
+
// 引数=シェルは決して破壊コマンドとして実行しない。破壊ゲート(生シェルコマンド想定)を prompt に
|
|
901
|
+
// 掛けるのは純誤検知で、`codex 'rm -rf / を説明して'` 等の正当な起動を塞いでしまう(A4)。
|
|
902
|
+
send(sid, full, { enter: true, mark: false, force: true, rtk: false, raw: true });
|
|
676
903
|
}
|
|
677
904
|
catch (e) {
|
|
678
905
|
// 起動コマンドを投入できなかった session は空のまま残る=残骸を作らない。片付けてから元エラーを伝える。
|
|
@@ -687,6 +914,8 @@ export function openAgent(kind, opts = {}) {
|
|
|
687
914
|
return [
|
|
688
915
|
sid,
|
|
689
916
|
`${label} を session ${sid} で起動した。\n${hint}\n` +
|
|
690
|
-
`
|
|
917
|
+
`TUI の描画には数秒かかる。少し置いてから pty_read(${sid}, screen:true) で画面を読み、` +
|
|
918
|
+
`pty_send(${sid}, "...") で入力・pty_key(${sid}, "Enter"/"Up"/"C-c" 等) で操作する(対話)。` +
|
|
919
|
+
`起動直後に増分 pty_read すると空/半描画になり得るので screen:true を使う。`,
|
|
691
920
|
];
|
|
692
921
|
}
|
package/dist/index.js
CHANGED
|
@@ -12,7 +12,13 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
|
12
12
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
13
13
|
import { z } from "zod";
|
|
14
14
|
import * as core from "./core.js";
|
|
15
|
-
|
|
15
|
+
import { createRequire } from "node:module";
|
|
16
|
+
// package.json の version を実行時に読み、MCP initialize で配るサーバ版と一致させる。
|
|
17
|
+
// createRequire を使うのは、import 属性 `with { type: "json" }` が Node 18.20+ 限定で
|
|
18
|
+
// engines "node >=18"(18.0〜18.19)を SyntaxError で壊し、旧 `assert` 構文は逆に Node 22 で
|
|
19
|
+
// 除去済み=どちらの静的構文も 18〜22 全域を満たせないため(実行時 require が唯一全域で動く)。
|
|
20
|
+
const pkg = createRequire(import.meta.url)("../package.json");
|
|
21
|
+
const server = new McpServer({ name: "aiterm", version: pkg.version });
|
|
16
22
|
function ok(s) {
|
|
17
23
|
return { content: [{ type: "text", text: s }] };
|
|
18
24
|
}
|
|
@@ -43,7 +49,11 @@ server.registerTool("pty_send", {
|
|
|
43
49
|
session_id: z.string(),
|
|
44
50
|
text: z.string().describe("送る文字列(コマンド)"),
|
|
45
51
|
enter: z.boolean().default(true).describe("末尾で Enter を送る"),
|
|
46
|
-
mark: z
|
|
52
|
+
mark: z
|
|
53
|
+
.boolean()
|
|
54
|
+
.default(false)
|
|
55
|
+
.describe("完了 sentinel(終了コード付き)で包む。pty_read(wait:true) が until 無しでも自動検出して" +
|
|
56
|
+
"完了確定する(ネスト中や非シェル前面でも効く確実な完了検出。手で until を組む必要なし)"),
|
|
47
57
|
force: z.boolean().default(false).describe("破壊的コマンドゲートを越える"),
|
|
48
58
|
rtk: z.boolean().default(false).describe("既知コマンドを rtk 形へ委譲して送る(rtk 不在なら素通し)"),
|
|
49
59
|
raw: z.boolean().default(false).describe("送信前サニタイズを無効化"),
|
|
@@ -61,8 +71,18 @@ server.registerTool("pty_read", {
|
|
|
61
71
|
"削減: 制御文字除去 / 反復圧縮 / head+tail 折りたたみ+復元ヒント+メタ併記。",
|
|
62
72
|
inputSchema: {
|
|
63
73
|
session_id: z.string(),
|
|
64
|
-
wait: z
|
|
65
|
-
|
|
74
|
+
wait: z
|
|
75
|
+
.boolean()
|
|
76
|
+
.default(false)
|
|
77
|
+
.describe("完了まで待つ(dead / mark sentinel 自動検出 / until / 出力静止∧シェル復帰 / timeout)"),
|
|
78
|
+
until: z
|
|
79
|
+
.string()
|
|
80
|
+
.nullish()
|
|
81
|
+
.describe("この文字列が出たら完了とみなす(既定はリテラル部分一致。`$ ` や `[..]` もそのまま探せる)"),
|
|
82
|
+
until_regex: z
|
|
83
|
+
.boolean()
|
|
84
|
+
.default(false)
|
|
85
|
+
.describe("until を正規表現として扱う(既定 false=リテラル部分一致。メタ文字を使いたい時のみ true)"),
|
|
66
86
|
timeout: z.number().default(10).describe("wait の最大待ち秒数"),
|
|
67
87
|
screen: z.boolean().default(false).describe("描画済みスクリーン(TUI 向け)"),
|
|
68
88
|
full: z.boolean().default(false).describe("増分でなく全文"),
|
|
@@ -71,20 +91,23 @@ server.registerTool("pty_read", {
|
|
|
71
91
|
raw: z.boolean().default(false).describe("削減せず生テキスト"),
|
|
72
92
|
rtk: z.boolean().default(false).describe("直前コマンド別の自前 reducer(git/grep/pytest 等)で縮約"),
|
|
73
93
|
},
|
|
74
|
-
}, async ({ session_id, wait, until, timeout, screen, full, lines, line_range, raw, rtk }) => {
|
|
94
|
+
}, async ({ session_id, wait, until, until_regex, timeout, screen, full, lines, line_range, raw, rtk }) => {
|
|
75
95
|
try {
|
|
76
96
|
let range = null;
|
|
77
97
|
if (line_range) {
|
|
78
98
|
const idx = line_range.indexOf(":");
|
|
79
99
|
const lo = idx < 0 ? line_range : line_range.slice(0, idx);
|
|
80
100
|
const hi = idx < 0 ? "" : line_range.slice(idx + 1);
|
|
81
|
-
//
|
|
101
|
+
// 不正/空/負の上端は「末尾まで」(null) に倒す。"5:abc" を空に潰さず "5:" と同じく 5 行目以降に。
|
|
102
|
+
// 下端は負値を 0 にクランプする("-3:5" が負 slice にならないように・C12)。
|
|
103
|
+
const loN = Math.max(0, parseInt(lo, 10) || 0);
|
|
82
104
|
const hiN = hi ? parseInt(hi, 10) : NaN;
|
|
83
|
-
range = [
|
|
105
|
+
range = [loN, Number.isNaN(hiN) || hiN < 0 ? null : hiN];
|
|
84
106
|
}
|
|
85
107
|
const out = await core.readOutput(session_id, {
|
|
86
108
|
wait,
|
|
87
109
|
until: until ?? null,
|
|
110
|
+
untilRegex: until_regex,
|
|
88
111
|
timeout,
|
|
89
112
|
screen,
|
|
90
113
|
full,
|