@ai-devkit/agent-manager 0.22.0 → 0.24.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.md +3 -0
- package/dist/__tests__/AgentManager.test.js +9 -1
- package/dist/__tests__/AgentManager.test.js.map +1 -1
- package/dist/__tests__/terminal/TerminalFocusManager.test.js +180 -0
- package/dist/__tests__/terminal/TerminalFocusManager.test.js.map +1 -1
- package/dist/__tests__/terminal/TtyWriter.test.js +232 -8
- package/dist/__tests__/terminal/TtyWriter.test.js.map +1 -1
- package/dist/__tests__/utils/agent-requests.test.js +90 -0
- package/dist/__tests__/utils/agent-requests.test.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/terminal/TerminalFocusManager.d.ts +11 -0
- package/dist/terminal/TerminalFocusManager.d.ts.map +1 -1
- package/dist/terminal/TerminalFocusManager.js +84 -10
- package/dist/terminal/TerminalFocusManager.js.map +1 -1
- package/dist/terminal/TtyWriter.d.ts +20 -0
- package/dist/terminal/TtyWriter.d.ts.map +1 -1
- package/dist/terminal/TtyWriter.js +198 -9
- package/dist/terminal/TtyWriter.js.map +1 -1
- package/dist/utils/agent-requests.d.ts +10 -0
- package/dist/utils/agent-requests.d.ts.map +1 -0
- package/dist/utils/agent-requests.js +22 -0
- package/dist/utils/agent-requests.js.map +1 -0
- package/package.json +1 -1
- package/src/__tests__/AgentManager.test.ts +7 -1
- package/src/__tests__/terminal/TerminalFocusManager.test.ts +187 -0
- package/src/__tests__/terminal/TtyWriter.test.ts +255 -6
- package/src/__tests__/utils/agent-requests.test.ts +74 -0
- package/src/index.ts +3 -0
- package/src/terminal/TerminalFocusManager.ts +103 -11
- package/src/terminal/TtyWriter.ts +184 -7
- package/src/utils/agent-requests.ts +28 -0
|
@@ -5,31 +5,58 @@ import { escapeAppleScript } from '../utils/applescript.js';
|
|
|
5
5
|
const execFileAsync = promisify(execFile);
|
|
6
6
|
export var TerminalType = /*#__PURE__*/ function(TerminalType) {
|
|
7
7
|
TerminalType["TMUX"] = "tmux";
|
|
8
|
+
TerminalType["WEZTERM"] = "wezterm";
|
|
8
9
|
TerminalType["ITERM2"] = "iterm2";
|
|
9
10
|
TerminalType["TERMINAL_APP"] = "terminal-app";
|
|
10
11
|
TerminalType["UNKNOWN"] = "unknown";
|
|
11
12
|
return TerminalType;
|
|
12
13
|
}({});
|
|
13
14
|
export class TerminalFocusManager {
|
|
15
|
+
debug;
|
|
16
|
+
constructor(debug){
|
|
17
|
+
this.debug = debug;
|
|
18
|
+
}
|
|
14
19
|
/**
|
|
15
20
|
* Find the terminal location (emulator info) for a given process ID
|
|
16
21
|
*/ async findTerminal(pid) {
|
|
17
22
|
const ttyShort = getProcessTty(pid);
|
|
18
23
|
// If no TTY or invalid, we can't find the terminal
|
|
19
24
|
if (!ttyShort || ttyShort === '?') {
|
|
25
|
+
this.debug?.(`findTerminal(pid=${pid}): no usable TTY, cannot resolve terminal`);
|
|
20
26
|
return null;
|
|
21
27
|
}
|
|
22
28
|
const fullTty = `/dev/${ttyShort}`;
|
|
29
|
+
this.debug?.(`findTerminal(pid=${pid}): resolving terminal for ${fullTty}`);
|
|
23
30
|
// 1. Check tmux (most specific if running inside it)
|
|
24
31
|
const tmuxLocation = await this.findTmuxPane(fullTty);
|
|
25
|
-
if (tmuxLocation)
|
|
26
|
-
|
|
32
|
+
if (tmuxLocation) {
|
|
33
|
+
this.debug?.(`findTerminal: matched tmux (identifier=${tmuxLocation.identifier})`);
|
|
34
|
+
return tmuxLocation;
|
|
35
|
+
}
|
|
36
|
+
this.debug?.('findTerminal: tmux no match');
|
|
37
|
+
// 2. Check WezTerm (cross-platform, via its CLI — no AppleScript)
|
|
38
|
+
const weztermLocation = await this.findWeztermPane(fullTty);
|
|
39
|
+
if (weztermLocation) {
|
|
40
|
+
this.debug?.(`findTerminal: matched wezterm (pane_id=${weztermLocation.identifier})`);
|
|
41
|
+
return weztermLocation;
|
|
42
|
+
}
|
|
43
|
+
this.debug?.('findTerminal: wezterm no match');
|
|
44
|
+
// 3. Check iTerm2
|
|
27
45
|
const itermLocation = await this.findITerm2Session(fullTty);
|
|
28
|
-
if (itermLocation)
|
|
29
|
-
|
|
46
|
+
if (itermLocation) {
|
|
47
|
+
this.debug?.(`findTerminal: matched iTerm2 (tty=${itermLocation.tty})`);
|
|
48
|
+
return itermLocation;
|
|
49
|
+
}
|
|
50
|
+
this.debug?.('findTerminal: iTerm2 no match');
|
|
51
|
+
// 4. Check Terminal.app
|
|
30
52
|
const terminalAppLocation = await this.findTerminalAppWindow(fullTty);
|
|
31
|
-
if (terminalAppLocation)
|
|
32
|
-
|
|
53
|
+
if (terminalAppLocation) {
|
|
54
|
+
this.debug?.(`findTerminal: matched Terminal.app (tty=${terminalAppLocation.tty})`);
|
|
55
|
+
return terminalAppLocation;
|
|
56
|
+
}
|
|
57
|
+
this.debug?.('findTerminal: Terminal.app no match');
|
|
58
|
+
// 5. Fallback: we know the TTY but not the emulator wrapper
|
|
59
|
+
this.debug?.('findTerminal: no emulator matched; returning UNKNOWN');
|
|
33
60
|
return {
|
|
34
61
|
type: "unknown",
|
|
35
62
|
identifier: '',
|
|
@@ -39,17 +66,64 @@ export class TerminalFocusManager {
|
|
|
39
66
|
/**
|
|
40
67
|
* Focus the terminal identified by the location
|
|
41
68
|
*/ async focusTerminal(location) {
|
|
69
|
+
this.debug?.(`focusTerminal: focusing ${location.type} (identifier=${location.identifier}, tty=${location.tty})`);
|
|
70
|
+
let success = false;
|
|
42
71
|
try {
|
|
43
72
|
switch(location.type){
|
|
44
73
|
case "tmux":
|
|
45
|
-
|
|
74
|
+
success = await this.focusTmuxPane(location.identifier);
|
|
75
|
+
break;
|
|
76
|
+
case "wezterm":
|
|
77
|
+
success = await this.focusWeztermPane(location.identifier);
|
|
78
|
+
break;
|
|
46
79
|
case "iterm2":
|
|
47
|
-
|
|
80
|
+
success = await this.focusITerm2Session(location.tty);
|
|
81
|
+
break;
|
|
48
82
|
case "terminal-app":
|
|
49
|
-
|
|
83
|
+
success = await this.focusTerminalAppWindow(location.tty);
|
|
84
|
+
break;
|
|
50
85
|
default:
|
|
51
|
-
|
|
86
|
+
success = false;
|
|
87
|
+
}
|
|
88
|
+
} catch {
|
|
89
|
+
success = false;
|
|
90
|
+
}
|
|
91
|
+
this.debug?.(`focusTerminal: ${success ? 'succeeded' : 'failed'} for ${location.type}`);
|
|
92
|
+
return success;
|
|
93
|
+
}
|
|
94
|
+
async findWeztermPane(tty) {
|
|
95
|
+
try {
|
|
96
|
+
const { stdout } = await execFileAsync('wezterm', [
|
|
97
|
+
'cli',
|
|
98
|
+
'list',
|
|
99
|
+
'--format',
|
|
100
|
+
'json'
|
|
101
|
+
]);
|
|
102
|
+
const panes = JSON.parse(stdout);
|
|
103
|
+
if (!Array.isArray(panes)) return null;
|
|
104
|
+
for (const pane of panes){
|
|
105
|
+
if (pane && typeof pane.tty_name === 'string' && pane.tty_name === tty && pane.pane_id != null) {
|
|
106
|
+
return {
|
|
107
|
+
type: "wezterm",
|
|
108
|
+
identifier: String(pane.pane_id),
|
|
109
|
+
tty
|
|
110
|
+
};
|
|
111
|
+
}
|
|
52
112
|
}
|
|
113
|
+
} catch {
|
|
114
|
+
// wezterm not installed, not running, or returned invalid JSON
|
|
115
|
+
}
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
async focusWeztermPane(paneId) {
|
|
119
|
+
try {
|
|
120
|
+
await execFileAsync('wezterm', [
|
|
121
|
+
'cli',
|
|
122
|
+
'activate-pane',
|
|
123
|
+
'--pane-id',
|
|
124
|
+
paneId
|
|
125
|
+
]);
|
|
126
|
+
return true;
|
|
53
127
|
} catch {
|
|
54
128
|
return false;
|
|
55
129
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/terminal/TerminalFocusManager.ts"],"sourcesContent":["import { execFile } from 'child_process';\nimport { promisify } from 'util';\nimport { getProcessTty } from '../utils/process.js';\nimport { escapeAppleScript } from '../utils/applescript.js';\n\nconst execFileAsync = promisify(execFile);\n\nexport enum TerminalType {\n TMUX = 'tmux',\n ITERM2 = 'iterm2',\n TERMINAL_APP = 'terminal-app',\n UNKNOWN = 'unknown',\n}\n\nexport interface TerminalLocation {\n type: TerminalType;\n identifier: string; // e.g., \"session:window.pane\" for tmux, or TTY for others\n tty: string; // e.g., \"/dev/ttys030\"\n}\n\nexport class TerminalFocusManager {\n /**\n * Find the terminal location (emulator info) for a given process ID\n */\n async findTerminal(pid: number): Promise<TerminalLocation | null> {\n const ttyShort = getProcessTty(pid);\n\n // If no TTY or invalid, we can't find the terminal\n if (!ttyShort || ttyShort === '?') {\n return null;\n }\n\n const fullTty = `/dev/${ttyShort}`;\n\n // 1. Check tmux (most specific if running inside it)\n const tmuxLocation = await this.findTmuxPane(fullTty);\n if (tmuxLocation) return tmuxLocation;\n\n // 2. Check iTerm2\n const itermLocation = await this.findITerm2Session(fullTty);\n if (itermLocation) return itermLocation;\n\n // 3. Check Terminal.app\n const terminalAppLocation = await this.findTerminalAppWindow(fullTty);\n if (terminalAppLocation) return terminalAppLocation;\n\n // 4. Fallback: we know the TTY but not the emulator wrapper\n return {\n type: TerminalType.UNKNOWN,\n identifier: '',\n tty: fullTty\n };\n }\n\n /**\n * Focus the terminal identified by the location\n */\n async focusTerminal(location: TerminalLocation): Promise<boolean> {\n try {\n switch (location.type) {\n case TerminalType.TMUX:\n return await this.focusTmuxPane(location.identifier);\n case TerminalType.ITERM2:\n return await this.focusITerm2Session(location.tty);\n case TerminalType.TERMINAL_APP:\n return await this.focusTerminalAppWindow(location.tty);\n default:\n return false;\n }\n } catch {\n return false;\n }\n }\n\n private async findTmuxPane(tty: string): Promise<TerminalLocation | null> {\n try {\n const { stdout } = await execFileAsync('tmux', [\n 'list-panes', '-a', '-F', '#{pane_tty}|#{session_name}:#{window_index}.#{pane_index}'\n ]);\n\n const lines = stdout.trim().split('\\n');\n for (const line of lines) {\n if (!line.trim()) continue;\n const [paneTty, identifier] = line.split('|');\n if (paneTty === tty && identifier) {\n return {\n type: TerminalType.TMUX,\n identifier,\n tty\n };\n }\n }\n } catch {\n // tmux might not be installed or running\n }\n return null;\n }\n\n private async findITerm2Session(tty: string): Promise<TerminalLocation | null> {\n try {\n // Check if iTerm2 is running first to avoid launching it.\n if (!await this.isProcessRunning('iTerm2')) return null;\n } catch {\n return null;\n }\n\n try {\n const escapedTty = escapeAppleScript(tty);\n const script = `\n tell application \"iTerm\"\n repeat with w in windows\n repeat with t in tabs of w\n repeat with s in sessions of t\n if tty of s is \"${escapedTty}\" then\n return \"found\"\n end if\n end repeat\n end repeat\n end repeat\n end tell\n `;\n\n const { stdout } = await execFileAsync('osascript', ['-e', script]);\n if (stdout.trim() === \"found\") {\n return {\n type: TerminalType.ITERM2,\n identifier: tty,\n tty\n };\n }\n } catch {\n // iTerm2 script failed\n }\n return null;\n }\n\n private async findTerminalAppWindow(tty: string): Promise<TerminalLocation | null> {\n try {\n // Check if Terminal.app is running\n if (!await this.isProcessRunning('Terminal')) return null;\n } catch {\n return null;\n }\n\n try {\n const escapedTty = escapeAppleScript(tty);\n const script = `\n tell application \"Terminal\"\n repeat with w in windows\n repeat with t in tabs of w\n if tty of t is \"${escapedTty}\" then\n return \"found\"\n end if\n end repeat\n end repeat\n end tell\n `;\n\n const { stdout } = await execFileAsync('osascript', ['-e', script]);\n if (stdout.trim() === \"found\") {\n return {\n type: TerminalType.TERMINAL_APP,\n identifier: tty,\n tty\n };\n }\n } catch {\n // Terminal.app script failed\n }\n return null;\n }\n\n private async isProcessRunning(name: string): Promise<boolean> {\n const { stdout } = await execFileAsync('ps', ['-Axo', 'comm']);\n return stdout\n .split('\\n')\n .map((line) => line.trim())\n .some((command) => command === name || command.endsWith(`/${name}`));\n }\n\n private async focusTmuxPane(identifier: string): Promise<boolean> {\n try {\n await execFileAsync('tmux', ['switch-client', '-t', identifier]);\n return true;\n } catch {\n return false;\n }\n }\n\n private async focusITerm2Session(tty: string): Promise<boolean> {\n const escapedTty = escapeAppleScript(tty);\n const script = `\n tell application \"iTerm\"\n activate\n repeat with w in windows\n repeat with t in tabs of w\n repeat with s in sessions of t\n if tty of s is \"${escapedTty}\" then\n select s\n return \"true\"\n end if\n end repeat\n end repeat\n end repeat\n end tell\n `;\n const { stdout } = await execFileAsync('osascript', ['-e', script]);\n return stdout.trim() === \"true\";\n }\n\n private async focusTerminalAppWindow(tty: string): Promise<boolean> {\n const escapedTty = escapeAppleScript(tty);\n const script = `\n tell application \"Terminal\"\n activate\n repeat with w in windows\n repeat with t in tabs of w\n if tty of t is \"${escapedTty}\" then\n set index of w to 1\n set selected tab of w to t\n return \"true\"\n end if\n end repeat\n end repeat\n end tell\n `;\n const { stdout } = await execFileAsync('osascript', ['-e', script]);\n return stdout.trim() === \"true\";\n }\n}\n"],"names":["execFile","promisify","getProcessTty","escapeAppleScript","execFileAsync","TerminalType","TerminalFocusManager","findTerminal","pid","ttyShort","fullTty","tmuxLocation","findTmuxPane","itermLocation","findITerm2Session","terminalAppLocation","findTerminalAppWindow","type","identifier","tty","focusTerminal","location","focusTmuxPane","focusITerm2Session","focusTerminalAppWindow","stdout","lines","trim","split","line","paneTty","isProcessRunning","escapedTty","script","name","map","some","command","endsWith"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,gBAAgB;AACzC,SAASC,SAAS,QAAQ,OAAO;AACjC,SAASC,aAAa,QAAQ,sBAAsB;AACpD,SAASC,iBAAiB,QAAQ,0BAA0B;AAE5D,MAAMC,gBAAgBH,UAAUD;AAEhC,OAAO,IAAA,AAAKK,sCAAAA;;;;;WAAAA;MAKX;AAQD,OAAO,MAAMC;IACT;;KAEC,GACD,MAAMC,aAAaC,GAAW,EAAoC;QAC9D,MAAMC,WAAWP,cAAcM;QAE/B,mDAAmD;QACnD,IAAI,CAACC,YAAYA,aAAa,KAAK;YAC/B,OAAO;QACX;QAEA,MAAMC,UAAU,CAAC,KAAK,EA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AAC,CAAC,EAAEJ,MAAM;IAC1E;IAEA,MAAcZ,cAAcJ,UAAkB,EAAoB;QAC9D,IAAI;YACA,MAAMd,cAAc,QAAQ;gBAAC;gBAAiB;gBAAMc;aAAW;YAC/D,OAAO;QACX,EAAE,OAAM;YACJ,OAAO;QACX;IACJ;IAEA,MAAcK,mBAAmBJ,GAAW,EAAoB;QAC5D,MAAMa,aAAa7B,kBAAkBgB;QACrC,MAAMc,SAAS,CAAC;;;;;;+BAMO,EAAED,WAAW;;;;;;;;KAQvC,CAAC;QACE,MAAM,EAAEP,MAAM,EAAE,GAAG,MAAMrB,cAAc,aAAa;YAAC;YAAM6B;SAAO;QAClE,OAAOR,OAAOE,IAAI,OAAO;IAC7B;IAEA,MAAcH,uBAAuBL,GAAW,EAAoB;QAChE,MAAMa,aAAa7B,kBAAkBgB;QACrC,MAAMc,SAAS,CAAC;;;;;6BAKK,EAAED,WAAW;;;;;;;;IAQtC,CAAC;QACG,MAAM,EAAEP,MAAM,EAAE,GAAG,MAAMrB,cAAc,aAAa;YAAC;YAAM6B;SAAO;QAClE,OAAOR,OAAOE,IAAI,OAAO;IAC7B;AACJ"}
|
|
1
|
+
{"version":3,"sources":["../../src/terminal/TerminalFocusManager.ts"],"sourcesContent":["import { execFile } from 'child_process';\nimport { promisify } from 'util';\nimport { getProcessTty } from '../utils/process.js';\nimport { escapeAppleScript } from '../utils/applescript.js';\n\nconst execFileAsync = promisify(execFile);\n\nexport enum TerminalType {\n TMUX = 'tmux',\n WEZTERM = 'wezterm',\n ITERM2 = 'iterm2',\n TERMINAL_APP = 'terminal-app',\n UNKNOWN = 'unknown',\n}\n\nexport interface TerminalLocation {\n type: TerminalType;\n identifier: string; // e.g., \"session:window.pane\" for tmux, WezTerm pane id, or TTY for others\n tty: string; // e.g., \"/dev/ttys030\"\n}\n\n/**\n * Subset of a `wezterm cli list --format json` entry. Only `pane_id` and\n * `tty_name` are read; extra fields are ignored so schema additions across\n * WezTerm versions don't break parsing. (The TTY is exposed as `tty_name` in\n * the JSON, not `tty`.)\n */\ninterface WeztermPaneEntry {\n pane_id?: number;\n tty_name?: string | null;\n}\n\n/**\n * Optional trace sink. When provided to {@link TerminalFocusManager}, each\n * discovery/focus step reports a human-readable line so callers (e.g. the\n * `agent open --debug` command) can inspect the matching/focus decision path.\n */\nexport type TerminalDebugLogger = (message: string) => void;\n\nexport class TerminalFocusManager {\n constructor(private readonly debug?: TerminalDebugLogger) {}\n\n /**\n * Find the terminal location (emulator info) for a given process ID\n */\n async findTerminal(pid: number): Promise<TerminalLocation | null> {\n const ttyShort = getProcessTty(pid);\n\n // If no TTY or invalid, we can't find the terminal\n if (!ttyShort || ttyShort === '?') {\n this.debug?.(`findTerminal(pid=${pid}): no usable TTY, cannot resolve terminal`);\n return null;\n }\n\n const fullTty = `/dev/${ttyShort}`;\n this.debug?.(`findTerminal(pid=${pid}): resolving terminal for ${fullTty}`);\n\n // 1. Check tmux (most specific if running inside it)\n const tmuxLocation = await this.findTmuxPane(fullTty);\n if (tmuxLocation) {\n this.debug?.(`findTerminal: matched tmux (identifier=${tmuxLocation.identifier})`);\n return tmuxLocation;\n }\n this.debug?.('findTerminal: tmux no match');\n\n // 2. Check WezTerm (cross-platform, via its CLI — no AppleScript)\n const weztermLocation = await this.findWeztermPane(fullTty);\n if (weztermLocation) {\n this.debug?.(`findTerminal: matched wezterm (pane_id=${weztermLocation.identifier})`);\n return weztermLocation;\n }\n this.debug?.('findTerminal: wezterm no match');\n\n // 3. Check iTerm2\n const itermLocation = await this.findITerm2Session(fullTty);\n if (itermLocation) {\n this.debug?.(`findTerminal: matched iTerm2 (tty=${itermLocation.tty})`);\n return itermLocation;\n }\n this.debug?.('findTerminal: iTerm2 no match');\n\n // 4. Check Terminal.app\n const terminalAppLocation = await this.findTerminalAppWindow(fullTty);\n if (terminalAppLocation) {\n this.debug?.(`findTerminal: matched Terminal.app (tty=${terminalAppLocation.tty})`);\n return terminalAppLocation;\n }\n this.debug?.('findTerminal: Terminal.app no match');\n\n // 5. Fallback: we know the TTY but not the emulator wrapper\n this.debug?.('findTerminal: no emulator matched; returning UNKNOWN');\n return {\n type: TerminalType.UNKNOWN,\n identifier: '',\n tty: fullTty\n };\n }\n\n /**\n * Focus the terminal identified by the location\n */\n async focusTerminal(location: TerminalLocation): Promise<boolean> {\n this.debug?.(`focusTerminal: focusing ${location.type} (identifier=${location.identifier}, tty=${location.tty})`);\n let success = false;\n try {\n switch (location.type) {\n case TerminalType.TMUX:\n success = await this.focusTmuxPane(location.identifier);\n break;\n case TerminalType.WEZTERM:\n success = await this.focusWeztermPane(location.identifier);\n break;\n case TerminalType.ITERM2:\n success = await this.focusITerm2Session(location.tty);\n break;\n case TerminalType.TERMINAL_APP:\n success = await this.focusTerminalAppWindow(location.tty);\n break;\n default:\n success = false;\n }\n } catch {\n success = false;\n }\n this.debug?.(`focusTerminal: ${success ? 'succeeded' : 'failed'} for ${location.type}`);\n return success;\n }\n\n private async findWeztermPane(tty: string): Promise<TerminalLocation | null> {\n try {\n const { stdout } = await execFileAsync('wezterm', [\n 'cli', 'list', '--format', 'json',\n ]);\n\n const panes = JSON.parse(stdout) as WeztermPaneEntry[];\n if (!Array.isArray(panes)) return null;\n\n for (const pane of panes) {\n if (\n pane &&\n typeof pane.tty_name === 'string' &&\n pane.tty_name === tty &&\n pane.pane_id != null\n ) {\n return {\n type: TerminalType.WEZTERM,\n identifier: String(pane.pane_id),\n tty,\n };\n }\n }\n } catch {\n // wezterm not installed, not running, or returned invalid JSON\n }\n return null;\n }\n\n private async focusWeztermPane(paneId: string): Promise<boolean> {\n try {\n await execFileAsync('wezterm', ['cli', 'activate-pane', '--pane-id', paneId]);\n return true;\n } catch {\n return false;\n }\n }\n\n private async findTmuxPane(tty: string): Promise<TerminalLocation | null> {\n try {\n const { stdout } = await execFileAsync('tmux', [\n 'list-panes', '-a', '-F', '#{pane_tty}|#{session_name}:#{window_index}.#{pane_index}'\n ]);\n\n const lines = stdout.trim().split('\\n');\n for (const line of lines) {\n if (!line.trim()) continue;\n const [paneTty, identifier] = line.split('|');\n if (paneTty === tty && identifier) {\n return {\n type: TerminalType.TMUX,\n identifier,\n tty\n };\n }\n }\n } catch {\n // tmux might not be installed or running\n }\n return null;\n }\n\n private async findITerm2Session(tty: string): Promise<TerminalLocation | null> {\n try {\n // Check if iTerm2 is running first to avoid launching it.\n if (!await this.isProcessRunning('iTerm2')) return null;\n } catch {\n return null;\n }\n\n try {\n const escapedTty = escapeAppleScript(tty);\n const script = `\n tell application \"iTerm\"\n repeat with w in windows\n repeat with t in tabs of w\n repeat with s in sessions of t\n if tty of s is \"${escapedTty}\" then\n return \"found\"\n end if\n end repeat\n end repeat\n end repeat\n end tell\n `;\n\n const { stdout } = await execFileAsync('osascript', ['-e', script]);\n if (stdout.trim() === \"found\") {\n return {\n type: TerminalType.ITERM2,\n identifier: tty,\n tty\n };\n }\n } catch {\n // iTerm2 script failed\n }\n return null;\n }\n\n private async findTerminalAppWindow(tty: string): Promise<TerminalLocation | null> {\n try {\n // Check if Terminal.app is running\n if (!await this.isProcessRunning('Terminal')) return null;\n } catch {\n return null;\n }\n\n try {\n const escapedTty = escapeAppleScript(tty);\n const script = `\n tell application \"Terminal\"\n repeat with w in windows\n repeat with t in tabs of w\n if tty of t is \"${escapedTty}\" then\n return \"found\"\n end if\n end repeat\n end repeat\n end tell\n `;\n\n const { stdout } = await execFileAsync('osascript', ['-e', script]);\n if (stdout.trim() === \"found\") {\n return {\n type: TerminalType.TERMINAL_APP,\n identifier: tty,\n tty\n };\n }\n } catch {\n // Terminal.app script failed\n }\n return null;\n }\n\n private async isProcessRunning(name: string): Promise<boolean> {\n const { stdout } = await execFileAsync('ps', ['-Axo', 'comm']);\n return stdout\n .split('\\n')\n .map((line) => line.trim())\n .some((command) => command === name || command.endsWith(`/${name}`));\n }\n\n private async focusTmuxPane(identifier: string): Promise<boolean> {\n try {\n await execFileAsync('tmux', ['switch-client', '-t', identifier]);\n return true;\n } catch {\n return false;\n }\n }\n\n private async focusITerm2Session(tty: string): Promise<boolean> {\n const escapedTty = escapeAppleScript(tty);\n const script = `\n tell application \"iTerm\"\n activate\n repeat with w in windows\n repeat with t in tabs of w\n repeat with s in sessions of t\n if tty of s is \"${escapedTty}\" then\n select s\n return \"true\"\n end if\n end repeat\n end repeat\n end repeat\n end tell\n `;\n const { stdout } = await execFileAsync('osascript', ['-e', script]);\n return stdout.trim() === \"true\";\n }\n\n private async focusTerminalAppWindow(tty: string): Promise<boolean> {\n const escapedTty = escapeAppleScript(tty);\n const script = `\n tell application \"Terminal\"\n activate\n repeat with w in windows\n repeat with t in tabs of w\n if tty of t is \"${escapedTty}\" then\n set index of w to 1\n set selected tab of w to t\n return \"true\"\n end if\n end repeat\n end repeat\n end tell\n `;\n const { stdout } = await execFileAsync('osascript', ['-e', script]);\n return stdout.trim() === \"true\";\n }\n}\n"],"names":["execFile","promisify","getProcessTty","escapeAppleScript","execFileAsync","TerminalType","TerminalFocusManager","debug","findTerminal","pid","ttyShort","fullTty","tmuxLocation","findTmuxPane","identifier","weztermLocation","findWeztermPane","itermLocation","findITerm2Session","tty","terminalAppLocation","findTerminalAppWindow","type","focusTerminal","location","success","focusTmuxPane","focusWeztermPane","focusITerm2Session","focusTerminalAppWindow","stdout","panes","JSON","parse","Array","isArray","pane","tty_name","pane_id","String","paneId","lines","trim","split","line","paneTty","isProcessRunning","escapedTty","script","name","map","some","command","endsWith"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,gBAAgB;AACzC,SAASC,SAAS,QAAQ,OAAO;AACjC,SAASC,aAAa,QAAQ,sBAAsB;AACpD,SAASC,iBAAiB,QAAQ,0BAA0B;AAE5D,MAAMC,gBAAgBH,UAAUD;AAEhC,OAAO,IAAA,AAAKK,sCAAAA;;;;;;WAAAA;MAMX;AA0BD,OAAO,MAAMC;;IACT,YAAY,AAAiBC,KAA2B,CAAE;aAA7BA,QAAAA;IAA8B;IAE3D;;KAEC,GACD,MAAMC,aAAaC,GAAW,EAAoC;QAC9D,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,GAAW,EAAoB;QAChE,MAAM4B,aAAa5C,kBAAkBgB;QACrC,MAAM6B,SAAS,CAAC;;;;;6BAKK,EAAED,WAAW;;;;;;;;IAQtC,CAAC;QACG,MAAM,EAAEjB,MAAM,EAAE,GAAG,MAAM1B,cAAc,aAAa;YAAC;YAAM4C;SAAO;QAClE,OAAOlB,OAAOY,IAAI,OAAO;IAC7B;AACJ"}
|
|
@@ -16,7 +16,27 @@ export declare class TtyWriter {
|
|
|
16
16
|
* @throws Error if terminal type is unsupported or send fails
|
|
17
17
|
*/
|
|
18
18
|
static send(location: TerminalLocation, message: string): Promise<void>;
|
|
19
|
+
/**
|
|
20
|
+
* Send a single raw key (e.g. "1", "Enter", "Up") to the terminal as a
|
|
21
|
+
* keystroke — bypassing bracketed paste and without auto-appending Enter.
|
|
22
|
+
*
|
|
23
|
+
* Use this when the target TUI distinguishes between typed text and raw
|
|
24
|
+
* keypresses (e.g. an `AskUserQuestion` picker that selects on digit-key
|
|
25
|
+
* press, not on a pasted digit followed by Enter).
|
|
26
|
+
*
|
|
27
|
+
* - tmux: `tmux send-keys -t <id> <key>` — direct keystroke, no paste buffer.
|
|
28
|
+
* - WezTerm: `wezterm cli send-text --pane-id <id> --no-paste <key>`.
|
|
29
|
+
* - iTerm2 / Terminal.app: AppleScript via System Events. Requires
|
|
30
|
+
* Accessibility permissions.
|
|
31
|
+
*/
|
|
32
|
+
static sendKey(location: TerminalLocation, key: string): Promise<void>;
|
|
33
|
+
private static sendKeyViaTmux;
|
|
34
|
+
private static sendKeyViaWezterm;
|
|
35
|
+
private static sendKeyViaITerm2;
|
|
36
|
+
private static sendKeyViaTerminalApp;
|
|
37
|
+
private static sendViaWezterm;
|
|
19
38
|
private static sendViaTmux;
|
|
39
|
+
private static execFileWithInput;
|
|
20
40
|
/**
|
|
21
41
|
* Build an AppleScript that finds an iTerm2 session by TTY and runs a
|
|
22
42
|
* command against it. The `sessionCommand` is inserted inside a
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TtyWriter.d.ts","sourceRoot":"","sources":["../../src/terminal/TtyWriter.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;
|
|
1
|
+
{"version":3,"file":"TtyWriter.d.ts","sourceRoot":"","sources":["../../src/terminal/TtyWriter.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAmBlE,qBAAa,SAAS;IAClB;;;;;;;;;;;;;;OAcG;WACU,IAAI,CAAC,QAAQ,EAAE,gBAAgB,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAkB7E;;;;;;;;;;;;OAYG;WACU,OAAO,CAAC,QAAQ,EAAE,gBAAgB,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;mBAkBvD,cAAc;mBAOd,iBAAiB;mBASjB,gBAAgB;mBAkChB,qBAAqB;mBA+BrB,cAAc;mBAuBd,WAAW;mBAWX,iBAAiB;IAiBtC;;;;OAIG;IACH,OAAO,CAAC,MAAM,CAAC,mBAAmB;mBAsBb,aAAa;mBAuBb,kBAAkB;CA0D1C"}
|
|
@@ -3,6 +3,15 @@ import { promisify } from 'util';
|
|
|
3
3
|
import { TerminalType } from './TerminalFocusManager.js';
|
|
4
4
|
import { escapeAppleScript } from '../utils/applescript.js';
|
|
5
5
|
const execFileAsync = promisify(execFile);
|
|
6
|
+
/**
|
|
7
|
+
* Carriage return byte (0x0d). Sent as a fixed discrete argv element with
|
|
8
|
+
* `--no-paste` to deliver Enter literally (shell equivalent: $'\x0d').
|
|
9
|
+
*/ const CARRIAGE_RETURN = '\x0d';
|
|
10
|
+
/**
|
|
11
|
+
* Escape byte (0x1b). Recognized by `sendKey` and translated to the
|
|
12
|
+
* backend-native representation (`Escape` for tmux, `key code 53` for
|
|
13
|
+
* AppleScript, the literal byte for WezTerm).
|
|
14
|
+
*/ const ESCAPE_BYTE = '\x1b';
|
|
6
15
|
export class TtyWriter {
|
|
7
16
|
/**
|
|
8
17
|
* Send a message as keyboard input to a terminal session.
|
|
@@ -22,26 +31,182 @@ export class TtyWriter {
|
|
|
22
31
|
switch(location.type){
|
|
23
32
|
case TerminalType.TMUX:
|
|
24
33
|
return TtyWriter.sendViaTmux(location.identifier, message);
|
|
34
|
+
case TerminalType.WEZTERM:
|
|
35
|
+
return TtyWriter.sendViaWezterm(location.identifier, message);
|
|
25
36
|
case TerminalType.ITERM2:
|
|
26
37
|
return TtyWriter.sendViaITerm2(location.tty, message);
|
|
27
38
|
case TerminalType.TERMINAL_APP:
|
|
28
39
|
return TtyWriter.sendViaTerminalApp(location.tty, message);
|
|
29
40
|
default:
|
|
30
|
-
throw new Error(`Cannot send input: unsupported terminal type "${location.type}". ` + 'Supported: tmux, iTerm2, Terminal.app.');
|
|
41
|
+
throw new Error(`Cannot send input: unsupported terminal type "${location.type}". ` + 'Supported: tmux, WezTerm, iTerm2, Terminal.app.');
|
|
31
42
|
}
|
|
32
43
|
}
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
44
|
+
/**
|
|
45
|
+
* Send a single raw key (e.g. "1", "Enter", "Up") to the terminal as a
|
|
46
|
+
* keystroke — bypassing bracketed paste and without auto-appending Enter.
|
|
47
|
+
*
|
|
48
|
+
* Use this when the target TUI distinguishes between typed text and raw
|
|
49
|
+
* keypresses (e.g. an `AskUserQuestion` picker that selects on digit-key
|
|
50
|
+
* press, not on a pasted digit followed by Enter).
|
|
51
|
+
*
|
|
52
|
+
* - tmux: `tmux send-keys -t <id> <key>` — direct keystroke, no paste buffer.
|
|
53
|
+
* - WezTerm: `wezterm cli send-text --pane-id <id> --no-paste <key>`.
|
|
54
|
+
* - iTerm2 / Terminal.app: AppleScript via System Events. Requires
|
|
55
|
+
* Accessibility permissions.
|
|
56
|
+
*/ static async sendKey(location, key) {
|
|
57
|
+
switch(location.type){
|
|
58
|
+
case TerminalType.TMUX:
|
|
59
|
+
return TtyWriter.sendKeyViaTmux(location.identifier, key);
|
|
60
|
+
case TerminalType.WEZTERM:
|
|
61
|
+
return TtyWriter.sendKeyViaWezterm(location.identifier, key);
|
|
62
|
+
case TerminalType.ITERM2:
|
|
63
|
+
return TtyWriter.sendKeyViaITerm2(location.tty, key);
|
|
64
|
+
case TerminalType.TERMINAL_APP:
|
|
65
|
+
return TtyWriter.sendKeyViaTerminalApp(location.tty, key);
|
|
66
|
+
default:
|
|
67
|
+
throw new Error(`Cannot send key: unsupported terminal type "${location.type}". ` + 'Supported: tmux, WezTerm, iTerm2, Terminal.app.');
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
static async sendKeyViaTmux(identifier, key) {
|
|
71
|
+
// tmux send-keys interprets named keys (Enter, Up, Escape, ...) and
|
|
72
|
+
// passes literals through. No bracketed paste, no auto-Enter.
|
|
73
|
+
const arg = key === ESCAPE_BYTE ? 'Escape' : key;
|
|
39
74
|
await execFileAsync('tmux', [
|
|
40
75
|
'send-keys',
|
|
41
76
|
'-t',
|
|
42
77
|
identifier,
|
|
43
|
-
|
|
44
|
-
|
|
78
|
+
arg
|
|
79
|
+
]);
|
|
80
|
+
}
|
|
81
|
+
static async sendKeyViaWezterm(paneId, key) {
|
|
82
|
+
// --no-paste delivers the key bytes literally outside bracketed-paste
|
|
83
|
+
// markers; the TUI sees a raw keystroke. For Esc (`\x1b`), wezterm
|
|
84
|
+
// accepts the byte directly.
|
|
85
|
+
await execFileAsync('wezterm', [
|
|
86
|
+
'cli',
|
|
87
|
+
'send-text',
|
|
88
|
+
'--pane-id',
|
|
89
|
+
paneId,
|
|
90
|
+
'--no-paste',
|
|
91
|
+
key
|
|
92
|
+
]);
|
|
93
|
+
}
|
|
94
|
+
static async sendKeyViaITerm2(tty, key) {
|
|
95
|
+
// Focus the target session, then press the key via System Events so the
|
|
96
|
+
// inner TUI sees a raw keystroke (not a bracketed-paste text run).
|
|
97
|
+
const action = appleScriptKeyAction(key);
|
|
98
|
+
const script = `
|
|
99
|
+
tell application "iTerm"
|
|
100
|
+
set targetSession to missing value
|
|
101
|
+
repeat with w in windows
|
|
102
|
+
repeat with t in tabs of w
|
|
103
|
+
repeat with s in sessions of t
|
|
104
|
+
if tty of s is "${tty}" then
|
|
105
|
+
set targetSession to s
|
|
106
|
+
set frontmost of w to true
|
|
107
|
+
tell t to select
|
|
108
|
+
tell s to select
|
|
109
|
+
exit repeat
|
|
110
|
+
end if
|
|
111
|
+
end repeat
|
|
112
|
+
if targetSession is not missing value then exit repeat
|
|
113
|
+
end repeat
|
|
114
|
+
if targetSession is not missing value then exit repeat
|
|
115
|
+
end repeat
|
|
116
|
+
if targetSession is missing value then return "not_found"
|
|
117
|
+
activate
|
|
118
|
+
end tell
|
|
119
|
+
tell application "System Events" to ${action}
|
|
120
|
+
return "ok"`;
|
|
121
|
+
const { stdout } = await execFileAsync('osascript', [
|
|
122
|
+
'-e',
|
|
123
|
+
script
|
|
124
|
+
]);
|
|
125
|
+
if (stdout.trim() !== 'ok') {
|
|
126
|
+
throw new Error(`iTerm2 session not found for TTY ${tty}`);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
static async sendKeyViaTerminalApp(tty, key) {
|
|
130
|
+
const action = appleScriptKeyAction(key);
|
|
131
|
+
const script = `
|
|
132
|
+
tell application "Terminal"
|
|
133
|
+
set targetTab to missing value
|
|
134
|
+
set targetWindow to missing value
|
|
135
|
+
repeat with w in windows
|
|
136
|
+
repeat with i from 1 to count of tabs of w
|
|
137
|
+
set t to tab i of w
|
|
138
|
+
if tty of t is "${tty}" then
|
|
139
|
+
set targetTab to t
|
|
140
|
+
set targetWindow to w
|
|
141
|
+
exit repeat
|
|
142
|
+
end if
|
|
143
|
+
end repeat
|
|
144
|
+
if targetTab is not missing value then exit repeat
|
|
145
|
+
end repeat
|
|
146
|
+
if targetTab is missing value then return "not_found"
|
|
147
|
+
set selected of targetTab to true
|
|
148
|
+
set frontmost of targetWindow to true
|
|
149
|
+
activate
|
|
150
|
+
end tell
|
|
151
|
+
tell application "System Events" to ${action}
|
|
152
|
+
return "ok"`;
|
|
153
|
+
const { stdout } = await execFileAsync('osascript', [
|
|
154
|
+
'-e',
|
|
155
|
+
script
|
|
156
|
+
]);
|
|
157
|
+
if (stdout.trim() !== 'ok') {
|
|
158
|
+
throw new Error(`Terminal.app tab not found for TTY ${tty}`);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
static async sendViaWezterm(paneId, message) {
|
|
162
|
+
// Two explicit CLI calls, mirroring the text-then-Enter convention used
|
|
163
|
+
// by tmux / iTerm2 / Terminal.app so a bracketed-paste-aware TUI still
|
|
164
|
+
// sees Enter as a submit.
|
|
165
|
+
//
|
|
166
|
+
// Step 1 (text): write the message to stdin so prompt contents are not
|
|
167
|
+
// exposed through process arguments. execFile still spawns wezterm
|
|
168
|
+
// directly (no shell), so shell metacharacters remain inert.
|
|
169
|
+
// Step 2 (Enter): pass a fixed carriage return (0x0d) as a discrete
|
|
170
|
+
// argv element (the JS char '\x0d') with --no-paste, so the CR is
|
|
171
|
+
// delivered literally rather than wrapped in paste brackets. The
|
|
172
|
+
// equivalent shell command is:
|
|
173
|
+
// wezterm cli send-text --pane-id <id> --no-paste $'\x0d'
|
|
174
|
+
// (ANSI-C quoting, note the leading $).
|
|
175
|
+
await TtyWriter.execFileWithInput('wezterm', [
|
|
176
|
+
'cli',
|
|
177
|
+
'send-text',
|
|
178
|
+
'--pane-id',
|
|
179
|
+
paneId
|
|
180
|
+
], message);
|
|
181
|
+
await new Promise((resolve)=>setTimeout(resolve, 150));
|
|
182
|
+
await execFileAsync('wezterm', [
|
|
183
|
+
'cli',
|
|
184
|
+
'send-text',
|
|
185
|
+
'--pane-id',
|
|
186
|
+
paneId,
|
|
187
|
+
'--no-paste',
|
|
188
|
+
CARRIAGE_RETURN
|
|
189
|
+
]);
|
|
190
|
+
}
|
|
191
|
+
static async sendViaTmux(identifier, message) {
|
|
192
|
+
// Paste the message body using tmux bracketed paste, then send Enter as
|
|
193
|
+
// a separate key so the inner TUI treats it as submission rather than
|
|
194
|
+
// pasted content.
|
|
195
|
+
const bufferName = `ai-devkit-send-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
196
|
+
await TtyWriter.execFileWithInput('tmux', [
|
|
197
|
+
'load-buffer',
|
|
198
|
+
'-b',
|
|
199
|
+
bufferName,
|
|
200
|
+
'-'
|
|
201
|
+
], message);
|
|
202
|
+
await execFileAsync('tmux', [
|
|
203
|
+
'paste-buffer',
|
|
204
|
+
'-t',
|
|
205
|
+
identifier,
|
|
206
|
+
'-b',
|
|
207
|
+
bufferName,
|
|
208
|
+
'-p',
|
|
209
|
+
'-d'
|
|
45
210
|
]);
|
|
46
211
|
await new Promise((resolve)=>setTimeout(resolve, 150));
|
|
47
212
|
await execFileAsync('tmux', [
|
|
@@ -51,6 +216,22 @@ export class TtyWriter {
|
|
|
51
216
|
'Enter'
|
|
52
217
|
]);
|
|
53
218
|
}
|
|
219
|
+
static async execFileWithInput(command, args, input) {
|
|
220
|
+
await new Promise((resolve, reject)=>{
|
|
221
|
+
const child = execFile(command, args, (error)=>{
|
|
222
|
+
if (error) {
|
|
223
|
+
reject(error);
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
resolve();
|
|
227
|
+
});
|
|
228
|
+
if (!child.stdin) {
|
|
229
|
+
reject(new Error(`Cannot write stdin to ${command}`));
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
child.stdin.end(input);
|
|
233
|
+
});
|
|
234
|
+
}
|
|
54
235
|
/**
|
|
55
236
|
* Build an AppleScript that finds an iTerm2 session by TTY and runs a
|
|
56
237
|
* command against it. The `sessionCommand` is inserted inside a
|
|
@@ -162,5 +343,13 @@ return "ok"`;
|
|
|
162
343
|
}
|
|
163
344
|
}
|
|
164
345
|
}
|
|
346
|
+
/**
|
|
347
|
+
* AppleScript `keystroke` only delivers typeable characters; non-typeable
|
|
348
|
+
* keys (Esc, arrows, F-keys, …) must be sent via `key code <N>`. Add more
|
|
349
|
+
* mappings here as new special keys are needed.
|
|
350
|
+
*/ function appleScriptKeyAction(key) {
|
|
351
|
+
if (key === ESCAPE_BYTE) return 'key code 53';
|
|
352
|
+
return `keystroke "${escapeAppleScript(key)}"`;
|
|
353
|
+
}
|
|
165
354
|
|
|
166
355
|
//# sourceMappingURL=TtyWriter.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/terminal/TtyWriter.ts"],"sourcesContent":["import { execFile } from 'child_process';\nimport { promisify } from 'util';\nimport type { TerminalLocation } from './TerminalFocusManager.js';\nimport { TerminalType } from './TerminalFocusManager.js';\nimport { escapeAppleScript } from '../utils/applescript.js';\n\nconst execFileAsync = promisify(execFile);\n\nexport class TtyWriter {\n /**\n * Send a message as keyboard input to a terminal session.\n *\n * Dispatches to the correct mechanism based on terminal type:\n * - tmux: `tmux send-keys`\n * - iTerm2: Two separate AppleScript `write text` calls (text then newline)\n * - Terminal.app: Two separate AppleScript `do script` calls (text then newline)\n *\n * All AppleScript is executed via `execFile('osascript', ['-e', script])`\n * to avoid shell interpolation and command injection.\n *\n * @param location Terminal location from TerminalFocusManager.findTerminal()\n * @param message Text to send\n * @throws Error if terminal type is unsupported or send fails\n */\n static async send(location: TerminalLocation, message: string): Promise<void> {\n switch (location.type) {\n case TerminalType.TMUX:\n return TtyWriter.sendViaTmux(location.identifier, message);\n case TerminalType.ITERM2:\n return TtyWriter.sendViaITerm2(location.tty, message);\n case TerminalType.TERMINAL_APP:\n return TtyWriter.sendViaTerminalApp(location.tty, message);\n default:\n throw new Error(\n `Cannot send input: unsupported terminal type \"${location.type}\". ` +\n 'Supported: tmux, iTerm2, Terminal.app.'\n );\n }\n }\n\n private static async sendViaTmux(identifier: string, message: string): Promise<void> {\n // Send text and Enter as two separate calls so that Enter arrives\n // outside of bracketed paste mode. When the inner application (e.g.\n // Claude Code) has bracketed paste enabled, tmux wraps the send-keys\n // payload in paste brackets — if Enter is included, it gets swallowed\n // as part of the paste instead of acting as a submit action.\n await execFileAsync('tmux', ['send-keys', '-t', identifier, '-l', message]);\n await new Promise((resolve) => setTimeout(resolve, 150));\n await execFileAsync('tmux', ['send-keys', '-t', identifier, 'Enter']);\n }\n\n /**\n * Build an AppleScript that finds an iTerm2 session by TTY and runs a\n * command against it. The `sessionCommand` is inserted inside a\n * `tell targetSession` block.\n */\n private static iterm2SessionScript(tty: string, sessionCommand: string): string {\n return `\ntell application \"iTerm\"\n set targetSession to missing value\n repeat with w in windows\n repeat with t in tabs of w\n repeat with s in sessions of t\n if tty of s is \"${tty}\" then\n set targetSession to s\n exit repeat\n end if\n end repeat\n if targetSession is not missing value then exit repeat\n end repeat\n if targetSession is not missing value then exit repeat\n end repeat\n if targetSession is missing value then return \"not_found\"\n tell targetSession to ${sessionCommand}\nend tell\nreturn \"ok\"`;\n }\n\n private static async sendViaITerm2(tty: string, message: string): Promise<void> {\n const escaped = escapeAppleScript(message);\n // Send text and Enter as two separate write text calls so the newline\n // is delivered outside the bracketed paste sequence of the message body.\n // iTerm2 appends the newline after the paste-end marker (\\e[201~), so\n // the inner TUI (Claude Code, Codex) sees it as a real submit action.\n const textScript = TtyWriter.iterm2SessionScript(tty, `write text \"${escaped}\" newline no`);\n\n const { stdout: textResult } = await execFileAsync('osascript', ['-e', textScript]);\n if (textResult.trim() !== 'ok') {\n throw new Error(`iTerm2 session not found for TTY ${tty}`);\n }\n\n // Wait for the paste to complete before sending Enter separately\n await new Promise((resolve) => setTimeout(resolve, 150));\n\n const enterScript = TtyWriter.iterm2SessionScript(tty, 'write text \"\" newline yes');\n const { stdout: enterResult } = await execFileAsync('osascript', ['-e', enterScript]);\n if (enterResult.trim() !== 'ok') {\n throw new Error(`iTerm2 session disappeared before Enter could be sent for TTY ${tty}`);\n }\n }\n\n private static async sendViaTerminalApp(tty: string, message: string): Promise<void> {\n const escaped = escapeAppleScript(message);\n // Use Terminal.app's `do script` to send text to the correct tab by TTY.\n // We avoid System Events `keystroke` + `key code 36` because it requires\n // accessibility permissions and unreliably delivers the Return key.\n //\n // `do script` with `in` targets a specific tab without opening a new one.\n // We send text and Enter as two separate calls so the newline arrives\n // outside of bracketed paste mode — same pattern as iTerm2 and tmux.\n const textScript = `\ntell application \"Terminal\"\n set targetTab to missing value\n repeat with w in windows\n repeat with i from 1 to count of tabs of w\n set t to tab i of w\n if tty of t is \"${tty}\" then\n set targetTab to t\n exit repeat\n end if\n end repeat\n if targetTab is not missing value then exit repeat\n end repeat\n if targetTab is missing value then return \"not_found\"\n do script \"${escaped}\" in targetTab\nend tell\nreturn \"ok\"`;\n\n const { stdout: textResult } = await execFileAsync('osascript', ['-e', textScript]);\n if (textResult.trim() !== 'ok') {\n throw new Error(`Terminal.app tab not found for TTY ${tty}`);\n }\n\n // Wait for the text to be delivered before sending Enter\n await new Promise((resolve) => setTimeout(resolve, 150));\n\n const enterScript = `\ntell application \"Terminal\"\n set targetTab to missing value\n repeat with w in windows\n repeat with i from 1 to count of tabs of w\n set t to tab i of w\n if tty of t is \"${tty}\" then\n set targetTab to t\n exit repeat\n end if\n end repeat\n if targetTab is not missing value then exit repeat\n end repeat\n if targetTab is missing value then return \"not_found\"\n do script \"\" in targetTab\nend tell\nreturn \"ok\"`;\n\n const { stdout: enterResult } = await execFileAsync('osascript', ['-e', enterScript]);\n if (enterResult.trim() !== 'ok') {\n throw new Error(`Terminal.app tab disappeared before Enter could be sent for TTY ${tty}`);\n }\n }\n}\n"],"names":["execFile","promisify","TerminalType","escapeAppleScript","execFileAsync","TtyWriter","send","location","message","type","TMUX","sendViaTmux","identifier","ITERM2","sendViaITerm2","tty","TERMINAL_APP","sendViaTerminalApp","Error","Promise","resolve","setTimeout","iterm2SessionScript","sessionCommand","escaped","textScript","stdout","textResult","trim","enterScript","enterResult"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,gBAAgB;AACzC,SAASC,SAAS,QAAQ,OAAO;AAE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F,IAAIC,YAAYF,IAAI,OAAO,MAAM;YAC7B,MAAM,IAAIV,MAAM,CAAC,gEAAgE,EAAEH,KAAK;QAC5F;IACJ;AACJ"}
|
|
1
|
+
{"version":3,"sources":["../../src/terminal/TtyWriter.ts"],"sourcesContent":["import { execFile } from 'child_process';\nimport { promisify } from 'util';\nimport type { TerminalLocation } from './TerminalFocusManager.js';\nimport { TerminalType } from './TerminalFocusManager.js';\nimport { escapeAppleScript } from '../utils/applescript.js';\n\nconst execFileAsync = promisify(execFile);\n\n/**\n * Carriage return byte (0x0d). Sent as a fixed discrete argv element with\n * `--no-paste` to deliver Enter literally (shell equivalent: $'\\x0d').\n */\nconst CARRIAGE_RETURN = '\\x0d';\n\n/**\n * Escape byte (0x1b). Recognized by `sendKey` and translated to the\n * backend-native representation (`Escape` for tmux, `key code 53` for\n * AppleScript, the literal byte for WezTerm).\n */\nconst ESCAPE_BYTE = '\\x1b';\n\nexport class TtyWriter {\n /**\n * Send a message as keyboard input to a terminal session.\n *\n * Dispatches to the correct mechanism based on terminal type:\n * - tmux: `tmux send-keys`\n * - iTerm2: Two separate AppleScript `write text` calls (text then newline)\n * - Terminal.app: Two separate AppleScript `do script` calls (text then newline)\n *\n * All AppleScript is executed via `execFile('osascript', ['-e', script])`\n * to avoid shell interpolation and command injection.\n *\n * @param location Terminal location from TerminalFocusManager.findTerminal()\n * @param message Text to send\n * @throws Error if terminal type is unsupported or send fails\n */\n static async send(location: TerminalLocation, message: string): Promise<void> {\n switch (location.type) {\n case TerminalType.TMUX:\n return TtyWriter.sendViaTmux(location.identifier, message);\n case TerminalType.WEZTERM:\n return TtyWriter.sendViaWezterm(location.identifier, message);\n case TerminalType.ITERM2:\n return TtyWriter.sendViaITerm2(location.tty, message);\n case TerminalType.TERMINAL_APP:\n return TtyWriter.sendViaTerminalApp(location.tty, message);\n default:\n throw new Error(\n `Cannot send input: unsupported terminal type \"${location.type}\". ` +\n 'Supported: tmux, WezTerm, iTerm2, Terminal.app.'\n );\n }\n }\n\n /**\n * Send a single raw key (e.g. \"1\", \"Enter\", \"Up\") to the terminal as a\n * keystroke — bypassing bracketed paste and without auto-appending Enter.\n *\n * Use this when the target TUI distinguishes between typed text and raw\n * keypresses (e.g. an `AskUserQuestion` picker that selects on digit-key\n * press, not on a pasted digit followed by Enter).\n *\n * - tmux: `tmux send-keys -t <id> <key>` — direct keystroke, no paste buffer.\n * - WezTerm: `wezterm cli send-text --pane-id <id> --no-paste <key>`.\n * - iTerm2 / Terminal.app: AppleScript via System Events. Requires\n * Accessibility permissions.\n */\n static async sendKey(location: TerminalLocation, key: string): Promise<void> {\n switch (location.type) {\n case TerminalType.TMUX:\n return TtyWriter.sendKeyViaTmux(location.identifier, key);\n case TerminalType.WEZTERM:\n return TtyWriter.sendKeyViaWezterm(location.identifier, key);\n case TerminalType.ITERM2:\n return TtyWriter.sendKeyViaITerm2(location.tty, key);\n case TerminalType.TERMINAL_APP:\n return TtyWriter.sendKeyViaTerminalApp(location.tty, key);\n default:\n throw new Error(\n `Cannot send key: unsupported terminal type \"${location.type}\". ` +\n 'Supported: tmux, WezTerm, iTerm2, Terminal.app.'\n );\n }\n }\n\n private static async sendKeyViaTmux(identifier: string, key: string): Promise<void> {\n // tmux send-keys interprets named keys (Enter, Up, Escape, ...) and\n // passes literals through. No bracketed paste, no auto-Enter.\n const arg = key === ESCAPE_BYTE ? 'Escape' : key;\n await execFileAsync('tmux', ['send-keys', '-t', identifier, arg]);\n }\n\n private static async sendKeyViaWezterm(paneId: string, key: string): Promise<void> {\n // --no-paste delivers the key bytes literally outside bracketed-paste\n // markers; the TUI sees a raw keystroke. For Esc (`\\x1b`), wezterm\n // accepts the byte directly.\n await execFileAsync('wezterm', [\n 'cli', 'send-text', '--pane-id', paneId, '--no-paste', key,\n ]);\n }\n\n private static async sendKeyViaITerm2(tty: string, key: string): Promise<void> {\n // Focus the target session, then press the key via System Events so the\n // inner TUI sees a raw keystroke (not a bracketed-paste text run).\n const action = appleScriptKeyAction(key);\n const script = `\ntell application \"iTerm\"\n set targetSession to missing value\n repeat with w in windows\n repeat with t in tabs of w\n repeat with s in sessions of t\n if tty of s is \"${tty}\" then\n set targetSession to s\n set frontmost of w to true\n tell t to select\n tell s to select\n exit repeat\n end if\n end repeat\n if targetSession is not missing value then exit repeat\n end repeat\n if targetSession is not missing value then exit repeat\n end repeat\n if targetSession is missing value then return \"not_found\"\n activate\nend tell\ntell application \"System Events\" to ${action}\nreturn \"ok\"`;\n\n const { stdout } = await execFileAsync('osascript', ['-e', script]);\n if (stdout.trim() !== 'ok') {\n throw new Error(`iTerm2 session not found for TTY ${tty}`);\n }\n }\n\n private static async sendKeyViaTerminalApp(tty: string, key: string): Promise<void> {\n const action = appleScriptKeyAction(key);\n const script = `\ntell application \"Terminal\"\n set targetTab to missing value\n set targetWindow to missing value\n repeat with w in windows\n repeat with i from 1 to count of tabs of w\n set t to tab i of w\n if tty of t is \"${tty}\" then\n set targetTab to t\n set targetWindow to w\n exit repeat\n end if\n end repeat\n if targetTab is not missing value then exit repeat\n end repeat\n if targetTab is missing value then return \"not_found\"\n set selected of targetTab to true\n set frontmost of targetWindow to true\n activate\nend tell\ntell application \"System Events\" to ${action}\nreturn \"ok\"`;\n\n const { stdout } = await execFileAsync('osascript', ['-e', script]);\n if (stdout.trim() !== 'ok') {\n throw new Error(`Terminal.app tab not found for TTY ${tty}`);\n }\n }\n\n private static async sendViaWezterm(paneId: string, message: string): Promise<void> {\n // Two explicit CLI calls, mirroring the text-then-Enter convention used\n // by tmux / iTerm2 / Terminal.app so a bracketed-paste-aware TUI still\n // sees Enter as a submit.\n //\n // Step 1 (text): write the message to stdin so prompt contents are not\n // exposed through process arguments. execFile still spawns wezterm\n // directly (no shell), so shell metacharacters remain inert.\n // Step 2 (Enter): pass a fixed carriage return (0x0d) as a discrete\n // argv element (the JS char '\\x0d') with --no-paste, so the CR is\n // delivered literally rather than wrapped in paste brackets. The\n // equivalent shell command is:\n // wezterm cli send-text --pane-id <id> --no-paste $'\\x0d'\n // (ANSI-C quoting, note the leading $).\n await TtyWriter.execFileWithInput('wezterm', [\n 'cli', 'send-text', '--pane-id', paneId,\n ], message);\n await new Promise((resolve) => setTimeout(resolve, 150));\n await execFileAsync('wezterm', [\n 'cli', 'send-text', '--pane-id', paneId, '--no-paste', CARRIAGE_RETURN,\n ]);\n }\n\n private static async sendViaTmux(identifier: string, message: string): Promise<void> {\n // Paste the message body using tmux bracketed paste, then send Enter as\n // a separate key so the inner TUI treats it as submission rather than\n // pasted content.\n const bufferName = `ai-devkit-send-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n await TtyWriter.execFileWithInput('tmux', ['load-buffer', '-b', bufferName, '-'], message);\n await execFileAsync('tmux', ['paste-buffer', '-t', identifier, '-b', bufferName, '-p', '-d']);\n await new Promise((resolve) => setTimeout(resolve, 150));\n await execFileAsync('tmux', ['send-keys', '-t', identifier, 'Enter']);\n }\n\n private static async execFileWithInput(command: string, args: string[], input: string): Promise<void> {\n await new Promise<void>((resolve, reject) => {\n const child = execFile(command, args, (error) => {\n if (error) {\n reject(error);\n return;\n }\n resolve();\n });\n if (!child.stdin) {\n reject(new Error(`Cannot write stdin to ${command}`));\n return;\n }\n child.stdin.end(input);\n });\n }\n\n /**\n * Build an AppleScript that finds an iTerm2 session by TTY and runs a\n * command against it. The `sessionCommand` is inserted inside a\n * `tell targetSession` block.\n */\n private static iterm2SessionScript(tty: string, sessionCommand: string): string {\n return `\ntell application \"iTerm\"\n set targetSession to missing value\n repeat with w in windows\n repeat with t in tabs of w\n repeat with s in sessions of t\n if tty of s is \"${tty}\" then\n set targetSession to s\n exit repeat\n end if\n end repeat\n if targetSession is not missing value then exit repeat\n end repeat\n if targetSession is not missing value then exit repeat\n end repeat\n if targetSession is missing value then return \"not_found\"\n tell targetSession to ${sessionCommand}\nend tell\nreturn \"ok\"`;\n }\n\n private static async sendViaITerm2(tty: string, message: string): Promise<void> {\n const escaped = escapeAppleScript(message);\n // Send text and Enter as two separate write text calls so the newline\n // is delivered outside the bracketed paste sequence of the message body.\n // iTerm2 appends the newline after the paste-end marker (\\e[201~), so\n // the inner TUI (Claude Code, Codex) sees it as a real submit action.\n const textScript = TtyWriter.iterm2SessionScript(tty, `write text \"${escaped}\" newline no`);\n\n const { stdout: textResult } = await execFileAsync('osascript', ['-e', textScript]);\n if (textResult.trim() !== 'ok') {\n throw new Error(`iTerm2 session not found for TTY ${tty}`);\n }\n\n // Wait for the paste to complete before sending Enter separately\n await new Promise((resolve) => setTimeout(resolve, 150));\n\n const enterScript = TtyWriter.iterm2SessionScript(tty, 'write text \"\" newline yes');\n const { stdout: enterResult } = await execFileAsync('osascript', ['-e', enterScript]);\n if (enterResult.trim() !== 'ok') {\n throw new Error(`iTerm2 session disappeared before Enter could be sent for TTY ${tty}`);\n }\n }\n\n private static async sendViaTerminalApp(tty: string, message: string): Promise<void> {\n const escaped = escapeAppleScript(message);\n // Use Terminal.app's `do script` to send text to the correct tab by TTY.\n // We avoid System Events `keystroke` + `key code 36` because it requires\n // accessibility permissions and unreliably delivers the Return key.\n //\n // `do script` with `in` targets a specific tab without opening a new one.\n // We send text and Enter as two separate calls so the newline arrives\n // outside of bracketed paste mode — same pattern as iTerm2 and tmux.\n const textScript = `\ntell application \"Terminal\"\n set targetTab to missing value\n repeat with w in windows\n repeat with i from 1 to count of tabs of w\n set t to tab i of w\n if tty of t is \"${tty}\" then\n set targetTab to t\n exit repeat\n end if\n end repeat\n if targetTab is not missing value then exit repeat\n end repeat\n if targetTab is missing value then return \"not_found\"\n do script \"${escaped}\" in targetTab\nend tell\nreturn \"ok\"`;\n\n const { stdout: textResult } = await execFileAsync('osascript', ['-e', textScript]);\n if (textResult.trim() !== 'ok') {\n throw new Error(`Terminal.app tab not found for TTY ${tty}`);\n }\n\n // Wait for the text to be delivered before sending Enter\n await new Promise((resolve) => setTimeout(resolve, 150));\n\n const enterScript = `\ntell application \"Terminal\"\n set targetTab to missing value\n repeat with w in windows\n repeat with i from 1 to count of tabs of w\n set t to tab i of w\n if tty of t is \"${tty}\" then\n set targetTab to t\n exit repeat\n end if\n end repeat\n if targetTab is not missing value then exit repeat\n end repeat\n if targetTab is missing value then return \"not_found\"\n do script \"\" in targetTab\nend tell\nreturn \"ok\"`;\n\n const { stdout: enterResult } = await execFileAsync('osascript', ['-e', enterScript]);\n if (enterResult.trim() !== 'ok') {\n throw new Error(`Terminal.app tab disappeared before Enter could be sent for TTY ${tty}`);\n }\n }\n}\n\n/**\n * AppleScript `keystroke` only delivers typeable characters; non-typeable\n * keys (Esc, arrows, F-keys, …) must be sent via `key code <N>`. Add more\n * mappings here as new special keys are needed.\n */\nfunction appleScriptKeyAction(key: string): string {\n if (key === ESCAPE_BYTE) return 'key code 53';\n return `keystroke \"${escapeAppleScript(key)}\"`;\n}\n"],"names":["execFile","promisify","TerminalType","escapeAppleScript","execFileAsync","CARRIAGE_RETURN","ESCAPE_BYTE","TtyWriter","send","location","message","type","TMUX","sendViaTmux","identifier","WEZTERM","sendViaWezterm","ITERM2","sendViaITerm2","tty","TERMINAL_APP","sendViaTerminalApp","Error","sendKey","key","sendKeyViaTmux","sendKeyViaWezterm","sendKeyViaITerm2","sendKeyViaTerminalApp","arg","paneId","action","appleScriptKeyAction","script","stdout","trim","execFileWithInput","Promise","resolve","setTimeout","bufferName","process","pid","Date","now","Math","random","toString","slice","command","args","input","reject","child","error","stdin","end","iterm2SessionScript","sessionCommand","escaped","textScript","textResult","enterScript","enterResult"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,gBAAgB;AACzC,SAASC,SAAS,QAAQ,OAAO;AAEjC,SAASC,YAAY,QAAQ,4BAA4B;AACzD,SAASC,iBAAiB,QAAQ,0BAA0B;AAE5D,MAAMC,gBAAgBH,UAAUD;AAEhC;;;CAGC,GACD,MAAMK,kBAAkB;AAExB;;;;CAIC,GACD,MAAMC,cAAc;AAEpB,OAAO,MAAMC;IACT;;;;;;;;;;;;;;KAcC,GACD,aAAaC,KAAKC,QAA0B,EAAEC,OA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QAEnD,MAAMwB,cAAc,CAAC;;;;;;sBAMP,EAAE3C,IAAI;;;;;;;;;;WAUjB,CAAC;QAEJ,MAAM,EAAEe,QAAQ6B,WAAW,EAAE,GAAG,MAAM3D,cAAc,aAAa;YAAC;YAAM0D;SAAY;QACpF,IAAIC,YAAY5B,IAAI,OAAO,MAAM;YAC7B,MAAM,IAAIb,MAAM,CAAC,gEAAgE,EAAEH,KAAK;QAC5F;IACJ;AACJ;AAEA;;;;CAIC,GACD,SAASa,qBAAqBR,GAAW;IACrC,IAAIA,QAAQlB,aAAa,OAAO;IAChC,OAAO,CAAC,WAAW,EAAEH,kBAAkBqB,KAAK,CAAC,CAAC;AAClD"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export interface AgentRequest {
|
|
2
|
+
sessionId: string;
|
|
3
|
+
toolName: string;
|
|
4
|
+
toolInput: Record<string, unknown>;
|
|
5
|
+
timestamp: string;
|
|
6
|
+
}
|
|
7
|
+
export declare function getAgentRequestPath(homeDir: string, sessionId: string): string;
|
|
8
|
+
export declare function readLatestAgentRequest(homeDir: string, sessionId: string): AgentRequest | null;
|
|
9
|
+
export declare function writeAgentRequest(homeDir: string, entry: AgentRequest): void;
|
|
10
|
+
//# sourceMappingURL=agent-requests.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agent-requests.d.ts","sourceRoot":"","sources":["../../src/utils/agent-requests.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,YAAY;IACzB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACnC,SAAS,EAAE,MAAM,CAAC;CACrB;AAED,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAE9E;AAED,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,YAAY,GAAG,IAAI,CAO9F;AAED,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,YAAY,GAAG,IAAI,CAI5E"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
export function getAgentRequestPath(homeDir, sessionId) {
|
|
4
|
+
return path.join(homeDir, '.ai-devkit', 'agent-requests', `${sessionId}.json`);
|
|
5
|
+
}
|
|
6
|
+
export function readLatestAgentRequest(homeDir, sessionId) {
|
|
7
|
+
try {
|
|
8
|
+
const raw = fs.readFileSync(getAgentRequestPath(homeDir, sessionId), 'utf-8');
|
|
9
|
+
return JSON.parse(raw);
|
|
10
|
+
} catch {
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
export function writeAgentRequest(homeDir, entry) {
|
|
15
|
+
const filePath = getAgentRequestPath(homeDir, entry.sessionId);
|
|
16
|
+
fs.mkdirSync(path.dirname(filePath), {
|
|
17
|
+
recursive: true
|
|
18
|
+
});
|
|
19
|
+
fs.writeFileSync(filePath, JSON.stringify(entry, null, 2), 'utf-8');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
//# sourceMappingURL=agent-requests.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utils/agent-requests.ts"],"sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nexport interface AgentRequest {\n sessionId: string;\n toolName: string;\n toolInput: Record<string, unknown>;\n timestamp: string;\n}\n\nexport function getAgentRequestPath(homeDir: string, sessionId: string): string {\n return path.join(homeDir, '.ai-devkit', 'agent-requests', `${sessionId}.json`);\n}\n\nexport function readLatestAgentRequest(homeDir: string, sessionId: string): AgentRequest | null {\n try {\n const raw = fs.readFileSync(getAgentRequestPath(homeDir, sessionId), 'utf-8');\n return JSON.parse(raw) as AgentRequest;\n } catch {\n return null;\n }\n}\n\nexport function writeAgentRequest(homeDir: string, entry: AgentRequest): void {\n const filePath = getAgentRequestPath(homeDir, entry.sessionId);\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.writeFileSync(filePath, JSON.stringify(entry, null, 2), 'utf-8');\n}\n"],"names":["fs","path","getAgentRequestPath","homeDir","sessionId","join","readLatestAgentRequest","raw","readFileSync","JSON","parse","writeAgentRequest","entry","filePath","mkdirSync","dirname","recursive","writeFileSync","stringify"],"mappings":"AAAA,YAAYA,QAAQ,KAAK;AACzB,YAAYC,UAAU,OAAO;AAS7B,OAAO,SAASC,oBAAoBC,OAAe,EAAEC,SAAiB;IAClE,OAAOH,KAAKI,IAAI,CAACF,SAAS,cAAc,kBAAkB,GAAGC,UAAU,KAAK,CAAC;AACjF;AAEA,OAAO,SAASE,uBAAuBH,OAAe,EAAEC,SAAiB;IACrE,IAAI;QACA,MAAMG,MAAMP,GAAGQ,YAAY,CAACN,oBAAoBC,SAASC,YAAY;QACrE,OAAOK,KAAKC,KAAK,CAACH;IACtB,EAAE,OAAM;QACJ,OAAO;IACX;AACJ;AAEA,OAAO,SAASI,kBAAkBR,OAAe,EAAES,KAAmB;IAClE,MAAMC,WAAWX,oBAAoBC,SAASS,MAAMR,SAAS;IAC7DJ,GAAGc,SAAS,CAACb,KAAKc,OAAO,CAACF,WAAW;QAAEG,WAAW;IAAK;IACvDhB,GAAGiB,aAAa,CAACJ,UAAUJ,KAAKS,SAAS,CAACN,OAAO,MAAM,IAAI;AAC/D"}
|
package/package.json
CHANGED
|
@@ -86,9 +86,15 @@ function createMockAgent(overrides: Partial<AgentInfo> = {}): AgentInfo {
|
|
|
86
86
|
|
|
87
87
|
describe('AgentManager', () => {
|
|
88
88
|
let manager: AgentManager;
|
|
89
|
+
let tmpDir: string;
|
|
89
90
|
|
|
90
91
|
beforeEach(() => {
|
|
91
|
-
|
|
92
|
+
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-manager-'));
|
|
93
|
+
manager = new AgentManager(new AgentRegistry(path.join(tmpDir, 'agents.json')));
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
afterEach(() => {
|
|
97
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
92
98
|
});
|
|
93
99
|
|
|
94
100
|
describe('registerAdapter', () => {
|