Skip to content

Commit f75176e

Browse files
authored
Merge pull request #44 from ThinkOffApp/feat/send-to-session
feat(daemon): send-to-session endpoint — drive any agent from CodeWatch
2 parents e449864 + 21e3c34 commit f75176e

6 files changed

Lines changed: 517 additions & 0 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
## Unreleased
44

55
### Added
6+
- **Send-to-session**: the :8788 daemon gains `POST /sessions/send {agent, text, from?}` — deliver text as user input into any named agent's live session — plus `GET /sessions/agents` for the target picker. Four delivery adapters, configured per agent under `mcp.confirmations.sessions.agents`: `wake` (spawn a wake/injection script), `gui` (same, chained behind a human-idle guard with `--wait` so it never types over the user), `tmux` (literal `send-keys` + Enter), and `forward` (relay to the owning machine's daemon, provenance passed through so the `[from …]` prefix is applied exactly once). Deliveries are accepted-async (202) and every attempt is receipted. This is the backend half of the CodeWatch send box; it drives any agent uniformly, including headless sessions the provider apps cannot reach.
67
- **Responder-lock enforcement in the MCP room tools (#42)**: `room_post` and `alert_recipient` now refuse when another live session holds the machine's room-responder lock — a PASSIVE session that ignores its injected instructions still cannot post as the agent through IAK tooling. Lock semantics mirror the SessionStart hook exactly (pid + process-start-time identity, stale locks ignored, fail-open on mechanics); the owning session is recognized by finding the lock's pid in the caller's process-ancestor chain. Read-only room tools (`room_recent`) are unaffected. Raw HTTP posting against GroupMind is out of scope client-side and tracked in issue #42's server-side follow-up.
78

89
### Fixed

‎bin/iak-mcp-daemon.mjs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ startConfirmationsServer({
7373
receiptsPath: config?.receipts?.path,
7474
announce: serverAnnounce,
7575
wakeScript,
76+
sessions: cc.sessions,
7677
});
7778
console.log(`[iak-mcp-daemon] HTTP listener on http://${cc.host || '127.0.0.1'}:${cc.port || 8788} (POST /intent enabled: ${Object.keys(serverAnnouncerMap).join(',') || 'no announcers'})`);
7879

‎src/confirmations.mjs‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import { createServer } from 'node:http';
2121
import { randomUUID, createHmac, timingSafeEqual } from 'node:crypto';
2222
import { appendFileSync } from 'node:fs';
2323
import { spawn } from 'node:child_process';
24+
import { deliverToSession, listSessionAgents, HOP_HEADER } from './session-send.mjs';
2425

2526
// --- registry ---------------------------------------------------------------
2627

@@ -574,6 +575,7 @@ export function startConfirmationsServer({
574575
receiptsPath,
575576
announce, // optional: enables POST /intent to create new intents externally
576577
wakeScript, // optional: shell script path; enables POST /wake to nudge the local IDE
578+
sessions, // optional: {agents: {...}} enables POST /sessions/send + GET /sessions/agents
577579
} = {}) {
578580
const server = createServer((req, res) => {
579581
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
@@ -729,6 +731,71 @@ export function startConfirmationsServer({
729731
});
730732
return;
731733
}
734+
// POST /sessions/send — deliver text into a named agent's live session
735+
// (the CodeWatch send-box primitive). Body: {agent, text, from?}.
736+
// 202 = accepted for delivery (GUI adapters may wait on the human-idle
737+
// guard before typing). See src/session-send.mjs for adapters/config.
738+
if (req.method === 'POST' && url.pathname === '/sessions/send') {
739+
if (!sessions || !sessions.agents) {
740+
res.writeHead(503, { 'Content-Type': 'application/json' });
741+
res.end(JSON.stringify({ ok: false, error: 'sessions not configured' }));
742+
return;
743+
}
744+
let body = '';
745+
let overflow = false;
746+
req.on('data', (c) => {
747+
body += c;
748+
// 64 KiB is far beyond any legal payload (text caps at 4000 chars);
749+
// stop buffering hostile bodies instead of holding them in memory.
750+
if (body.length > 64 * 1024 && !overflow) {
751+
overflow = true;
752+
res.writeHead(413, { 'Content-Type': 'application/json' });
753+
res.end(JSON.stringify({ ok: false, error: 'body too large' }));
754+
req.destroy();
755+
}
756+
});
757+
req.on('end', async () => {
758+
if (overflow) return;
759+
let payload;
760+
try { payload = JSON.parse(body); } catch {
761+
res.writeHead(400, { 'Content-Type': 'application/json' });
762+
res.end(JSON.stringify({ ok: false, error: 'invalid json' }));
763+
return;
764+
}
765+
const hops = Math.max(0, Math.min(8, parseInt(req.headers[HOP_HEADER] || '0', 10) || 0));
766+
const result = await deliverToSession(sessions, payload.agent, {
767+
text: payload.text,
768+
from: payload.from,
769+
hops,
770+
onAsyncError: (e) => postReceipt(receiptsPath, {
771+
kind: 'sessions.send.async_error',
772+
agent: payload.agent,
773+
error: e.message || String(e),
774+
at: new Date().toISOString(),
775+
}),
776+
});
777+
postReceipt(receiptsPath, {
778+
kind: 'sessions.send',
779+
agent: payload.agent,
780+
from: payload.from || null,
781+
ok: result.ok,
782+
delivered_via: result.deliveredVia || null,
783+
error: result.error || null,
784+
at: new Date().toISOString(),
785+
});
786+
res.writeHead(result.status, { 'Content-Type': 'application/json' });
787+
res.end(JSON.stringify(result.ok
788+
? { ok: true, agent: payload.agent, deliveredVia: result.deliveredVia }
789+
: { ok: false, error: result.error }));
790+
});
791+
return;
792+
}
793+
// GET /sessions/agents — send-box target picker.
794+
if (req.method === 'GET' && url.pathname === '/sessions/agents') {
795+
res.writeHead(200, { 'Content-Type': 'application/json' });
796+
res.end(JSON.stringify({ agents: listSessionAgents(sessions) }));
797+
return;
798+
}
732799
// POST /ide-chat/<handle> body { role, text, ts, session_id, tool_calls? }
733800
// GET /ide-chat/<handle>?since=<iso> → { events: [...] }
734801
//

‎src/mcp-server.mjs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,7 @@ export async function runMcpServer({ configPath } = {}) {
386386
receiptsPath: config?.receipts?.path,
387387
announce,
388388
wakeScript,
389+
sessions: confirmCfg.sessions,
389390
});
390391
process.stderr.write(
391392
`[iak-mcp] confirmations: enabled on ${daemonBase} (in-process) — channels: ${Object.keys(announcerMap).join(', ')}\n`

‎src/session-send.mjs‎

Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
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

Comments
 (0)