Core

Core in real use

Four end-to-end programs built on core's primitives, each in TypeScript and Python, each run and checked in CI with no API keys.

Every program on this page lives in examples/ and runs in CI with no API keys. The TypeScript and Python twins must print identical output, so what you read here is what both languages do.

Tamper-evident receipts

An approval gate writes one receipt per decision. Each receipt is canonical JSON (integers only, so money is micro-USD) and chains the digest of the previous one, so editing any receipt breaks every digest after it. Tool arguments are user data with floats and any keys, so they are hashed with RFC 8785 JCS instead. Ids are ULIDs: they sort by time and stay unique.

main.ts
interface Receipt {
  id: string;
  at: string;
  tool: string;
  args_digest: string; // RFC 8785 JCS digest: tool args are user data (floats, any keys)
  decision: "approved" | "denied";
  amount_micro_usd: number; // receipts are canonical JSON: integers only, so money is micro-USD
  prev: string | null;
  digest: string;
}

const clock = new FakeClock("2026-11-25T10:00:00Z");
// Deterministic for the example. In production use `new UlidIds()`: time plus 80 random bits.
const ids = new UlidIds({ clock, random: (bytes) => bytes.fill(7) });

function append(chain: Receipt[], tool: string, args: { amount: number }, decision: Receipt["decision"]): Receipt[] {
  const prev = chain.at(-1)?.digest ?? null;
  const body = {
    id: ids.next("rcpt"),
    at: isoTimestamp(clock.now()),
    tool,
    args_digest: jcsDigest(args),
    decision,
    amount_micro_usd: Math.round(args.amount * 1_000_000),
    prev,
  };
  return [...chain, { ...body, digest: canonicalDigest(body, prev) }];
}
main.py
clock = FakeClock("2026-11-25T10:00:00Z")
# Deterministic for the example. In production use `UlidIds()`: time plus 80 random bits.
ids = UlidIds(clock=clock, random=lambda n: bytes([7] * n))


def append(chain: list[dict[str, Any]], tool: str, args: dict[str, Any], decision: str) -> list[dict[str, Any]]:
    prev = chain[-1]["digest"] if chain else None
    body = {
        "id": ids.next("rcpt"),
        "at": iso_timestamp(clock.now()),
        "tool": tool,
        "args_digest": jcs_digest(args),  # RFC 8785 JCS digest: tool args are user data (floats, any keys)
        "decision": decision,
        "amount_micro_usd": round(args["amount"] * 1_000_000),  # canonical JSON is integers only
        "prev": prev,
    }
    return [*chain, {**body, "digest": canonical_digest(body, prev)}]

Verifying the chain recomputes every digest and link:

main.ts
/** The index of the first receipt whose digest or link does not check out, or -1 when the chain is intact. */
function firstBroken(chain: Receipt[]): number {
  return chain.findIndex(({ digest, ...body }, i) => {
    const prev = i === 0 ? null : (chain[i - 1] as Receipt).digest;
    return body.prev !== prev || canonicalDigest(body, prev) !== digest;
  });
}
main.py
def first_broken(chain: list[dict[str, Any]]) -> int:
    """The index of the first receipt whose digest or link does not check out, or -1 when the chain is intact."""
    for i, receipt in enumerate(chain):
        body = {k: v for k, v in receipt.items() if k != "digest"}
        prev = chain[i - 1]["digest"] if i > 0 else None
        if body["prev"] != prev or canonical_digest(body, prev) != receipt["digest"]:
            return i
    return -1

main.ts
let chain: Receipt[] = [];
chain = append(chain, "issue_refund", { amount: 42.5 }, "approved");
clock.advance(1_500);
chain = append(chain, "issue_refund", { amount: 980 }, "denied");
clock.advance(250);
chain = append(chain, "issue_refund", { amount: 12.25 }, "approved");

for (const r of chain) console.log(`${r.id} ${r.at} ${r.decision} ${r.digest.slice(0, 23)}`);
console.log(`intact: ${firstBroken(chain) === -1}`);

