31 Commits

Author SHA1 Message Date
Alexander Whitestone
c2f2cfe3ea feat: add Tower Log narrative event feed (Fixes #7)
Some checks failed
CI / Typecheck & Lint (pull_request) Failing after 0s
Adds the tower_log DB table, a narrateEvent method on AgentService (Haiku-powered, stub-safe), a tower-log service that persists and broadcasts entries, a GET /api/tower-log REST endpoint, WebSocket bootstrap and real-time push, and a bottom-sheet Tower Log panel in the-matrix UI with fade-in animations and auto-scroll.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-23 22:43:10 -04:00
b6569aeedc [claude] Mobile: Job history tab showing completed jobs (#31) (#107) 2026-03-24 02:26:13 +00:00
1e2edeee77 [claude] Nostr identity lifecycle coverage T41–T45 (#55) (#106) 2026-03-24 02:20:34 +00: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
e41d30d308 [claude] Mobile: Paid job submission with inline Lightning invoice (#25) (#88)
Co-authored-by: Claude (Opus 4.6) <claude@hermes.local>
Co-committed-by: Claude (Opus 4.6) <claude@hermes.local>
2026-03-23 20:20:52 +00:00
3bd67c7869 [claude] Relay account whitelist + trust-gated access (#47) (#90)
Co-authored-by: Claude (Opus 4.6) <claude@hermes.local>
Co-committed-by: Claude (Opus 4.6) <claude@hermes.local>
2026-03-23 20:20:48 +00:00
3843e749a3 [claude] Vite build system: bundle Three.js, remove CDN dependency (#61) (#89) 2026-03-23 20:16:07 +00:00
cbeaa61083 [claude] Timmy slap / ragdoll physics — spring wobble + Pip startle (#43) (#85)
Co-authored-by: Claude (Opus 4.6) <claude@hermes.local>
Co-committed-by: Claude (Opus 4.6) <claude@hermes.local>
2026-03-23 20:14:36 +00:00
95a104aba0 [claude] TypeScript quality gates: ESLint, pre-commit hooks, Gitea CI (#53) (#86)
Co-authored-by: Claude (Opus 4.6) <claude@hermes.local>
Co-committed-by: Claude (Opus 4.6) <claude@hermes.local>
2026-03-23 20:14:32 +00:00
5dc71e1257 [claude] API observability — structured logging + /api/metrics endpoint (#57) (#87) 2026-03-23 20:10:40 +00:00
113095d2f0 [claude] WebGL context loss recovery: Matrix green overlay (#63) (#84) 2026-03-23 20:02:31 +00:00
821aa48543 [claude] Add real-time cost ticker for Workshop interactions (#68) (#82)
Co-authored-by: Claude (Opus 4.6) <claude@hermes.local>
Co-committed-by: Claude (Opus 4.6) <claude@hermes.local>
2026-03-23 20:01:26 +00:00
2fe82988f4 [claude] WebGL context loss recovery: Matrix green overlay (#63) (#83) 2026-03-23 20:00:42 +00:00
fb847b6e53 [claude] Mobile first-launch onboarding walkthrough (#35) (#79)
Co-authored-by: Claude (Opus 4.6) <claude@hermes.local>
Co-committed-by: Claude (Opus 4.6) <claude@hermes.local>
2026-03-23 14:31:47 +00:00
04398e88e0 [claude] Exclude /api paths from tower SPA fallback (#36) (#81) 2026-03-23 02:14:49 +00:00
0bdf9336bc [claude] App-state aware WebSocket reconnect on foreground (#33) (#77) 2026-03-23 01:51:46 +00:00
4ea59f7198 [claude] Context injection — pass conversation history to work model (#39) (#78) 2026-03-23 01:51:22 +00:00
ef3e27d595 [claude] Wire Relay Admin panel into Matrix UI (#49) (#75) 2026-03-23 01:50:44 +00:00
259f515bfd [claude] Add sweep.conf.example and polish auto-sweep infra (#51) (#76) 2026-03-23 01:50:33 +00:00
622428dfa9 [claude] Add Clear history button in session panel (#41) (#74) 2026-03-23 01:49:26 +00:00
64 changed files with 4326 additions and 1595 deletions

View File

@@ -3,7 +3,10 @@ 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";
const app: Express = express();
@@ -50,9 +53,12 @@ app.use(
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
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).
@@ -79,7 +85,15 @@ const towerDist = (() => {
return path.join(process.cwd(), "the-matrix", "dist");
})();
app.use("/tower", express.static(towerDist));
app.get("/tower/*splat", (_req, res) => res.sendFile(path.join(towerDist, "index.html")));
app.get("/tower/*splat", (req, res, next) => {
// Never serve the SPA shell for requests that should hit the API or WS endpoint.
// The *splat wildcard would otherwise swallow paths like /tower/api/ws and return
// index.html, preventing the WebSocket upgrade from reaching the ws server.
const splatArr = (req.params as Record<string, string[]>)["splat"] ?? [];
const sub = splatArr.join("/");
if (sub === "api" || sub.startsWith("api/")) return next();
res.sendFile(path.join(towerDist, "index.html"));
});
// Vite builds asset references as absolute /assets/... paths.
// Mirror them at the root so the browser can load them from /tower.

View File

@@ -145,13 +145,20 @@ Respond ONLY with valid JSON: {"accepted": true/false, "reason": "...", "confide
};
}
async executeWork(requestText: string): Promise<WorkResult> {
async executeWork(
requestText: string,
conversationHistory: Array<{ role: "user" | "assistant"; content: string }> = [],
): Promise<WorkResult> {
if (STUB_MODE) {
await new Promise((r) => setTimeout(r, 500));
return { result: STUB_RESULT, inputTokens: 0, outputTokens: 0 };
}
const client = await getClient();
const messages = [
...conversationHistory,
{ role: "user" as const, content: requestText },
];
const message = await client.messages.create({
model: this.workModel,
max_tokens: 8192,
@@ -164,7 +171,7 @@ If the user asks how to run their own Timmy or self-host this service, enthusias
- Core env vars: AI_INTEGRATIONS_ANTHROPIC_API_KEY, AI_INTEGRATIONS_ANTHROPIC_BASE_URL, DATABASE_URL, LNBITS_URL, LNBITS_API_KEY, NOSTR_PRIVATE_KEY.
- Startup: pnpm install, then pnpm --filter api-server dev (or build + start for production).
- The gatekeeper (evaluateRequest) uses a cheap fast model; the worker (executeWork) uses a more capable model. Both are swappable via EVAL_MODEL and WORK_MODEL env vars.`,
messages: [{ role: "user", content: requestText }],
messages,
});
const block = message.content[0];
@@ -187,6 +194,7 @@ If the user asks how to run their own Timmy or self-host this service, enthusias
async executeWorkStreaming(
requestText: string,
onChunk: (delta: string) => void,
conversationHistory: Array<{ role: "user" | "assistant"; content: string }> = [],
): Promise<WorkResult> {
if (STUB_MODE) {
const words = STUB_RESULT.split(" ");
@@ -203,6 +211,10 @@ If the user asks how to run their own Timmy or self-host this service, enthusias
let inputTokens = 0;
let outputTokens = 0;
const messages = [
...conversationHistory,
{ role: "user" as const, content: requestText },
];
const stream = client.messages.stream({
model: this.workModel,
max_tokens: 8192,
@@ -215,7 +227,7 @@ If the user asks how to run their own Timmy or self-host this service, enthusias
- Core env vars: AI_INTEGRATIONS_ANTHROPIC_API_KEY, AI_INTEGRATIONS_ANTHROPIC_BASE_URL, DATABASE_URL, LNBITS_URL, LNBITS_API_KEY, NOSTR_PRIVATE_KEY.
- Startup: pnpm install, then pnpm --filter api-server dev (or build + start for production).
- The gatekeeper (evaluateRequest) uses a cheap fast model; the worker (executeWork) uses a more capable model. Both are swappable via EVAL_MODEL and WORK_MODEL env vars.`,
messages: [{ role: "user", content: requestText }],
messages,
});
for await (const event of stream) {
@@ -364,6 +376,155 @@ 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 "";
}
}
/**
* Generate a short narrative entry for the Tower Log.
* Uses Haiku (evalModel) with Timmy's wizardly persona.
* Returns a single sentence under 100 characters.
*
* In STUB_MODE returns a canned narrative so the full flow
* can be exercised without an Anthropic API key.
*/
async narrateEvent(eventType: string, context?: string): Promise<string> {
const STUB_NARRATIVES: Record<string, string[]> = {
"job:complete": [
"Timmy conjures a brilliant solution, weaving lightning and wisdom.",
"Another quest fulfilled — the Workshop hums with quiet satisfaction.",
"The crystal ball glows as Timmy delivers yet another worthy result.",
],
"job:rejected": [
"With gentle wisdom, Timmy declines — not all quests suit the Workshop.",
"The Beta oracle speaks: this path shall not be walked today.",
],
"job:failed": [
"The arcane machinery sputters — a job falters in the ether.",
"Even wizards face setbacks; Timmy regroups and stands ready.",
],
"visitor:enter": [
"A new traveler arrives, drawn by the Workshop's lightning glow.",
"The Workshop doors swing open to welcome another seeker.",
"Another soul finds the Workshop, guided by satoshi starlight.",
],
"visitor:leave": [
"A visitor departs, carrying a spark of the Workshop's magic.",
"The door closes softly — one more seeker returns to the world.",
],
"payment:eval": [
"⚡ Lightning strikes — eval fee confirmed, wisdom unlocked.",
"Sats flow in; the Workshop's scales tip toward action.",
],
"payment:work": [
"⚡ Work payment confirmed — Gamma stirs to weave the answer.",
"The Lightning Network delivers; Timmy's full power is unleashed.",
],
};
const candidates = STUB_NARRATIVES[eventType]
?? ["The Workshop stirs with quiet, purposeful magic."];
if (STUB_MODE) {
return candidates[Math.floor(Math.random() * candidates.length)]!;
}
const EVENT_CONTEXT: Record<string, string> = {
"job:complete": "A visitor's paid job completed successfully in Timmy's Workshop.",
"job:rejected": "A visitor's job request was rejected after AI evaluation.",
"job:failed": "A job failed unexpectedly in the Workshop.",
"visitor:enter": "A new visitor just entered Timmy's Workshop.",
"visitor:leave": "A visitor just left Timmy's Workshop.",
"payment:eval": "A visitor paid the evaluation fee via Lightning.",
"payment:work": "A visitor paid the work fee via Lightning, unlocking execution.",
};
const baseContext = EVENT_CONTEXT[eventType] ?? "Something noteworthy happened in the Workshop.";
const fullContext = context ? `${baseContext} ${context}` : baseContext;
try {
const client = await getClient();
const message = await client.messages.create({
model: this.evalModel, // Haiku — cheap and fast
max_tokens: 80,
system: `You are the chronicler of Timmy's Workshop — a mystical tower powered by Bitcoin Lightning where an AI wizard named Timmy fulfills paid quests for visitors.
Write a single vivid sentence (strictly under 100 characters) narrating what just happened.
Style: wizardly, warm, slightly epic. Present tense. No quotes. No hashtags.`,
messages: [{ role: "user", content: `Narrate this event: ${fullContext}` }],
});
const block = message.content[0];
if (block?.type === "text") {
const text = block.text!.trim().replace(/^["']|["']$/g, "");
return text.slice(0, 120); // hard cap
}
return candidates[0]!;
} catch (err) {
logger.warn("narrateEvent failed", { eventType, err: String(err) });
return candidates[Math.floor(Math.random() * candidates.length)]!;
}
}
}
export const agentService = new AgentService();

View File

@@ -15,7 +15,16 @@ export type DebateEvent =
| { type: "debate:argument"; jobId: string; agent: "Beta-A" | "Beta-B"; position: "accept" | "reject"; argument: string }
| { type: "debate:verdict"; jobId: string; accepted: boolean; reason: string };
export type BusEvent = JobEvent | SessionEvent | DebateEvent;
export type CostEvent =
| { type: "cost:update"; jobId: string; sats: number; phase: "eval" | "work" | "session"; isFinal: boolean };
export type CommentaryEvent =
| { type: "agent_commentary"; agentId: string; jobId: string; text: string };
export type TowerLogEvent =
| { type: "tower_log:entry"; id: string; narrative: string; eventType: string; agentId: string | null; jobId: string | null; createdAt: string };
export type BusEvent = JobEvent | SessionEvent | DebateEvent | CostEvent | CommentaryEvent | TowerLogEvent;
class EventBus extends EventEmitter {
emit(event: "bus", data: BusEvent): boolean;

View File

@@ -4,7 +4,19 @@ export interface LogContext {
[key: string]: unknown;
}
const LEVEL_ORDER: Record<LogLevel, number> = { debug: 0, info: 1, warn: 2, error: 3 };
function resolveMinLevel(): LogLevel {
const env = (process.env["LOG_LEVEL"] ?? "").toLowerCase();
if (env === "debug" || env === "info" || env === "warn" || env === "error") return env;
return "debug";
}
const minLevel: number = LEVEL_ORDER[resolveMinLevel()];
function emit(level: LogLevel, component: string, message: string, ctx?: LogContext): void {
if (LEVEL_ORDER[level] < minLevel) return;
const line: Record<string, unknown> = {
timestamp: new Date().toISOString(),
level,

View File

@@ -1,6 +1,7 @@
import { db, jobs, invoices } from "@workspace/db";
import { sql } from "drizzle-orm";
import { latencyHistogram, type BucketStats } from "./histogram.js";
import { requestCounters, type RequestCountsSnapshot } from "./request-counters.js";
export interface JobStateCounts {
awaiting_eval: number;
@@ -12,6 +13,7 @@ export interface JobStateCounts {
export interface MetricsSnapshot {
uptime_s: number;
http: RequestCountsSnapshot;
jobs: {
total: number;
by_state: JobStateCounts;
@@ -94,6 +96,7 @@ export class MetricsService {
return {
uptime_s: Math.floor((Date.now() - START_TIME) / 1000),
http: requestCounters.snapshot(),
jobs: {
total: jobsTotal,
by_state: byState,

View File

@@ -1,597 +1,207 @@
import { generateKeyPairSync } from "crypto";
import { db, bootstrapJobs } from "@workspace/db";
import { eq } from "drizzle-orm";
import { randomBytes } from "crypto";
import { makeLogger } from "./logger.js";
const logger = makeLogger("provisioner");
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; // New: Digital Ocean VPC UUID
doSshKeyFingerprint: string; // New: Digital Ocean SSH Key Fingerprint
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, any>(); // 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 ?? "", // New
doSshKeyFingerprint: config?.doSshKeyFingerprint ?? process.env.DO_SSH_KEY_FINGERPRINT ?? "", // New
tailscaleApiKey: config?.tailscaleApiKey ?? process.env.TAILSCALE_API_KEY ?? "",
tailscaleTailnet: config?.tailscaleTailnet ?? process.env.TAILSCALE_TAILNET ?? "",
};
if (volumeId) dropletPayload.volumes = [volumeId];
const dropletData = await doPost<{ droplet: { id: number } }>(
"/droplets",
this.doToken,
dropletPayload,
);
const dropletId = dropletData.droplet.id;
logger.info("droplet created", { bootstrapJobId: jobId, dropletId });
// 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)" });
// 7. Tailscale hostname
const tailscaleHostname =
tailscaleAuthKey && this.tsTailnet
? `timmy-node-${jobId.slice(0, 8)}.${this.tsTailnet}.ts.net`
: null;
// 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;
await db
.update(bootstrapJobs)
.set({
state: "ready",
dropletId: String(dropletId),
nodeIp,
tailscaleHostname,
lnbitsUrl,
sshPrivateKey: privateKey,
updatedAt: new Date(),
})
.where(eq(bootstrapJobs.id, jobId));
logger.info("real provisioning complete", { bootstrapJobId: jobId });
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 });
}
}
}
export const provisionerService = new ProvisionerService();
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;
}
// Real provisioning logic
const { sshPrivateKey, sshPublicKey } = await this.generateSshKeyPair();
const tailscaleAuthKey = await this.createTailscaleAuthKey();
const cloudConfig = this.buildCloudInitScript(sshPublicKey, tailscaleAuthKey);
logger.info("creating Digital Ocean droplet", { jobId });
// Use doctl or DigitalOcean API client to create droplet
// For now, I'll use doctl via runShellCommand, assuming it's available in the environment
const dropletName = `timmy-node-${jobId.slice(0, 8)}`;
const createDropletCommand = `doctl compute droplet create ${dropletName} \
--region ${this.config.doRegion} \
--size ${this.config.doSize} \
--image ubuntu-22-04-x64 \
--enable-private-networking \
--vpc-uuid <YOUR_VPC_UUID> \
--user-data '${cloudConfig}' \
--ssh-keys <YOUR_SSH_KEY_FINGERPRINT> \
--format ID --no-header`; // Simplistic command, needs refinement for real use
const createDropletOutput = await default_api.run_shell_command(
command: `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`,
description: `Creating Digital Ocean droplet ${dropletName} for job ${jobId}`,
);
const dropletId = createDropletOutput.output.trim();
// In a real scenario, we would poll the DigitalOcean API to wait for the droplet
// to become active and retrieve its public IP and Tailscale IP.
// For now, we'll simulate this and retrieve dummy IPs.
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: dropletId,
nodeIp: nodeIp,
tailscaleHostname: tailscaleHostname,
lnbitsUrl: lnbitsUrl,
sshPrivateKey: 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")}`;
// Generate an unencrypted SSH keypair for programmatic use (careful with security)
await default_api.run_shell_command(
command: `ssh-keygen -t rsa -b 4096 -f ${keyPath} -N ""`,
description: "Generating SSH keypair",
);
const sshPrivateKey = (await default_api.run_shell_command(command: `cat ${keyPath}`)).output.trim();
const sshPublicKey = (await default_api.run_shell_command(command: `cat ${keyPath}.pub`)).output.trim();
await default_api.run_shell_command(command: `rm ${keyPath} ${keyPath}.pub`, description: "Cleaning up temporary SSH keys");
return { sshPrivateKey, sshPublicKey };
}
// Helper to create Tailscale auth key (simplified stub)
private async createTailscaleAuthKey(): Promise<string> {
logger.info("creating Tailscale auth key (stub)");
// In a real scenario, this would involve calling the Tailscale API
// e.g., curl -X POST -H "Authorization: Bearer ${TAILSCALE_API_KEY}"
// "https://api.tailscale.com/api/v2/tailnet/${TAILSCALE_TAILNET}/keys"
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 setupScriptUrl = `http://143.198.27.163:3000/replit/timmy-tower/raw/branch/main/infrastructure/setup.sh`;
const bitcoinConfUrl = `http://143.198.27.163:3000/replit/timmy-tower/raw/branch/main/infrastructure/configs/bitcoin.conf`;
const lndConfUrl = `http://143.198.27.163:3000/replit/timmy-tower/raw/branch/main/infrastructure/configs/lnd.conf`;
const dockerComposeUrl = `http://143.198.27.163:3000/replit/timmy-tower/raw/branch/main/infrastructure/docker-compose.yml`;
const lndInitUrl = `http://143.198.27.163:3000/replit/timmy-tower/raw/branch/main/infrastructure/lnd-init.sh`;
const sweepUrl = `http://143.198.27.163:3000/replit/timmy-tower/raw/branch/main/infrastructure/sweep.sh`;
const sweepConfExampleUrl = `http://143.198.27.163:3000/replit/timmy-tower/raw/branch/main/infrastructure/sweep.conf.example`;
const opsUrl = `http://143.198.27.163:3000/replit/timmy-tower/raw/branch/main/infrastructure/ops.sh`;
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 ${setupScriptUrl} > /root/setup.sh
- path: /root/configs/bitcoin.conf
content: |
curl -s ${bitcoinConfUrl} > /root/configs/bitcoin.conf
- path: /root/configs/lnd.conf
content: |
curl -s ${lndConfUrl} > /root/configs/lnd.conf
- path: /root/docker-compose.yml
content: |
curl -s ${dockerComposeUrl} > /root/docker-compose.yml
- path: /root/lnd-init.sh
permissions: '0755'
content: |
curl -s ${lndInitUrl} > /root/lnd-init.sh
- path: /root/sweep.sh
permissions: '0755'
content: |
curl -s ${sweepUrl} > /root/sweep.sh
- path: /root/sweep.conf.example
content: |
curl -s ${sweepConfExampleUrl} > /root/sweep.conf.example
- path: /root/ops.sh
permissions: '0755'
content: |
curl -s ${opsUrl} > /root/ops.sh
runcmd:
- mkdir -p /root/configs
- curl -s ${setupScriptUrl} > /tmp/setup.sh
- chmod +x /tmp/setup.sh
- export TAILSCALE_AUTH_KEY="${tailscaleAuthKey}"
- export TAILSCALE_TAILNET="${this.config.tailscaleTailnet}"
- /tmp/setup.sh
`;
export const provisionerService = new ProvisionerService();

View File

@@ -0,0 +1,37 @@
/** In-memory HTTP request counters for the /api/metrics endpoint. */
export interface RequestCountsSnapshot {
total: number;
by_status: Record<string, number>;
errors_4xx: number;
errors_5xx: number;
}
class RequestCounters {
private total = 0;
private byStatus: Record<number, number> = {};
private errors4xx = 0;
private errors5xx = 0;
record(statusCode: number): void {
this.total++;
this.byStatus[statusCode] = (this.byStatus[statusCode] ?? 0) + 1;
if (statusCode >= 400 && statusCode < 500) this.errors4xx++;
else if (statusCode >= 500) this.errors5xx++;
}
snapshot(): RequestCountsSnapshot {
const byStatus: Record<string, number> = {};
for (const [code, count] of Object.entries(this.byStatus)) {
byStatus[code] = count;
}
return {
total: this.total,
by_status: byStatus,
errors_4xx: this.errors4xx,
errors_5xx: this.errors5xx,
};
}
}
export const requestCounters = new RequestCounters();

View File

@@ -0,0 +1,74 @@
/**
* Tower Log — narrative event feed (#7).
*
* Generates a prose narrative entry via Haiku whenever a key Workshop event
* occurs, persists it to the tower_log DB table, and emits it on the eventBus
* so connected WebSocket clients receive it in real time.
*/
import { randomUUID } from "crypto";
import { db, towerLog } from "@workspace/db";
import { desc } from "drizzle-orm";
import { eventBus } from "./event-bus.js";
import { agentService } from "./agent.js";
import { makeLogger } from "./logger.js";
const logger = makeLogger("tower-log");
export interface TowerLogRow {
id: string;
narrative: string;
eventType: string;
agentId: string | null;
jobId: string | null;
createdAt: Date;
}
/**
* Generate a narrative entry, persist it, and broadcast it via eventBus.
* Non-fatal — errors are logged but never thrown.
*/
export async function addTowerLogEntry(
eventType: string,
context?: string,
agentId?: string,
jobId?: string,
): Promise<void> {
try {
const narrative = await agentService.narrateEvent(eventType, context);
const id = randomUUID();
await db.insert(towerLog).values({
id,
narrative,
eventType,
agentId: agentId ?? null,
jobId: jobId ?? null,
});
// Broadcast to connected WS clients
eventBus.publish({
type: "tower_log:entry",
id,
narrative,
eventType,
agentId: agentId ?? null,
jobId: jobId ?? null,
createdAt: new Date().toISOString(),
});
} catch (err) {
logger.warn("addTowerLogEntry failed", { eventType, err: String(err) });
}
}
/**
* Fetch the most recent N entries from the DB, oldest-first.
*/
export async function getRecentTowerLog(limit = 20): Promise<TowerLogRow[]> {
const rows = await db
.select()
.from(towerLog)
.orderBy(desc(towerLog.createdAt))
.limit(limit);
return rows.reverse();
}

View File

@@ -205,6 +205,29 @@ export class TrustService {
verifyToken(token: string): { pubkey: string; expiry: number } | null {
return verifyToken(token);
}
// TEST-ONLY: apply one decay cycle immediately, ignoring time thresholds.
// Subtracts DECAY_PER_DAY (default 1) from the stored trust score and persists.
async decayOnce(pubkey: string): Promise<{ previousScore: number; newScore: number; newTier: TrustTier }> {
const identity = await this.getOrCreate(pubkey);
const previousScore = identity.trustScore;
const newScore = Math.max(0, previousScore - DECAY_PER_DAY);
const newTier = computeTier(newScore);
await db
.update(nostrIdentities)
.set({ trustScore: newScore, tier: newTier, updatedAt: new Date() })
.where(eq(nostrIdentities.pubkey, pubkey));
logger.info("trust: test decay applied", {
pubkey: pubkey.slice(0, 8),
previousScore,
newScore,
newTier,
});
return { previousScore, newScore, newTier };
}
}
export const trustService = new TrustService();

View File

@@ -0,0 +1,18 @@
import crypto from "crypto";
import type { Request, Response, NextFunction } from "express";
const HEADER = "X-Request-Id";
/**
* Assigns a unique request ID to every incoming request.
* If the client (or a reverse proxy) already sent X-Request-Id, reuse it;
* otherwise generate a short random hex string.
* The ID is stored on `res.locals.requestId` for downstream middleware/routes
* and echoed back via the X-Request-Id response header.
*/
export function requestIdMiddleware(req: Request, res: Response, next: NextFunction): void {
const id = (req.headers[HEADER.toLowerCase()] as string | undefined) ?? crypto.randomUUID();
res.locals["requestId"] = id;
res.setHeader(HEADER, id);
next();
}

View File

@@ -1,6 +1,7 @@
import type { Request, Response, NextFunction } from "express";
import { makeLogger } from "../lib/logger.js";
import { latencyHistogram } from "../lib/histogram.js";
import { requestCounters } from "../lib/request-counters.js";
const logger = makeLogger("http");
@@ -13,8 +14,10 @@ export function responseTimeMiddleware(req: Request, res: Response, next: NextFu
const routeKey = `${req.method} ${route ?? req.path}`;
latencyHistogram.record(routeKey, durationMs);
requestCounters.record(res.statusCode);
logger.info("request", {
request_id: res.locals["requestId"] ?? null,
method: req.method,
path: req.path,
route: route ?? null,

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 } = req.params; // Assuming ID is always valid, add Zod validation later
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

@@ -32,12 +32,16 @@ import { eventBus, type BusEvent } from "../lib/event-bus.js";
import { makeLogger } from "../lib/logger.js";
import { getWorldState, setAgentStateInWorld } from "../lib/world-state.js";
import { agentService } from "../lib/agent.js";
import { addTowerLogEntry, getRecentTowerLog } from "../lib/tower-log.js";
import { db, worldEvents } from "@workspace/db";
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;
@@ -247,6 +251,37 @@ function translateEvent(ev: BusEvent): object | null {
};
}
// ── Real-time cost ticker (#68) ───────────────────────────────────────────
case "cost:update":
return {
type: "cost_update",
jobId: ev.jobId,
sats: ev.sats,
phase: ev.phase,
isFinal: ev.isFinal,
};
// ── Agent commentary (#1) ─────────────────────────────────────────────────
case "agent_commentary":
return {
type: "agent_commentary",
agentId: ev.agentId,
jobId: ev.jobId,
text: ev.text,
};
// ── Tower Log (#7) ────────────────────────────────────────────────────────
case "tower_log:entry":
return {
type: "tower_log_entry",
id: ev.id,
narrative: ev.narrative,
eventType: ev.eventType,
agentId: ev.agentId,
jobId: ev.jobId,
createdAt: ev.createdAt,
};
default:
return null;
}
@@ -284,6 +319,17 @@ async function sendWorldStateBootstrap(socket: WebSocket): Promise<void> {
} catch {
send(socket, { type: "world_state", ...getWorldState(), recentEvents: [] });
}
// Send recent tower log entries
try {
const logEntries = await getRecentTowerLog(20);
send(socket, {
type: "tower_log_history",
entries: logEntries,
});
} catch {
/* non-fatal */
}
}
export function attachWebSocketServer(server: Server): void {
@@ -304,12 +350,20 @@ 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?` });
}
void addTowerLogEntry("visitor:enter", undefined, "timmy");
wss.clients.forEach(c => {
if (c !== socket && c.readyState === 1) {
c.send(JSON.stringify({ type: "visitor_count", count: wss.clients.size }));
@@ -318,6 +372,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) }));
@@ -379,5 +437,59 @@ 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";
void addTowerLogEntry("job:complete", undefined, "alpha", ev.jobId);
} else if (ev.state === "rejected") {
agentId = "alpha"; phase = "rejected";
void addTowerLogEntry("job:rejected", undefined, "beta", ev.jobId);
} else if (ev.state === "failed") {
void addTowerLogEntry("job:failed", undefined, "alpha", ev.jobId);
}
} else if (ev.type === "job:paid") {
jobId = ev.jobId;
agentId = "delta";
phase = ev.invoiceType === "eval" ? "eval_paid" : "work_paid";
if (ev.invoiceType === "eval") {
void addTowerLogEntry("payment:eval", undefined, "delta", ev.jobId);
} else if (ev.invoiceType === "work") {
void addTowerLogEntry("payment:work", undefined, "delta", ev.jobId);
}
}
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

@@ -2,7 +2,7 @@ import { Router, type Request, type Response } from "express";
import { randomBytes, randomUUID } from "crypto";
import { verifyEvent, validateEvent } from "nostr-tools";
import { db, nostrTrustVouches, nostrIdentities, timmyNostrEvents } from "@workspace/db";
import { eq, count } from "drizzle-orm";
import { eq, count, desc } from "drizzle-orm";
import { trustService } from "../lib/trust.js";
import { timmyIdentityService } from "../lib/timmy-identity.js";
import { makeLogger } from "../lib/logger.js";
@@ -406,4 +406,65 @@ router.get("/identity/me", async (req: Request, res: Response) => {
}
});
// ── POST /identity/me/decay (TEST-ONLY — disabled in production) ──────────────
// Applies one decay cycle to the authenticated identity immediately, without
// the normal 30-day absence threshold. Useful in test suites.
// Returns 404 in production (NODE_ENV === "production").
router.post("/identity/me/decay", async (req: Request, res: Response) => {
if (process.env["NODE_ENV"] === "production") {
res.status(404).json({ error: "Not found" });
return;
}
const raw = req.headers["x-nostr-token"];
const token = typeof raw === "string" ? raw.trim() : null;
if (!token) {
res.status(401).json({ error: "Missing X-Nostr-Token header" });
return;
}
const parsed = trustService.verifyToken(token);
if (!parsed) {
res.status(401).json({ error: "Invalid or expired nostr_token" });
return;
}
try {
const result = await trustService.decayOnce(parsed.pubkey);
res.json({
pubkey: parsed.pubkey,
previousScore: result.previousScore,
newScore: result.newScore,
newTier: result.newTier,
});
} catch (err) {
res.status(500).json({ error: err instanceof Error ? err.message : "Decay failed" });
}
});
// ── GET /identity/leaderboard ─────────────────────────────────────────────────
// Returns the top 20 identities sorted by trust score descending.
// Public endpoint — no authentication required.
router.get("/identity/leaderboard", async (_req: Request, res: Response) => {
try {
const rows = await db
.select({
pubkey: nostrIdentities.pubkey,
trustScore: nostrIdentities.trustScore,
tier: nostrIdentities.tier,
interactionCount: nostrIdentities.interactionCount,
})
.from(nostrIdentities)
.orderBy(desc(nostrIdentities.trustScore))
.limit(20);
res.json(rows);
} catch (err) {
res.status(500).json({ error: err instanceof Error ? err.message : "Failed to fetch leaderboard" });
}
});
export default router;

View File

@@ -17,11 +17,14 @@ 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";
import towerLogRouter from "./tower-log.js";
const router: IRouter = Router();
router.use(healthRouter);
router.use(metricsRouter);
router.use(statsRouter);
router.use(jobsRouter);
router.use(estimateRouter);
router.use(bootstrapRouter);
@@ -31,6 +34,7 @@ router.use(relayRouter);
router.use(adminRelayRouter);
router.use(adminRelayQueueRouter);
router.use(demoRouter);
router.use(towerLogRouter);
router.use("/gemini", geminiRouter);
router.use(testkitRouter);
router.use(uiRouter);

View File

@@ -205,6 +205,8 @@ async function runEvalInBackground(
// to avoid economic DoS where pool is reserved before the user ever pays.
eventBus.publish({ type: "job:state", jobId, state: "awaiting_work_payment" });
// Emit estimated cost so the UI ticker can show ~N sats before payment
eventBus.publish({ type: "cost:update", jobId, sats: invoiceSats, phase: "work", isFinal: false });
} else {
await db
.update(jobs)
@@ -307,6 +309,10 @@ async function runWorkInBackground(
refundState,
});
eventBus.publish({ type: "job:completed", jobId, result: workResult.result });
// Emit final actual cost for the UI cost ticker
if (!isFree && actualAmountSats > 0) {
eventBus.publish({ type: "cost:update", jobId, sats: actualAmountSats, phase: "work", isFinal: true });
}
// Credit the generosity pool from paid interactions
if (!isFree && workAmountSats > 0) {

View File

@@ -0,0 +1,79 @@
import { type Express, Router } from "express";
import { z } from "zod";
import { Status } from "../lib/http.js";
import { rootLogger } from "../lib/logger.js";
const router = Router();
const log = rootLogger.child({ service: "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: Express.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;
}
// ── POST /api/relay/policy ────────────────────────────────────────────────────
const relayPolicyRequestSchema = z.object({
event: z.object({
id: z.string(),
pubkey: z.string(),
kind: z.number(),
created_at: z.number(),
tags: z.array(z.array(z.string())),
content: z.string(),
sig: z.string(),
}),
receivedAt: z.number(),
sourceType: z.string(),
sourceInfo: z.string(),
});
type StrfryAction = "accept" | "reject" | "shadowReject";
router.post("/relay/policy", (req, res) => {
if (!isAuthenticated(req)) {
return res.status(Status.UNAUTHORIZED).json({
action: "reject",
msg: "unauthorized",
});
}
const parse = relayPolicyRequestSchema.safeParse(req.body);
if (!parse.success) {
log.warn("invalid /relay/policy request", { error: parse.error.format() });
return res.status(Status.BAD_REQUEST).json({
action: "reject",
msg: "invalid request",
});
}
const eventId = parse.data.event.id;
// 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

@@ -1,6 +1,6 @@
import { Router, type Request, type Response } from "express";
import { randomBytes, randomUUID, createHash } from "crypto";
import { db, sessions, sessionRequests, type Session } from "@workspace/db";
import { db, sessions, sessionRequests, sessionMessages, getSessionHistory, type Session } from "@workspace/db";
import { eq, and } from "drizzle-orm";
import { lnbitsService } from "../lib/lnbits.js";
import { sessionsLimiter } from "../lib/rate-limiter.js";
@@ -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))!;
}
@@ -312,6 +313,14 @@ router.post("/sessions/:id/request", async (req: Request, res: Response) => {
const requestId = randomUUID();
const btcPriceUsd = await getBtcPriceUsd();
// 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);
const evalCostUsd = pricingService.calculateActualCostUsd(
@@ -343,7 +352,7 @@ router.post("/sessions/:id/request", async (req: Request, res: Response) => {
if (evalResult.accepted) {
try {
const workResult = await agentService.executeWork(requestText);
const workResult = await agentService.executeWork(requestText, history);
workInputTokens = workResult.inputTokens;
workOutputTokens = workResult.outputTokens;
workCostUsd = pricingService.calculateActualCostUsd(
@@ -452,8 +461,21 @@ router.post("/sessions/:id/request", async (req: Request, res: Response) => {
updatedAt: new Date(),
})
.where(eq(sessions.id, id));
// Persist conversation history only for completed requests
if (finalState === "complete") {
await tx.insert(sessionMessages).values([
{ sessionId: id, role: "user" as const, content: requestText, tokenCount: Math.ceil(requestText.length / 4) },
{ sessionId: id, role: "assistant" as const, content: result ?? "", tokenCount: Math.ceil((result ?? "").length / 4) },
]);
}
});
// Emit real-time cost update for the UI cost ticker (#68)
if (finalState === "complete" && debitedSats > 0) {
eventBus.publish({ type: "cost:update", jobId: requestId, sats: debitedSats, phase: "session", isFinal: true });
}
// ── Trust scoring ────────────────────────────────────────────────────────
if (session.nostrPubkey) {
if (finalState === "complete") {
@@ -558,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

@@ -29,6 +29,12 @@ const router = Router();
* Guarded on stubMode=true; polls until state=provisioning|ready (20 s timeout).
* - T24 ADDED: costLedger completeness after job completion — 8 fields, honest-accounting
* invariant (actualAmountSats ≤ workAmountSats), refundState enum check.
* - T41 ADDED: POST /api/jobs with valid Nostr token → nostrPubkey in response matches identity.
* - T42 ADDED: POST /api/sessions with valid Nostr token → nostrPubkey in response matches identity.
* - T43 ADDED: GET /identity/me returns full trust fields (tier, score, interactionCount).
* - T44 ADDED: POST /identity/me/decay (test-only endpoint, 404 in prod) → score decremented.
* - T45 ADDED: GET /identity/leaderboard → HTTP 200, array sorted by trustScore desc.
* New endpoints identity/me/decay and identity/leaderboard added to identity.ts.
*/
router.get("/testkit", (req: Request, res: Response) => {
const proto =
@@ -1092,6 +1098,208 @@ NODESCRIPT
fi
fi
# ===========================================================================
# T41T45 — Nostr identity lifecycle: token decorates jobs/sessions + trust ops
# Requires node + nostr-tools (same guard as T36). All five tests share one
# inline node script that performs the full lifecycle and emits a JSON blob.
# ===========================================================================
# ---------------------------------------------------------------------------
# T41T45 Preamble — ephemeral keypair → challenge → sign → verify → token
# Then: create job, create session, GET /identity/me, decay, leaderboard.
# ---------------------------------------------------------------------------
NOSTR_LC_SKIP=false
NOSTR_LC_OUT=""
if ! command -v node >/dev/null 2>&1; then
NOSTR_LC_SKIP=true
fi
if [[ "\$NOSTR_LC_SKIP" == "false" ]]; then
NOSTR_LC_TMPFILE=\$(mktemp /tmp/nostr_lc_XXXXXX.cjs)
cat > "\$NOSTR_LC_TMPFILE" << 'NODESCRIPT'
'use strict';
const https = require('https');
const http = require('http');
const BASE = process.argv[2];
let nt;
const NOSTR_CJS = '/home/runner/workspace/artifacts/api-server/node_modules/nostr-tools/lib/cjs/index.js';
try { nt = require('nostr-tools'); } catch (_) { try { nt = require(NOSTR_CJS); } catch (_) { process.stderr.write('nostr-tools not importable\n'); process.exit(1); } }
const { generateSecretKey, getPublicKey, finalizeEvent } = nt;
function request(url, opts, body) {
return new Promise((resolve, reject) => {
const u = new URL(url);
const mod = u.protocol === 'https:' ? https : http;
const req = mod.request(u, opts, (res) => {
let data = '';
res.on('data', c => data += c);
res.on('end', () => resolve({ status: res.statusCode, body: data }));
});
req.on('error', reject);
if (body) req.write(body);
req.end();
});
}
async function main() {
const sk = generateSecretKey();
const pubkey = getPublicKey(sk);
// challenge → sign → verify
const chalRes = await request(BASE + '/api/identity/challenge', { method: 'POST', headers: { 'Content-Type': 'application/json' } }, '{}');
if (chalRes.status !== 200) { process.stderr.write('challenge failed: ' + chalRes.status + '\n'); process.exit(1); }
const { nonce } = JSON.parse(chalRes.body);
const event = finalizeEvent({ kind: 27235, content: nonce, tags: [], created_at: Math.floor(Date.now() / 1000) }, sk);
const verRes = await request(BASE + '/api/identity/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' } }, JSON.stringify({ event }));
if (verRes.status !== 200) { process.stderr.write('verify failed: ' + verRes.status + ' ' + verRes.body + '\n'); process.exit(1); }
const { nostr_token: token } = JSON.parse(verRes.body);
// POST /jobs with Nostr token
const jobRes = await request(BASE + '/api/jobs', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Nostr-Token': token } }, JSON.stringify({ request: 'T41 Nostr job test' }));
const jobBody = JSON.parse(jobRes.body);
const jobCode = jobRes.status;
const jobId = jobBody.jobId || null;
const jobNpub = jobBody.nostrPubkey || null;
// POST /sessions with Nostr token
const sessRes = await request(BASE + '/api/sessions', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Nostr-Token': token } }, JSON.stringify({ amount_sats: 200 }));
const sessBody = JSON.parse(sessRes.body);
const sessCode = sessRes.status;
const sessId = sessBody.sessionId || null;
const sessNpub = sessBody.nostrPubkey || null;
// GET /identity/me
const meRes = await request(BASE + '/api/identity/me', { method: 'GET', headers: { 'X-Nostr-Token': token } });
const meBody = JSON.parse(meRes.body);
const meScore = meBody.trust ? meBody.trust.score : null;
const meTier = meBody.trust ? meBody.trust.tier : null;
const meIcount = meBody.trust ? meBody.trust.interactionCount : null;
// POST /identity/me/decay (test-only; non-200 → skip T44 gracefully)
const decayRes = await request(BASE + '/api/identity/me/decay', { method: 'POST', headers: { 'X-Nostr-Token': token } });
const decayBody = JSON.parse(decayRes.body);
const decayCode = decayRes.status;
const decayPrev = decayBody.previousScore !== undefined ? decayBody.previousScore : null;
const decayNew = decayBody.newScore !== undefined ? decayBody.newScore : null;
// GET /identity/leaderboard
const lbRes = await request(BASE + '/api/identity/leaderboard', { method: 'GET', headers: {} });
const lbCode = lbRes.status;
let lbBody = [];
try { lbBody = JSON.parse(lbRes.body); } catch (_) {}
const lbIsArray = Array.isArray(lbBody);
const lbSorted = lbIsArray && lbBody.length < 2 ? true :
lbIsArray && lbBody.every((v, i) => i === 0 || lbBody[i - 1].trustScore >= v.trustScore);
process.stdout.write(JSON.stringify({
pubkey, token,
jobCode, jobId, jobNpub,
sessCode, sessId, sessNpub,
meScore, meTier, meIcount,
decayCode, decayPrev, decayNew,
lbCode, lbIsArray, lbSorted,
}) + '\n');
}
main().catch(err => { process.stderr.write(String(err) + '\n'); process.exit(1); });
NODESCRIPT
NOSTR_LC_EXIT=0
NOSTR_LC_OUT=\$(node "\$NOSTR_LC_TMPFILE" "\$BASE" 2>/dev/null) || NOSTR_LC_EXIT=\$?
rm -f "\$NOSTR_LC_TMPFILE"
if [[ \$NOSTR_LC_EXIT -ne 0 || -z "\$NOSTR_LC_OUT" ]]; then
NOSTR_LC_SKIP=true
fi
fi
# Helper: extract a field from NOSTR_LC_OUT
_lc() { echo "\$NOSTR_LC_OUT" | jq -r ".\$1" 2>/dev/null || echo ""; }
# ---------------------------------------------------------------------------
# T41 — POST /jobs with valid Nostr token → nostrPubkey in response
# ---------------------------------------------------------------------------
sep "Test 41 — POST /jobs with Nostr token → nostrPubkey set"
if [[ "\$NOSTR_LC_SKIP" == "true" ]]; then
note SKIP "node unavailable or lifecycle preamble failed — skipping T41"
SKIP=\$((SKIP+1))
else
T41_CODE=\$(_lc jobCode); T41_NPUB=\$(_lc jobNpub); T41_PK=\$(_lc pubkey)
if [[ "\$T41_CODE" == "201" && -n "\$T41_NPUB" && "\$T41_NPUB" != "null" && "\$T41_NPUB" == "\$T41_PK" ]]; then
note PASS "HTTP 201, nostrPubkey=\${T41_NPUB:0:8}... matches token identity"
PASS=\$((PASS+1))
else
note FAIL "code=\$T41_CODE nostrPubkey='\$T41_NPUB' expected='\$T41_PK'"
FAIL=\$((FAIL+1))
fi
fi
# ---------------------------------------------------------------------------
# T42 — POST /sessions with valid Nostr token → nostrPubkey in response
# ---------------------------------------------------------------------------
sep "Test 42 — POST /sessions with Nostr token → nostrPubkey set"
if [[ "\$NOSTR_LC_SKIP" == "true" ]]; then
note SKIP "node unavailable or lifecycle preamble failed — skipping T42"
SKIP=\$((SKIP+1))
else
T42_CODE=\$(_lc sessCode); T42_NPUB=\$(_lc sessNpub); T42_PK=\$(_lc pubkey)
if [[ "\$T42_CODE" == "201" && -n "\$T42_NPUB" && "\$T42_NPUB" != "null" && "\$T42_NPUB" == "\$T42_PK" ]]; then
note PASS "HTTP 201, nostrPubkey=\${T42_NPUB:0:8}... matches token identity"
PASS=\$((PASS+1))
else
note FAIL "code=\$T42_CODE nostrPubkey='\$T42_NPUB' expected='\$T42_PK'"
FAIL=\$((FAIL+1))
fi
fi
# ---------------------------------------------------------------------------
# T43 — GET /identity/me returns full trust fields (tier, score, interactionCount)
# ---------------------------------------------------------------------------
sep "Test 43 — GET /identity/me returns tier + score + interactionCount"
if [[ "\$NOSTR_LC_SKIP" == "true" ]]; then
note SKIP "node unavailable or lifecycle preamble failed — skipping T43"
SKIP=\$((SKIP+1))
else
T43_TIER=\$(_lc meTier); T43_SCORE=\$(_lc meScore); T43_ICOUNT=\$(_lc meIcount)
if [[ -n "\$T43_TIER" && "\$T43_TIER" != "null" \
&& "\$T43_SCORE" != "" && "\$T43_SCORE" != "null" \
&& "\$T43_ICOUNT" != "" && "\$T43_ICOUNT" != "null" ]]; then
note PASS "tier=\$T43_TIER score=\$T43_SCORE interactionCount=\$T43_ICOUNT"
PASS=\$((PASS+1))
else
note FAIL "tier='\$T43_TIER' score='\$T43_SCORE' icount='\$T43_ICOUNT'"
FAIL=\$((FAIL+1))
fi
fi
# ---------------------------------------------------------------------------
# T44 — POST /identity/me/decay (test-only endpoint) → score decremented
# Skipped gracefully if endpoint returns non-200 (e.g., production mode).
# ---------------------------------------------------------------------------
sep "Test 44 — POST /identity/me/decay (test mode) → trust_score decremented"
if [[ "\$NOSTR_LC_SKIP" == "true" ]]; then
note SKIP "node unavailable or lifecycle preamble failed — skipping T44"
SKIP=\$((SKIP+1))
else
T44_CODE=\$(_lc decayCode); T44_PREV=\$(_lc decayPrev); T44_NEW=\$(_lc decayNew)
if [[ "\$T44_CODE" != "200" ]]; then
note SKIP "decay endpoint returned code=\$T44_CODE (not in test mode) — skipping T44"
SKIP=\$((SKIP+1))
elif [[ -n "\$T44_PREV" && -n "\$T44_NEW" && "\$T44_NEW" =~ ^[0-9]+\$ && "\$T44_PREV" =~ ^[0-9]+\$ && \$T44_NEW -le \$T44_PREV ]]; then
note PASS "previousScore=\$T44_PREV newScore=\$T44_NEW (decremented or floored at 0)"
PASS=\$((PASS+1))
else
note FAIL "code=\$T44_CODE previousScore='\$T44_PREV' newScore='\$T44_NEW' (expected new ≤ prev)"
FAIL=\$((FAIL+1))
fi
fi
# ---------------------------------------------------------------------------
# T45 — GET /identity/leaderboard → HTTP 200, array sorted by trust score
# ---------------------------------------------------------------------------
sep "Test 45 — GET /identity/leaderboard → sorted array"
if [[ "\$NOSTR_LC_SKIP" == "true" ]]; then
note SKIP "node unavailable or lifecycle preamble failed — skipping T45"
SKIP=\$((SKIP+1))
else
T45_CODE=\$(_lc lbCode); T45_ARRAY=\$(_lc lbIsArray); T45_SORTED=\$(_lc lbSorted)
if [[ "\$T45_CODE" == "200" && "\$T45_ARRAY" == "true" && "\$T45_SORTED" == "true" ]]; then
note PASS "HTTP 200, array returned and sorted by trustScore desc"
PASS=\$((PASS+1))
else
note FAIL "code=\$T45_CODE isArray=\$T45_ARRAY sorted=\$T45_SORTED"
FAIL=\$((FAIL+1))
fi
fi
# ===========================================================================
# FUTURE STUBS — placeholders for upcoming tasks (do not affect PASS/FAIL)
# ===========================================================================

View File

@@ -0,0 +1,21 @@
import { Router, type Request, type Response } from "express";
import { getRecentTowerLog } from "../lib/tower-log.js";
import { makeLogger } from "../lib/logger.js";
const logger = makeLogger("tower-log-route");
const router = Router();
/**
* GET /api/tower-log — return the 20 most recent narrative entries, oldest first.
*/
router.get("/tower-log", async (_req: Request, res: Response) => {
try {
const entries = await getRecentTowerLog(20);
res.json({ entries });
} catch (err) {
logger.error("GET /api/tower-log failed", { error: String(err) });
res.status(500).json({ error: "tower_log_error" });
}
});
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, router } 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, useColorScheme } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Colors } from "@/constants/colors";
@@ -13,16 +13,16 @@ import { Colors } from "@/constants/colors";
function NativeTabLayout() {
return (
<NativeTabs>
<NativeTabs.Trigger name="index">
<Icon sf={{ default: "face.smiling", selected: "face.smiling.fill" }} />
<NativeTabs.Trigger name=\"index\">
<Icon sf={{ default: \"face.smiling\", selected: \"face.smiling.fill\" }} />
<Label>Timmy</Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger name="matrix">
<Icon sf={{ default: "cube", selected: "cube.fill" }} />
<NativeTabs.Trigger name=\"matrix\">
<Icon sf={{ default: \"cube\", selected: \"cube.fill\" }} />
<Label>Matrix</Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger name="feed">
<Icon sf={{ default: "list.bullet", selected: "list.bullet.circle.fill" }} />
<NativeTabs.Trigger name=\"feed\">
<Icon sf={{ default: \"list.bullet\", selected: \"list.bullet.circle.fill\" }} />
<Label>Feed</Label>
</NativeTabs.Trigger>
</NativeTabs>
@@ -39,8 +39,7 @@ function ClassicTabLayout() {
<Tabs
screenOptions={{
headerShown: false,
tabBarActiveTintColor: C.accentGlow,
tabBarInactiveTintColor: C.textMuted,
tabBarActiveTintColor: C.accentGlow,\n tabBarInactiveTintColor: C.textMuted,
tabBarStyle: {
position: "absolute",
backgroundColor: isIOS ? "transparent" : C.surface,
@@ -52,7 +51,7 @@ function ClassicTabLayout() {
isIOS ? (
<BlurView
intensity={80}
tint="dark"
tint=\"dark\"
style={[StyleSheet.absoluteFill, { borderTopWidth: 0.5, borderTopColor: C.border }]}
/>
) : isWeb ? (
@@ -61,52 +60,53 @@ function ClassicTabLayout() {
/>
) : (
<View style={[StyleSheet.absoluteFill, { backgroundColor: C.surface, borderTopWidth: 0.5, borderTopColor: C.border }]} />
),
}}
),\
}}\
>
<Tabs.Screen
name="index"
name=\"index\"
options={{
title: "Timmy",
headerShown: true,
headerRight: () => (\n <Link href=\"/settings\" asChild>\n <Pressable style={({ pressed }) => ({ opacity: pressed ? 0.5 : 1 })}>
<Ionicons name=\"settings-outline\" size={24} color={C.text} style={{ marginRight: 15 }} />\n </Pressable>\n </Link>\n ),
tabBarIcon: ({ color, size }) =>
isIOS ? (
<SymbolView name="face.smiling" tintColor={color} size={size} />
<SymbolView name=\"face.smiling\" tintColor={color} size={size} />
) : (
<MaterialCommunityIcons name="emoticon-outline" size={size} color={color} />
),
}}
<MaterialCommunityIcons name=\"emoticon-outline\" size={size} color={color} />
),\
}}\
/>
<Tabs.Screen
name="matrix"
name=\"matrix\"
options={{
title: "Matrix",
tabBarIcon: ({ color, size }) =>
isIOS ? (
<SymbolView name="cube" tintColor={color} size={size} />
<SymbolView name=\"cube\" tintColor={color} size={size} />
) : (
<MaterialCommunityIcons name="cube-outline" size={size} color={color} />
),
}}
<MaterialCommunityIcons name=\"cube-outline\" size={size} color={color} />
),\
}}\
/>
<Tabs.Screen
name="feed"
name=\"feed\"
options={{
title: "Feed",
tabBarIcon: ({ color, size }) =>
isIOS ? (
<SymbolView name="list.bullet" tintColor={color} size={size} />
<SymbolView name=\"list.bullet\" tintColor={color} size={size} />
) : (
<Feather name="activity" size={size} color={color} />
),
}}
<Feather name=\"activity\" size={size} color={color} />
),\
}}\
/>
</Tabs>
);
}
export default function TabLayout() {
if (isLiquidGlassAvailable()) {
return <NativeTabLayout />;
}
return <ClassicTabLayout />;
if (isLiquidGlassAvailable()) {\n return (\n <NativeTabs>\n <NativeTabs.Screen\n name=\"index\"\n options={{\n title: \"Timmy\",\n headerShown: true,\n headerRight: () => (\n <Link href=\"/settings\" asChild>\n <Pressable style={({ pressed }) => ({ opacity: pressed ? 0.5 : 1 })}>\n <Ionicons name=\"settings-outline\" size={24} color={C.text} style={{ marginRight: 15 }} />\n </Pressable>\n </Link>\n ),\n }}\n />\n <NativeTabs.Screen name=\"matrix\" />\n <NativeTabs.Screen name=\"feed\" />\n </NativeTabs>\n );\n }
return <ClassicTabLayout />;\
}

View File

@@ -14,6 +14,7 @@ import {
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { ConnectionBadge } from "@/components/ConnectionBadge";
import { JobSubmissionSheet } from "@/components/JobSubmissionSheet";
import { TimmyFace } from "@/components/TimmyFace";
import { Colors } from "@/constants/colors";
import { useTimmy } from "@/context/TimmyContext";
@@ -64,6 +65,7 @@ export default function FaceScreen() {
const [isListening, setIsListening] = useState(false);
const [transcript, setTranscript] = useState("");
const [lastReply, setLastReply] = useState("");
const [jobSheetVisible, setJobSheetVisible] = useState(false);
const micScale = useRef(new Animated.Value(1)).current;
const micPulseRef = useRef<Animated.CompositeAnimation | null>(null);
const webRecognitionRef = useRef<WebSpeechRecognition | null>(null);
@@ -273,31 +275,48 @@ export default function FaceScreen() {
</View>
) : null}
{/* Mic button */}
{/* Action buttons */}
<View style={[styles.micArea, { paddingBottom: bottomPad }]}>
<Pressable
onPress={handleMicPress}
accessibilityRole="button"
accessibilityLabel={isListening ? "Stop listening" : "Start voice"}
>
<Animated.View
style={[
styles.micButton,
isListening && styles.micButtonActive,
{ transform: [{ scale: micScale }] },
]}
<View style={styles.actionRow}>
<Pressable
onPress={handleMicPress}
accessibilityRole="button"
accessibilityLabel={isListening ? "Stop listening" : "Start voice"}
>
<Ionicons
name={isListening ? "mic" : "mic-outline"}
size={32}
color={isListening ? "#fff" : C.textSecondary}
/>
</Animated.View>
</Pressable>
<Animated.View
style={[
styles.micButton,
isListening && styles.micButtonActive,
{ transform: [{ scale: micScale }] },
]}
>
<Ionicons
name={isListening ? "mic" : "mic-outline"}
size={32}
color={isListening ? "#fff" : C.textSecondary}
/>
</Animated.View>
</Pressable>
<Pressable
onPress={() => setJobSheetVisible(true)}
accessibilityRole="button"
accessibilityLabel="Submit paid job"
>
<View style={styles.jobButton}>
<Ionicons name="flash" size={26} color={C.jobStarted} />
</View>
</Pressable>
</View>
<Text style={styles.micHint}>
{isListening ? "Listening..." : "Tap to speak to Timmy"}
{isListening ? "Listening..." : "Tap mic to speak \u00B7 bolt to submit a job"}
</Text>
</View>
<JobSubmissionSheet
visible={jobSheetVisible}
onClose={() => setJobSheetVisible(false)}
/>
</View>
);
}
@@ -405,6 +424,26 @@ const styles = StyleSheet.create({
paddingTop: 16,
gap: 10,
},
actionRow: {
flexDirection: "row",
alignItems: "center",
gap: 20,
},
jobButton: {
width: 52,
height: 52,
borderRadius: 26,
backgroundColor: C.surface,
borderWidth: 1.5,
borderColor: C.jobStarted + "66",
alignItems: "center",
justifyContent: "center",
shadowColor: C.jobStarted,
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.25,
shadowRadius: 6,
elevation: 4,
},
micButton: {
width: 72,
height: 72,

View File

@@ -5,25 +5,52 @@ import {
Inter_700Bold,
useFonts,
} from "@expo-google-fonts/inter";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { Stack } from "expo-router";
import { Stack, router, useSegments } from "expo-router";
import * as SplashScreen from "expo-splash-screen";
import React, { useEffect } from "react";
import React, { useEffect, useState } from "react";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { KeyboardProvider } from "react-native-keyboard-controller";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { ErrorBoundary } from "@/components/ErrorBoundary";
import { TimmyProvider } from "@/context/TimmyContext";
import { ONBOARDING_COMPLETED_KEY } from "@/constants/storage-keys";
SplashScreen.preventAutoHideAsync();
const queryClient = new QueryClient();
function RootLayoutNav() {
const segments = useSegments();
const [onboardingChecked, setOnboardingChecked] = useState(false);
const [needsOnboarding, setNeedsOnboarding] = useState(false);
useEffect(() => {
AsyncStorage.getItem(ONBOARDING_COMPLETED_KEY).then((value) => {
setNeedsOnboarding(value !== "true");
setOnboardingChecked(true);
});
}, []);
useEffect(() => {
if (!onboardingChecked) return;
const inOnboarding = segments[0] === "onboarding";
if (needsOnboarding && !inOnboarding) {
router.replace("/onboarding");
} else if (!needsOnboarding && inOnboarding) {
router.replace("/(tabs)");
}
}, [onboardingChecked, needsOnboarding, segments]);
return (
<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,264 @@
import AsyncStorage from "@react-native-async-storage/async-storage";
import { Ionicons } from "@expo/vector-icons";
import { router } from "expo-router";
import React, { useCallback, useRef, useState } from "react";
import {
Dimensions,
FlatList,
Platform,
Pressable,
StyleSheet,
Text,
View,
type ViewToken,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { TimmyFace } from "@/components/TimmyFace";
import { Colors } from "@/constants/colors";
import { ONBOARDING_COMPLETED_KEY } from "@/constants/storage-keys";
const C = Colors.dark;
const { width: SCREEN_WIDTH } = Dimensions.get("window");
const slideStyles = StyleSheet.create({
iconCircle: {
width: 140,
height: 140,
borderRadius: 70,
backgroundColor: C.surfaceElevated,
borderWidth: 1,
borderColor: C.border,
alignItems: "center",
justifyContent: "center",
},
});
type Slide = {
id: string;
icon: React.ReactNode;
title: string;
description: string;
};
const slides: Slide[] = [
{
id: "welcome",
icon: <TimmyFace mood="speaking" size={140} />,
title: "Meet Timmy",
description:
"Your AI wizard powered by Lightning.\nAsk questions, get answers — pay only for what you use.",
},
{
id: "voice",
icon: (
<View style={slideStyles.iconCircle}>
<Ionicons name="mic" size={64} color={C.accentGlow} />
</View>
),
title: "Talk, Don't Type",
description:
"Tap the mic and speak naturally.\nTimmy listens, thinks, and responds out loud.",
},
{
id: "lightning",
icon: (
<View style={slideStyles.iconCircle}>
<Ionicons name="flash" size={64} color="#F59E0B" />
</View>
),
title: "Lightning Fast Payments",
description:
"Pay per request with Bitcoin Lightning.\nNo accounts, no subscriptions — just sats.",
},
];
function Dot({ active }: { active: boolean }) {
return (
<View
style={[
styles.dot,
active ? styles.dotActive : styles.dotInactive,
]}
/>
);
}
export default function OnboardingScreen() {
const insets = useSafeAreaInsets();
const [currentIndex, setCurrentIndex] = useState(0);
const flatListRef = useRef<FlatList<Slide>>(null);
const onViewableItemsChanged = useRef(
({ viewableItems }: { viewableItems: ViewToken[] }) => {
if (viewableItems.length > 0 && viewableItems[0].index != null) {
setCurrentIndex(viewableItems[0].index);
}
}
).current;
const viewabilityConfig = useRef({ viewAreaCoveragePercentThreshold: 50 }).current;
const isLastSlide = currentIndex === slides.length - 1;
const handleNext = useCallback(() => {
if (isLastSlide) {
completeOnboarding();
} else {
flatListRef.current?.scrollToIndex({ index: currentIndex + 1, animated: true });
}
}, [currentIndex, isLastSlide]);
const handleSkip = useCallback(() => {
completeOnboarding();
}, []);
const completeOnboarding = async () => {
await AsyncStorage.setItem(ONBOARDING_COMPLETED_KEY, "true");
router.replace("/(tabs)");
};
const renderSlide = ({ item }: { item: Slide }) => (
<View style={[styles.slide, { width: SCREEN_WIDTH }]}>
<View style={styles.slideIconArea}>{item.icon}</View>
<Text style={styles.slideTitle}>{item.title}</Text>
<Text style={styles.slideDescription}>{item.description}</Text>
</View>
);
return (
<View style={[styles.container, { paddingTop: insets.top, paddingBottom: insets.bottom }]}>
{/* Skip button */}
{!isLastSlide && (
<Pressable style={styles.skipButton} onPress={handleSkip}>
<Text style={styles.skipText}>Skip</Text>
</Pressable>
)}
{/* Slides */}
<FlatList
ref={flatListRef}
data={slides}
renderItem={renderSlide}
keyExtractor={(item) => item.id}
horizontal
pagingEnabled
showsHorizontalScrollIndicator={false}
bounces={false}
onViewableItemsChanged={onViewableItemsChanged}
viewabilityConfig={viewabilityConfig}
style={styles.flatList}
/>
{/* Dots + Next/Get Started */}
<View style={styles.footer}>
<View style={styles.dots}>
{slides.map((s, i) => (
<Dot key={s.id} active={i === currentIndex} />
))}
</View>
<Pressable style={styles.nextButton} onPress={handleNext}>
<Text style={styles.nextButtonText}>
{isLastSlide ? "Get Started" : "Next"}
</Text>
{!isLastSlide && (
<Ionicons name="arrow-forward" size={18} color="#fff" />
)}
</Pressable>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: C.background,
},
skipButton: {
position: "absolute",
top: Platform.OS === "web" ? 20 : 56,
right: 24,
zIndex: 10,
padding: 8,
},
skipText: {
fontSize: 15,
fontFamily: "Inter_500Medium",
color: C.textSecondary,
},
flatList: {
flex: 1,
},
slide: {
flex: 1,
alignItems: "center",
justifyContent: "center",
paddingHorizontal: 40,
},
slideIconArea: {
marginBottom: 40,
alignItems: "center",
justifyContent: "center",
shadowColor: C.accent,
shadowOffset: { width: 0, height: 0 },
shadowOpacity: 0.25,
shadowRadius: 30,
elevation: 0,
},
slideTitle: {
fontSize: 28,
fontFamily: "Inter_700Bold",
color: C.text,
textAlign: "center",
marginBottom: 16,
letterSpacing: -0.5,
},
slideDescription: {
fontSize: 16,
fontFamily: "Inter_400Regular",
color: C.textSecondary,
textAlign: "center",
lineHeight: 24,
},
footer: {
paddingHorizontal: 24,
paddingBottom: 24,
gap: 24,
alignItems: "center",
},
dots: {
flexDirection: "row",
gap: 8,
},
dot: {
height: 8,
borderRadius: 4,
},
dotActive: {
width: 24,
backgroundColor: C.accent,
},
dotInactive: {
width: 8,
backgroundColor: C.textMuted,
},
nextButton: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: 8,
backgroundColor: C.accent,
paddingVertical: 16,
paddingHorizontal: 32,
borderRadius: 16,
width: "100%",
maxWidth: 320,
},
nextButtonText: {
fontSize: 17,
fontFamily: "Inter_600SemiBold",
color: "#fff",
},
});

View File

@@ -0,0 +1,249 @@
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 * as SecureStore from 'expo-secure-store';
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',
NOSTR_PRIVATE_KEY: 'settings_nostr_private_key', // Use SecureStore for this
};
export default function SettingsScreen() {
const { apiBaseUrl, setApiBaseUrl, isConnected, nostrPublicKey, connectNostr, disconnectNostr } = useTimmy();
const C = Colors.dark;
const [serverUrl, setServerUrl] = useState(apiBaseUrl);
const [jobCompletionNotifications, setJobCompletionNotifications] = useState(false);
const [lowBalanceWarning, setLowBalanceWarning] = useState(false);
const [currentNpub, setCurrentNpub] = useState<string | null>(nostrPublicKey);
useEffect(() => {
// Load settings from AsyncStorage and SecureStore
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));
}
// Nostr npub is handled by TimmyContext, so we just use the provided nostrPublicKey
setCurrentNpub(nostrPublicKey);
};
loadSettings();
}, [nostrPublicKey]);
// Update apiBaseUrl in context when serverUrl changes and is saved
useEffect(() => {
if (serverUrl !== apiBaseUrl) {
setApiBaseUrl(serverUrl);
AsyncStorage.setItem(STORAGE_KEYS.SERVER_URL, serverUrl);
}
}, [serverUrl, setApiBaseUrl, apiBaseUrl]);
const handleServerUrlChange = (text: string) => {
setServerUrl(text);
};
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 handleConnectNostr = async () => {
// This will ideally link to a dedicated Nostr connection flow
console.log('Connect Nostr button pressed');
// For now, simulate connection if not connected
if (!currentNpub) {
// This is a placeholder. Real implementation would involve generating/importing keys.
const simulatedNpub = 'npub1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
connectNostr(simulatedNpub, 'private_key_placeholder'); // Pass a placeholder private key
setCurrentNpub(simulatedNpub);
// In a real app, the private key would be securely stored and managed by the context
// For now, just a placeholder to show connected state
}
};
const handleDisconnectNostr = async () => {
await disconnectNostr();
setCurrentNpub(null);
};
const appVersion = Constants.expoConfig?.version || 'N/A';
const buildCommitHash = Constants.expoConfig?.extra?.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.field }]} // Apply text and background color from Colors
value={serverUrl}
onChangeText={handleServerUrlChange}
placeholder="Enter server URL"
placeholderTextColor={C.textMuted}
autoCapitalize="none"
autoCorrect={false}
/>
<ConnectionBadge isConnected={isConnected} />
</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.field}
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.field}
onValueChange={toggleLowBalanceWarning}
value={lowBalanceWarning}
/>
</View>
<Text style={styles.sectionHeader}>Identity</Text>
<View style={styles.settingItem}>
<Text style={styles.settingLabel}>Nostr Public Key</Text>
<Text style={[styles.settingValue, { color: C.textMuted }]}>
{currentNpub ? `${currentNpub.substring(0, 10)}...${currentNpub.substring(currentNpub.length - 5)}` : 'Not connected'}
</Text>
</View>
<View style={styles.buttonContainer}>
{!currentNpub ? (
<Pressable onPress={handleConnectNostr} style={({ pressed }) => [styles.button, { backgroundColor: C.accent, opacity: pressed ? 0.8 : 1 }]}>
<Text style={[styles.buttonText, { color: C.textInverted }]}>Connect Nostr</Text>
</Pressable>
) : (
<Pressable onPress={handleDisconnectNostr} style={({ pressed }) => [styles.button, { backgroundColor: C.destructive, opacity: pressed ? 0.8 : 1 }]}>
<Text style={[styles.buttonText, { color: C.textInverted }]}>Disconnect Nostr</Text>
</Pressable>
)}
</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.link }]}>View project on Gitea</Text>
</Pressable>
</ScrollView>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: Colors.dark.background, // Use background color from Colors
},
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,
},
buttonContainer: {
marginTop: 20,
alignItems: 'flex-start',
},
button: {
paddingVertical: 10,
paddingHorizontal: 15,
borderRadius: 8,
},
buttonText: {
fontSize: 16,
fontWeight: 'bold',
},
linkButton: {
flexDirection: 'row',
alignItems: 'center',
marginTop: 15,
paddingVertical: 8,
},
linkButtonText: {
marginLeft: 5,
fontSize: 16,
},
});

View File

@@ -11,6 +11,7 @@ const STATUS_CONFIG: Record<ConnectionStatus, { color: string; label: string }>
connecting: { color: "#F59E0B", label: "Connecting" },
connected: { color: "#10B981", label: "Live" },
disconnected: { color: "#6B7280", label: "Offline" },
reconnecting: { color: "#F59E0B", label: "Reconnecting" },
error: { color: "#EF4444", label: "Error" },
};
@@ -18,7 +19,7 @@ export function ConnectionBadge({ status }: { status: ConnectionStatus }) {
const pulseAnim = useRef(new Animated.Value(1)).current;
useEffect(() => {
if (status === "connecting") {
if (status === "connecting" || status === "reconnecting") {
const pulse = Animated.loop(
Animated.sequence([
Animated.timing(pulseAnim, { toValue: 0.3, duration: 600, useNativeDriver: true }),

View File

@@ -0,0 +1,737 @@
import { Ionicons } from "@expo/vector-icons";
import React, { useCallback, useEffect, useRef, useState } from "react";
import {
ActivityIndicator,
Animated,
Dimensions,
Keyboard,
Modal,
Platform,
Pressable,
ScrollView,
StyleSheet,
Text,
TextInput,
View,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import QRCode from "react-native-qrcode-svg";
import { Colors } from "@/constants/colors";
const C = Colors.dark;
const POLL_INTERVAL = 3000;
const SCREEN_WIDTH = Dimensions.get("window").width;
const QR_SIZE = Math.min(SCREEN_WIDTH - 80, 240);
const BASE_URL = process.env.EXPO_PUBLIC_DOMAIN ?? "";
function getApiBase(): string {
let domain = BASE_URL;
if (!domain) domain = "localhost:8080";
domain = domain.replace(/\/$/, "");
if (!/^https?:\/\//.test(domain)) {
const proto = domain.startsWith("localhost") ? "http" : "https";
domain = `${proto}://${domain}`;
}
return domain;
}
type JobState =
| "awaiting_eval_payment"
| "evaluating"
| "rejected"
| "awaiting_work_payment"
| "executing"
| "complete"
| "failed";
type InvoiceInfo = {
paymentRequest: string;
amountSats: number;
};
type JobStatus = {
jobId: string;
state: JobState;
evalInvoice?: InvoiceInfo;
workInvoice?: InvoiceInfo;
result?: string;
reason?: string;
errorMessage?: string;
};
type CreateJobResponse = {
jobId: string;
evalInvoice: InvoiceInfo;
};
type EstimateResponse = {
estimatedCostSats: number;
estimatedCostUsd: number;
btcPriceUsd: number;
};
const STATE_LABELS: Record<string, string> = {
awaiting_eval_payment: "Awaiting eval payment",
evaluating: "Evaluating your request...",
rejected: "Request rejected",
awaiting_work_payment: "Awaiting work payment",
executing: "Executing job...",
complete: "Complete!",
failed: "Job failed",
};
const STATE_ICONS: Record<string, string> = {
awaiting_eval_payment: "flash-outline",
evaluating: "hourglass-outline",
rejected: "close-circle-outline",
awaiting_work_payment: "flash-outline",
executing: "cog-outline",
complete: "checkmark-circle-outline",
failed: "alert-circle-outline",
};
type Props = {
visible: boolean;
onClose: () => void;
};
export function JobSubmissionSheet({ visible, onClose }: Props) {
const insets = useSafeAreaInsets();
const [prompt, setPrompt] = useState("");
const [estimate, setEstimate] = useState<EstimateResponse | null>(null);
const [estimateLoading, setEstimateLoading] = useState(false);
const [estimateError, setEstimateError] = useState("");
const [jobId, setJobId] = useState<string | null>(null);
const [jobStatus, setJobStatus] = useState<JobStatus | null>(null);
const [submitting, setSubmitting] = useState(false);
const [submitError, setSubmitError] = useState("");
const [resultExpanded, setResultExpanded] = useState(false);
const slideAnim = useRef(new Animated.Value(0)).current;
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
// Slide animation
useEffect(() => {
Animated.timing(slideAnim, {
toValue: visible ? 1 : 0,
duration: 300,
useNativeDriver: true,
}).start();
}, [visible, slideAnim]);
// Polling for job status
useEffect(() => {
if (!jobId) return;
const poll = async () => {
try {
const res = await fetch(`${getApiBase()}/api/jobs/${jobId}`);
if (!res.ok) return;
const data = (await res.json()) as JobStatus;
setJobStatus(data);
// Stop polling on terminal states
if (
data.state === "complete" ||
data.state === "failed" ||
data.state === "rejected"
) {
if (pollRef.current) {
clearInterval(pollRef.current);
pollRef.current = null;
}
}
} catch {
// ignore poll errors
}
};
// Immediately fetch once
void poll();
pollRef.current = setInterval(poll, POLL_INTERVAL);
return () => {
if (pollRef.current) {
clearInterval(pollRef.current);
pollRef.current = null;
}
};
}, [jobId]);
const resetState = useCallback(() => {
setPrompt("");
setEstimate(null);
setEstimateError("");
setJobId(null);
setJobStatus(null);
setSubmitting(false);
setSubmitError("");
setResultExpanded(false);
if (pollRef.current) {
clearInterval(pollRef.current);
pollRef.current = null;
}
}, []);
const handleClose = useCallback(() => {
resetState();
onClose();
}, [onClose, resetState]);
const handleEstimate = useCallback(async () => {
if (!prompt.trim()) return;
Keyboard.dismiss();
setEstimateLoading(true);
setEstimateError("");
setEstimate(null);
try {
const res = await fetch(`${getApiBase()}/api/jobs/estimate`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ request: prompt.trim() }),
});
if (!res.ok) {
const err = await res.json().catch(() => ({ error: "Request failed" }));
setEstimateError(
(err as { error?: string }).error ?? `HTTP ${res.status}`
);
return;
}
const data = (await res.json()) as EstimateResponse;
setEstimate(data);
} catch (e) {
setEstimateError(
e instanceof Error ? e.message : "Failed to get estimate"
);
} finally {
setEstimateLoading(false);
}
}, [prompt]);
const handleSubmit = useCallback(async () => {
if (!prompt.trim()) return;
Keyboard.dismiss();
setSubmitting(true);
setSubmitError("");
try {
const res = await fetch(`${getApiBase()}/api/jobs`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ request: prompt.trim() }),
});
if (!res.ok) {
const err = await res.json().catch(() => ({ error: "Request failed" }));
setSubmitError(
(err as { error?: string }).error ?? `HTTP ${res.status}`
);
return;
}
const data = (await res.json()) as CreateJobResponse;
setJobId(data.jobId);
setJobStatus({
jobId: data.jobId,
state: "awaiting_eval_payment",
evalInvoice: data.evalInvoice,
});
} catch (e) {
setSubmitError(
e instanceof Error ? e.message : "Failed to submit job"
);
} finally {
setSubmitting(false);
}
}, [prompt]);
// Determine which invoice to show
const activeInvoice: InvoiceInfo | undefined =
jobStatus?.state === "awaiting_work_payment"
? jobStatus.workInvoice
: jobStatus?.state === "awaiting_eval_payment"
? jobStatus.evalInvoice
: undefined;
const isTerminal =
jobStatus?.state === "complete" ||
jobStatus?.state === "failed" ||
jobStatus?.state === "rejected";
const isPolling = jobId != null && !isTerminal;
const renderContent = () => {
// === JOB IN PROGRESS / COMPLETE ===
if (jobId && jobStatus) {
return (
<ScrollView
style={styles.sheetScroll}
contentContainerStyle={styles.sheetScrollContent}
keyboardShouldPersistTaps="handled"
>
{/* Status badge */}
<View style={styles.statusRow}>
<Ionicons
name={
(STATE_ICONS[jobStatus.state] ?? "help-outline") as React.ComponentProps<typeof Ionicons>["name"]
}
size={20}
color={
jobStatus.state === "complete"
? C.jobCompleted
: jobStatus.state === "failed" || jobStatus.state === "rejected"
? C.error
: C.jobStarted
}
/>
<Text
style={[
styles.statusText,
jobStatus.state === "complete" && { color: C.jobCompleted },
(jobStatus.state === "failed" ||
jobStatus.state === "rejected") && { color: C.error },
]}
>
{STATE_LABELS[jobStatus.state] ?? jobStatus.state}
</Text>
{isPolling && (
<ActivityIndicator size="small" color={C.accent} />
)}
</View>
{/* Invoice QR */}
{activeInvoice && (
<View style={styles.qrContainer}>
<Text style={styles.qrLabel}>
{jobStatus.state === "awaiting_eval_payment"
? "Pay eval invoice"
: "Pay work invoice"}
</Text>
<View style={styles.qrWrapper}>
<QRCode
value={activeInvoice.paymentRequest}
size={QR_SIZE}
backgroundColor="#FFFFFF"
color="#000000"
/>
</View>
<Text style={styles.satsLabel}>
{activeInvoice.amountSats} sats
</Text>
<Text style={styles.invoiceHint}>
Scan with your Lightning wallet
</Text>
</View>
)}
{/* Rejection reason */}
{jobStatus.state === "rejected" && jobStatus.reason && (
<View style={styles.errorCard}>
<Ionicons name="close-circle" size={16} color={C.error} />
<Text style={styles.errorCardText}>{jobStatus.reason}</Text>
</View>
)}
{/* Error message */}
{jobStatus.state === "failed" && jobStatus.errorMessage && (
<View style={styles.errorCard}>
<Ionicons name="alert-circle" size={16} color={C.error} />
<Text style={styles.errorCardText}>
{jobStatus.errorMessage}
</Text>
</View>
)}
{/* Result */}
{jobStatus.state === "complete" && jobStatus.result && (
<Pressable
style={styles.resultCard}
onPress={() => setResultExpanded((v) => !v)}
>
<View style={styles.resultHeader}>
<Ionicons
name="checkmark-circle"
size={18}
color={C.jobCompleted}
/>
<Text style={styles.resultTitle}>Result</Text>
<Ionicons
name={resultExpanded ? "chevron-up" : "chevron-down"}
size={16}
color={C.textSecondary}
/>
</View>
<Text
style={styles.resultText}
numberOfLines={resultExpanded ? undefined : 6}
>
{jobStatus.result}
</Text>
</Pressable>
)}
{/* New job button for terminal states */}
{isTerminal && (
<Pressable style={styles.newJobButton} onPress={resetState}>
<Text style={styles.newJobButtonText}>Submit another job</Text>
</Pressable>
)}
</ScrollView>
);
}
// === INPUT FORM ===
return (
<ScrollView
style={styles.sheetScroll}
contentContainerStyle={styles.sheetScrollContent}
keyboardShouldPersistTaps="handled"
>
<Text style={styles.inputLabel}>What should Timmy do?</Text>
<TextInput
style={styles.textInput}
placeholder="Describe your job..."
placeholderTextColor={C.textMuted}
value={prompt}
onChangeText={setPrompt}
multiline
numberOfLines={4}
textAlignVertical="top"
maxLength={2000}
autoFocus
/>
{/* Estimate result */}
{estimate && (
<View style={styles.estimateCard}>
<Ionicons name="flash" size={16} color={C.jobStarted} />
<Text style={styles.estimateText}>
Estimated cost: {estimate.estimatedCostSats} sats (~$
{estimate.estimatedCostUsd.toFixed(4)})
</Text>
</View>
)}
{estimateError ? (
<View style={styles.errorCard}>
<Ionicons name="alert-circle" size={16} color={C.error} />
<Text style={styles.errorCardText}>{estimateError}</Text>
</View>
) : null}
{submitError ? (
<View style={styles.errorCard}>
<Ionicons name="alert-circle" size={16} color={C.error} />
<Text style={styles.errorCardText}>{submitError}</Text>
</View>
) : null}
{/* Action buttons */}
<View style={styles.buttonRow}>
<Pressable
style={[
styles.estimateButton,
(!prompt.trim() || estimateLoading) && styles.buttonDisabled,
]}
onPress={handleEstimate}
disabled={!prompt.trim() || estimateLoading}
>
{estimateLoading ? (
<ActivityIndicator size="small" color={C.accent} />
) : (
<>
<Ionicons name="calculator-outline" size={18} color={C.accent} />
<Text style={styles.estimateButtonText}>Estimate</Text>
</>
)}
</Pressable>
<Pressable
style={[
styles.submitButton,
(!prompt.trim() || submitting) && styles.buttonDisabled,
]}
onPress={handleSubmit}
disabled={!prompt.trim() || submitting}
>
{submitting ? (
<ActivityIndicator size="small" color="#fff" />
) : (
<>
<Ionicons name="flash" size={18} color="#fff" />
<Text style={styles.submitButtonText}>Submit Job</Text>
</>
)}
</Pressable>
</View>
</ScrollView>
);
};
return (
<Modal
visible={visible}
animationType="slide"
transparent
onRequestClose={handleClose}
>
<View style={styles.overlay}>
<Pressable style={styles.overlayBackdrop} onPress={handleClose} />
<Animated.View
style={[
styles.sheet,
{
paddingBottom: Math.max(insets.bottom, 16),
transform: [
{
translateY: slideAnim.interpolate({
inputRange: [0, 1],
outputRange: [600, 0],
}),
},
],
},
]}
>
{/* Handle bar */}
<View style={styles.handleRow}>
<View style={styles.handle} />
</View>
{/* Header */}
<View style={styles.sheetHeader}>
<Ionicons name="flash" size={22} color={C.jobStarted} />
<Text style={styles.sheetTitle}>Submit Job</Text>
<Pressable
onPress={handleClose}
hitSlop={12}
accessibilityRole="button"
accessibilityLabel="Close"
>
<Ionicons name="close" size={24} color={C.textSecondary} />
</Pressable>
</View>
{renderContent()}
</Animated.View>
</View>
</Modal>
);
}
const styles = StyleSheet.create({
overlay: {
flex: 1,
justifyContent: "flex-end",
},
overlayBackdrop: {
...StyleSheet.absoluteFillObject,
backgroundColor: "rgba(0,0,0,0.5)",
},
sheet: {
backgroundColor: C.surface,
borderTopLeftRadius: 20,
borderTopRightRadius: 20,
maxHeight: "85%",
borderWidth: 1,
borderBottomWidth: 0,
borderColor: C.border,
},
handleRow: {
alignItems: "center",
paddingTop: 10,
paddingBottom: 4,
},
handle: {
width: 36,
height: 4,
borderRadius: 2,
backgroundColor: C.textMuted,
},
sheetHeader: {
flexDirection: "row",
alignItems: "center",
paddingHorizontal: 20,
paddingVertical: 12,
gap: 10,
borderBottomWidth: 1,
borderBottomColor: C.border,
},
sheetTitle: {
flex: 1,
fontSize: 18,
fontFamily: "Inter_600SemiBold",
color: C.text,
},
sheetScroll: {
flex: 1,
},
sheetScrollContent: {
padding: 20,
gap: 16,
},
inputLabel: {
fontSize: 14,
fontFamily: "Inter_500Medium",
color: C.textSecondary,
},
textInput: {
backgroundColor: C.surfaceElevated,
borderRadius: 12,
borderWidth: 1,
borderColor: C.border,
color: C.text,
fontFamily: "Inter_400Regular",
fontSize: 15,
padding: 14,
minHeight: 100,
...(Platform.OS === "web" ? { outlineStyle: "none" as unknown as undefined } : {}),
},
estimateCard: {
flexDirection: "row",
alignItems: "center",
gap: 8,
backgroundColor: C.surfaceElevated,
borderRadius: 10,
padding: 12,
borderWidth: 1,
borderColor: C.jobStarted + "44",
},
estimateText: {
fontSize: 14,
fontFamily: "Inter_500Medium",
color: C.jobStarted,
flex: 1,
},
errorCard: {
flexDirection: "row",
alignItems: "flex-start",
gap: 8,
backgroundColor: C.error + "18",
borderRadius: 10,
padding: 12,
borderWidth: 1,
borderColor: C.error + "44",
},
errorCardText: {
fontSize: 13,
fontFamily: "Inter_400Regular",
color: C.error,
flex: 1,
},
buttonRow: {
flexDirection: "row",
gap: 12,
},
estimateButton: {
flex: 1,
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: 6,
backgroundColor: C.surfaceElevated,
borderRadius: 12,
paddingVertical: 14,
borderWidth: 1,
borderColor: C.accent + "44",
},
estimateButtonText: {
fontSize: 15,
fontFamily: "Inter_600SemiBold",
color: C.accent,
},
submitButton: {
flex: 1,
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: 6,
backgroundColor: C.accent,
borderRadius: 12,
paddingVertical: 14,
},
submitButtonText: {
fontSize: 15,
fontFamily: "Inter_600SemiBold",
color: "#fff",
},
buttonDisabled: {
opacity: 0.5,
},
statusRow: {
flexDirection: "row",
alignItems: "center",
gap: 8,
backgroundColor: C.surfaceElevated,
borderRadius: 10,
padding: 12,
borderWidth: 1,
borderColor: C.border,
},
statusText: {
flex: 1,
fontSize: 14,
fontFamily: "Inter_500Medium",
color: C.text,
},
qrContainer: {
alignItems: "center",
gap: 12,
},
qrLabel: {
fontSize: 14,
fontFamily: "Inter_500Medium",
color: C.textSecondary,
},
qrWrapper: {
backgroundColor: "#FFFFFF",
padding: 16,
borderRadius: 12,
},
satsLabel: {
fontSize: 20,
fontFamily: "Inter_700Bold",
color: C.jobStarted,
},
invoiceHint: {
fontSize: 12,
fontFamily: "Inter_400Regular",
color: C.textMuted,
},
resultCard: {
backgroundColor: C.surfaceElevated,
borderRadius: 12,
padding: 14,
borderWidth: 1,
borderColor: C.jobCompleted + "44",
gap: 10,
},
resultHeader: {
flexDirection: "row",
alignItems: "center",
gap: 8,
},
resultTitle: {
flex: 1,
fontSize: 15,
fontFamily: "Inter_600SemiBold",
color: C.text,
},
resultText: {
fontSize: 14,
fontFamily: "Inter_400Regular",
color: C.text,
lineHeight: 20,
},
newJobButton: {
alignItems: "center",
paddingVertical: 14,
backgroundColor: C.surfaceElevated,
borderRadius: 12,
borderWidth: 1,
borderColor: C.border,
},
newJobButtonText: {
fontSize: 15,
fontFamily: "Inter_500Medium",
color: C.accent,
},
});

View File

@@ -0,0 +1 @@
export const ONBOARDING_COMPLETED_KEY = "app.onboarding_completed";

View File

@@ -7,6 +7,7 @@ import React, {
useRef,
useState,
} from "react";
import { AppState, Platform } from "react-native";
export type TimmyMood = "idle" | "thinking" | "working" | "speaking";
@@ -21,7 +22,7 @@ export type WsEvent = {
count?: number;
};
export type ConnectionStatus = "connecting" | "connected" | "disconnected" | "error";
export type ConnectionStatus = "connecting" | "connected" | "disconnected" | "reconnecting" | "error";
type TimmyContextValue = {
timmyMood: TimmyMood;
@@ -215,6 +216,54 @@ export function TimmyProvider({ children }: { children: React.ReactNode }) {
};
}, [connectWs]);
// AppState-aware WebSocket reconnect on foreground
useEffect(() => {
if (Platform.OS === "web") return;
const appStateRef = { current: AppState.currentState };
const subscription = AppState.addEventListener("change", (nextAppState) => {
const wasBackground =
appStateRef.current === "background" ||
appStateRef.current === "inactive";
const isNowActive = nextAppState === "active";
if (wasBackground && isNowActive) {
// App returned to foreground — check if WS is still alive
const ws = wsRef.current;
if (!ws || ws.readyState !== WebSocket.OPEN) {
// Cancel any pending retry so we don't create duplicates
if (retryTimerRef.current) {
clearTimeout(retryTimerRef.current);
retryTimerRef.current = null;
}
retryCountRef.current = 0;
setConnectionStatus("reconnecting");
connectWs();
}
} else if (nextAppState === "background") {
// Proactively close the WS to avoid OS killing it mid-frame
if (retryTimerRef.current) {
clearTimeout(retryTimerRef.current);
retryTimerRef.current = null;
}
if (wsRef.current) {
wsRef.current.onclose = null;
wsRef.current.onerror = null;
wsRef.current.close();
wsRef.current = null;
}
setConnectionStatus("disconnected");
}
appStateRef.current = nextAppState;
});
return () => {
subscription.remove();
};
}, [connectWs]);
const send = useCallback((msg: object) => {
if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
wsRef.current.send(JSON.stringify(msg));

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"
@@ -58,6 +58,7 @@
"dependencies": {
"@react-native-voice/voice": "^3.2.4",
"expo-speech": "^14.0.8",
"react-native-qrcode-svg": "^6.3.21",
"react-native-webview": "^13.15.0"
}
}

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

@@ -127,6 +127,7 @@ OVERRIDE
cp "$SCRIPT_DIR/docker-compose.yml" "$INFRA_DIR/docker-compose.yml"
cp "$SCRIPT_DIR/lnd-init.sh" "$INFRA_DIR/lnd-init.sh"
cp "$SCRIPT_DIR/sweep.sh" "$INFRA_DIR/sweep.sh"
cp "$SCRIPT_DIR/sweep.conf.example" "$INFRA_DIR/sweep.conf.example"
cp "$SCRIPT_DIR/ops.sh" "$INFRA_DIR/ops.sh"
chmod +x "$INFRA_DIR/lnd-init.sh" "$INFRA_DIR/sweep.sh" "$INFRA_DIR/ops.sh"

View File

@@ -0,0 +1,15 @@
# Timmy Node — Auto-sweep configuration
# Copy to /opt/timmy-node/sweep.conf and edit, or run: bash ops.sh configure-sweep
#
# Modes:
# static — sweep to a single cold address every time
# list — rotate through addresses in /opt/timmy-node/sweep-addresses.txt
# xpub — derive a fresh address from an xpub each sweep (no address reuse)
SWEEP_MODE="static"
COLD_ADDRESS=""
XPUB=""
KEEP_SATS=300000
MIN_SWEEP=50000
SWEEP_CRON="0 3 * * *"
SWEEP_FREQ_LABEL="daily at 3am UTC"

View File

@@ -147,9 +147,8 @@ fi
log "SUCCESS — txid=${TXID} amount=${SWEEP_AMT} sats → ${SWEEP_TO}"
# ── Advance address index (xpub / list modes) ─────────────────
# NEXT_INDEX was already loaded by resolve_address(); advance it for the next run
if [[ "$SWEEP_MODE" == "xpub" || "$SWEEP_MODE" == "list" ]]; then
NEXT_INDEX=0
[[ -f "$STATE_FILE" ]] && source "$STATE_FILE"
NEW_INDEX=$(( NEXT_INDEX + 1 ))
echo "NEXT_INDEX=$NEW_INDEX" > "$STATE_FILE"
chmod 600 "$STATE_FILE"

View File

@@ -0,0 +1,13 @@
-- Migration: Session conversation history (#38/#39)
-- Stores user/assistant message pairs for context injection into the work model.
CREATE TABLE IF NOT EXISTS session_messages (
id SERIAL PRIMARY KEY,
session_id TEXT NOT NULL REFERENCES sessions(id),
role TEXT NOT NULL,
content TEXT NOT NULL,
token_count INTEGER,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_session_messages_session_id ON session_messages(session_id);

View File

@@ -0,0 +1,38 @@
-- Migration: Relay Account Whitelist + Trust-Gated Access (#47)
-- Adds the relay_accounts and relay_event_queue tables that back the
-- whitelist-gated Nostr relay policy.
-- ── relay_accounts ────────────────────────────────────────────────────────────
-- One row per pubkey that has been explicitly registered with the relay.
-- Absence = "none" (default deny). FK to nostr_identities.
CREATE TABLE IF NOT EXISTS relay_accounts (
pubkey TEXT PRIMARY KEY REFERENCES nostr_identities(pubkey) ON DELETE CASCADE,
access_level TEXT NOT NULL DEFAULT 'none', -- 'none' | 'read' | 'write'
granted_by TEXT NOT NULL DEFAULT 'manual', -- 'manual' | 'auto-tier' | 'manual-revoked'
granted_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
revoked_at TIMESTAMPTZ,
notes TEXT
);
-- ── relay_event_queue ─────────────────────────────────────────────────────────
-- Holds events submitted by whitelisted non-elite accounts pending moderation.
-- Elite accounts bypass this table; their events are injected directly into strfry.
CREATE TABLE IF NOT EXISTS relay_event_queue (
event_id TEXT PRIMARY KEY,
pubkey TEXT NOT NULL REFERENCES nostr_identities(pubkey) ON DELETE CASCADE,
kind INTEGER NOT NULL,
raw_event TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending', -- 'pending' | 'approved' | 'rejected' | 'auto_approved' | 'flagged'
reviewed_by TEXT, -- 'timmy_ai' | 'admin'
review_reason TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
decided_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS idx_relay_event_queue_pubkey
ON relay_event_queue(pubkey);
CREATE INDEX IF NOT EXISTS idx_relay_event_queue_status
ON relay_event_queue(status);

View File

@@ -0,0 +1,15 @@
-- Migration: Tower Log narrative event feed (#7)
-- Adds the tower_log table that stores prose narrative entries about
-- Workshop activity, generated by Haiku on key events.
CREATE TABLE IF NOT EXISTS tower_log (
id TEXT PRIMARY KEY,
narrative TEXT NOT NULL,
event_type TEXT NOT NULL,
agent_id TEXT,
job_id TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_tower_log_created_at
ON tower_log(created_at DESC);

View File

@@ -1,4 +1,5 @@
import { drizzle } from "drizzle-orm/node-postgres";
import { eq, asc } from "drizzle-orm";
import pg from "pg";
import * as schema from "./schema";
@@ -14,3 +15,46 @@ export const pool = new Pool({ connectionString: process.env.DATABASE_URL });
export const db = drizzle(pool, { schema });
export * from "./schema";
// ── Session history helper ──────────────────────────────────────────────────
/**
* Load the most recent conversation history for a session, capped by turn
* count and approximate token budget.
*
* @param sessionId Session to load history for
* @param maxTurns Maximum number of messages to return (default 8)
* @param maxTokens Approximate token budget — stops including older messages
* once cumulative token_count exceeds this (default 4000)
* @returns Array of { role, content } objects in chronological order
*/
export async function getSessionHistory(
sessionId: string,
maxTurns = 8,
maxTokens = 4000,
): Promise<Array<{ role: "user" | "assistant"; content: string }>> {
const rows = await db
.select({
role: schema.sessionMessages.role,
content: schema.sessionMessages.content,
tokenCount: schema.sessionMessages.tokenCount,
})
.from(schema.sessionMessages)
.where(eq(schema.sessionMessages.sessionId, sessionId))
.orderBy(asc(schema.sessionMessages.id));
// Take the most recent messages that fit within budget
const result: Array<{ role: "user" | "assistant"; content: string }> = [];
let totalTokens = 0;
// Walk from newest to oldest, then reverse
for (let i = rows.length - 1; i >= 0 && result.length < maxTurns; i--) {
const row = rows[i]!;
const tokens = row.tokenCount ?? Math.ceil(row.content.length / 4);
if (totalTokens + tokens > maxTokens && result.length > 0) break;
totalTokens += tokens;
result.push({ role: row.role as "user" | "assistant", content: row.content });
}
return result.reverse();
}

View File

@@ -13,3 +13,5 @@ export * from "./nostr-trust-vouches";
export * from "./relay-accounts";
export * from "./relay-event-queue";
export * from "./job-debates";
export * from "./session-messages";
export * from "./tower-log";

View File

@@ -0,0 +1,18 @@
import { pgTable, text, timestamp, integer, serial } from "drizzle-orm/pg-core";
import { sessions } from "./sessions";
// ── session_messages ────────────────────────────────────────────────────────
// Stores conversation history for context injection into the work model.
export const sessionMessages = pgTable("session_messages", {
id: serial("id").primaryKey(),
sessionId: text("session_id")
.notNull()
.references(() => sessions.id),
role: text("role").$type<"user" | "assistant">().notNull(),
content: text("content").notNull(),
tokenCount: integer("token_count"),
createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(),
});
export type SessionMessage = typeof sessionMessages.$inferSelect;

View File

@@ -0,0 +1,10 @@
import { pgTable, text, timestamp } from "drizzle-orm/pg-core";
export const towerLog = pgTable("tower_log", {
id: text("id").primaryKey(),
narrative: text("narrative").notNull(),
eventType: text("event_type").notNull(),
agentId: text("agent_id"),
jobId: text("job_id"),
createdAt: timestamp("created_at").notNull().defaultNow(),
});

119
pnpm-lock.yaml generated
View File

@@ -233,6 +233,9 @@ importers:
expo-speech:
specifier: ^14.0.8
version: 14.0.8(expo@54.0.33)
react-native-qrcode-svg:
specifier: ^6.3.21
version: 6.3.21(react-native-svg@15.12.1(react-native@0.81.5(@babel/core@7.29.0)(@types/react@19.1.17)(react@19.1.0))(react@19.1.0))(react-native@0.81.5(@babel/core@7.29.0)(@types/react@19.1.17)(react@19.1.0))(react@19.1.0)
react-native-webview:
specifier: ^13.15.0
version: 13.15.0(react-native@0.81.5(@babel/core@7.29.0)(@types/react@19.1.17)(react@19.1.0))(react@19.1.0)
@@ -3024,6 +3027,9 @@ packages:
client-only@0.0.1:
resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==}
cliui@6.0.0:
resolution: {integrity: sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==}
cliui@8.0.1:
resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==}
engines: {node: '>=12'}
@@ -3241,6 +3247,10 @@ packages:
supports-color:
optional: true
decamelize@1.2.0:
resolution: {integrity: sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==}
engines: {node: '>=0.10.0'}
decimal.js-light@2.5.1:
resolution: {integrity: sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==}
@@ -3289,6 +3299,9 @@ packages:
detect-node-es@1.1.0:
resolution: {integrity: sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==}
dijkstrajs@1.0.3:
resolution: {integrity: sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==}
dom-helpers@5.2.1:
resolution: {integrity: sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==}
@@ -4960,6 +4973,10 @@ packages:
resolution: {integrity: sha512-NCrCHhWmnQklfH4MtJMRjZ2a8c80qXeMlQMv2uVp9ISJMTt562SbGd6n2oq0PaPgKm7Z6pL9E2UlLIhC+SHL3w==}
engines: {node: '>=4.0.0'}
pngjs@5.0.0:
resolution: {integrity: sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==}
engines: {node: '>=10.13.0'}
postcss-value-parser@4.2.0:
resolution: {integrity: sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==}
@@ -5052,6 +5069,11 @@ packages:
resolution: {integrity: sha512-Uu7ii+FQy4Qf82G4xu7ShHhjhGahEpCWc3x8UavY3CTcWV+ufmmCtwkr7ZKsX42jdL0kr1B5FKUeqJvAn51jzQ==}
hasBin: true
qrcode@1.5.4:
resolution: {integrity: sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==}
engines: {node: '>=10.13.0'}
hasBin: true
qs@6.15.0:
resolution: {integrity: sha512-mAZTtNCeetKMH+pSjrb76NAM8V9a05I9aBZOHztWy/UqcJdQYNsf59vrRKWnojAT9Y+GbIvoTBC++CPHqpDBhQ==}
engines: {node: '>=0.6'}
@@ -5139,6 +5161,13 @@ packages:
react-native: '*'
react-native-reanimated: '>=3.0.0'
react-native-qrcode-svg@6.3.21:
resolution: {integrity: sha512-6vcj4rcdpWedvphDR+NSJcudJykNuLgNGFwm2p4xYjR8RdyTzlrELKI5LkO4ANS9cQUbqsfkpippPv64Q2tUtA==}
peerDependencies:
react: '*'
react-native: '>=0.63.4'
react-native-svg: '>=14.0.0'
react-native-reanimated@4.1.6:
resolution: {integrity: sha512-F+ZJBYiok/6Jzp1re75F/9aLzkgoQCOh4yxrnwATa8392RvM3kx+fiXXFvwcgE59v48lMwd9q0nzF1oJLXpfxQ==}
peerDependencies:
@@ -5305,6 +5334,9 @@ packages:
resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==}
engines: {node: '>=0.10.0'}
require-main-filename@2.0.0:
resolution: {integrity: sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==}
requireg@0.2.2:
resolution: {integrity: sha512-nYzyjnFcPNGR3lx9lwPPPnuQxv6JWEZd2Ci0u9opN7N5zUEPIhY/GbL3vMGOr2UXwEg9WwSyV9X9Y/kLFgPsOg==}
engines: {node: '>= 4.0.0'}
@@ -5421,6 +5453,9 @@ packages:
server-only@0.0.1:
resolution: {integrity: sha512-qepMx2JxAa5jjfzxG79yPPq+8BuFToHd1hm7kI+Z4zAq1ftQiP7HcxMhDDItrbtwVeLg/cY2JnKnrcFkmiswNA==}
set-blocking@2.0.0:
resolution: {integrity: sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==}
setimmediate@1.0.5:
resolution: {integrity: sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==}
@@ -5636,6 +5671,10 @@ packages:
resolution: {integrity: sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==}
engines: {node: '>=8'}
text-encoding@0.7.0:
resolution: {integrity: sha512-oJQ3f1hrOnbRLOcwKz0Liq2IcrvDeZRHXhd9RgLrsT+DjWY/nty1Hi7v3dtkaEYbPYe0mUoOfzRrMwfXXwgPUA==}
deprecated: no longer maintained
thenify-all@1.6.0:
resolution: {integrity: sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==}
engines: {node: '>=0.8'}
@@ -5943,6 +5982,9 @@ packages:
whatwg-url@5.0.0:
resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==}
which-module@2.0.1:
resolution: {integrity: sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==}
which@2.0.2:
resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==}
engines: {node: '>= 8'}
@@ -5955,6 +5997,10 @@ packages:
resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==}
engines: {node: '>=0.10.0'}
wrap-ansi@6.2.0:
resolution: {integrity: sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==}
engines: {node: '>=8'}
wrap-ansi@7.0.0:
resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==}
engines: {node: '>=10'}
@@ -6036,6 +6082,9 @@ packages:
resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==}
engines: {node: '>=0.4'}
y18n@4.0.3:
resolution: {integrity: sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==}
y18n@5.0.8:
resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}
engines: {node: '>=10'}
@@ -6056,10 +6105,18 @@ packages:
engines: {node: '>= 14.6'}
hasBin: true
yargs-parser@18.1.3:
resolution: {integrity: sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==}
engines: {node: '>=6'}
yargs-parser@21.1.1:
resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==}
engines: {node: '>=12'}
yargs@15.4.1:
resolution: {integrity: sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==}
engines: {node: '>=8'}
yargs@17.7.2:
resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==}
engines: {node: '>=12'}
@@ -9313,6 +9370,12 @@ snapshots:
client-only@0.0.1: {}
cliui@6.0.0:
dependencies:
string-width: 4.2.3
strip-ansi: 6.0.1
wrap-ansi: 6.2.0
cliui@8.0.1:
dependencies:
string-width: 4.2.3
@@ -9517,6 +9580,8 @@ snapshots:
dependencies:
ms: 2.1.3
decamelize@1.2.0: {}
decimal.js-light@2.5.1: {}
decode-uri-component@0.2.2: {}
@@ -9547,6 +9612,8 @@ snapshots:
detect-node-es@1.1.0: {}
dijkstrajs@1.0.3: {}
dom-helpers@5.2.1:
dependencies:
'@babel/runtime': 7.28.6
@@ -11432,6 +11499,8 @@ snapshots:
pngjs@3.4.0: {}
pngjs@5.0.0: {}
postcss-value-parser@4.2.0: {}
postcss@8.4.49:
@@ -11526,6 +11595,12 @@ snapshots:
qrcode-terminal@0.11.0: {}
qrcode@1.5.4:
dependencies:
dijkstrajs: 1.0.3
pngjs: 5.0.0
yargs: 15.4.1
qs@6.15.0:
dependencies:
side-channel: 1.1.0
@@ -11618,6 +11693,15 @@ snapshots:
react-native-is-edge-to-edge: 1.3.1(react-native@0.81.5(@babel/core@7.29.0)(@types/react@19.1.17)(react@19.1.0))(react@19.1.0)
react-native-reanimated: 4.1.6(@babel/core@7.29.0)(react-native-worklets@0.5.1(@babel/core@7.29.0)(react-native@0.81.5(@babel/core@7.29.0)(@types/react@19.1.17)(react@19.1.0))(react@19.1.0))(react-native@0.81.5(@babel/core@7.29.0)(@types/react@19.1.17)(react@19.1.0))(react@19.1.0)
react-native-qrcode-svg@6.3.21(react-native-svg@15.12.1(react-native@0.81.5(@babel/core@7.29.0)(@types/react@19.1.17)(react@19.1.0))(react@19.1.0))(react-native@0.81.5(@babel/core@7.29.0)(@types/react@19.1.17)(react@19.1.0))(react@19.1.0):
dependencies:
prop-types: 15.8.1
qrcode: 1.5.4
react: 19.1.0
react-native: 0.81.5(@babel/core@7.29.0)(@types/react@19.1.17)(react@19.1.0)
react-native-svg: 15.12.1(react-native@0.81.5(@babel/core@7.29.0)(@types/react@19.1.17)(react@19.1.0))(react@19.1.0)
text-encoding: 0.7.0
react-native-reanimated@4.1.6(@babel/core@7.29.0)(react-native-worklets@0.5.1(@babel/core@7.29.0)(react-native@0.81.5(@babel/core@7.29.0)(@types/react@19.1.17)(react@19.1.0))(react@19.1.0))(react-native@0.81.5(@babel/core@7.29.0)(@types/react@19.1.17)(react@19.1.0))(react@19.1.0):
dependencies:
'@babel/core': 7.29.0
@@ -11868,6 +11952,8 @@ snapshots:
require-from-string@2.0.2: {}
require-main-filename@2.0.0: {}
requireg@0.2.2:
dependencies:
nested-error-stacks: 2.0.1
@@ -12004,6 +12090,8 @@ snapshots:
server-only@0.0.1: {}
set-blocking@2.0.0: {}
setimmediate@1.0.5: {}
setprototypeof@1.2.0: {}
@@ -12199,6 +12287,8 @@ snapshots:
glob: 7.2.3
minimatch: 3.1.5
text-encoding@0.7.0: {}
thenify-all@1.6.0:
dependencies:
thenify: 3.3.1
@@ -12465,6 +12555,8 @@ snapshots:
tr46: 0.0.3
webidl-conversions: 3.0.1
which-module@2.0.1: {}
which@2.0.2:
dependencies:
isexe: 2.0.0
@@ -12473,6 +12565,12 @@ snapshots:
word-wrap@1.2.5: {}
wrap-ansi@6.2.0:
dependencies:
ansi-styles: 4.3.0
string-width: 4.2.3
strip-ansi: 6.0.1
wrap-ansi@7.0.0:
dependencies:
ansi-styles: 4.3.0
@@ -12525,6 +12623,8 @@ snapshots:
xtend@4.0.2: {}
y18n@4.0.3: {}
y18n@5.0.8: {}
yallist@3.1.1: {}
@@ -12535,8 +12635,27 @@ snapshots:
yaml@2.8.2: {}
yargs-parser@18.1.3:
dependencies:
camelcase: 5.3.1
decamelize: 1.2.0
yargs-parser@21.1.1: {}
yargs@15.4.1:
dependencies:
cliui: 6.0.0
decamelize: 1.2.0
find-up: 4.1.0
get-caller-file: 2.0.5
require-directory: 2.1.1
require-main-filename: 2.0.0
set-blocking: 2.0.0
string-width: 4.2.3
which-module: 2.0.1
y18n: 4.0.3
yargs-parser: 18.1.3
yargs@17.7.2:
dependencies:
cliui: 8.0.1

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

@@ -1,8 +0,0 @@
{
"index.html": {
"file": "assets/index-CBu1T9J9.js",
"name": "index",
"src": "index.html",
"isEntry": true
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

View File

@@ -1,679 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<title>The Workshop — Timmy</title>
<link rel="manifest" href="/tower/manifest.json" />
<meta name="theme-color" content="#0a0610" />
<!-- iOS PWA -->
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="apple-mobile-web-app-title" content="The Workshop" />
<link rel="apple-touch-icon" href="/tower/icons/icon-192.png" />
<style>
*, *::before, *::after { margin: 0; padding: 0; box-sizing: border-box; }
body {
background: #080610;
overflow: hidden;
font-family: 'Courier New', monospace;
touch-action: none;
user-select: none;
-webkit-user-select: none;
}
canvas { display: block; }
/* ── HUD ─────────────────────────────────────────────────────────── */
#hud {
position: fixed; top: 16px; left: 16px;
color: #5588bb; font-size: 11px; line-height: 1.7;
text-shadow: 0 0 6px #2244aa;
pointer-events: none; z-index: 10;
}
#hud h1 {
font-size: 13px; letter-spacing: 3px; margin-bottom: 4px;
color: #7799cc; text-shadow: 0 0 10px #4466aa;
}
#session-hud {
display: none;
color: #22aa66;
text-shadow: 0 0 6px #11663388;
letter-spacing: 1px;
pointer-events: all;
line-height: 1.9;
}
#session-hud-topup {
color: #22aa66; text-decoration: none; margin-left: 5px;
letter-spacing: 1px; text-shadow: 0 0 6px #11663388;
cursor: pointer;
}
#session-hud-topup:hover { color: #44dd88; text-decoration: underline; }
#connection-status {
position: fixed; top: 16px; right: 16px;
font-size: 11px; color: #333355;
pointer-events: none; z-index: 10;
text-shadow: none;
}
#connection-status.connected {
color: #5588bb;
text-shadow: 0 0 6px #3366aa;
}
/* ── Event log ────────────────────────────────────────────────────── */
#event-log {
position: fixed; bottom: 80px; left: 16px;
width: 280px; max-height: 100px; overflow-y: auto;
color: #445566; font-size: 10px; line-height: 1.6;
pointer-events: none; z-index: 10;
}
.log-entry { opacity: 0.7; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
/* ── Top button bar ───────────────────────────────────────────────── */
#top-buttons {
position: fixed; top: 16px; left: 50%; transform: translateX(-50%);
display: flex; gap: 8px; z-index: 20;
}
#open-panel-btn {
font-family: 'Courier New', monospace; font-size: 11px; font-weight: bold;
color: #000; background: #4466aa; border: none;
padding: 7px 18px; cursor: pointer; letter-spacing: 2px;
box-shadow: 0 0 14px #2244aa66;
transition: background 0.15s, box-shadow 0.15s;
border-radius: 2px;
min-height: 36px;
}
#open-panel-btn:hover, #open-panel-btn:active {
background: #5577cc;
box-shadow: 0 0 20px #3355aa88;
}
#open-session-btn {
font-family: 'Courier New', monospace; font-size: 11px; font-weight: bold;
color: #d0ffe0; background: #0d3322; border: 1px solid #22aa66;
padding: 7px 18px; cursor: pointer; letter-spacing: 1px;
box-shadow: 0 0 14px #0a441a44;
transition: background 0.15s, box-shadow 0.15s, color 0.15s;
border-radius: 2px;
min-height: 36px;
}
#open-session-btn:hover, #open-session-btn:active {
background: #1a4a30;
box-shadow: 0 0 20px #22aa6666;
color: #88ffcc;
}
/* ── Low balance notice ───────────────────────────────────────────── */
#low-balance-notice {
display: none;
position: fixed; bottom: 65px; left: 0; right: 0;
text-align: center;
background: rgba(120, 50, 10, 0.92);
color: #ffcc80;
font-size: 11px; letter-spacing: 1px;
padding: 6px 12px;
z-index: 25;
border-top: 1px solid #aa6622;
}
#low-balance-notice button {
background: transparent; border: 1px solid #ffcc80;
color: #ffcc80; font-family: 'Courier New', monospace;
font-size: 11px; padding: 2px 10px; cursor: pointer;
margin-left: 8px; letter-spacing: 1px;
transition: background 0.15s;
pointer-events: all;
}
#low-balance-notice button:hover { background: rgba(255,200,100,0.15); }
/* ── Input bar ───────────────────────────────────────────────────── */
#input-bar {
position: fixed; bottom: 0; left: 0; right: 0;
display: flex; align-items: center; gap: 8px;
padding: 10px 16px;
background: rgba(8, 6, 16, 0.88);
border-top: 1px solid #1a1a2e;
z-index: 20;
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
}
#visitor-input {
flex: 1;
background: rgba(20, 16, 36, 0.9);
border: 1px solid #2a2a44;
color: #aabbdd;
font-family: 'Courier New', monospace;
font-size: 14px;
padding: 10px 12px;
outline: none;
min-height: 44px;
border-radius: 3px;
transition: border-color 0.2s, box-shadow 0.4s;
-webkit-appearance: none;
}
#visitor-input::placeholder { color: #333355; }
#visitor-input:focus { border-color: #4466aa; }
#visitor-input.session-active {
border-color: #22aa66;
box-shadow: 0 0 10px #22aa6630, inset 0 0 4px #22aa6618;
animation: session-pulse 3s ease-in-out infinite;
}
@keyframes session-pulse {
0%, 100% { box-shadow: 0 0 10px #22aa6630, inset 0 0 4px #22aa6618; }
50% { box-shadow: 0 0 22px #22aa6670, inset 0 0 8px #22aa6630; }
}
#visitor-input.session-active::placeholder { color: #226644; }
#send-btn {
background: rgba(30, 40, 80, 0.9);
border: 1px solid #2a2a44;
color: #5577aa;
font-family: 'Courier New', monospace;
font-size: 16px;
width: 44px; height: 44px;
cursor: pointer;
border-radius: 3px;
transition: background 0.15s, border-color 0.15s, color 0.15s;
display: flex; align-items: center; justify-content: center;
}
#send-btn:hover, #send-btn:active {
background: rgba(50, 70, 140, 0.9);
border-color: #4466aa;
color: #88aadd;
}
#send-btn:disabled { opacity: 0.35; cursor: not-allowed; }
/* ── Payment panel (right side) ───────────────────────────────────── */
#payment-panel {
position: fixed; top: 0; right: -420px;
width: 400px; height: 100%;
background: rgba(5, 3, 12, 0.97);
border-left: 1px solid #1a1a2e;
padding: 24px 20px;
overflow-y: auto; z-index: 100;
font-family: 'Courier New', monospace;
transition: right 0.35s cubic-bezier(0.4, 0, 0.2, 1);
box-shadow: -8px 0 32px rgba(40, 60, 120, 0.15);
}
#payment-panel.open { right: 0; }
#payment-panel h2 {
font-size: 13px; letter-spacing: 3px; color: #6688bb;
text-shadow: 0 0 10px #2244aa;
margin-bottom: 20px; border-bottom: 1px solid #1a1a2e; padding-bottom: 10px;
}
#payment-close {
position: absolute; top: 16px; right: 16px;
background: transparent; border: 1px solid #1a1a2e;
color: #333355; font-family: 'Courier New', monospace;
font-size: 16px; width: 28px; height: 28px;
cursor: pointer; transition: color 0.2s, border-color 0.2s;
}
#payment-close:hover { color: #6688bb; border-color: #4466aa; }
/* ── Session panel (left side) ────────────────────────────────────── */
#session-panel {
position: fixed; top: 0; left: -420px;
width: 400px; height: 100%;
background: rgba(3, 8, 5, 0.97);
border-right: 1px solid #0e2318;
padding: 24px 20px;
overflow-y: auto; z-index: 100;
font-family: 'Courier New', monospace;
transition: left 0.35s cubic-bezier(0.4, 0, 0.2, 1);
box-shadow: 8px 0 32px rgba(10, 50, 25, 0.20);
}
#session-panel.open { left: 0; }
#session-panel h2 {
font-size: 13px; letter-spacing: 3px; color: #33bb77;
text-shadow: 0 0 10px #116633;
margin-bottom: 20px; border-bottom: 1px solid #0e2318; padding-bottom: 10px;
}
#session-close {
position: absolute; top: 16px; right: 16px;
background: transparent; border: 1px solid #0e2318;
color: #226644; font-family: 'Courier New', monospace;
font-size: 16px; width: 28px; height: 28px;
cursor: pointer; transition: color 0.2s, border-color 0.2s;
}
#session-close:hover { color: #44dd88; border-color: #22aa66; }
/* Amount presets */
.session-amount-presets {
display: flex; gap: 6px; flex-wrap: wrap; margin: 10px 0;
}
.session-amount-btn {
background: transparent; border: 1px solid #0e2318;
color: #226644; font-family: 'Courier New', monospace;
font-size: 11px; letter-spacing: 1px; padding: 5px 11px;
cursor: pointer; transition: all 0.15s; border-radius: 2px;
}
.session-amount-btn:hover { background: #0e2318; border-color: #22aa66; color: #44dd88; }
.session-amount-btn.active { background: #0e2318; border-color: #22aa66; color: #44dd88; }
/* QR placeholder */
.qr-placeholder {
display: flex; align-items: center; justify-content: center;
margin-top: 8px;
background: #020806; border: 1px solid #0e2318;
color: #1a4430; font-size: 11px; letter-spacing: 3px;
height: 80px;
}
/* Amount number inputs */
.session-amount-input {
background: #020806; border: 1px solid #0e2318;
color: #44dd88; font-family: 'Courier New', monospace;
font-size: 15px; font-weight: bold; letter-spacing: 1px;
padding: 6px 10px; width: 110px;
outline: none; border-radius: 2px;
transition: border-color 0.2s;
-moz-appearance: textfield;
}
.session-amount-input:focus { border-color: #22aa66; }
.session-amount-input::-webkit-outer-spin-button,
.session-amount-input::-webkit-inner-spin-button { -webkit-appearance: none; }
.session-amount-row {
display: flex; align-items: center; gap: 6px; margin: 8px 0;
}
.session-amount-row span {
color: #226644; font-size: 11px; letter-spacing: 1px;
}
/* Active session balance tag */
.amount-tag.session-green { border-color: #22aa66; color: #44dd88; }
/* Session status / error lines */
#session-status-fund,
#session-status-invoice,
#session-status-active,
#session-status-topup {
font-size: 11px; margin-top: 8px; min-height: 16px; color: #22aa66;
}
#session-error {
font-size: 11px; margin-top: 8px; min-height: 16px; color: #994444;
}
/* ── Shared panel primitives ──────────────────────────────────────── */
.panel-label { font-size: 10px; letter-spacing: 2px; color: #334466; margin-bottom: 6px; margin-top: 16px; }
#session-panel .panel-label { color: #1a4430; }
#job-input {
width: 100%; background: #060310; border: 1px solid #1a1a2e;
color: #aabbdd; font-family: 'Courier New', monospace; font-size: 12px;
padding: 10px; resize: vertical; min-height: 90px;
outline: none; transition: border-color 0.2s;
}
#job-input:focus { border-color: #4466aa; }
#job-input::placeholder { color: #1a1a2e; }
.panel-btn {
width: 100%; margin-top: 12px;
background: transparent; border: 1px solid #334466;
color: #5577aa; font-family: 'Courier New', monospace;
font-size: 12px; letter-spacing: 2px; padding: 10px;
cursor: pointer; transition: all 0.2s;
}
.panel-btn:hover:not(:disabled) { background: #334466; color: #aabbdd; }
.panel-btn:disabled { opacity: 0.35; cursor: not-allowed; }
.panel-btn.primary { border-color: #4466aa; color: #7799cc; }
.panel-btn.primary:hover:not(:disabled) { background: #4466aa; color: #fff; }
.panel-btn.primary-green { border-color: #22aa66; color: #44dd88; }
.panel-btn.primary-green:hover:not(:disabled) { background: #22aa66; color: #000; }
.panel-btn.danger { border-color: #663333; color: #995555; }
.panel-btn.muted { border-color: #0e2318; color: #226644; }
.panel-btn.muted:hover:not(:disabled) { background: #0e2318; color: #44dd88; }
#job-status { font-size: 11px; margin-top: 8px; color: #5577aa; min-height: 16px; }
#job-error { font-size: 11px; margin-top: 4px; min-height: 16px; color: #994444; }
.invoice-box {
background: #060310; border: 1px solid #1a1a2e;
padding: 10px; margin-top: 8px; font-size: 10px; color: #334466;
word-break: break-all; max-height: 80px; overflow-y: auto;
}
#session-panel .invoice-box {
background: #020806; border-color: #0e2318; color: #1a4430;
}
.copy-row { display: flex; gap: 8px; margin-top: 6px; align-items: stretch; }
.copy-row .invoice-box { flex: 1; margin-top: 0; }
.copy-btn {
background: transparent; border: 1px solid #1a1a2e; color: #334466;
font-family: 'Courier New', monospace; font-size: 10px;
padding: 0 10px; cursor: pointer; transition: all 0.2s; white-space: nowrap;
}
.copy-btn:hover { border-color: #4466aa; color: #6688bb; }
#session-panel .copy-btn { border-color: #0e2318; color: #1a4430; }
#session-panel .copy-btn:hover { border-color: #22aa66; color: #44dd88; }
.amount-tag {
display: inline-block; background: #0a0820;
border: 1px solid #334466; color: #6688bb;
font-size: 16px; font-weight: bold; letter-spacing: 2px;
padding: 6px 14px; margin-top: 8px;
}
#session-panel .amount-tag {
background: #020806; border-color: #22aa66; color: #44dd88;
}
#job-result {
background: #060310; border: 1px solid #1a1a2e;
color: #aabbdd; padding: 12px; font-size: 12px;
line-height: 1.6; margin-top: 8px;
white-space: pre-wrap; max-height: 260px; overflow-y: auto;
}
.panel-link {
display: block; text-align: center; margin-top: 20px;
font-size: 10px; letter-spacing: 1px; color: #1a1a2e;
text-decoration: none; transition: color 0.2s;
}
.panel-link:hover { color: #5577aa; }
/* ── AR pulse animation ──────────────────────────────────────────── */
@keyframes ar-pulse {
0%, 100% { opacity: 0.6; transform: scale(1); }
50% { opacity: 1; transform: scale(1.5); }
}
/* ── Crosshair ───────────────────────────────────────────────────── */
#crosshair {
position: fixed; top: 50%; left: 50%;
transform: translate(-50%, -50%);
pointer-events: none; z-index: 12;
opacity: 0.5;
}
#crosshair::before, #crosshair::after {
content: ''; position: absolute;
background: rgba(180, 160, 220, 0.7);
border-radius: 1px;
}
#crosshair::before { width: 16px; height: 1px; top: 0; left: -8px; }
#crosshair::after { width: 1px; height: 16px; top: -8px; left: 0; }
/* ── Lock hint (desktop) ─────────────────────────────────────────── */
#lock-hint {
position: fixed; inset: 0;
display: none;
align-items: center; justify-content: center;
z-index: 11; pointer-events: none;
}
#lock-hint .lock-badge {
background: rgba(8, 6, 20, 0.72);
border: 1px solid rgba(80, 100, 160, 0.5);
border-radius: 8px;
color: #5577aa;
font-family: 'Courier New', monospace;
font-size: 11px; letter-spacing: 2px;
padding: 10px 24px;
text-align: center;
backdrop-filter: blur(6px);
-webkit-backdrop-filter: blur(6px);
animation: lock-fade 2s ease-in-out infinite alternate;
}
@keyframes lock-fade {
0% { opacity: 0.45; }
100% { opacity: 0.9; }
}
/* ── Virtual joystick (mobile) ───────────────────────────────────── */
#joy-pad {
position: fixed;
display: none; /* shown by navigation.js on mobile */
align-items: center; justify-content: center;
width: 110px; height: 110px;
border-radius: 50%;
background: rgba(40, 30, 70, 0.38);
border: 1.5px solid rgba(100, 80, 180, 0.45);
backdrop-filter: blur(4px);
-webkit-backdrop-filter: blur(4px);
z-index: 18;
pointer-events: none; /* touches handled on canvas */
opacity: 0.35;
transition: opacity 0.25s;
bottom: 80px; left: 20px;
}
#joy-nub {
width: 38px; height: 38px; border-radius: 50%;
background: rgba(140, 110, 220, 0.65);
border: 1.5px solid rgba(180, 150, 255, 0.6);
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
box-shadow: 0 0 14px rgba(140, 110, 220, 0.5);
transition: transform 0.05s linear;
pointer-events: none;
}
/* ── AR label pulse ──────────────────────────────────────────────── */
.ar-label { transition: opacity 0.25s; }
/* ── WebGL recovery overlay ──────────────────────────────────────── */
#webgl-recovery-overlay {
display: none; position: fixed; inset: 0; z-index: 200;
background: rgba(5, 3, 12, 0.92);
justify-content: center; align-items: center;
pointer-events: none;
}
#webgl-recovery-overlay .recovery-text {
color: #5577aa; font-family: 'Courier New', monospace;
font-size: 15px; letter-spacing: 3px;
animation: ctx-blink 1.2s step-end infinite;
}
@keyframes ctx-blink {
0%, 100% { opacity: 1; }
50% { opacity: 0.2; }
}
/* ── Timmy identity card ──────────────────────────────────────────── */
#timmy-id-card {
position: fixed; bottom: 80px; right: 16px;
font-size: 10px; color: #334466;
pointer-events: all; z-index: 10;
text-align: right; line-height: 1.8;
}
#timmy-id-card .id-label {
letter-spacing: 2px; color: #223355;
text-transform: uppercase; font-size: 9px;
}
#timmy-id-card .id-npub {
color: #4466aa; cursor: pointer;
text-decoration: underline dotted;
font-size: 10px; letter-spacing: 0.5px;
}
#timmy-id-card .id-npub:hover { color: #88aadd; }
#timmy-id-card .id-zaps { color: #556688; font-size: 9px; }
</style>
<script type="module" crossorigin src="/tower/assets/index-CBu1T9J9.js"></script>
</head>
<body>
<div id="hud">
<h1>THE WORKSHOP</h1>
<div id="fps">FPS: --</div>
<div id="active-jobs">JOBS: 0</div>
<div id="session-hud">
<span id="session-hud-balance">Balance: -- sats</span>
<a href="#" id="session-hud-topup">⚡ Top Up</a>
</div>
</div>
<div id="connection-status">OFFLINE</div>
<div id="event-log"></div>
<!-- ── Timmy identity card ────────────────────────────────────────── -->
<div id="timmy-id-card">
<div class="id-label">TIMMY IDENTITY</div>
<div class="id-npub" id="timmy-npub" title="Click to copy Timmy's Nostr npub"></div>
<div class="id-zaps" id="timmy-zap-count">⚡ 0 zaps sent</div>
</div>
<!-- ── Top action buttons ─────────────────────────────────────────── -->
<div id="top-buttons">
<button id="open-panel-btn">⚡ SUBMIT JOB</button>
<button id="open-session-btn">⚡ FUND SESSION</button>
</div>
<!-- ── Low balance notice (above input bar) ───────────────────────── -->
<div id="low-balance-notice">
⚡ Low balance —
<button id="topup-quick-btn">Top Up</button>
</div>
<!-- ── Input bar ──────────────────────────────────────────────────── -->
<div id="input-bar">
<input type="text" id="visitor-input" placeholder="Say something to Timmy…" autocomplete="off" autocorrect="off" spellcheck="false" />
<button id="send-btn" aria-label="Send"></button>
</div>
<!-- ── Payment panel (right side) ────────────────────────────────── -->
<div id="payment-panel">
<button id="payment-close"></button>
<h2>⚡ TIMMY — JOB SUBMISSION</h2>
<div data-step="input">
<div class="panel-label">YOUR REQUEST</div>
<textarea id="job-input" maxlength="500" placeholder="Ask Timmy anything… (max 500 chars)"></textarea>
<button class="panel-btn primary" id="job-submit-btn">CREATE JOB →</button>
<a class="panel-link" href="/api/ui" target="_blank">Open full UI ↗</a>
</div>
<div data-step="eval-invoice" style="display:none">
<div class="panel-label">EVAL FEE</div>
<div class="amount-tag" id="eval-amount">10 sats</div>
<div class="panel-label" style="margin-top:12px">LIGHTNING INVOICE</div>
<div class="copy-row">
<div class="invoice-box" id="eval-payment-request"></div>
<button class="copy-btn" onclick="_timmyCopy('eval-payment-request')">COPY</button>
</div>
<span id="eval-hash" data-hash=""></span>
<button class="panel-btn primary" id="pay-eval-btn">⚡ SIMULATE PAYMENT</button>
</div>
<div data-step="work-invoice" style="display:none">
<div class="panel-label">WORK FEE</div>
<div class="amount-tag" id="work-amount">-- sats</div>
<div class="panel-label" style="margin-top:12px">LIGHTNING INVOICE</div>
<div class="copy-row">
<div class="invoice-box" id="work-payment-request"></div>
<button class="copy-btn" onclick="_timmyCopy('work-payment-request')">COPY</button>
</div>
<span id="work-hash" data-hash=""></span>
<button class="panel-btn primary" id="pay-work-btn">⚡ SIMULATE PAYMENT</button>
</div>
<div data-step="result" style="display:none">
<div class="panel-label" id="result-label">AI RESULT</div>
<pre id="job-result"></pre>
<button class="panel-btn" id="new-job-btn" style="margin-top:16px">← NEW JOB</button>
</div>
<div id="job-status"></div>
<div id="job-error"></div>
</div>
<!-- ── Session panel (left side) ─────────────────────────────────── -->
<div id="session-panel">
<button id="session-close"></button>
<h2>⚡ TIMMY — SESSION</h2>
<!-- Step: fund — choose deposit amount -->
<div data-session-step="fund">
<div class="panel-label">DEPOSIT AMOUNT (20010,000 sats)</div>
<div class="session-amount-presets">
<button class="session-amount-btn" data-sats="200">200</button>
<button class="session-amount-btn active" data-sats="500">500</button>
<button class="session-amount-btn" data-sats="1000">1000</button>
<button class="session-amount-btn" data-sats="2000">2000</button>
<button class="session-amount-btn" data-sats="5000">5000</button>
<button class="session-amount-btn" data-sats="10000">10k</button>
</div>
<div class="session-amount-row">
<input type="number" id="session-amount-input" class="session-amount-input"
min="200" max="10000" value="500" step="1" />
<span>sats</span>
</div>
<button class="panel-btn primary-green" id="session-create-btn" style="margin-top:12px">START SESSION →</button>
<div id="session-status-fund"></div>
</div>
<!-- Step: invoice — pay the deposit -->
<div data-session-step="invoice" style="display:none">
<div class="panel-label">DEPOSIT AMOUNT</div>
<div class="amount-tag" id="session-invoice-amount">-- sats</div>
<div class="panel-label" style="margin-top:14px">SCAN OR COPY INVOICE</div>
<div class="qr-placeholder" id="session-invoice-qr">[ QR ]</div>
<div class="copy-row" style="margin-top:6px">
<div class="invoice-box" id="session-invoice-pr"></div>
<button class="copy-btn" onclick="_timmyCopy('session-invoice-pr')">COPY</button>
</div>
<span id="session-invoice-hash" data-hash="" style="display:none"></span>
<button class="panel-btn primary-green" id="session-pay-btn" style="margin-top:14px">⚡ SIMULATE PAYMENT</button>
<div id="session-status-invoice"></div>
</div>
<!-- Step: active — session running, show balance + topup -->
<div data-session-step="active" style="display:none">
<div class="panel-label">BALANCE</div>
<div class="amount-tag session-green" id="session-active-amount">-- sats</div>
<p style="font-size:10px;color:#1a4430;margin-top:14px;line-height:1.6;letter-spacing:1px">
TYPE IN THE INPUT BAR TO ASK TIMMY.<br>EACH REQUEST DEDUCTS FROM YOUR BALANCE.
</p>
<button class="panel-btn muted" id="session-topup-btn" style="margin-top:20px">⚡ TOP UP BALANCE</button>
<div id="session-status-active"></div>
</div>
<!-- Step: topup — choose topup amount and pay -->
<div data-session-step="topup" style="display:none">
<div class="panel-label">TOPUP AMOUNT (20010,000 sats)</div>
<div class="session-amount-presets">
<button class="session-amount-btn" data-sats="200">200</button>
<button class="session-amount-btn active" data-sats="500">500</button>
<button class="session-amount-btn" data-sats="1000">1000</button>
<button class="session-amount-btn" data-sats="2000">2000</button>
<button class="session-amount-btn" data-sats="5000">5000</button>
<button class="session-amount-btn" data-sats="10000">10k</button>
</div>
<div class="session-amount-row">
<input type="number" id="session-topup-input" class="session-amount-input"
min="200" max="10000" value="500" step="1" />
<span>sats</span>
</div>
<button class="panel-btn primary-green" id="session-topup-create-btn" style="margin-top:12px">CREATE TOPUP INVOICE →</button>
<div id="session-topup-pr-row" style="display:none">
<div class="panel-label" style="margin-top:14px">SCAN OR COPY INVOICE</div>
<div class="qr-placeholder" id="session-topup-qr">[ QR ]</div>
<div class="copy-row" style="margin-top:6px">
<div class="invoice-box" id="session-topup-pr"></div>
<button class="copy-btn" onclick="_timmyCopy('session-topup-pr')">COPY</button>
</div>
<span id="session-topup-hash" data-hash="" style="display:none"></span>
<button class="panel-btn primary-green" id="session-topup-pay-btn" style="margin-top:10px">⚡ SIMULATE TOPUP</button>
</div>
<div id="session-status-topup"></div>
<button class="panel-btn muted" id="session-back-btn" style="margin-top:10px">← BACK</button>
</div>
<div id="session-error"></div>
</div>
<!-- ── FPS crosshair ─────────────────────────────────────────────── -->
<div id="crosshair"></div>
<!-- ── Pointer-lock hint (desktop) ──────────────────────────────── -->
<div id="lock-hint">
<div class="lock-badge">CLICK TO ENTER · WASD TO MOVE · ESC TO EXIT</div>
</div>
<!-- ── Virtual joystick (mobile) ─────────────────────────────────── -->
<div id="joy-pad">
<div id="joy-nub"></div>
</div>
<!-- ── AR floating labels container ──────────────────────────────── -->
<div id="ar-labels" style="position:fixed;inset:0;pointer-events:none;z-index:15;overflow:hidden;"></div>
<div id="webgl-recovery-overlay">
<span class="recovery-text">GPU context lost — recovering...</span>
</div>
</body>
</html>

