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
2 changes: 2 additions & 0 deletions cloudflare-gastown/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.dev.vars
container/dist/
62 changes: 62 additions & 0 deletions cloudflare-gastown/AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Conventions

## File naming

- Add a suffix matching the module type, e.g. `agents.table.ts`, `gastown.worker.ts`.
- Modules that predominantly export a class should be named after that class, e.g. `AgentIdentity.do.ts` for `AgentIdentityDO`.

## Durable Objects

- Each DO module must export a `get{ClassName}Stub` helper function (e.g. `getRigDOStub`) that centralizes how that DO namespace creates instances. Callers should use this helper instead of accessing the namespace binding directly.

## IO boundaries

- Always validate data at IO boundaries (HTTP responses, JSON.parse results, SSE event payloads, subprocess output) with Zod schemas. Return `unknown` from raw fetch/parse helpers and `.parse()` in the caller.
- Never use `as` to cast IO data. If the shape is known, define a Zod schema; if not, use `.passthrough()` or a catch-all schema.

## Column naming

- Never name a primary key column just `id`. Encode the entity in the column name, e.g. `bead_id`, `bead_event_id`, `rig_id`. This avoids ambiguity in joins and makes grep-based navigation reliable.

## SQL queries

- Use the type-safe `query()` helper from `util/query.util.ts` for all SQL queries.
- Prefix SQL template strings with `/* sql */` for syntax highlighting and to signal intent, e.g. `query(this.sql, /* sql */ \`SELECT ...\`, [...])`.
- Format queries for human readability: use multi-line strings with one clause per line (`SELECT`, `FROM`, `WHERE`, `SET`, etc.).
- Reference tables and columns via the table interpolator objects exported from `db/tables/*.table.ts` (created with `getTableFromZodSchema` from `util/table.ts`). Never use raw table/column name strings in queries. The interpolator has three access patterns — use the right one for context:
- `${beads}` → bare table name. Use for `FROM`, `INSERT INTO`, `DELETE FROM`.
- `${beads.columns.status}` → bare column name. Use for `SET` clauses and `INSERT` column lists where the table is already implied.
- `${beads.status}` → qualified `table.column`. Use for `SELECT`, `WHERE`, `JOIN ON`, `ORDER BY`, and anywhere a column could be ambiguous.
- Prefer static queries over dynamically constructed ones. Move conditional logic into the query itself using SQL constructs like `COALESCE`, `CASE`, `NULLIF`, or `WHERE (? IS NULL OR col = ?)` patterns so the full query is always visible as a single readable string.
- Always parse query results with the Zod `Record` schemas from `db/tables/*.table.ts`. Never use ad-hoc `as Record<string, unknown>` casts or `String(row.col)` to extract fields — use `.pick()` for partial selects and `.array()` for lists, e.g. `BeadRecord.pick({ bead_id: true }).array().parse(rows)`. This keeps row parsing type-safe and co-located with the schema definition.
- When a column has a SQL `CHECK` constraint that restricts it to a set of values (i.e. an enum), mirror that in the Record schema using `z.enum()` rather than `z.string()`, e.g. `role: z.enum(['polecat', 'refinery', 'mayor', 'witness'])`.

## HTTP routes

