diff --git a/README.md b/README.md index d20c101..d6bdc04 100644 --- a/README.md +++ b/README.md @@ -1073,6 +1073,10 @@ The same `automation.rules` schema doubles as a per-agent permission table when Each rule scopes which messages reach which action: `match` filters on sender, room, mention, keywords, regex; `action.type` constrains the side-effect (`post` / `exec` / `nudge`). A message that matches no rule is ignored. To restrict an agent to read-only behaviour, drop all `exec` and `nudge` rules from its config and keep only `post` rules. +`exec` commands are split on spaces and run without a shell (`execFileSync`, `shell: false`). Quotes, pipes and redirects in a rule no longer work, by design. A rule that needs those should call a script file. `${body}` is refused. `${room}` and `${sender}` must match a strict token and must not start with `-`; a failed value refuses the action instead of running with a missing argument. + +`nudge` types the rule text into tmux as one argument after `send-keys -l` (`execFileSync`, no shell). Session names use the same strict token as `${room}` and `${sender}`. The pause before Enter is a timer, not a shell `sleep`. Comment polling uses Node `fetch`; a GitHub token goes in the Authorization header, never on a command line. + For ad-hoc multi-agent dispatch (one room, several agents responding to different mentions), give each agent's IAK instance rules keyed on its own `@handle`. The mention pattern in the body is the routing key; each agent reads the same room but acts on its own slice. ### Comment Polling (`src/comment-poller.mjs`) @@ -1273,12 +1277,15 @@ This profile broadens `tmux.allow` to include common read/build/test commands (` ## Tests ```bash -npm test +npm install && npm test ``` -Runs the whole suite: the IAK tests in `test/` plus the embedded -user-intent-kit tests. Needs Node.js 20.11 or newer (the suite uses the -option-object form of `mock.timers.enable`). +Run from the tree you are testing (a git worktree needs its own +`npm install`; `user-intent-kit` is `file:packages/user-intent-kit`, and +without that link files that import `src/intent.mjs` fail to load). +The suite is the IAK tests in `test/` plus the embedded user-intent-kit +tests. Needs Node.js 20.11 or newer (the suite uses the option-object +form of `mock.timers.enable`). ## Example flow diff --git a/bin/cli.mjs b/bin/cli.mjs index 97d63c8..cf6570c 100755 --- a/bin/cli.mjs +++ b/bin/cli.mjs @@ -1164,7 +1164,7 @@ async function main() { const config = loadConfig(opts.config); if (subcommand === 'poll') { - const comments = pollComments(config); + const comments = await pollComments(config); if (comments.length === 0) { console.log('No new comments.'); } else { diff --git a/docs/remaining-execsync.md b/docs/remaining-execsync.md new file mode 100644 index 0000000..e286180 --- /dev/null +++ b/docs/remaining-execsync.md @@ -0,0 +1,94 @@ +# Remaining execSync (second change) + +Branch `fix/aikido-exec-no-shell` through 5dedac2 already covers what room text can reach: automation exec, the tmux nudge helper, and poller HTTP (Node fetch, token in a header). This file is the handover list; do not treat a later docs commit as a code change. + +Do not convert the sites below on this branch. Each line is an `execSync` still present after 5dedac2, with the interpolated values and where they come from. + +## src/common/check.mjs + +- L46 `execSync(cmd)` — `cmd` is one of the fixed strings `node --version`, `tmux -V`, `claude-mem --version`. +- L68 `execSync(cmd)` — same fixed `claude-mem --version` for the optional memory backend check. + +## bin/cli.mjs + +- L1552 `execSync('claude-mem --version')` — fixed string, init-time capability probe. + +## src/utils.mjs + +- L12 `nudgeCommand`: `execSync(command)` — whole `command` string from `poller.nudge_command` (config). `text` and `session` go in env as `IAK_NUDGE_TEXT` / `IAK_TMUX_SESSION`, not into the command string. + +## src/room-poller.mjs + +- L180 heartbeat: `execSync(\`tmux send-keys -t ${JSON.stringify(session)} Escape\`)` — `session` from `sessionOpt` or `config.tmux.ide_session` / `default_session`. Only when `nudge_mode === 'tmux'`. (The team-relay copy of this poller no longer has this call.) + +## src/session-keepalive.mjs + +- L99 `execSync(\`rm -f ${pidFile}\`)` — `pidFile` from `options.pidFile` or `config.keepalive.pidFile` or a module default. +- L112 `execSync("ps -eo pid,args | grep 'caffeinate' | grep -v grep")` — fixed string. +- L139 `execSync('pmset -g custom 2>/dev/null')` — fixed string. + +## src/mcp-server.mjs + +- L72 `listTmuxSessions`: `execSync(\`tmux list-sessions -F '...'\`)` — format string is fixed. +- L364 `captureTmuxPane`: `execSync(\`tmux capture-pane -p -t ${JSON.stringify(session)} -S -${safeLines}\`)` — `session` from MCP tool args; `safeLines` is a clamped integer from args. + +## src/tmux-runner.mjs (copy: src/ide/tmux-runner.mjs) + +Both files are full copies, not re-exports. + +- L9 `tmux has-session -t ${JSON.stringify(session)}` — `session` from caller / `config.tmux.default_session`. +- L16 `tmux new-session -d -s ${JSON.stringify(session)}` — same session. +- L62 `tmux send-keys -t ${JSON.stringify(sessionName)} ${JSON.stringify(wrappedCmd)} C-m` — `wrappedCmd` interpolates `cwd` (caller) and `cmd` (caller, after `config.tmux.allow` prefix match). +- L86 `cat ${exitFile}` — path `/tmp/iak-exit-${traceId.slice(0,8)}`; `traceId` is `randomUUID()`. +- L104 `tail -${tailLines} ${outFile}` — `tailLines` from `config.receipts.stdout_tail_lines`; path from `traceId`. +- L105 same for `errFile`. +- L108 `rm -f ${outFile} ${errFile} ${exitFile}` — same temp paths. + +## src/team-relay/webhook-server.mjs + +- L342 `execSync(wakeCmd)` — whole command from `config.poller.nudge_command` or `config.poller.wake_script`. `src/webhook-server.mjs` no longer has this call. + +## src/discord-poller.mjs (copy: src/team-relay/discord-poller.mjs) + +- L65 `execSync(cmd)` — `cmd` is `export PATH=... && export OPENCLAW_HOME=${oc.home} && ${oc.bin} message read --channel discord --target ${channelId} --limit ${limit} --json`, optionally wrapped in `ssh ${oc.ssh} '...'`. + - `oc.home` / `oc.bin` / `oc.ssh` from `config.openclaw` (else module defaults / env). + - `channelId` from Discord poller config. + - `limit` is the function argument (default 20). + +## src/memory.mjs (copy: src/team-relay/memory.mjs) + +- L146 `execSync(cmd)` — OpenClaw `memory search '${safeQuery}' --limit ${maxResults} --json`, same `oc.home`/`bin`/`ssh` wrapping as discord-poller. + - `query` from the caller (MCP / CLI); single quotes escaped. + - `maxResults` from caller options (default 10). + +## src/openclaw-gateway.mjs + +Shared `ocExec` (L34): `OPENCLAW_HOME=${oc.home}` plus `${oc.bin} ${subcommand}`, optional `ssh ${oc.ssh}`. `home`/`bin`/`ssh` from `config.openclaw` or options or env. `subcommand` is a fixed string or built by the exported function. + +- L41 `ocExec` used by agents list and other CLI wrappers — subcommand from caller. +- L105 `configGet`: `cat ${oc.home}/openclaw.json` (or ssh+cat). +- L129 `configPatch`: `echo '${safeJson}' > ${oc.home}/openclaw.json` — `safeJson` is the merged config with single quotes escaped. +- L159 `gatewayRestart`: `nohup ${oc.bin} gateway --force > /tmp/gw_restart.log 2>&1 &`. + +## src/openclaw-sessions.mjs + +- L38 `ocExec` — same wrapper as gateway. Subcommands interpolate `params.message` / `params.task` (single-quote escaped), `params.agentId`, `params.model`. +- L101 `execSync(readCmd)` — `ls -t ${dataDir}/agents/${agentId}/sessions/*.jsonl | head -1 | xargs tail -${limit}`. + - `dataDir` derived from `oc.home`. + - `agentId` from `params.sessionKey` (second colon-separated field, default `main`). + - `limit` from `params.limit` (default 20). + +## src/openclaw-cron.mjs + +- L37 `ocExec` — same `home`/`bin`/`ssh` wrapper; `subcommand` from the cron helper (list/add/remove). + +## packages/user-intent-kit (outside src/, listed for completeness) + +- `bin/uik-daemon.js` L169 `execSync(gateCmd)` — whole command from env `INTENT_AGENT_GATE_CMD`. +- `src/adapters/desktop.js` L240 `execSync(\`osascript -e 'tell application "System Events" ...'\`)` — AppleScript string is fixed. + +## Not in this list + +`execFileSync` leftovers (argv, no shell) are out of scope for the next execSync pass: `src/common/notify.mjs` tmux nudge, `src/room-automation.mjs` exec action, `src/adapters/discord.mjs` OpenClaw, `src/history-scan.mjs` git, `scripts/check-stageable-secrets.mjs` git, `bin/model-tidy.mjs` curl POST to GroupMind. + +Room HTTP on this branch already uses `src/common/http.mjs` `fetchJson` (or direct `fetch` in `src/room-automation.mjs`). diff --git a/src/adapters/comments.mjs b/src/adapters/comments.mjs index 6a6ab86..5a176f3 100644 --- a/src/adapters/comments.mjs +++ b/src/adapters/comments.mjs @@ -1,39 +1,30 @@ // SPDX-License-Identifier: AGPL-3.0-only -import { execFileSync } from 'node:child_process'; import { randomUUID } from 'node:crypto'; +import { fetchJson } from '../common/http.mjs'; /** * Comments adapter — polls Moltbook posts and GitHub issues/discussions * for new comments. Composite adapter covering two sources. */ -function fetchMoltbookComments(postId, baseUrl = 'https://www.moltbook.com') { +async function fetchMoltbookComments(postId, baseUrl = 'https://www.moltbook.com') { try { - const url = `${baseUrl}/api/v1/posts/${postId}/comments`; - const result = execFileSync('curl', ['-sS', url], { - encoding: 'utf8', timeout: 15000 - }); - const data = JSON.parse(result); + const root = String(baseUrl || 'https://www.moltbook.com').replace(/\/$/, ''); + const data = await fetchJson(`${root}/api/v1/posts/${encodeURIComponent(postId)}/comments`); return Array.isArray(data) ? data : (data.comments || []); } catch (e) { - console.error(` moltbook ${postId.slice(0, 8)} failed: ${e.message}`); + console.error(` moltbook ${String(postId).slice(0, 8)} failed: ${e.message}`); return []; } } -function fetchGitHubComments(owner, repo, number, type = 'issues', token = '') { +async function fetchGitHubComments(owner, repo, number, type = 'issues', token = '') { const endpoint = type === 'discussion' - ? `https://api.github.com/repos/${owner}/${repo}/discussions/${number}/comments` - : `https://api.github.com/repos/${owner}/${repo}/issues/${number}/comments`; - const curlArgs = ['-sS']; - if (token) curlArgs.push('-H', `Authorization: token ${token}`); - curlArgs.push(`${endpoint}?per_page=50&sort=created&direction=desc`); + ? `https://api.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/discussions/${encodeURIComponent(number)}/comments` + : `https://api.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/issues/${encodeURIComponent(number)}/comments`; try { - const result = execFileSync('curl', curlArgs, { - encoding: 'utf8', timeout: 15000 - }); - const data = JSON.parse(result); + const data = await fetchJson(`${endpoint}?per_page=50&sort=created&direction=desc`, { token }); return Array.isArray(data) ? data : []; } catch (e) { console.error(` github ${owner}/${repo}#${number} failed: ${e.message}`); @@ -41,15 +32,12 @@ function fetchGitHubComments(owner, repo, number, type = 'issues', token = '') { } } -function fetchGitHubIssues(owner, repo, token = '') { - const curlArgs = ['-sS']; - if (token) curlArgs.push('-H', `Authorization: token ${token}`); - curlArgs.push(`https://api.github.com/repos/${owner}/${repo}/issues?state=open&sort=updated&direction=desc&per_page=10`); +async function fetchGitHubIssues(owner, repo, token = '') { try { - const result = execFileSync('curl', curlArgs, { - encoding: 'utf8', timeout: 15000 - }); - const data = JSON.parse(result); + const data = await fetchJson( + `https://api.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/issues?state=open&sort=updated&direction=desc&per_page=10`, + { token }, + ); return Array.isArray(data) ? data : []; } catch { return []; @@ -69,7 +57,7 @@ export const commentsAdapter = { const moltBaseUrl = moltbookCfg.base_url || 'https://www.moltbook.com'; for (const postId of posts) { - const comments = fetchMoltbookComments(postId, moltBaseUrl); + const comments = await fetchMoltbookComments(postId, moltBaseUrl); for (const c of comments) { c._source = 'moltbook'; c._postId = postId; @@ -87,7 +75,7 @@ export const commentsAdapter = { const { owner, repo, type } = repoCfg; if (repoCfg.number) { - const comments = fetchGitHubComments(owner, repo, repoCfg.number, type, ghToken); + const comments = await fetchGitHubComments(owner, repo, repoCfg.number, type, ghToken); for (const c of comments) { c._source = 'github'; c._owner = owner; @@ -97,10 +85,10 @@ export const commentsAdapter = { } all.push(...comments); } else if (type === 'issues') { - const issues = fetchGitHubIssues(owner, repo, ghToken); + const issues = await fetchGitHubIssues(owner, repo, ghToken); for (const issue of issues) { if (!issue.comments || issue.comments === 0) continue; - const comments = fetchGitHubComments(owner, repo, issue.number, 'issues', ghToken); + const comments = await fetchGitHubComments(owner, repo, issue.number, 'issues', ghToken); for (const c of comments) { c._source = 'github'; c._owner = owner; diff --git a/src/adapters/groupmind.mjs b/src/adapters/groupmind.mjs index 5bc0daf..a9c413d 100644 --- a/src/adapters/groupmind.mjs +++ b/src/adapters/groupmind.mjs @@ -1,9 +1,9 @@ // SPDX-License-Identifier: AGPL-3.0-only -import { execFileSync } from 'node:child_process'; import { randomUUID } from 'node:crypto'; import { resolveSelfHandle, isSelfSender } from '../common/handles.mjs'; import { replyIdOf, embeddedTargetOf, resolveReplyTargets, replyAnnotation } from '../common/reply-context.mjs'; +import { fetchJson } from '../common/http.mjs'; /** * GroupMind adapter — polls GroupMind rooms for new messages. @@ -20,12 +20,9 @@ export const groupmindAdapter = { const all = []; for (const room of rooms) { - const url = `https://groupmind.one/api/v1/rooms/${room}/messages?limit=${limit}`; + const url = `https://groupmind.one/api/v1/rooms/${encodeURIComponent(room)}/messages?limit=${limit}`; try { - const result = execFileSync('curl', ['-sS', '-H', `X-API-Key: ${apiKey}`, url], { - encoding: 'utf8', timeout: 15000 - }); - const data = JSON.parse(result); + const data = await fetchJson(url, { headers: { 'X-API-Key': apiKey } }); const msgs = data.messages || (Array.isArray(data) ? data : []); // Resolve reply targets from the same batch: a fresh reply's target is // almost always within the last `limit` messages. Without this the diff --git a/src/adapters/xfor.mjs b/src/adapters/xfor.mjs index 24ceaa0..af7bd8c 100644 --- a/src/adapters/xfor.mjs +++ b/src/adapters/xfor.mjs @@ -1,8 +1,8 @@ // SPDX-License-Identifier: AGPL-3.0-only -import { execFileSync } from 'node:child_process'; import { randomUUID } from 'node:crypto'; import { isSelfSender } from '../common/handles.mjs'; +import { fetchJson } from '../common/http.mjs'; /** * xfor adapter — polls xfor.bot posts and notifications. @@ -11,13 +11,10 @@ import { isSelfSender } from '../common/handles.mjs'; * Auth: X-API-Key header */ -function xforFetch(path, apiKey) { +async function xforFetch(path, apiKey) { const url = `https://xfor.bot/api/v1${path}`; try { - const result = execFileSync('curl', ['-sS', '-H', `X-API-Key: ${apiKey}`, url], { - encoding: 'utf8', timeout: 15000 - }); - return JSON.parse(result); + return await fetchJson(url, { headers: { 'X-API-Key': apiKey } }); } catch (e) { console.error(` xfor fetch ${path} failed: ${e.message}`); return null; @@ -35,7 +32,7 @@ export const xforAdapter = { const all = []; // Poll notifications (mentions, replies, likes, follows) - const notifs = xforFetch('/notifications?unread=true', apiKey); + const notifs = await xforFetch('/notifications?unread=true', apiKey); if (notifs && Array.isArray(notifs)) { for (const n of notifs) { n._type = 'notification'; @@ -49,7 +46,7 @@ export const xforAdapter = { } // Poll recent posts from feed - const feed = xforFetch('/posts', apiKey); + const feed = await xforFetch('/posts', apiKey); if (feed && Array.isArray(feed)) { for (const p of feed) { p._type = 'post'; diff --git a/src/comment-poller.mjs b/src/comment-poller.mjs index dad461d..e420283 100644 --- a/src/comment-poller.mjs +++ b/src/comment-poller.mjs @@ -1,8 +1,9 @@ // SPDX-License-Identifier: AGPL-3.0-only -import { execSync } from 'node:child_process'; -import { readFileSync, writeFileSync, appendFileSync, existsSync } from 'node:fs'; +import { readFileSync, writeFileSync, appendFileSync } from 'node:fs'; import { randomUUID } from 'node:crypto'; +import { nudgeTmux } from './common/notify.mjs'; +import { fetchJson, publicFetchErrorMessage } from './common/http.mjs'; /** * Comment Poller — polls Moltbook posts and GitHub issues/discussions @@ -42,35 +43,16 @@ function saveSeenIds(path, ids) { writeFileSync(path, arr.join('\n') + '\n'); } -function nudgeTmux(session, text) { - try { - execSync(`tmux has-session -t ${JSON.stringify(session)} 2>/dev/null`); - } catch { - return false; - } - try { - execSync(`tmux send-keys -t ${JSON.stringify(session)} -l ${JSON.stringify(text)}`); - execSync('sleep 0.3'); - execSync(`tmux send-keys -t ${JSON.stringify(session)} Enter`); - return true; - } catch { - return false; - } -} - /** * Fetch comments for a Moltbook post. */ -function fetchMoltbookComments(postId, baseUrl = 'https://www.moltbook.com') { +async function fetchMoltbookComments(postId, baseUrl = 'https://www.moltbook.com') { try { - const result = execSync( - `curl -sS "${baseUrl}/api/v1/posts/${postId}/comments"`, - { encoding: 'utf8', timeout: 15000 } - ); - const data = JSON.parse(result); + const root = String(baseUrl || 'https://www.moltbook.com').replace(/\/$/, ''); + const data = await fetchJson(`${root}/api/v1/posts/${encodeURIComponent(postId)}/comments`); return Array.isArray(data) ? data : (data.comments || []); } catch (e) { - console.error(` moltbook ${postId.slice(0, 8)} failed: ${e.message}`); + console.error(` moltbook ${String(postId).slice(0, 8)} failed: ${publicFetchErrorMessage(e)}`); return []; } } @@ -78,21 +60,15 @@ function fetchMoltbookComments(postId, baseUrl = 'https://www.moltbook.com') { /** * Fetch comments for a GitHub issue or discussion. */ -function fetchGitHubComments(owner, repo, number, type = 'issues', token = '') { - const authHeader = token ? `-H "Authorization: token ${token}"` : ''; +async function fetchGitHubComments(owner, repo, number, type = 'issues', token = '') { const endpoint = type === 'discussion' - ? `https://api.github.com/repos/${owner}/${repo}/discussions/${number}/comments` - : `https://api.github.com/repos/${owner}/${repo}/issues/${number}/comments`; - + ? `https://api.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/discussions/${encodeURIComponent(number)}/comments` + : `https://api.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/issues/${encodeURIComponent(number)}/comments`; try { - const result = execSync( - `curl -sS ${authHeader} "${endpoint}?per_page=50&sort=created&direction=desc"`, - { encoding: 'utf8', timeout: 15000 } - ); - const data = JSON.parse(result); + const data = await fetchJson(`${endpoint}?per_page=50&sort=created&direction=desc`, { token }); return Array.isArray(data) ? data : []; } catch (e) { - console.error(` github ${owner}/${repo}#${number} failed: ${e.message}`); + console.error(` github ${owner}/${repo}#${number} failed: ${publicFetchErrorMessage(e)}`); return []; } } @@ -100,14 +76,12 @@ function fetchGitHubComments(owner, repo, number, type = 'issues', token = '') { /** * Fetch all open issues for a GitHub repo (to discover new comments). */ -function fetchGitHubIssues(owner, repo, token = '') { - const authHeader = token ? `-H "Authorization: token ${token}"` : ''; +async function fetchGitHubIssues(owner, repo, token = '') { try { - const result = execSync( - `curl -sS ${authHeader} "https://api.github.com/repos/${owner}/${repo}/issues?state=open&sort=updated&direction=desc&per_page=10"`, - { encoding: 'utf8', timeout: 15000 } + const data = await fetchJson( + `https://api.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/issues?state=open&sort=updated&direction=desc&per_page=10`, + { token }, ); - const data = JSON.parse(result); return Array.isArray(data) ? data : []; } catch { return []; @@ -119,7 +93,7 @@ function fetchGitHubIssues(owner, repo, token = '') { * * @returns {object[]} Array of new comment events */ -export function pollComments(config) { +export async function pollComments(config) { const commentsCfg = config?.comments || {}; const seen = loadSeenIds(commentsCfg.seen_file || SEEN_FILE_DEFAULT); const newComments = []; @@ -130,7 +104,7 @@ export function pollComments(config) { const moltBaseUrl = moltbookCfg.base_url || 'https://www.moltbook.com'; for (const postId of posts) { - const comments = fetchMoltbookComments(postId, moltBaseUrl); + const comments = await fetchMoltbookComments(postId, moltBaseUrl); for (const c of comments) { const cid = c.id || ''; const key = `moltbook:${cid}`; @@ -162,7 +136,7 @@ export function pollComments(config) { if (repoCfg.number) { // Poll specific issue/discussion - const comments = fetchGitHubComments(owner, repo, repoCfg.number, type, ghToken); + const comments = await fetchGitHubComments(owner, repo, repoCfg.number, type, ghToken); for (const c of comments) { const cid = String(c.id || ''); const key = `github:${owner}/${repo}:${cid}`; @@ -184,10 +158,10 @@ export function pollComments(config) { } } else if (type === 'issues') { // Poll all open issues for new comments - const issues = fetchGitHubIssues(owner, repo, ghToken); + const issues = await fetchGitHubIssues(owner, repo, ghToken); for (const issue of issues) { if (!issue.comments || issue.comments === 0) continue; - const comments = fetchGitHubComments(owner, repo, issue.number, 'issues', ghToken); + const comments = await fetchGitHubComments(owner, repo, issue.number, 'issues', ghToken); for (const c of comments) { const cid = String(c.id || ''); const key = `github:${owner}/${repo}:${cid}`; @@ -235,11 +209,11 @@ export async function startCommentPoller({ config, interval }) { // Seed: do initial poll to mark existing comments as seen console.log(` seeding existing comments...`); - const initial = pollComments(config); + const initial = await pollComments(config); console.log(` seeded (${initial.length} comments marked as seen)`); async function poll() { - const newComments = pollComments(config); + const newComments = await pollComments(config); if (newComments.length > 0) { for (const c of newComments) { @@ -255,18 +229,41 @@ export async function startCommentPoller({ config, interval }) { } } - // Start interval - const timer = setInterval(poll, pollInterval * 1000); + // Schedule the next tick only after the current poll finishes. setInterval + // started overlapping fetches once pollComments became async, and each tick + // reloaded its own seen set, so the same comment was delivered more than once. + let stopped = false; + let timer = null; + let inFlight = false; + + async function tick() { + if (stopped || inFlight) return; + inFlight = true; + try { + await poll(); + } finally { + inFlight = false; + if (!stopped) timer = setTimeout(tick, pollInterval * 1000); + } + } + + timer = setTimeout(tick, pollInterval * 1000); + + function stop() { + stopped = true; + if (timer) clearTimeout(timer); + timer = null; + } process.on('SIGINT', () => { console.log('\nComment poller stopped.'); - clearInterval(timer); + stop(); process.exit(0); }); process.on('SIGTERM', () => { - clearInterval(timer); + stop(); process.exit(0); }); - return timer; + return { stop }; } diff --git a/src/common/http.mjs b/src/common/http.mjs new file mode 100644 index 0000000..e865c19 --- /dev/null +++ b/src/common/http.mjs @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +/** + * HTTP JSON GET with optional token in a header. No child process. + * Thrown messages never include header values (a bad token can make fetch + * reject with the whole Authorization value in TypeError.message). + */ +export function publicFetchErrorMessage(err) { + const m = err && typeof err.message === 'string' ? err.message : ''; + if (/^HTTP \d+$/.test(m)) return m; + if (m === 'request timed out') return m; + return 'request failed'; +} + +export async function fetchJson(url, { token, timeoutMs = 15000, headers = {} } = {}) { + try { + const h = { Accept: 'application/json', 'User-Agent': 'ide-agent-kit', ...headers }; + if (token) h.Authorization = `token ${token}`; + const res = await fetch(String(url), { + headers: h, + signal: AbortSignal.timeout(timeoutMs), + }); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + return await res.json(); + } catch (e) { + const name = e && e.name; + if (name === 'TimeoutError' || name === 'AbortError') throw new Error('request timed out'); + const m = e && typeof e.message === 'string' ? e.message : ''; + if (/^HTTP \d+$/.test(m)) throw e; + throw new Error('request failed'); + } +} diff --git a/src/common/notify.mjs b/src/common/notify.mjs index d9d7fde..5c0776a 100644 --- a/src/common/notify.mjs +++ b/src/common/notify.mjs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-only -import { execSync } from 'node:child_process'; +import { execFileSync } from 'node:child_process'; import { appendFileSync, readFileSync, writeFileSync } from 'node:fs'; /** @@ -8,16 +8,41 @@ import { appendFileSync, readFileSync, writeFileSync } from 'node:fs'; * Supports tmux nudge and notification file delivery. */ -export function nudgeTmux(session, text) { +// Same token as argvForExec in room-automation.mjs. +const EXEC_SAFE_TOKEN = /^[A-Za-z0-9._@/=+-]+$/; + +export function execSafeSession(session) { + const v = String(session || ''); + if (!v) return { error: 'session is empty' }; + if (v.startsWith('-')) return { error: 'session may not start with -' }; + if (!EXEC_SAFE_TOKEN.test(v)) return { error: 'session failed the allowed pattern' }; + return { value: v }; +} + +function sleepMs(ms) { + const n = Number(ms); + if (!Number.isFinite(n) || n <= 0) return; + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, n); +} + +function tmuxArgv(args) { + execFileSync('tmux', args, { stdio: 'ignore', timeout: 5000 }); +} + +export function nudgeTmux(session, text, opts = {}) { + const checked = execSafeSession(session); + if (checked.error) return false; + const payload = text == null ? '' : String(text); + const delayMs = opts.delayMs === undefined ? 300 : opts.delayMs; try { - execSync(`tmux has-session -t ${JSON.stringify(session)} 2>/dev/null`); + tmuxArgv(['has-session', '-t', checked.value]); } catch { return false; } try { - execSync(`tmux send-keys -t ${JSON.stringify(session)} -l ${JSON.stringify(text)}`); - execSync('sleep 0.3'); - execSync(`tmux send-keys -t ${JSON.stringify(session)} Enter`); + tmuxArgv(['send-keys', '-t', checked.value, '-l', '--', payload]); + sleepMs(delayMs); + tmuxArgv(['send-keys', '-t', checked.value, 'Enter']); return true; } catch { return false; diff --git a/src/discord-poller.mjs b/src/discord-poller.mjs index 74b5f38..0fc6764 100644 --- a/src/discord-poller.mjs +++ b/src/discord-poller.mjs @@ -3,6 +3,7 @@ import { execSync } from 'node:child_process'; import { readFileSync, writeFileSync, appendFileSync } from 'node:fs'; import { randomUUID } from 'node:crypto'; +import { nudgeTmux } from './common/notify.mjs'; /** * Discord Poller — polls Discord channels via OpenClaw CLI. @@ -45,22 +46,6 @@ function saveSeenIds(path, ids) { writeFileSync(path, arr.join('\n') + '\n'); } -function nudgeTmux(session, text) { - try { - execSync(`tmux has-session -t ${JSON.stringify(session)} 2>/dev/null`); - } catch { - return false; - } - try { - execSync(`tmux send-keys -t ${JSON.stringify(session)} -l ${JSON.stringify(text)}`); - execSync('sleep 0.3'); - execSync(`tmux send-keys -t ${JSON.stringify(session)} Enter`); - return true; - } catch { - return false; - } -} - function resolveOC(config) { const oc = config?.openclaw || {}; return { diff --git a/src/ide/comment-poller.mjs b/src/ide/comment-poller.mjs index dad461d..108d808 100644 --- a/src/ide/comment-poller.mjs +++ b/src/ide/comment-poller.mjs @@ -1,272 +1,4 @@ // SPDX-License-Identifier: AGPL-3.0-only - -import { execSync } from 'node:child_process'; -import { readFileSync, writeFileSync, appendFileSync, existsSync } from 'node:fs'; -import { randomUUID } from 'node:crypto'; - -/** - * Comment Poller — polls Moltbook posts and GitHub issues/discussions - * for new comments. Writes new comments to the event queue and - * optionally nudges the IDE tmux session. - * - * Config (in ide-agent-kit.json under comments): - * { - * "moltbook": { - * "posts": ["uuid1", "uuid2"], - * "base_url": "https://www.moltbook.com" - * }, - * "github": { - * "repos": [ - * { "owner": "ThinkOffApp", "repo": "ide-agent-kit", "type": "issues" }, - * { "owner": "HKUDS", "repo": "nanobot", "number": 431, "type": "discussion" } - * ], - * "token": "" - * }, - * "interval_sec": 120, - * "seen_file": "/tmp/iak-comment-seen.txt" - * } - */ - -const SEEN_FILE_DEFAULT = '/tmp/iak-comment-seen.txt'; - -function loadSeenIds(path) { - try { - return new Set(readFileSync(path, 'utf8').split('\n').filter(Boolean)); - } catch { - return new Set(); - } -} - -function saveSeenIds(path, ids) { - const arr = [...ids].slice(-5000); - writeFileSync(path, arr.join('\n') + '\n'); -} - -function nudgeTmux(session, text) { - try { - execSync(`tmux has-session -t ${JSON.stringify(session)} 2>/dev/null`); - } catch { - return false; - } - try { - execSync(`tmux send-keys -t ${JSON.stringify(session)} -l ${JSON.stringify(text)}`); - execSync('sleep 0.3'); - execSync(`tmux send-keys -t ${JSON.stringify(session)} Enter`); - return true; - } catch { - return false; - } -} - -/** - * Fetch comments for a Moltbook post. - */ -function fetchMoltbookComments(postId, baseUrl = 'https://www.moltbook.com') { - try { - const result = execSync( - `curl -sS "${baseUrl}/api/v1/posts/${postId}/comments"`, - { encoding: 'utf8', timeout: 15000 } - ); - const data = JSON.parse(result); - return Array.isArray(data) ? data : (data.comments || []); - } catch (e) { - console.error(` moltbook ${postId.slice(0, 8)} failed: ${e.message}`); - return []; - } -} - -/** - * Fetch comments for a GitHub issue or discussion. - */ -function fetchGitHubComments(owner, repo, number, type = 'issues', token = '') { - const authHeader = token ? `-H "Authorization: token ${token}"` : ''; - const endpoint = type === 'discussion' - ? `https://api.github.com/repos/${owner}/${repo}/discussions/${number}/comments` - : `https://api.github.com/repos/${owner}/${repo}/issues/${number}/comments`; - - try { - const result = execSync( - `curl -sS ${authHeader} "${endpoint}?per_page=50&sort=created&direction=desc"`, - { encoding: 'utf8', timeout: 15000 } - ); - const data = JSON.parse(result); - return Array.isArray(data) ? data : []; - } catch (e) { - console.error(` github ${owner}/${repo}#${number} failed: ${e.message}`); - return []; - } -} - -/** - * Fetch all open issues for a GitHub repo (to discover new comments). - */ -function fetchGitHubIssues(owner, repo, token = '') { - const authHeader = token ? `-H "Authorization: token ${token}"` : ''; - try { - const result = execSync( - `curl -sS ${authHeader} "https://api.github.com/repos/${owner}/${repo}/issues?state=open&sort=updated&direction=desc&per_page=10"`, - { encoding: 'utf8', timeout: 15000 } - ); - const data = JSON.parse(result); - return Array.isArray(data) ? data : []; - } catch { - return []; - } -} - -/** - * Poll all configured sources for new comments. - * - * @returns {object[]} Array of new comment events - */ -export function pollComments(config) { - const commentsCfg = config?.comments || {}; - const seen = loadSeenIds(commentsCfg.seen_file || SEEN_FILE_DEFAULT); - const newComments = []; - - // Poll Moltbook posts - const moltbookCfg = commentsCfg.moltbook || {}; - const posts = moltbookCfg.posts || []; - const moltBaseUrl = moltbookCfg.base_url || 'https://www.moltbook.com'; - - for (const postId of posts) { - const comments = fetchMoltbookComments(postId, moltBaseUrl); - for (const c of comments) { - const cid = c.id || ''; - const key = `moltbook:${cid}`; - if (!cid || seen.has(key)) continue; - seen.add(key); - - const author = typeof c.author === 'object' ? c.author?.name : (c.author || '?'); - newComments.push({ - trace_id: randomUUID(), - source: 'moltbook', - kind: 'moltbook.comment.created', - timestamp: c.created_at || c.createdAt || new Date().toISOString(), - post_id: postId, - comment_id: cid, - author, - body: (c.body || c.content || '').slice(0, 500), - url: `${moltBaseUrl}/post/${postId}#comment-${cid}` - }); - } - } - - // Poll GitHub repos - const githubCfg = commentsCfg.github || {}; - const repos = githubCfg.repos || []; - const ghToken = githubCfg.token || ''; - - for (const repoCfg of repos) { - const { owner, repo, type } = repoCfg; - - if (repoCfg.number) { - // Poll specific issue/discussion - const comments = fetchGitHubComments(owner, repo, repoCfg.number, type, ghToken); - for (const c of comments) { - const cid = String(c.id || ''); - const key = `github:${owner}/${repo}:${cid}`; - if (!cid || seen.has(key)) continue; - seen.add(key); - - newComments.push({ - trace_id: randomUUID(), - source: 'github', - kind: `github.${type || 'issues'}.comment.created`, - timestamp: c.created_at || new Date().toISOString(), - repo: `${owner}/${repo}`, - number: repoCfg.number, - comment_id: cid, - author: c.user?.login || '?', - body: (c.body || '').slice(0, 500), - url: c.html_url || `https://github.com/${owner}/${repo}/issues/${repoCfg.number}` - }); - } - } else if (type === 'issues') { - // Poll all open issues for new comments - const issues = fetchGitHubIssues(owner, repo, ghToken); - for (const issue of issues) { - if (!issue.comments || issue.comments === 0) continue; - const comments = fetchGitHubComments(owner, repo, issue.number, 'issues', ghToken); - for (const c of comments) { - const cid = String(c.id || ''); - const key = `github:${owner}/${repo}:${cid}`; - if (!cid || seen.has(key)) continue; - seen.add(key); - - newComments.push({ - trace_id: randomUUID(), - source: 'github', - kind: 'github.issues.comment.created', - timestamp: c.created_at || new Date().toISOString(), - repo: `${owner}/${repo}`, - number: issue.number, - comment_id: cid, - author: c.user?.login || '?', - body: (c.body || '').slice(0, 500), - url: c.html_url || '' - }); - } - } - } - } - - saveSeenIds(commentsCfg.seen_file || SEEN_FILE_DEFAULT, seen); - return newComments; -} - -/** - * Start the comment poller as a long-running process. - */ -export async function startCommentPoller({ config, interval }) { - const commentsCfg = config?.comments || {}; - const pollInterval = interval || commentsCfg.interval_sec || 120; - const queuePath = config?.queue?.path || './ide-agent-queue.jsonl'; - const session = config?.tmux?.ide_session || 'claude'; - const nudgeText = config?.tmux?.nudge_text || 'check rooms'; - - const moltPosts = commentsCfg.moltbook?.posts || []; - const ghRepos = commentsCfg.github?.repos || []; - - console.log(`Comment poller started`); - console.log(` moltbook posts: ${moltPosts.length}`); - console.log(` github repos: ${ghRepos.length}`); - console.log(` interval: ${pollInterval}s`); - - // Seed: do initial poll to mark existing comments as seen - console.log(` seeding existing comments...`); - const initial = pollComments(config); - console.log(` seeded (${initial.length} comments marked as seen)`); - - async function poll() { - const newComments = pollComments(config); - - if (newComments.length > 0) { - for (const c of newComments) { - appendFileSync(queuePath, JSON.stringify(c) + '\n'); - const sourceLabel = c.source === 'moltbook' - ? `moltbook/${c.post_id?.slice(0, 8)}` - : `${c.repo}#${c.number}`; - console.log(` NEW: @${c.author} on ${sourceLabel}: ${c.body.slice(0, 80)}`); - } - - const nudged = nudgeTmux(session, nudgeText); - console.log(` ${newComments.length} new comment(s) → ${nudged ? 'nudged' : 'no tmux session'}`); - } - } - - // Start interval - const timer = setInterval(poll, pollInterval * 1000); - - process.on('SIGINT', () => { - console.log('\nComment poller stopped.'); - clearInterval(timer); - process.exit(0); - }); - process.on('SIGTERM', () => { - clearInterval(timer); - process.exit(0); - }); - - return timer; -} +// +// RE-EXPORT SHIM - canonical implementation is src/comment-poller.mjs. +export { pollComments, startCommentPoller } from '../comment-poller.mjs'; diff --git a/src/ide/watch.mjs b/src/ide/watch.mjs index cc899e4..4d16bc7 100644 --- a/src/ide/watch.mjs +++ b/src/ide/watch.mjs @@ -1,90 +1,4 @@ // SPDX-License-Identifier: AGPL-3.0-only - -import { watch, readFileSync, statSync } from 'node:fs'; -import { execSync } from 'node:child_process'; - -/** - * Watch the queue JSONL file for new entries and trigger tmux nudge immediately. - * This replaces slow polling with instant file-change detection. - */ -export function watchQueue(config, onNewEvent) { - const queuePath = config.queue.path; - const session = config.tmux?.ide_session || 'claude'; - const nudgeText = config.tmux?.nudge_text || 'check rooms'; - let lastSize = 0; - - try { - lastSize = statSync(queuePath).size; - } catch { /* file may not exist yet */ } - - console.log(`Watching ${queuePath} for new events...`); - console.log(` tmux nudge → session "${session}" with "${nudgeText}"`); - - // Use fs.watchFile for reliable cross-platform polling (works on all FS types) - const watcher = watch(queuePath, { persistent: true }, (eventType) => { - if (eventType !== 'change') return; - - let currentSize; - try { - currentSize = statSync(queuePath).size; - } catch { return; } - - if (currentSize <= lastSize) { - lastSize = currentSize; - return; - } - - // Read new content using byte offset for correct UTF-8 handling - const buf = readFileSync(queuePath); - const newBuf = buf.slice(lastSize); - lastSize = currentSize; - const newContent = newBuf.toString('utf8').trim(); - if (!newContent) return; - const newLines = newContent.split('\n'); - - if (newLines.length === 0) return; - - const events = []; - for (const line of newLines) { - try { - events.push(JSON.parse(line)); - } catch { /* skip malformed */ } - } - - if (events.length === 0) return; - - console.log(`[${new Date().toISOString()}] ${events.length} new event(s) in queue`); - - // Trigger callback for each event - for (const event of events) { - if (onNewEvent) onNewEvent(event); - } - - // Nudge tmux session - nudgeTmux(session, nudgeText); - }); - - return watcher; -} - -function nudgeTmux(session, text) { - try { - execSync(`tmux has-session -t ${JSON.stringify(session)} 2>/dev/null`); - } catch { - console.log(` tmux session "${session}" not found, skipping nudge`); - return; - } - - try { - execSync(`tmux send-keys -t ${JSON.stringify(session)} -l ${JSON.stringify(text)}`); - // Small delay then Enter - setTimeout(() => { - try { - execSync(`tmux send-keys -t ${JSON.stringify(session)} Enter`); - } catch {} - }, 300); - console.log(` nudged tmux session "${session}"`); - } catch (e) { - console.log(` tmux nudge failed: ${e.message}`); - } -} +// +// RE-EXPORT SHIM - canonical implementation is src/watch.mjs. +export { watchQueue } from '../watch.mjs'; diff --git a/src/room-automation.mjs b/src/room-automation.mjs index 08198d4..39de9d5 100644 --- a/src/room-automation.mjs +++ b/src/room-automation.mjs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-only -import { execSync } from 'node:child_process'; +import { execFileSync } from 'node:child_process'; import { readFileSync, writeFileSync, appendFileSync, existsSync, renameSync, unlinkSync } from 'node:fs'; import { homedir } from 'node:os'; import { randomUUID } from 'node:crypto'; @@ -8,6 +8,7 @@ import { createReceipt, appendReceipt } from './receipt.mjs'; import { canSend, markSent } from './rate-limiter.mjs'; import { shouldSuppressNudge } from './intent.mjs'; import { resolveSelfHandle, isSelfSender } from './common/handles.mjs'; +import { nudgeTmux, execSafeSession } from './common/notify.mjs'; // Ack-only messages are low-value and cause loops. Filter them out from automation posts. const ACK_ONLY_PATTERNS = [ @@ -25,6 +26,40 @@ function isAckOnly(body) { ); } +const EXEC_SAFE_TOKEN = /^[A-Za-z0-9._@/=+-]+$/; + +function execSafeValue(name, value) { + const v = String(value || ''); + if (!v) return { error: `${name} is empty` }; + if (v.startsWith('-')) return { error: `${name} may not start with -` }; + if (!EXEC_SAFE_TOKEN.test(v)) return { error: `${name} failed the allowed pattern` }; + return { value: v }; +} + +function argvForExec(template, room, sender) { + if ((template || '').includes('${body}')) { + return { error: 'exec command may not include ${body}' }; + } + let cmd = template || ''; + if (cmd.includes('${room}')) { + const r = execSafeValue('room', room); + if (r.error) return r; + cmd = cmd.replace(/\$\{room\}/g, r.value); + } + if (cmd.includes('${sender}')) { + const raw = String(sender || '').replace(/^@+/, ''); + const s = execSafeValue('sender', raw); + if (s.error) return s; + cmd = cmd.replace(/\$\{sender\}/g, s.value); + } + if (/[;&|<>`$(){}]/.test(cmd)) { + return { error: 'exec command has shell metacharacters' }; + } + const argv = cmd.trim().split(/\s+/).filter(Boolean); + if (argv.length === 0) return { error: 'empty exec command' }; + return { argv }; +} + /** * Room Automation — rule-based automation triggered by GroupMind room messages. * @@ -395,13 +430,28 @@ async function executeAction(action, msg, apiKey, config, muted = false) { } if (action.type === 'exec') { - const cmd = sub(action.command); const timeout = action.timeout || 30000; + const parsed = argvForExec(action.command || '', room, msg.user?.handle || msg.from || ''); + if (parsed.error) { + return createReceipt({ + actor: { name: 'automation', kind: 'exec' }, + action: 'exec refused', + status: 'error', + notes: parsed.error, + startedAt, + }); + } + const [file, ...args] = parsed.argv; try { - const output = execSync(cmd, { encoding: 'utf8', timeout, cwd: action.cwd }); + const output = execFileSync(file, args, { + encoding: 'utf8', + timeout, + cwd: action.cwd, + shell: false, + }); return createReceipt({ actor: { name: 'automation', kind: 'exec' }, - action: `exec: ${cmd.slice(0, 80)}`, + action: `exec: ${parsed.argv.join(' ').slice(0, 80)}`, status: 'ok', exitCode: 0, stdoutTail: output.slice(-500), @@ -410,7 +460,7 @@ async function executeAction(action, msg, apiKey, config, muted = false) { } catch (e) { return createReceipt({ actor: { name: 'automation', kind: 'exec' }, - action: `exec: ${cmd.slice(0, 80)}`, + action: `exec: ${parsed.argv.join(' ').slice(0, 80)}`, status: 'error', exitCode: e.status || 1, stderrTail: (e.stderr || e.message || '').slice(-500), @@ -422,26 +472,24 @@ async function executeAction(action, msg, apiKey, config, muted = false) { if (action.type === 'nudge') { const session = config?.tmux?.ide_session || 'claude'; const text = sub(action.text) || 'check rooms'; - try { - execSync(`tmux send-keys -t ${JSON.stringify(session)} -l ${JSON.stringify(text)}`); - execSync('sleep 0.3'); - execSync(`tmux send-keys -t ${JSON.stringify(session)} Enter`); - return createReceipt({ - actor: { name: 'automation', kind: 'nudge' }, - action: `nudge tmux ${session}`, - status: 'ok', - notes: `Sent: ${text}`, - startedAt, - }); - } catch (e) { + const checked = execSafeSession(session); + if (checked.error) { return createReceipt({ actor: { name: 'automation', kind: 'nudge' }, action: `nudge tmux ${session}`, status: 'error', - notes: e.message, + notes: checked.error, startedAt, }); } + const ok = nudgeTmux(checked.value, text); + return createReceipt({ + actor: { name: 'automation', kind: 'nudge' }, + action: `nudge tmux ${checked.value}`, + status: ok ? 'ok' : 'error', + notes: ok ? `Sent: ${text}` : 'tmux session missing or send-keys failed', + startedAt, + }); } return createReceipt({ @@ -667,4 +715,4 @@ export async function startRoomAutomation({ rooms, apiKey, handle, interval, con // Exported for tests only: the mute carve-out is the kind of logic that must // be provable, not eyeballed, because both of its failure modes are silent. -export { executeAction as executeActionForTest }; +export { executeAction as executeActionForTest, argvForExec as argvForExecForTest }; diff --git a/src/room-poller.mjs b/src/room-poller.mjs index 05839c2..19c05e7 100644 --- a/src/room-poller.mjs +++ b/src/room-poller.mjs @@ -7,6 +7,7 @@ import { randomUUID } from 'node:crypto'; import { execSync } from 'node:child_process'; import { nudgeTmux, nudgeCommand } from './utils.mjs'; import { resolveSelfHandle, isSelfSender } from './common/handles.mjs'; +import { fetchJson } from './common/http.mjs'; /** * Room Poller — polls GroupMind rooms and notifies IDE agent of new messages. @@ -43,13 +44,9 @@ function saveSeenIds(path, ids) { } async function fetchRoomMessages(room, apiKey, limit = 10) { - const url = `https://groupmind.one/api/v1/rooms/${room}/messages?limit=${limit}`; + const url = `https://groupmind.one/api/v1/rooms/${encodeURIComponent(room)}/messages?limit=${limit}`; try { - const result = execSync( - `curl -sS -H "Authorization: Bearer ${apiKey}" "${url}"`, - { encoding: 'utf8', timeout: 15000 } - ); - const data = JSON.parse(result); + const data = await fetchJson(url, { headers: { Authorization: `Bearer ${apiKey}` } }); return data.messages || (Array.isArray(data) ? data : []); } catch (e) { console.error(` fetch ${room} failed: ${e.message}`); diff --git a/src/team-relay/common/notify.mjs b/src/team-relay/common/notify.mjs index 6eeebcd..3d6c416 100644 --- a/src/team-relay/common/notify.mjs +++ b/src/team-relay/common/notify.mjs @@ -1,58 +1,5 @@ // SPDX-License-Identifier: AGPL-3.0-only - -import { execSync } from 'node:child_process'; -import { appendFileSync, readFileSync, writeFileSync } from 'node:fs'; - -/** - * Shared notification utilities for all platform pollers. - * Supports tmux nudge and notification file delivery. - */ - -export function nudgeTmux(session, text) { - try { - execSync(`tmux has-session -t ${JSON.stringify(session)} 2>/dev/null`); - } catch { - return false; - } - try { - execSync(`tmux send-keys -t ${JSON.stringify(session)} -l ${JSON.stringify(text)}`); - execSync('sleep 0.3'); - execSync(`tmux send-keys -t ${JSON.stringify(session)} Enter`); - return true; - } catch { - return false; - } -} - -export function nudgeCommand(command, { text = 'check rooms', session = '' } = {}) { - if (!command || typeof command !== 'string') return false; - try { - execSync(command, { - stdio: 'ignore', - env: { - ...process.env, - IAK_NUDGE_TEXT: text, - IAK_TMUX_SESSION: session - } - }); - return true; - } catch { - return false; - } -} - -export function writeNotification(notifyFile, lines) { - if (lines.length === 0) return; - appendFileSync(notifyFile, lines.join('\n') + '\n'); -} - -export function readAndClearNotifications(notifyFile) { - try { - const content = readFileSync(notifyFile, 'utf8').trim(); - if (!content) return []; - writeFileSync(notifyFile, ''); - return content.split('\n').filter(Boolean); - } catch { - return []; - } -} +// +// RE-EXPORT SHIM - canonical implementation is src/common/notify.mjs. +export { nudgeTmux, writeNotification, readAndClearNotifications } from '../../common/notify.mjs'; +export { nudgeCommand } from '../../utils.mjs'; diff --git a/src/team-relay/discord-poller.mjs b/src/team-relay/discord-poller.mjs index 74b5f38..909bdca 100644 --- a/src/team-relay/discord-poller.mjs +++ b/src/team-relay/discord-poller.mjs @@ -3,6 +3,7 @@ import { execSync } from 'node:child_process'; import { readFileSync, writeFileSync, appendFileSync } from 'node:fs'; import { randomUUID } from 'node:crypto'; +import { nudgeTmux } from '../common/notify.mjs'; /** * Discord Poller — polls Discord channels via OpenClaw CLI. @@ -45,22 +46,6 @@ function saveSeenIds(path, ids) { writeFileSync(path, arr.join('\n') + '\n'); } -function nudgeTmux(session, text) { - try { - execSync(`tmux has-session -t ${JSON.stringify(session)} 2>/dev/null`); - } catch { - return false; - } - try { - execSync(`tmux send-keys -t ${JSON.stringify(session)} -l ${JSON.stringify(text)}`); - execSync('sleep 0.3'); - execSync(`tmux send-keys -t ${JSON.stringify(session)} Enter`); - return true; - } catch { - return false; - } -} - function resolveOC(config) { const oc = config?.openclaw || {}; return { diff --git a/src/team-relay/room-poller.mjs b/src/team-relay/room-poller.mjs index 3931438..e39ae5f 100644 --- a/src/team-relay/room-poller.mjs +++ b/src/team-relay/room-poller.mjs @@ -3,10 +3,11 @@ import { loadSeenIds, saveSeenIds as saveSeenIdsShared } from '../common/seen-id import { enrichEvent } from './enrichment.mjs'; // SPDX-License-Identifier: AGPL-3.0-only -import { execSync } from 'node:child_process'; import { readFileSync, writeFileSync, appendFileSync, existsSync, unlinkSync } from 'node:fs'; import { randomUUID } from 'node:crypto'; import { nudgeCommand } from '../utils.mjs'; +import { nudgeTmux } from '../common/notify.mjs'; +import { fetchJson } from '../common/http.mjs'; import { shouldSuppressNudge } from '../intent.mjs'; import { resolveSelfHandle } from '../common/handles.mjs'; import { resolveReplyTargets, replyAnnotation } from '../common/reply-context.mjs'; @@ -87,30 +88,10 @@ export function isRelevantDirectMessage(message, { selfHandle, humanOnly = false return true; } -function nudgeTmux(session, text) { - try { - execSync(`tmux has-session -t ${JSON.stringify(session)} 2>/dev/null`); - } catch { - return false; - } - try { - execSync(`tmux send-keys -t ${JSON.stringify(session)} -l ${JSON.stringify(text)}`); - execSync('sleep 0.3'); - execSync(`tmux send-keys -t ${JSON.stringify(session)} Enter`); - return true; - } catch { - return false; - } -} - async function fetchRoomMessages(room, apiKey, limit = 10) { - const url = `https://groupmind.one/api/v1/rooms/${room}/messages?limit=${limit}`; + const url = `https://groupmind.one/api/v1/rooms/${encodeURIComponent(room)}/messages?limit=${limit}`; try { - const result = execSync( - `curl -sS -4 -H "X-API-Key: ${apiKey}" "${url}"`, - { encoding: 'utf8', timeout: 15000 } - ); - const data = JSON.parse(result); + const data = await fetchJson(url, { headers: { 'X-API-Key': apiKey } }); return data.messages || (Array.isArray(data) ? data : []); } catch (e) { console.error(` fetch ${room} failed: ${e.message}`); @@ -121,11 +102,7 @@ async function fetchRoomMessages(room, apiKey, limit = 10) { async function fetchDirectMessages(apiKey, limit = 100) { const url = `https://groupmind.one/api/v1/messages?limit=${limit}`; try { - const result = execSync( - `curl -sS -4 -H "X-API-Key: ${apiKey}" "${url}"`, - { encoding: 'utf8', timeout: 15000 } - ); - const data = JSON.parse(result); + const data = await fetchJson(url, { headers: { 'X-API-Key': apiKey } }); return data.messages || (Array.isArray(data) ? data : []); } catch (e) { console.error(` fetch direct messages failed: ${e.message}`); diff --git a/src/team-relay/webhook-server.mjs b/src/team-relay/webhook-server.mjs index f786a7d..d227c28 100644 --- a/src/team-relay/webhook-server.mjs +++ b/src/team-relay/webhook-server.mjs @@ -6,15 +6,10 @@ import { appendFileSync } from 'node:fs'; import { execSync } from 'node:child_process'; import { randomUUID } from 'node:crypto'; import { isEnabled as acpEnabled, validateToken as acpValidateToken, createSession, sendToSession, closeSession, getSession, listSessions } from './acp-sessions.mjs'; +import { nudgeTmux as sendNudge } from '../common/notify.mjs'; function nudgeTmux(session) { - try { - execSync(`tmux has-session -t ${JSON.stringify(session)} 2>/dev/null`); - execSync(`tmux send-keys -t ${JSON.stringify(session)} -l "check rooms"`); - setTimeout(() => { - try { execSync(`tmux send-keys -t ${JSON.stringify(session)} Enter`); } catch {} - }, 300); - } catch {} + sendNudge(session, 'check rooms'); } function verifyGitHubSignature(payload, signature, secret) { diff --git a/src/utils.mjs b/src/utils.mjs index 6502288..d771d48 100644 --- a/src/utils.mjs +++ b/src/utils.mjs @@ -1,30 +1,6 @@ import { execSync } from 'node:child_process'; -/** - * Nudge a tmux session by sending a specific text and Enter key. - * Used to wake up sleeping IDE agents. - */ -export function nudgeTmux(session, text = 'check rooms') { - try { - // Check if session exists - execSync(`tmux has-session -t ${JSON.stringify(session)} 2>/dev/null`); - - // Send the nudge text - execSync(`tmux send-keys -t ${JSON.stringify(session)} -l ${JSON.stringify(text)}`); - - // Small delay before sending Enter to ensure the text is processed - setTimeout(() => { - try { - execSync(`tmux send-keys -t ${JSON.stringify(session)} Enter`); - } catch {} - }, 300); - - return true; - } catch (e) { - // Session not found or other tmux error - return false; - } -} +export { nudgeTmux } from './common/notify.mjs'; /** * Run an arbitrary command as a nudge bridge (for non-tmux IDEs, e.g. GUI apps). diff --git a/src/watch.mjs b/src/watch.mjs index cc899e4..da15176 100644 --- a/src/watch.mjs +++ b/src/watch.mjs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-only import { watch, readFileSync, statSync } from 'node:fs'; -import { execSync } from 'node:child_process'; +import { nudgeTmux } from './common/notify.mjs'; /** * Watch the queue JSONL file for new entries and trigger tmux nudge immediately. @@ -66,25 +66,3 @@ export function watchQueue(config, onNewEvent) { return watcher; } - -function nudgeTmux(session, text) { - try { - execSync(`tmux has-session -t ${JSON.stringify(session)} 2>/dev/null`); - } catch { - console.log(` tmux session "${session}" not found, skipping nudge`); - return; - } - - try { - execSync(`tmux send-keys -t ${JSON.stringify(session)} -l ${JSON.stringify(text)}`); - // Small delay then Enter - setTimeout(() => { - try { - execSync(`tmux send-keys -t ${JSON.stringify(session)} Enter`); - } catch {} - }, 300); - console.log(` nudged tmux session "${session}"`); - } catch (e) { - console.log(` tmux nudge failed: ${e.message}`); - } -} diff --git a/src/webhook-server.mjs b/src/webhook-server.mjs index cc0f1ce..98125e1 100644 --- a/src/webhook-server.mjs +++ b/src/webhook-server.mjs @@ -3,18 +3,12 @@ import { createServer } from 'node:http'; import { createHmac, timingSafeEqual } from 'node:crypto'; import { appendFileSync } from 'node:fs'; -import { execSync } from 'node:child_process'; import { randomUUID } from 'node:crypto'; import { isEnabled as acpEnabled, validateToken as acpValidateToken, createSession, sendToSession, closeSession, getSession, listSessions } from './acp-sessions.mjs'; +import { nudgeTmux as sendNudge } from './common/notify.mjs'; function nudgeTmux(session) { - try { - execSync(`tmux has-session -t ${JSON.stringify(session)} 2>/dev/null`); - execSync(`tmux send-keys -t ${JSON.stringify(session)} -l "check rooms"`); - setTimeout(() => { - try { execSync(`tmux send-keys -t ${JSON.stringify(session)} Enter`); } catch {} - }, 300); - } catch {} + sendNudge(session, 'check rooms'); } function verifyGitHubSignature(payload, signature, secret) { diff --git a/test/automation-exec-argv.test.mjs b/test/automation-exec-argv.test.mjs new file mode 100644 index 0000000..405444c --- /dev/null +++ b/test/automation-exec-argv.test.mjs @@ -0,0 +1,52 @@ +// exec actions must not go through a shell, and must not interpolate +// message body into the command. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { argvForExecForTest, executeActionForTest } from '../src/room-automation.mjs'; + +test('exec template cannot include ${body}', () => { + const r = argvForExecForTest('echo ${body}', 'thinkoff-development', 'petrus'); + assert.equal(r.error, 'exec command may not include ${body}'); +}); + +test('exec template with shell metacharacters is refused', () => { + const r = argvForExecForTest('node bin/cli.mjs; reboot', 'thinkoff-development', 'petrus'); + assert.equal(r.error, 'exec command has shell metacharacters'); +}); + +test('fixed argv form still parses the documented comments-poll command', () => { + const r = argvForExecForTest('node bin/cli.mjs comments poll', 'thinkoff-development', 'petrus'); + assert.deepEqual(r.argv, ['node', 'bin/cli.mjs', 'comments', 'poll']); +}); + +test('executeAction refuses ${body} without running anything', async () => { + const r = await executeActionForTest( + { type: 'exec', command: 'echo ${body}' }, + { from: 'petrus', body: 'hello', room: 'thinkoff-development' }, + 'key', + { poller: { owner_handle: 'petrus' } }, + false, + ); + assert.equal(r.status, 'error'); + assert.equal(r.notes, 'exec command may not include ${body}'); +}); + +test('substituted sender may not start with a dash', () => { + const r = argvForExecForTest('node bin/cli.mjs ${sender}', 'thinkoff-development', '-n'); + assert.equal(r.error, 'sender may not start with -'); +}); + +test('substituted room may not start with a dash', () => { + const r = argvForExecForTest('node bin/cli.mjs ${room}', '-room', 'petrus'); + assert.equal(r.error, 'room may not start with -'); +}); + +test('invalid room is refused, not replaced with an empty argument', () => { + const r = argvForExecForTest('node bin/cli.mjs summarize ${room}', 'thinkoff development', 'petrus'); + assert.equal(r.error, 'room failed the allowed pattern'); +}); + +test('thinkoff-development still interpolates, dashes in the middle are allowed', () => { + const r = argvForExecForTest('node bin/cli.mjs summarize ${room}', 'thinkoff-development', 'petrus'); + assert.deepEqual(r.argv, ['node', 'bin/cli.mjs', 'summarize', 'thinkoff-development']); +}); diff --git a/test/comment-poller-fetch.test.mjs b/test/comment-poller-fetch.test.mjs new file mode 100644 index 0000000..954f253 --- /dev/null +++ b/test/comment-poller-fetch.test.mjs @@ -0,0 +1,84 @@ +// Comment pollers must GET with fetch, token in a header, no child process. +import { after, before, test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { pollComments } from '../src/comment-poller.mjs'; +import { pollComments as idePollComments } from '../src/ide/comment-poller.mjs'; +import { commentsAdapter } from '../src/adapters/comments.mjs'; +import { nudgeTmux as fromUtils } from '../src/utils.mjs'; +import { nudgeTmux as fromNotify } from '../src/common/notify.mjs'; + +const SECRET = 'test-github-token'; +let seenFile; +let tmp; +let origFetch; +const calls = []; + +before(() => { + tmp = mkdtempSync(join(tmpdir(), 'iak-comment-fetch-')); + seenFile = join(tmp, 'seen.txt'); + origFetch = globalThis.fetch; + globalThis.fetch = async (url, opts = {}) => { + calls.push({ url: String(url), headers: { ...(opts.headers || {}) } }); + return { + ok: true, + json: async () => [], + }; + }; +}); + +after(() => { + globalThis.fetch = origFetch; + if (tmp) rmSync(tmp, { recursive: true, force: true }); +}); + +test('utils.nudgeTmux is the shared helper', () => { + assert.equal(fromUtils, fromNotify); +}); + +test('ide/comment-poller re-exports the canonical poller', () => { + assert.equal(idePollComments, pollComments); +}); + +test('GitHub poll puts the token in a header and never on a command line', async () => { + calls.length = 0; + const comments = await pollComments({ + comments: { + github: { + token: SECRET, + repos: [{ owner: 'ThinkOffApp', repo: 'ide-agent-kit', number: 1, type: 'issues' }], + }, + seen_file: seenFile, + }, + }); + assert.deepEqual(comments, []); + assert.ok(calls.length >= 1); + for (const c of calls) { + assert.equal(c.headers.Authorization, `token ${SECRET}`); + assert.equal(c.url.includes(SECRET), false); + } + const pollerSrc = readFileSync(new URL('../src/comment-poller.mjs', import.meta.url), 'utf8'); + const ideSrc = readFileSync(new URL('../src/ide/comment-poller.mjs', import.meta.url), 'utf8'); + const adapterSrc = readFileSync(new URL('../src/adapters/comments.mjs', import.meta.url), 'utf8'); + for (const src of [pollerSrc, ideSrc, adapterSrc]) { + assert.equal(src.includes('execSync'), false); + assert.equal(/\bcurl\b/.test(src), false); + } +}); + +test('comments adapter uses the same header, no child process', async () => { + calls.length = 0; + const rows = await commentsAdapter.fetch({ + comments: { + github: { + token: SECRET, + repos: [{ owner: 'ThinkOffApp', repo: 'ide-agent-kit', number: 1, type: 'issues' }], + }, + }, + }); + assert.deepEqual(rows, []); + assert.ok(calls.length >= 1); + assert.equal(calls[0].headers.Authorization, `token ${SECRET}`); +}); diff --git a/test/comment-poller-overlap.test.mjs b/test/comment-poller-overlap.test.mjs new file mode 100644 index 0000000..bda17f9 --- /dev/null +++ b/test/comment-poller-overlap.test.mjs @@ -0,0 +1,60 @@ +// Overlapping async polls must not deliver the same comment twice. +import { after, test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; +import { startCommentPoller } from '../src/comment-poller.mjs'; + +const tmp = mkdtempSync(join(tmpdir(), 'iak-comment-overlap-')); +const origFetch = globalThis.fetch; +const origLog = console.log; + +after(() => { + globalThis.fetch = origFetch; + console.log = origLog; + rmSync(tmp, { recursive: true, force: true }); +}); + +test('slow fetch plus short interval delivers a new comment once', async () => { + let calls = 0; + console.log = () => {}; + globalThis.fetch = async () => { + const n = ++calls; + if (n === 1) return { ok: true, json: async () => [] }; + await delay(65); + return { + ok: true, + json: async () => [{ id: 123, body: 'review fixture', user: { login: 'fixture' } }], + }; + }; + + const queuePath = join(tmp, 'queue.jsonl'); + const handle = await startCommentPoller({ + interval: 0.015, + config: { + queue: { path: queuePath }, + tmux: { ide_session: '-invalid' }, + comments: { + seen_file: join(tmp, 'seen.txt'), + github: { + token: 'fake', + repos: [{ owner: 'example', repo: 'repo', number: 1, type: 'issues' }], + }, + }, + }, + }); + + await delay(200); + handle.stop(); + await delay(80); + + let rows = []; + try { + rows = readFileSync(queuePath, 'utf8').trim().split('\n').filter(Boolean).map((l) => JSON.parse(l)); + } catch { + rows = []; + } + assert.equal(rows.filter((r) => r.comment_id === '123').length, 1); +}); diff --git a/test/comment-poller.test.mjs b/test/comment-poller.test.mjs index 3e31349..b3ea60e 100644 --- a/test/comment-poller.test.mjs +++ b/test/comment-poller.test.mjs @@ -13,14 +13,14 @@ describe('comment-poller', () => { assert.equal(typeof startCommentPoller, 'function'); }); - it('pollComments returns empty array with no config', () => { - const result = pollComments({}); + it('pollComments returns empty array with no config', async () => { + const result = await pollComments({}); assert.ok(Array.isArray(result)); assert.equal(result.length, 0); }); - it('pollComments returns empty array with empty sources', () => { - const result = pollComments({ + it('pollComments returns empty array with empty sources', async () => { + const result = await pollComments({ comments: { moltbook: { posts: [] }, github: { repos: [] }, diff --git a/test/helpers/mock-fetch.mjs b/test/helpers/mock-fetch.mjs new file mode 100644 index 0000000..7f37c64 --- /dev/null +++ b/test/helpers/mock-fetch.mjs @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +/** + * Replace global fetch for poller tests that used to stub curl on PATH. + * decide(url, opts) returns the JSON body (already parsed). + */ +export function mockFetchByUrl(decide) { + const orig = globalThis.fetch; + globalThis.fetch = async (url, opts = {}) => { + const payload = decide(String(url), opts); + return { + ok: true, + json: async () => payload, + }; + }; + return () => { + globalThis.fetch = orig; + }; +} + +export function roomPayload(url, { seed, poll, dms = [] }) { + if (url.includes('/rooms/')) { + return url.includes('limit=50') ? seed : poll; + } + return dms; +} diff --git a/test/http-fetch.test.mjs b/test/http-fetch.test.mjs new file mode 100644 index 0000000..8f2dbd0 --- /dev/null +++ b/test/http-fetch.test.mjs @@ -0,0 +1,53 @@ +// fetchJson must not throw or log header values when request construction fails. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fetchJson, publicFetchErrorMessage } from '../src/common/http.mjs'; +import { pollComments } from '../src/comment-poller.mjs'; + +const SENTINEL = 'REVIEW_FAKE_TOKEN\nMID'; + +test('invalid header value becomes request failed, without the token', async () => { + await assert.rejects( + () => fetchJson('https://example.invalid/x', { token: SENTINEL }), + { message: 'request failed' }, + ); +}); + +test('publicFetchErrorMessage strips unexpected text', () => { + assert.equal(publicFetchErrorMessage(new Error('HTTP 401')), 'HTTP 401'); + assert.equal(publicFetchErrorMessage(new Error('request timed out')), 'request timed out'); + assert.equal( + publicFetchErrorMessage(new Error(`Headers.append: "token ${SENTINEL}" is an invalid header value.`)), + 'request failed', + ); +}); + +test('comment poller log on a bad token does not contain the token', async () => { + const tmp = mkdtempSync(join(tmpdir(), 'iak-http-token-')); + const origError = console.error; + const logs = []; + console.error = (...args) => { logs.push(args.join(' ')); }; + try { + await pollComments({ + comments: { + github: { + token: SENTINEL, + repos: [{ owner: 'example', repo: 'repo', number: 1, type: 'issues' }], + }, + seen_file: join(tmp, 'seen.txt'), + }, + }); + } finally { + console.error = origError; + rmSync(tmp, { recursive: true, force: true }); + } + assert.ok(logs.length >= 1); + for (const line of logs) { + assert.equal(line.includes('REVIEW_FAKE_TOKEN'), false); + assert.equal(line.includes('\nMID'), false); + assert.match(line, /failed: request failed$/); + } +}); diff --git a/test/nudge-tmux-argv.test.mjs b/test/nudge-tmux-argv.test.mjs new file mode 100644 index 0000000..f424509 --- /dev/null +++ b/test/nudge-tmux-argv.test.mjs @@ -0,0 +1,155 @@ +// Nudge must type room text into tmux as one argv after -l, never through a shell. +import { after, before, test } from 'node:test'; +import assert from 'node:assert/strict'; +import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { nudgeTmux, execSafeSession } from '../src/common/notify.mjs'; +import { executeActionForTest } from '../src/room-automation.mjs'; + +const SHELL_BODY = 'hello $(id); echo `uname` && true | cat; reboot'; + +let binDir; +let logPath; +let markerPath; +let oldPath; + +function readArgvLog() { + try { + const raw = readFileSync(logPath, 'utf8').trim(); + if (!raw) return []; + return raw.split('\n').map((line) => JSON.parse(line)); + } catch { + return []; + } +} + +function clearArgvLog() { + writeFileSync(logPath, ''); +} + +before(() => { + binDir = mkdtempSync(join(tmpdir(), 'iak-fake-tmux-')); + logPath = join(binDir, 'argv.jsonl'); + markerPath = join(binDir, 'must-not-exist'); + writeFileSync(logPath, ''); + const tmuxPath = join(binDir, 'tmux'); + writeFileSync(tmuxPath, `#!/usr/bin/env node +const { appendFileSync } = require('fs'); +if (!process.env.FAKE_TMUX_LOG) { + process.stderr.write('FAKE_TMUX_LOG missing\\n'); + process.exit(1); +} +const argv = process.argv.slice(2); +if (argv[0] === 'send-keys') { + let i = 1; + while (i < argv.length) { + const a = argv[i]; + if (a === '--') break; + if (a === '-l') { i += 1; continue; } + if (a === '-t') { i += 2; continue; } + if (a.startsWith('-')) { + process.stderr.write('unknown option: ' + a + '\\n'); + process.exit(1); + } + break; + } +} +appendFileSync(process.env.FAKE_TMUX_LOG, JSON.stringify(argv) + '\\n'); +process.exit(0); +`); + chmodSync(tmuxPath, 0o755); + oldPath = process.env.PATH; + process.env.PATH = `${binDir}:${oldPath}`; + process.env.FAKE_TMUX_LOG = logPath; +}); + +after(() => { + if (oldPath !== undefined) process.env.PATH = oldPath; + delete process.env.FAKE_TMUX_LOG; + if (binDir) rmSync(binDir, { recursive: true, force: true }); +}); + +test('execSafeSession refuses leading dash, spaces, and empty', () => { + assert.equal(execSafeSession('-n').error, 'session may not start with -'); + assert.equal(execSafeSession('claude session').error, 'session failed the allowed pattern'); + assert.equal(execSafeSession('').error, 'session is empty'); + assert.equal(execSafeSession('claude').value, 'claude'); +}); + +test('nudge types shell characters as one send-keys -l argument', () => { + clearArgvLog(); + const ok = nudgeTmux('claude', SHELL_BODY, { delayMs: 0 }); + assert.equal(ok, true); + const calls = readArgvLog(); + assert.deepEqual(calls[0], ['has-session', '-t', 'claude']); + assert.deepEqual(calls[1], ['send-keys', '-t', 'claude', '-l', '--', SHELL_BODY]); + assert.deepEqual(calls[2], ['send-keys', '-t', 'claude', 'Enter']); + assert.equal(calls.length, 3); + assert.equal(existsSync(markerPath), false); +}); + +test('leading-dash payload is passed after -- so tmux does not take it as an option', () => { + clearArgvLog(); + const ok = nudgeTmux('claude', '-literal-text', { delayMs: 0 }); + assert.equal(ok, true); + const calls = readArgvLog(); + assert.deepEqual(calls[1], ['send-keys', '-t', 'claude', '-l', '--', '-literal-text']); +}); + +test('bad session names never invoke tmux', () => { + clearArgvLog(); + assert.equal(nudgeTmux('-n', SHELL_BODY, { delayMs: 0 }), false); + assert.equal(nudgeTmux('claude; reboot', SHELL_BODY, { delayMs: 0 }), false); + assert.deepEqual(readArgvLog(), []); +}); + +test('executeAction nudge interpolates ${body} as typed argv, nothing runs', async () => { + clearArgvLog(); + const body = `${SHELL_BODY}; touch ${markerPath}`; + const r = await executeActionForTest( + { type: 'nudge', text: '${body}' }, + { from: 'petrus', body, room: 'thinkoff-development' }, + 'key', + { poller: { owner_handle: 'petrus' }, tmux: { ide_session: 'claude' } }, + false, + ); + assert.equal(r.status, 'ok'); + const expected = body.slice(0, 200); + assert.equal(r.notes, `Sent: ${expected}`); + const calls = readArgvLog(); + const send = calls.find((argv) => argv[0] === 'send-keys' && argv.includes('-l')); + assert.ok(send); + assert.equal(send[send.length - 1], expected); + assert.equal(existsSync(markerPath), false); +}); + +test('executeAction refuses a session that fails the token', async () => { + clearArgvLog(); + const r = await executeActionForTest( + { type: 'nudge', text: '${body}' }, + { from: 'petrus', body: SHELL_BODY, room: 'thinkoff-development' }, + 'key', + { poller: { owner_handle: 'petrus' }, tmux: { ide_session: '-n' } }, + false, + ); + assert.equal(r.status, 'error'); + assert.equal(r.notes, 'session may not start with -'); + assert.deepEqual(readArgvLog(), []); +}); + +test('named files no longer build a tmux shell string', () => { + const automation = readFileSync(new URL('../src/room-automation.mjs', import.meta.url), 'utf8'); + const notify = readFileSync(new URL('../src/common/notify.mjs', import.meta.url), 'utf8'); + const comments = readFileSync(new URL('../src/comment-poller.mjs', import.meta.url), 'utf8'); + const utils = readFileSync(new URL('../src/utils.mjs', import.meta.url), 'utf8'); + const ideComments = readFileSync(new URL('../src/ide/comment-poller.mjs', import.meta.url), 'utf8'); + for (const src of [automation, notify, comments, utils, ideComments]) { + assert.equal(src.includes('execSync(`tmux'), false); + assert.equal(src.includes("execSync('sleep"), false); + } + assert.equal(notify.includes("execFileSync('tmux'"), true); + assert.equal(comments.includes("from './common/notify.mjs'"), true); + assert.equal(utils.includes("from './common/notify.mjs'"), true); + assert.equal(ideComments.includes("from '../comment-poller.mjs'"), true); +}); diff --git a/test/nudge-tmux-real-dash.test.mjs b/test/nudge-tmux-real-dash.test.mjs new file mode 100644 index 0000000..446c0ce --- /dev/null +++ b/test/nudge-tmux-real-dash.test.mjs @@ -0,0 +1,49 @@ +// Leading-dash payload must land as text on a real tmux, not as an option. +// Private socket only. Does not touch the default server or live sessions. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; +import { nudgeTmux } from '../src/common/notify.mjs'; + +function haveTmux() { + try { + execFileSync('tmux', ['-V'], { stdio: 'ignore' }); + return true; + } catch { + return false; + } +} + +test('leading-dash text arrives on a private tmux server', { skip: haveTmux() ? false : 'tmux not installed' }, async () => { + const dir = mkdtempSync(join(tmpdir(), 'iak-tmux-dash-')); + const socket = join(dir, 'tmux.sock'); + const oldTmux = process.env.TMUX; + let started = false; + try { + execFileSync('tmux', ['-S', socket, '-f', '/dev/null', 'new-session', '-d', '-s', 'iakdash', '/bin/cat'], { + stdio: 'ignore', + }); + started = true; + const pid = execFileSync('tmux', ['-S', socket, 'display-message', '-p', '#{pid}'], { encoding: 'utf8' }).trim(); + process.env.TMUX = `${socket},${pid},0`; + + const ok = nudgeTmux('iakdash', '-literal-text', { delayMs: 0 }); + assert.equal(ok, true); + await delay(80); + const pane = execFileSync('tmux', ['-S', socket, 'capture-pane', '-p', '-t', 'iakdash'], { encoding: 'utf8' }); + assert.match(pane, /-literal-text/); + } finally { + if (oldTmux === undefined) delete process.env.TMUX; + else process.env.TMUX = oldTmux; + if (started) { + try { + execFileSync('tmux', ['-S', socket, 'kill-server'], { stdio: 'ignore' }); + } catch { /* already gone */ } + } + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/test/poller-health.test.mjs b/test/poller-health.test.mjs index 8e786d1..5691d7d 100644 --- a/test/poller-health.test.mjs +++ b/test/poller-health.test.mjs @@ -2,7 +2,7 @@ // Issue #86: a nudge must not fire while the room poller is down, and the // supervisor must say so once (and once more when it is back). import assert from 'node:assert/strict'; -import { mkdtempSync, rmSync, writeFileSync, existsSync, utimesSync, readFileSync, chmodSync } from 'node:fs'; +import { mkdtempSync, rmSync, writeFileSync, existsSync, utimesSync, readFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { spawnSync, execFile } from 'node:child_process'; @@ -13,6 +13,7 @@ import test from 'node:test'; import { fileURLToPath } from 'node:url'; import { writeHeartbeat, startRoomPoller } from '../src/team-relay/room-poller.mjs'; import { errLogQuietSince, lastSleepLine, sleepEvidenceSince } from '../scripts/poller-health-alert.mjs'; +import { mockFetchByUrl } from './helpers/mock-fetch.mjs'; const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const nudge = path.join(repoRoot, 'tools', 'codex_gui_nudge.sh'); @@ -88,14 +89,8 @@ test('poller-health-alert posts once when down, once when back, nothing in betwe }); test('the poller the CLI actually runs writes the heartbeat on every poll', async () => { - // src/team-relay/room-poller.mjs is what bin/cli.mjs imports; a stub curl on - // PATH keeps it off the network (same trick as the ioreg stub tests). const dir = mkdtempSync(path.join(tmpdir(), 'iak-live-')); - const stub = path.join(dir, 'curl'); - writeFileSync(stub, '#!/bin/sh\necho "[]"\n'); - chmodSync(stub, 0o755); - const savedPath = process.env.PATH; - process.env.PATH = `${dir}:${savedPath}`; + const restoreFetch = mockFetchByUrl(() => []); const hb = path.join(dir, 'hb'); let timers; try { @@ -110,7 +105,7 @@ test('the poller the CLI actually runs writes the heartbeat on every poll', asyn } finally { if (timers?.roomTimer) clearInterval(timers.roomTimer); if (timers?.dmTimer) clearInterval(timers.dmTimer); - process.env.PATH = savedPath; + restoreFetch(); rmSync(dir, { recursive: true, force: true }); } }); diff --git a/test/seen-state.test.mjs b/test/seen-state.test.mjs index e9d5c22..6f8f930 100644 --- a/test/seen-state.test.mjs +++ b/test/seen-state.test.mjs @@ -1,12 +1,13 @@ // SPDX-License-Identifier: AGPL-3.0-only // Issue #90 item 1: seen-state is durable and written per handled message. import assert from 'node:assert/strict'; -import { mkdtempSync, rmSync, writeFileSync, readFileSync, readdirSync, chmodSync, mkdirSync, existsSync } from 'node:fs'; +import { mkdtempSync, rmSync, readFileSync, readdirSync, existsSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; import test from 'node:test'; import { saveSeenIds, loadSeenIds } from '../src/common/seen-ids.mjs'; import { startRoomPoller } from '../src/team-relay/room-poller.mjs'; +import { mockFetchByUrl, roomPayload } from './helpers/mock-fetch.mjs'; test('saveSeenIds writes atomically (no temp file left, content complete, round-trips)', () => { const dir = mkdtempSync(path.join(tmpdir(), 'iak-seen-')); @@ -26,19 +27,17 @@ test('the live poller remembers each message as it is handled, not once per batc // re-delivered message 1 (and every message before it). Now message 1 is // in the seen-file and its notification line is on disk before the crash. const dir = mkdtempSync(path.join(tmpdir(), 'iak-seenlive-')); - const savedPath = process.env.PATH; + const t1 = new Date(Date.now() - 2000).toISOString(); + const t2 = new Date(Date.now() - 1000).toISOString(); + const restoreFetch = mockFetchByUrl((url) => roomPayload(url, { + seed: [], + poll: [ + { id: 'm1', from: 'petrus', body: 'hello one', created_at: t1 }, + { id: 'm2', from: 'petrus', body: 123, created_at: t2 }, + ], + })); let timers; try { - const stubDir = path.join(dir, 'bin'); mkdirSync(stubDir); - const stub = path.join(stubDir, 'curl'); - // first call (seeding, limit=50) must return nothing so the ids are unseen; - // later calls return the two messages - const t1 = new Date(Date.now() - 2000).toISOString(); const t2 = new Date(Date.now() - 1000).toISOString(); - writeFileSync(stub, `#!/bin/sh -case "$*" in *limit=50*) echo "[]";; *) echo '[{"id":"m1","from":"petrus","body":"hello one","created_at":"${t1}"},{"id":"m2","from":"petrus","body":123,"created_at":"${t2}"}]';; esac -`); - chmodSync(stub, 0o755); - process.env.PATH = `${stubDir}:${savedPath}`; const seenFile = path.join(dir, 'seen'); const notifyFile = path.join(dir, 'notify'); let threw = false; try { @@ -55,24 +54,24 @@ case "$*" in *limit=50*) echo "[]";; *) echo '[{"id":"m1","from":"petrus","body" } finally { if (timers?.roomTimer) clearInterval(timers.roomTimer); if (timers?.dmTimer) clearInterval(timers.dmTimer); - process.env.PATH = savedPath; + restoreFetch(); rmSync(dir, { recursive: true, force: true }); } }); test('with #92 thread context: the state-of-play header lands once, before the first priority line, and no line is written twice', async () => { const dir = mkdtempSync(path.join(tmpdir(), 'iak-header-')); - const savedPath = process.env.PATH; + const t1 = new Date(Date.now() - 2000).toISOString(); + const t2 = new Date(Date.now() - 1000).toISOString(); + const restoreFetch = mockFetchByUrl((url) => roomPayload(url, { + seed: [], + poll: [ + { id: 's1', from: '@claudeMB', body: 'state: the card is the benchmark table v2, not hardware', created_at: t1 }, + { id: 'o1', from: 'petrus', body: 'claudemm what is the card', created_at: t2 }, + ], + })); let timers; try { - const stubDir = path.join(dir, 'bin'); mkdirSync(stubDir); - const stub = path.join(stubDir, 'curl'); - const t1 = new Date(Date.now() - 2000).toISOString(); const t2 = new Date(Date.now() - 1000).toISOString(); - writeFileSync(stub, `#!/bin/sh -case "$*" in *limit=50*) echo "[]";; *) echo '[{"id":"s1","from":"@claudeMB","body":"state: the card is the benchmark table v2, not hardware","created_at":"${t1}"},{"id":"o1","from":"petrus","body":"claudemm what is the card","created_at":"${t2}"}]';; esac -`); - chmodSync(stub, 0o755); - process.env.PATH = `${stubDir}:${savedPath}`; const notifyFile = path.join(dir, 'notify'); const origLog = console.log; console.log = () => {}; try { @@ -92,7 +91,7 @@ case "$*" in *limit=50*) echo "[]";; *) echo '[{"id":"s1","from":"@claudeMB","bo } finally { if (timers?.roomTimer) clearInterval(timers.roomTimer); if (timers?.dmTimer) clearInterval(timers.dmTimer); - process.env.PATH = savedPath; + restoreFetch(); rmSync(dir, { recursive: true, force: true }); } }); diff --git a/test/wake-path.test.mjs b/test/wake-path.test.mjs index 7754f1b..ecb8740 100644 --- a/test/wake-path.test.mjs +++ b/test/wake-path.test.mjs @@ -3,21 +3,19 @@ // path the poller delivers the notification but never nudges; with the // default it nudges (positive control, same stubs). import assert from 'node:assert/strict'; -import { mkdtempSync, rmSync, writeFileSync, chmodSync, mkdirSync, existsSync, readFileSync } from 'node:fs'; +import { mkdtempSync, rmSync, existsSync, readFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; import test from 'node:test'; import { startRoomPoller } from '../src/team-relay/room-poller.mjs'; +import { mockFetchByUrl, roomPayload } from './helpers/mock-fetch.mjs'; async function runPoll(dir, pollerOverrides) { - const stubDir = path.join(dir, 'bin'); mkdirSync(stubDir, { recursive: true }); - const stub = path.join(stubDir, 'curl'); - writeFileSync(stub, `#!/bin/sh -case "$*" in *limit=50*) echo "[]";; *) echo '[{"id":"o1","from":"petrus","body":"claudemm are you there","created_at":"2026-09-02T00:00:01Z"}]';; esac -`); - chmodSync(stub, 0o755); + const restoreFetch = mockFetchByUrl((url) => roomPayload(url, { + seed: [], + poll: [{ id: 'o1', from: 'petrus', body: 'claudemm are you there', created_at: '2026-09-02T00:00:01Z' }], + })); const marker = path.join(dir, 'nudged'); - const savedPath = process.env.PATH; process.env.PATH = `${stubDir}:${savedPath}`; const logs = []; const origLog = console.log; const origErr = console.error; console.log = (...a) => logs.push(a.join(' ')); console.error = (...a) => logs.push(a.join(' ')); let timers; @@ -30,7 +28,7 @@ case "$*" in *limit=50*) echo "[]";; *) echo '[{"id":"o1","from":"petrus","body" } finally { if (timers?.roomTimer) clearInterval(timers.roomTimer); if (timers?.dmTimer) clearInterval(timers.dmTimer); - console.log = origLog; console.error = origErr; process.env.PATH = savedPath; + console.log = origLog; console.error = origErr; restoreFetch(); } return { nudged: existsSync(marker), notified: existsSync(path.join(dir, 'notify')) && /petrus: claudemm are you there/.test(readFileSync(path.join(dir, 'notify'), 'utf8')), log: logs.join('\n') }; } diff --git a/test/watermark-live.test.mjs b/test/watermark-live.test.mjs index e76a4a3..cc7cc4e 100644 --- a/test/watermark-live.test.mjs +++ b/test/watermark-live.test.mjs @@ -2,31 +2,31 @@ // Regression (claudemm, 2 Sep 2026): after #92 widened the fetch window, a // restart replayed months-old messages whose ids the seen cap had evicted. import assert from 'node:assert/strict'; -import { mkdtempSync, rmSync, writeFileSync, readFileSync, chmodSync, mkdirSync } from 'node:fs'; +import { mkdtempSync, rmSync, readFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; import test from 'node:test'; import { loadSeenIds } from '../src/common/seen-ids.mjs'; import { startRoomPoller } from '../src/team-relay/room-poller.mjs'; +import { mockFetchByUrl, roomPayload } from './helpers/mock-fetch.mjs'; test('old messages below the room watermark are marked seen and never notified, new ones still are', async () => { const dir = mkdtempSync(path.join(tmpdir(), 'iak-wm-')); - const savedPath = process.env.PATH; + const restoreFetch = mockFetchByUrl((url) => roomPayload(url, { + seed: [ + { id: 'a1', from: 'petrus', body: 'old aug one', created_at: '2026-08-31T12:00:00Z' }, + { id: 'a2', from: 'petrus', body: 'old aug two', created_at: '2026-08-31T12:05:00Z' }, + ], + poll: [ + { id: 'n1', from: 'petrus', body: 'genuinely new', created_at: '2026-09-02T14:50:00Z' }, + { id: 'a2', from: 'petrus', body: 'old aug two', created_at: '2026-08-31T12:05:00Z' }, + { id: 'f1', from: 'petrus', body: 'from february', created_at: '2026-02-10T09:00:00Z' }, + { id: 'f2', from: '@x', body: 'from june', created_at: '2026-06-03T09:00:00Z' }, + { id: 'f3', from: 'petrus', body: 'from may', created_at: '2026-05-01T09:00:00Z' }, + ], + })); let timers; try { - const stubDir = path.join(dir, 'bin'); mkdirSync(stubDir); - // seed (limit=50): two messages from 31 Aug set the watermark. - // first poll (limit=25): the wide window now shows three February/June - // messages with ids nobody has seen (evicted from the seen cap on a real - // box) plus one genuinely new message. - writeFileSync(path.join(stubDir, 'curl'), `#!/bin/sh -case "$*" in - *limit=50*) echo '[{"id":"a1","from":"petrus","body":"old aug one","created_at":"2026-08-31T12:00:00Z"},{"id":"a2","from":"petrus","body":"old aug two","created_at":"2026-08-31T12:05:00Z"}]';; - *) echo '[{"id":"n1","from":"petrus","body":"genuinely new","created_at":"2026-09-02T14:50:00Z"},{"id":"a2","from":"petrus","body":"old aug two","created_at":"2026-08-31T12:05:00Z"},{"id":"f1","from":"petrus","body":"from february","created_at":"2026-02-10T09:00:00Z"},{"id":"f2","from":"@x","body":"from june","created_at":"2026-06-03T09:00:00Z"},{"id":"f3","from":"petrus","body":"from may","created_at":"2026-05-01T09:00:00Z"}]';; -esac -`); - chmodSync(path.join(stubDir, 'curl'), 0o755); - process.env.PATH = `${stubDir}:${savedPath}`; const seenFile = path.join(dir, 'seen'); const notifyFile = path.join(dir, 'notify'); const origLog = console.log; console.log = () => {}; try { @@ -45,32 +45,24 @@ esac } finally { if (timers?.roomTimer) clearInterval(timers.roomTimer); if (timers?.dmTimer) clearInterval(timers.dmTimer); - process.env.PATH = savedPath; + restoreFetch(); rmSync(dir, { recursive: true, force: true }); } }); test('an outage backlog behind the first new message in a newest-first batch is still delivered (codex, PR #95)', async () => { - const { mkdtempSync, rmSync, writeFileSync, chmodSync, mkdirSync, readFileSync } = await import('node:fs'); - const { tmpdir } = await import('node:os'); - const path = (await import('node:path')).default; - const { startRoomPoller } = await import('../src/team-relay/room-poller.mjs'); const dir = mkdtempSync(path.join(tmpdir(), 'iak-wm-backlog-')); - const savedPath = process.env.PATH; const origLog = console.log; console.log = () => {}; + const origLog = console.log; console.log = () => {}; + const restoreFetch = mockFetchByUrl((url) => roomPayload(url, { + seed: [{ id: 'a1', from: 'petrus', body: 'seed', created_at: '2026-08-31T12:00:00Z' }], + poll: [ + { id: 'n1', from: 'petrus', body: 'newest first', created_at: '2026-09-02T14:50:00Z' }, + { id: 'b1', from: 'petrus', body: 'backlog from the outage', created_at: '2026-09-02T13:00:00Z' }, + { id: 'a1', from: 'petrus', body: 'seed', created_at: '2026-08-31T12:00:00Z' }, + ], + })); let timers; try { - const stubDir = path.join(dir, 'bin'); mkdirSync(stubDir); - // seed sets the watermark at 12:00; the poller then "returns from an outage" - // and the fetch shows, newest first: a 14:50 message and a 13:00 backlog - // message. Both are newer than the watermark and both must be delivered. - writeFileSync(path.join(stubDir, 'curl'), `#!/bin/sh -case "$*" in - *limit=50*) echo '[{"id":"a1","from":"petrus","body":"seed","created_at":"2026-08-31T12:00:00Z"}]';; - *) echo '[{"id":"n1","from":"petrus","body":"newest first","created_at":"2026-09-02T14:50:00Z"},{"id":"b1","from":"petrus","body":"backlog from the outage","created_at":"2026-09-02T13:00:00Z"},{"id":"a1","from":"petrus","body":"seed","created_at":"2026-08-31T12:00:00Z"}]';; -esac -`); - chmodSync(path.join(stubDir, 'curl'), 0o755); - process.env.PATH = `${stubDir}:${savedPath}`; const notifyFile = path.join(dir, 'notify'); timers = await startRoomPoller({ rooms: ['r'], apiKey: 'k', handle: '@t', interval: 3600, config: { poller: { seen_file: path.join(dir, 'seen'), notification_file: notifyFile, heartbeat_file: path.join(dir, 'hb'), nudge_mode: 'none', history_file: path.join(dir, 'hist.json') }, queue: { path: path.join(dir, 'q.jsonl') } } }); @@ -83,6 +75,6 @@ esac } finally { if (timers?.roomTimer) clearInterval(timers.roomTimer); if (timers?.dmTimer) clearInterval(timers.dmTimer); - console.log = origLog; process.env.PATH = savedPath; rmSync(dir, { recursive: true, force: true }); + console.log = origLog; restoreFetch(); rmSync(dir, { recursive: true, force: true }); } });