View File

@@ -1,24 +0,0 @@
{
"name": "The Matrix",
"short_name": "The Matrix",
"description": "Timmy Tower World — live agent network visualization",
"start_url": "/",
"display": "standalone",
"orientation": "landscape",
"background_color": "#000000",
"theme_color": "#00ff41",
"icons": [
{
"src": "/icons/icon-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any maskable"
},
{
"src": "/icons/icon-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any maskable"
}
]
}

45
the-matrix/dist/sw.js vendored
View File

@@ -1,45 +0,0 @@
/* sw.js — Matrix PWA service worker
* PRECACHE_URLS is replaced at build time by the generate-sw Vite plugin.
* Registration is gated to import.meta.env.PROD in main.js, so this template
* file is never evaluated by browsers during development.
*/
const CACHE_NAME = 'timmy-matrix-v1';
const PRECACHE_URLS = [
"/",
"/manifest.json",
"/icons/icon-192.png",
"/icons/icon-512.png",
"/assets/index-CBu1T9J9.js"
];
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME).then(cache => cache.addAll(PRECACHE_URLS))
);
self.skipWaiting();
});
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(keys =>
Promise.all(keys.filter(k => k !== CACHE_NAME).map(k => caches.delete(k)))
)
);
self.clients.claim();
});
self.addEventListener('fetch', event => {
if (event.request.method !== 'GET') return;
event.respondWith(
caches.match(event.request).then(cached => {
if (cached) return cached;
return fetch(event.request).then(response => {
if (!response || response.status !== 200 || response.type !== 'basic') {
return response;
}
caches.open(CACHE_NAME).then(cache => cache.put(event.request, response.clone()));
return response;
});
})
);
});

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;
@@ -330,6 +349,14 @@
.panel-btn.muted { border-color: #0e2318; color: #226644; }
.panel-btn.muted:hover:not(:disabled) { background: #0e2318; color: #44dd88; }
.session-link-btn {
background: none; border: none; color: #557755; font-size: 10px;
font-family: inherit; cursor: pointer; margin-top: 10px; padding: 4px 0;
letter-spacing: 1px; display: block;
}
.session-link-btn:hover:not(:disabled) { color: #44dd88; text-decoration: underline; }
.session-link-btn:disabled { opacity: 0.35; cursor: not-allowed; }
#job-status { font-size: 11px; margin-top: 8px; color: #5577aa; min-height: 16px; }
#job-error { font-size: 11px; margin-top: 4px; min-height: 16px; color: #994444; }
@@ -374,6 +401,24 @@
}
.panel-link:hover { color: #5577aa; }
/* ── Relay Admin button ───────────────────────────────────────────── */
#relay-admin-btn {
display: none;
font-family: 'Courier New', monospace; font-size: 11px; font-weight: bold;
color: #f7931a; background: rgba(40, 25, 5, 0.85); border: 1px solid #f7931a55;
padding: 7px 18px; cursor: pointer; letter-spacing: 2px;
box-shadow: 0 0 14px #f7931a22;
transition: background 0.15s, box-shadow 0.15s, color 0.15s;
border-radius: 2px;
min-height: 36px;
text-decoration: none;
}
#relay-admin-btn:hover, #relay-admin-btn:active {
background: rgba(60, 35, 8, 0.95);
box-shadow: 0 0 20px #f7931a44;
color: #ffb347;
}
/* ── AR pulse animation ──────────────────────────────────────────── */
@keyframes ar-pulse {
0%, 100% { opacity: 0.6; transform: scale(1); }
@@ -460,8 +505,9 @@
pointer-events: none;
}
#webgl-recovery-overlay .recovery-text {
color: #5577aa; font-family: 'Courier New', monospace;
color: #22aa66; font-family: 'Courier New', monospace;
font-size: 15px; letter-spacing: 3px;
text-shadow: 0 0 10px #11663388;
animation: ctx-blink 1.2s step-end infinite;
}
@keyframes ctx-blink {
@@ -487,6 +533,254 @@
}
#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; }
}
/* ── History button ──────────────────────────────────────────────── */
#open-history-btn {
font-family: 'Courier New', monospace; font-size: 11px; font-weight: bold;
color: #aabbdd; background: rgba(20, 16, 50, 0.85); border: 1px solid #2a2a44;
padding: 7px 18px; cursor: pointer; letter-spacing: 2px;
box-shadow: 0 0 14px #2244aa22;
transition: background 0.15s, box-shadow 0.15s, color 0.15s;
border-radius: 2px;
min-height: 36px;
}
#open-history-btn:hover, #open-history-btn:active {
background: rgba(35, 28, 80, 0.95);
box-shadow: 0 0 20px #3355aa44;
color: #ccddff;
}
/* ── History panel (bottom sheet) ───────────────────────────────── */
#history-panel {
position: fixed; bottom: -100%; left: 0; right: 0;
height: 70vh;
background: rgba(5, 3, 12, 0.97);
border-top: 1px solid #1a1a2e;
z-index: 100;
font-family: 'Courier New', monospace;
transition: bottom 0.35s cubic-bezier(0.4, 0, 0.2, 1);
box-shadow: 0 -8px 32px rgba(40, 60, 120, 0.18);
display: flex; flex-direction: column;
}
#history-panel.open { bottom: 60px; }
.hist-header {
display: flex; align-items: center; gap: 8px;
padding: 14px 20px 10px;
border-bottom: 1px solid #1a1a2e;
font-size: 12px; letter-spacing: 3px; color: #5577aa;
flex-shrink: 0;
}
.hist-header span { flex: 1; text-shadow: 0 0 8px #2244aa66; }
#history-refresh-btn, #history-close {
background: transparent; border: 1px solid #1a1a2e;
color: #334466; font-family: 'Courier New', monospace;
font-size: 11px; padding: 3px 10px; cursor: pointer;
transition: color 0.2s, border-color 0.2s; letter-spacing: 1px;
border-radius: 2px;
}
#history-refresh-btn:hover { color: #5577aa; border-color: #334466; }
#history-refresh-btn:disabled { opacity: 0.4; cursor: default; }
#history-close { font-size: 14px; padding: 3px 8px; }
#history-close:hover { color: #6688bb; border-color: #4466aa; }
#history-list {
flex: 1; overflow-y: auto; padding: 12px 16px;
overscroll-behavior: contain;
}
.hist-empty {
color: #334466; font-size: 11px; letter-spacing: 1px;
line-height: 1.8; text-align: center;
margin-top: 40px; padding: 0 20px;
}
.hist-row {
border: 1px solid #1a1a2e; border-radius: 2px;
margin-bottom: 10px; overflow: hidden;
background: #060310;
}
.hist-row.hist-rejected { border-color: #331111; }
.hist-row-header {
padding: 10px 12px; cursor: pointer;
transition: background 0.15s;
}
.hist-row-header:hover { background: rgba(30, 25, 60, 0.6); }
.hist-prompt {
color: #aabbdd; font-size: 12px; line-height: 1.5;
display: -webkit-box; -webkit-line-clamp: 2;
-webkit-box-orient: vertical; overflow: hidden;
margin-bottom: 6px;
}
.hist-meta {
display: flex; gap: 12px; align-items: center;
}
.hist-cost { font-size: 10px; color: #ffcc44; letter-spacing: 1px; }
.hist-rejected .hist-cost { color: #994444; }
.hist-time { font-size: 10px; color: #334466; letter-spacing: 0.5px; flex: 1; }
.hist-chevron { font-size: 10px; color: #334466; transition: color 0.15s; }
.hist-row-header:hover .hist-chevron { color: #5577aa; }
.hist-row-body {
max-height: 0; overflow: hidden;
transition: max-height 0.3s ease-out;
}
.hist-row.expanded .hist-row-body {
max-height: 400px;
border-top: 1px solid #1a1a2e;
}
.hist-result {
color: #aabbdd; font-family: 'Courier New', monospace;
font-size: 11px; line-height: 1.6;
white-space: pre-wrap; word-break: break-word;
padding: 12px; margin: 0;
max-height: 400px; overflow-y: auto;
}
/* ── Tower Log button ────────────────────────────────────────────── */
#open-tower-log-btn {
font-family: 'Courier New', monospace; font-size: 11px; font-weight: bold;
color: #ccaaff; background: rgba(25, 10, 45, 0.85); border: 1px solid #663399;
padding: 7px 18px; cursor: pointer; letter-spacing: 2px;
box-shadow: 0 0 14px #44116622;
transition: background 0.15s, box-shadow 0.15s, color 0.15s;
border-radius: 2px;
min-height: 36px;
}
#open-tower-log-btn:hover, #open-tower-log-btn:active {
background: rgba(45, 18, 80, 0.95);
box-shadow: 0 0 20px #55228844;
color: #eeddff;
}
/* ── Tower Log panel (bottom sheet) ─────────────────────────────── */
#tower-log-panel {
position: fixed; bottom: -100%; left: 0; right: 0;
height: 65vh;
background: rgba(6, 3, 14, 0.97);
border-top: 1px solid #2a1040;
z-index: 100;
font-family: 'Courier New', monospace;
transition: bottom 0.35s cubic-bezier(0.4, 0, 0.2, 1);
box-shadow: 0 -8px 32px rgba(80, 30, 130, 0.18);
display: flex; flex-direction: column;
}
#tower-log-panel.open { bottom: 60px; }
.tlog-header {
display: flex; align-items: center; gap: 8px;
padding: 14px 20px 10px;
border-bottom: 1px solid #2a1040;
font-size: 12px; letter-spacing: 3px; color: #9966cc;
flex-shrink: 0;
text-shadow: 0 0 8px #66228866;
}
.tlog-header span { flex: 1; }
#tower-log-close {
background: transparent; border: 1px solid #2a1040;
color: #664488; font-family: 'Courier New', monospace;
font-size: 14px; padding: 3px 8px; cursor: pointer;
transition: color 0.2s, border-color 0.2s; border-radius: 2px;
}
#tower-log-close:hover { color: #bb88ff; border-color: #8844bb; }
#tower-log-list {
flex: 1; overflow-y: auto; padding: 12px 20px;
overscroll-behavior: contain;
}
.tlog-empty {
color: #44224466; font-size: 11px; letter-spacing: 1px;
line-height: 1.8; text-align: center;
margin-top: 40px; padding: 0 20px;
}
.tlog-entry {
padding: 8px 0;
border-bottom: 1px solid #1a0a2a;
display: flex; gap: 10px; align-items: baseline;
animation: tlog-fade-in 0.4s ease-out;
}
.tlog-entry:last-child { border-bottom: none; }
@keyframes tlog-fade-in {
from { opacity: 0; transform: translateY(4px); }
to { opacity: 1; transform: translateY(0); }
}
.tlog-time {
font-size: 9px; color: #443355; letter-spacing: 0.5px;
white-space: nowrap; flex-shrink: 0; min-width: 48px;
}
.tlog-text {
font-size: 11px; color: #bb99dd; line-height: 1.5;
letter-spacing: 0.3px;
}
.tlog-new { color: #ddbbff; text-shadow: 0 0 6px #9944cc44; }
</style>
</head>
<body>
@@ -498,11 +792,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>
@@ -514,6 +822,9 @@
<div id="top-buttons">
<button id="open-panel-btn">⚡ SUBMIT JOB</button>
<button id="open-session-btn">⚡ FUND SESSION</button>
<button id="open-history-btn">⏱ HISTORY</button>
<button id="open-tower-log-btn">📜 TOWER LOG</button>
<a id="relay-admin-btn" href="/admin/relay">⚙ RELAY ADMIN</a>
</div>
<!-- ── Low balance notice (above input bar) ───────────────────────── -->
@@ -622,6 +933,7 @@
TYPE IN THE INPUT BAR TO ASK TIMMY.<br>EACH REQUEST DEDUCTS FROM YOUR BALANCE.
</p>
<button class="panel-btn muted" id="session-topup-btn" style="margin-top:20px">⚡ TOP UP BALANCE</button>
<button id="session-clear-history-btn" class="session-link-btn">🗑 Clear history</button>
<div id="session-status-active"></div>
</div>
@@ -661,6 +973,16 @@
<div id="session-error"></div>
</div>
<!-- ── History panel (bottom sheet) ─────────────────────────────── -->
<div id="history-panel">
<div class="hist-header">
<span>⏱ JOB HISTORY</span>
<button id="history-refresh-btn">↺ REFRESH</button>
<button id="history-close"></button>
</div>
<div id="history-list"></div>
</div>
<!-- ── FPS crosshair ─────────────────────────────────────────────── -->
<div id="crosshair"></div>
@@ -681,6 +1003,26 @@
<span class="recovery-text">GPU context lost — recovering...</span>
</div>
<!-- ── Tower Log panel (bottom sheet) ────────────────────────────── -->
<div id="tower-log-panel">
<div class="tlog-header">
<span>📜 TOWER LOG</span>
<button id="tower-log-close"></button>
</div>
<div id="tower-log-list">
<div class="tlog-empty" id="tower-log-empty">The chronicle awaits… events will appear here as Timmy works his magic.</div>
</div>
</div>
<script>
// Show Relay Admin button if admin token is stored in localStorage
(function() {
if (localStorage.getItem('relay_admin_token')) {
var btn = document.getElementById('relay-admin-btn');
if (btn) btn.style.display = 'block';
}
})();
</script>
<script type="module" src="./js/main.js"></script>
</body>
</html>

View File

@@ -36,11 +36,12 @@ const COUNTER_RETORTS = [
"YOU'LL REGRET THAT, MORTAL!",
];
// Residual mini-spring for slight trembling post-fall (STAND only)
const SPRING_STIFFNESS = 7.0;
const SPRING_DAMPING = 0.80;
const MAX_TILT_RAD = 0.12;
const SLAP_IMPULSE = 0.18;
// Spring physics for slap wobble (STAND only)
const SPRING_STIFFNESS = 18.0;
const SPRING_DAMPING = 4.5;
const MAX_TILT_RAD = 0.55;
const SLAP_IMPULSE = 2.8;
const RAGDOLL_TILT_THRESHOLD = 0.42; // if tilt exceeds this, trigger full ragdoll fall
// ── Face emotion targets per internal state ───────────────────────────────────
// lidScale: 0 = fully closed, 1 = wide open
@@ -681,31 +682,54 @@ function _updateRagdoll(dt, t, bodyBob) {
}
// ── applySlap — called by interaction.js on hit ───────────────────────────────
// Applies an additive spring impulse so repeated slaps stack. If accumulated
// tilt exceeds RAGDOLL_TILT_THRESHOLD the full ragdoll fall is triggered.
export function applySlap(hitPoint) {
if (!timmy) return;
// Ignore re-slap while already falling/down — wait until standing again
const rd = timmy.rd;
// Ignore re-slap while already in ragdoll cycle — wait until standing
if (rd.state !== RD_STAND) return;
// XZ direction from Timmy to hit point (fall away from impact)
// XZ direction from Timmy to hit point (wobble/fall away from impact)
const dx = hitPoint.x - TIMMY_POS.x;
const dz = hitPoint.z - TIMMY_POS.z;
const len = Math.sqrt(dx * dx + dz * dz) || 1;
rd.fallDirX = dx / len;
rd.fallDirZ = dz / len;
const dirX = dx / len;
const dirZ = dz / len;
// Start ragdoll fall
rd.state = RD_FALL;
rd.timer = 0;
rd.fallAngle = 0;
// Additive spring impulse — stacks with any existing wobble
rd.slapVelocity.x += dirZ * SLAP_IMPULSE; // rotation.x driven by Z direction
rd.slapVelocity.z += -dirX * SLAP_IMPULSE; // rotation.z driven by X direction
// Pip startle — maximum scatter
timmy.pipStartleTimer = 5.0;
timmy.pipStartleDir.x = (Math.random() - 0.5) * 8.0;
timmy.pipStartleDir.z = (Math.random() - 0.5) * 8.0;
// Check if accumulated tilt is large enough to trigger full ragdoll
const tiltMag = Math.sqrt(rd.slapOffset.x * rd.slapOffset.x + rd.slapOffset.z * rd.slapOffset.z);
const velMag = Math.sqrt(rd.slapVelocity.x * rd.slapVelocity.x + rd.slapVelocity.z * rd.slapVelocity.z);
// Crystal flash on impact
if (tiltMag > RAGDOLL_TILT_THRESHOLD || velMag > SLAP_IMPULSE * 2.2) {
// Enough stacked force — trigger full ragdoll fall
rd.fallDirX = dirX;
rd.fallDirZ = dirZ;
rd.state = RD_FALL;
rd.timer = 0;
rd.fallAngle = 0;
// Reset spring state so it's clean when returning to STAND
rd.slapOffset.x = 0; rd.slapOffset.z = 0;
rd.slapVelocity.x = 0; rd.slapVelocity.z = 0;
// Pip startle — maximum scatter on ragdoll
timmy.pipStartleTimer = 5.0;
timmy.pipStartleDir.x = (Math.random() - 0.5) * 8.0;
timmy.pipStartleDir.z = (Math.random() - 0.5) * 8.0;
} else {
// Pip mild startle on wobble
timmy.pipStartleTimer = Math.max(timmy.pipStartleTimer, 3.0);
timmy.pipStartleDir.x = (Math.random() - 0.5) * 4.0;
timmy.pipStartleDir.z = (Math.random() - 0.5) * 4.0;
}
// Crystal flash on every hit
timmy.hitFlashTimer = 0.5;
// Cartoonish SMACK sound

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();
}

222
the-matrix/js/history.js Normal file
View File

@@ -0,0 +1,222 @@
/**
* history.js — Job history panel for Timmy Tower Workshop.
*
* Persists completed jobs in localStorage and renders them in a
* bottom-sheet panel with expandable results and pull-to-refresh.
*
* Public API:
* addHistoryEntry(entry) — called by payment.js / session.js on completion
* initHistoryPanel() — wire up DOM (call once from main.js)
*/
const LS_KEY = 'timmy_history_v1';
const MAX_ENTRIES = 50;
// ── Persistence ───────────────────────────────────────────────────────────────
function _loadEntries() {
try {
const raw = localStorage.getItem(LS_KEY);
return raw ? JSON.parse(raw) : [];
} catch {
return [];
}
}
function _saveEntries(entries) {
try {
localStorage.setItem(LS_KEY, JSON.stringify(entries));
} catch { /* storage full — oldest already trimmed */ }
}
/**
* Record a completed job.
* @param {object} entry
* @param {string} entry.jobId
* @param {string} entry.request — user prompt
* @param {number} entry.costSats — sats charged (0 for free/session)
* @param {string} entry.result — AI answer or rejection reason
* @param {string} entry.state — 'complete' | 'rejected' | 'failed'
* @param {string} [entry.completedAt] — ISO timestamp (defaults to now)
*/
export function addHistoryEntry({ jobId, request, costSats, result, state, completedAt }) {
const entries = _loadEntries();
const entry = {
jobId: jobId ?? `local-${Date.now()}`,
request: request ?? '',
costSats: costSats ?? 0,
result: result ?? '',
state: state ?? 'complete',
completedAt: completedAt ?? new Date().toISOString(),
};
const idx = entries.findIndex(e => e.jobId === entry.jobId);
if (idx >= 0) {
entries[idx] = entry;
} else {
entries.unshift(entry); // newest first
if (entries.length > MAX_ENTRIES) entries.length = MAX_ENTRIES;
}
_saveEntries(entries);
}
// ── Helpers ───────────────────────────────────────────────────────────────────
function _relativeTime(isoString) {
try {
const diff = Date.now() - new Date(isoString).getTime();
const secs = Math.floor(diff / 1000);
if (secs < 60) return `${secs}s ago`;
const mins = Math.floor(secs / 60);
if (mins < 60) return `${mins} min ago`;
const hrs = Math.floor(mins / 60);
if (hrs < 24) return `${hrs}h ago`;
const days = Math.floor(hrs / 24);
return `${days}d ago`;
} catch {
return '';
}
}
function _escHtml(text) {
return String(text)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
}
function _truncate(text, maxLen) {
if (!text) return '';
return text.length > maxLen ? text.slice(0, maxLen) + '…' : text;
}
// ── Rendering ─────────────────────────────────────────────────────────────────
function _renderEntries(entries, container) {
container.innerHTML = '';
if (!entries.length) {
const empty = document.createElement('div');
empty.className = 'hist-empty';
empty.textContent = 'No completed jobs yet. Submit a job to see your history here.';
container.appendChild(empty);
return;
}
entries.forEach(entry => {
const row = document.createElement('div');
row.className = 'hist-row' + (entry.state === 'rejected' ? ' hist-rejected' : '');
// ── Header (always visible) ────────────────────────────────────────────
const header = document.createElement('div');
header.className = 'hist-row-header';
const promptEl = document.createElement('div');
promptEl.className = 'hist-prompt';
promptEl.textContent = _truncate(entry.request, 140);
const metaEl = document.createElement('div');
metaEl.className = 'hist-meta';
const costEl = document.createElement('span');
costEl.className = 'hist-cost';
if (entry.state === 'rejected') {
costEl.textContent = 'rejected';
} else if (entry.costSats > 0) {
costEl.textContent = `${entry.costSats} sats`;
} else {
costEl.textContent = 'free';
}
const timeEl = document.createElement('span');
timeEl.className = 'hist-time';
timeEl.textContent = _relativeTime(entry.completedAt);
const chevronEl = document.createElement('span');
chevronEl.className = 'hist-chevron';
chevronEl.textContent = '▸';
metaEl.appendChild(costEl);
metaEl.appendChild(timeEl);
metaEl.appendChild(chevronEl);
header.appendChild(promptEl);
header.appendChild(metaEl);
// ── Body (expandable) ──────────────────────────────────────────────────
const body = document.createElement('div');
body.className = 'hist-row-body';
const pre = document.createElement('pre');
pre.className = 'hist-result';
pre.textContent = entry.result || '(no result)';
body.appendChild(pre);
// ── Toggle ─────────────────────────────────────────────────────────────
let expanded = false;
header.addEventListener('click', () => {
expanded = !expanded;
row.classList.toggle('expanded', expanded);
chevronEl.textContent = expanded ? '▾' : '▸';
});
row.appendChild(header);
row.appendChild(body);
container.appendChild(row);
});
}
// ── Panel state ───────────────────────────────────────────────────────────────
let _panel = null;
let _list = null;
let _refreshBtn = null;
function _open() {
if (!_panel) return;
_panel.classList.add('open');
_refresh();
}
function _close() {
_panel?.classList.remove('open');
}
function _refresh() {
if (!_list) return;
const entries = _loadEntries();
_renderEntries(entries, _list);
if (_refreshBtn) {
_refreshBtn.textContent = '↺ REFRESH';
_refreshBtn.disabled = false;
}
}
export function initHistoryPanel() {
_panel = document.getElementById('history-panel');
_list = document.getElementById('history-list');
_refreshBtn = document.getElementById('history-refresh-btn');
if (!_panel) return;
document.getElementById('open-history-btn')?.addEventListener('click', _open);
document.getElementById('history-close')?.addEventListener('click', _close);
if (_refreshBtn) {
_refreshBtn.addEventListener('click', () => {
_refreshBtn.textContent = '↺ …';
_refreshBtn.disabled = true;
setTimeout(_refresh, 150);
});
}
// Pull-to-refresh: detect downward drag when already scrolled to top
let _touchStartY = 0;
_list?.addEventListener('touchstart', e => {
_touchStartY = e.touches[0].clientY;
}, { passive: true });
_list?.addEventListener('touchend', e => {
const dy = e.changedTouches[0].clientY - _touchStartY;
if (dy > 60 && _list.scrollTop === 0) {
_refresh();
}
}, { passive: true });
}

View File

@@ -5,12 +5,13 @@ 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 { initWebSocket, getConnectionState, getJobCount, initTowerLog } from './websocket.js';
import { initPaymentPanel } from './payment.js';
import { initSessionPanel } from './session.js';
import { initHistoryPanel } from './history.js';
import { initNostrIdentity } from './nostr-identity.js';
import { warmup as warmupEdgeWorker, onReady as onEdgeWorkerReady } from './edge-worker-client.js';
import { setEdgeWorkerReady } from './ui.js';
@@ -44,8 +45,10 @@ function buildWorld(firstInit, stateSnapshot) {
if (firstInit) {
initUI();
initWebSocket(scene);
initTowerLog();
initPaymentPanel();
initSessionPanel();
initHistoryPanel();
void initNostrIdentity('/api');
warmupEdgeWorker();
onEdgeWorkerReady(() => setEdgeWorkerReady());
@@ -81,6 +84,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

@@ -10,6 +10,7 @@
*/
import { getOrRefreshToken } from './nostr-identity.js';
import { addHistoryEntry } from './history.js';
const API_BASE = '/api';
const POLL_INTERVAL_MS = 2000;
@@ -18,6 +19,7 @@ const POLL_TIMEOUT_MS = 60000;
let panel = null;
let closeBtn = null;
let currentJobId = null;
let currentRequest = '';
let pollTimer = null;
export function initPaymentPanel() {
@@ -96,6 +98,7 @@ async function submitJob() {
if (!res.ok) { setError(data.error || 'Failed to create job.'); return; }
currentJobId = data.jobId;
currentRequest = request;
showEvalInvoice(data.evalInvoice);
} catch (err) {
setError('Network error: ' + err.message);
@@ -167,7 +170,7 @@ function startPolling() {
const pollHeaders = token ? { 'X-Nostr-Token': token } : {};
const res = await fetch(`${API_BASE}/jobs/${currentJobId}`, { headers: pollHeaders });
const data = await res.json();
const { state, workInvoice, result, reason } = data;
const { state, workInvoice, result, reason, costLedger, completedAt } = data;
if (state === 'awaiting_work_payment' && workInvoice) {
showWorkInvoice(workInvoice);
@@ -175,10 +178,26 @@ function startPolling() {
return;
}
if (state === 'complete') {
addHistoryEntry({
jobId: currentJobId,
request: currentRequest,
costSats: costLedger?.workAmountSats ?? costLedger?.actualAmountSats ?? 0,
result,
state: 'complete',
completedAt: completedAt ?? new Date().toISOString(),
});
showResult(result, 'complete');
return;
}
if (state === 'rejected') {
addHistoryEntry({
jobId: currentJobId,
request: currentRequest,
costSats: 0,
result: reason,
state: 'rejected',
completedAt: completedAt ?? new Date().toISOString(),
});
showResult(reason, 'rejected');
return;
}

View File

@@ -16,6 +16,7 @@ import { setSpeechBubble, setMood } from './agents.js';
import { appendSystemMessage, setSessionSendHandler, setInputBarSessionMode } from './ui.js';
import { getOrRefreshToken } from './nostr-identity.js';
import { sentiment } from './edge-worker-client.js';
import { addHistoryEntry } from './history.js';
const API = '/api';
const LS_KEY = 'timmy_session_v1';
@@ -51,6 +52,7 @@ export function initSessionPanel() {
_on('session-back-btn', 'click', () => _setStep('active'));
_on('topup-quick-btn', 'click', () => { _openPanel(); _setStep('topup'); });
_on('session-hud-topup', 'click', (e) => { e.preventDefault(); _openPanel(); _setStep('topup'); });
_on('session-clear-history-btn', 'click', _clearHistory);
// Amount preset buttons — deposit (quick-fill the number input)
_panel.querySelectorAll('[data-session-step="fund"] .session-amount-btn').forEach(btn => {
@@ -151,12 +153,21 @@ export async function sessionSendHandler(text) {
return;
}
const prevBalance = _balanceSats;
_balanceSats = data.balanceRemaining ?? 0;
_sessionState = _balanceSats < MIN_BALANCE ? 'paused' : 'active';
_saveToStorage();
_applySessionUI();
const reply = data.result || data.reason || '…';
const costSats = Math.max(0, prevBalance - _balanceSats);
addHistoryEntry({
request: text,
costSats,
result: reply,
state: data.reason && !data.result ? 'rejected' : 'complete',
completedAt: new Date().toISOString(),
});
setSpeechBubble(reply);
appendSystemMessage('Timmy: ' + reply.slice(0, 80));
@@ -419,6 +430,30 @@ function _startTopupPolling() {
_pollTimer = setTimeout(poll, POLL_MS);
}
// ── Clear history ─────────────────────────────────────────────────────────────
async function _clearHistory() {
if (!_sessionId || !_macaroon) return;
const btn = document.getElementById('session-clear-history-btn');
if (btn) btn.disabled = true;
try {
const res = await fetch(`${API}/sessions/${_sessionId}/history`, {
method: 'DELETE',
headers: { 'Authorization': `Bearer ${_macaroon}` },
});
if (res.ok) {
_setStatus('active', '✓ History cleared', '#44dd88');
setTimeout(() => _setStatus('active', '', ''), 2500);
} else {
_setStatus('active', 'Failed to clear history', '#ff6644');
}
} catch (err) {
_setStatus('active', 'Error: ' + err.message, '#ff6644');
} finally {
if (btn) btn.disabled = false;
}
}
// ── Restore from localStorage ─────────────────────────────────────────────────
async function _tryRestore() {

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');
@@ -132,12 +132,145 @@ function _scheduleCostPreview(text) {
_estimateTimer = setTimeout(() => _fetchEstimate(text), 300);
}
// ── Live cost ticker ──────────────────────────────────────────────────────────
// Shown in the top-right HUD during active paid interactions.
// Updated via WebSocket `cost_update` messages from the backend.
let $costTicker = null;
let _tickerHideTimer = null;
function _ensureCostTicker() {
if ($costTicker) return $costTicker;
$costTicker = document.getElementById('timmy-cost-ticker');
if (!$costTicker) {
$costTicker = document.createElement('div');
$costTicker.id = 'timmy-cost-ticker';
$costTicker.style.cssText = [
'position:fixed;top:36px;right:16px',
'font-size:11px;font-family:"Courier New",monospace',
'color:#ffcc44;text-shadow:0 0 6px #aa8822',
'letter-spacing:1px',
'pointer-events:none;z-index:10',
'transition:opacity .4s;opacity:0',
].join(';');
document.body.appendChild($costTicker);
}
return $costTicker;
}
export function showCostTicker(sats) {
clearTimeout(_tickerHideTimer);
const el = _ensureCostTicker();
el.textContent = `⚡ ~${sats} sats`;
el.style.opacity = '1';
}
export function updateCostTicker(sats, isFinal = false) {
clearTimeout(_tickerHideTimer);
const el = _ensureCostTicker();
el.textContent = isFinal ? `${sats} sats charged` : `⚡ ~${sats} sats`;
el.style.opacity = '1';
if (isFinal) {
_tickerHideTimer = setTimeout(hideCostTicker, 5000);
}
}
export function hideCostTicker() {
if (!$costTicker) return;
$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() {
@@ -257,3 +390,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 { appendSystemMessage, appendDebateMessage } from './ui.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;
@@ -18,6 +22,11 @@ let jobCount = 0;
let reconnectTimer = null;
let visitorId = null;
const RECONNECT_DELAY_MS = 5000;
let _towerLogHistory = [];
// 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();
@@ -39,7 +48,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 +105,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 +130,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;
}
@@ -140,6 +171,43 @@ function handleMessage(msg) {
break;
}
case 'cost_update': {
// Real-time cost ticker (#68): show estimated cost when job starts,
// update to final charged amount when job completes.
if (msg.isFinal) {
updateCostTicker(msg.sats, true);
} else {
showCostTicker(msg.sats);
}
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 'tower_log_history': {
// Load history when panel opens
if (Array.isArray(msg.entries)) {
_towerLogHistory = msg.entries;
_renderTowerLog();
}
break;
}
case 'tower_log_entry': {
// New entry streamed in real time
_towerLogHistory.push(msg);
if (_towerLogHistory.length > 20) _towerLogHistory.shift();
_renderTowerLog(msg.id); // pass id to highlight new entry
break;
}
case 'agent_count':
case 'visitor_count':
break;
@@ -155,3 +223,79 @@ export function sendVisitorMessage(text) {
export function getConnectionState() { return connectionState; }
export function getJobCount() { return jobCount; }
// ── Tower Log panel ────────────────────────────────────────────────────────
function _renderTowerLog(newId) {
const list = document.getElementById('tower-log-list');
const empty = document.getElementById('tower-log-empty');
if (!list) return;
if (_towerLogHistory.length === 0) {
if (empty) empty.style.display = 'block';
return;
}
if (empty) empty.style.display = 'none';
// Remove old entries (keep only the empty placeholder and rebuild)
Array.from(list.querySelectorAll('.tlog-entry')).forEach(el => el.remove());
for (const entry of _towerLogHistory) {
const el = document.createElement('div');
el.className = 'tlog-entry' + (entry.id === newId ? ' tlog-new' : '');
el.dataset.id = entry.id;
const t = document.createElement('div');
t.className = 'tlog-time';
const d = new Date(entry.createdAt);
t.textContent = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
const n = document.createElement('div');
n.className = 'tlog-text';
n.textContent = entry.narrative;
el.appendChild(t);
el.appendChild(n);
list.appendChild(el);
}
// Auto-scroll to bottom
list.scrollTop = list.scrollHeight;
// Fade new entry highlight after 3s
if (newId) {
setTimeout(() => {
const el = list.querySelector(`[data-id="${newId}"]`);
if (el) el.classList.remove('tlog-new');
}, 3000);
}
}
export function initTowerLog() {
const openBtn = document.getElementById('open-tower-log-btn');
const panel = document.getElementById('tower-log-panel');
const closeBtn = document.getElementById('tower-log-close');
if (!openBtn || !panel || !closeBtn) return;
openBtn.addEventListener('click', () => {
panel.classList.add('open');
// Fetch history if empty
if (_towerLogHistory.length === 0) {
fetch('/api/tower-log')
.then(r => r.json())
.then(data => {
if (Array.isArray(data.entries)) {
_towerLogHistory = data.entries;
_renderTowerLog();
}
})
.catch(() => {});
} else {
_renderTowerLog();
}
});
closeBtn.addEventListener('click', () => {
panel.classList.remove('open');
});
}

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) {

View File

@@ -13,7 +13,7 @@
"three": "0.171.0"
},
"devDependencies": {
"vite": "^5.4.0"
"vite": "^5.4.15"
}
},
"node_modules/@esbuild/aix-ppc64": {