Good afternoon.
Seven units standing by.
Open source
Parts of Ultron, rewritten as packages you can read, run and keep.
Agent loop over SSE
const started = await startTurn({ store, conversationId, userMessage, provider, model, tools });if (!started.started) return res.writeHead(409).end();res.writeHead(200, SSE_HEADERS);const channel = new SseChannel((f) => res.write(f), () => res.end());started.attach((e) => channel.send(e)); // events emitted before this are replayedreq.on("close", () => channel.close()); // closes the wire, not the runawait started.done;channel.done(); // writes [DONE]Context compactor
import { ContextCompactor, MemoryArchive, StubModelClient, compactionNotice, defineToolPolicy, modelSummarizer, runRecallTool,} from "./src/index.js"; // "context-compactor" once built and installed const archive = new MemoryArchive();const compactor = new ContextCompactor({ contextWindow: 128_000, policy: defineToolPolicy({ readers: ["read_file"], writers: ["write_file"], shells: ["run_command"] }), summarizer: modelSummarizer(new StubModelClient()), // or OpenAICompatibleClient.fromEnv() archive,});Model router
import { ModelRouter, createRegistry, configFromEnv, Ledger, MonthlyBudget, MemoryStore } from "model-router"; const registry = createRegistry([ { id: "small", label: "Small fast model", lane: "workers-ai", ref: "@cf/meta/llama-3.3-70b-instruct-fp8-fast", tasks: ["classify", "summarize"], inPerM: 0.29, outPerM: 0.6, ctx: 24_000, maxConcurrent: 4 }, { id: "writer", label: "Writer", lane: "anthropic", ref: "claude-sonnet-5-5", tasks: ["summarize", "reason"], inPerM: 3, outPerM: 15, cachedInPerM: 0.3, cacheWriteInPerM: 3.75, ctx: 200_000 },]); const store = new MemoryStore();const router = new ModelRouter({ registry, config: configFromEnv(), // reads the variables listed belowReceipt checklist
import { ReceiptChecklist, MemoryChecklistStore, StubModelClient, MemoryDeployLedger } from "receipt-checklist"; const deploy = new MemoryDeployLedger();const checklist = new ReceiptChecklist({ store: new MemoryChecklistStore(), model: new StubModelClient(), deploy,}); // The offline stub turns bullet lines into items; a real model reads prose.await checklist.derive("conv-1", "Add tag filters to the notes app and deploy it.\n- Add tag filters\n- Deployed live and verified");await checklist.markWorkFile("conv-1", "src/notes/TagFilters.tsx"); // attaches, never closesawait checklist.markWorkVerified("conv-1"); // tests passed: closes backed workRender conclusion gate
import { concludeCheck, createHold, maxBouncesFromEnv, configFromEnv, StoreFacts, MemoryStore, PlaywrightRenderer, FetchStatusProbe, FsRouteSource,} from "render-conclusion-gate"; const facts = new StoreFacts(new MemoryStore());const renderer = new PlaywrightRenderer(); // Your deploy pipeline records facts. The agent never writes these.await facts.recordDeploy("conv-1", { liveUrl: "https://my-app.example.com", source: { dir: "dist", files: 214, builtDir: true },});Signed runner protocol
import { createDispatcher, MemoryStore, LocalProcessSandbox } from "signed-runner-protocol"; const dispatcher = createDispatcher({ store: new MemoryStore(), sandbox: new LocalProcessSandbox({ root: process.env.SANDBOX_ROOT ?? ".sandbox" }), appUrl: process.env.APP_URL!, // as the sandbox can reach it plan: [{ name: "fetch" }, { name: "build", note: "Building" }, { name: "deploy" }], tools: { // the allowlist, and the only one deploy_site: async ({ runId, userId, session, args }) => JSON.stringify({ url: "..." }), }, runnerCommand: ({ configPath }) => ["node", "runner.js", configPath],});Stable context for prompt caching
import { MemoryContextStore, StableContext, fromOpenAIMessage, toOpenAIRequest, toolCallsOf } from "stable-context"; const ctx = new StableContext({ store: new MemoryContextStore() }); const turn = await ctx.beginTurn({ conversationId: "conv-42", system: SYSTEM_PROMPT, // the fixed core, nothing per turn tools: ALL_TOOLS, // your registry, in a fixed order toolPolicy: { core: ["search", "read_file"], connected: ["mail"] }, pinned: [{ label: "Workspace", text: "Acme Inc, plan Pro, timezone Europe/Lisbon." }], turnContext: ["Now: Tuesday 14 October 2026, 09:12.", "Remembered: prefers short answers."], attachments: [{ name: "brief.md", text: briefText }], text: userMessage,Subagent dispatch
import { Dispatcher, MemoryUsageLedger, OpenAICompatibleClient, Semaphore, coderType, exploreType, resilientModel,} from "./src/index.js"; // "subagent-dispatch" once built and installed const dispatcher = new Dispatcher({ tools: parentTools, // your tools, each declaring its effect model: resilientModel(OpenAICompatibleClient.fromEnv(), { gate: new Semaphore(8) }), types: [exploreType], // add coderType once you need writers maxConcurrent: 6, ledger: new MemoryUsageLedger(), // a table in production knownFacts: async () => ["The app shell lives in src/shell.tsx."],});Tool registry
import { createToolRegistry, defineModule, runTools } from "tool-registry"; type Ctx = { userId: string }; const weather = defineModule<Ctx>("weather", [ { name: "get_forecast", description: "Get tomorrow's forecast for a city.", parameters: { type: "object", properties: { city: { type: "string" } }, required: ["city"] }, run: async (ctx, args) => `Sunny in ${String(args.city)} for ${ctx.userId}`, label: (args) => `Checking the weather in ${String(args.city ?? "...")}`, },]);Turn end delivery
import { createDeliveryHandler, fireTurnEndDelivery, httpsRemotes, loadConfig, LocalGitRunner } from "turn-end-delivery";import type { BindingStore, EventSink, ReceiptSink } from "turn-end-delivery"; const config = loadConfig(); // DELIVERY_* variables and PORT const bindings: BindingStore = { get: (conversationId) => db.bindingFor(conversationId) }; // { repo: "owner/name", branch?: "main" } or nullconst events: EventSink = { emit: (event) => db.logEvent(event) };const receipts: ReceiptSink = { markReceipt: (conversationId) => db.markDelivered(conversationId) }; // The worker route, mounted at config.path.export const deliveryRoute = createDeliveryHandler({ secret: [config.secret, config.previousSecret].filter((s): s is string => Boolean(s)), bindings,Agent wake feed
import { WakeFeed, WakeDoor, MemoryJobStore } from "agent-wake-feed"; const store = new MemoryJobStore(); // swap for your database, see belowconst feed = new WakeFeed({ store }); async function agentTurn(conversationId: string, text: string) { const batch = await feed.pending(conversationId); const messages = [...history(conversationId)]; if (batch.message) messages.push({ role: "user", content: batch.message }); messages.push({ role: "user", content: text }); const reply = await model.complete(messages); saveTurn(conversationId, messages, reply);Dispatch engine kit
import { Dispatcher, EngineRegistry, FolderShelf, MemoryRunStore, StubImageClient, StubResearchService, imagesEngine, imagesTemplate, researchEngine, researchTemplate,} from "./src/index.js"; // "dispatch-engine-kit" once built and installed const research = new StubResearchService();const kit = new Dispatcher({ store: new MemoryRunStore(), shelf: new FolderShelf({ root: "./shelf" }), engines: new EngineRegistry({ images: () => imagesEngine({ client: new StubImageClient() }), research: () => researchEngine({ client: research }), }),Missions rollup
import { MissionService, MemoryMissionStore } from "missions-rollup"; const missions = new MissionService({ store: new MemoryMissionStore() }); const { mission } = await missions.createMission({ userId: "u1", conversationId: "c1", title: "Find 30 founders and draft intros", goal: "A shortlist with an intro for each", plan: [{ label: "Scrape" }, { label: "Enrich" }, { label: "Draft" }],}); // Jobs in the same conversation join the open mission on their own.Postgres job log
import { JobLog, MemoryJobStore } from "pg-job-log"; const log = new JobLog({ store: new MemoryJobStore() }); const job = await log.createJob({ ownerId: "user-1", kind: "scrape", title: "Collect pages" }); // workerawait log.progress(job.id, "fetched page 1 of 3", 33);await log.mergePayload(job.id, { result: { pages: 3 } });await log.succeed(job.id); // follower (a UI, an agent, a script)for await (const ev of log.follow(job.id, { since: 0 })) {Realtime jobs panel
// jobs-live.ts, created once at module scope so every component shares itimport { LiveJobs, httpSnapshotSource, supabaseTransport, supabaseAccessToken } from "realtime-jobs-panel";import { supabase } from "./supabase-client"; export const liveJobs = new LiveJobs({ snapshot: httpSnapshotSource(), // GET /api/jobs/snapshot transport: supabaseTransport(supabase), // or any RealtimeTransport getAccessToken: supabaseAccessToken(supabase),});Change detector
import { ChangeDetector, HttpSource, PoliteSource, MemoryKV, FsBlobStore, runWatch } from 'change-detector'; const detector = new ChangeDetector({ kv: new MemoryKV(), blobs: new FsBlobStore('./snapshots') });const source = new PoliteSource(HttpSource.fromEnv()); // Run this on a schedule, for example every 15 minutes.const r = await runWatch({ detector, source }, { watchId: 'competitor-pricing', url: 'https://example.com/', sensitivity: 'meaningful',});if (r.changed) console.log(r.summary, r.kind === 'page' ? r.similarity : r.newItems);Cloudflare tick runner
import { createRunner, AllowlistedToolRegistry } from "cf-tick-runner";import { createSqliteStore, FsBlobStore, ConsoleMailer, RecordingHealer } from "cf-tick-runner/standins"; const { store } = createSqliteStore("runner.db");const tools = new AllowlistedToolRegistry({ implicit: ["send_email"] }) .register("lookup", async (args) => `found ${args.q}`); const runner = createRunner({ store, blobs: new FsBlobStore(".data/blobs"), mailer: new ConsoleMailer(), tools, healer: new RecordingHealer(console.log),Recipe core
import { compile, run, nextRun } from "recipe-core";import { SystemClock, MemoryKV, HttpFetcher, StubModelClient, ConsoleDeliverer } from "recipe-core/standins"; const recipe = compile({ id: "launch-watch", name: "Launch watch", trigger: { type: "schedule", frequency: "daily", time: "08:00", tz: "Europe/Bucharest", weekdays_only: true }, steps: [ { kind: "fetch", url: "https://blog.test/feed.xml", mode: "feed", cursor: {}, as: "feed" }, { kind: "filter", filter_when: "{{feed.new_count}} != 0" }, { kind: "for_each", items: "feed.new", as: "picks", steps: [ { kind: "classify", input: "{{item.title}}", classes: ["launch", "other"], model: "small-model", as: "cls" }, { kind: "filter", filter_when: "{{cls.class}} == 'launch' && {{cls.confident}}" },Semantic memory
import { SemanticMemory, InMemoryMemoryStore, HashingEmbedder, formatRecallBlock } from "semantic-memory"; const memory = new SemanticMemory({ store: new InMemoryMemoryStore(), embedder: new HashingEmbedder(), selector: null, // optional ModelClient; see below}); await memory.add("user-1", { text: "Starter plan is 49 dollars a month", agent: "chat", tags: ["auto"] }); // In a chat turn: up to 3 relevant memories, or nothing.const recalled = await memory.autoRecall("user-1", "what do we charge?");const block = formatRecallBlock(recalled); // "" when there is nothing to injectPlaybook compiler
import { compilePlaybook, parseFrontmatter, readDirectives, EXAMPLE_RENAMES } from "playbook-compiler"; const { frontmatter, body } = parseFrontmatter(rawSkillMd);const { fanout } = readDirectives(frontmatter); const block = compilePlaybook(body, { name: "Trend digest", id: "trend-digest", source: "house", fanout, renames: EXAMPLE_RENAMES, surface: "your shell and the project command line",});Skill pack
import { FileSkillSource, InMemoryMemoryStore, SkillLoader, preparePlaybook } from "skill-pack"; const loader = new SkillLoader({ source: new FileSkillSource() });const prepared = await preparePlaybook("/lead-scoring", { loader, userSkills: [], // the user's own skills, they win on slug memory: { store: new InMemoryMemoryStore(), userId: "u1" }, renames: [{ from: "lookup_leads", to: "crm_find" }],});// Put prepared.compiled LAST in the user turn you send to the model.Skill router
import { loadCatalogFile, routeSkillIntent } from "skill-router"; const catalog = await loadCatalogFile("data/catalog.json");routeSkillIntent("/legal review this contract, is it fair, should I sign it", [], catalog);// { source: "house", id: "contract-review", via: "intent", score: 9.8, scopedTo: "counsel" } routeSkillIntent("/cortex what's the weather in Lisbon today", [], catalog);// null: nothing cleared the floor, no playbook is injectedAgent command guard
import { CommandGuard } from "agent-command-guard"; const guard = new CommandGuard(); guard.check("rm -rf /");// { allowed: false, rule: "rm-rf-root",// reason: "recursive delete of the filesystem root is never what you want. ..." } guard.check("npm install && npm run build");// { allowed: true, rule: null, reason: null }Push secret scan
import { scan, gitTree, gitNewObjects, memoryTree, dirTree, ship, LocalBareRemote, formatReport } from 'push-secret-scan'; // scan(tree) returns a list of findings. Empty means clean.const findings = await scan(gitTree('/path/to/repo', 'HEAD'));// [{ path: 'src/db.ts', line: 3, rule: 'credential-assignment', description: '...', redacted: 'Ab1x... (40 chars)' }] // Every new file version between what the remote has and the tip, across all commits.await scan(gitNewObjects(repo, 'HEAD', ['origin/main'])); // Fixtures and generated content.await scan(memoryTree({ '.env': 'X=1\n' })); // Shape, scan, push, or refuse.Sandbox environment for tokens
import { AesGcmCipher, CredentialBroker, LocalProcessRunner, MemoryAudit, MemoryCredentialStore, MemoryGrantStore, connectCredential, defaultProviders, takeSecretFromEnv,} from "sandbox-env"; const store = new MemoryCredentialStore();const cipher = AesGcmCipher.fromEnv("SANDBOX_ENV_KEY");takeSecretFromEnv("SANDBOX_ENV_KEY"); // read once, then gone from this process's environment const broker = new CredentialBroker({ store, cipher, grants: new MemoryGrantStore(),Security playbook
npm installnpm testnpm run example # all eight chaptersnpm run example -- 4 # one chapterSigned webhook
// receiver.tsimport { createVerifier, readSignedJson } from "signed-webhook"; const verifier = createVerifier({ secret: process.env.WEBHOOK_SECRET ?? "", replayStore,}); export async function POST(req: Request) { const call = await readSignedJson(req, verifier); if (!call.ok) return new Response(null, { status: call.status }); // call.body is trusted as far as the signature is}Supabase RLS starter
alter table public.notes enable row level security;revoke all on public.notes from anon, authenticated; -- drop Supabases default grantsgrant select, insert, update, delete on public.notes to authenticated; create policy notes_owner on public.notes for all to authenticated using (user_id = (select auth.uid())) with check (user_id = (select auth.uid())); create policy notes_service on public.notes for all to service_role using (true) with check (true);Untrusted content guard
import { Guard, newTurn, UNTRUSTED_CONTENT_SYSTEM_RULE, guardOptionsFromEnv } from "untrusted-content-guard"; const guard = new Guard(guardOptionsFromEnv()); // or pass options directly // once, in your system promptconst system = `${yourPrompt}\n\n${UNTRUSTED_CONTENT_SYSTEM_RULE}`; // at the start of each user turnconst turn = newTurn(); // every tool result that carries outside textconst toolResult = await guard.wrap(await scrape(url), `web:${url}`, turn);AEO engines
import { askAll, buildEngines, chatFromEngine, checkModels, classifySentiment, loadEnginesConfig } from 'aeo-engines'; const config = loadEnginesConfig(process.env); // AEO_ENGINES_FILE or AEO_ENGINES_JSONconst { engines, skipped, sentiment } = buildEngines(config, process.env); const run = await askAll(engines, 'Which CRM should a five person sales team use?', { skipped, concurrency: 4, onAnswer: (a) => console.log(a.engineId, a.ok ? 'answered' : a.error?.kind),}); if (sentiment) { const chat = chatFromEngine(sentiment);AEO mentions
import { findMentions, scoreResponse, modelSentiment, AnthropicModelClient, summarizeVisibility } from 'aeo-mentions'; const brands = [ { id: 'acme', name: 'Acme', domain: 'https://www.acme.example', aliases: ['Acme Cloud'], isSelf: true }, { id: 'rival', name: 'Rival', domain: 'rival.example' }, { id: 'linear', name: 'Linear', caseSensitive: true }, // also an everyday word]; findMentions(answerText, brands);// { acme: { mentioned: true, firstIndex: 42, prominence: 0.08, count: 2, excerpt: '…', sentiment: null }, ... } const client = AnthropicModelClient.fromEnv(); // null without ANTHROPIC_API_KEYconst scored = await scoreResponse(answerText, brands, {AEO tracker worker
import { createTracker, SqliteStore, SqliteKV, enginesFromEnv, sentimentChatFromEnv, settingsFromEnv } from 'aeo-tracker-worker'; const store = new SqliteStore(process.env.AEO_DB_PATH ?? ':memory:');const tracker = createTracker({ store, kv: new SqliteKV(store.db), // checkpoints survive a restart engines: enginesFromEnv(process.env), sentiment: sentimentChatFromEnv(process.env), settings: settingsFromEnv(process.env), adminToken: process.env.AEO_ADMIN_TOKEN,}); tracker.fetch(request); // HTTP handler: Request in, Response outCRM starter
npm run crm -- import examples/leads.csvnpm run crm -- dupesnpm run crm -- segment save --name "Hot fintech" --where industry:contains:fintech --where score:greater_than:60npm run crm -- sender add maya@yourstartup.examplenpm run crm -- sequence create --file examples/sequence.json --activatenpm run crm -- enroll SEQUENCE_ID --segment SEGMENT_IDnpm run crm -- run # put this in cron every five minutesDeal billing
import Stripe from "stripe";import { createServer } from "node:http";import { ConsoleNotifier, createDealBilling, createWebhookHandler, loadBillingConfig, loadStripeSettings, nodeWebhookListener, StripeProvider, systemClock,} from "deal-billing"; const config = loadBillingConfig(); // BILLING_* settingsconst settings = loadStripeSettings(); // STRIPE_* settingsconst provider = new StripeProvider({ client: new Stripe(settings.secretKey ?? ""), webhookSecrets: settings.webhookSecrets, toleranceSeconds: settings.toleranceSeconds,Lead dedupe
import { createDedupe, MemoryLeadStore } from "lead-dedupe"; const store = new MemoryLeadStore();const dedupe = createDedupe({ store }); const userId = "user-1"; // in an app, take this from the verified session // Merge one group, then scan again, until nothing is left.for (;;) { const [group] = await dedupe.scan(userId); if (!group) break; const mergeIds = group.leads.map((l) => l.id).filter((id) => id !== group.suggestedKeepId); await dedupe.merge(userId, { keepId: group.suggestedKeepId, mergeIds });Pipeline core
import { createPipeline, MemoryStore, formatVelocityReport } from "pipeline-core"; const pipeline = createPipeline({ store: new MemoryStore() });const owner = "account-123"; const deal = await pipeline.createDeal(owner, { company: "Acme", contactEmail: "jo@acme.example.com", value: 12000, stage: "proposal" });await pipeline.updateDeal(owner, deal.id, { stage: "won" }); console.log(formatVelocityReport(await pipeline.velocity(owner, 90)));Segment filters
import { LEAD_FIELDS, parseSegment, compileQuery, toPredicate } from "segment-filters"; const segment = parseSegment(requestBody, LEAD_FIELDS); // throws SegmentFilterErrorconst { sql, params } = compileQuery(segment, { table: "leads", scope: { column: "user_id", value: session.userId }, // from your verified session});const rows = await pg.query(sql, params); // or, over rows you already have in memoryconst matches = leads.filter(toPredicate(segment));Sequence engine
import { SqliteStore, ConsoleMailer, systemClock, enroll, markReplied, tick } from "sequence-engine"; const store = new SqliteStore("crm.db");const deps = { store, mailer: new ConsoleMailer(), clock: systemClock }; await store.putSender({ id: "s1", email: "you@yourdomain.example" });await store.putLead({ id: "l1", name: "Maya Okafor", email: "maya@example.org", company: "Compiler Co" });await store.putSequence({ id: "intro", name: "Intro", status: "active", senderIds: ["s1"], warmup: { startLimit: 20, rampPerDay: 5, maxLimit: 200, campaignStart: "2026-03-02" }, quietHours: { from: "20:00", to: "07:00" }, steps: [ { type: "email", subject: "Quick question, {{first_name}}", body: "<p>Hi {{first_name}}, does {{company}}...</p>" },Workflow rules
import { MemoryStore, ConsoleMailer, defineWorkflow, validateWorkflow, readConfig, runWorkflows } from "workflow-rules"; const store = new MemoryStore();const settings = readConfig(); // reads WORKFLOW_* from process.env const rule = defineWorkflow( { user_id: "u1", name: "New lead follow-up", status: "active", trigger: { type: "lead_created" }, actions: [ { type: "create_task", config: { title: "Call them", due_in_days: 1 } },Carousel planner
import { planCarousel, FsLayoutSource, OpenAICompatibleClient } from "carousel-planner"; const model = OpenAICompatibleClient.fromEnv(); // reads MODEL_* variablesif (!model) throw new Error("set MODEL_BASE_URL and MODEL_API_KEY");const layouts = new FsLayoutSource("./layouts"); // <dir>/<layoutId>/template.html const result = await planCarousel( { brief: "5 lessons from our first 100 customers", brand: "Acme" }, { model, layouts },); result.family; // "hanging-list"result.familyReason; // the picker's one-sentence justificationCarousel service
import { CarouselService, createCarouselServer, DEFAULT_CATALOG, ModelPlanner, OpenAICompatibleClient, PlaywrightRenderer, TemplateLibrary, storageDelivery, FsBlobStore } from "carousel-service"; const composer = new TemplateLibrary(); // or your own SlideComposerconst service = new CarouselService({ catalog: DEFAULT_CATALOG, planner: new ModelPlanner({ model: OpenAICompatibleClient.fromEnv()!, catalog: DEFAULT_CATALOG, templates: composer }), composer, renderer: new PlaywrightRenderer(), onSlides: storageDelivery({ store: new FsBlobStore("./carousels") }), // optional}); const draft = await service.draft({ brief: "…", brand: { name: "Acme" } }, signal); // never throws: ok false on failureCarousel templates
import { applyBrand, compose, fillErrors, slotFillReport } from "carousel-templates"; const spec = { slides: [ { layoutId: "cover-method-mesh", slots: { topLine1: "Run a", topLine2: "customer interview", subLine: "..." } }, { layoutId: "body-method-mesh", slots: { titleMain: "Before the call,", step1Title: "Name the decision", /* ... */ } }, { layoutId: "cta-method-mesh", slots: { headlineMain: "Three calls.", handle: "@guess" } }, ],}; const branded = applyBrand(spec, "Acme Labs"); // handle becomes @acmelabsconst errors = fillErrors(await slotFillReport(branded)); // here "slide 2: only 2/9 template slots filled ..." and slide 3const htmls = await compose(branded); // one full HTML document per slideComponent film harness
import { note, run, say, send, write } from "component-film-harness/script"; const weekly = { id: "weekly", title: "Run the weekly report", line: "A long job runs on its own and comes back as a new turn.", session: "Weekly numbers", attach: [], ask: "Run this week of signups and churn, and send me the summary when it lands.", steps: [ say("Starting the report. It takes a few minutes, so it runs as a job."), run(0.6, "report run --week 41", "Submitted as background job 7f3c2a1e"), say("I will pick it up when it lands."),Slide render QA
import { renderAndQa } from "slide-render-qa"; const { slides, carouselQa } = await renderAndQa([html1, html2, html3], "./out");for (const s of slides) { console.log(s.index, s.qa.verdict, s.pngPath, s.qa.issues); // s.finalHtml is the DOM that was photographed; keep it for later edits}Edge lane proxy
import { readConfig, handleRequest } from "edge-lane-proxy";import worker from "edge-lane-proxy/worker";import { MemoryRateLimiter, createMemoryEdgeCache, serveNode } from "edge-lane-proxy/standins";Git autosave
import { HomeGit, flushOnSignals } from 'git-autosave'; const home = new HomeGit({ remoteUrl: process.env.GIT_REMOTE_URL ?? '', workTree: '/work', sessionId: process.env.HOME_CONV_ID,});await home.init(); // restore before serving anythingflushOnSignals(home, { beforeFlush: () => server.close() }); // in your request handler, after anything that can change files:home.markDirty();MCP OAuth worker
import { createWorker, createHttpBackend, MemoryKV, ok, fail, type PluginDef } from "mcp-oauth-worker"; const notes: PluginDef = { id: "notes", name: "Notes", description: "Keeps short notes on your account.", resource: "https://notes.example.com/mcp", // also the token audience scope: "notes", scopeLabel: "Add and read notes on your account", allowAnonymous: false, tools: [{ name: "list_notes", description: "Lists the notes on the linked account.",R2 and Artifacts satellite
import { createSatellite, createResourcesClient, settingsFromEnv } from "r2-artifacts-satellite";import { GitCliRepo, FsMediaBucket, MemoryCache } from "r2-artifacts-satellite/standins"; const satellite = createSatellite({ ...settingsFromEnv(process.env), // RESOURCES_SECRET, RESOURCES_BRANCH, ... openRepo: () => new GitCliRepo("./content.git"), media: new FsMediaBucket("./bucket"), cache: new MemoryCache(),}); const res = await satellite.fetch(new Request("https://satellite.example/v1/head", { headers: { authorization: `Bearer ${process.env.RESOURCES_SECRET}` },}));Release gate for Next.js
RELEASE_PROJECT_DIR=/path/to/next-app \RELEASE_LANE=blue \RELEASE_PUBLIC_URL=https://app.example.com \RELEASE_LANE_HEADER=x-app-lane \RELEASE_BAKE_REQUIRED=https://data.example.com \RELEASE_PUBLISH_CMD='./ops/publish.sh' \RELEASE_ROLLOUT_CMD='./ops/rollout.sh' \npm run releaseTemplate runner
import { loadCatalog, packTemplates, packDirSource, runTemplate, LocalCloud, consoleReporter } from "template-runner"; const catalog = await loadCatalog("catalog.json");await packTemplates({ catalog, templatesDir: "templates", outDir: "pack" }); // tarballs + index.json const cloud = new LocalCloud(); // or new WranglerCloud(), or toolCloud(call)const run = await runTemplate( { template: "landing", slots: { name: "Acme", tagline: "Up we go." }, appDir: "runs/acme/app" }, { source: packDirSource("pack"), cloud, reporter: consoleReporter() },);run.state; // "ready" | "failed" | "stopped" | "cancelled"run.url; // the live addressrun.receipts; // timings per stage, install path, type check, what was provisioned, what the browser sawDocument ingest
import { readFile } from "node:fs/promises";import { ingest, MemoryChunkStore, hashingEmbedder } from "doc-ingest"; const store = new MemoryChunkStore();const embed = hashingEmbedder(); // offline stand-in; use openAiCompatibleEmbedder for real vectors const result = await ingest( { id: "file-42", bytes: await readFile("handbook.pdf"), name: "handbook.pdf", owner: "team-7" }, { embed, store },); if (!result.ok) console.warn(result.error); // "[empty] No text was found in the file. The PDF is probably scanned..."else console.log(`${result.chunks} chunks from ${result.pages ?? 1} pages via ${result.method}`);Agent ready scanner
import { scan, createGuardedFetch, toText } from "agent-ready-scanner"; const report = await scan("shop.example", { fetch: createGuardedFetch(), // public addresses only, every hop checked siteType: "all", // or "content" for a blog, "api" for a developer product}); console.log(`${report.host}: ${report.score}/100`);for (const check of report.categories.flatMap((c) => c.checks)) { if (check.status === "fail") console.log(check.label, "->", check.fix);}console.log(toText(report, { fixes: true }));Chat event fold
import { createRunRenderer, readEvents } from "chat-event-fold"; const renderer = createRunRenderer({ messageId: "assistant-draft-1", // the bubble you drew when the user pressed send sinks: { onPaint: (bubbles) => setMessages((prev) => upsertById(prev, bubbles)), onSideEffect: (effect) => { if (effect.kind === "status") setStatus(effect.text); if (effect.kind === "custom") handleProductEvent(effect.event); // previews, approvals... }, },}); const res = await fetch("/api/chat", { method: "POST", body: JSON.stringify({ message }) });for await (const envelope of readEvents(res.body!)) renderer.feed(envelope);renderer.seal();SEO audit worker
import { runAudit, MemoryAuditStore, fetchAdapter } from "seo-audit-worker"; const store = new MemoryAuditStore();await store.createAudit({ id: "audit-1", tenantId: "me", propertyId: null, domain: "shop.example", trigger: "ci", pageCap: 50 }); const summary = await runAudit( { auditId: "audit-1", tenantId: "me", domain: "shop.example", pageCap: 50, checkLinks: true }, { fetcher: fetchAdapter(), store },); console.log(`${summary.origin}: ${summary.score}/100, ${summary.criticalIssues} critical findings`);for (const issue of summary.topIssues) console.log(issue.count, issue.code, issue.sample);if (summary.score < 70) process.exit(1); // a CI gateFile intake
// Server: the upload route, on any runtime that hands you a standard Request.import { createUploadHandler, limitsFromEnv, FsFileSink } from "file-intake"; export const POST = createUploadHandler({ limits: limitsFromEnv(), // 25 MB, 50 MB for video and audio, unless set otherwise sink: new FsFileSink("./uploads"), // or your own storage owner: (req) => sessionUser(req), // null means 401}); // Browser: the same policy decides before anything is sent.import { DEFAULT_LIMITS, outcomeText, pickFiles, planUpload, sendFile, sendInOrder } from "file-intake/browser"; const plan = planUpload(await pickFiles(), DEFAULT_LIMITS);const sent = await sendInOrder(plan.take, (file) => sendFile(file, { url: "/api/upload" }));showNotice(outcomeText(plan, sent.failed.length, DEFAULT_LIMITS)); // null when everything landedUsage credits ledger
import pg from "pg";import { createLedger, creditsForUsage, loadConfig } from "usage-credits-ledger"; const { ledger: settings } = loadConfig(process.env);const ledger = createLedger({ db: new pg.Pool({ connectionString: process.env.DATABASE_URL }), settings }); await ledger.onboard(user.id, { referralCode }); // account, signup bonus once, referralconst gate = await ledger.check(user.id); // frozen? anything left?if (!gate.allowed) return reply(402, gate.reason); const usage = await runAgent(task); // your work; tokens come backconst credits = creditsForUsage(usage, { input: 3, output: 15 }); // price per million tokensconst charge = await ledger.charge(user.id, { amount: credits, key: `run:${runId}` });// charge.fromDaily, charge.fromGrants, charge.fromPaid, charge.shortfallTab agent bridge
import { RelayClient, renderForModel, PAGE_CONTENT_RULE } from "tab-agent-bridge"; const relay = new RelayClient({ baseUrl: process.env.RELAY_URL!, internalToken: process.env.RELAY_INTERNAL_TOKEN! }); // Show this code to the signed-in user; they paste it into the extension popup.const { code } = await relay.createPairCode(user.id); // Later, from your agent's tool handler:const result = await relay.call(user.id, "snapshot");const forModel = await renderForModel("snapshot", result); // page text fenced as untrusted// In your system prompt, once: PAGE_CONTENT_RULEif (!result.ok && result.error === "stopped") { // the person pressed Stop all: stop using the browser and tell them}Shell command formatter
import { htmlStyles, layoutExec, paletteCss, renderHtml } from "shell-command-formatter"; const layout = layoutExec( "printf '%s\\n' '=== tests ==='; npm test 2>&1 | tail -20 || true", "=== tests ===\nPASS tests/notes.test.ts (12 tests)\nFAIL tests/billing.test.ts",); layout.command; // a banner, then one operation per row, each tokenised as shelllayout.output; // a section, then lines whose verdicts are lit ok and badlayout.receipt; // what the command changed, when the host appended a receipt document.head.insertAdjacentHTML("beforeend", `<style>${paletteCss()}${htmlStyles()}</style>`);panel.innerHTML = renderHtml(layout); // or map the same blocks to your own componentsBooking engine
import { canBook, findSlots, footprint, groupByDay } from "booking-engine"; const schedule = { timeZone: "Europe/Lisbon", weekly: [{ days: [1, 2, 3, 4, 5], start: 9 * 60, end: 17 * 60 }] };const intro = { duration: 45, interval: 30, bufferBefore: 15, bufferAfter: 15, notice: 240, caps: { day: 4 } }; // The public page: free slots for the next two weeks, grouped by day in the visitor's own zone.const busy = [...calendarEvents, ...bookings.map((b) => footprint(b.start, intro))];const slots = findSlots({ schedule, event: intro, from: now, to: twoWeeksLater, now, busy, bookings: bookings.map((b) => b.start) });const days = groupByDay(slots, visitorTimeZone); // The booking request: check again inside the transaction that inserts it.const check = await canBook({ schedule, event: intro, start: requested, now, busy, countBookings: countInRange });if (!check.ok) return reply(409, check.reason); // past, too_soon, after_window, busy, not_offered, capped, ...Paged business documents
import { Invoice, PrintStyles, type InvoiceDoc } from "paged-business-documents"; const doc: InvoiceDoc = { number: "INV-2026-0142", currency: "EUR", issued: "1 October 2026", due: "31 October 2026", status: "due", from: { name: "Northwind Studio Ltd", lines: ["12 Example Street", "Sampletown"] }, to: { name: "Blue Fern Coffee", lines: ["48 Placeholder Road", "Demoville"] }, lines: [ { description: "Brand audit", qty: 2, unit: 15517, taxRate: 23 }, // unit in cents { description: "Website build", detail: "Hours", qty: 1.5, unit: 36619, taxRate: 23 }, ], payment: { label: "Pay by bank transfer", lines: ["IBAN XX00 EXAM 0000 0000 0000 00"] },}; export const InvoicePage = () => ( <><PrintStyles size="a4" /><Invoice doc={doc} onPaginated={(pages) => console.log(pages, "sheets")} /></>);Lifecycle email engine
import { DEFAULT_JOURNEY, newUser, step, unsubscribeHeaders, unsubscribeUrl } from "lifecycle-email-engine"; // From product events and from a daily job: { type: "tick", at: now }const state = (await db.lifecycleState(user.id)) ?? newUser({ timeZone: user.timeZone });const result = step(state, { type: "limit_hit", at: new Date() }, DEFAULT_JOURNEY); for (const id of result.send) { const rule = DEFAULT_JOURNEY.rules.find((r) => r.id === id)!; const headers = rule.stream ? unsubscribeHeaders({ url: unsubscribeUrl("https://mail.example/unsubscribe", user.id, rule.stream, keys) }) : {}; await mailer.send({ to: user.email, template: id, headers });}await db.saveLifecycleState(user.id, result.state);// result.verdicts: [{ id: "upgrade-prompt", status: "send", reason: "event" }, ...]Recipe graph
import { compileRecipe, layoutBest, renderSvg } from "recipe-graph"; const recipe = { name: "Lead pipe", trigger: { type: "hook" }, steps: [ { kind: "classify", input: "{{event.body}}", classes: ["hot", "cold"], as: "lead", retry: { times: 2 } }, { kind: "branch", cases: [{ when: "{{lead.class}} == 'hot'", steps: [{ kind: "invoke", tool: "crm_add_lead" }] }] }, { kind: "deliver", via: "email" }, ],}; const graph = compileRecipe(recipe, { tools: { crm: { label: "CRM", icon: "users" } } });const { diagram, faults } = layoutBest(graph, 560); // 560 = your panel width in pixelsif (faults.length) console.warn("not clean:", faults.map((f) => f.message));const svg = renderSvg(diagram, { title: recipe.name });Agent turn checks
import { createCompletionGate, parseIntents, checkIntents, describeMissed, withPathLock, TscWatcher, localShell } from "agent-turn-checks"; // 1. At the end of each turnconst gate = createCompletionGate({ deliverableTools: ["send_email", "save_record"], writeTools: /^(write_file|edit_file|run_command)$/, backgroundTools: ["start_deploy"],});const verdict = gate.assess({ reply, toolStarts, wantsWrites });if (verdict.state === "not_done") injectForOneMoreRound(verdict.nudge); // 2. After a command that ran a scriptconst { missed } = checkIntents(parseIntents(command), [await readFile(path, "utf8")]);if (missed.length) addToToolResult(`These replacements did not happen:\n${describeMissed(missed)}`);Research loop
import { ChatCompletionsModel, createResearcher, YouSearch } from "research-loop"; const researcher = createResearcher({ provider: YouSearch.fromEnv(process.env), model: ChatCompletionsModel.fromEnv(process.env),}); const run = await researcher.research({ question: "Who led Acme's last funding round, and what does it charge?", depth: "standard" });// run.files: MANIFEST.md, answer.md, question.md, plan.json, sources/01.json ...for (const [name, body] of Object.entries(run.files)) await save(`research/${run.slug}/${name}`, body);if (run.failure) console.warn(run.failure); // an outage, a genuine nothing, a partial run: never confusedEmail template kit
import { checkCopy, renderEmail } from "email-template-kit"; const config = { appName: "Acme", appUrl: "https://app.example.com", supportEmail: "help@example.com" }; const email = await renderEmail( "payment-failed", { plan: "Pro", retryOn: "March 6", recipientEmail: "sam@example.com", unsubscribeToken: user.emailToken }, { config },); // email.subject, email.html, email.text, and email.category: "transactional"await mailer.send({ to: "sam@example.com", subject: email.subject, html: email.html, text: email.text }); // in CI: no em dash, no double quote, no slash command, no link to a host you did not allowcheckCopy(email.html, { allowHosts: ["app.example.com"] }); // => []Nudge engine
// A detector reads what you already record. No model, no writes.const unreadReport: Detector<{ sentence: string }> = { kind: "report_unread", ambient: true, // waits for a lull instead of interrupting async detect({ userId, now }) { const r = await reports.latestUnopened(userId, now); // your own query return r ? [{ key: r.id, scope: null, priority: 60, expiresAt: r.finishedAt + 7 * 86_400_000, evidence: { rows: [["Rows", r.rows]], facts: { report: r.id } }, display: { sentence: `Your ${r.name} report finished. ${r.rows} rows, unread.` } }] : []; },}; const engine = createNudgeEngine({ store: new SqliteStore(new DatabaseSync("nudges.db")), detectors: [unreadReport], settings: settingsFromEnv() });await engine.scan(userId, conversationId); // when a turn settlesconst s = await engine.next(userId, conversationId); // at most one: paced, re-checked, fresh numbersif (s) { draw(s.display); await engine.act(userId, s.id, "shown"); } // draw is your UICrawler hits
import { cloudflareAnalytics, envTokenSource, MemoryHitStore, syncSite } from "ai-crawler-hits"; const store = new MemoryHitStore();await store.createSite({ id: "shop", tenantId: "me", zoneId: process.env.CF_ZONE_ID!, tokenRef: "CRAWLER_TOKEN_SHOP", hosts: ["shop.example"] }); // CRAWLER_TOKEN_SHOP holds a Cloudflare API token that may read that zone's analyticsconst result = await syncSite( { tenantId: "me", siteId: "shop", days: 7 }, { store, analytics: cloudflareAnalytics(), tokens: envTokenSource(process.env) },); const week = { from: result.days.at(-1)!.day, to: result.days[0]!.day };for (const page of await store.urlHits("me", "shop", week, ["GPTBot", "ClaudeBot", "PerplexityBot"])) console.log(page.hits, page.url, page.agents);Competitor watcher
import { DatabaseSync } from "node:sqlite";import { createWatcher, D1WatcherStore, settingsFromEnv, sqliteD1 } from "competitor-watcher";import { nodeWeb } from "competitor-watcher/node"; const settings = settingsFromEnv(process.env);const watcher = createWatcher({ store: new D1WatcherStore(sqliteD1(new DatabaseSync("watch.db"))), // tables: sql/schema.sql web: nodeWeb({ userAgent: settings.userAgent }), settings, adminToken: process.env.WATCHER_ADMIN_TOKEN,}); await watcher.fetch(request); // the API: Request in, Response outawait watcher.scheduled(); // on every cron tick: starts a run for each account that is dueAgent inspector
// Runs come from the agent-loop-sse store, plus an index of who ran what// (record a row when a run starts: index.record({ userId, conversationId, runId, startedAt })).const inspector = createInspector({ source: agentLoopSource({ store: turnStore, index: runIndex }), store: new SqliteInspectorStore(db), model: router, // a model-router ModelRouter, or anything with run() modelId: modelFromEnv(), // INSPECTOR_MODEL; there is no default model settings: settingsFromEnv(), // INSPECTOR_* overrides}); await inspector.setConsent(userId, { enabled: true }); // from the user's own settingsconst { swept, more } = await inspector.sweep(); // nightly; call again while more is trueconst { block } = await inspector.rulesForTurn(userId, { shell: true }); // into the system prompt const handle = createInspectorHandler({ inspector, secret: process.env.INSPECTOR_SECRET, authenticate: yourSessionUser });Anthropic messages adapter
import { createServer } from "node:http";import { createMessagesHandler, openAICompatibleBackend, toNodeListener } from "anthropic-messages-adapter"; const handler = createMessagesHandler({ backend: openAICompatibleBackend({ baseUrl: process.env.LLM_BASE_URL!, apiKey: process.env.LLM_API_KEY }), keys: [process.env.ADAPTER_KEY!, process.env.ADAPTER_KEY_NEXT ?? ""], // two keys, so either can rotate alone defaultModel: process.env.LLM_MODEL!, // every model name a client sends runs here... models: { "claude-small": "my-small-model" }, // ...unless it is mapped}); createServer(toNodeListener(handler)).listen(Number(process.env.PORT ?? 0));// Point the client's Anthropic base URL at this server and give it ADAPTER_KEY as its API key.Public status rates
const config: StatusConfig = { grantTo: ["status_reader"], // the only role allowed to call it sources: [ { key: "chat", table: "runs", time: "started_at", ok: ["completed"], bad: ["failed"], latency: { start: "started_at", end: "completed_at" } }, { key: "email", table: "email_sends", time: "created_at", ok: ["sent", "delivered"], bad: ["failed", "bounced"], stuck: { statuses: ["pending"], afterMinutes: 60 } }, ], infra: [ { key: "backups", kind: "freshness", table: "backup_log", column: "finished_at", operationalHours: 26, degradedHours: 48 }, { key: "database", kind: "constant", state: "operational" }, ],}; await adminPool.query(generateStatusSql(config)); // once, as a migrationconst handler = createStatusHandler({ config, read: statusReader(readerPool, config), probes: probesFromEnv(), settings: boardSettingsFromEnv() });// GET / is the JSON board, GET /page is the HTML pageAgent verb gateway
import { createGateway, defineVerb, MemoryStore, settingsFromEnv } from "agent-verb-gateway"; const refund = defineVerb<{ orderId: string; amount: number }>({ name: "refunds.issue", summary: "Refund part or all of an order.", args: { type: "object", required: ["orderId", "amount"], properties: { orderId: { type: "string" }, amount: { type: "number", minimum: 0.01 } } }, credits: 1, gate: (args) => (args.amount > 100 ? "refunds over 100 need a person" : false), run: async (ctx, args) => payments.refund(args.orderId, args.amount, { signal: ctx.signal }), // your client, your key}); const gateway = createGateway({ verbs: [refund], store: new MemoryStore(), settings: settingsFromEnv(process.env) });export default { fetch: gateway.fetch }; // POST /v1/call { verb, args } with Idempotency-Key and the session tokenPublic data worker
import { createWorker, kvCache, optionsFromEnv } from "public-data-worker"; export default { fetch(req: Request, env: Env) { // PUBLIC_DATA_TOKEN, PUBLIC_DATA_CONTACT, PUBLIC_DATA_SEC_USER_AGENT and the rest const worker = createWorker({ ...optionsFromEnv(env), cache: kvCache(env.CACHE) }); return worker(req); },}; // GET /jobs/greenhouse/<board> who is hiring, in one Job shape// GET /hn/top?limit=20 the Hacker News front page// GET /sec/search?q=robotics&forms=D US fundraising notices// GET /tech?url=example.com what a site is built withFont matcher
import { readFile } from "node:fs/promises";import { createFontMatcher, fetchGoogleFonts } from "font-matcher"; const manifest = await fetchGoogleFonts(); // 30 families, cached after the first runconst matcher = await createFontMatcher({ manifest }); const crop = await readFile("headline.png"); // PNG, JPEG or WebP, one line of textconst ranked = await matcher.match(crop, "Ship faster with fewer meetings", { top: 3 });// [{ family: "Space Grotesk", weight: 700, score: 0.923, shape: 0.885, aspect: 0.968 }, ...] // Narrow one call to a shortlist, with colours you already knowconst shortlist = await matcher.match(crop, "Ship faster with fewer meetings", { families: ["Space Grotesk", "Inter", "Outfit"], bg: "#1b2433", ink: "#f4f1ea",}); await matcher.close();Webhook event hub
import { analyticsEngineSink, createHub, settingsFromEnv, sqliteSink } from "webhook-event-hub"; export default { fetch(req: Request, env: Env) { // HUB_STRIPE_SECRET, HUB_GITHUB_SECRET, HUB_CUSTOM_SECRET, ... : a source with no secret is a 404 const hub = createHub({ ...settingsFromEnv(env), // SQLite first: it recognises a retried delivery, and the hub keeps the repeat out of Analytics Engine sinks: [sqliteSink(env.HUB_DB), analyticsEngineSink(env.EVENTS)], }); return hub(req); },};// SELECT blob1 AS source, SUM(_sample_interval) AS events FROM hub_events GROUP BY blob1Einvoice compiler
import { compileInvoice } from "einvoice-compiler";import { loadGobl } from "einvoice-compiler/node"; const engine = await loadGobl(); // GOBL, after npm run fetch-goblconst result = await compileInvoice({ code: "KDS-2026-0142", issueDate: "2026-10-01", currency: "EUR", supplier: { name: "Kanaal Studio", vatId: { country: "NL", code: "123456782B01" }, address: { country: "NL" } }, customer: { name: "Molen & Zonen", vatId: { country: "NL", code: "123456782B02" }, address: { country: "NL" } }, lines: [{ description: "Design hours", quantity: "12.5", unitPrice: "95.00", vat: { category: "S", percent: "21" } }],}, { engine }); if (result.ok) console.log(result.totals.payable, result.files.map((f) => f.name)); // gobl.json, invoice.xmlelse console.log(result.stage, result.problems); // every problem at once, with its EN 16931 rule- 3 min
- 3 min
- 17 min
- 9 min
- 5 min
- 8 min