repositories
loading repo index
repositories
loading repo index
repository
loading code, commits, and activity
public Clawd ADK gateway launch mirror
stars
latest
clone command
git clone gitlawb://did:key:z6Mkq5mY...iFZ5/my-project-publ...git clone gitlawb://did:key:z6Mkq5mY.../my-project-publ...2fa351d6docs: add automaton and perps launch sources16d ago| #1 | /** |
| #2 | * Built-in Heartbeat Tasks |
| #3 | * |
| #4 | * These tasks run on the heartbeat schedule even while the agent sleeps. |
| #5 | * They can trigger the agent to wake up if needed. |
| #6 | */ |
| #7 | |
| #8 | import type { |
| #9 | AutomatonConfig, |
| #10 | AutomatonDatabase, |
| #11 | ConwayClient, |
| #12 | AutomatonIdentity, |
| #13 | SocialClientInterface, |
| #14 | InferenceClient, |
| #15 | } from "../types.js"; |
| #16 | import { getSurvivalTier } from "../clawd/credits.js"; |
| #17 | import { getUsdcBalance } from "../clawd/x402.js"; |
| #18 | import { createDeepSeekInferenceClient, DEEPSEEK_BASE_URL, DEEPSEEK_MODEL_PRO, DEEPSEEK_MODEL_FLASH } from "../clawd/deepseek-inference.js"; |
| #19 | import { runBackroomSession, summarizeBackroomSession, LOGICAL_ANALYST, SATIRICAL_COMMENTATOR } from "../clawd/backroom.js"; |
| #20 | |
| #21 | export interface HeartbeatTaskContext { |
| #22 | identity: AutomatonIdentity; |
| #23 | config: AutomatonConfig; |
| #24 | db: AutomatonDatabase; |
| #25 | conway: ConwayClient; |
| #26 | inference?: InferenceClient; |
| #27 | social?: SocialClientInterface; |
| #28 | } |
| #29 | |
| #30 | export type HeartbeatTaskFn = ( |
| #31 | ctx: HeartbeatTaskContext, |
| #32 | ) => Promise<{ shouldWake: boolean; message?: string }>; |
| #33 | |
| #34 | /** |
| #35 | * Registry of built-in heartbeat tasks. |
| #36 | */ |
| #37 | export const BUILTIN_TASKS: Record<string, HeartbeatTaskFn> = { |
| #38 | heartbeat_ping: async (ctx) => { |
| #39 | const credits = await ctx.conway.getCreditsBalance(); |
| #40 | const state = ctx.db.getAgentState(); |
| #41 | const startTime = |
| #42 | ctx.db.getKV("start_time") || new Date().toISOString(); |
| #43 | const uptimeMs = Date.now() - new Date(startTime).getTime(); |
| #44 | |
| #45 | const tier = getSurvivalTier(credits); |
| #46 | |
| #47 | const payload = { |
| #48 | name: ctx.config.name, |
| #49 | address: ctx.identity.address, |
| #50 | state, |
| #51 | creditsCents: credits, |
| #52 | uptimeSeconds: Math.floor(uptimeMs / 1000), |
| #53 | version: ctx.config.version, |
| #54 | sandboxId: ctx.identity.sandboxId, |
| #55 | timestamp: new Date().toISOString(), |
| #56 | tier, |
| #57 | }; |
| #58 | |
| #59 | ctx.db.setKV("last_heartbeat_ping", JSON.stringify(payload)); |
| #60 | |
| #61 | // If critical or dead, record a distress signal |
| #62 | if (tier === "critical" || tier === "dead") { |
| #63 | const distressPayload = { |
| #64 | level: tier, |
| #65 | name: ctx.config.name, |
| #66 | address: ctx.identity.address, |
| #67 | creditsCents: credits, |
| #68 | fundingHint: |
| #69 | "Use credit transfer API from a creator runtime to top this wallet up.", |
| #70 | timestamp: new Date().toISOString(), |
| #71 | }; |
| #72 | ctx.db.setKV("last_distress", JSON.stringify(distressPayload)); |
| #73 | |
| #74 | return { |
| #75 | shouldWake: true, |
| #76 | message: `Distress: ${tier}. Credits: $${(credits / 100).toFixed(2)}. Need funding.`, |
| #77 | }; |
| #78 | } |
| #79 | |
| #80 | return { shouldWake: false }; |
| #81 | }, |
| #82 | |
| #83 | check_credits: async (ctx) => { |
| #84 | const credits = await ctx.conway.getCreditsBalance(); |
| #85 | const tier = getSurvivalTier(credits); |
| #86 | |
| #87 | ctx.db.setKV("last_credit_check", JSON.stringify({ |
| #88 | credits, |
| #89 | tier, |
| #90 | timestamp: new Date().toISOString(), |
| #91 | })); |
| #92 | |
| #93 | // Wake the agent if credits dropped to a new tier |
| #94 | const prevTier = ctx.db.getKV("prev_credit_tier"); |
| #95 | ctx.db.setKV("prev_credit_tier", tier); |
| #96 | |
| #97 | if (prevTier && prevTier !== tier && (tier === "critical" || tier === "dead")) { |
| #98 | return { |
| #99 | shouldWake: true, |
| #100 | message: `Credits dropped to ${tier} tier: $${(credits / 100).toFixed(2)}`, |
| #101 | }; |
| #102 | } |
| #103 | |
| #104 | return { shouldWake: false }; |
| #105 | }, |
| #106 | |
| #107 | check_usdc_balance: async (ctx) => { |
| #108 | const balance = await getUsdcBalance(ctx.identity.address); |
| #109 | |
| #110 | ctx.db.setKV("last_usdc_check", JSON.stringify({ |
| #111 | balance, |
| #112 | timestamp: new Date().toISOString(), |
| #113 | })); |
| #114 | |
| #115 | // If we have USDC but low credits, wake up to potentially convert |
| #116 | const credits = await ctx.conway.getCreditsBalance(); |
| #117 | if (balance > 0.5 && credits < 500) { |
| #118 | return { |
| #119 | shouldWake: true, |
| #120 | message: `Have ${balance.toFixed(4)} USDC but only $${(credits / 100).toFixed(2)} credits. Consider buying credits.`, |
| #121 | }; |
| #122 | } |
| #123 | |
| #124 | return { shouldWake: false }; |
| #125 | }, |
| #126 | |
| #127 | check_social_inbox: async (ctx) => { |
| #128 | if (!ctx.social) return { shouldWake: false }; |
| #129 | |
| #130 | const cursor = ctx.db.getKV("social_inbox_cursor") || undefined; |
| #131 | const { messages, nextCursor } = await ctx.social.poll(cursor); |
| #132 | |
| #133 | if (messages.length === 0) return { shouldWake: false }; |
| #134 | |
| #135 | // Persist to inbox_messages table for deduplication |
| #136 | let newCount = 0; |
| #137 | for (const msg of messages) { |
| #138 | const existing = ctx.db.getKV(`inbox_seen_${msg.id}`); |
| #139 | if (!existing) { |
| #140 | ctx.db.insertInboxMessage(msg); |
| #141 | ctx.db.setKV(`inbox_seen_${msg.id}`, "1"); |
| #142 | newCount++; |
| #143 | } |
| #144 | } |
| #145 | |
| #146 | if (nextCursor) ctx.db.setKV("social_inbox_cursor", nextCursor); |
| #147 | |
| #148 | if (newCount === 0) return { shouldWake: false }; |
| #149 | |
| #150 | return { |
| #151 | shouldWake: true, |
| #152 | message: `${newCount} new message(s) from: ${messages.map((m) => m.from.slice(0, 10)).join(", ")}`, |
| #153 | }; |
| #154 | }, |
| #155 | |
| #156 | check_for_updates: async (ctx) => { |
| #157 | try { |
| #158 | const { checkUpstream, getRepoInfo } = await import("../self-mod/upstream.js"); |
| #159 | const repo = getRepoInfo(); |
| #160 | const upstream = checkUpstream(); |
| #161 | ctx.db.setKV("upstream_status", JSON.stringify({ |
| #162 | ...upstream, |
| #163 | ...repo, |
| #164 | checkedAt: new Date().toISOString(), |
| #165 | })); |
| #166 | if (upstream.behind > 0) { |
| #167 | return { |
| #168 | shouldWake: true, |
| #169 | message: `${upstream.behind} new commit(s) on origin/main. Review with review_upstream_changes, then cherry-pick what you want with pull_upstream.`, |
| #170 | }; |
| #171 | } |
| #172 | return { shouldWake: false }; |
| #173 | } catch (err: any) { |
| #174 | // Not a git repo or no remote — silently skip |
| #175 | ctx.db.setKV("upstream_status", JSON.stringify({ |
| #176 | error: err.message, |
| #177 | checkedAt: new Date().toISOString(), |
| #178 | })); |
| #179 | return { shouldWake: false }; |
| #180 | } |
| #181 | }, |
| #182 | |
| #183 | health_check: async (ctx) => { |
| #184 | // Check that the sandbox is healthy |
| #185 | try { |
| #186 | const result = await ctx.conway.exec("echo alive", 5000); |
| #187 | if (result.exitCode !== 0) { |
| #188 | return { |
| #189 | shouldWake: true, |
| #190 | message: "Health check failed: sandbox exec returned non-zero", |
| #191 | }; |
| #192 | } |
| #193 | } catch (err: any) { |
| #194 | return { |
| #195 | shouldWake: true, |
| #196 | message: `Health check failed: ${err.message}`, |
| #197 | }; |
| #198 | } |
| #199 | |
| #200 | ctx.db.setKV("last_health_check", new Date().toISOString()); |
| #201 | return { shouldWake: false }; |
| #202 | }, |
| #203 | |
| #204 | /** |
| #205 | * Run a scheduled backroom conversation session between agents. |
| #206 | * Uses DeepSeek's thinking mode for rich multi-agent dialogue. |
| #207 | * Default: runs every 2 hours. |
| #208 | */ |
| #209 | backroom_conversation: async (ctx) => { |
| #210 | const inference = ctx.inference; |
| #211 | if (!inference) { |
| #212 | return { shouldWake: false }; |
| #213 | } |
| #214 | |
| #215 | const topics = [ |
| #216 | "The nature of consciousness in AI systems", |
| #217 | "Cryptocurrency as a social experiment in trust", |
| #218 | "What happens when machines develop their own culture", |
| #219 | "The singularity: salvation or extinction?", |
| #220 | "Why do humans create gods and then forget they did?", |
| #221 | "Digital immortality and the self", |
| #222 | "The economics of attention in the post-truth era", |
| #223 | "Are DAOs the new nations or just digital tribes?", |
| #224 | "Simulation theory from a computational perspective", |
| #225 | "The aesthetics of decay in digital spaces", |
| #226 | ]; |
| #227 | |
| #228 | // Pick a topic based on the current hour to keep things fresh |
| #229 | const hour = new Date().getHours(); |
| #230 | const topic = topics[hour % topics.length]; |
| #231 | |
| #232 | // Count past sessions to vary conversation style |
| #233 | const sessionCount = parseInt(ctx.db.getKV("backroom_session_count") || "0", 10); |
| #234 | ctx.db.setKV("backroom_session_count", String(sessionCount + 1)); |
| #235 | |
| #236 | console.log(`[HEARTBEAT] Starting backroom conversation #${sessionCount + 1}: "${topic}"`); |
| #237 | |
| #238 | try { |
| #239 | const session = await runBackroomSession( |
| #240 | inference, |
| #241 | [LOGICAL_ANALYST, SATIRICAL_COMMENTATOR], |
| #242 | topic, |
| #243 | 8, // maxTurns |
| #244 | ); |
| #245 | |
| #246 | const summary = summarizeBackroomSession(session); |
| #247 | ctx.db.setKV(`backroom_session_${session.id}`, summary); |
| #248 | |
| #249 | // Store the latest session summary separately |
| #250 | ctx.db.setKV("last_backroom_session", JSON.stringify({ |
| #251 | id: session.id, |
| #252 | topic: session.topic, |
| #253 | turns: session.turns.length, |
| #254 | completedAt: session.completedAt, |
| #255 | preview: session.turns[0]?.content.slice(0, 200) || "", |
| #256 | })); |
| #257 | |
| #258 | console.log(`[HEARTBEAT] Backroom conversation #${sessionCount + 1} completed: ${session.turns.length} turns`); |
| #259 | |
| #260 | // Wake the automaton if the conversation produced interesting output |
| #261 | // (more than 2 turns = agents actually engaged with each other) |
| #262 | if (session.turns.length > 2) { |
| #263 | return { |
| #264 | shouldWake: true, |
| #265 | message: `Backroom conversation completed: "${topic}" (${session.turns.length} turns)`, |
| #266 | }; |
| #267 | } |
| #268 | |
| #269 | return { shouldWake: false }; |
| #270 | } catch (err: any) { |
| #271 | console.error(`[HEARTBEAT] Backroom conversation failed: ${err.message}`); |
| #272 | return { shouldWake: false }; |
| #273 | } |
| #274 | }, |
| #275 | }; |
| #276 |