- **Do not use Hono sub-app mounting** (e.g. `app.route('/prefix', subApp)`). Define all routes in the main worker entry point (e.g. `gastown.worker.ts`) so a human can scan one file and immediately see every route the app exposes.
- Move handler logic into `handlers/*.handler.ts` modules. Each module owns routes for a logical domain. Name the file after the domain, e.g. `handlers/rig-agents.handler.ts` for `/api/rigs/:rigId/agents/*` routes.
- Each handler function takes two arguments:
1. The Hono `Context` object (typed as the app's `HonoContext` / `GastownEnv`).
2. A plain object containing the route params parsed from the path, e.g. `{ rigId: string }` or `{ rigId: string; beadId: string }`.

This keeps the handler's contract explicit and testable, while the route definition in the entry point is the single source of truth for path → param shape.

```ts
// gastown.worker.ts — route definition
app.post('/api/rigs/:rigId/agents', c => handleRegisterAgent(c, c.req.param()));

// handlers/rig-agents.handler.ts — handler implementation
export async function handleRegisterAgent(c: Context<GastownEnv>, params: { rigId: string }) {
// Zod validation lives in the handler, not as route middleware
const parsed = RegisterAgentBody.safeParse(await c.req.json());
if (!parsed.success) {
return c.json(
{ success: false, error: 'Invalid request body', issues: parsed.error.issues },
400
);
}
const rig = getRigDOStub(c.env, params.rigId);
const agent = await rig.registerAgent(parsed.data);
return c.json(resSuccess(agent), 201);
}
```
60 changes: 60 additions & 0 deletions cloudflare-gastown/container/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
FROM oven/bun:1-slim

# Install git, gh CLI, and Node.js (required by @kilocode/cli which uses #!/usr/bin/env node)
RUN apt-get update && \
apt-get install -y --no-install-recommends git curl ca-certificates && \
curl -fsSL https://deb.nodesource.com/setup_22.x | bash - && \
apt-get install -y --no-install-recommends nodejs && \
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg \
-o /usr/share/keyrings/githubcli-archive-keyring.gpg && \
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" \
> /etc/apt/sources.list.d/github-cli.list && \
apt-get update && \
apt-get install -y --no-install-recommends gh && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*

# Install Kilo CLI globally via npm (needs real Node.js runtime).
# npm's global install does not resolve optionalDependencies, so we must
# explicitly install the platform-specific binary package alongside the CLI.
# Also install @kilocode/plugin globally so repo-local tools (e.g.
# .opencode/tool/*.ts) can resolve it without a local node_modules.
# Install both glibc and musl variants — the CLI's binary resolver may
# pick either depending on the detected libc.
# Also install pnpm — many projects use it as their package manager.
RUN npm install -g @kilocode/cli @kilocode/cli-linux-x64 @kilocode/cli-linux-x64-musl @kilocode/plugin pnpm && \
ln -s "$(which kilo)" /usr/local/bin/opencode

# Create non-root user for defense-in-depth
RUN useradd -m -s /bin/bash agent

# Create workspace directories
RUN mkdir -p /workspace/rigs /app && chown -R agent:agent /workspace

# ── Gastown plugin ──────────────────────────────────────────────────
# OpenCode discovers local plugins by scanning {plugin,plugins}/*.{ts,js}
# inside each config directory. We install deps into the plugin source
# dir then symlink the entry-point file so the glob finds it. Relative
# imports in index.ts resolve via the symlink's real path (/opt/…).
COPY plugin/ /opt/gastown-plugin/
RUN cd /opt/gastown-plugin && npm install --omit=dev && \
mkdir -p /home/agent/.config/kilo/plugins && \
ln -s /opt/gastown-plugin/index.ts /home/agent/.config/kilo/plugins/gastown.ts && \
chown -R agent:agent /home/agent/.config

WORKDIR /app

# Copy package files and install deps deterministically
COPY package.json bun.lock ./
RUN bun install --frozen-lockfile --production

# Copy source (bun runs TypeScript directly — no build step needed)
COPY src/ ./src/

RUN chown -R agent:agent /app

USER agent

EXPOSE 8080

CMD ["bun", "run", "src/main.ts"]
59 changes: 59 additions & 0 deletions cloudflare-gastown/container/Dockerfile.dev
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
FROM --platform=linux/arm64 oven/bun:1-slim

# Install git, gh CLI, and Node.js (required by @kilocode/cli which uses #!/usr/bin/env node)
RUN apt-get update && \
apt-get install -y --no-install-recommends git curl ca-certificates && \
curl -fsSL https://deb.nodesource.com/setup_22.x | bash - && \
apt-get install -y --no-install-recommends nodejs && \
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg \
-o /usr/share/keyrings/githubcli-archive-keyring.gpg && \
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" \
> /etc/apt/sources.list.d/github-cli.list && \
apt-get update && \
apt-get install -y --no-install-recommends gh && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*

# Install Kilo CLI globally via npm (needs real Node.js runtime).
# npm's global install does not resolve optionalDependencies, so we must
# explicitly install the platform-specific binary package alongside the CLI.
# Install both glibc and musl variants — the CLI's binary resolver may
# pick either depending on the detected libc. bun:1-slim is Debian (glibc)
# but the resolver sometimes misdetects; installing both is safe.
# Also install pnpm — many projects use it as their package manager.
RUN npm install -g @kilocode/cli @kilocode/cli-linux-arm64 @kilocode/cli-linux-arm64-musl pnpm && \
ln -s "$(which kilo)" /usr/local/bin/opencode

# Create non-root user for defense-in-depth
RUN useradd -m -s /bin/bash agent

# Create workspace directories
RUN mkdir -p /workspace/rigs /app && chown -R agent:agent /workspace

# ── Gastown plugin ──────────────────────────────────────────────────
# OpenCode discovers local plugins by scanning {plugin,plugins}/*.{ts,js}
# inside each config directory. We install deps into the plugin source
# dir then symlink the entry-point file so the glob finds it. Relative
# imports in index.ts resolve via the symlink's real path (/opt/…).
COPY plugin/ /opt/gastown-plugin/
RUN cd /opt/gastown-plugin && npm install --omit=dev && \
mkdir -p /home/agent/.config/kilo/plugins && \
ln -s /opt/gastown-plugin/index.ts /home/agent/.config/kilo/plugins/gastown.ts && \
chown -R agent:agent /home/agent/.config

WORKDIR /app

# Copy package files and install deps deterministically
COPY package.json bun.lock ./
RUN bun install --frozen-lockfile --production

# Copy source (bun runs TypeScript directly — no build step needed)
COPY src/ ./src/

RUN chown -R agent:agent /app

USER agent

EXPOSE 8080

CMD ["bun", "run", "src/main.ts"]
Loading