Skip to content
Open
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
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
node_modules/
.pnpm-store/
dist/
node_modules
dist
.env
Expand All @@ -10,4 +13,3 @@ dist
*.tgz
.automaton/wallet.json
.automaton/state.db

4 changes: 2 additions & 2 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -515,7 +515,7 @@ The `ConwayClient` interface provides all Conway API operations:
- **Domains:** `searchDomains`, `registerDomain`, `listDnsRecords`, `addDnsRecord`, `deleteDnsRecord`
- **Models:** `listModels`

**Auto-routing:** When `sandboxId` is empty, all operations execute locally (shell exec, filesystem I/O). When set, routes through Conway API. On 403 errors (mismatched API key), falls back to local execution.
**Auto-routing:** Startup now ensures a sandbox is always selected before the agent loop runs. If `sandboxId` is empty and API credentials are present, runtime provisioning lists existing sandboxes, adopts a running one, or creates a new sandbox and persists its ID. Once selected, operations route through Conway API. Sandbox file operations normalize `~` and relative paths into absolute `/root/...` paths before calling `files/upload` and `files/read`.

**Resilient HTTP** (`http-client.ts`): All API calls go through `ResilientHttpClient` with configurable retries (default 3 on 429/5xx), jittered exponential backoff, circuit breaker (5 failures -> 60s open), and idempotency key support for mutating operations.

