|
| 1 | +// SPDX-License-Identifier: AGPL-3.0-only |
| 2 | +// |
| 3 | +// send-to-session: deliver a text message as user input into a named |
| 4 | +// agent's live session. This is the backend primitive behind CodeWatch's |
| 5 | +// send box — the uniform way to drive ANY agent (desktop-app, tmux, |
| 6 | +// or an agent owned by another machine's daemon) from the phone. |
| 7 | +// |
| 8 | +// Config block (ide-agent-kit.json / dogfood.json): |
| 9 | +// |
| 10 | +// "sessions": { |
| 11 | +// "agents": { |
| 12 | +// "claudemm": { "adapter": "wake", "script": "/path/gui-wake.sh" }, |
| 13 | +// "sally": { "adapter": "tmux", "tmux_session": "sally" }, |
| 14 | +// "claudemb": { "adapter": "forward", "peer": "http://192.168.50.x:8788", |
| 15 | +// "token_file": "~/.config/iak-gate.token" }, |
| 16 | +// // and on the OWNING machine's daemon: |
| 17 | +// // "claudemb": { "adapter": "gui", "script": "/path/gui-nudge.sh", |
| 18 | +// // "idle_guard": "/path/human-idle-guard.sh" } |
| 19 | +// } |
| 20 | +// } |
| 21 | +// |
| 22 | +// Adapters: |
| 23 | +// wake — spawn script with the text as its only argument (the /wake |
| 24 | +// pattern; the script owns focusing/typing/logging). |
| 25 | +// gui — like wake, but when idle_guard is set the guard runs first |
| 26 | +// with --wait so injection never types over a human at the |
| 27 | +// keyboard. |
| 28 | +// tmux — literal send-keys into the tmux session, then Enter. |
| 29 | +// forward — POST the same body to the owning machine's daemon. |
| 30 | +// |
| 31 | +// Delivery is accepted-async (202): spawn-based adapters detach, so a |
| 32 | +// guard that waits minutes for the human to go idle never blocks the |
| 33 | +// HTTP response. |
| 34 | + |
| 35 | +import { spawn } from 'node:child_process'; |
| 36 | +import { readFileSync } from 'node:fs'; |
| 37 | +import { homedir } from 'node:os'; |
| 38 | + |
| 39 | +const MAX_TEXT_LENGTH = 4000; |
| 40 | +const MAX_FROM_LENGTH = 200; |
| 41 | +const FORWARD_TIMEOUT_MS = 8000; |
| 42 | +// One forward, ever: app → reachable daemon → owning daemon. The owning |
| 43 | +// daemon must deliver locally; a second hop means a misconfigured peer |
| 44 | +// chain (worst case a peer pointing back at itself), so it is refused |
| 45 | +// instead of retried. |
| 46 | +const MAX_FORWARD_HOPS = 1; |
| 47 | +export const HOP_HEADER = 'x-iak-send-hops'; |
| 48 | + |
| 49 | +function expandHome(p) { |
| 50 | + if (typeof p !== 'string') return p; |
| 51 | + return p.startsWith('~/') ? `${homedir()}/${p.slice(2)}` : p; |
| 52 | +} |
| 53 | + |
| 54 | +export function listSessionAgents(sessions) { |
| 55 | + const agents = (sessions && sessions.agents) || {}; |
| 56 | + return Object.entries(agents).map(([name, cfg]) => ({ |
| 57 | + name, |
| 58 | + adapter: (cfg && cfg.adapter) || 'unconfigured', |
| 59 | + })); |
| 60 | +} |
| 61 | + |
| 62 | +/** |
| 63 | + * Deliver `text` into the session of `agentName`. |
| 64 | + * Returns {ok, status, deliveredVia?|error?} — status is the HTTP code the |
| 65 | + * caller should use. Never throws. |
| 66 | + */ |
| 67 | +export async function deliverToSession(sessions, agentName, { text, from, hops = 0, onAsyncError } = {}) { |
| 68 | + if (typeof agentName !== 'string' || !agentName.trim()) { |
| 69 | + return { ok: false, status: 400, error: 'missing agent' }; |
| 70 | + } |
| 71 | + if (typeof text !== 'string' || !text.trim()) { |
| 72 | + return { ok: false, status: 400, error: 'missing text' }; |
| 73 | + } |
| 74 | + if (text.length > MAX_TEXT_LENGTH) { |
| 75 | + return { ok: false, status: 400, error: `text too long (max ${MAX_TEXT_LENGTH})` }; |
| 76 | + } |
| 77 | + if (from !== undefined && (typeof from !== 'string' || from.length > MAX_FROM_LENGTH)) { |
| 78 | + return { ok: false, status: 400, error: `from must be a string of at most ${MAX_FROM_LENGTH} characters` }; |
| 79 | + } |
| 80 | + const cfg = sessions && sessions.agents && sessions.agents[agentName]; |
| 81 | + if (!cfg) { |
| 82 | + return { ok: false, status: 404, error: 'unknown agent' }; |
| 83 | + } |
| 84 | + |
| 85 | + const message = from ? `[from ${from}] ${text}` : text; |
| 86 | + // Delivery is accepted-async: a failure after the detached spawn cannot |
| 87 | + // change the already-sent 202, but it must not vanish either. |
| 88 | + const reportAsync = (e) => { try { onAsyncError?.(e); } catch { /* never throw */ } }; |
| 89 | + |
| 90 | + switch (cfg.adapter) { |
| 91 | + case 'wake': |
| 92 | + case 'gui': { |
| 93 | + const script = expandHome(cfg.script); |
| 94 | + if (!script) return { ok: false, status: 503, error: 'no adapter configured' }; |
| 95 | + try { |
| 96 | + let child; |
| 97 | + const guard = expandHome(cfg.idle_guard); |
| 98 | + if (guard) { |
| 99 | + // Chain through the human-idle guard so we never type over a |
| 100 | + // human. Everything passed as argv — no shell interpolation of |
| 101 | + // the message. |
| 102 | + child = spawn('bash', [ |
| 103 | + '-c', '"$1" --wait && exec "$2" "$3"', '--', guard, script, message, |
| 104 | + ], { detached: true, stdio: 'ignore' }); |
| 105 | + } else { |
| 106 | + child = spawn(script, [message], { detached: true, stdio: 'ignore' }); |
| 107 | + } |
| 108 | + child.on('error', reportAsync); |
| 109 | + child.on('close', (code) => { |
| 110 | + if (code !== 0 && code !== null) reportAsync(new Error(`${cfg.adapter} adapter exited ${code}`)); |
| 111 | + }); |
| 112 | + child.unref(); |
| 113 | + return { ok: true, status: 202, deliveredVia: cfg.adapter }; |
| 114 | + } catch (e) { |
| 115 | + return { ok: false, status: 500, error: e.message || String(e) }; |
| 116 | + } |
| 117 | + } |
| 118 | + case 'tmux': { |
| 119 | + const session = cfg.tmux_session; |
| 120 | + if (!session) return { ok: false, status: 503, error: 'no adapter configured' }; |
| 121 | + try { |
| 122 | + // -l sends the message literally (no key-name interpretation), |
| 123 | + // then a separate Enter submits it as user input. |
| 124 | + await runOnce('tmux', ['send-keys', '-t', session, '-l', message]); |
| 125 | + await runOnce('tmux', ['send-keys', '-t', session, 'C-m']); |
| 126 | + return { ok: true, status: 202, deliveredVia: 'tmux' }; |
| 127 | + } catch (e) { |
| 128 | + return { ok: false, status: 500, error: e.message || String(e) }; |
| 129 | + } |
| 130 | + } |
| 131 | + case 'forward': { |
| 132 | + if (!cfg.peer) return { ok: false, status: 503, error: 'no adapter configured' }; |
| 133 | + if (hops >= MAX_FORWARD_HOPS) { |
| 134 | + return { ok: false, status: 508, error: 'forward hop limit reached — peer chain is misconfigured (possible loop)' }; |
| 135 | + } |
| 136 | + let token = cfg.token || ''; |
| 137 | + if (!token && cfg.token_file) { |
| 138 | + try { token = readFileSync(expandHome(cfg.token_file), 'utf8').trim(); } catch { /* peer may be open */ } |
| 139 | + } |
| 140 | + try { |
| 141 | + const controller = new AbortController(); |
| 142 | + const timer = setTimeout(() => controller.abort(), FORWARD_TIMEOUT_MS); |
| 143 | + const resp = await fetch(`${cfg.peer.replace(/\/$/, '')}/sessions/send`, { |
| 144 | + method: 'POST', |
| 145 | + headers: { |
| 146 | + 'Content-Type': 'application/json', |
| 147 | + [HOP_HEADER]: String(hops + 1), |
| 148 | + ...(token ? { Authorization: `Bearer ${token}` } : {}), |
| 149 | + }, |
| 150 | + // The peer daemon owns the final adapter; pass provenance through |
| 151 | + // untouched rather than double-prefixing. |
| 152 | + body: JSON.stringify({ agent: agentName, text, from }), |
| 153 | + signal: controller.signal, |
| 154 | + }); |
| 155 | + clearTimeout(timer); |
| 156 | + const data = await resp.json().catch(() => null); |
| 157 | + // Peer confirmation must be explicit: exactly 202 + ok:true. A bare |
| 158 | + // 200/204 or an unparseable body is NOT a delivery. |
| 159 | + if (resp.status !== 202 || !data || data.ok !== true) { |
| 160 | + return { ok: false, status: 502, error: `peer: ${(data && data.error) || `unexpected response ${resp.status}`}` }; |
| 161 | + } |
| 162 | + return { ok: true, status: 202, deliveredVia: `forward:${data.deliveredVia || cfg.peer}` }; |
| 163 | + } catch (e) { |
| 164 | + return { ok: false, status: 502, error: `peer unreachable: ${e.message || String(e)}` }; |
| 165 | + } |
| 166 | + } |
| 167 | + default: |
| 168 | + return { ok: false, status: 503, error: 'no adapter configured' }; |
| 169 | + } |
| 170 | +} |
| 171 | + |
| 172 | +function runOnce(cmd, args) { |
| 173 | + return new Promise((resolvePromise, reject) => { |
| 174 | + const child = spawn(cmd, args, { stdio: 'ignore' }); |
| 175 | + child.on('error', reject); |
| 176 | + child.on('close', (code) => { |
| 177 | + if (code === 0) resolvePromise(); |
| 178 | + else reject(new Error(`${cmd} exited ${code}`)); |
| 179 | + }); |
| 180 | + }); |
| 181 | +} |
0 commit comments