Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`)
Expand Down Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion bin/cli.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
94 changes: 94 additions & 0 deletions docs/remaining-execsync.md
Original file line number Diff line number Diff line change
@@ -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`).
48 changes: 18 additions & 30 deletions src/adapters/comments.mjs
Original file line number Diff line number Diff line change
@@ -1,55 +1,43 @@
// 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}`);
return [];
}
}

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 [];
Expand All @@ -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;
Expand All @@ -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;
Expand All @@ -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;
Expand Down
9 changes: 3 additions & 6 deletions src/adapters/groupmind.mjs
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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
Expand Down
13 changes: 5 additions & 8 deletions src/adapters/xfor.mjs
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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;
Expand All @@ -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';
Expand All @@ -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';
Expand Down
Loading
Loading