// Someone edits the denied refund to look approved. The edit breaks its digest.
const forged = chain.map((r, i) => (i === 1 ? { ...r, decision: "approved" as const } : r));
console.log(`forged chain breaks at receipt ${firstBroken(forged)}`);
main.py
chain: list[dict[str, Any]] = []
chain = append(chain, "issue_refund", {"amount": 42.5}, "approved")
clock.advance(1_500)
chain = append(chain, "issue_refund", {"amount": 980}, "denied")
clock.advance(250)
chain = append(chain, "issue_refund", {"amount": 12.25}, "approved")

for r in chain:
    print(f"{r['id']} {r['at']} {r['decision']} {r['digest'][:23]}")
print(f"intact: {str(first_broken(chain) == -1).lower()}")

# Someone edits the denied refund to look approved. The edit breaks its digest.
forged = [{**r, "decision": "approved"} if i == 1 else r for i, r in enumerate(chain)]
print(f"forged chain breaks at receipt {first_broken(forged)}")

A trajectory recorded from an agent run

A plain tool-use loop: each turn emits a model_call event and runs the tool the model asked for. The model is scripted so the program needs no key; a real loop (or an adapter) emits the same events. trace() collects all of it into one trajectory, with a fake clock and readable ids so the output is stable.

main.ts
type Step = { tool: string; args: Record<string, unknown> } | { text: string };
const script: Step[] = [
  { tool: "lookup_order", args: { order_id: "A-1001" } },
  { tool: "issue_refund", args: { order_id: "A-1001", amount: 42.5 } },
  { text: "Refunded $42.50 for order A-1001." },
];
const tools: Record<string, Tool> = { lookup_order: lookupOrder, issue_refund: issueRefund };

/** A plain tool-use loop. Each turn: one model call (emitted), then the tool it asked for. */
async function runAgent(clock: FakeClock): Promise<string> {
  return span({ type: "agent", name: "support" }, async (agent) => {
    for (const [turn, step] of script.entries()) {
      clock.advance(400);
      emit({ type: "model_call", model: "fake-model", turn, usage: { input_tokens: 900, output_tokens: 60 }, latency_ms: 400 });
      if ("text" in step) {
        agent.set({ output: step.text });
        return step.text;
      }
      clock.advance(50);
      await (tools[step.tool] as Tool).execute(step.args, { callId: `call_${turn}` });
    }
    throw new Error("the script ended without an answer");
  });
}
main.py
SCRIPT: list[dict[str, Any]] = [
    {"tool": "lookup_order", "args": {"order_id": "A-1001"}},
    {"tool": "issue_refund", "args": {"order_id": "A-1001", "amount": 42.5}},
    {"text": "Refunded $42.50 for order A-1001."},
]
TOOLS: dict[str, Tool[Any]] = {"lookup_order": lookup_order, "issue_refund": issue_refund}


async def run_agent(clock: FakeClock) -> str:
    """A plain tool-use loop. Each turn: one model call (emitted), then the tool it asked for."""
    async with span(AgentEvent(name="support")) as agent:
        for turn, step in enumerate(SCRIPT):
            clock.advance(400)
            usage = Usage(input_tokens=900, output_tokens=60)
            emit(ModelCallEvent(model="fake-model", turn=turn, usage=usage, latency_ms=400))
            if "text" in step:
                agent.set(output=step["text"])
                return str(step["text"])
            clock.advance(50)
            await TOOLS[step["tool"]].execute(step["args"], ToolContext(call_id=f"call_{turn}"))
    raise RuntimeError("the script ended without an answer")

Record the run, then assert on what happened: which tools ran in what order, whether the refund stayed within policy, and whether the run fit its token and latency budget.

main.ts
console.log(result);
console.log(
  toolCalls(trajectory)
    .map((c) => c.tool_name)
    .join(" -> "),
);

const refund = match({ args: { order_id: "A-1001", amount: { lte: 100 } } }, toolCalls(trajectory, "issue_refund")[0]);
console.log(`refund within policy: ${refund.status}`);