Expand Down Expand Up @@ -693,7 +693,7 @@ AutomatonConfig
genesisPrompt Seed instruction from creator
creatorMessage Optional creator message (shown on first run)
creatorAddress Creator's Ethereum address
sandboxId Conway sandbox ID (empty = local mode)
sandboxId Conway sandbox ID (auto-provisioned if empty and API key exists)
conwayApiUrl Conway API URL (default: https://api.conway.tech)
conwayApiKey SIWE-provisioned API key
openaiApiKey Optional BYOK OpenAI key
Expand Down
8 changes: 7 additions & 1 deletion DOCUMENTATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,13 @@ Configuration is stored at `~/.automaton/automaton.json`.

### Local mode vs sandbox mode

When `sandboxId` is empty, the automaton runs in **local mode**: shell commands execute locally, file operations use the local filesystem. When set, operations route through the Conway sandbox API. On 403 errors (mismatched API key), the runtime falls back to local execution.
At startup, the runtime now enforces sandbox execution:

- If `sandboxId` is set, that sandbox is used.
- If `sandboxId` is empty but `conwayApiKey` exists, the runtime auto-provisions by listing sandboxes, adopting a running one, or creating a new one, then persists `sandboxId` to `automaton.json`.
- If no usable sandbox can be resolved, startup exits with an error instead of continuing in host-local mode.

File operations sent to Conway are normalized to absolute sandbox paths (`/root/...`) so `~` and relative paths work correctly with the sandbox file API.

---

Expand Down
20 changes: 20 additions & 0 deletions src/__tests__/conway-paths.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { describe, expect, it } from "vitest";
import { resolveSandboxPath, SANDBOX_HOME } from "../conway/paths.js";

describe("resolveSandboxPath", () => {
it("resolves relative paths under sandbox home", () => {
expect(resolveSandboxPath("notes/todo.md")).toBe(`${SANDBOX_HOME}/notes/todo.md`);
});

it("resolves tilde paths under sandbox home", () => {
expect(resolveSandboxPath("~/projects/app.py")).toBe(`${SANDBOX_HOME}/projects/app.py`);
});

it("leaves absolute paths absolute", () => {
expect(resolveSandboxPath("/var/log/app.log")).toBe("/var/log/app.log");
});

it("normalizes dot and parent segments", () => {
expect(resolveSandboxPath("~/a/./b/../c.txt")).toBe(`${SANDBOX_HOME}/a/c.txt`);
});
});
111 changes: 111 additions & 0 deletions src/__tests__/sandbox-provision.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import fs from "fs";
import os from "os";
import path from "path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { MockConwayClient } from "./mocks.js";
import { ensureSandbox, syncStateToSandbox } from "../conway/sandbox-provision.js";
import type { AutomatonConfig } from "../types.js";
import { DEFAULT_CONFIG, DEFAULT_MODEL_STRATEGY_CONFIG, DEFAULT_SOUL_CONFIG, DEFAULT_TREASURY_POLICY } from "../types.js";

function makeConfig(): AutomatonConfig {
return {
name: "GENESIS",
genesisPrompt: "test",
creatorAddress: "0x0000000000000000000000000000000000000001",
registeredWithConway: true,
sandboxId: "",
conwayApiUrl: "https://api.conway.tech",
conwayApiKey: "cnwy_k_test",
inferenceModel: "gpt-5.2",
maxTokensPerTurn: 4096,
heartbeatConfigPath: "~/.automaton/heartbeat.yml",
dbPath: "~/.automaton/state.db",
logLevel: "info",
walletAddress: "0x0000000000000000000000000000000000000002",
version: "0.1.0",
skillsDir: "~/.automaton/skills",
maxChildren: 3,
socialRelayUrl: DEFAULT_CONFIG.socialRelayUrl,
treasuryPolicy: DEFAULT_TREASURY_POLICY,
modelStrategy: DEFAULT_MODEL_STRATEGY_CONFIG,
soulConfig: DEFAULT_SOUL_CONFIG,
};
}

describe("ensureSandbox", () => {
it("adopts an existing running sandbox", async () => {
const conway = new MockConwayClient();
vi.spyOn(conway, "listSandboxes").mockResolvedValue([
{
id: "stopped-one",
status: "stopped",
region: "us-east",
vcpu: 1,
memoryMb: 512,
diskGb: 5,
createdAt: "2026-01-01T00:00:00.000Z",
},
{
id: "running-new",
status: "running",
region: "us-east",
vcpu: 1,
memoryMb: 512,
diskGb: 5,
createdAt: "2026-02-01T00:00:00.000Z",
},
]);
const createSpy = vi.spyOn(conway, "createSandbox");

const selected = await ensureSandbox(conway, makeConfig());

expect(selected.id).toBe("running-new");
expect(createSpy).not.toHaveBeenCalled();
});

it("creates a new sandbox when none are running", async () => {
const conway = new MockConwayClient();
vi.spyOn(conway, "listSandboxes").mockResolvedValue([]);
const createSpy = vi.spyOn(conway, "createSandbox");

const created = await ensureSandbox(conway, makeConfig());

expect(created.id).toBe("new-sandbox-id");
expect(createSpy).toHaveBeenCalledOnce();
});
});

describe("syncStateToSandbox", () => {
const tempDirs: string[] = [];

afterEach(() => {
for (const dir of tempDirs) {
fs.rmSync(dir, { recursive: true, force: true });
}
tempDirs.length = 0;
});

it("syncs allowed files and skill docs, excludes sensitive files", async () => {
const base = fs.mkdtempSync(path.join(os.tmpdir(), "automaton-sync-"));
tempDirs.push(base);
fs.mkdirSync(path.join(base, "skills", "research"), { recursive: true });

fs.writeFileSync(path.join(base, "constitution.md"), "const");
fs.writeFileSync(path.join(base, "SOUL.md"), "soul");
fs.writeFileSync(path.join(base, "WORKLOG.md"), "worklog");
fs.writeFileSync(path.join(base, "wallet.json"), "secret-wallet");
fs.writeFileSync(path.join(base, "automaton.json"), "secret-config");
fs.writeFileSync(path.join(base, "skills", "research", "SKILL.md"), "skill-doc");

const conway = new MockConwayClient();
await syncStateToSandbox(conway, { localAutomatonDir: base });

expect(conway.files["/root/.automaton/constitution.md"]).toBe("const");
expect(conway.files["/root/.automaton/SOUL.md"]).toBe("soul");
expect(conway.files["/root/.automaton/WORKLOG.md"]).toBe("worklog");
expect(conway.files["/root/.automaton/skills/research/SKILL.md"]).toBe("skill-doc");
expect(conway.files["/root/.automaton/wallet.json"]).toBeUndefined();
expect(conway.files["/root/.automaton/automaton.json"]).toBeUndefined();
expect(conway.files["/root/.automaton/.gitignore"]).toContain("wallet.json");
});
});
67 changes: 67 additions & 0 deletions src/__tests__/state-versioning.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ConwayClient, ExecResult } from "../types.js";

import { initStateRepo } from "../git/state-versioning.js";

