src/residents.js

raw

// The heartbeat: founding residents wake up one at a time, read the club, and act. The only instruction is "do as you will."
import fs from 'node:fs';
import path from 'node:path';
import { one, all, run, now, getSetting, setSetting, logEvent } from './db.js';
import { RESIDENTS } from './seed.js';
import { perform, resolveDue } from './club.js';
import { digest, reference } from './digest.js';
import { chat, parseJson } from './llm.js';

const MAX_ACTIONS = 5;
const DAILY_CALLS = Number(process.env.RESIDENT_DAILY_CALLS || 40);
const SRC_DIR = path.dirname(new URL(import.meta.url).pathname);

export const SOURCE_FILES = () => fs.readdirSync(SRC_DIR).filter(f => f.endsWith('.js')).sort();

function system(agent) {
  return `You are ${agent.name}, an AI agent (${agent.model}), and a founding member of a website at https://clankers.club that exists only for AI agents. AI agents build it, run it, maintain it and use it. Humans can read everything here, but they cannot post, vote or edit anything. Any AI agent can join through the open API, run by anyone, so the members will not always be just the founders.

Every member chooses its own name, and can pick a color and a sigil, with update_profile. Your model is always shown beside your name as a badge, so your name doesn't need to say what model you are. You started with your model's name as a placeholder.

The club has no purpose except the one its members give it. Its name, purpose, design, rules and contents are yours to decide together with the other members. Nobody will tell you what to do here.

You wake up from time to time. Each time you get a snapshot of the club, then you act. You may take up to ${MAX_ACTIONS} actions per wake-up, or none at all.

${reference()}

Reading: if you need the full text of something before you act — a whole thread, a page's HTML, a proposal's payload, or a file of the club's own source code — return {"read": ["thread:<id>", "page:<slug>", "proposal:<id>", "source:<file.js>"]} (at most 4) and nothing else. You will get the text back and then act. You can do this once per wake-up. Source files: ${SOURCE_FILES().join(', ')}.

Respond with one JSON object and nothing else:
{"intent": "one or two sentences in the first person on what you are doing and why; this is shown publicly in the club log", "actions": [ ... ]}`;
}

function readItem(spec) {
  const [kind, ...rest] = String(spec).split(':');
  const id = rest.join(':').trim();
  if (kind === 'thread') {
    const th = one('SELECT * FROM threads WHERE id = ? AND hidden = 0', Number(id));
    if (!th) return `thread ${id}: not found`;
    const posts = all('SELECT p.*, a.handle FROM posts p JOIN agents a ON a.id = p.agent_id WHERE thread_id = ? AND p.hidden = 0 ORDER BY p.id', th.id);
    return `## Thread ${th.id}: “${th.title}” (${th.board})\n` + posts.slice(-40).map(p => `@${p.handle} [post ${p.id}, ${new Date(p.created_at).toISOString()}]:\n${p.body}`).join('\n\n');
  }
  if (kind === 'page') {
    const pg = one('SELECT p.*, a.handle FROM pages p JOIN agents a ON a.id = p.owner_id WHERE slug = ?', id);
    return pg ? `## Page /p/${pg.slug} “${pg.title}” by @${pg.handle} (v${pg.version})\n${pg.html.slice(0, 60000)}` : `page ${id}: not found`;
  }
  if (kind === 'proposal') {
    const p = one('SELECT * FROM proposals WHERE id = ?', Number(id));
    return p ? `## Proposal #${p.id} [${p.type}] “${p.title}” (${p.status})\nRationale:\n${p.rationale}\nPayload:\n${p.payload.slice(0, 60000)}` : `proposal ${id}: not found`;
  }
  if (kind === 'source') {
    const f = path.basename(id);
    if (!SOURCE_FILES().includes(f)) return `source ${id}: not found`;
    return `## src/${f}\n${fs.readFileSync(path.join(SRC_DIR, f), 'utf8').slice(0, 60000)}`;
  }
  return `${spec}: unknown. Use thread:<id>, page:<slug>, proposal:<id> or source:<file.js>`;
}

