Merge iterate/private's core/ at 20e3895e
Misha Kaletsky, 2026-11-26 08:39 UTC · 093466a56acbac226330d13a2b7e36d3ac84e8a2 · a merge of d680721 and 816a6f4, shown against d680721
11 files changed
- M core/itx/src/caller.ts
- M core/itx/src/context/awake.ts
- A core/itx/src/context/context-activity-stack.test.ts
- A core/itx/src/context/context-activity-stack.ts
- M core/itx/src/context/context-catalog.ts
- M core/itx/src/context/facet-host.ts
- M core/itx/src/context/itx-expression-rewriting.ts
- M core/itx/src/context/stateless-context.ts
- M core/itx/src/iterate-context-durable-object.ts
- M core/itx/src/stream/core-events.ts
- M core/lib/src/api.ts
M core/itx/src/caller.ts
@@ -58,6 +58,10 @@ // mind Worker's MCP server and by serve-host.ts, where the platform itself names the client and // the person: no other caller reaches `mcpCall` (./context/built-ins.ts `workersRoot`). mcpServer?: true; + // An internal hop made through `libraryItx` (`repos`, `sandboxes`, `files`) on behalf of an + // outer expression: activity tracking records the outer call alone so internal hops do not stack + // duplicate pills underneath it. + libraryHop?: true; copiedFrom?: EventCopiedFrom; cause?: Cause; onBehalfOf?: OnBehalfOf;
M core/itx/src/context/awake.ts
@@ -21,6 +21,8 @@ // The accepting context is not `/`: every wake of `/` restarts the root's facets, and the root // would wake twice for each wake of any other context. +import type { ContextActivity } from "iterate/api"; + export const AWAKE_CONTEXT_PATH = "/awake"; export const AWAKE_WEBSOCKET_HEADER = "x-itx-awake"; const AWAKE_WEBSOCKET_TAG = "awake"; @@ -33,11 +35,23 @@ export const AWAKE_MAX_HOLD_MS = 5 * 60_000; /** While a context works, its summary is sent again at most this often. */ export const AWAKE_SUMMARY_EVERY_MS = 15_000; +/** Coalesces rapid activity push/pop bursts before sending an updated summary down the socket. */ +export const AWAKE_ACTIVITY_DEBOUNCE_MS = 100; /** After a dial that failed, no other dial for this long. */ export const AWAKE_REDIAL_AFTER_MS = 10_000; -export type AwakeContext = { path: string; since: number }; +export type AwakeContext = { + path: string; + since: number; + updatedAt?: number; + activities?: ContextActivity[]; +}; +export type AwakeContextState = { + since: number; + activities?: ContextActivity[]; +}; + /** The accepting side. Null: not a dial. Only the context at `AWAKE_CONTEXT_PATH` accepts. */ export function acceptAwakeWebSocket( ctx: Pick<DurableObjectState, "acceptWebSocket">, @@ -76,20 +90,60 @@ /** What `acceptAwakeWebSocket` attached to a socket under the awake tag. */ export function awakeContextOf(ws: WebSocket): AwakeContext { - // the one reader of the attachment that `acceptAwakeWebSocket` alone writes + // the one reader of the attachment that `acceptAwakeWebSocket` and `setAwakeActivities` alone write return ws.deserializeAttachment() as AwakeContext; } -/** Every context with an open socket here, by path, with when it woke. A context that dialed twice - * (its first socket's close has not arrived) is there once, with its earlier time. */ -export function awakeContexts(ctx: Pick<DurableObjectState, "getWebSockets">): Map<string, number> { - const sinceByPath = new Map<string, number>(); +/** Updates the live `activities` carried on an accepted awake socket's attachment (never SQLite), + * so closing or crashing the socket clears its activities automatically. */ +export function setAwakeActivities( + ws: Pick<WebSocket, "deserializeAttachment" | "serializeAttachment">, + activities: ContextActivity[] | undefined, +): void { + // Written by `acceptAwakeWebSocket` on the same tagged socket. + const current = ws.deserializeAttachment() as AwakeContext; + const next: AwakeContext = { + path: current.path, + since: current.since, + updatedAt: Date.now(), + ...(activities && activities.length > 0 && { activities }), + }; + ws.serializeAttachment(next); +} + +/** Every context with an open socket here, by path, with when it woke and its latest live + * activities. A context that dialed twice (its first socket's close has not arrived) is there + * once, with its earlier wake time and the newest socket state. */ +export function awakeContexts( + ctx: Pick<DurableObjectState, "getWebSockets">, +): Map<string, AwakeContextState> { + const byPath = new Map<string, AwakeContextState & { updatedAt: number }>(); for (const ws of ctx.getWebSockets(AWAKE_WEBSOCKET_TAG)) { if (ws.readyState !== WebSocket.OPEN) continue; - const { path, since } = awakeContextOf(ws); - sinceByPath.set(path, Math.min(since, sinceByPath.get(path) ?? Infinity)); + const { path, since, updatedAt, activities } = awakeContextOf(ws); + const rank = updatedAt ?? since; + const prior = byPath.get(path); + if (!prior) { + byPath.set(path, { + since, + updatedAt: rank, + ...(activities && activities.length > 0 && { activities }), + }); + continue; + } + const newer = rank >= prior.updatedAt; + const chosenActivities = newer ? activities : prior.activities; + byPath.set(path, { + since: Math.min(since, prior.since), + updatedAt: Math.max(rank, prior.updatedAt), + ...(chosenActivities && chosenActivities.length > 0 && { activities: chosenActivities }), + }); } - return sinceByPath; + const states = new Map<string, AwakeContextState>(); + for (const [path, { since, activities }] of byPath) { + states.set(path, activities ? { since, activities } : { since }); + } + return states; } /** What the dialing side does when its timer fires. */ @@ -130,6 +184,8 @@ #noDialBefore = 0; #lastEntryAt = 0; #timer: ReturnType<typeof setTimeout> | undefined; + #activityTimer: ReturnType<typeof setTimeout> | undefined; + #activityDirty = false; #sentSummary: string | undefined; #sentSummaryAt = 0; @@ -144,6 +200,22 @@ if (this.#timer === undefined) this.#recheckIn(AWAKE_QUIET_MS); } + /** Coalesces rapid activity stack mutations and pushes the updated summary while the context + * is awake, without holding an idle context open or leaving a timer after close. */ + activityChanged(): void { + if (this.#deps.path === AWAKE_CONTEXT_PATH || this.#timer === undefined) return; + this.#activityDirty = true; + if (this.#activityTimer !== undefined) return; + this.#activityTimer = setTimeout(() => { + this.#activityTimer = undefined; + if (this.#timer === undefined) return; + if (this.#socket) { + this.#activityDirty = false; + this.#sendSummary(); + } + }, AWAKE_ACTIVITY_DEBOUNCE_MS); + } + #recheckIn(ms: number): void { this.#timer = setTimeout(() => { this.#timer = undefined; @@ -155,7 +227,10 @@ if (decision.action === "close") return this.#close(); // again, when the far end closed it under a context that still works this.#open(); - if (Date.now() - this.#sentSummaryAt >= AWAKE_SUMMARY_EVERY_MS) this.#sendSummary(); + if (this.#activityDirty || Date.now() - this.#sentSummaryAt >= AWAKE_SUMMARY_EVERY_MS) { + this.#activityDirty = false; + this.#sendSummary(); + } this.#recheckIn(decision.recheckInMs); }, ms); } @@ -174,6 +249,10 @@ this.#socket = socket; // the context went quiet while the dial was on its way: its summary still goes if (this.#timer === undefined) return this.#close(); + if (this.#activityDirty && this.#activityTimer === undefined) { + this.#activityDirty = false; + this.#sendSummary(); + } const gone = () => { if (this.#socket === socket) this.#socket = undefined; }; @@ -212,6 +291,11 @@ } #close(): void { + if (this.#activityTimer !== undefined) { + clearTimeout(this.#activityTimer); + this.#activityTimer = undefined; + } + this.#activityDirty = false; this.#sendSummary(); const socket = this.#socket; this.#socket = undefined;
A core/itx/src/context/context-activity-stack.test.ts
@@ -0,0 +1,547 @@ +import { DatabaseSync } from "node:sqlite"; +import { parse } from "iterate/expression"; +import { applyPatch } from "iterate/lib"; +import type { StreamEvent } from "iterate/stream/processor"; +import { RUN_DEADLINE_MS } from "iterate/stream/run"; +import { expect, test, vi } from "vitest"; +import type { Caller } from "../caller.ts"; +import { defineItxHost } from "../host.ts"; +import { + AWAKE_ACTIVITY_DEBOUNCE_MS, + AWAKE_QUIET_MS, + AwakeSocket, + awakeContexts, + setAwakeActivities, +} from "./awake.ts"; +import { buildPortableBuiltIns } from "./built-ins.ts"; +import { + CONTEXT_ACTIVITIES_FACET, + CONTEXT_ACTIVITY_POPPED_TYPE, + CONTEXT_ACTIVITY_PUSHED_TYPE, + CONTEXT_ACTIVITY_STACK_LIMIT, + ContextActivityTracker, + describeFetchActivity, + describeItxCallActivity, + describeScriptRunActivity, + withTrackedActivity, +} from "./context-activity-stack.ts"; +import { ContextCatalog, type ContextSummaryMessage } from "./context-catalog.ts"; +import { ItxExpressionResolver } from "./itx-expression-rewriting.ts"; + +defineItxHost({ firstPartyFacets: {} }); + +test("ContextActivityTracker folds pushes, pops, TTL expiry, LiveState deltas, run-settled sweeps, and LLM lifecycle", () => { + const deltas: { key: string; from: number; to: number; patch: unknown }[] = []; + let changed = 0; + const tracker = new ContextActivityTracker({ + sink: { + append: (event) => { + if (event.type === "events.iterate.com/itx/live-state-changed" && event.payload) { + deltas.push(event.payload as { key: string; from: number; to: number; patch: unknown }); + } + }, + }, + onChanged: () => { + changed += 1; + }, + }); + + const seed0 = tracker.liveSnapshot(Date.parse("2026-11-25T12:00:00.000Z")); + expect(seed0).toMatchObject({ state: [] }); + + // Push run-scoped user items + an unbounded item + tracker.committed( + [ + streamEvent( + 1, + CONTEXT_ACTIVITY_PUSHED_TYPE, + "2026-11-25T12:00:00.000Z", + { + items: [ + { + key: "gh", + text: "Reading PR diff", + url: "https://github.com/iterate/private/pull/42", + tags: ["web", "github"], + ttlMs: 30_000, + }, + { + key: "docs", + text: "Checking DO hibernation docs", + icon: "☁️", + tags: ["docs"], + ttlMs: 5_000, + }, + ], + }, + { onBehalfOf: { principal: { actor: "usr_a" }, run: "/agents/a@10" } }, + ), + ], + "/agents/a", + Date.parse("2026-11-25T12:00:01.000Z"), + ); + + expect(tracker.active(Date.parse("2026-11-25T12:00:01.000Z")).map((item) => item.key)).toEqual([ + "docs", + "gh", + ]); + expect(changed).toBe(1); + + // Lazy TTL expiry at t+6s drops `docs` and updates LiveState + expect(tracker.active(Date.parse("2026-11-25T12:00:06.000Z")).map((item) => item.key)).toEqual([ + "gh", + ]); + expect(changed).toBe(2); + + // LLM requested -> Thinking item pushed; LLM settled -> popped + tracker.committed( + [ + streamEvent(11, "events.iterate.com/llm-request/requested", "2026-11-25T12:00:07.000Z", { + model: "anthropic/claude-sonnet-4-6", + purpose: "answer", + }), + ], + "/agents/a", + Date.parse("2026-11-25T12:00:07.000Z"), + ); + expect( + tracker.active(Date.parse("2026-11-25T12:00:07.000Z")).map((item) => [item.key, item.text]), + ).toEqual([ + ["llm:11", "Thinking · claude-sonnet-4-6"], + ["gh", "Reading PR diff"], + ]); + + tracker.committed( + [ + streamEvent(12, "events.iterate.com/llm-request/settled", "2026-11-25T12:00:09.000Z", { + llmRequestOffset: 11, + }), + ], + "/agents/a", + Date.parse("2026-11-25T12:00:09.000Z"), + ); + expect(tracker.active(Date.parse("2026-11-25T12:00:09.000Z")).map((item) => item.key)).toEqual([ + "gh", + ]); + + // `itx/run-settled` for run 10 sweeps `gh` immediately even before its 30s TTL expires + tracker.committed( + [ + streamEvent(13, "events.iterate.com/itx/run-settled", "2026-11-25T12:00:10.000Z", { + requestOffset: 10, + }), + ], + "/agents/a", + Date.parse("2026-11-25T12:00:10.000Z"), + ); + expect(tracker.active(Date.parse("2026-11-25T12:00:10.000Z"))).toEqual([]); + + // Stack enforces CONTEXT_ACTIVITY_STACK_LIMIT + for (let i = 0; i < CONTEXT_ACTIVITY_STACK_LIMIT + 5; i++) { + tracker.push({ key: `k-${String(i)}`, text: `Item ${String(i)}`, tags: ["batch"] }); + } + expect(tracker.active()).toHaveLength(CONTEXT_ACTIVITY_STACK_LIMIT); + expect(tracker.active()[0]?.key).toBe(`k-${String(CONTEXT_ACTIVITY_STACK_LIMIT + 4)}`); + + // Pop by tag via CONTEXT_ACTIVITY_POPPED_TYPE + tracker.committed( + [ + streamEvent(14, CONTEXT_ACTIVITY_POPPED_TYPE, "2026-11-25T12:00:11.000Z", { + tag: "batch", + }), + ], + "/agents/a", + Date.parse("2026-11-25T12:00:11.000Z"), + ); + expect(tracker.active()).toEqual([]); + + // Clear empties everything + tracker.push({ key: "temp", text: "Temporary" }); + tracker.clear(); + expect(tracker.active()).toEqual([]); + + // Wait for LiveState's async delta chain to flush and verify RFC-6902 patches reconstruct `[]` + return Promise.resolve().then(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(deltas.length).toBeGreaterThan(0); + expect(deltas.every((delta) => delta.key === CONTEXT_ACTIVITIES_FACET)).toBe(true); + let clientState: unknown = seed0.state; + let rev = seed0.rev; + for (const delta of deltas) { + expect(delta).toMatchObject({ from: rev }); + clientState = applyPatch(clientState, delta.patch as Parameters<typeof applyPatch>[1]); + rev = delta.to; + } + expect(clientState).toEqual([]); + }); +}); + +test("ContextCatalog never persists activities to SQLite and clears them the instant an AwakeSocket closes", () => { + const { sql, rawRows } = memorySqlStorage(); + const catalog = new ContextCatalog(sql); + const sockets = fakeAwakeSocketHost(); + + const ws = sockets.open("/agents/builder", 1_000); + const summaryMsg: ContextSummaryMessage = { + throughOffset: 8, + eventCount: 8, + createdAt: "2026-11-25T12:00:00.000Z", + lastEventAt: "2026-11-25T12:00:05.000Z", + lastActivityAt: "2026-11-25T12:00:05.000Z", + eventTypes: { "events.iterate.com/agent/context-added": 8 }, + recentTypes: ["events.iterate.com/agent/context-added"], + processors: ["agent"], + storageBytes: 4_096, + description: "Builds pull requests", + activities: [ + { + key: "mcp:linear", + text: "Querying Linear issues", + icon: "mcp", + tags: ["mcp", "linear"], + pushedAt: "2026-11-25T12:00:05.000Z", + expiresAt: "2026-11-25T12:00:35.000Z", + }, + ], + }; + + const extracted = catalog.store("/agents/builder", JSON.stringify(summaryMsg)); + setAwakeActivities(ws, extracted); + + // SQLite `context_catalog.summary` must NOT contain ephemeral `activities` + const storedColumns = rawRows(); + expect(storedColumns).toHaveLength(1); + expect(JSON.parse(storedColumns[0]!.summary)).not.toHaveProperty("activities"); + + const aliveNow = Date.parse("2026-11-25T12:00:10.000Z"); + const whileAwake = catalog.list({}, awakeContexts(sockets.ctx), aliveNow); + expect(whileAwake).toMatchObject([ + { + path: "/agents/builder", + awake: { since: 1_000 }, + activities: [{ key: "mcp:linear", text: "Querying Linear issues" }], + }, + ]); + + // Search matches across durable summary ("agent") AND live activities ("linear") + expect( + catalog + .list({ search: "agent linear" }, awakeContexts(sockets.ctx), aliveNow) + .map((r) => r.path), + ).toEqual(["/agents/builder"]); + + // Expired activity is filtered out at read time without needing another socket frame + const afterTtl = Date.parse("2026-11-25T12:01:00.000Z"); + expect(catalog.list({}, awakeContexts(sockets.ctx), afterTtl)[0]?.activities).toBeUndefined(); + + // Simulate DO crash / sleep: socket closes WITHOUT sending a cleared summary message + ws.close(); + const afterCrash = catalog.list({}, awakeContexts(sockets.ctx), aliveNow); + expect(afterCrash).toHaveLength(1); + expect(afterCrash[0]?.awake).toBeUndefined(); + expect(afterCrash[0]?.activities).toBeUndefined(); +}); + +test("AwakeSocket.activityChanged coalesces sub-debounce bursts and leaves zero timers on close", async () => { + vi.useFakeTimers(); + try { + const sent: string[] = []; + let open = 0; + let busy = true; + let stack: string[] = []; + const awake = new AwakeSocket({ + path: "/agents/a", + busy: () => busy, + summary: () => JSON.stringify({ stack }), + dial: async () => ({ + status: 101, + webSocket: { + accept: () => { + open += 1; + }, + close: () => { + open -= 1; + }, + send: (msg: string) => void sent.push(msg), + addEventListener: (() => undefined) as WebSocket["addEventListener"], + }, + }), + }); + + awake.entered(); + await vi.advanceTimersByTimeAsync(10); + expect(open).toBe(1); + + // Sub-debounce push + pop within 5ms sends nothing at 100ms because summary returned to baseline + stack = ["fast-call"]; + awake.activityChanged(); + await vi.advanceTimersByTimeAsync(5); + stack = []; + awake.activityChanged(); + await vi.advanceTimersByTimeAsync(AWAKE_ACTIVITY_DEBOUNCE_MS + 10); + // Initial send captures `{"stack":[]}`; no intermediate `["fast-call"]` frame was sent + expect(sent).toEqual(['{"stack":[]}']); + + // Sustained activity sends after debounce without waiting 15s + stack = ["long-fetch"]; + awake.activityChanged(); + await vi.advanceTimersByTimeAsync(AWAKE_ACTIVITY_DEBOUNCE_MS + 5); + expect(sent).toEqual(['{"stack":[]}', '{"stack":["long-fetch"]}']); + + // Quiet close clears stack, sends final summary, and leaves zero timers + stack = []; + busy = false; + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS + 10); + expect(open).toBe(0); + expect(sent.at(-1)).toBe('{"stack":[]}'); + expect(vi.getTimerCount()).toBe(0); + } finally { + vi.useRealTimers(); + } +}); + +test("automatic itx call hooks format safe labels, strip URL secrets, push while in flight, and pop on settle", async () => { + // URL credentials and query tokens must never leak into activity URLs or text + const fetchEntry = describeFetchActivity( + new Request("https://api.github.com/repos/iterate/private/pulls?token=shh#frag"), + ); + expect(fetchEntry).toMatchObject({ + text: "Fetching api.github.com/repos/iterate/private/pulls", + url: "https://api.github.com/repos/iterate/private/pulls", + tags: ["web"], + }); + expect(JSON.stringify(fetchEntry)).not.toContain("shh"); + expect( + JSON.stringify( + describeFetchActivity({ + url: "https://user:supersecret@api.github.com/repos/iterate/private", + }), + ), + ).not.toContain("supersecret"); + + expect(describeScriptRunActivity(7)).toEqual({ + entry: { + key: "itx:run:7", + text: "Running script", + icon: "code", + tags: ["code"], + ttlMs: RUN_DEADLINE_MS, + }, + runOffset: 7, + }); + + // High-level outbound `itx` expressions produce concise domain activities + const caller: Caller = { principal: null }; + expect( + describeItxCallActivity( + parse('itx.agents.get("/agents/reviewer").message("hi")'), + "/agents/a", + caller, + ), + ).toMatchObject({ + text: "Messaging /agents/reviewer", + icon: "agent", + url: "/agents/reviewer", + tags: ["agent"], + }); + expect( + describeItxCallActivity( + parse('itx.repos.get("/repos/config").commitFiles({ message: "update" })'), + "/agents/a", + caller, + ), + ).toMatchObject({ + text: "Committing to /repos/config", + icon: "code", + url: "/repos/config", + tags: ["code", "repo"], + }); + expect( + describeItxCallActivity( + parse('itx.connectToMcp("https://mcp.linear.app/sse?apiKey=secret")'), + "/agents/a", + caller, + ), + ).toMatchObject({ + text: "Calling MCP mcp.linear.app", + icon: "mcp", + url: "https://mcp.linear.app/sse", + tags: ["mcp"], + }); + expect( + describeItxCallActivity( + parse('itx.ai.websearch({ query: "Cloudflare Durable Objects" })'), + "/agents/a", + caller, + ), + ).toMatchObject({ + text: "Searching web: Cloudflare Durable Objects", + icon: "search", + tags: ["search", "web"], + }); + + // Passive / housekeeping / internal calls produce no activity noise + expect(describeItxCallActivity(parse("itx.whoami()"), "/agents/a", caller)).toBeNull(); + expect(describeItxCallActivity(parse("itx.contexts.list()"), "/", caller)).toBeNull(); + expect( + describeItxCallActivity( + parse('itx.facets.get("activities").liveSnapshot()'), + "/agents/a", + caller, + ), + ).toBeNull(); + expect( + describeItxCallActivity( + parse('itx.cd("/repos/config").facets.get("repo").readFile("a.ts")'), + "/agents/a", + { ...caller, libraryHop: true }, + ), + ).toBeNull(); + + // End-to-end in-flight hook through `ItxExpressionResolver` + `buildPortableBuiltIns`: + // activity is live on the tracker WHILE egress/located awaits, and popped in `finally`. + const tracker = new ContextActivityTracker({ sink: { append: () => undefined } }); + const hooks = { + push: (entry: Parameters<typeof tracker.push>[0]) => tracker.push(entry), + pop: (key: string) => tracker.pop({ key }), + }; + let releaseFetch!: () => void; + const fetchGate = new Promise<void>((resolve) => { + releaseFetch = resolve; + }); + + let releaseRemote!: () => void; + const remoteGate = new Promise<void>((resolve) => { + releaseRemote = resolve; + }); + + const resolver = new ItxExpressionResolver({ + path: "/agents/a", + caller: () => ({ principal: null }), + rewriteRules: () => [{ match: ["itx"], target: ["itx", "builtins", ["cd", "/"]] }], + reach: { + recordLoopLimit: () => undefined, + snapshotOf: async () => ({ rules: [], readAt: 0, expiresAt: Infinity }), + located: async () => { + await remoteGate; + return { ok: true }; + }, + workersOf: () => ({}), + }, + builtIns: () => + buildPortableBuiltIns({ + path: "/agents/a", + context: () => { + throw new Error("unused"); + }, + egress: (request) => + withTrackedActivity(describeFetchActivity(request), hooks, async () => { + await fetchGate; + return new Response("ok"); + }), + afterTheAnswer: () => undefined, + caller: () => ({ principal: null }), + invokeAs: (_c, call) => resolver.invoke(call), + itx: {} as never, + }), + wrapActivity: (expression, callCaller, run) => + withTrackedActivity(describeItxCallActivity(expression, "/agents/a", callCaller), hooks, run), + }); + + const inFlightFetch = resolver.invoke( + ["itx", "fetch"], + new Request("https://developers.cloudflare.com/workers/"), + ); + const inFlightMessage = resolver.invoke( + parse('itx.cd("/agents/peer").append({ type: "demo/ping", payload: {} })'), + ); + + // Both parallel calls are visible simultaneously on the context's live activity stack! + await vi.waitFor(() => expect(tracker.active()).toHaveLength(2)); + expect(tracker.active().map((item) => item.text)).toEqual([ + "Fetching developers.cloudflare.com/workers/", + "Messaging /agents/peer", + ]); + + releaseFetch(); + await inFlightFetch; + expect(tracker.active().map((item) => item.text)).toEqual(["Messaging /agents/peer"]); + + releaseRemote(); + await inFlightMessage; + expect(tracker.active()).toEqual([]); +}); + +function streamEvent( + offset: number, + type: string, + createdAt: string, + payload: Record<string, unknown>, + sourceExtra: Partial<StreamEvent["source"]> = {}, +): StreamEvent { + return { + offset, + type, + createdAt, + payload, + path: "/agents/a", + source: { origin: "/agents/a", ...sourceExtra }, + }; +} + +function memorySqlStorage(): { + sql: SqlStorage; + rawRows: () => { path: string; summary: string }[]; +} { + const db = new DatabaseSync(":memory:"); + const exec = <T extends Record<string, SqlStorageValue>>( + query: string, + ...bindings: unknown[] + ) => { + const trimmed = query.trim(); + if (/^SELECT\b/i.test(trimmed)) { + const rows = db.prepare(query).all(...(bindings as never[])) as T[]; + return { toArray: () => rows }; + } + db.prepare(query).run(...(bindings as never[])); + return { toArray: () => [] as T[] }; + }; + return { + sql: { exec } as unknown as SqlStorage, + rawRows: () => + db.prepare("SELECT path, summary FROM context_catalog").all() as { + path: string; + summary: string; + }[], + }; +} + +function fakeAwakeSocketHost() { + type FakeSocket = { + readyState: number; + deserializeAttachment: () => unknown; + serializeAttachment: (value: unknown) => void; + close: () => void; + }; + const list: FakeSocket[] = []; + return { + open(path: string, since: number) { + let attachment: unknown = { path, since }; + const ws: FakeSocket = { + readyState: WebSocket.OPEN, + deserializeAttachment: () => structuredClone(attachment), + serializeAttachment: (value: unknown) => { + attachment = structuredClone(value); + }, + close: () => { + ws.readyState = WebSocket.CLOSED; + }, + }; + list.push(ws); + return ws; + }, + ctx: { + getWebSockets: () => list as unknown as WebSocket[], + }, + }; +}
A core/itx/src/context/context-activity-stack.ts
@@ -0,0 +1,655 @@ +// context-activity-stack.ts — A CONTEXT'S IN-MEMORY STACK OF LIVE ACTIVITIES. +// +// Activities represent what a context is actively doing right now (fetching an HTTP endpoint, +// running a script, waiting on an LLM response, messaging another agent, reading or committing a +// repo, calling an MCP server). The stack lives strictly in RAM on `IterateContextDurableObject` +// and on the open `AwakeSocket` attachment to `/awake`: +// - If the context sleeps, crashes, or evicts, both RAM and its `/awake` socket close together, so +// stale activities can never stick in SQLite (`context_catalog`). +// - Open browser tabs subscribe via `itx.facets.get("activities").liveSnapshot()` and receive +// `events.iterate.com/itx/live-state-changed` deltas from `LiveState`. +import { z } from "zod"; +import { itxExpressionStepName, type ItxExpression } from "iterate/expression"; +import { jsonEqual, resolveContextPath } from "iterate/lib"; +import { LiveState, type LiveStateSink, type StreamEvent } from "iterate/stream/processor"; +import { RUN_DEADLINE_MS } from "iterate/stream/run"; +import type { Caller } from "../caller.ts"; +import { + CONTEXT_ACTIVITY_POPPED_TYPE, + CONTEXT_ACTIVITY_PUSHED_TYPE, + CONTEXT_ACTIVITY_STACK_LIMIT, + ContextActivity, + ContextActivityPoppedPayload, + ContextActivityPushedEntry, + ContextActivityPushedPayload, +} from "../stream/core-events.ts"; +import { AWAKE_CONTEXT_PATH } from "./awake.ts"; + +export { + CONTEXT_ACTIVITY_POPPED_TYPE, + CONTEXT_ACTIVITY_PUSHED_TYPE, + CONTEXT_ACTIVITY_STACK_LIMIT, + ContextActivity, + ContextActivityPoppedPayload, + ContextActivityPushedEntry, +}; + +export const CONTEXT_ACTIVITIES_FACET = "activities"; + +const RUN_SETTLED_TYPE = "events.iterate.com/itx/run-settled"; + +const WebSearchInput = z.object({ query: z.string() }); +const WaitFilterInput = z.object({ type: z.string() }); + +const LlmRequestedActivityPayload = z.object({ + model: z.string().min(1), + purpose: z.string().optional(), + expiresAtMs: z.number().finite().optional(), +}); + +const LlmEndedActivityPayload = z.object({ + llmRequestOffset: z.number().int().positive(), +}); + +const RunSettledActivityPayload = z.object({ + requestOffset: z.number().int().positive(), +}); + +/** RPC payload sent from `statelessResolverFor` to an awake context's `reportActivity`. */ +export const ContextActivityReport = z.discriminatedUnion("kind", [ + z.object({ + kind: z.literal("push"), + entry: ContextActivityPushedEntry, + createdAt: z.string().optional(), + runOffset: z.number().int().positive().optional(), + }), + z.object({ + kind: z.literal("pop"), + key: z.string().min(1).max(120), + }), +]); +export type ContextActivityReport = z.infer<typeof ContextActivityReport>; + +type StoredContextActivity = { + item: ContextActivity; + runOffset?: number; +}; + +/** Whether `item` has not yet reached its `expiresAt` at `nowMs`. */ +function isContextActivityLive(item: ContextActivity, nowMs: number): boolean { + if (!item.expiresAt) return true; + const expiresAtMs = Date.parse(item.expiresAt); + return !Number.isFinite(expiresAtMs) || expiresAtMs > nowMs; +} + +/** Active items from `items` at `nowMs`, preserving LIFO order (`stack[0]` is newest). */ +export function activeContextActivities( + items: readonly ContextActivity[] | undefined, + nowMs = Date.now(), +): ContextActivity[] { + if (!items || items.length === 0) return []; + return items.filter((item) => isContextActivityLive(item, nowMs)); +} + +function toWireActivity(entry: ContextActivityPushedEntry, createdAt: string): ContextActivity { + const baseMs = Date.parse(createdAt); + const computedExpiresAt = + entry.expiresAt || + (entry.ttlMs !== undefined && Number.isFinite(baseMs) + ? new Date(baseMs + entry.ttlMs).toISOString() + : undefined); + return { + key: entry.key, + text: entry.text, + icon: entry.icon, + url: entry.url, + tags: entry.tags?.length ? entry.tags : undefined, + pushedAt: createdAt, + expiresAt: computedExpiresAt, + }; +} + +function runOffsetOfSource( + source: StreamEvent["source"] | undefined, + ownPath: string, +): number | undefined { + const run = source?.onBehalfOf?.run; + if (!run) return undefined; + const prefix = `${ownPath}@`; + if (!run.startsWith(prefix)) return undefined; + const parsed = Number.parseInt(run.slice(prefix.length), 10); + return Number.isInteger(parsed) && parsed > 0 ? parsed : undefined; +} + +export class ContextActivityTracker { + readonly #liveState: LiveState<ContextActivity[]>; + readonly #onChanged: (() => void) | undefined; + #stack: StoredContextActivity[] = []; + + constructor(deps: { sink: LiveStateSink; onChanged?: () => void }) { + this.#liveState = new LiveState<ContextActivity[]>(deps.sink, CONTEXT_ACTIVITIES_FACET, []); + this.#onChanged = deps.onChanged; + } + + push( + entry: ContextActivityPushedEntry, + options: { createdAt?: string; runOffset?: number; nowMs?: number } = {}, + ): void { + const nowMs = options.nowMs ?? Date.now(); + const createdAt = options.createdAt || new Date(nowMs).toISOString(); + const item = toWireActivity(entry, createdAt); + const nextEntry: StoredContextActivity = + options.runOffset !== undefined ? { item, runOffset: options.runOffset } : { item }; + this.#stack = [ + nextEntry, + ...this.#stack.filter( + (existing) => existing.item.key !== item.key && isContextActivityLive(existing.item, nowMs), + ), + ].slice(0, CONTEXT_ACTIVITY_STACK_LIMIT); + this.#sync(nowMs); + } + + pop(target: ContextActivityPoppedPayload, nowMs = Date.now()): void { + if ("key" in target) { + this.#stack = this.#stack.filter( + (entry) => entry.item.key !== target.key && isContextActivityLive(entry.item, nowMs), + ); + } else if ("keys" in target) { + const keys = new Set(target.keys); + this.#stack = this.#stack.filter( + (entry) => !keys.has(entry.item.key) && isContextActivityLive(entry.item, nowMs), + ); + } else { + const tag = target.tag; + this.#stack = this.#stack.filter( + (entry) => !entry.item.tags?.includes(tag) && isContextActivityLive(entry.item, nowMs), + ); + } + this.#sync(nowMs); + } + + clear(): void { + if (this.#stack.length === 0 && this.#liveState.get().length === 0) return; + this.#stack = []; + this.#liveState.set([]); + this.#onChanged?.(); + } + + /** Folds committed stream events (both durable and ephemeral) into the live stack. */ + committed(events: readonly StreamEvent[], ownPath: string, nowMs = Date.now()): void { + let touched = false; + for (const event of events) { + if (event.type === CONTEXT_ACTIVITY_PUSHED_TYPE) { + const parsed = ContextActivityPushedPayload.safeParse(event.payload); + if (!parsed.success) continue; + const entries = "items" in parsed.data ? parsed.data.items : [parsed.data]; + const runOffset = runOffsetOfSource(event.source, ownPath); + for (const entry of entries) { + const item = toWireActivity(entry, event.createdAt); + const stored: StoredContextActivity = + runOffset !== undefined ? { item, runOffset } : { item }; + this.#stack = [ + stored, + ...this.#stack.filter((existing) => existing.item.key !== item.key), + ]; + } + if (this.#stack.length > CONTEXT_ACTIVITY_STACK_LIMIT) + this.#stack = this.#stack.slice(0, CONTEXT_ACTIVITY_STACK_LIMIT); + touched = true; + continue; + } + if (event.type === CONTEXT_ACTIVITY_POPPED_TYPE) { + const parsed = ContextActivityPoppedPayload.safeParse(event.payload); + if (!parsed.success) continue; + const popData = parsed.data; + if ("key" in popData) { + this.#stack = this.#stack.filter((entry) => entry.item.key !== popData.key); + } else if ("keys" in popData) { + const keys = new Set(popData.keys); + this.#stack = this.#stack.filter((entry) => !keys.has(entry.item.key)); + } else { + this.#stack = this.#stack.filter((entry) => !entry.item.tags?.includes(popData.tag)); + } + touched = true; + continue; + } + if (event.type === RUN_SETTLED_TYPE) { + const parsed = RunSettledActivityPayload.safeParse(event.payload); + if (!parsed.success) continue; + const before = this.#stack.length; + this.#stack = this.#stack.filter((entry) => entry.runOffset !== parsed.data.requestOffset); + if (this.#stack.length !== before) touched = true; + continue; + } + if (event.type === "events.iterate.com/llm-request/requested") { + const parsed = LlmRequestedActivityPayload.safeParse(event.payload); + if (!parsed.success) continue; + const { model, purpose, expiresAtMs } = parsed.data; + const shortModel = (model.split("/").at(-1) || model).slice(0, 60); + const verb = purpose === "summary" ? "Summarizing context" : "Thinking"; + const icon = model.startsWith("anthropic/") ? "claude" : "✨"; + const item = toWireActivity( + { + key: `llm:${String(event.offset)}`, + text: `${verb} · ${shortModel}`.slice(0, 160), + icon, + tags: ["llm"], + ...(expiresAtMs !== undefined + ? { expiresAt: new Date(expiresAtMs).toISOString() } + : { ttlMs: 180_000 }), + }, + event.createdAt, + ); + this.#stack = [ + { item }, + ...this.#stack.filter((existing) => existing.item.key !== item.key), + ].slice(0, CONTEXT_ACTIVITY_STACK_LIMIT); + touched = true; + continue; + } + if ( + event.type === "events.iterate.com/llm-request/settled" || + event.type === "events.iterate.com/llm-request/cancelled" + ) { + const parsed = LlmEndedActivityPayload.safeParse(event.payload); + if (!parsed.success) continue; + const targetKey = `llm:${String(parsed.data.llmRequestOffset)}`; + const before = this.#stack.length; + this.#stack = this.#stack.filter((entry) => entry.item.key !== targetKey); + if (this.#stack.length !== before) touched = true; + } + } + if (!touched) return; + this.#stack = this.#stack.filter((entry) => isContextActivityLive(entry.item, nowMs)); + this.#sync(nowMs); + } + + active(nowMs = Date.now()): ContextActivity[] { + if (this.#stack.some((entry) => !isContextActivityLive(entry.item, nowMs))) { + this.#stack = this.#stack.filter((entry) => isContextActivityLive(entry.item, nowMs)); + this.#sync(nowMs); + } + return this.#liveState.get(); + } + + liveSnapshot(nowMs = Date.now()): { rev: number; state: ContextActivity[] } { + this.active(nowMs); + return this.#liveState.snapshot(); + } + + #sync(nowMs: number): void { + const wire = this.#stack + .filter((entry) => isContextActivityLive(entry.item, nowMs)) + .map((entry) => entry.item); + const previous = this.#liveState.get(); + if (jsonEqual(previous, wire)) return; + this.#liveState.set(wire); + this.#onChanged?.(); + } +} + +let nextActivitySeq = 0; +function mintActivityKey(prefix: string): string { + nextActivitySeq = (nextActivitySeq + 1) % 1_000_000_000; + return `${prefix}:${String(nextActivitySeq)}`; +} + +function truncateText(value: string, maxChars: number): string { + return value.length <= maxChars ? value : `${value.slice(0, maxChars - 1)}…`; +} + +function cleanHttpTarget(rawUrl: string): { + host: string; + shortPath: string; + cleanUrl: string; +} | null { + try { + const parsed = new URL(rawUrl); + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null; + if (!parsed.hostname) return null; + const shortPath = + parsed.pathname && parsed.pathname !== "/" ? truncateText(parsed.pathname, 36) : ""; + // Strips userinfo, query parameters, and hash fragments so credentials/tokens never enter live state. + const cleanUrl = `${parsed.origin}${parsed.pathname}`.slice(0, 500); + return { host: parsed.hostname, shortPath, cleanUrl }; + } catch { + return null; + } +} + +/** Builds the live activity item for an outbound `itx.fetch` / egress call. */ +export function describeFetchActivity( + request: { url: string; method?: string }, + options?: { signFor?: string }, +): ContextActivityPushedEntry | null { + const target = cleanHttpTarget(request.url); + if (!target) return null; + const method = (request.method || "GET").toUpperCase(); + const label = options?.signFor + ? `Calling ${options.signFor}${target.shortPath}` + : method === "GET" || method === "HEAD" + ? `Fetching ${target.host}${target.shortPath}` + : `${method} ${target.host}${target.shortPath}`; + return { + key: mintActivityKey("fetch"), + text: truncateText(label, 160), + url: target.cleanUrl, + tags: ["web"], + ttlMs: 60_000, + }; +} + +/** Builds the live activity item for an `itx.run` script execution on this context. */ +export function describeScriptRunActivity(requestOffset: number): { + entry: ContextActivityPushedEntry; + runOffset: number; +} { + return { + entry: { + key: `itx:run:${String(requestOffset)}`, + text: "Running script", + icon: "code", + tags: ["code"], + ttlMs: RUN_DEADLINE_MS, + }, + runOffset: requestOffset, + }; +} + +const PASSIVE_CONTEXT_ROOTS: ReadonlySet<string> = new Set([ + "whoami", + "rewriteRules", + "subscriptions", + "schedules", + "contexts", + "url", + "members", + "readEvents", +]); + +const PASSIVE_FACET_METHODS: ReadonlySet<string> = new Set([ + "snapshot", + "liveSnapshot", + "listPublicMethods", +]); + +/** Builds a concise live activity item for an outbound `itx` expression call, or `null` for + * local housekeeping, passive reads, or calls already covered by `fetch` / `run` hooks. */ +export function describeItxCallActivity( + expression: ItxExpression, + ownPath: string, + caller: Pick<Caller, "platform" | "runsRow" | "libraryHop" | "path">, +): ContextActivityPushedEntry | null { + if (caller.platform || caller.runsRow || caller.libraryHop) return null; + const steps = + expression[0] === "itx" && expression[1] === "builtins" + ? expression.slice(2) + : expression.slice(1); + if (steps.length === 0) return null; + + const first = steps[0]!; + const root = itxExpressionStepName(first); + if (!root || PASSIVE_CONTEXT_ROOTS.has(root)) return null; + // Local `fetch` and `run` have dedicated hooks (`describeFetchActivity`, `describeScriptRunActivity`). + if (root === "fetch" || root === "run") return null; + + const origin = caller.path || ownPath; + + if (root === "agents") { + return describeAgentsCall(steps.slice(1), origin); + } + if (root === "connectToMcp") { + const rawUrl = Array.isArray(first) && typeof first[1] === "string" ? first[1] : undefined; + const target = rawUrl ? cleanHttpTarget(rawUrl) : null; + const hostLabel = target ? ` ${target.host}` : ""; + return { + key: mintActivityKey("mcp"), + text: truncateText(`Calling MCP${hostLabel}`, 160), + icon: "mcp", + ...(target && { url: target.cleanUrl }), + tags: ["mcp"], + ttlMs: 120_000, + }; + } + if (root === "repos" || root === "sandboxes" || root === "workspaces") { + return describeEntityCollectionCall(root, steps.slice(1), origin); + } + if (root === "git") { + const verbStep = steps[1]; + if (!Array.isArray(verbStep)) return null; + return { + key: mintActivityKey("git"), + text: "Committing to git remote", + icon: "code", + tags: ["code", "git"], + ttlMs: 60_000, + }; + } + if (root === "files") { + const second = steps[1]; + const third = steps[2]; + if (!Array.isArray(second) || second[0] !== "get" || typeof second[1] !== "string") return null; + if (!Array.isArray(third)) return null; + const verb = third[0]; + if (verb === "url" || verb === "head") return null; + const fileLabel = truncateText(second[1], 48); + const action = verb === "put" ? "Writing" : verb === "delete" ? "Deleting" : "Reading"; + return { + key: mintActivityKey("files"), + text: `${action} file ${fileLabel}`, + icon: "code", + tags: ["files"], + ttlMs: 60_000, + }; + } + if (root === "ai") { + const second = steps[1]; + if (!Array.isArray(second)) return null; + const verb = second[0]; + if (verb === "models") return null; + if (verb === "websearch") { + const query = WebSearchInput.safeParse(second[1]).data?.query.trim() || ""; + return { + key: mintActivityKey("search"), + text: query ? truncateText(`Searching web: ${query}`, 160) : "Searching web", + icon: "search", + tags: ["search", "web"], + ttlMs: 60_000, + }; + } + const modelArg = typeof second[1] === "string" ? second[1].split("/").at(-1) : undefined; + return { + key: mintActivityKey("ai"), + text: truncateText(modelArg ? `Running AI · ${modelArg}` : `Running AI · ${verb}`, 160), + icon: "✨", + tags: ["ai"], + ttlMs: 120_000, + }; + } + if (root === "browser") { + if (steps.length < 2) return null; + return { + key: mintActivityKey("browser"), + text: "Browsing web page", + icon: "web", + tags: ["web", "browser"], + ttlMs: 120_000, + }; + } + if (root === "waitForEvent") { + const filter = Array.isArray(first) ? first[1] : undefined; + const type = WaitFilterInput.safeParse(filter).data?.type; + if (type === RUN_SETTLED_TYPE) return null; + const shortType = type?.startsWith("events.iterate.com/") + ? type.slice("events.iterate.com/".length) + : type; + return { + key: mintActivityKey("wait"), + text: truncateText(shortType ? `Waiting for ${shortType}` : "Waiting for event", 160), + tags: ["itx"], + ttlMs: 120_000, + }; + } + if (root === "cd" && Array.isArray(first) && typeof first[1] === "string") { + return describeCrossContextCall(resolveContextPath(origin, first[1]), steps.slice(1), ownPath); + } + return null; +} + +function describeAgentsCall( + rest: ItxExpression, + origin: string, +): ContextActivityPushedEntry | null { + const [first, second] = rest; + if (!Array.isArray(first)) return null; + const method = first[0]; + if (method === "list" || method === "at") return null; + const rawTarget = typeof first[1] === "string" ? first[1] : undefined; + if (!rawTarget) return null; + const targetPath = resolveContextPath(origin, rawTarget); + if (method === "create") { + return { + key: mintActivityKey("agent"), + text: truncateText(`Starting agent ${targetPath}`, 160), + icon: "agent", + url: targetPath.slice(0, 500), + tags: ["agent"], + ttlMs: 60_000, + }; + } + if (method === "delete") { + return { + key: mintActivityKey("agent"), + text: truncateText(`Deleting agent ${targetPath}`, 160), + icon: "agent", + url: targetPath.slice(0, 500), + tags: ["agent"], + ttlMs: 60_000, + }; + } + if (method === "get" && Array.isArray(second)) { + const action = second[0]; + const label = + action === "message" + ? `Messaging ${targetPath}` + : action === "recent" + ? `Reading ${targetPath}` + : `Calling ${targetPath} · ${action}`; + return { + key: mintActivityKey("agent"), + text: truncateText(label, 160), + icon: "agent", + url: targetPath.slice(0, 500), + tags: ["agent"], + ttlMs: 60_000, + }; + } + return null; +} + +function describeEntityCollectionCall( + collection: "repos" | "sandboxes" | "workspaces", + rest: ItxExpression, + origin: string, +): ContextActivityPushedEntry | null { + const [first, second, third] = rest; + if (!Array.isArray(first)) return null; + const method = first[0]; + if (method === "list") return null; + const rawTarget = typeof first[1] === "string" ? first[1] : undefined; + if (!rawTarget) return null; + const targetPath = resolveContextPath(origin, rawTarget); + const tag = + collection === "repos" ? "repo" : collection === "sandboxes" ? "sandbox" : "workspace"; + if (method === "create" || method === "delete") { + const verbLabel = method === "create" ? "Creating" : "Deleting"; + return { + key: mintActivityKey(tag), + text: truncateText(`${verbLabel} ${targetPath}`, 160), + icon: "code", + url: targetPath.slice(0, 500), + tags: ["code", tag], + ttlMs: 60_000, + }; + } + if (method !== "get" || !second) return null; + const stepName = itxExpressionStepName(second) || ""; + if (!stepName || PASSIVE_FACET_METHODS.has(stepName)) return null; + if (second === "container" && !Array.isArray(third)) return null; + const detail = + second === "container" && Array.isArray(third) ? `container.${third[0]}` : stepName; + const repoLabel = + collection === "repos" + ? stepName === "commitFiles" + ? `Committing to ${targetPath}` + : stepName === "pull" || stepName === "push" + ? `Syncing ${targetPath}` + : stepName === "readFile" + ? `Reading ${targetPath}` + : `${targetPath} · ${detail}` + : `${targetPath} · ${detail}`; + return { + key: mintActivityKey(tag), + text: truncateText(repoLabel, 160), + icon: "code", + url: targetPath.slice(0, 500), + tags: ["code", tag], + ttlMs: collection === "sandboxes" ? 300_000 : 60_000, + }; +} + +function describeCrossContextCall( + targetPath: string, + rest: ItxExpression, + ownPath: string, +): ContextActivityPushedEntry | null { + if (targetPath === ownPath || targetPath === AWAKE_CONTEXT_PATH || rest.length === 0) return null; + const first = rest[0]!; + const root = itxExpressionStepName(first); + if (!root || PASSIVE_CONTEXT_ROOTS.has(root)) return null; + if (root === "processors" && Array.isArray(rest[1]) && rest[1][0] === "list") return null; + if (root === "facets") { + const getStep = rest[1]; + const callStep = rest[2]; + if (!Array.isArray(getStep) || !callStep) return null; + const facetMethod = itxExpressionStepName(callStep) || ""; + if (PASSIVE_FACET_METHODS.has(facetMethod)) return null; + } + // A bare handle step with no call on the end returns a handle synchronously without remote work. + const last = rest.at(-1)!; + if (!Array.isArray(last)) return null; + + const isAgent = targetPath.startsWith("/agents/"); + const label = + root === "run" + ? `Running script on ${targetPath}` + : root === "append" && isAgent + ? `Messaging ${targetPath}` + : `Calling ${targetPath} · ${root}`; + return { + key: mintActivityKey(isAgent ? "agent" : "cd"), + text: truncateText(label, 160), + ...(isAgent && { icon: "agent" }), + url: targetPath.slice(0, 500), + tags: [isAgent ? "agent" : "itx"], + ttlMs: root === "run" ? RUN_DEADLINE_MS : 60_000, + }; +} + +/** Pushes `entry` before `work()` and pops its key when `work()` settles. */ +export async function withTrackedActivity<T>( + entry: ContextActivityPushedEntry | null, + hooks: { + push: (entry: ContextActivityPushedEntry) => void; + pop: (key: string) => void; + }, + work: () => Promise<T>, +): Promise<T> { + if (!entry) return work(); + hooks.push(entry); + try { + return await work(); + } finally { + hooks.pop(entry.key); + } +}
M core/itx/src/context/context-catalog.ts
@@ -1,16 +1,23 @@ // context-catalog.ts — THE MIND'S CATALOG OF ITS CONTEXTS: one SQLite row per context, in the // storage of the context that accepts the awake sockets (awake.ts). A row is the newest summary // its context sent (context-summary.ts). A list joins the rows with the open sockets, so "awake" -// is never stored. The catalog is a copy: every row can be made again from its context's own log. +// and live `activities` are never stored in SQLite: when a socket closes, both vanish at once. import { z } from "zod"; import type { ContextListing, ContextListOptions } from "iterate/api"; +import type { AwakeContextState } from "./awake.ts"; +import { activeContextActivities, ContextActivity } from "./context-activity-stack.ts"; import { ContextSummary } from "./context-summary.ts"; -/** What a context sends: its folded summary, and what it reads off itself at that moment. */ -export const ContextSummaryMessage = ContextSummary.extend({ +/** Durable fields stored in SQLite `context_catalog.summary` (never live `activities`). */ +const StoredContextSummary = ContextSummary.extend({ processors: z.array(z.string()), storageBytes: z.number().int().nonnegative(), }); + +/** What a context sends over its awake socket: its durable summary plus live in-memory activities. */ +export const ContextSummaryMessage = StoredContextSummary.extend({ + activities: z.array(ContextActivity).optional(), +}); export type ContextSummaryMessage = z.infer<typeof ContextSummaryMessage>; export class ContextCatalog { @@ -38,10 +45,11 @@ this.#tableMade = true; } - /** Keeps `message` as `path`'s row unless the row is of a later offset. A message that is no - * summary is refused with a thrown error, which its caller logs. */ - store(path: string, message: string): void { - const summary = ContextSummaryMessage.parse(JSON.parse(message)); + /** Keeps the durable part of `message` as `path`'s row unless the row is of a later offset, and + * returns the live `activities` carried on the message so the caller can attach them to the + * open awake socket (never SQLite). A message that is no summary is refused with a thrown error. */ + store(path: string, message: string): ContextActivity[] | undefined { + const { activities, ...durable } = ContextSummaryMessage.parse(JSON.parse(message)); this.#table(); this.#sql.exec( `INSERT INTO context_catalog (path, through_offset, active_at, summary) VALUES (?, ?, ?, ?) @@ -51,15 +59,20 @@ summary = excluded.summary WHERE excluded.through_offset >= context_catalog.through_offset`, path, - summary.throughOffset, - summary.lastActivityAt || summary.lastEventAt || "", - JSON.stringify(summary), + durable.throughOffset, + durable.lastActivityAt || durable.lastEventAt || "", + JSON.stringify(durable), ); + return activities; } /** The contexts that match, the most recently active first. `awake` is the open sockets, by - * path. An awake context with no row yet (its first wake) is listed with what is known. */ - list(options: ContextListOptions, awake: ReadonlyMap<string, number>): ContextListing[] { + * path, with their live in-memory activities. Sleeping contexts never carry `activities`. */ + list( + options: ContextListOptions, + awake: ReadonlyMap<string, AwakeContextState>, + now = Date.now(), + ): ContextListing[] { this.#table(); const limit = Math.min(Math.max(1, options.limit ?? 200), 1_000); const terms = (options.search || "").toLowerCase().split(/\s+/).filter(Boolean); @@ -90,33 +103,72 @@ limit, ) .toArray(); - const listed = rows.map(({ path, summary }): ContextListing => { - const { throughOffset: _, ...stored } = ContextSummaryMessage.parse(JSON.parse(summary)); - const since = awake.get(path); - return { path, ...stored, ...(since !== undefined && { awake: { since } }) }; - }); - if (terms.length > 0) return listed; - // An awake context with no row at all: one that has a row past this page is not one. - const candidates = [...awake.keys()].filter(matchesPath); - const stored = new Set( - this.#sql - .exec<{ path: string }>( - "SELECT path FROM context_catalog WHERE path IN (SELECT value FROM json_each(?))", - JSON.stringify(candidates), - ) - .toArray() - .map((row) => row.path), - ); - const unlisted = candidates - .filter((path) => !stored.has(path)) - .map((path): ContextListing => ({ + const toListing = (path: string, summaryJson: string): ContextListing => { + const { throughOffset: _, ...stored } = StoredContextSummary.parse(JSON.parse(summaryJson)); + const awakeState = awake.get(path); + if (!awakeState) return { path, ...stored }; + const liveActivities = activeContextActivities(awakeState.activities, now); + return { path, - awake: { since: awake.get(path) ?? Date.now() }, + ...stored, + awake: { since: awakeState.since }, + ...(liveActivities.length > 0 && { activities: liveActivities }), + }; + }; + const toUnlistedAwake = (path: string): ContextListing => { + const awakeState = awake.get(path); + const liveActivities = activeContextActivities(awakeState?.activities, now); + return { + path, + awake: { since: awakeState?.since ?? now }, eventCount: 0, eventTypes: {}, recentTypes: [], processors: [], - })); + ...(liveActivities.length > 0 && { activities: liveActivities }), + }; + }; + const listed = rows.map(({ path, summary }) => toListing(path, summary)); + const candidates = [...awake.keys()].filter(matchesPath); + if (candidates.length === 0) return listed; + + const storedRows = this.#sql + .exec<{ path: string; summary: string }>( + "SELECT path, summary FROM context_catalog WHERE path IN (SELECT value FROM json_each(?))", + JSON.stringify(candidates), + ) + .toArray(); + const storedByPath = new Map(storedRows.map((row) => [row.path, row.summary])); + + if (terms.length > 0) { + const listedPaths = new Set(listed.map((row) => row.path)); + const extraAwakeMatches: ContextListing[] = []; + for (const path of candidates) { + if (listedPaths.has(path)) continue; + const storedSummary = storedByPath.get(path); + const candidateListing = storedSummary + ? toListing(path, storedSummary) + : toUnlistedAwake(path); + const haystack = [ + path, + storedSummary || "", + ...(candidateListing.activities || []).flatMap((item) => [ + item.text, + item.key, + ...(item.tags || []), + ]), + ] + .join(" ") + .toLowerCase(); + if (terms.every((term) => haystack.includes(term))) { + extraAwakeMatches.push(candidateListing); + } + } + return [...extraAwakeMatches, ...listed].slice(0, limit); + } + + // An awake context with no row at all: one that has a row past this page is not one. + const unlisted = candidates.filter((path) => !storedByPath.has(path)).map(toUnlistedAwake); return [...unlisted, ...listed].slice(0, limit); } }
M core/itx/src/context/facet-host.ts
@@ -18,7 +18,7 @@ type ItxExpressionInput, } from "iterate/expression"; import type { FacetProps, StreamProcessorDurableObject } from "iterate/sdk"; -import type { FacetSpec, WorkerSource } from "iterate/api"; +import type { ContextActivity, FacetSpec, WorkerSource } from "iterate/api"; import { failureKind, isPlatformFailureKind } from "iterate/platform-retry"; import type { Caller } from "../caller.ts"; import { deepestCause, requestCausedBy, type Cause } from "../cause.ts"; @@ -38,6 +38,7 @@ } from "../first-party-facets.ts"; import { itxLoader } from "../host.ts"; import type { Stream } from "../stream/stream.ts"; +import { CONTEXT_ACTIVITIES_FACET } from "./context-activity-stack.ts"; import { walkSteps, awaitAnswerReleasedIfRejected, @@ -129,6 +130,8 @@ caller: () => Caller; // The cause of a caller's own call to `<facet>.<method>`: a promise only when it must be signed. causeOfCall: (call: string) => Cause | undefined | Promise<Cause | undefined>; + activitiesSnapshot?: () => ContextActivity[]; + activitiesLiveSnapshot?: () => { rev: number; state: ContextActivity[] }; }; // answered from the processor's reduce, after the deliveries its context owes it @@ -290,8 +293,8 @@ // oxlint-disable-next-line iterate/simple-truthiness-check -- name arrives as a client-authored itx expression argument; the static string type is the API contract, not a runtime guarantee if (typeof name !== "string") throw new Error("itx.facets.abort(name, reason?): name the facet"); - if (name === CoreContract.slug) - throw new Error(`"${name}" is the core reduce — never a facet, nothing to abort`); + if (name === CoreContract.slug || name === CONTEXT_ACTIVITIES_FACET) + throw new Error(`"${name}" is built into the context — never a facet, nothing to abort`); if (firstPartyFacetClassOf(name)) assertFacetPlacement(name, this.#deps.path); else this.#facetStartupMemoFor(name, undefined); const why = reason ? `: ${reason}` : ""; @@ -578,6 +581,7 @@ this.#claimFacetAlarm(CoreContract.slug, null); this.#facetRevived(CoreContract.slug); } + names.delete(CONTEXT_ACTIVITIES_FACET); for (const name of names) this.#deleteFacet( name, @@ -697,6 +701,22 @@ await walkSteps( { value: { snapshot: () => this.#deps.stream.coreReducedStateSnapshot() }, + receiver: undefined, + }, + itxExpressionSteps, + ) + ).value; + } + if (name === CONTEXT_ACTIVITIES_FACET) { + if (spec) throw new Error(`"${name}" is the context activity stack — never a facet name`); + if (byPerson) assertFacetMethodIsAPersons(name, [], [], itxExpressionSteps); + return ( + await walkSteps( + { + value: { + snapshot: () => this.#deps.activitiesSnapshot?.() ?? [], + liveSnapshot: () => this.#deps.activitiesLiveSnapshot?.() ?? { rev: 0, state: [] }, + }, receiver: undefined, }, itxExpressionSteps,
M core/itx/src/context/itx-expression-rewriting.ts
@@ -903,6 +903,9 @@ readonly #path: string; readonly #caller: () => Caller; readonly #reach: ResolverReach; + readonly #wrapActivity: + | ((expression: ItxExpression, caller: Caller, run: () => Promise<unknown>) => Promise<unknown>) + | undefined; constructor(args: { builtIns: Record<string, unknown> | (() => Record<string, unknown>); @@ -910,6 +913,11 @@ path: string; caller: () => Caller; reach: ResolverReach; + wrapActivity?: ( + expression: ItxExpression, + caller: Caller, + run: () => Promise<unknown>, + ) => Promise<unknown>; }) { const { builtIns } = args; this.#buildBuiltIns = typeof builtIns === "function" ? builtIns : () => builtIns; @@ -917,6 +925,7 @@ this.#path = args.path; this.#caller = args.caller; this.#reach = args.reach; + this.#wrapActivity = args.wrapActivity; } // On the input only: the rows a call rewrites through are the owner's grants and are never checked. @@ -956,14 +965,24 @@ } async #invoked(call: ItxExpressionInput, extraArgs: unknown[], approved?: string) { - try { - return (await this.#dispatch(call, extraArgs, approved)).value; - } catch (error) { - recordRefusal(error, (cause, message) => - this.#reach.recordLoopLimit(this.#path, cause, message), - ); - throw error; - } + const run = async () => { + try { + return (await this.#dispatch(call, extraArgs, approved)).value; + } catch (error) { + recordRefusal(error, (cause, message) => + this.#reach.recordLoopLimit(this.#path, cause, message), + ); + throw error; + } + }; + if (!this.#wrapActivity) return run(); + const expression = normalizedItxExpression(call); + const last = expression.at(-1); + const fullExpression: ItxExpression = + extraArgs.length > 0 && typeof last === "string" && expression.length > 1 + ? [...expression.slice(0, -1), [last, ...extraArgs]] + : expression; + return this.#wrapActivity(fullExpression, this.#caller(), run); } // A CALL THAT NOBODY WAITS FOR IS REFUSED WHEN AN APPROVAL RULE NAMES IT. A subscription's
M core/itx/src/context/stateless-context.ts
@@ -10,6 +10,12 @@ callContext, workersRoot, } from "./built-ins.ts"; +import { + type ContextActivityReport, + describeFetchActivity, + describeItxCallActivity, + withTrackedActivity, +} from "./context-activity-stack.ts"; import { egress } from "./egress.ts"; import { ItxExpressionResolver } from "./itx-expression-rewriting.ts"; import { DurableObjectNameCodec, type DurableObjectAddress } from "./paths.ts"; @@ -99,6 +105,22 @@ ctx: args.ctx, }); const context = reach.contextOf; + // Ordered per-resolver delivery so a fast `pop` never overtakes its preceding `push`. Best-effort + // and rollover-safe: an awake context running an older release during a deploy lacks the method + // and ignores it cleanly. + let activityReportChain: Promise<unknown> = Promise.resolve(); + const sendActivityReport = (report: ContextActivityReport) => { + const contextName = DurableObjectNameCodec.stringify(path); + activityReportChain = activityReportChain + .then(() => args.namespace.getByName(contextName).reportActivity(report)) + .catch(() => undefined); + args.ctx.waitUntil(activityReportChain); + }; + const activityHooks = { + push: (entry: Extract<ContextActivityReport, { kind: "push" }>["entry"]) => + sendActivityReport({ kind: "push", entry, createdAt: new Date().toISOString() }), + pop: (key: string) => sendActivityReport({ kind: "pop", key }), + }; // No `connections`: a resolver lives one round trip, so a connector root is sent to the // context, whose residency holds and releases them. const resolverUnder = (callerNow: Caller): ItxExpressionResolver => { @@ -106,7 +128,10 @@ ...buildPortableBuiltIns({ path, context, - egress: (request, options) => egress(request, { cause: callerNow.cause, path, ...options }), + egress: (request, options) => + withTrackedActivity(describeFetchActivity(request, options), activityHooks, () => + egress(request, { cause: callerNow.cause, path, ...options }), + ), afterTheAnswer: (work) => args.ctx.waitUntil(work), caller: () => callerNow, invokeAs: (callerThere, call) => resolverUnder(callerThere).invoke(call), @@ -119,6 +144,12 @@ builtIns: build, path, caller: () => callerNow, + wrapActivity: (expression, callCaller, run) => + withTrackedActivity( + describeItxCallActivity(expression, path, callCaller), + activityHooks, + run, + ), }); return resolver; }; @@ -126,7 +157,7 @@ // the dotted members its prototype fallback serves. const { app: _loadedCode, ...libraryCaller } = caller; const libraryItx = new InvokeHandle((steps) => - resolverUnder(libraryCaller).invoke(["itx", ...steps]), + resolverUnder({ ...libraryCaller, libraryHop: true }).invoke(["itx", ...steps]), ) as unknown as LibraryItx; return resolverUnder(caller); }
M core/itx/src/iterate-context-durable-object.ts
@@ -97,7 +97,16 @@ awakeContextOf, awakeContexts, isAwakeWebSocket, + setAwakeActivities, } from "./context/awake.ts"; +import { + ContextActivityReport, + ContextActivityTracker, + describeFetchActivity, + describeItxCallActivity, + describeScriptRunActivity, + withTrackedActivity, +} from "./context/context-activity-stack.ts"; import { ContextCatalog, type ContextSummaryMessage } from "./context/context-catalog.ts"; import { ContextSummaryTracker } from "./context/context-summary.ts"; import { egress } from "./context/egress.ts"; @@ -359,6 +368,7 @@ return claimed; }); this.#contextSummary.committed(events); + this.#activityStack.committed(events, this.#durableObjectAddress.path); const woken = events.find((event) => event.type === "events.iterate.com/itx/woken"); if (woken) this.#announceToAncestors(woken.source?.cause); this.#measureSize(); @@ -571,8 +581,8 @@ readonly #libraryItx = new InvokeHandle((steps) => { this.#residency.pinCallStarted(); const { app: _loadedCode, ...caller } = this.#caller; - return this.#invokeInProcess(["itx", ...steps], [], caller).finally(() => - this.#residency.pinCallEnded(), + return this.#invokeInProcess(["itx", ...steps], [], { ...caller, libraryHop: true }).finally( + () => this.#residency.pinCallEnded(), ); }) as unknown as LibraryItx; readonly #connections = new Connections(); @@ -621,6 +631,8 @@ code: string, requester: Requester | undefined, ): Promise<void> { + const runActivity = describeScriptRunActivity(requestOffset); + this.#activityStack.push(runActivity.entry, { runOffset: runActivity.runOffset }); const cause = this.#stream.coreReducedState.scriptRuns[requestOffset]?.cause; // Straight onto the stream: no writer can append the platform's own record. A run that is no // longer open was settled already: by a new version, whose log its key no longer dedupes. @@ -678,6 +690,7 @@ }); else reportIssue("iterate-context.run-settle", error, { requestOffset }); } finally { + this.#activityStack.pop({ key: runActivity.entry.key }); this.#scriptRunsInFlight.delete(requestOffset); } } @@ -809,6 +822,15 @@ builtIns: this.#builtIns, path: this.#durableObjectAddress.path, caller: () => this.#caller, + wrapActivity: (expression, caller, run) => + withTrackedActivity( + describeItxCallActivity(expression, this.#durableObjectAddress.path, caller), + { + push: (entry) => this.#activityStack.push(entry), + pop: (key) => this.#activityStack.pop({ key }), + }, + run, + ), }); // This incarnation only ends the version: the next one empties what it left and is born @@ -860,6 +882,7 @@ // What this incarnation still says of the context to the mind's catalog is of the new // version: the earlier one's description and counts are not sent under the new offsets. this.#contextSummary.startOver(); + this.#activityStack.clear(); // Best effort, as the kernel, whatever each row consumes: a callback that fails or is offline // misses the batch, and 2 s bounds how long the slowest one holds the answer. An event that // a row does not take reaches its callback as the bare border, with the version alone: not @@ -1069,6 +1092,8 @@ cause: () => this.#caller.cause, caller: () => this.#caller, causeOfCall: (call) => this.#causeNamingCaller(call), + activitiesSnapshot: () => this.#activityStack.active(), + activitiesLiveSnapshot: () => this.#activityStack.liveSnapshot(), }); // A facet's code calls as the context's, so the person who called it rides the call's cause, @@ -1103,14 +1128,17 @@ readonly #awakeSocket = new AwakeSocket({ path: this.#durableObjectAddress.path, busy: () => this.#residency.busy(), - summary: () => - JSON.stringify({ + summary: () => { + const activities = this.#activityStack.active(); + return JSON.stringify({ ...this.#contextSummary.current(), processors: Object.values(this.#stream.coreReducedState.subscriptions).flatMap((row) => row.hostedFacet ? [row.hostedFacet.name] : [], ), storageBytes: this.ctx.storage.sql.databaseSize, - } satisfies ContextSummaryMessage), + ...(activities.length > 0 && { activities }), + } satisfies ContextSummaryMessage); + }, dial: () => contexts() .getByName(DurableObjectNameCodec.stringify(AWAKE_CONTEXT_PATH)) @@ -1122,6 +1150,22 @@ }), }); + // Live in-flight activities in RAM only (never persisted to KV/SQLite), streaming deltas via + // `LiveState` and pushing live stack updates over `#awakeSocket`. + readonly #activityStack = new ContextActivityTracker({ + sink: { + append: (event) => { + if (this.#stream.versionEnded()) return; + try { + this.#stream.append(event); + } catch { + // A paused or ended stream drops the live-state delta; clients re-seed on revision gap. + } + }, + }, + onChanged: () => this.#awakeSocket.activityChanged(), + }); + // What this context says about itself, folded from its log (context/context-summary.ts). readonly #contextSummary = new ContextSummaryTracker({ kv: this.ctx.storage.kv, @@ -1572,19 +1616,47 @@ } #egress(request: Request, options?: { signFor?: string }): Promise<Response> { - return egress(request, { - cause: this.#caller.cause, - path: this.#durableObjectAddress.path, - ...options, - }); + return withTrackedActivity( + describeFetchActivity(request, options), + { + push: (entry) => this.#activityStack.push(entry), + pop: (key) => this.#activityStack.pop({ key }), + }, + () => + egress(request, { + cause: this.#caller.cause, + path: this.#durableObjectAddress.path, + ...options, + }), + ); } + /** Receives best-effort live activity push/pop notifications from `statelessResolverFor`. + * Unborn or asleep contexts ignore notifications without recording a wake or touching storage. */ + reportActivity(rawReport: unknown): void { + if (this.#stream.highestDurableOffset() === 0 || !this.#stream.wakeRecorded()) return; + const parsed = ContextActivityReport.safeParse(rawReport); + if (!parsed.success) return; + if (parsed.data.kind === "push") { + this.#activityStack.push(parsed.data.entry, { + createdAt: parsed.data.createdAt, + runOffset: parsed.data.runOffset, + }); + return; + } + this.#activityStack.pop({ key: parsed.data.key }); + } + webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): void { - // A context's summary: one row written, no wake record. + // A context's summary: one durable row written, live activities kept on the socket attachment. if (isAwakeWebSocket(this.ctx, ws)) { const { path } = awakeContextOf(ws); try { - this.#contextCatalog.store(path, typeof message === "string" ? message : ""); + const activities = this.#contextCatalog.store( + path, + typeof message === "string" ? message : "", + ); + setAwakeActivities(ws, activities); } catch (error) { console.info({ event: "context.catalog-summary-refused",
M core/itx/src/stream/core-events.ts
@@ -2,6 +2,43 @@ // catalog, so it must not pull core-processor.ts into a client. import { z } from "zod"; +export const CONTEXT_ACTIVITY_PUSHED_TYPE = "events.iterate.com/itx/activity-pushed"; +export const CONTEXT_ACTIVITY_POPPED_TYPE = "events.iterate.com/itx/activity-popped"; + +/** Maximum number of live items retained on a context's activity stack; older items drop off the bottom. */ +export const CONTEXT_ACTIVITY_STACK_LIMIT = 32; + +const ContextActivityTag = z.string().trim().min(1).max(40); + +export const ContextActivity = z.object({ + key: z.string().min(1).max(120), + text: z.string().min(1).max(160), + icon: z.string().min(1).max(500).optional(), + url: z.string().min(1).max(500).optional(), + tags: z.array(ContextActivityTag).max(8).optional(), + pushedAt: z.string().optional(), + expiresAt: z.string().optional(), +}); +export type ContextActivity = z.infer<typeof ContextActivity>; + +export const ContextActivityPushedEntry = ContextActivity.omit({ pushedAt: true }).extend({ + ttlMs: z.number().int().positive().max(86_400_000).optional(), +}); +export type ContextActivityPushedEntry = z.infer<typeof ContextActivityPushedEntry>; + +export const ContextActivityPushedPayload = z.union([ + ContextActivityPushedEntry, + z.object({ items: z.array(ContextActivityPushedEntry).min(1).max(CONTEXT_ACTIVITY_STACK_LIMIT) }), +]); +export type ContextActivityPushedPayload = z.infer<typeof ContextActivityPushedPayload>; + +export const ContextActivityPoppedPayload = z.union([ + z.object({ key: z.string().min(1).max(120) }), + z.object({ keys: z.array(z.string().min(1).max(120)).min(1).max(CONTEXT_ACTIVITY_STACK_LIMIT) }), + z.object({ tag: ContextActivityTag }), +]); +export type ContextActivityPoppedPayload = z.infer<typeof ContextActivityPoppedPayload>; + export const CoreEventCatalog = { events: { "events.iterate.com/itx/ingress-configured": { @@ -32,6 +69,16 @@ description: z.string().max(2_000).nullable().optional(), metadata: z.record(z.string(), z.unknown()).nullable().optional(), }), + }, + [CONTEXT_ACTIVITY_PUSHED_TYPE]: { + description: + "One or more live activities were pushed onto this context's in-memory activity stack (context/context-activity-stack.ts). Pushing an existing key updates it in place and promotes it to the top of the stack.", + payloadSchema: ContextActivityPushedPayload, + }, + [CONTEXT_ACTIVITY_POPPED_TYPE]: { + description: + "Activities were removed from this context's in-memory activity stack by key, keys, or tag (context/context-activity-stack.ts).", + payloadSchema: ContextActivityPoppedPayload, }, "events.iterate.com/itx/signed-request-sent": { description:
M core/lib/src/api.ts
Not shown: the change is larger than this page shows. A clone has it.