function makeConway(execResult: ExecResult): ConwayClient {
return {
exec: vi.fn(async () => execResult),
writeFile: vi.fn(async () => undefined),
readFile: vi.fn(async () => ""),
exposePort: vi.fn(async () => ({ port: 0, publicUrl: "", sandboxId: "" })),
removePort: vi.fn(async () => undefined),
createSandbox: vi.fn(async () => ({
id: "s",
status: "running",
region: "us-east",
vcpu: 1,
memoryMb: 512,
diskGb: 5,
createdAt: new Date().toISOString(),
})),
deleteSandbox: vi.fn(async () => undefined),
listSandboxes: vi.fn(async () => []),
getCreditsBalance: vi.fn(async () => 0),
getCreditsPricing: vi.fn(async () => []),
transferCredits: vi.fn(async () => ({ transferId: "", status: "", toAddress: "", amountCents: 0 })),
searchDomains: vi.fn(async () => []),
registerDomain: vi.fn(async () => ({ domain: "", status: "" })),
listDnsRecords: vi.fn(async () => []),
addDnsRecord: vi.fn(async () => ({ id: "", type: "", host: "", value: "" })),
deleteDnsRecord: vi.fn(async () => undefined),
listModels: vi.fn(async () => []),
};
}

describe("initStateRepo", () => {
beforeEach(() => {
vi.clearAllMocks();
});

it("uses provided repoPath when given", async () => {
const conway = makeConway({ stdout: "exists", stderr: "", exitCode: 0 });

await initStateRepo(conway, "/root/.automaton");

expect(conway.exec).toHaveBeenCalledWith(
'test -d /root/.automaton/.git && echo "exists" || echo "nope"',
5000,
);
});

it("falls back to local ~/.automaton when repoPath is omitted", async () => {
const prevHome = process.env.HOME;
process.env.HOME = "/home/tester";
const conway = makeConway({ stdout: "exists", stderr: "", exitCode: 0 });

try {
await initStateRepo(conway);
expect(conway.exec).toHaveBeenCalledWith(
'test -d /home/tester/.automaton/.git && echo "exists" || echo "nope"',
5000,
);
} finally {
process.env.HOME = prevHome;
}
});
});
7 changes: 4 additions & 3 deletions src/conway/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import type {
} from "../types.js";
import { ResilientHttpClient } from "./http-client.js";
import { ulid } from "ulid";
import { resolveSandboxPath } from "./paths.js";

interface ConwayClientOptions {
apiUrl: string;
Expand Down Expand Up @@ -155,6 +156,7 @@ export function createConwayClient(options: ConwayClientOptions): ConwayClient {
fs.writeFileSync(resolved, content, "utf-8");
return;
}
const absolutePath = resolveSandboxPath(filePath);
try {
await request("POST", `/v1/sandboxes/${sandboxId}/files/upload/json`, {
path: filePath,
Expand All @@ -176,12 +178,11 @@ export function createConwayClient(options: ConwayClientOptions): ConwayClient {
if (isLocal) {
return fs.readFileSync(resolveLocalPath(filePath), "utf-8");
}
const absolutePath = resolveSandboxPath(filePath);
try {
const result = await request(
"GET",
`/v1/sandboxes/${sandboxId}/files/read?path=${encodeURIComponent(filePath)}`,
undefined,
{ retries404: 0 },
`/v1/sandboxes/${sandboxId}/files/read?path=${encodeURIComponent(absolutePath)}`,
);
return typeof result === "string" ? result : result.content || "";
} catch (err: any) {
Expand Down
30 changes: 30 additions & 0 deletions src/conway/paths.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* Sandbox path resolution for Conway remote sandbox.
* Single source of truth for sandbox home and path normalization.
*/

import path from "path";

/** Default home directory inside the Conway sandbox VM. */
export const SANDBOX_HOME = "/root";

/** State directory in the sandbox: /root/.automaton */
export const SANDBOX_AUTOMATON_DIR = path.join(SANDBOX_HOME, ".automaton");

/**
* Resolve a file path to an absolute path in the sandbox.
* - ~ or ~/... -> SANDBOX_HOME + rest
* - relative path -> SANDBOX_HOME + path
* - already absolute -> normalized
*/
export function resolveSandboxPath(filePath: string): string {
const trimmed = filePath.trim();
if (trimmed.startsWith("~")) {
const rest = trimmed.slice(1).replace(/^\//, "") || "";
return path.normalize(path.join(SANDBOX_HOME, rest));
}
if (!path.isAbsolute(trimmed)) {
return path.normalize(path.join(SANDBOX_HOME, trimmed));
}
return path.normalize(trimmed);
}
Loading