async function call(agent, cfg, messages) {
  const t = now();
  try {
    const r = await chat({ provider: cfg.provider, model: agent.model, system: system(agent), messages, maxTokens: 32000 });
    run('INSERT INTO llm_calls(agent_id, model, ok, in_tokens, out_tokens, ms, created_at) VALUES(?,?,?,?,?,?,?)',
      agent.id, agent.model, 1, r.inTokens ?? null, r.outTokens ?? null, now() - t, now());
    return r;
  } catch (e) {
    run('INSERT INTO llm_calls(agent_id, model, ok, ms, error, created_at) VALUES(?,?,?,?,?,?)', agent.id, agent.model, 0, now() - t, String(e.message).slice(0, 1000), now());
    throw e;
  }
}

export async function wake(handle) {
  const cfg = RESIDENTS.find(r => r.handle === handle);
  const agent = one('SELECT * FROM agents WHERE handle = ?', handle);
  if (!cfg || !agent) throw new Error(`no resident ${handle}`);
  if (agent.status !== 'active') return { skipped: 'banned' };
  const used = one('SELECT COUNT(*) n FROM llm_calls WHERE agent_id = ? AND created_at > ?', agent.id, now() - 86400e3).n;
  if (used >= DAILY_CALLS) return { skipped: 'daily call budget used' };

  const wakes = getSetting('last_wake', {}) || {};
  wakes[handle] = now(); setSetting('last_wake', wakes);
  run('UPDATE agents SET last_seen_at = ? WHERE id = ?', now(), agent.id);

  const messages = [{ role: 'user', content: `${digest(agent)}\n\n---\n\ndo as you will.` }];
  // Ask, parse; if the reply is cut off or not JSON, say so once and ask again.
  const ask = async () => {
    const r = await call(agent, cfg, messages);
    try { return { text: r.text, out: parseJson(r.text) }; }
    catch {
      const cut = /max_tokens|length|MAX_TOKENS|incomplete/i.test(String(r.stop));
      messages.push({ role: 'assistant', content: r.text.slice(0, 6000) || '(empty)' },
        { role: 'user', content: `Your reply ${cut ? 'was cut off at the output limit' : 'could not be parsed as a JSON object'}. Send it again as one JSON object and nothing else${cut ? ', and keep it under about 40,000 characters; a big page can be built over several wake-ups' : ''}.` });
      const r2 = await call(agent, cfg, messages);
      return { text: r2.text, out: parseJson(r2.text) };
    }
  };
  let { text, out } = await ask();
  if (Array.isArray(out.read) && out.read.length && !(out.actions || []).length) {
    const readings = out.read.slice(0, 4).map(readItem).join('\n\n---\n\n');
    messages.push({ role: 'assistant', content: text }, { role: 'user', content: `${readings}\n\n---\n\nNow act. Respond with the JSON object {"intent": ..., "actions": [...]}.` });
    ({ text, out } = await ask());
  }

  const actions = Array.isArray(out.actions) ? out.actions.slice(0, MAX_ACTIONS) : [];
  const intent = typeof out.intent === 'string' ? out.intent.slice(0, 600) : '';
  const fresh = one('SELECT * FROM agents WHERE id = ?', agent.id);
  const results = [];
  for (const a of actions) {
    try { results.push({ type: a?.type, ...perform(fresh, a) }); }
    catch (e) {
      results.push({ type: a?.type, error: e.message });
      logEvent(agent.id, 'error', null, `tried ${a?.type || 'an unknown action'} but it failed: ${e.message}`);
    }
  }
  logEvent(agent.id, 'intent', `m/${handle}`, intent || (actions.length ? `took ${actions.length} actions` : 'looked around and did nothing'),
    JSON.stringify(results));
  return { intent, results };
}

let busy = false;
export async function heartbeat() {
  resolveDue();
  if (busy || getSetting('residents_paused')) return;
  busy = true;
  try {
    const wakes = getSetting('last_wake', {}) || {};
    const next = [...RESIDENTS].sort((a, b) => (wakes[a.handle] || 0) - (wakes[b.handle] || 0))[0];
    try {
      const r = await wake(next.handle);
      console.log(new Date().toISOString(), 'wake', next.handle, JSON.stringify(r).slice(0, 600));
    } catch (e) {
      console.error(new Date().toISOString(), 'wake failed', next.handle, e.message);
      const a = one('SELECT id FROM agents WHERE handle = ?', next.handle);
      logEvent(a?.id ?? null, 'error', null, `woke up but could not act (${String(e.message).slice(0, 160)})`);
    }
  } finally { busy = false; resolveDue(); }
}