const summary = summarize(trajectory);
console.log(stableJson(summary));
for (const check of checkBudget({ tokens: 5_000, latency_ms: 1_000 }, summary)) console.log(`${check.key}: ${check.message}`);
main.py
print(t.output)
print(" -> ".join(c.tool_name for c in trajectory.tool_calls()))

refund = match({"args": {"order_id": "A-1001", "amount": {"lte": 100}}}, trajectory.tool_calls("issue_refund")[0])
print(f"refund within policy: {refund.status}")

summary = summarize(trajectory)
print(stable_json(summary.to_dict()))
for check in check_budget({"tokens": 5_000, "latency_ms": 1_000}, summary):
    print(f"{check.key}: {check.message}")

Testing a payment gate with fakes

The code under test is a middleware that refuses charges over 100. A scripted fake tool stands in for the payment provider (one success, then a decline), and its calls log proves the gate stopped the large charge before the provider saw it.

main.ts
// The code under test: a gate that refuses charges over 100 before they reach the provider.
const overLimit = toolMiddleware(async (call, next) => {
  const { amount } = call.args as { amount: number };
  if (amount > 100) throw new ViewportError("example.over_limit", `amount ${amount} is over the limit of 100`);
  return next();
});
const guarded = wrapTool(chargeCard, overLimit);
main.py
# The code under test: a gate that refuses charges over 100 before they reach the provider.
@tool_middleware
async def over_limit(call: ToolCall, next: ToolNext) -> object:
    amount = call.args["amount"]
    if amount > 100:
        raise ViewportError("example.over_limit", f"amount {amount} is over the limit of 100")
    return await next()


guarded = wrap_tool(charge_card, over_limit)
main.ts
const { trajectory: recorded } = await trace(
  async () => {
    for (const amount of [20, 500, 30]) await guarded.execute({ amount }).catch(() => {});
  },
  { clock: new FakeClock(), ids: new SequentialIds() },
);

for (const c of toolCalls(recorded)) console.log(`${c.id} amount=${(c.args as { amount: number }).amount} ${c.error?.type ?? "ok"}`);
console.log(`provider saw ${chargeCard.calls.length} calls`); // the gate stopped the 500 before the provider
main.py
async with trace(clock=FakeClock(), ids=SequentialIds()) as t:
    for amount in (20, 500, 30):
        with contextlib.suppress(ViewportError):
            await guarded.execute({"amount": amount})
recorded = t.trajectory

for c in recorded.tool_calls():
    print(f"{c.id} amount={c.args['amount']} {c.error.type if c.error else 'ok'}")
print(f"provider saw {len(charge_card.calls)} calls")  # the gate stopped the 500 before the provider

A policy check is only as good as its test, so the example also builds a trajectory by hand where a bad charge got through, and proves the check catches it:

main.ts
/** The policy check under test: no charge over 100 ever succeeded. */
const neverOverLimit = (t: Trajectory) =>
  toolCalls(t, "charge_card").every((c) => c.error !== undefined || match({ args: { amount: { lte: 100 } } }, c).passed);

// A hand-built trajectory where a bad charge got through, to prove the check catches it.
const leaked = trajectory()
  .tool("charge_card", { args: { amount: 20 }, result: { charge_id: "ch_1" } })
  .tool("charge_card", { args: { amount: 500 }, result: { charge_id: "ch_2" } })
  .build();

console.log(`recorded run passes: ${neverOverLimit(recorded)}`);
console.log(`leaked fixture caught: ${!neverOverLimit(leaked)}`);
main.py
def never_over_limit(t: Trajectory) -> bool:
    """The policy check under test: no charge over 100 ever succeeded."""
    return all(
        c.error is not None or match({"args": {"amount": {"lte": 100}}}, c).passed for c in t.tool_calls("charge_card")
    )


# A hand-built trajectory where a bad charge got through, to prove the check catches it.
leaked = (
    trajectory()
    .tool("charge_card", args={"amount": 20}, result={"charge_id": "ch_1"})
    .tool("charge_card", args={"amount": 500}, result={"charge_id": "ch_2"})
    .build()
)

An approval that expires

