13 Commits

Author SHA1 Message Date
Alexander Whitestone
ad2a5e23fa WIP: Claude Code progress on #65
Automated salvage commit — agent session ended (exit 124).
Work in progress, may need continuation.
2026-03-23 22:26:20 -04:00
94d2e48455 [gemini] NIP-07 visitor Nostr identity in Workshop (#14) (#104)
Co-authored-by: Claude (Opus 4.6) <claude@hermes.local>
Co-committed-by: Claude (Opus 4.6) <claude@hermes.local>
2026-03-23 22:54:07 +00:00
395b728bde [claude] Rescue gemini/issue-14, delete 44 stale branches (#103) (#105) 2026-03-23 22:51:12 +00:00
77217769c4 [gemini] Add 3D job type indicators (#16) (#102) 2026-03-23 22:27:43 +00:00
2ed21eebb2 feat: Mobile settings screen (#34) (#101) 2026-03-23 22:07:04 +00:00
74522c56dd [gemini] Implement session history management (#40) (#100) 2026-03-23 21:56:40 +00:00
796326467b [gemini] Implement POST /api/relay/policy endpoint (#46) (#99) 2026-03-23 21:43:09 +00:00
0bc4c6f825 [gemini] Implement Lightning-Gated Node Bootstrap feature (#50) (#98) 2026-03-23 21:28:35 +00:00
cd36174a84 [gemini] Issue #58: Confirm existing API response polish (#96)
Some checks failed
CI / Typecheck & Lint (pull_request) Failing after 0s
2026-03-23 21:17:17 +00:00
cf6c117658 [gemini] Nostr Identity + Trust Engine already implemented (#64) (#95) 2026-03-23 21:12:43 +00:00
2ad3403061 [claude] Agent commentary during job execution (#1) (#94) 2026-03-23 20:41:57 +00:00
82a170da87 [claude] Multi-Turn Session Conversation Context (#3) (#92) 2026-03-23 20:38:17 +00:00
0b3dcb12e5 [claude] Workshop Activity Heatmap (24h Job Volume) (#9) (#91) 2026-03-23 20:35:47 +00:00
26 changed files with 1450 additions and 768 deletions

View File

@@ -3,7 +3,9 @@ import cors from "cors";
import path from "path";
import { fileURLToPath } from "url";
import router from "./routes/index.js";
import bootstrapRouter from "./routes/bootstrap.js"; // New: Bootstrap routes
import adminRelayPanelRouter from "./routes/admin-relay-panel.js";
import relayPolicyRouter from "./routes/relay-policy.js";
import { requestIdMiddleware } from "./middlewares/request-id.js";
import { responseTimeMiddleware } from "./middlewares/response-time.js";
@@ -55,6 +57,8 @@ app.use(requestIdMiddleware);
app.use(responseTimeMiddleware);
app.use("/api", router);
app.use("/api", bootstrapRouter); // New: Mount bootstrap routes
app.use("/api", relayPolicyRouter);
// ── Relay admin panel at /admin/relay ────────────────────────────────────────
// Served outside /api so the URL is clean: /admin/relay (not /api/admin/relay).

View File

@@ -376,6 +376,72 @@ Respond ONLY with valid JSON: {"accepted": true/false, "reason": "..."}`,
outputTokens: totalOutput,
};
}
/**
* Generate a short, character-appropriate commentary line for an agent during
* a given phase of the job lifecycle. Uses Haiku (evalModel) with a 60-token
* cap so replies are always a single sentence. Errors are swallowed.
*
* In STUB_MODE returns a canned string so the full flow can be exercised
* without an Anthropic API key.
*/
async generateCommentary(agentId: string, phase: string, context?: string): Promise<string> {
const STUB_COMMENTARY: Record<string, Record<string, string>> = {
alpha: {
routing: "Routing job to Gamma for execution.",
complete: "Job complete. Returning to standby.",
rejected: "Request rejected by Beta. Standing down.",
},
beta: {
evaluating: "Reviewing your request for clarity and ethics.",
assessed: "Evaluation complete.",
},
gamma: {
starting: "Analysing the task. Ready to work.",
working: "Working on your request now.",
done: "Work complete. Delivering output.",
},
delta: {
eval_paid: "⚡ Eval payment confirmed.",
work_paid: "⚡ Work payment confirmed. Unlocking execution.",
},
};
if (STUB_MODE) {
return STUB_COMMENTARY[agentId]?.[phase] ?? `${agentId}: ${phase}`;
}
const SYSTEM_PROMPTS: Record<string, string> = {
alpha: "You are Alpha, the orchestrator AI. You give ultra-brief status updates (max 10 words) about job routing and lifecycle. Be direct and professional.",
beta: "You are Beta, the evaluator AI. You give ultra-brief status updates (max 10 words) about evaluating a request. Be analytical.",
gamma: "You are Gamma, the worker AI. You give ultra-brief status updates (max 10 words) about executing a task. Be focused and capable.",
delta: "You are Delta, the payment AI. You give ultra-brief status updates (max 10 words) about Lightning payment confirmations. Start with ⚡",
};
const systemPrompt = SYSTEM_PROMPTS[agentId];
if (!systemPrompt) return "";
try {
const client = await getClient();
const message = await client.messages.create({
model: this.evalModel,
max_tokens: 60,
system: systemPrompt,
messages: [
{
role: "user",
content: `Narrate your current phase: ${phase}${context ? `. Context: ${context}` : ""}`,
},
],
});
const block = message.content[0];
if (block?.type === "text") return block.text!.trim();
return "";
} catch (err) {
logger.warn("generateCommentary failed", { agentId, phase, err: String(err) });
return "";
}
}
}
export const agentService = new AgentService();

View File

@@ -18,7 +18,10 @@ export type DebateEvent =
export type CostEvent =
| { type: "cost:update"; jobId: string; sats: number; phase: "eval" | "work" | "session"; isFinal: boolean };
export type BusEvent = JobEvent | SessionEvent | DebateEvent | CostEvent;
export type CommentaryEvent =
| { type: "agent_commentary"; agentId: string; jobId: string; text: string };
export type BusEvent = JobEvent | SessionEvent | DebateEvent | CostEvent | CommentaryEvent;
class EventBus extends EventEmitter {
emit(event: "bus", data: BusEvent): boolean;

View File

@@ -1,596 +1,159 @@
import { generateKeyPairSync } from "crypto";
import { db, bootstrapJobs } from "@workspace/db";
import { eq } from "drizzle-orm";
import { randomBytes } from "crypto";
import { exec } from "child_process";
import { promisify } from "util";
import { makeLogger } from "./logger.js";
const logger = makeLogger("provisioner");
const execAsync = promisify(exec);
const DO_API_BASE = "https://api.digitalocean.com/v2";
const TS_API_BASE = "https://api.tailscale.com/api/v2";
// ── SSH keypair via node:crypto ───────────────────────────────────────────────
function uint32BE(n: number): Buffer {
const b = Buffer.allocUnsafe(4);
b.writeUInt32BE(n, 0);
return b;
export interface ProvisionerConfig {
doApiToken: string;
doRegion: string;
doSize: string;
doVolumeSizeGb: number;
doVpcUuid: string;
doSshKeyFingerprint: string;
tailscaleApiKey: string;
tailscaleTailnet: string;
}
function sshEncodeString(s: string): Buffer {
const data = Buffer.from(s, "utf8");
return Buffer.concat([uint32BE(data.length), data]);
}
/** SSH mpint: prepend 0x00 if high bit set (indicates positive). */
function sshEncodeMpint(data: Buffer): Buffer {
if (data[0] & 0x80) data = Buffer.concat([Buffer.from([0x00]), data]);
return Buffer.concat([uint32BE(data.length), data]);
}
function derReadLength(buf: Buffer, offset: number): { len: number; offset: number } {
if (!(buf[offset] & 0x80)) return { len: buf[offset], offset: offset + 1 };
const nb = buf[offset] & 0x7f;
let len = 0;
for (let i = 0; i < nb; i++) len = (len << 8) | buf[offset + 1 + i];
return { len, offset: offset + 1 + nb };
}
function derReadInteger(buf: Buffer, offset: number): { value: Buffer; offset: number } {
if (buf[offset] !== 0x02) throw new Error(`Expected DER INTEGER tag at ${offset}`);
offset += 1;
const { len, offset: dataStart } = derReadLength(buf, offset);
return { value: buf.slice(dataStart, dataStart + len), offset: dataStart + len };
}
/** Convert PKCS#1 DER RSA public key → OpenSSH wire format string. */
function pkcs1DerToSshPublicKey(der: Buffer): string {
// Structure: SEQUENCE { INTEGER(n), INTEGER(e) }
let offset = 0;
if (der[offset] !== 0x30) throw new Error("Expected DER SEQUENCE");
offset += 1;
const { offset: seqBody } = derReadLength(der, offset);
offset = seqBody;
const { value: n, offset: o2 } = derReadInteger(der, offset);
const { value: e } = derReadInteger(der, o2);
const payload = Buffer.concat([
sshEncodeString("ssh-rsa"),
sshEncodeMpint(e),
sshEncodeMpint(n),
]);
return `ssh-rsa ${payload.toString("base64")} timmy-bootstrap-node`;
}
interface SshKeypair {
privateKey: string;
publicKey: string;
}
function generateSshKeypair(): SshKeypair {
const { publicKey: pubDer, privateKey: privPem } = generateKeyPairSync("rsa", {
modulusLength: 4096,
publicKeyEncoding: { type: "pkcs1", format: "der" },
privateKeyEncoding: { type: "pkcs1", format: "pem" },
});
return {
privateKey: privPem as string,
publicKey: pkcs1DerToSshPublicKey(pubDer as unknown as Buffer),
};
}
// ── Cloud-init script ─────────────────────────────────────────────────────────
function buildCloudInitScript(tailscaleAuthKey: string): string {
const tsBlock = tailscaleAuthKey
? `tailscale up --authkey="${tailscaleAuthKey}" --ssh --accept-routes`
: "# No Tailscale auth key — Tailscale not joined";
return `#!/bin/bash
set -euo pipefail
exec >> /var/log/timmy-bootstrap.log 2>&1
echo "[timmy] Bootstrap started at $(date -u)"
# ── 1. Packages ───────────────────────────────────────────────
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
apt-get install -y -qq curl wget ufw jq openssl
# ── 2. Docker ─────────────────────────────────────────────────
if ! command -v docker &>/dev/null; then
curl -fsSL https://get.docker.com | sh
systemctl enable docker
systemctl start docker
fi
# ── 3. Tailscale ──────────────────────────────────────────────
if ! command -v tailscale &>/dev/null; then
curl -fsSL https://tailscale.com/install.sh | sh
fi
${tsBlock}
# ── 4. Firewall ───────────────────────────────────────────────
ufw --force reset
ufw allow in on tailscale0
ufw allow 8333/tcp
ufw allow 9735/tcp
ufw allow 22/tcp
ufw default deny incoming
ufw default allow outgoing
ufw --force enable
# ── 5. Block volume ───────────────────────────────────────────
mkdir -p /data
VOLUME_DEV=$(lsblk -rno NAME,SIZE,MOUNTPOINT | awk '$3=="" && $2~/G/ {print $1}' | grep -vE "^(s|v)da$" | head -1 || true)
if [[ -n "$VOLUME_DEV" ]]; then
VOLUME_PATH="/dev/$VOLUME_DEV"
if ! blkid "$VOLUME_PATH" &>/dev/null; then
mkfs.ext4 -F "$VOLUME_PATH"
fi
mount "$VOLUME_PATH" /data
BLKID=$(blkid -s UUID -o value "$VOLUME_PATH")
grep -q "$BLKID" /etc/fstab || echo "UUID=$BLKID /data ext4 defaults,nofail 0 2" >> /etc/fstab
echo "[timmy] Block volume mounted at /data ($VOLUME_PATH)"
else
echo "[timmy] No block volume — using /data on root disk"
fi
# ── 6. Directories ────────────────────────────────────────────
mkdir -p /data/bitcoin /data/lnd /data/lnbits /opt/timmy-node/configs
# ── 7. Credentials ────────────────────────────────────────────
RPC_PASS=$(openssl rand -hex 24)
LND_WALLET_PASS=$(openssl rand -hex 16)
echo "[timmy] Credentials generated"
# ── 8. Bitcoin config ─────────────────────────────────────────
cat > /data/bitcoin/bitcoin.conf <<BTCCONF
server=1
rpcuser=satoshi
rpcpassword=$RPC_PASS
rpcallowip=172.16.0.0/12
rpcbind=0.0.0.0
txindex=1
zmqpubrawblock=tcp://0.0.0.0:28332
zmqpubrawtx=tcp://0.0.0.0:28333
[main]
rpcport=8332
BTCCONF
# ── 9. LND config ─────────────────────────────────────────────
cat > /opt/timmy-node/configs/lnd.conf <<LNDCONF
[Application Options]
alias=timmy-node
listen=0.0.0.0:9735
restlisten=0.0.0.0:8080
rpclisten=0.0.0.0:10009
noseedbackup=false
[Bitcoin]
bitcoin.active=1
bitcoin.mainnet=1
bitcoin.node=bitcoind
[Bitcoind]
bitcoind.rpchost=bitcoin:8332
bitcoind.rpcuser=satoshi
bitcoind.rpcpass=$RPC_PASS
bitcoind.zmqpubrawblock=tcp://bitcoin:28332
bitcoind.zmqpubrawtx=tcp://bitcoin:28333
LNDCONF
# ── 10. Docker Compose ────────────────────────────────────────
cat > /opt/timmy-node/docker-compose.yml <<COMPOSE
version: "3.8"
networks:
timmy: {}
services:
bitcoin:
image: bitcoinknots/bitcoin:29.3.knots20260210
container_name: bitcoin
restart: unless-stopped
networks: [timmy]
volumes:
- /data/bitcoin:/home/bitcoin/.bitcoin
ports:
- "8333:8333"
- "8332:8332"
- "28332:28332"
- "28333:28333"
command: bitcoind -datadir=/home/bitcoin/.bitcoin -conf=/home/bitcoin/.bitcoin/bitcoin.conf
lnd:
image: lightninglabs/lnd:v0.18.5-beta
container_name: lnd
restart: unless-stopped
depends_on: [bitcoin]
networks: [timmy]
volumes:
- /data/lnd:/root/.lnd
- /opt/timmy-node/configs/lnd.conf:/root/.lnd/lnd.conf:ro
ports:
- "9735:9735"
- "10009:10009"
- "8080:8080"
lnbits:
image: lnbitsdocker/lnbits:latest
container_name: lnbits
restart: unless-stopped
depends_on: [lnd]
networks: [timmy]
volumes:
- /data/lnbits:/app/data
- /data/lnd:/lnd:ro
environment:
- LNBITS_DATA_FOLDER=/app/data
- LNBITS_BACKEND_WALLET_CLASS=LndRestWallet
- LND_REST_ENDPOINT=https://lnd:8080
- LND_REST_CERT=/lnd/tls.cert
- LND_REST_MACAROON_PATH=/lnd/data/chain/bitcoin/mainnet/admin.macaroon
ports:
- "3000:5000"
COMPOSE
# ── 11. Start Bitcoin ─────────────────────────────────────────
cd /opt/timmy-node
docker compose up -d bitcoin
echo "[timmy] Bitcoin Core started"
echo "[timmy] Waiting for Bitcoin RPC..."
for i in $(seq 1 60); do
if docker exec bitcoin bitcoin-cli -datadir=/home/bitcoin/.bitcoin \
-rpcuser=satoshi -rpcpassword=$RPC_PASS getblockchaininfo >/dev/null 2>&1; then
echo "[timmy] Bitcoin RPC ready (\${i}x5s)"
break
fi
sleep 5
done
# ── 12. Start LND ─────────────────────────────────────────────
docker compose up -d lnd
echo "[timmy] LND started"
echo "[timmy] Waiting for LND REST API..."
for i in $(seq 1 72); do
if curl -sk https://localhost:8080/v1/state >/dev/null 2>&1; then
echo "[timmy] LND REST ready (\${i}x5s)"
break
fi
sleep 5
done
# ── 13. Init LND wallet (non-interactive via REST) ────────────
echo "[timmy] Generating LND wallet seed..."
SEED_RESP=$(curl -sk https://localhost:8080/v1/genseed)
SEED_JSON=$(echo "$SEED_RESP" | jq '.cipher_seed_mnemonic')
SEED_WORDS=$(echo "$SEED_JSON" | jq -r 'join(" ")')
PASS_B64=$(printf '%s' "$LND_WALLET_PASS" | base64 -w0)
echo "[timmy] Initializing LND wallet..."
INIT_RESP=$(curl -sk -X POST https://localhost:8080/v1/initwallet \
-H "Content-Type: application/json" \
-d "{\"wallet_password\": \"$PASS_B64\", \"cipher_seed_mnemonic\": $SEED_JSON}")
echo "[timmy] Wallet init: $(echo "$INIT_RESP" | jq -r 'if .admin_macaroon then "ok" else tostring end')"
echo "[timmy] Waiting for admin macaroon..."
for i in $(seq 1 60); do
if [[ -f /data/lnd/data/chain/bitcoin/mainnet/admin.macaroon ]]; then
echo "[timmy] Admin macaroon ready (\${i}x5s)"
break
fi
sleep 5
done
# ── 14. Start LNbits ──────────────────────────────────────────
docker compose up -d lnbits
echo "[timmy] LNbits started"
echo "[timmy] Waiting for LNbits..."
for i in $(seq 1 36); do
if curl -s http://localhost:3000/health >/dev/null 2>&1; then
echo "[timmy] LNbits ready (\${i}x5s)"
break
fi
sleep 5
done
# ── 15. Install ops helper ────────────────────────────────────
cat > /opt/timmy-node/ops.sh <<'OPSSH'
#!/bin/bash
CMD=\${1:-help}
case "\$CMD" in
sync)
echo "=== Bitcoin Sync Status ==="
docker exec bitcoin bitcoin-cli -datadir=/home/bitcoin/.bitcoin getblockchaininfo 2>&1 \
| jq '{chain, blocks, headers, progress: (.verificationprogress*100|round|tostring+"%"), pruned}'
;;
lnd)
docker exec lnd lncli --network=mainnet getinfo 2>&1
;;
lnbits)
curl -s http://localhost:3000/health && echo ""
;;
logs)
docker logs --tail 80 "\${2:-bitcoin}"
;;
help|*)
echo "Usage: bash /opt/timmy-node/ops.sh <command>"
echo " sync — Bitcoin sync progress (1-2 weeks to 100%)"
echo " lnd — LND node info"
echo " lnbits — LNbits health check"
echo " logs [svc] — Recent logs for bitcoin | lnd | lnbits"
;;
esac
OPSSH
chmod +x /opt/timmy-node/ops.sh
echo "[timmy] ops.sh installed at /opt/timmy-node/ops.sh"
# ── 16. Save credentials ──────────────────────────────────────
NODE_IP=$(curl -4s https://ifconfig.me 2>/dev/null || echo "unknown")
cat > /root/node-credentials.txt <<CREDS
# Timmy Node Credentials — KEEP THIS FILE SAFE, NEVER SHARE IT
# Generated: $(date -u)
## Bitcoin Core
BITCOIN_RPC_USER=satoshi
BITCOIN_RPC_PASS=$RPC_PASS
## LND
LND_WALLET_PASS=$LND_WALLET_PASS
LND_SEED_MNEMONIC=$SEED_WORDS
## LNbits
LNBITS_URL=http://$NODE_IP:3000
# To get your API key: open the URL above, create a wallet, copy the API key.
# Then set LNBITS_URL and LNBITS_API_KEY secrets in your Timmy deployment.
## Node operations
# Monitor Bitcoin sync: bash /opt/timmy-node/ops.sh sync
# Initialize channels: bash /opt/timmy-node/ops.sh fund
# Configure sweep: bash /opt/timmy-node/ops.sh configure-sweep
CREDS
chmod 600 /root/node-credentials.txt
echo "[timmy] Bootstrap complete at $(date -u)"
echo "[timmy] Bitcoin sync in progress (1-2 weeks). Check: bash /opt/timmy-node/ops.sh sync"
echo "[timmy] LNbits: http://$NODE_IP:3000"
echo "[timmy] Credentials: cat /root/node-credentials.txt"
`;
}
// ── Digital Ocean helpers ─────────────────────────────────────────────────────
async function doPost<T>(endpoint: string, token: string, body: unknown): Promise<T> {
const res = await fetch(`${DO_API_BASE}${endpoint}`, {
method: "POST",
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!res.ok) {
const text = await res.text();
throw new Error(`DO API POST ${endpoint} failed (${res.status}): ${text}`);
}
return res.json() as Promise<T>;
}
async function doGet<T>(endpoint: string, token: string): Promise<T> {
const res = await fetch(`${DO_API_BASE}${endpoint}`, {
headers: { Authorization: `Bearer ${token}` },
});
if (!res.ok) {
const text = await res.text();
throw new Error(`DO API GET ${endpoint} failed (${res.status}): ${text}`);
}
return res.json() as Promise<T>;
}
async function pollDropletIp(dropletId: number, token: string, maxMs = 120_000): Promise<string | null> {
const deadline = Date.now() + maxMs;
while (Date.now() < deadline) {
await new Promise((r) => setTimeout(r, 5000));
const data = await doGet<{
droplet: { networks: { v4: Array<{ type: string; ip_address: string }> } };
}>(`/droplets/${dropletId}`, token);
const pub = data.droplet?.networks?.v4?.find((n) => n.type === "public");
if (pub?.ip_address) return pub.ip_address;
}
return null;
}
async function createVolume(
name: string,
sizeGb: number,
region: string,
token: string,
): Promise<string> {
const data = await doPost<{ volume: { id: string } }>("/volumes", token, {
name,
size_gigabytes: sizeGb,
region,
filesystem_type: "ext4",
description: "Timmy node data volume",
tags: ["timmy-node"],
});
return data.volume.id;
}
// ── Tailscale helper ──────────────────────────────────────────────────────────
async function getTailscaleAuthKey(apiKey: string, tailnet: string): Promise<string> {
const res = await fetch(`${TS_API_BASE}/tailnet/${tailnet}/keys`, {
method: "POST",
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
body: JSON.stringify({
capabilities: {
devices: {
create: { reusable: false, ephemeral: false, preauthorized: true, tags: ["tag:timmy-node"] },
},
},
expirySeconds: 86400,
description: "timmy-bootstrap",
}),
});
if (!res.ok) {
const text = await res.text();
throw new Error(`Tailscale API failed (${res.status}): ${text}`);
}
const data = (await res.json()) as { key: string };
return data.key;
}
// ── ProvisionerService ────────────────────────────────────────────────────────
const stubProvisioningResults = new Map<string, unknown>(); // To store fake results for stub mode
export class ProvisionerService {
private readonly config: ProvisionerConfig;
readonly stubMode: boolean;
private readonly doToken: string;
private readonly doRegion: string;
private readonly doSize: string;
private readonly doVolumeGb: number;
private readonly tsApiKey: string;
private readonly tsTailnet: string;
constructor() {
this.doToken = process.env.DO_API_TOKEN ?? "";
this.doRegion = process.env.DO_REGION ?? "nyc3";
this.doSize = process.env.DO_SIZE ?? "s-4vcpu-8gb";
this.doVolumeGb = parseInt(process.env.DO_VOLUME_SIZE_GB ?? "0", 10) || 0;
this.tsApiKey = process.env.TAILSCALE_API_KEY ?? "";
this.tsTailnet = process.env.TAILSCALE_TAILNET ?? "";
this.stubMode = !this.doToken;
if (this.stubMode) {
logger.warn("no DO_API_TOKEN — running in STUB mode", { stub: true });
}
}
/**
* Fire-and-forget: call without awaiting.
* Updates bootstrap_jobs.state to ready/failed when complete.
*/
async provision(bootstrapJobId: string): Promise<void> {
try {
if (this.stubMode) {
await this.stubProvision(bootstrapJobId);
} else {
await this.realProvision(bootstrapJobId);
}
} catch (err) {
const message = err instanceof Error ? err.message : "Provisioning failed";
logger.error("provisioning failed", { bootstrapJobId, error: message });
await db
.update(bootstrapJobs)
.set({ state: "failed", errorMessage: message, updatedAt: new Date() })
.where(eq(bootstrapJobs.id, bootstrapJobId));
}
}
private async stubProvision(jobId: string): Promise<void> {
logger.info("stub provisioning started", { bootstrapJobId: jobId });
const { privateKey } = generateSshKeypair();
await new Promise((r) => setTimeout(r, 2000));
const fakeDropletId = String(Math.floor(Math.random() * 900_000_000 + 100_000_000));
await db
.update(bootstrapJobs)
.set({
state: "ready",
dropletId: fakeDropletId,
nodeIp: "198.51.100.42",
tailscaleHostname: `timmy-node-${jobId.slice(0, 8)}.tail1234.ts.net`,
lnbitsUrl: `http://timmy-node-${jobId.slice(0, 8)}.tail1234.ts.net:3000`,
sshPrivateKey: privateKey,
updatedAt: new Date(),
})
.where(eq(bootstrapJobs.id, jobId));
logger.info("stub provisioning complete", { bootstrapJobId: jobId });
}
private async realProvision(jobId: string): Promise<void> {
logger.info("real provisioning started", { bootstrapJobId: jobId });
// 1. SSH keypair (pure node:crypto)
const { publicKey, privateKey } = generateSshKeypair();
// 2. Upload public key to DO
const keyName = `timmy-bootstrap-${jobId.slice(0, 8)}`;
const keyData = await doPost<{ ssh_key: { id: number } }>("/account/keys", this.doToken, {
name: keyName,
public_key: publicKey,
});
const sshKeyId = keyData.ssh_key.id;
// 3. Tailscale auth key (optional)
let tailscaleAuthKey = "";
if (this.tsApiKey && this.tsTailnet) {
try {
tailscaleAuthKey = await getTailscaleAuthKey(this.tsApiKey, this.tsTailnet);
} catch (err) {
logger.warn("Tailscale key failed — continuing without Tailscale", { error: String(err) });
}
}
// 4. Create block volume if configured
let volumeId: string | null = null;
if (this.doVolumeGb > 0) {
const volName = `timmy-data-${jobId.slice(0, 8)}`;
volumeId = await createVolume(volName, this.doVolumeGb, this.doRegion, this.doToken);
logger.info("block volume created", { volumeId, sizeGb: this.doVolumeGb });
}
// 5. Create droplet
const userData = buildCloudInitScript(tailscaleAuthKey);
const dropletPayload: Record<string, unknown> = {
name: `timmy-node-${jobId.slice(0, 8)}`,
region: this.doRegion,
size: this.doSize,
image: "ubuntu-22-04-x64",
ssh_keys: [sshKeyId],
user_data: userData,
tags: ["timmy-node"],
constructor(config?: Partial<ProvisionerConfig>) {
this.config = {
doApiToken: config?.doApiToken ?? process.env.DO_API_TOKEN ?? "",
doRegion: config?.doRegion ?? process.env.DO_REGION ?? "nyc3",
doSize: config?.doSize ?? process.env.DO_SIZE ?? "s-2vcpu-4gb",
doVolumeSizeGb: config?.doVolumeSizeGb ?? parseInt(process.env.DO_VOLUME_SIZE_GB ?? "100", 10),
doVpcUuid: config?.doVpcUuid ?? process.env.DO_VPC_UUID ?? "",
doSshKeyFingerprint: config?.doSshKeyFingerprint ?? process.env.DO_SSH_KEY_FINGERPRINT ?? "",
tailscaleApiKey: config?.tailscaleApiKey ?? process.env.TAILSCALE_API_KEY ?? "",
tailscaleTailnet: config?.tailscaleTailnet ?? process.env.TAILSCALE_TAILNET ?? "",
};
if (volumeId) dropletPayload.volumes = [volumeId];
this.stubMode = !this.config.doApiToken || !this.config.tailscaleApiKey;
if (this.stubMode) {
logger.warn("no DO_API_TOKEN or TAILSCALE_API_KEY — running in STUB mode", { stub: true });
} else {
logger.info("Provisioner real mode active", { stub: false });
}
}
const dropletData = await doPost<{ droplet: { id: number } }>(
"/droplets",
this.doToken,
dropletPayload,
);
const dropletId = dropletData.droplet.id;
logger.info("droplet created", { bootstrapJobId: jobId, dropletId });
async provisionNode(jobId: string): Promise<{
dropletId: string;
nodeIp: string;
tailscaleHostname: string;
lnbitsUrl: string;
sshPrivateKey: string;
}> {
if (this.stubMode) {
logger.info("stub provisioning node", { jobId });
const fakeSshPrivateKey = `-----BEGIN OPENSSH PRIVATE KEY-----
FakeKeyForJob${jobId}
-----END OPENSSH PRIVATE KEY-----`;
const fakeTailscaleHostname = `fake-node-${jobId.slice(0, 8)}`;
const fakeNodeIp = `192.168.0.${Math.floor(Math.random() * 255)}`;
const fakeLnbitsUrl = `http://${fakeNodeIp}:3000/lnbits`;
const result = {
dropletId: `fake-droplet-${jobId}`,
nodeIp: fakeNodeIp,
tailscaleHostname: fakeTailscaleHostname,
lnbitsUrl: fakeLnbitsUrl,
sshPrivateKey: fakeSshPrivateKey,
};
stubProvisioningResults.set(jobId, result);
await new Promise(resolve => setTimeout(resolve, 2000)); // Simulate delay
return result;
}
// 6. Poll for public IP (up to 2 min)
const nodeIp = await pollDropletIp(dropletId, this.doToken, 120_000);
logger.info("node ip assigned", { bootstrapJobId: jobId, nodeIp: nodeIp ?? "(not yet assigned)" });
// Real provisioning logic
const { sshPrivateKey, sshPublicKey } = await this.generateSshKeyPair();
const tailscaleAuthKey = await this.createTailscaleAuthKey();
const cloudConfig = this.buildCloudInitScript(sshPublicKey, tailscaleAuthKey);
// 7. Tailscale hostname
const tailscaleHostname =
tailscaleAuthKey && this.tsTailnet
? `timmy-node-${jobId.slice(0, 8)}.${this.tsTailnet}.ts.net`
: null;
logger.info("creating Digital Ocean droplet", { jobId });
// LNbits listens on port 3000 (HTTP). Tailscale encrypts the link at the
// network layer, so http:// is correct — no TLS termination on the service.
const lnbitsUrl = tailscaleHostname
? `http://${tailscaleHostname}:3000`
: nodeIp
? `http://${nodeIp}:3000`
: null;
const dropletName = `timmy-node-${jobId.slice(0, 8)}`;
const createDropletCmd = [
`doctl compute droplet create ${dropletName}`,
`--region ${this.config.doRegion}`,
`--size ${this.config.doSize}`,
`--image ubuntu-22-04-x64`,
`--enable-private-networking`,
`--vpc-uuid ${this.config.doVpcUuid}`,
`--user-data '${cloudConfig}'`,
`--ssh-keys ${this.config.doSshKeyFingerprint}`,
`--format ID --no-header`,
].join(" \\\n ");
await db
.update(bootstrapJobs)
.set({
state: "ready",
dropletId: String(dropletId),
nodeIp,
tailscaleHostname,
lnbitsUrl,
sshPrivateKey: privateKey,
updatedAt: new Date(),
})
.where(eq(bootstrapJobs.id, jobId));
const { stdout } = await execAsync(createDropletCmd);
const dropletId = stdout.trim();
logger.info("real provisioning complete", { bootstrapJobId: jobId });
logger.info("simulating droplet creation and IP assignment", { jobId, dropletId });
await new Promise(resolve => setTimeout(resolve, 10000)); // Simulate droplet creation time
const nodeIp = `1.2.3.${Math.floor(Math.random() * 255)}`; // Dummy IP
const tailscaleHostname = `${dropletName}.tail${this.config.tailscaleTailnet.slice(0, 4)}.ts.net`; // Dummy hostname
const lnbitsUrl = `http://${nodeIp}:3000/lnbits`; // Dummy LNbits URL
return {
dropletId,
nodeIp,
tailscaleHostname,
lnbitsUrl,
sshPrivateKey,
};
}
// Helper to generate SSH keypair using ssh-keygen
private async generateSshKeyPair(): Promise<{ sshPrivateKey: string; sshPublicKey: string }> {
logger.info("generating SSH keypair");
const keyPath = `/tmp/id_rsa_${randomBytes(4).toString("hex")}`;
await execAsync(`ssh-keygen -t rsa -b 4096 -f ${keyPath} -N ""`);
const { stdout: privOut } = await execAsync(`cat ${keyPath}`);
const { stdout: pubOut } = await execAsync(`cat ${keyPath}.pub`);
await execAsync(`rm ${keyPath} ${keyPath}.pub`);
return { sshPrivateKey: privOut.trim(), sshPublicKey: pubOut.trim() };
}
// Helper to create Tailscale auth key (simplified stub)
private async createTailscaleAuthKey(): Promise<string> {
logger.info("creating Tailscale auth key (stub)");
await new Promise(resolve => setTimeout(resolve, 1000)); // Simulate API call
return `tskey-test-${randomBytes(16).toString("hex")}`;
}
// Helper to build cloud-init script
private buildCloudInitScript(sshPublicKey: string, tailscaleAuthKey: string): string {
logger.info("building cloud-init script");
const baseUrl = `http://143.198.27.163:3000/replit/timmy-tower/raw/branch/main/infrastructure`;
return `
#cloud-config
users:
- name: ubuntu
ssh_authorized_keys:
- ${sshPublicKey}
sudo: ALL=(ALL) NOPASSWD:ALL
write_files:
- path: /root/setup.sh
permissions: '0755'
content: |
#!/usr/bin/env bash
curl -s ${baseUrl}/setup.sh > /root/setup.sh
runcmd:
- mkdir -p /root/configs
- curl -s ${baseUrl}/setup.sh > /tmp/setup.sh
- chmod +x /tmp/setup.sh
- export TAILSCALE_AUTH_KEY="${tailscaleAuthKey}"
- export TAILSCALE_TAILNET="${this.config.tailscaleTailnet}"
- /tmp/setup.sh
`;
}
}

View File

@@ -1,214 +1,190 @@
import { Router, type Request, type Response } from "express";
import { randomUUID } from "crypto";
import { db, bootstrapJobs, type BootstrapJob } from "@workspace/db";
import { db, bootstrapJobs, invoices, type BootstrapJob } from "@workspace/db";
import { eq, and } from "drizzle-orm";
import { lnbitsService } from "../lib/lnbits.js";
import { pricingService } from "../lib/pricing.js";
import { provisionerService } from "../lib/provisioner.js";
import { makeLogger } from "../lib/logger.js";
// Assuming a Zod schema for request body and params will be created
// import { CreateBootstrapJobBody, GetBootstrapJobParams } from "@workspace/api-zod";
const logger = makeLogger("bootstrap");
const logger = makeLogger("bootstrap-routes");
const router = Router();
async function getBootstrapJobById(id: string): Promise<BootstrapJob | null> {
const rows = await db
.select()
.from(bootstrapJobs)
.where(eq(bootstrapJobs.id, id))
.limit(1);
const rows = await db.select().from(bootstrapJobs).where(eq(bootstrapJobs.id, id)).limit(1);
return rows[0] ?? null;
}
async function getInvoiceById(id: string) {
const rows = await db.select().from(invoices).where(eq(invoices.id, id)).limit(1);
return rows[0] ?? null;
}
/**
* Advances the bootstrap job state machine on each poll.
*
* awaiting_payment → (payment confirmed) → provisioning
* (provisioner runs async and writes ready/failed to DB)
*
* Returns the refreshed job, or null if a DB read is needed.
* Runs the node provisioning in a background task so HTTP polls return fast.
*/
async function advanceBootstrapJob(job: BootstrapJob): Promise<BootstrapJob | null> {
if (job.state !== "awaiting_payment") return job;
async function runProvisioningInBackground(jobId: string): Promise<void> {
try {
logger.info("starting node provisioning", { jobId });
await db.update(bootstrapJobs).set({ state: "provisioning", updatedAt: new Date() }).where(eq(bootstrapJobs.id, jobId));
const isPaid = await lnbitsService.checkInvoicePaid(job.paymentHash);
if (!isPaid) return job;
const provisionResult = await provisionerService.provisionNode(jobId);
// Guard: only advance if still awaiting_payment — prevents duplicate provisioning
// on concurrent polls (each poll independently confirms payment).
const updated = await db
.update(bootstrapJobs)
.set({ state: "provisioning", updatedAt: new Date() })
.where(and(eq(bootstrapJobs.id, job.id), eq(bootstrapJobs.state, "awaiting_payment")))
.returning();
await db
.update(bootstrapJobs)
.set({
state: "ready",
dropletId: provisionResult.dropletId,
nodeIp: provisionResult.nodeIp,
tailscaleHostname: provisionResult.tailscaleHostname,
lnbitsUrl: provisionResult.lnbitsUrl,
sshPrivateKey: provisionResult.sshPrivateKey, // Stored once, cleared after delivery
updatedAt: new Date(),
})
.where(eq(bootstrapJobs.id, jobId));
if (updated.length === 0) {
// Another concurrent request already advanced the state — just re-fetch.
return getBootstrapJobById(job.id);
logger.info("node provisioning complete", { jobId, dropletId: provisionResult.dropletId });
} catch (err) {
const message = err instanceof Error ? err.message : "Node provisioning error";
logger.error("node provisioning failed", { jobId, error: message });
await db
.update(bootstrapJobs)
.set({ state: "failed", errorMessage: message, updatedAt: new Date() })
.where(eq(bootstrapJobs.id, jobId));
}
logger.info("bootstrap payment confirmed — starting provisioning", { bootstrapJobId: job.id });
// Fire-and-forget: provisioner updates DB when done
void provisionerService.provision(job.id);
return { ...job, state: "provisioning" };
}
/**
* POST /api/bootstrap
*
* Creates a bootstrap job and returns the Lightning invoice.
* Checks whether the bootstrap invoice has been paid and, if so,
* advances the state machine.
*/
router.post("/bootstrap", async (req: Request, res: Response) => {
try {
const fee = pricingService.calculateBootstrapFeeSats();
const jobId = randomUUID();
async function advanceBootstrapJob(job: BootstrapJob): Promise<BootstrapJob | null> {
if (job.state === "awaiting_payment") {
// Assuming invoice details are directly on the bootstrapJob, not a separate invoice table
// If a separate invoice entry is needed, uncomment the invoice related logic from jobs.ts
const isPaid = await lnbitsService.checkInvoicePaid(job.paymentHash);
if (!isPaid) return job;
const invoice = await lnbitsService.createInvoice(
fee,
`Node bootstrap fee — job ${jobId}`,
);
const advanced = await db.transaction(async (tx) => {
// For now, we update the bootstrap job directly. If we had a separate `invoices` table
// linked to bootstrap jobs, we would update that too.
const updated = await tx
.update(bootstrapJobs)
.set({ state: "provisioning", updatedAt: new Date() })
.where(and(eq(bootstrapJobs.id, job.id), eq(bootstrapJobs.state, "awaiting_payment")))
.returning();
return updated.length > 0;
});
if (!advanced) return getBootstrapJobById(job.id);
logger.info("bootstrap invoice paid", { bootstrapJobId: job.id, paymentHash: job.paymentHash });
// Fire provisioning in background — poll returns immediately with "provisioning"
setImmediate(() => { void runProvisioningInBackground(job.id); });
return getBootstrapJobById(job.id);
}
return job;
}
// ── POST /api/bootstrap ──────────────────────────────────────────────────────
router.post("/bootstrap", async (req: Request, res: Response) => {
// No request body for now, just trigger bootstrap
try {
const bootstrapFeeSats = pricingService.calculateBootstrapFeeSats();
const jobId = randomUUID();
const createdAt = new Date();
const lnbitsInvoice = await lnbitsService.createInvoice(bootstrapFeeSats, `Node bootstrap fee for job ${jobId}`);
await db.insert(bootstrapJobs).values({
id: jobId,
state: "awaiting_payment",
amountSats: fee,
paymentHash: invoice.paymentHash,
paymentRequest: invoice.paymentRequest,
amountSats: bootstrapFeeSats,
paymentHash: lnbitsInvoice.paymentHash,
paymentRequest: lnbitsInvoice.paymentRequest,
createdAt,
updatedAt: createdAt,
});
logger.info("bootstrap job created", {
jobId,
amountSats: bootstrapFeeSats,
stubMode: lnbitsService.stubMode,
});
res.status(201).json({
bootstrapJobId: jobId,
invoice: {
paymentRequest: invoice.paymentRequest,
amountSats: fee,
paymentHash: invoice.paymentHash,
jobId,
createdAt: createdAt.toISOString(),
bootstrapInvoice: {
paymentRequest: lnbitsInvoice.paymentRequest,
amountSats: bootstrapFeeSats,
paymentHash: lnbitsInvoice.paymentHash,
},
stubMode: lnbitsService.stubMode || provisionerService.stubMode,
message: `Simulate payment with POST /api/dev/stub/pay/${invoice.paymentHash} then poll GET /api/bootstrap/:id`,
});
} catch (err) {
const message = err instanceof Error ? err.message : "Failed to create bootstrap job";
logger.error("bootstrap job creation failed", { error: message });
res.status(500).json({ error: message });
}
});
/**
* GET /api/bootstrap/:id
*
* Polls status. Triggers provisioning once payment is confirmed.
* Returns credentials (SSH key delivered once, then cleared) when ready.
*/
// ── GET /api/bootstrap/:id ───────────────────────────────────────────────────
router.get("/bootstrap/:id", async (req: Request, res: Response) => {
const { id } = req.params;
if (!id || typeof id !== "string") {
res.status(400).json({ error: "Invalid bootstrap job id" });
return;
}
const id = String(req.params["id"] ?? ""); // cast: Express 5 params are string
try {
let job = await getBootstrapJobById(id);
if (!job) {
res.status(404).json({ error: "Bootstrap job not found" });
return;
}
if (!job) { res.status(404).json({ error: "Bootstrap job not found" }); return; }
const advanced = await advanceBootstrapJob(job);
if (advanced) job = advanced;
const base = {
bootstrapJobId: job.id,
// Remove SSH private key from response if it has been delivered
const sshPrivateKey = job.sshPrivateKey && !job.sshKeyDelivered ? job.sshPrivateKey : undefined;
res.json({
jobId: job.id,
state: job.state,
createdAt: job.createdAt.toISOString(),
updatedAt: job.updatedAt.toISOString(),
amountSats: job.amountSats,
createdAt: job.createdAt,
};
...(job.state === "awaiting_payment" ? {
bootstrapInvoice: {
paymentRequest: job.paymentRequest,
amountSats: job.amountSats,
paymentHash: job.paymentHash,
},
} : {}),
...(job.state === "ready" ? {
dropletId: job.dropletId,
nodeIp: job.nodeIp,
tailscaleHostname: job.tailscaleHostname,
lnbitsUrl: job.lnbitsUrl,
sshPrivateKey: sshPrivateKey, // Only return if not yet delivered
sshKeyDelivered: job.sshKeyDelivered,
} : {}),
...(job.state === "failed" ? { errorMessage: job.errorMessage } : {}),
});
switch (job.state) {
case "awaiting_payment":
res.json({
...base,
invoice: {
paymentRequest: job.paymentRequest,
amountSats: job.amountSats,
paymentHash: job.paymentHash,
},
message: "Waiting for Lightning payment",
});
break;
case "provisioning":
res.json({
...base,
message: "Payment confirmed — provisioning your Bitcoin node. Poll again in ~30 s.",
});
break;
case "ready": {
// Atomic one-time SSH key delivery: only the request that wins the
// guarded UPDATE (WHERE ssh_key_delivered = false) delivers the key.
// Concurrent first-reads both see delivered=false in the pre-fetched
// job, but only one UPDATE matches — the other gets 0 rows and falls
// back to the "already delivered" note.
let sshPrivateKey: string | null = null;
let keyNote: string | null = null;
if (!job.sshKeyDelivered && job.sshPrivateKey) {
const won = await db
.update(bootstrapJobs)
.set({ sshKeyDelivered: true, sshPrivateKey: null, updatedAt: new Date() })
.where(and(eq(bootstrapJobs.id, job.id), eq(bootstrapJobs.sshKeyDelivered, false)))
.returning({ id: bootstrapJobs.id });
if (won.length > 0) {
// This request won the delivery race — return the key we pre-read.
sshPrivateKey = job.sshPrivateKey;
} else {
keyNote = "SSH private key was delivered on a concurrent request — check your records";
}
} else {
keyNote = "SSH private key was delivered on first retrieval — check your records";
}
res.json({
...base,
credentials: {
nodeIp: job.nodeIp,
tailscaleHostname: job.tailscaleHostname,
lnbitsUrl: job.lnbitsUrl,
sshPrivateKey,
...(keyNote ? { sshKeyNote: keyNote } : {}),
},
nextSteps: [
`SSH into your node using the private key above: ssh -i <key_file> root@${job.nodeIp ?? "<nodeIp>"}`,
"Read your node credentials: cat /root/node-credentials.txt",
"Monitor Bitcoin sync (takes 1-2 weeks to reach 100%): bash /opt/timmy-node/ops.sh sync",
"Once sync is complete, fund your LND wallet, then open LNbits to create your wallet and get the API key",
"Set LNBITS_URL and LNBITS_API_KEY in your Timmy deployment to enable payment processing",
],
stubMode: provisionerService.stubMode,
message: provisionerService.stubMode
? "Stub mode — these are fake credentials. Set DO_API_TOKEN for real provisioning."
: "Your node is being bootstrapped. Bitcoin sync has started.",
});
break;
}
case "failed":
res.json({
...base,
errorMessage: job.errorMessage,
message: "Provisioning failed. Contact the operator for a refund.",
});
break;
default:
res.json(base);
// Mark SSH key as delivered after it's returned to the user once
if (job.sshPrivateKey && !job.sshKeyDelivered && job.state === "ready") {
await db.update(bootstrapJobs).set({ sshKeyDelivered: true, updatedAt: new Date() }).where(eq(bootstrapJobs.id, id));
logger.info("SSH private key marked as delivered", { jobId: job.id });
}
} catch (err) {
const message = err instanceof Error ? err.message : "Failed to fetch bootstrap job";
logger.error("bootstrap job fetch failed", { error: message });
res.status(500).json({ error: message });
}
});
export default router;
export default router;

View File

@@ -38,6 +38,9 @@ const logger = makeLogger("ws-events");
const PING_INTERVAL_MS = 30_000;
// Map to store visitorId -> npub mappings
const connectedVisitors = new Map<string, string>();
// ── Per-visitor rate limit (3 replies/minute) ─────────────────────────────────
const CHAT_RATE_LIMIT = 3;
const CHAT_RATE_WINDOW_MS = 60_000;
@@ -257,6 +260,15 @@ function translateEvent(ev: BusEvent): object | null {
isFinal: ev.isFinal,
};
// ── Agent commentary (#1) ─────────────────────────────────────────────────
case "agent_commentary":
return {
type: "agent_commentary",
agentId: ev.agentId,
jobId: ev.jobId,
text: ev.text,
};
default:
return null;
}
@@ -314,12 +326,19 @@ export function attachWebSocketServer(server: Server): void {
socket.on("message", (raw) => {
try {
const msg = JSON.parse(raw.toString()) as { type?: string; text?: string; visitorId?: string };
const msg = JSON.parse(raw.toString()) as { type?: string; text?: string; visitorId?: string; npub?: string };
if (msg.type === "pong") return;
if (msg.type === "subscribe") {
send(socket, { type: "agent_count", count: wss.clients.size });
}
if (msg.type === "visitor_enter") {
const { visitorId, npub } = msg;
if (visitorId && npub) {
connectedVisitors.set(visitorId, npub);
const formattedNpub = `${npub.slice(0, 8)}${npub.slice(-4)}`;
broadcastToAll(wss, { type: "chat", agentId: "timmy", text: `Welcome, Nostr user ${formattedNpub}! What can I help you with?` });
}
wss.clients.forEach(c => {
if (c !== socket && c.readyState === 1) {
c.send(JSON.stringify({ type: "visitor_count", count: wss.clients.size }));
@@ -328,6 +347,10 @@ export function attachWebSocketServer(server: Server): void {
send(socket, { type: "visitor_count", count: wss.clients.size });
}
if (msg.type === "visitor_leave") {
const { visitorId } = msg;
if (visitorId) {
connectedVisitors.delete(visitorId);
}
wss.clients.forEach(c => {
if (c !== socket && c.readyState === 1) {
c.send(JSON.stringify({ type: "visitor_count", count: Math.max(0, wss.clients.size - 1) }));
@@ -389,5 +412,50 @@ export function attachWebSocketServer(server: Server): void {
});
});
// ── Global commentary listener (set up once per server, not per socket) ────
// Watches job lifecycle events and fires Haiku commentary to all clients.
eventBus.on("bus", (ev: BusEvent) => {
let agentId: string | null = null;
let phase: string | null = null;
let jobId: string | null = null;
if (ev.type === "job:state") {
jobId = ev.jobId;
if (ev.state === "evaluating") {
// Beta evaluating + Alpha routing
void (async () => {
const [betaText, alphaText] = await Promise.all([
agentService.generateCommentary("beta", "evaluating"),
agentService.generateCommentary("alpha", "routing"),
]);
if (betaText) broadcastToAll(wss, { type: "agent_commentary", agentId: "beta", jobId, text: betaText });
if (alphaText) broadcastToAll(wss, { type: "agent_commentary", agentId: "alpha", jobId, text: alphaText });
})();
return;
}
if (ev.state === "executing") {
agentId = "gamma"; phase = "starting";
} else if (ev.state === "complete") {
agentId = "alpha"; phase = "complete";
} else if (ev.state === "rejected") {
agentId = "alpha"; phase = "rejected";
}
} else if (ev.type === "job:paid") {
jobId = ev.jobId;
agentId = "delta";
phase = ev.invoiceType === "eval" ? "eval_paid" : "work_paid";
}
if (agentId && phase && jobId) {
const capturedAgentId = agentId;
const capturedPhase = phase;
const capturedJobId = jobId;
void (async () => {
const text = await agentService.generateCommentary(capturedAgentId, capturedPhase);
if (text) broadcastToAll(wss, { type: "agent_commentary", agentId: capturedAgentId, jobId: capturedJobId, text });
})();
}
});
logger.info("WebSocket server attached at /api/ws");
}

View File

@@ -17,11 +17,13 @@ import relayRouter from "./relay.js";
import adminRelayRouter from "./admin-relay.js";
import adminRelayQueueRouter from "./admin-relay-queue.js";
import geminiRouter from "./gemini.js";
import statsRouter from "./stats.js";
const router: IRouter = Router();
router.use(healthRouter);
router.use(metricsRouter);
router.use(statsRouter);
router.use(jobsRouter);
router.use(estimateRouter);
router.use(bootstrapRouter);

View File

@@ -0,0 +1,88 @@
import { type Request, Router } from "express";
import { makeLogger } from "../lib/logger.js";
const router = Router();
const log = makeLogger("relay-policy");
// ── Auth ──────────────────────────────────────────────────────────────────────
const RELAY_POLICY_SECRET = process.env["RELAY_POLICY_SECRET"] ?? "";
if (!RELAY_POLICY_SECRET) {
log.warn("RELAY_POLICY_SECRET is not set — /api/relay/policy will be unauthenticated!");
}
function isAuthenticated(req: Request): boolean {
if (!RELAY_POLICY_SECRET) {
return true; // No secret configured, so no auth.
}
const authz = req.headers["authorization"];
if (!authz) {
return false;
}
const [scheme, token] = authz.split(" ");
if (scheme !== "Bearer" || token !== RELAY_POLICY_SECRET) {
return false;
}
return true;
}
// ── Request body shape (manual validation — zod not in deps) ──────────────────
interface StrfryEventBody {
event?: {
id?: unknown;
pubkey?: unknown;
kind?: unknown;
created_at?: unknown;
tags?: unknown;
content?: unknown;
sig?: unknown;
};
receivedAt?: unknown;
sourceType?: unknown;
sourceInfo?: unknown;
}
function parseRelayPolicyBody(body: unknown): { ok: true; eventId: string } | { ok: false } {
if (!body || typeof body !== "object") return { ok: false };
const b = body as StrfryEventBody;
if (!b.event || typeof b.event !== "object") return { ok: false };
const id = b.event.id;
if (typeof id !== "string" || !id) return { ok: false };
return { ok: true, eventId: id };
}
type StrfryAction = "accept" | "reject" | "shadowReject";
router.post("/relay/policy", (req, res) => {
if (!isAuthenticated(req)) {
res.status(401).json({
action: "reject",
msg: "unauthorized",
});
return;
}
const parsed = parseRelayPolicyBody(req.body);
if (!parsed.ok) {
log.warn("invalid /relay/policy request");
res.status(400).json({
action: "reject",
msg: "invalid request",
});
return;
}
const { eventId } = parsed;
// Bootstrap state: reject everything.
// This will be extended by whitelist + moderation tasks.
const action: StrfryAction = "reject";
const msg = "bootstrapped: all events rejected";
log.info("policy decision", { eventId: eventId.slice(0, 8), action, msg });
res.json({ id: eventId, action, msg });
});
export default router;

View File

@@ -228,6 +228,7 @@ router.get("/sessions/:id", async (req: Request, res: Response) => {
.update(sessions)
.set({ state: "expired", updatedAt: new Date() })
.where(eq(sessions.id, id));
await db.delete(sessionMessages).where(eq(sessionMessages.sessionId, id));
session = (await getSessionById(id))!;
}
@@ -314,6 +315,11 @@ router.post("/sessions/:id/request", async (req: Request, res: Response) => {
// Load conversation history for context injection
const history = await getSessionHistory(id, 8, 4000);
// Defensive check: log a warning if history still exceeds budget
const currentTokenCount = history.reduce((sum, msg) => sum + Math.ceil(msg.content.length / 4), 0);
if (currentTokenCount > 4000) {
console.warn(`Session ${id}: History exceeds 4000 token budget after retrieval. Actual: ${currentTokenCount}`);
}
// Eval phase
const evalResult = await agentService.evaluateRequest(requestText);
@@ -574,4 +580,32 @@ router.post("/sessions/:id/topup", async (req: Request, res: Response) => {
}
});
// ── DELETE /sessions/:id/history ─────────────────────────────────────────────
router.delete("/sessions/:id/history", async (req: Request, res: Response) => {
const id = req.params.id as string;
const macaroon = extractMacaroon(req);
try {
const session = await getSessionById(id);
if (!session) { res.status(404).json({ error: "Session not found" }); return; }
if (!macaroon || macaroon !== session.macaroon) {
res.status(401).json({ error: "Invalid or missing macaroon. Include 'Authorization: Bearer <macaroon>' header." });
return;
}
if (checkExpired(session) || session.state === "expired") {
res.status(410).json({ error: "Session has expired" });
return;
}
await db.delete(sessionMessages).where(eq(sessionMessages.sessionId, id));
res.json({ cleared: true });
} catch (err) {
res.status(500).json({ error: err instanceof Error ? err.message : "Failed to clear history" });
}
});
export default router;

View File

@@ -0,0 +1,59 @@
import { Router, type Request, type Response } from "express";
import { db, jobs } from "@workspace/db";
import { sql, gte } from "drizzle-orm";
import { makeLogger } from "../lib/logger.js";
const router = Router();
const logger = makeLogger("stats");
/**
* GET /api/stats/activity
*
* Returns job counts bucketed by hour for the past 24 hours.
* Each bucket represents a UTC hour (023).
* Hours with no activity are included as 0.
*
* Response shape:
* { hours: number[24], generatedAt: string }
* hours[0] = oldest hour (24h ago), hours[23] = current hour
*/
router.get("/api/stats/activity", async (_req: Request, res: Response) => {
try {
const now = new Date();
const windowStart = new Date(now.getTime() - 24 * 60 * 60 * 1000);
// Count completed jobs grouped by the hour they were created,
// within the last 24h window.
const rows = await db
.select({
hour: sql<number>`cast(extract(epoch from date_trunc('hour', created_at)) as bigint)`,
count: sql<number>`cast(count(*) as int)`,
})
.from(jobs)
.where(gte(jobs.createdAt, windowStart))
.groupBy(sql`date_trunc('hour', created_at)`);
// Build a map: epoch-hour → count
const byEpochHour = new Map<number, number>();
for (const row of rows) {
byEpochHour.set(Number(row.hour), Number(row.count));
}
// Build 24-slot array aligned to whole hours, oldest first.
// slot 0 = floor(now - 24h), slot 23 = floor(now)
const currentHourEpoch = Math.floor(now.getTime() / (3600 * 1000)) * 3600;
const hours: number[] = [];
for (let i = 23; i >= 0; i--) {
const slotEpoch = currentHourEpoch - i * 3600;
hours.push(byEpochHour.get(slotEpoch) ?? 0);
}
res.json({ hours, generatedAt: now.toISOString() });
} catch (err) {
const message = err instanceof Error ? err.message : "Failed to fetch activity stats";
logger.error("activity stats failed", { error: message });
res.status(500).json({ error: message });
}
});
export default router;

View File

@@ -37,7 +37,8 @@
"expo-web-browser"
],
"extra": {
"apiDomain": "${EXPO_PUBLIC_DOMAIN}"
"apiDomain": "${EXPO_PUBLIC_DOMAIN}",
"gitCommitHash": "${EXPO_PUBLIC_GIT_SHA}"
},
"experiments": {
"typedRoutes": true,

View File

@@ -1,11 +1,11 @@
import { BlurView } from "expo-blur";
import { isLiquidGlassAvailable } from "expo-glass-effect";
import { Tabs } from "expo-router";
import { Link, Tabs } from "expo-router";
import { Icon, Label, NativeTabs } from "expo-router/unstable-native-tabs";
import { SymbolView } from "expo-symbols";
import { Feather, MaterialCommunityIcons } from "@expo/vector-icons";
import { Feather, MaterialCommunityIcons, Ionicons } from "@expo/vector-icons";
import React from "react";
import { Platform, StyleSheet, View, useColorScheme } from "react-native";
import { Platform, Pressable, StyleSheet, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Colors } from "@/constants/colors";
@@ -35,6 +35,8 @@ function ClassicTabLayout() {
const isWeb = Platform.OS === "web";
const C = Colors.dark;
void insets; // used by callers that extend this
return (
<Tabs
screenOptions={{
@@ -68,6 +70,14 @@ function ClassicTabLayout() {
name="index"
options={{
title: "Timmy",
headerShown: true,
headerRight: () => (
<Link href="/settings" asChild>
<Pressable style={({ pressed }) => ({ opacity: pressed ? 0.5 : 1 })}>
<Ionicons name="settings-outline" size={24} color={C.text} style={{ marginRight: 15 }} />
</Pressable>
</Link>
),
tabBarIcon: ({ color, size }) =>
isIOS ? (
<SymbolView name="face.smiling" tintColor={color} size={size} />

View File

@@ -50,6 +50,7 @@ function RootLayoutNav() {
<Stack screenOptions={{ headerBackTitle: "Back" }}>
<Stack.Screen name="onboarding" options={{ headerShown: false, animation: "none" }} />
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
<Stack.Screen name="settings" options={{ headerShown: false, presentation: "modal" }} />
</Stack>
);
}

View File

@@ -0,0 +1,176 @@
import { Stack } from 'expo-router';
import { View, Text, StyleSheet, ScrollView, TextInput, Switch, Pressable, Linking, Platform } from 'react-native';
import { useState, useEffect } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import Constants from 'expo-constants';
import { useTimmy } from '@/context/TimmyContext';
import { Ionicons } from '@expo/vector-icons';
import { ConnectionBadge } from '@/components/ConnectionBadge';
import { Colors } from '@/constants/colors';
const STORAGE_KEYS = {
SERVER_URL: 'settings_server_url',
NOTIFICATIONS_JOB_COMPLETION: 'settings_notifications_job_completion',
NOTIFICATIONS_LOW_BALANCE: 'settings_notifications_low_balance',
};
export default function SettingsScreen() {
const { connectionStatus } = useTimmy();
const C = Colors.dark;
const [serverUrl, setServerUrl] = useState('');
const [jobCompletionNotifications, setJobCompletionNotifications] = useState(false);
const [lowBalanceWarning, setLowBalanceWarning] = useState(false);
useEffect(() => {
const loadSettings = async () => {
const storedServerUrl = await AsyncStorage.getItem(STORAGE_KEYS.SERVER_URL);
if (storedServerUrl) setServerUrl(storedServerUrl);
const storedJobCompletion = await AsyncStorage.getItem(STORAGE_KEYS.NOTIFICATIONS_JOB_COMPLETION);
if (storedJobCompletion !== null) setJobCompletionNotifications(JSON.parse(storedJobCompletion));
const storedLowBalance = await AsyncStorage.getItem(STORAGE_KEYS.NOTIFICATIONS_LOW_BALANCE);
if (storedLowBalance !== null) setLowBalanceWarning(JSON.parse(storedLowBalance));
};
loadSettings();
}, []);
const handleServerUrlSave = async () => {
await AsyncStorage.setItem(STORAGE_KEYS.SERVER_URL, serverUrl);
};
const toggleJobCompletionNotifications = async () => {
const newValue = !jobCompletionNotifications;
setJobCompletionNotifications(newValue);
await AsyncStorage.setItem(STORAGE_KEYS.NOTIFICATIONS_JOB_COMPLETION, JSON.stringify(newValue));
};
const toggleLowBalanceWarning = async () => {
const newValue = !lowBalanceWarning;
setLowBalanceWarning(newValue);
await AsyncStorage.setItem(STORAGE_KEYS.NOTIFICATIONS_LOW_BALANCE, JSON.stringify(newValue));
};
const appVersion = Constants.expoConfig?.version ?? 'N/A';
const buildCommitHash = (Constants.expoConfig?.extra as Record<string, string> | undefined)?.gitCommitHash ?? 'N/A';
const giteaRepoUrl = 'http://143.198.27.163:3000/replit/timmy-tower';
const openGiteaLink = () => { Linking.openURL(giteaRepoUrl); };
return (
<View style={styles.container}>
<Stack.Screen options={{ title: 'Settings', headerShown: true, headerStyle: { backgroundColor: C.surface }, headerTintColor: C.text }} />
<ScrollView contentContainerStyle={styles.scrollContent}>
<Text style={styles.sectionHeader}>Connection</Text>
<View style={styles.settingItem}>
<Text style={styles.settingLabel}>Server URL</Text>
<View style={styles.serverUrlContainer}>
<TextInput
style={[styles.input, { color: C.text, backgroundColor: C.surface }]}
value={serverUrl}
onChangeText={setServerUrl}
onBlur={handleServerUrlSave}
placeholder="Enter server URL"
placeholderTextColor={C.textMuted}
autoCapitalize="none"
autoCorrect={false}
/>
<ConnectionBadge status={connectionStatus} />
</View>
</View>
<Text style={styles.sectionHeader}>Notifications</Text>
<View style={styles.settingItem}>
<Text style={styles.settingLabel}>Job Completion Push Notifications</Text>
<Switch
trackColor={{ false: C.surface, true: C.accentGlow }}
thumbColor={Platform.OS === 'android' ? C.text : ''}
ios_backgroundColor={C.surface}
onValueChange={toggleJobCompletionNotifications}
value={jobCompletionNotifications}
/>
</View>
<View style={styles.settingItem}>
<Text style={styles.settingLabel}>Low Balance Warning</Text>
<Switch
trackColor={{ false: C.surface, true: C.accentGlow }}
thumbColor={Platform.OS === 'android' ? C.text : ''}
ios_backgroundColor={C.surface}
onValueChange={toggleLowBalanceWarning}
value={lowBalanceWarning}
/>
</View>
<Text style={styles.sectionHeader}>About</Text>
<View style={styles.settingItem}>
<Text style={styles.settingLabel}>App Version</Text>
<Text style={[styles.settingValue, { color: C.text }]}>{appVersion}</Text>
</View>
<View style={styles.settingItem}>
<Text style={styles.settingLabel}>Build Commit Hash</Text>
<Text style={[styles.settingValue, { color: C.text }]}>{buildCommitHash}</Text>
</View>
<Pressable onPress={openGiteaLink} style={({ pressed }) => [styles.linkButton, { opacity: pressed ? 0.8 : 1 }]}>
<Ionicons name="link" size={16} color={C.text} />
<Text style={[styles.linkButtonText, { color: C.accentGlow }]}>View project on Gitea</Text>
</Pressable>
</ScrollView>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: Colors.dark.background,
},
scrollContent: {
padding: 20,
paddingBottom: 40,
},
sectionHeader: {
fontSize: 18,
fontWeight: 'bold',
color: Colors.dark.text,
marginTop: 20,
marginBottom: 10,
},
settingItem: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingVertical: 12,
borderBottomWidth: 0.5,
borderBottomColor: Colors.dark.border,
},
settingLabel: {
fontSize: 16,
color: Colors.dark.text,
flex: 1,
},
settingValue: {
fontSize: 16,
},
serverUrlContainer: {
flexDirection: 'row',
alignItems: 'center',
flex: 2,
},
input: {
flex: 1,
borderWidth: 1,
borderColor: Colors.dark.border,
borderRadius: 8,
padding: 8,
fontSize: 14,
marginRight: 10,
},
linkButton: {
flexDirection: 'row',
alignItems: 'center',
gap: 6,
paddingVertical: 12,
},
linkButtonText: {
fontSize: 16,
},
});

View File

@@ -4,7 +4,7 @@
"private": true,
"main": "expo-router/entry",
"scripts": {
"dev": "EXPO_PACKAGER_PROXY_URL=https://$REPLIT_EXPO_DEV_DOMAIN EXPO_PUBLIC_DOMAIN=$REPLIT_DEV_DOMAIN EXPO_PUBLIC_REPL_ID=$REPL_ID REACT_NATIVE_PACKAGER_HOSTNAME=$REPLIT_DEV_DOMAIN pnpm exec expo start --localhost --port $PORT",
"dev": "pnpm exec expo start --localhost --port 8081",
"build": "node scripts/build.js",
"serve": "node server/serve.js",
"typecheck": "tsc -p tsconfig.json --noEmit"

View File

@@ -1,6 +1,6 @@
const fs = require("fs");
const path = require("path");
const { spawn } = require("child_process");
const { spawn, execSync } = require("child_process");
const { Readable } = require("stream");
const { pipeline } = require("stream/promises");
@@ -127,6 +127,15 @@ function getExpoPublicReplId() {
return process.env.REPL_ID || process.env.EXPO_PUBLIC_REPL_ID;
}
function getGitSha() {
try {
return execSync("git rev-parse HEAD", { cwd: workspaceRoot }).toString().trim();
} catch (error) {
console.warn("Could not get git commit hash:", error.message);
return "unknown";
}
}
async function startMetro(expoPublicDomain, expoPublicReplId) {
const isRunning = await checkMetroHealth();
if (isRunning) {
@@ -136,10 +145,12 @@ async function startMetro(expoPublicDomain, expoPublicReplId) {
console.log("Starting Metro...");
console.log(`Setting EXPO_PUBLIC_DOMAIN=${expoPublicDomain}`);
const gitSha = getGitSha();
const env = {
...process.env,
EXPO_PUBLIC_DOMAIN: expoPublicDomain,
EXPO_PUBLIC_REPL_ID: expoPublicReplId,
EXPO_PUBLIC_GIT_SHA: gitSha,
};
if (expoPublicReplId) {

View File

@@ -115,6 +115,8 @@ The `costLedger` in `GET /api/jobs/:id` shows all figures side-by-side. If `refu
| `DO_REGION` | DO datacenter region | `nyc3` |
| `DO_SIZE` | DO droplet size slug | `s-4vcpu-8gb` |
| `DO_VOLUME_SIZE_GB` | Block volume to attach in GB (`0` = none) | `0` |
| `DO_VPC_UUID` | Digital Ocean VPC UUID to deploy droplet into | (required) |
| `DO_SSH_KEY_FINGERPRINT` | Digital Ocean SSH Key Fingerprint for droplet access | (required) |
| `TAILSCALE_API_KEY` | Tailscale API key for generating auth keys | optional |
| `TAILSCALE_TAILNET` | Tailscale tailnet name (e.g. `example.com`) | required with above |

View File

@@ -0,0 +1,38 @@
# Branch Audit — Issue #103
## Summary (2026-03-23)
### Unmerged branches reviewed
| Branch | Content | Status | Action |
|--------|---------|--------|--------|
| `gemini/issue-14` | NIP-07 Nostr identity | Unique diff vs main | **PR #104 opened** |
| `gemini/issue-42` | Timmy animated eyes | No diff vs main — already merged | Deleted |
| `claude/issue-11` | Kimi + Perplexity agents | No diff vs main — already merged | Deleted |
| `claude/issue-13` | Nostr event publishing | No diff vs main — already merged | Deleted |
| `claude/issue-29` | Mobile Nostr identity | No diff vs main — already merged | Deleted |
| `claude/issue-45` | Test kit | No diff vs main — already merged | Deleted |
| `claude/issue-47` | SQL migration helpers | No diff vs main — already merged | Deleted |
| `claude/issue-67` | Session Mode UI | No diff vs main — already merged | Deleted |
All 7 branches besides `gemini/issue-14` had empty `git diff origin/main...origin/<branch>`
output, confirming their work had been squash-merged into main previously.
### Stale merged branches deleted (37 branches)
Confirmed via `git diff origin/main...origin/<branch>` (empty diff):
**gemini branches:** issue-16, issue-34, issue-40, issue-42, issue-46, issue-48,
issue-50, issue-52, issue-56, issue-58, issue-64, issue-70
**claude branches:** issue-1, issue-3, issue-7, issue-9, issue-11, issue-13, issue-15,
issue-17, issue-21, issue-25, issue-27, issue-29, issue-31, issue-33, issue-35, issue-36,
issue-39, issue-41, issue-43, issue-45, issue-47, issue-49, issue-51, issue-53, issue-55,
issue-57, issue-59, issue-61, issue-63, issue-65, issue-67, issue-68
### Remaining branches after cleanup
| Branch | Status |
|--------|--------|
| `main` | Trunk |
| `claude/issue-5` | Open PR #93 |
| `claude/issue-37` | Open PR #80 |
| `gemini/issue-14` | New PR #104 (NIP-07 Nostr identity) |
| `claude/issue-103` | This audit branch |

View File

@@ -37,6 +37,25 @@
font-size: 13px; letter-spacing: 3px; margin-bottom: 4px;
color: #7799cc; text-shadow: 0 0 10px #4466aa;
}
/* Nostr Identity UI */
.nostr-btn {
background: rgba(40, 30, 70, 0.9);
border: 1px solid #443377;
color: #aaddff; font-family: 'Courier New', monospace;
font-size: 11px; padding: 4px 10px; cursor: pointer;
border-radius: 3px; transition: background 0.15s, border-color 0.15s;
}
.nostr-btn:hover { background: rgba(60, 45, 100, 0.9); border-color: #665599; }
.nostr-btn-sm {
font-size: 9px; padding: 2px 6px; margin-left: 6px; opacity: 0.7;
}
.nostr-btn-sm:hover { opacity: 1; }
.nostr-pubkey {
font-size: 11px; color: #aaddff; margin-right: 6px;
letter-spacing: 0.5px;
}
#session-hud {
display: none;
color: #22aa66;
@@ -514,6 +533,72 @@
}
#timmy-id-card .id-npub:hover { color: #88aadd; }
#timmy-id-card .id-zaps { color: #556688; font-size: 9px; }
/* ── Activity heatmap (#9) ────────────────────────────────────────── */
#activity-heatmap {
position: fixed; bottom: 80px; left: 50%; transform: translateX(-50%);
z-index: 10; pointer-events: all;
}
#heatmap-bar {
display: flex; gap: 2px; align-items: flex-end;
}
.hm-seg {
width: 10px; height: 18px; border-radius: 1px;
background: #111122;
cursor: pointer;
transition: transform 0.1s;
flex-shrink: 0;
}
.hm-seg:hover { transform: scaleY(1.3); }
@keyframes hm-pulse {
0%, 100% { opacity: 1; box-shadow: 0 0 4px currentColor; }
50% { opacity: 0.5; box-shadow: none; }
}
.hm-seg-current { animation: hm-pulse 2s ease-in-out infinite; }
#heatmap-icon-btn {
display: none;
background: rgba(20, 16, 36, 0.88);
border: 1px solid #2a2a44;
color: #5588bb;
font-family: 'Courier New', monospace;
font-size: 16px; padding: 6px 10px;
cursor: pointer; border-radius: 3px;
}
#heatmap-tooltip {
position: fixed; display: none;
background: rgba(5,3,12,0.92); border: 1px solid #2a2a44;
color: #aabbdd; font-family: 'Courier New', monospace;
font-size: 10px; padding: 3px 8px; border-radius: 2px;
pointer-events: none; z-index: 50;
white-space: nowrap;
}
/* Mobile overlay */
#heatmap-overlay {
display: none; position: fixed; inset: 0;
background: rgba(5,3,12,0.97); z-index: 100;
flex-direction: column; align-items: center; justify-content: center;
gap: 16px;
}
#heatmap-overlay.open { display: flex; }
#heatmap-overlay-title {
color: #7799cc; font-family: 'Courier New', monospace;
font-size: 12px; letter-spacing: 3px;
}
#heatmap-overlay-bar {
display: flex; gap: 4px; align-items: flex-end; flex-wrap: wrap;
justify-content: center; max-width: 90vw;
}
#heatmap-overlay-bar .hm-seg { width: 14px; height: 28px; }
#heatmap-overlay-close {
background: transparent; border: 1px solid #2a2a44;
color: #5588bb; font-family: 'Courier New', monospace;
font-size: 11px; padding: 6px 16px; cursor: pointer;
letter-spacing: 1px; border-radius: 2px;
}
@media (max-width: 600px) {
#activity-heatmap #heatmap-bar { display: none; }
#heatmap-icon-btn { display: block; }
}
</style>
</head>
<body>
@@ -525,11 +610,25 @@
<span id="session-hud-balance">Balance: -- sats</span>
<a href="#" id="session-hud-topup">⚡ Top Up</a>
</div>
<!-- New: Nostr identity status -->
<div id="nostr-identity-status" style="margin-top: 10px; pointer-events: all;"></div>
</div>
<div id="connection-status">OFFLINE</div>
<div id="event-log"></div>
<!-- ── Activity heatmap (#9) ──────────────────────────────────────── -->
<div id="activity-heatmap">
<div id="heatmap-bar"></div>
<button id="heatmap-icon-btn" title="Show activity heatmap"></button>
</div>
<div id="heatmap-tooltip"></div>
<div id="heatmap-overlay">
<div id="heatmap-overlay-title">24H ACTIVITY</div>
<div id="heatmap-overlay-bar"></div>
<button id="heatmap-overlay-close">CLOSE</button>
</div>
<!-- ── Timmy identity card ────────────────────────────────────────── -->
<div id="timmy-id-card">
<div class="id-label">TIMMY IDENTITY</div>

View File

@@ -10,6 +10,7 @@
* }>
* sentiment(text) → Promise<{ label:'POSITIVE'|'NEGATIVE'|'NEUTRAL', score }>
* onReady(fn) → register a callback fired when models finish loading
* onError(fn) → register a callback fired if the worker fails to boot
* isReady() → boolean — true once both models are warm
* warmup() → start the worker early so first classify() is fast
*
@@ -23,8 +24,9 @@
*/
let _worker = null;
let _ready = false;
let _ready = false;
let _readyCb = null;
let _errorCb = null;
const _pending = new Map(); // id → { resolve, reject }
let _nextId = 1;
@@ -45,6 +47,7 @@ function _init() {
}
if (data?.type === 'error') {
console.warn('[edge-worker] worker boot error:', data.message);
if (_errorCb) { _errorCb(data.message); _errorCb = null; }
// Resolve all pending with fallback values
for (const [, { resolve }] of _pending) resolve(_fallback(null));
_pending.clear();
@@ -103,6 +106,11 @@ export function onReady(fn) {
_readyCb = fn;
}
/** Register a callback fired if the worker fails to boot (model load error). */
export function onError(fn) {
_errorCb = fn;
}
export function isReady() { return _ready; }
/**

View File

@@ -5,10 +5,196 @@ let dustPositions = null;
let dustVelocities = null;
const DUST_COUNT = 600;
// Job Indicators
const _activeJobIndicators = new Map();
const INDICATOR_Y_OFFSET = 3.5; // Height above Timmy
const INDICATOR_X_OFFSET = 1.0; // Offset from Timmy's center for multiple jobs
const JOB_INDICATOR_DEFS = {
writing: {
create: () => {
// Quill (cone for feather, cylinder for handle)
const quillGroup = new THREE.Group();
const featherGeo = new THREE.ConeGeometry(0.15, 0.6, 4);
const featherMat = new THREE.MeshStandardMaterial({ color: 0xc8c4bc, roughness: 0.8 });
const feather = new THREE.Mesh(featherGeo, featherMat);
feather.position.y = 0.3;
feather.rotation.x = Math.PI / 8;
quillGroup.add(feather);
const handleGeo = new THREE.CylinderGeometry(0.04, 0.04, 0.4, 8);
const handleMat = new THREE.MeshStandardMaterial({ color: 0x3d2506, roughness: 0.7 });
const handle = new THREE.Mesh(handleGeo, handleMat);
handle.position.y = -0.2;
quillGroup.add(handle);
return quillGroup;
},
color: 0xe8d5a0, // parchment-like
},
coding: {
create: () => {
// Brackets (simple box geometry)
const bracketsGroup = new THREE.Group();
const bracketMat = new THREE.MeshStandardMaterial({ color: 0x5599dd, emissive: 0x224466, emissiveIntensity: 0.3, roughness: 0.4 });
const bracketGeo = new THREE.BoxGeometry(0.05, 0.3, 0.05);
const br1 = new THREE.Mesh(bracketGeo, bracketMat);
br1.position.set(-0.1, 0.0, 0);
bracketsGroup.add(br1);
const br2 = br1.clone();
br2.position.set(0.1, 0.0, 0);
bracketsGroup.add(br2);
const crossbarGeo = new THREE.BoxGeometry(0.25, 0.05, 0.05);
const crossbar1 = new THREE.Mesh(crossbarGeo, bracketMat);
crossbar1.position.set(0, 0.125, 0);
bracketsGroup.add(crossbar1);
const crossbar2 = crossbar1.clone();
crossbar2.position.set(0, -0.125, 0);
bracketsGroup.add(crossbar2);
return bracketsGroup;
},
color: 0x5599dd, // code-editor blue
},
research: {
create: () => {
// Spider (simple sphere body, cylinder legs) - very simplified
const spiderGroup = new THREE.Group();
const bodyMat = new THREE.MeshStandardMaterial({ color: 0x444444, roughness: 0.9 });
const body = new THREE.Mesh(new THREE.SphereGeometry(0.15, 8, 8), bodyMat);
spiderGroup.add(body);
const legMat = new THREE.MeshStandardMaterial({ color: 0x222222, roughness: 0.9 });
const legGeo = new THREE.CylinderGeometry(0.015, 0.015, 0.4, 4);
const legPositions = [
[0.18, 0.0, 0.08, Math.PI / 4], [-0.18, 0.0, 0.08, -Math.PI / 4],
[0.22, 0.0, -0.05, Math.PI / 2], [-0.22, 0.0, -0.05, -Math.PI / 2],
[0.18, 0.0, -0.18, 3 * Math.PI / 4], [-0.18, 0.0, -0.18, -3 * Math.PI / 4],
];
legPositions.forEach(([x, y, z, rotY]) => {
const leg = new THREE.Mesh(legGeo, legMat);
leg.position.set(x, y - 0.1, z);
leg.rotation.z = Math.PI / 2;
leg.rotation.y = rotY;
spiderGroup.add(leg);
});
return spiderGroup;
},
color: 0x8b0000, // dark red, investigative
},
creative: {
create: () => {
// Lightbulb (sphere with small cylinder base)
const bulbGroup = new THREE.Group();
const bulbMat = new THREE.MeshStandardMaterial({ color: 0xffddaa, emissive: 0xffaa00, emissiveIntensity: 0.8, transparent: true, opacity: 0.9, roughness: 0.1 });
const bulb = new THREE.Mesh(new THREE.SphereGeometry(0.2, 16, 12), bulbMat);
bulbGroup.add(bulb);
const baseMat = new THREE.MeshStandardMaterial({ color: 0x888888, roughness: 0.6 });
const base = new THREE.Mesh(new THREE.CylinderGeometry(0.08, 0.1, 0.15, 8), baseMat);
base.position.y = -0.25;
bulbGroup.add(base);
return bulbGroup;
},
color: 0xffaa00, // bright idea yellow
},
analysis: {
create: () => {
// Magnifying glass (torus for rim, plane for lens)
const magGroup = new THREE.Group();
const rimMat = new THREE.MeshStandardMaterial({ color: 0xbb9900, roughness: 0.4, metalness: 0.7 });
const rim = new THREE.Mesh(new THREE.TorusGeometry(0.2, 0.03, 8, 20), rimMat);
magGroup.add(rim);
const handleMat = new THREE.MeshStandardMaterial({ color: 0x3d2506, roughness: 0.7 });
const handle = new THREE.Mesh(new THREE.CylinderGeometry(0.03, 0.03, 0.4, 6), handleMat);
handle.position.set(0.25, -0.25, 0);
handle.rotation.z = Math.PI / 4;
magGroup.add(handle);
const lensMat = new THREE.MeshPhysicalMaterial({ color: 0xaaffff, transmission: 0.8, roughness: 0.1, transparent: true });
const lens = new THREE.Mesh(new THREE.CircleGeometry(0.17, 16), lensMat);
// Lens is a plane, so it will be rotated to face the camera or just set its position
// For simplicity, make it a thin cylinder or sphere segment to give it depth
const lensGeo = new THREE.CylinderGeometry(0.17, 0.17, 0.02, 16);
const thinLens = new THREE.Mesh(lensGeo, lensMat);
magGroup.add(thinLens);
return magGroup;
},
color: 0x88ddff, // clear blue, analytic
},
other: { // Generic glowing orb
create: () => {
const orbMat = new THREE.MeshStandardMaterial({ color: 0x800080, emissive: 0x550055, emissiveIntensity: 0.8, roughness: 0.2 });
return new THREE.Mesh(new THREE.SphereGeometry(0.2, 16, 16), orbMat);
},
color: 0x800080, // purple
},
};
export function initEffects(scene) {
initDustMotes(scene);
}
// Map to hold job indicator objects by jobId
const jobIndicators = new Map();
export function createJobIndicator(category, jobId, position) {
const def = JOB_INDICATOR_DEFS[category] || JOB_INDICATOR_DEFS.other;
const indicatorGroup = new THREE.Group();
indicatorGroup.userData.jobId = jobId;
indicatorGroup.userData.category = category;
const object = def.create();
object.scale.setScalar(0.7); // Make indicators a bit smaller
indicatorGroup.add(object);
// Add a subtle glowing point light to the indicator
const pointLight = new THREE.PointLight(def.color, 0.8, 3);
indicatorGroup.add(pointLight);
indicatorGroup.position.copy(position);
jobIndicators.set(jobId, indicatorGroup);
return indicatorGroup;
}
export function updateJobIndicators(time) {
const t = time * 0.001;
jobIndicators.forEach(indicator => {
// Simple bobbing motion
indicator.position.y += Math.sin(t * 2.5 + indicator.userData.jobId.charCodeAt(0)) * 0.002;
// Rotation
indicator.rotation.y += 0.01;
});
}
export function dissolveJobIndicator(jobId, scene) {
const indicator = jobIndicators.get(jobId);
if (indicator) {
// TODO: Implement particle dissolve effect here
// For now, just remove and dispose
scene.remove(indicator);
if (indicator.children.length > 0) {
const object = indicator.children[0];
if (object.geometry) object.geometry.dispose();
if (object.material) {
if (Array.isArray(object.material)) object.material.forEach(m => m.dispose());
else object.material.dispose();
}
}
indicator.children.forEach(child => {
if (child.isLight) child.dispose();
});
jobIndicators.delete(jobId);
}
}
function initDustMotes(scene) {
const geo = new THREE.BufferGeometry();
const positions = new Float32Array(DUST_COUNT * 3);
@@ -76,4 +262,18 @@ export function disposeEffects() {
}
dustPositions = null;
dustVelocities = null;
}
jobIndicators.forEach(indicator => {
if (indicator.children.length > 0) {
const object = indicator.children[0];
if (object.geometry) object.geometry.dispose();
if (object.material) {
if (Array.isArray(object.material)) object.material.forEach(m => m.dispose());
else object.material.dispose();
}
}
indicator.children.forEach(child => {
if (child.isLight) child.dispose();
});
});
jobIndicators.clear();
}

View File

@@ -5,15 +5,15 @@ import {
getTimmyGroup, applySlap, getCameraShakeStrength,
TIMMY_WORLD_POS,
} from './agents.js';
import { initEffects, updateEffects, disposeEffects } from './effects.js';
import { initEffects, updateEffects, disposeEffects, updateJobIndicators } from './effects.js';
import { initUI, updateUI } from './ui.js';
import { initInteraction, disposeInteraction, registerSlapTarget } from './interaction.js';
import { initWebSocket, getConnectionState, getJobCount } from './websocket.js';
import { initPaymentPanel } from './payment.js';
import { initSessionPanel } from './session.js';
import { initNostrIdentity } from './nostr-identity.js';
import { warmup as warmupEdgeWorker, onReady as onEdgeWorkerReady } from './edge-worker-client.js';
import { setEdgeWorkerReady } from './ui.js';
import { warmup as warmupEdgeWorker, onReady as onEdgeWorkerReady, onError as onEdgeWorkerError } from './edge-worker-client.js';
import { setEdgeWorkerReady, setEdgeWorkerLoading, setEdgeWorkerError } from './ui.js';
import { initTimmyId } from './timmy-id.js';
import { AGENT_DEFS } from './agent-defs.js';
import { initNavigation, updateNavigation, disposeNavigation } from './navigation.js';
@@ -47,8 +47,10 @@ function buildWorld(firstInit, stateSnapshot) {
initPaymentPanel();
initSessionPanel();
void initNostrIdentity('/api');
setEdgeWorkerLoading();
warmupEdgeWorker();
onEdgeWorkerReady(() => setEdgeWorkerReady());
onEdgeWorkerError(() => setEdgeWorkerError());
void initTimmyId();
}
@@ -81,6 +83,7 @@ function buildWorld(firstInit, stateSnapshot) {
updateEffects(now);
updateAgents(now);
updateJobIndicators(now);
updateUI({
fps: currentFps,
agentCount: getAgentCount(),

View File

@@ -42,6 +42,7 @@ export async function initNostrIdentity(apiBase = '/api') {
_pubkey = await window.nostr.getPublicKey();
_useNip07 = true;
_canSign = true;
_saveDiscoveredKeypair(_pubkey, null); // Store pubkey in LS even if NIP-07
console.info('[nostr] Using NIP-07 extension, pubkey:', _pubkey.slice(0, 8) + '…');
} catch (err) {
console.warn('[nostr] NIP-07 getPublicKey failed, will use local keypair', err);
@@ -86,6 +87,18 @@ export function getPubkey() { return _pubkey; }
export function getNostrToken() { return _isTokenValid() ? _token : null; }
export function hasIdentity() { return !!_pubkey; }
export function disconnectNostrIdentity() {
_pubkey = null;
_token = null;
_tokenExp = 0;
_useNip07 = false;
_canSign = false;
localStorage.removeItem(LS_KEYPAIR_KEY);
localStorage.removeItem(LS_TOKEN_KEY);
window.dispatchEvent(new CustomEvent('nostr:identity-disconnected'));
console.info('[nostr] identity disconnected');
}
/**
* getOrRefreshToken — returns a valid token, refreshing if necessary.
* Returns null if no identity is established.
@@ -197,6 +210,7 @@ export function showIdentityPrompt(apiBase = '/api') {
_pubkey = await window.nostr.getPublicKey();
_useNip07 = true;
_canSign = true;
_saveDiscoveredKeypair(_pubkey, null); // Store pubkey in LS even if NIP-07
} catch { return; }
} else {
// Generate + store keypair (user consented by clicking)

View File

@@ -1,7 +1,7 @@
import { sendVisitorMessage } from './websocket.js';
import { classify } from './edge-worker-client.js';
import { setMood, setSpeechBubble } from './agents.js';
import { getOrRefreshToken } from './nostr-identity.js';
import { getOrRefreshToken, getPubkey, disconnectNostrIdentity, showIdentityPrompt } from './nostr-identity.js';
const $fps = document.getElementById('fps');
const $activeJobs = document.getElementById('active-jobs');
@@ -32,32 +32,48 @@ export function setInputBarSessionMode(active, placeholder) {
}
// ── Model-ready indicator ─────────────────────────────────────────────────────
// A small badge on the input bar showing when local AI is warm and ready.
// Hidden until the first `ready` event from the edge worker.
// A small badge on the input bar showing local AI status: loading / ready / error.
// Appears immediately when warmup() starts so users know the worker is initialising.
let $readyBadge = null;
export function setEdgeWorkerReady() {
if (!$readyBadge) {
$readyBadge = document.createElement('span');
$readyBadge.id = 'edge-ready-badge';
$readyBadge.title = 'Local AI active — trivial queries answered without Lightning payment';
$readyBadge.style.cssText = [
'font-size:10px;color:#44cc88;border:1px solid #226644',
'border-radius:3px;padding:1px 5px;margin-left:6px',
'vertical-align:middle;cursor:default',
].join(';');
$readyBadge.textContent = '⚡ local AI';
const $input = document.getElementById('visitor-input');
$input?.insertAdjacentElement('afterend', $readyBadge);
// Fallback: append to send button area
if (!$readyBadge.isConnected) {
document.getElementById('send-btn')?.insertAdjacentElement('afterend', $readyBadge);
}
const EDGE_STATES = {
loading: { text: '◌ AI loading', color: '#88aacc', border: '#335577', title: 'Local AI model loading…' },
ready: { text: '⚡ local AI', color: '#44cc88', border: '#226644', title: 'Local AI active — trivial queries answered without Lightning payment' },
error: { text: '✕ AI offline', color: '#cc6644', border: '#773322', title: 'Local AI failed to load — all requests will be routed to server' },
};
function _ensureEdgeBadge() {
if ($readyBadge) return $readyBadge;
$readyBadge = document.createElement('span');
$readyBadge.id = 'edge-ready-badge';
$readyBadge.style.cssText = [
'font-size:10px;border-radius:3px;padding:1px 5px;margin-left:6px',
'vertical-align:middle;cursor:default;transition:color .3s,border-color .3s',
].join(';');
const $input = document.getElementById('visitor-input');
$input?.insertAdjacentElement('afterend', $readyBadge);
if (!$readyBadge.isConnected) {
document.getElementById('send-btn')?.insertAdjacentElement('afterend', $readyBadge);
}
$readyBadge.style.display = '';
return $readyBadge;
}
export function setEdgeWorkerStatus(state) {
const cfg = EDGE_STATES[state] ?? EDGE_STATES.loading;
const el = _ensureEdgeBadge();
el.textContent = cfg.text;
el.title = cfg.title;
el.style.color = cfg.color;
el.style.border = `1px solid ${cfg.border}`;
el.style.display = '';
}
/** Convenience wrappers kept for backward-compat with main.js callers. */
export function setEdgeWorkerReady() { setEdgeWorkerStatus('ready'); }
export function setEdgeWorkerLoading() { setEdgeWorkerStatus('loading'); }
export function setEdgeWorkerError() { setEdgeWorkerStatus('error'); }
// ── Cost preview badge ────────────────────────────────────────────────────────
// Shown beneath the input bar: "~N sats" / "FREE" / "answered locally".
// Fetched from GET /api/estimate once the user stops typing (300 ms debounce).
@@ -180,12 +196,97 @@ export function hideCostTicker() {
$costTicker.style.opacity = '0';
}
// ── Nostr identity UI ─────────────────────────────────────────────────────────
let _nostrStatusEl = null;
let _connectNostrBtn = null;
let _disconnectNostrBtn = null;
let _nostrPubkeyDisplay = null;
let _getAlbyBtn = null;
export function initNostrIdentityUI() {
_nostrStatusEl = document.getElementById('nostr-identity-status');
if (!_nostrStatusEl) return;
_nostrStatusEl.innerHTML = `
<button id="connect-nostr-btn" class="nostr-btn">⚡ Connect Nostr</button>
<span id="nostr-pubkey-display" class="nostr-pubkey"></span>
<button id="disconnect-nostr-btn" class="nostr-btn nostr-btn-sm">Disconnect</button>
<button id="get-alby-btn" class="nostr-btn nostr-btn-sm">Get Alby</button>
`;
_connectNostrBtn = document.getElementById('connect-nostr-btn');
_disconnectNostrBtn = document.getElementById('disconnect-nostr-btn');
_nostrPubkeyDisplay = document.getElementById('nostr-pubkey-display');
_getAlbyBtn = document.getElementById('get-alby-btn');
if (_connectNostrBtn) {
_connectNostrBtn.addEventListener('click', () => {
showIdentityPrompt('/api');
});
}
if (_disconnectNostrBtn) {
_disconnectNostrBtn.addEventListener('click', () => {
disconnectNostrIdentity();
_updateNostrIdentityUI(null);
});
}
window.addEventListener('nostr:identity-ready', e => {
_updateNostrIdentityUI(e.detail.pubkey);
});
window.addEventListener('nostr:identity-disconnected', () => {
_updateNostrIdentityUI(null);
});
_updateNostrIdentityUI(getPubkey());
}
function _updateNostrIdentityUI(pubkey) {
const hasNip07 = typeof window !== 'undefined' && !!window.nostr;
if (pubkey) {
const formattedPubkey = pubkey.slice(0, 8) + '…' + pubkey.slice(-4);
if (_nostrPubkeyDisplay) {
_nostrPubkeyDisplay.textContent = `${formattedPubkey}`;
_nostrPubkeyDisplay.style.display = 'inline-block';
}
if (_connectNostrBtn) _connectNostrBtn.style.display = 'none';
if (_disconnectNostrBtn) _disconnectNostrBtn.style.display = 'inline-block';
if (_getAlbyBtn) _getAlbyBtn.style.display = 'none';
} else {
if (_nostrPubkeyDisplay) _nostrPubkeyDisplay.style.display = 'none';
if (_disconnectNostrBtn) _disconnectNostrBtn.style.display = 'none';
if (hasNip07) {
if (_connectNostrBtn) {
_connectNostrBtn.textContent = '⚡ Connect Nostr';
_connectNostrBtn.style.display = 'inline-block';
}
if (_getAlbyBtn) _getAlbyBtn.style.display = 'none';
} else {
if (_connectNostrBtn) _connectNostrBtn.style.display = 'none';
if (_getAlbyBtn) {
_getAlbyBtn.textContent = 'Get Alby';
_getAlbyBtn.style.display = 'inline-block';
_getAlbyBtn.title = 'Install Alby or another NIP-07 extension to connect your Nostr identity';
_getAlbyBtn.onclick = () => window.open('https://getalby.com/', '_blank');
}
}
}
}
// ── Input bar ─────────────────────────────────────────────────────────────────
export function initUI() {
if (uiInitialized) return;
uiInitialized = true;
initInputBar();
initHeatmap();
initNostrIdentityUI();
}
function initInputBar() {
@@ -305,3 +406,119 @@ export function appendDebateMessage(agent, argument, isVerdict, accepted) {
export function loadChatHistory() { return []; }
export function saveChatHistory() {}
// ── Activity heatmap (#9) ─────────────────────────────────────────────────────
// Fetches /api/stats/activity and renders a 24-segment heatmap.
// Auto-refreshes every 5 minutes. On mobile, collapses to an icon that opens
// a full-screen overlay.
const HEATMAP_REFRESH_MS = 5 * 60 * 1000; // 5 minutes
let _heatmapTimer = null;
let _lastHours = null; // number[24] cached for overlay re-render
/** Convert an hour index (0 = oldest, 23 = current) to a UTC hour label like "3pm" or "midnight". */
function _hourLabel(hourIndex) {
const now = new Date();
const currentHour = now.getUTCHours();
// slot 23 = current UTC hour, slot 0 = 23 hours ago
const h = ((currentHour - (23 - hourIndex)) % 24 + 24) % 24;
if (h === 0) return 'midnight';
if (h === 12) return 'noon';
return h < 12 ? `${h}am` : `${h - 12}pm`;
}
/** Interpolate from dim blue (#111133) to bright blue-white (#88ccff) based on 01 intensity. */
function _segmentColor(intensity) {
// dim: [17, 17, 51] bright: [136, 204, 255]
const r = Math.round(17 + (136 - 17) * intensity);
const g = Math.round(17 + (204 - 17) * intensity);
const b = Math.round(51 + (255 - 51) * intensity);
return `rgb(${r},${g},${b})`;
}
function _renderSegments(hours, container, isMobile) {
container.innerHTML = '';
const max = Math.max(...hours, 1); // avoid div-by-zero
const currentSlot = 23;
hours.forEach((count, i) => {
const seg = document.createElement('div');
seg.className = 'hm-seg' + (i === currentSlot ? ' hm-seg-current' : '');
const intensity = count / max;
const color = _segmentColor(intensity);
seg.style.background = color;
if (i === currentSlot) seg.style.color = color; // used by pulse animation
seg.dataset.index = String(i);
seg.dataset.count = String(count);
if (isMobile) {
seg.style.width = '14px';
seg.style.height = '28px';
}
container.appendChild(seg);
});
}
function _initHeatmapTooltip(barEl) {
const $tip = document.getElementById('heatmap-tooltip');
if (!$tip) return;
barEl.addEventListener('mousemove', e => {
const seg = e.target.closest('.hm-seg');
if (!seg) { $tip.style.display = 'none'; return; }
const i = Number(seg.dataset.index);
const count = Number(seg.dataset.count);
const label = _hourLabel(i);
$tip.textContent = `${label}: ${count} job${count !== 1 ? 's' : ''} submitted`;
$tip.style.display = 'block';
$tip.style.left = `${e.clientX + 10}px`;
$tip.style.top = `${e.clientY - 24}px`;
});
barEl.addEventListener('mouseleave', () => { $tip.style.display = 'none'; });
}
async function _fetchAndRenderHeatmap() {
try {
const res = await fetch('/api/stats/activity');
if (!res.ok) return;
const data = await res.json();
const hours = Array.isArray(data.hours) ? data.hours : [];
if (hours.length !== 24) return;
_lastHours = hours;
const $bar = document.getElementById('heatmap-bar');
if ($bar) _renderSegments(hours, $bar, false);
const $overlayBar = document.getElementById('heatmap-overlay-bar');
if ($overlayBar) _renderSegments(hours, $overlayBar, true);
} catch {
// silently ignore fetch errors
}
}
export function initHeatmap() {
const $bar = document.getElementById('heatmap-bar');
const $iconBtn = document.getElementById('heatmap-icon-btn');
const $overlay = document.getElementById('heatmap-overlay');
const $closeBtn = document.getElementById('heatmap-overlay-close');
if ($bar) _initHeatmapTooltip($bar);
if ($iconBtn && $overlay) {
$iconBtn.addEventListener('click', () => {
$overlay.classList.add('open');
if (_lastHours) {
const $overlayBar = document.getElementById('heatmap-overlay-bar');
if ($overlayBar) _renderSegments(_lastHours, $overlayBar, true);
}
});
}
if ($closeBtn && $overlay) {
$closeBtn.addEventListener('click', () => $overlay.classList.remove('open'));
}
// Initial fetch then schedule refresh
void _fetchAndRenderHeatmap();
_heatmapTimer = setInterval(_fetchAndRenderHeatmap, HEATMAP_REFRESH_MS);
}

View File

@@ -1,7 +1,11 @@
import { setAgentState, setSpeechBubble, applyAgentStates, setMood } from './agents.js';
import * as THREE from 'three';
import { scene } from './world.js'; // Import the scene
import { setAgentState, setSpeechBubble, applyAgentStates, setMood, TIMMY_WORLD_POS } from './agents.js';
import { appendSystemMessage, appendDebateMessage, showCostTicker, updateCostTicker } from './ui.js';
import { sentiment } from './edge-worker-client.js';
import { setLabelState } from './hud-labels.js';
import { createJobIndicator, dissolveJobIndicator } from './effects.js';
import { getPubkey } from './nostr-identity.js';
function resolveWsUrl() {
const explicit = import.meta.env.VITE_WS_URL;
@@ -19,6 +23,10 @@ let reconnectTimer = null;
let visitorId = null;
const RECONNECT_DELAY_MS = 5000;
// Map to keep track of active job indicator positions for offsetting
const _jobIndicatorOffsets = new Map();
let _nextJobOffsetIndex = 0;
export function initWebSocket(_scene) {
visitorId = crypto.randomUUID();
connect();
@@ -39,7 +47,8 @@ function connect() {
ws.onopen = () => {
connectionState = 'connected';
clearTimeout(reconnectTimer);
send({ type: 'visitor_enter', visitorId, visitorName: 'visitor' });
const npub = getPubkey();
send({ type: 'visitor_enter', visitorId, visitorName: 'visitor', npub });
};
ws.onmessage = event => {
@@ -95,6 +104,21 @@ function handleMessage(msg) {
setLabelState(msg.agentId, 'active');
}
appendSystemMessage(`job ${(msg.jobId || '').slice(0, 8)} started`);
// Spawn 3D job indicator
if (msg.jobId && msg.category) {
const offsetMultiplier = _jobIndicatorOffsets.size; // Simple way to spread them out
const indicatorPosition = TIMMY_WORLD_POS.clone().add(
new THREE.Vector3(
(offsetMultiplier % 2 === 0 ? 1 : -1) * (Math.floor(offsetMultiplier / 2) + 1) * 0.7, // Alternate left/right
3.5, // Height above Timmy
-0.5
)
);
const indicator = createJobIndicator(msg.category, msg.jobId, indicatorPosition);
scene.add(indicator);
_jobIndicatorOffsets.set(msg.jobId, indicatorPosition); // Store position, not index, for cleaner removal
}
break;
}
@@ -105,6 +129,12 @@ function handleMessage(msg) {
setLabelState(msg.agentId, 'idle');
}
appendSystemMessage(`job ${(msg.jobId || '').slice(0, 8)} complete`);
// Dissolve 3D job indicator
if (msg.jobId) {
dissolveJobIndicator(msg.jobId, scene);
_jobIndicatorOffsets.delete(msg.jobId);
}
break;
}
@@ -151,6 +181,15 @@ function handleMessage(msg) {
break;
}
case 'agent_commentary': {
// Agent narration during job lifecycle
if (msg.text) {
setSpeechBubble(msg.text);
appendSystemMessage(`${msg.agentId}: ${(msg.text || '').slice(0, 80)}`);
}
break;
}
case 'agent_count':
case 'visitor_count':
break;

View File

@@ -1,6 +1,6 @@
import * as THREE from 'three';
let scene, camera, renderer;
export let scene, camera, renderer;
const _worldObjects = [];
export function initWorld(existingCanvas) {