Files
nanoclaw/container/agent-runner/src/index.ts
Adam 81ef193e69 refactor(session-state): key continuations per provider to survive provider switches
Before, every provider stored its opaque continuation id under the
single outbound.db key `sdk_session_id`. Flipping a session's
agent_provider (e.g. Codex → Claude) meant the new provider read the
old provider's id at wake, handed it to its own SDK, and got a
"No conversation found" error that cost the user one sacrificed
message before the stale-session recovery path cleared the id.

This reshapes session_state so continuations are keyed
`continuation:<provider>` instead. Consequences:

- Per-provider continuations coexist. Flipping Claude → Codex → Claude
  resumes the Claude thread exactly where it left off, with the
  intervening Codex thread also still on file.
- No provider ever reads another provider's id. Switching costs no
  sacrificed message and emits no transient error.
- Legacy installs are migrated forward on first startup:
  migrateLegacyContinuation() adopts any pre-existing `sdk_session_id`
  row into the current provider's slot (best guess — it was whichever
  provider ran last), then deletes the legacy row unconditionally so
  it can't poison a future provider's read.

runPollLoop now takes providerName alongside the provider instance,
and threads it through processQuery to setContinuation on init.

Tests: 9 new tests covering set/get isolation across providers,
clear-specificity, legacy-adoption, legacy-always-deleted,
prefer-existing-slot-over-legacy, and idempotency of a second
migration call.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 15:34:28 +10:00

108 lines
3.9 KiB
TypeScript

/**
* NanoClaw Agent Runner v2
*
* Runs inside a container. All IO goes through the session DB.
* No stdin, no stdout markers, no IPC files.
*
* Config is read from /workspace/agent/container.json (mounted RO).
* Only TZ and OneCLI networking vars come from env.
*
* Mount structure:
* /workspace/
* inbound.db ← host-owned session DB (container reads only)
* outbound.db ← container-owned session DB
* .heartbeat ← container touches for liveness detection
* outbox/ ← outbound files
* agent/ ← agent group folder (CLAUDE.md, container.json, working files)
* container.json ← per-group config (RO nested mount)
* global/ ← shared global memory (RO)
* /app/src/ ← shared agent-runner source (RO)
* /app/skills/ ← shared skills (RO)
* /home/node/.claude/ ← Claude SDK state + skill symlinks (RW)
*/
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { loadConfig } from './config.js';
import { buildSystemPromptAddendum } from './destinations.js';
// Providers barrel — each enabled provider self-registers on import.
// Provider skills append imports to providers/index.ts.
import './providers/index.js';
import { createProvider, type ProviderName } from './providers/factory.js';
import { runPollLoop } from './poll-loop.js';
function log(msg: string): void {
console.error(`[agent-runner] ${msg}`);
}
const CWD = '/workspace/agent';
async function main(): Promise<void> {
const config = loadConfig();
const providerName = config.provider.toLowerCase() as ProviderName;
log(`Starting v2 agent-runner (provider: ${providerName})`);
// Runtime-generated system-prompt addendum: agent identity (name) plus
// the live destinations map. Everything else (capabilities, per-module
// instructions, per-channel formatting) is loaded by Claude Code from
// /workspace/agent/CLAUDE.md — the composed entry imports the shared
// base (/app/CLAUDE.md) and each enabled module's fragment. Per-group
// memory lives in /workspace/agent/CLAUDE.local.md (auto-loaded).
const instructions = buildSystemPromptAddendum(config.assistantName || undefined);
// Discover additional directories mounted at /workspace/extra/*
const additionalDirectories: string[] = [];
const extraBase = '/workspace/extra';
if (fs.existsSync(extraBase)) {
for (const entry of fs.readdirSync(extraBase)) {
const fullPath = path.join(extraBase, entry);
if (fs.statSync(fullPath).isDirectory()) {
additionalDirectories.push(fullPath);
}
}
if (additionalDirectories.length > 0) {
log(`Additional directories: ${additionalDirectories.join(', ')}`);
}
}
// MCP server path — bun runs TS directly; no tsc build step in-image.
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mcpServerPath = path.join(__dirname, 'mcp-tools', 'index.ts');
// Build MCP servers config: nanoclaw built-in + any from container.json
const mcpServers: Record<string, { command: string; args: string[]; env: Record<string, string> }> = {
nanoclaw: {
command: 'bun',
args: ['run', mcpServerPath],
env: {},
},
};
for (const [name, serverConfig] of Object.entries(config.mcpServers)) {
mcpServers[name] = serverConfig;
log(`Additional MCP server: ${name} (${serverConfig.command})`);
}
const provider = createProvider(providerName, {
assistantName: config.assistantName || undefined,
mcpServers,
env: { ...process.env },
additionalDirectories: additionalDirectories.length > 0 ? additionalDirectories : undefined,
});
await runPollLoop({
provider,
providerName,
cwd: CWD,
systemContext: { instructions },
});
}
main().catch((err) => {
log(`Fatal error: ${err instanceof Error ? err.message : String(err)}`);
process.exit(1);
});