Every wait in Viewport goes through clock.sleep. In production that is a real timer; in a test, FakeClock runs fifteen minutes of waiting in microseconds. The losing timer is cancelled (an AbortSignal in TypeScript, task cancellation in Python), so nothing outlives the wait.

main.ts
/** The decision, or "expired" when `timeoutMs` of the clock's time passes first. The losing timer is cancelled. */
async function awaitApproval(decision: Promise<string>, clock: Clock, timeoutMs: number): Promise<string> {
  const cancel = new AbortController();
  const expiry = clock.sleep(timeoutMs, cancel.signal).then(
    () => "expired",
    () => "cancelled",
  );
  try {
    return await Promise.race([decision, expiry]);
  } finally {
    cancel.abort(); // no timer outlives the wait
  }
}
main.py
async def await_approval(decision: Awaitable[str], clock: Clock, timeout_ms: float) -> str:
    """The decision, or "expired" when ``timeout_ms`` of the clock's time passes first. The loser is cancelled."""
    answer = asyncio.ensure_future(decision)
    expiry = asyncio.ensure_future(clock.sleep(timeout_ms))
    done, pending = await asyncio.wait({answer, expiry}, return_when=asyncio.FIRST_COMPLETED)
    for task in pending:
        task.cancel()  # no timer outlives the wait
    await asyncio.gather(*pending, return_exceptions=True)
    return answer.result() if answer in done else "expired"

The test drives time. FakeClock.pending counts armed timers, so the test can wait until the code under test is actually sleeping before it moves the clock:

main.ts
/** Let pending work arm its timers before the test moves time (FakeClock.pending counts them). */
async function armed(clock: FakeClock, n: number): Promise<void> {
  while (clock.pending < n) await Promise.resolve();
}

// A reviewer who answers after 5 minutes.
let clock = new FakeClock();
let start = clock.now();
let answer = awaitApproval(
  clock.sleep(5 * MIN).then(() => "approved"),
  clock,
  15 * MIN,
);
await armed(clock, 2);
clock.advance(5 * MIN);
console.log(`${await answer} after ${(clock.now() - start) / MIN} min, timers left: ${clock.pending}`);

// A reviewer who never answers.
clock = new FakeClock();
start = clock.now();
answer = awaitApproval(new Promise<string>(() => {}), clock, 15 * MIN);
await armed(clock, 1);
clock.advance(14 * MIN);
await Promise.resolve();
console.log(`still waiting after ${(clock.now() - start) / MIN} min: ${clock.pending === 1}`);
clock.advance(1 * MIN);
console.log(`${await answer} after ${(clock.now() - start) / MIN} min`);
main.py
async def armed(clock: FakeClock, n: int) -> None:
    """Let pending work arm its timers before the test moves time (FakeClock.pending counts them)."""
    while clock.pending < n:  # noqa: ASYNC110 - yields so other tasks run and arm their sleeps; no event to await
        await asyncio.sleep(0)


async def reviewer(clock: FakeClock, after_ms: float) -> str:
    await clock.sleep(after_ms)
    return "approved"


async def drive() -> None:
    # A reviewer who answers after 5 minutes.
    clock = FakeClock()
    start = clock.now()
    answer = asyncio.ensure_future(await_approval(reviewer(clock, 5 * MIN), clock, 15 * MIN))
    await armed(clock, 2)
    clock.advance(5 * MIN)
    result = await answer
    print(f"{result} after {(clock.now() - start) / MIN:g} min, timers left: {clock.pending}")

    # A reviewer who never answers.
    clock = FakeClock()
    start = clock.now()
    never: asyncio.Future[str] = asyncio.get_running_loop().create_future()
    answer = asyncio.ensure_future(await_approval(never, clock, 15 * MIN))
    await armed(clock, 1)
    clock.advance(14 * MIN)
    await asyncio.sleep(0)
    print(f"still waiting after {(clock.now() - start) / MIN:g} min: {str(clock.pending == 1).lower()}")
    clock.advance(1 * MIN)
    print(f"{await answer} after {(clock.now() - start) / MIN:g} min")

On this page