### Host wiring example for editor.agent (docs example, not shipped code) Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-10-08-agent-control/03-in-app-surface.md Illustrates the intended host integration with editor.agent: obtaining tools and guidance, beginning a turn, stopping it, and ending it in a finally block. The comment shows the host's own loop for handling tool_use blocks. This is a documentation example, not shipped code. ```ts const tools = await editor.agent.tools({ format: 'anthropic' }); const system = await editor.agent.guidance(); const turn = editor.agent.begin({ agent: { id: 'assistant', name: 'Assistant' } }); stopButton.onclick = () => turn.stop(); try { // host's own loop with its own SDK; for each tool_use block: // const r = await turn.call(block.name, block.input); // push { type: 'tool_result', tool_use_id: block.id, content: r.content, is_error: r.isError } } finally { turn.end(); } ``` -------------------------------- ### Install dependencies with yarn install Source: https://github.com/jackuait/blok/blob/main/README.md Run this command to install the project dependencies before starting development or running tests. ```bash yarn install ``` -------------------------------- ### Start dev playground with yarn serve Source: https://github.com/jackuait/blok/blob/main/README.md Starts the development playground. Add --no-server to skip the collaboration backend. ```bash yarn serve # dev playground (add --no-server to skip the collaboration backend) ``` -------------------------------- ### withRoom: Start a conformance server and run a test callback Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-10-08-agent-control/plans/04-outside-surface-plan.md Creates a temporary collab directory, starts a doc endpoint and a server with specific flags (--listen, --auth ticket, --collab, --conformance-journal, etc.), then runs the provided callback with wsUrl, baseUrl, and a request helper. The request helper adds Origin and Authorization headers using a blokTicket. Cleans up server, endpoint, and directory in a finally block. ```TypeScript const withRoom = async (run: (input: { wsUrl: string; baseUrl: string; request: (method: string, path: string) => Promise<{ status: number; text: string }> }) => Promise): Promise => { const collabDirectory = await mkdtemp(join(tmpdir(), 'blok-mcp-conformance-')); const endpoint = await startDocEndpoint(); const server = await startServer({ args: [ '--listen', '127.0.0.1:0', '--auth', 'ticket', '--storage-dir', '', '--rate-limit', '0', '--collab', '--collab-dir', collabDirectory, '--doc-endpoint', endpoint.url, '--conformance-journal', '--allow-origin', ORIGIN, ], env: { BLOK_SECRET: SECRET }, }); try { await run({ wsUrl: `${server.baseUrl.replace(/^http:/, 'ws:')}/sync`, baseUrl: server.baseUrl, request: async (method, path) => { const answer = await server.request(method, path, { headers: { Origin: ORIGIN, Authorization: `Bearer ${blokTicket(SECRET, { user: HUMAN, doc: DOC, write: true })}` }, }); return { status: answer.status, text: answer.text }; }, }); } finally { await server.stop(); await endpoint.stop(); await rm(collabDirectory, { recursive: true, force: true }); } }; ``` -------------------------------- ### Test setup and keyboard event helpers for title keyboard Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-10-08-page-title-core-plan.md Defines a setup function that creates an editable title element, binds it with bindTitleKeyboard, and returns the title and a mock host. Also defines a press helper to dispatch keyboard events. Used in unit tests for title keyboard behavior. ```ts const setup = (text: string, caret: number): { title: HTMLElement; host: { [K in keyof TitleKeyboardHost]: ReturnType } } => { const title = document.createElement('h1'); title.contentEditable = 'true'; title.textContent = text; document.body.appendChild(title); title.focus(); window.getSelection()?.setPosition(title.firstChild, caret); const host = { isReadOnly: vi.fn(() => false), split: vi.fn(), toFirstBlock: vi.fn(), undo: vi.fn(), redo: vi.fn(), commit: vi.fn() }; bindTitleKeyboard(title, host); return { title, host }; }; const press = (el: HTMLElement, init: KeyboardEventInit): KeyboardEvent => { const event = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init }); el.dispatchEvent(event); return event; }; ``` -------------------------------- ### Implement follow logic in start() Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-10-08-agent-control/plans/03-in-app-surface-plan.md Sets following state and attaches intent listeners when follow is enabled. Provides stopFollowing to clean up. ```ts state.following = follow; if (follow) { const stop = (): void => { state.following = false; }; INTENT_EVENTS.forEach((type) => window.addEventListener(type, stop, { capture: true, passive: true })); state.stopFollowing = (): void => { INTENT_EVENTS.forEach((type) => window.removeEventListener(type, stop, { capture: true })); }; } ``` -------------------------------- ### Change start() signature to use startOptions Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-10-08-agent-control/plans/03-in-app-surface-plan.md Updates the start method signature to accept startOptions with follow, avoiding shadowing the outer options. ```ts start(agent: AgentIdentity, startOptions: { follow: boolean }): void ``` -------------------------------- ### editor.agent.begin() Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-10-08-agent-control/03-in-app-surface.md Starts a new agent turn on the editor. Throws AgentTurnOpenError if a turn is already open. ```APIDOC ## editor.agent.begin() ### Description Starts a new agent turn on the editor. Throws AgentTurnOpenError if a turn is already open. ### Method begin ### Endpoint editor.agent.begin() ### Parameters #### Request Body - **agent** (object) - Required - Agent descriptor with `id` and `name`. ### Request Example ```ts const turn = editor.agent.begin({ agent: { id: 'assistant', name: 'Assistant' } }); ``` ### Response #### Success Response - **turn** (AgentTurn) - The newly opened turn. #### Error Handling - Throws `AgentTurnOpenError` if a turn is already open. ``` -------------------------------- ### Install @bloklabs/presets and @bloklabs/core Source: https://github.com/jackuait/blok/blob/main/packages/presets/README.md Install the presets package along with the core Blok package to use the ready-made uploader implementations. ```bash npm install @bloklabs/presets @bloklabs/core ``` -------------------------------- ### Example: describeCode module (src/shared/tool-descriptions/code.ts) Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-10-08-agent-control/plans/02-tool-self-description-plan.md Example pattern for writing the four tool description modules, following Task 16. Shows the structure for `describeCode` with `CODE_DATA`, guidance, default data, and summary fields. ```ts // src/shared/tool-descriptions/code.ts import type { BlockToolDescription } from '../../../types/tools/tool-description'; export const CODE_DATA = /* the `code` $defs literal, moved verbatim */ {}; export const describeCode = (_config: Record = {}): BlockToolDescription => ({ summary: 'A code block with a language and an optional file name.', guidance: '`code` is raw text, never HTML and never a Markdown fence. language is a lowercase name such as "javascript" or "plain text".', data: CODE_DATA, defaultData: { code: '', language: 'plain text' }, examples: [{ code: 'const a = 1;', language: 'javascript', filename: 'a.js' }], summaryFields: ['language', 'filename'], }); ``` -------------------------------- ### Start HTTP server with transport configuration Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-10-08-agent-control/plans/04-outside-surface-plan.md Used in the start method to initialize the HTTP server when the transport kind is 'http'. It passes listen, tools, dispatch, auth, principal, and version options, then logs the server URL and stores the handle. Falls back to serveStdio for other transport kinds. ```TypeScript import { startHttpServer } from './http'; // ... start: async () => { if (options.transport.kind === 'http') { const http = await startHttpServer({ listen: options.transport.listen, tools: assembled.tools, dispatch: assembled.dispatch, auth: options.auth, principal: options.principal ?? DEFAULTS.principal, version: getBlokVersion(), }); console.error(`blok-mcp: listening on ${http.url}/mcp`); running.handle = http; return; } running.handle = serveStdio(/* as before */); }, ``` -------------------------------- ### Harness setup and session helpers (test/unit/agent/harness.ts) Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-10-08-agent-control/plans/05-coverage-and-evals-plan.md Defines the test actor, node setup, contract, and session opener for agent tests. Uses createHeadlessAgentSetup and createDocumentAgentSession. validateSaved maps schema problems to strings. ```typescript // test/unit/agent/harness.ts import type { OutputData } from '../../../types'; import type { AgentActor, AgentContract, AgentSession } from '../../../types/agent'; import { createDocumentAgentSession } from '../../../src/shared/agent'; import { validateAgainst } from '../../../src/shared/schema/validate'; import { createHeadlessAgentSetup, loadStoredDocument } from '../../../src/view/agent-runtime'; import { blokDocumentSchema } from '../../../src/view/document-schema'; export const TEST_ACTOR: AgentActor = { id: 'agent-test', name: 'Parity', kind: 'agent' }; // 01 Task 21: built-in snapshot (02 Task 27) + runtimes (02 Task 13) + COMMANDS (01 Task 3) + headless ports (01 Task 19). export const nodeSetup = (runtime: 'node' | 'node-live' = 'node') => createHeadlessAgentSetup({ runtime }); export const nodeContract = (runtime: 'node' | 'node-live' = 'node'): AgentContract => nodeSetup(runtime).contract; export const openJsonSession = (seed: OutputData, actor: AgentActor = TEST_ACTOR): AgentSession & { output(): OutputData } => { const setup = nodeSetup('node'); return createDocumentAgentSession({ document: loadStoredDocument(structuredClone(seed), setup.richTextFieldsFor), tools: setup.tools, contract: setup.contract, actor, ports: setup.ports, }); }; // validateAgainst returns SchemaProblem[] (02 Task 2); empty means valid. export const validateSaved = (doc: OutputData): string[] => validateAgainst(blokDocumentSchema as unknown as Record, doc).map((e) => `${e.path}: ${e.message}`); ``` -------------------------------- ### TabSync start() sketch with role resolution and join Source: https://github.com/jackuait/blok/blob/main/docs/superpowers/plans/2026-10-03-tab-sync.md Sketch of the start() method for the TabSync module. It resolves the channel and lock, checks isAllowed(), acquires the lock to become leader, or joins. On error, it logs and sets role to 'solo'. isAllowed() returns false when tabSync is false or collaboration is set. ```typescript public async start(context: { loadedFromPersistence: boolean; isEmpty: boolean }): Promise { try { const key = this.resolveKey(context); const channel = key === null ? null : this.platform.channel(key); const lock = key === null ? null : this.platform.lock(key); if (key === null || channel === null || lock === null || !this.isAllowed()) { return; } this.key = key; this.channel = channel; this.lock = lock; this.unlisten = channel.onMessage((message) => this.receive(message)); if (!this.Blok.ReadOnly.isEnabled && await lock.tryAcquire()) { this.becomeLeader(); return; } this.join(); } catch (error) { log('Tab sync could not start; this tab works on its own.', 'debug', error); this.setRole('solo'); } } /** Off with `tabSync: false` and with `collaboration`, whose server already syncs tabs. */ private isAllowed(): boolean { return this.config.tabSync !== false && this.config.collaboration === undefined; } ``` -------------------------------- ### startHttpServer Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-10-08-agent-control/plans/04-outside-surface-plan.md Starts an HTTP server for MCP with streamable transport. It accepts an HttpServerInput configuration and returns a promise resolving to the server URL and a close function. ```APIDOC ## startHttpServer ### Description Starts an HTTP server for MCP with streamable transport. It accepts an HttpServerInput configuration and returns a promise resolving to the server URL and a close function. ### Method POST ### Endpoint / (root) ### Parameters #### Request Body - **listen** (string) - Required - host:port, port 0 allowed in tests - **path** (string) - Optional - default '/mcp' - **tools** (McpTool[]) - Required - List of MCP tools - **dispatch** (Dispatch) - Required - Dispatch function - **auth** (BlokMcpOptions['auth']) - Required - Authentication configuration - **principal** (string) - Required - used with auth none - **version** (string) - Required - Version string - **fetchImpl** (typeof fetch) - Optional - JWKS fetch, tests inject ### Request Example { "listen": "localhost:8080", "path": "/mcp", "tools": [], "dispatch": {}, "auth": {}, "principal": "user", "version": "1.0.0" } ### Response #### Success Response (200) - **url** (string) - The server URL - **close** (function) - Closes the server #### Response Example { "url": "http://localhost:8080", "close": "function" } ``` -------------------------------- ### Create server entrypoint (main.go) Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-08-22-backend-service-plan.md Main function parses -listen flag (default 127.0.0.1:4000), logs version, and starts HTTP server. Version is stamped via -ldflags. ```go package main import ( "flag" "log" "net/http" "github.com/JackUait/blok/packages/server/internal/httpapi" ) // version is stamped at build time via -ldflags. var version = "dev" func main() { listen := flag.String("listen", "127.0.0.1:4000", "address to listen on") flag.Parse() log.Printf("blok-server %s listening on %s", version, *listen) if err := http.ListenAndServe(*listen, httpapi.New(httpapi.Options{Version: version})); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Install and add markdownlint-cli Source: https://github.com/jackuait/blok/blob/main/test/fixtures/notion/demo-page.clipboard.html Commands to install the markdownlint CLI globally and add it as a dev dependency using yarn. Part of the dependency resolution step in the installation workflow. ```bash npm install -g @docsify/cli yarn add -D markdownlint-cli ``` -------------------------------- ### Update constant arrays only Source: https://github.com/jackuait/blok/blob/main/test/playwright/CONFIG.md Correct example: add new test patterns to the CROSS_BROWSER_TESTS array. ```typescript // GOOD const CROSS_BROWSER_TESTS = [ '**/drag-drop.spec.ts', '**/my-new-browser-test.spec.ts', // Add here ]; ``` -------------------------------- ### Set up HTTP router and options (router.go) Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-08-22-backend-service-plan.md Defines Options struct with Version field, server struct, and New() constructor that registers GET /health route. All options are optional for tests. ```go package httpapi import "net/http" // Options carries everything the HTTP layer needs. Later tasks add fields; // they are all optional so tests can construct a server with only what they use. type Options struct { Version string } type server struct { opts Options mux *http.ServeMux } func New(opts Options) http.Handler { s := &server{opts: opts, mux: http.NewServeMux()} s.mux.HandleFunc("GET /health", s.handleHealth) return s } func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) { s.mux.ServeHTTP(w, r) } ``` -------------------------------- ### Avoid manually editing the projects array Source: https://github.com/jackuait/blok/blob/main/test/playwright/CONFIG.md Incorrect example: manually editing the projects array is discouraged because projects are auto-generated. ```typescript // BAD - projects are auto-generated projects: [ { name: 'chromium', testMatch: [...] }, // Don't edit this ] ``` -------------------------------- ### Build Go and run green Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-08-24-go-server-removal-plan.md Step 4 of Task 1: builds the Go server binary and runs the conformance test against it. The test should pass after implementing the harness. ```bash go build -o /tmp/blok-server-go ./packages/server/cmd/blok-server BLOK_CONFORMANCE_SERVER=/tmp/blok-server-go yarn vitest run --project=unit test/server-conformance/server-contract.test.ts ``` -------------------------------- ### Avoid duplicate patterns across arrays Source: https://github.com/jackuait/blok/blob/main/test/playwright/CONFIG.md Incorrect example: duplicating a test pattern in both CROSS_BROWSER_TESTS and LOGIC_TESTS causes the test to run in both projects. ```typescript // BAD const CROSS_BROWSER_TESTS = ['**/drag-drop.spec.ts']; const LOGIC_TESTS = ['**/drag-drop.spec.ts']; // Duplicate! ``` -------------------------------- ### Build Go server binaries for conformance testing Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-10-31-go-server-research/delivery-ci.md Run in packages/server/go to build the ordinary and conformance-tagged binaries for the conformance test runner. The runtime bundle must be in place first. ```bash go build -o /go-ordinary/blok-server ./cmd/blok-server ``` ```bash go build -tags conformance -o /go-conformance/blok-server ./cmd/blok-server ``` -------------------------------- ### rowMatchesFilters number operator tests (partial) Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-10-09-database-notion-parity/01-phase-0-foundations.md Starts the number operator test suite with a row containing a numeric property. The snippet is incomplete in the source, so only the setup is shown. ```typescript describe('rowMatchesFilters — number', () => { const r = row('r', 'a0', { num: 5 }); ``` -------------------------------- ### Implementation of bookmark.create action Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-10-08-agent-control/plans/02-tool-self-description-plan.md Step 2 of Task 48. Defines the create action with prepare that fetches link metadata and falls back to just the URL on failure, and run that inserts a bookmark block. Requires `BookmarkMeta` from `types/tools/bookmark.d.ts` and registration in `LINK_ACTION_HANDLERS`. ```TypeScript import type { BlockPosition, BookmarkMeta } from '../../../types'; import type { LinkMetadataService } from './services'; const create: ToolActionImpl<{ url: string; parentId?: string | null; position?: BlockPosition }, BookmarkMeta, { id: string; childIds: string[] }> = { prepare: async ({ services }, args) => { const metadata = services.linkMetadata as LinkMetadataService; try { return { ...(await metadata.fetch(args.url)), url: args.url }; } catch { return { url: args.url }; } }, run: (ctx, args, prepared) => ({ id: ctx.insert({ type: ctx.tool, data: { ...(prepared ?? { url: args.url }) }, parentId: args.parentId, position: args.position }), childIds: [], }), }; export const LINK_ACTION_HANDLERS = { embed: { setUrl }, bookmark: { create } } as const; ``` -------------------------------- ### JavaScript variable assignment example Source: https://github.com/jackuait/blok/blob/main/test/fixtures/notion/demo-page.clipboard.html A simple JavaScript code block from the demo page, assigning the string "fuck" to a constant variable named test. ```javascript const test = "fuck" ``` -------------------------------- ### Run tests for table create, descriptions, and schema Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-10-08-agent-control/plans/02-tool-self-description-plan.md Run these test commands one at a time. All should pass. ```bash yarn test test/unit/shared/tool-actions/table-create.test.ts ``` ```bash yarn test test/unit/shared/tool-descriptions/descriptions.test.ts ``` ```bash yarn test test/unit/view/document-schema.test.ts ``` -------------------------------- ### Tests for publishing activity stamps Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-09-08-collaboration-activity-client.md Tests added inside the existing describe('what it publishes') block (line 325) to verify that activity is stamped on session start, moves forward with caret movement, and is not rewritten more than once a second. Uses fake timers installed in beforeEach at line 313 and the FakeAwareness seam. ```TypeScript it('stamps activity when the session starts, so opening the document counts', () => { vi.setSystemTime(new Date(1_700_000_000_000)); const { seam, presence } = setup(); presence.start(); expect(seam.states.get(42)?.activeAt).toBe(1_700_000_000_000); }); it('moves the stamp forward as the caret moves', () => { vi.setSystemTime(new Date(1_700_000_000_000)); const { seam, target, presence } = setup(); presence.start(); vi.setSystemTime(new Date(1_700_000_005_000)); moveCaret(target); vi.advanceTimersByTime(200); expect(seam.states.get(42)?.activeAt).toBe(1_700_000_005_000); }); // The caret publisher runs every 100ms and skips an unchanged value. A stamp // that moved every pass would defeat that dedupe and put a fresh awareness // frame on the wire for every keystroke, for a number nobody reads at that // resolution. it('does not rewrite the stamp more than once a second', () => { vi.setSystemTime(new Date(1_700_000_000_000)); const { seam, target, presence } = setup(); presence.start(); const before = seam.writes.filter((write) => write.field === 'activeAt').length; vi.setSystemTime(new Date(1_700_000_000_300)); moveCaret(target); vi.advanceTimersByTime(200); expect(seam.writes.filter((write) => write.field === 'activeAt')).toHaveLength(before); }); ``` -------------------------------- ### dateStart Source: https://github.com/jackuait/blok/blob/main/src/tools/database/formula/README.md Returns the start of a date. Renamed from `start` in 2.0. ```APIDOC ## dateStart ### Description Returns the start of a date. Renamed from `start` in 2.0. ### Signature `dateStart(date)` ### Parameters - `date` (Date) - Required - The date to get the start of. ### Returns - The start of the date. ``` -------------------------------- ### Generate Editor.js migration guide Source: https://github.com/jackuait/blok/blob/main/packages/cli/README.md Outputs the EditorJS to Blok migration guide to a file. The guide is written to be pasted into an LLM alongside your codebase. ```bash npx @bloklabs/cli --migration --output migration-guide.md ``` -------------------------------- ### Boot helper for page-title-data tests Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-10-08-page-title-core-plan.md Creates a Core instance with the given config, waits for readiness, and returns it. Used by all tests in this file to set up a fresh editor state. ```typescript const boot = async (config: Partial = {}): Promise => { const core = new Core({ holder, tools: { paragraph: { class: Paragraph } }, ...config }); await core.isReady; return core; }; ``` -------------------------------- ### Generate fixtures and verify Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-09-02-yjs-engine-plan.md Run the generator, then the freshness test, then lint the generator and test files. ```bash node scripts/generate-yjs-engine-fixtures.mjs ``` ```bash yarn test test/unit/server-conformance/yjs-engine-fixtures.freshness.test.ts ``` ```bash yarn eslint scripts/generate-yjs-engine-fixtures.mjs test/unit/server-conformance/yjs-engine-fixtures.freshness.test.ts ``` -------------------------------- ### Register GET /unfurl route Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-08-22-backend-service-plan.md Registers the handleUnfurl handler for the GET /unfurl route in the mux. ```go s.mux.HandleFunc("GET /unfurl", s.handleUnfurl) ``` -------------------------------- ### Go: main function with flags and config validation Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-08-22-backend-service-plan.md Defines the server entry point, parsing flags for listen address, auth mode, secret, allowed origins, storage directory, and unfurl disabling. Validates the configuration and exits with a fatal error if invalid. ```go func main() { var ( listen = flag.String("listen", "127.0.0.1:4000", "address to listen on") auth = flag.String("auth", "none", "access mode: none, proxy, or ticket") secret = flag.String("secret", "", "shared secret for --auth ticket") origins = flag.String("allow-origin", "", "comma-separated origins allowed to call this service") storage = flag.String("storage-dir", "./blok-uploads", "directory for uploaded files") noUnfurl = flag.Bool("no-unfurl", false, "disable link previews entirely") ) flag.Parse() cfg := config.Config{ Listen: *listen, Auth: config.AuthMode(*auth), Secret: *secret, StorageDir: *storage, UnfurlDisabled: *noUnfurl, } if *origins != "" { cfg.AllowedOrigins = strings.Split(*origins, ",") } if err := config.Validate(cfg); err != nil { log.Fatalf("blok-server refused to start: %v", err) } ... } ``` -------------------------------- ### Install dependencies and update lockfile Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-08-23-storage-presets-plan.md Updates the lockfile and installs dependencies immutably to register the new workspace. ```bash yarn install --mode=update-lockfile yarn install --immutable ``` -------------------------------- ### WAAPI implicit start keyframe note Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-10-05-find-bar-bloom-hop-plan.md Notes that `chip.animate([{}, …])` uses an implicit start keyframe, which is valid WAAPI and starts from the chip's computed tint. ```TypeScript chip.animate([{}, { backgroundColor: 'transparent' }], { duration: HOP_MS, delay, easing: 'ease-in', fill: 'both' }) ``` -------------------------------- ### Basic performance analysis Source: https://github.com/jackuait/blok/blob/main/scripts/README.md Run the performance analyzer with default settings. ```bash yarn perf:analyze ``` -------------------------------- ### createBlokMcpServer Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-10-08-agent-control/04-outside-surface.md Creates and starts a Blok MCP server with the provided options. The server exposes tools and resources to MCP clients, supporting both stdio and HTTP transports. ```APIDOC ## createBlokMcpServer(options) ### Description Creates a Blok MCP server instance with the given configuration. The server can be started and stopped asynchronously. ### Method Function call ### Signature ```ts createBlokMcpServer(options: BlokMcpOptions): { start(): Promise; stop(): Promise } ``` ### Parameters #### options (BlokMcpOptions) - Required - **transport** (object) - Required - Transport configuration: `{ kind: 'stdio' }` or `{ kind: 'http'; listen: string; public?: boolean }` - **auth** (object) - Required - Authentication configuration: `{ kind: 'none' }` or `{ kind: 'oauth'; issuer: string; audience: string; jwksUrl: string }` - **sync** (object) - Optional - Live mode configuration: `{ url: string; origin?: string }`; absent means no live mode - **tickets** (object) - Optional - Ticket configuration: `{ kind: 'secret'; secret: string }` or `{ kind: 'url'; url: string; hostToken: string }` - **authorize** (function) - Optional - Authorization callback: `(principal: string, documentId: string, write: boolean) => Promise` - **agentActor** (function) - Optional - Builds the session's actor: `(principal: string, clientName: string) => AgentActor`; the ticket `user` must equal the returned `id` - **source** (object) - Optional - Source configuration: `{ kind: 'endpoint'; url: string; endpointAuth: string; list?: string }` or `{ kind: 'files'; dir: string }` - **manifest** (BlokCustomToolsFile) - Optional - Host custom tool descriptions, as `--manifest ` loads them - **pageTitles** (string) - Optional - `'off'` or `'page-map'`; enables headless page.rename / page.setIcon (default `'off'`) - **overrides** (ManifestOverrides) - Optional - Same shape as `--manifest-overrides ` - **richTextFields** (Record) - Optional - Only for block types missing from the manifest - **schema** (string) - Optional - `'envelope'` or `'full'` (default `'envelope'`) - **handleIdleMs** (number) - Optional - Idle timeout in milliseconds - **maxHandlesPerPrincipal** (number) - Optional - Maximum number of handles per principal ### Returns - **start()** (function) - Starts the server, returns a Promise that resolves when started - **stop()** (function) - Stops the server, returns a Promise that resolves when stopped ### Example ```ts const server = createBlokMcpServer({ transport: { kind: 'stdio' }, auth: { kind: 'none' }, source: { kind: 'files', dir: './docs' } }); await server.start(); ``` ``` -------------------------------- ### Run the release wiring test Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-08-22-backend-service-plan.md Run the test to see it fail initially, then pass after registering the package. ```bash yarn test test/unit/architecture/server-release-wiring.test.ts ``` -------------------------------- ### Install @bloklabs/react and @bloklabs/core Source: https://github.com/jackuait/blok/blob/main/packages/react/README.md Install the React bindings and core package. @bloklabs/core, react, and react-dom are peer dependencies. ```bash npm install @bloklabs/react @bloklabs/core ``` -------------------------------- ### Install Browsers Job (YAML) Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-07-19-ci-critical-path-optimization.md Defines a GitHub Actions job to install Playwright browsers. Node is pinned to 24.14.1 due to a hang in `playwright install` on Node >= 24.16. This job intentionally has no `needs` to reduce the critical path. ```yaml install-browsers: name: Install Browsers runs-on: ubuntu-latest timeout-minutes: 10 steps: - name: Checkout code uses: actions/checkout@v4 # Node is pinned to 24.14.1 because `playwright install` (< 1.60.0) hangs forever # after the browser download on Node >= 24.16 (vendored-yauzl extract bug, # microsoft/playwright#40998). Remove the pin after bumping @playwright/test to >= 1.60.0. - name: Setup Node.js and Dependencies uses: ./.github/actions/setup-node-deps with: node-version: 24.14.1 - name: Setup Playwright Browsers uses: ./.github/actions/setup-playwright-browsers with: browsers: chromium firefox webkit ``` -------------------------------- ### Run tests for mode, sdk-server, and view-entry-law Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-10-08-agent-control/plans/04-outside-surface-plan.md Commands to verify the changes. Run each test sequentially; the last test proves that importing src/view/agent-runtime.ts from src/mcp/opener.ts is allowed by 01's exception. ```bash yarn test test/unit/mcp/mode.test.ts ``` ```bash yarn test test/unit/mcp/sdk-server.test.ts ``` ```bash yarn test test/unit/architecture/view-entry-law.test.ts ``` -------------------------------- ### Build fonts and Vite for /verify Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-10-09-database-notion-parity/01-phase-0-foundations.md Build step for /verify: generate fonts and run Vite build in test mode. ```bash node scripts/generate-fonts.mjs && npx vite build --mode test ``` -------------------------------- ### Install @bloklabs/core with npm Source: https://github.com/jackuait/blok/blob/main/README.md Install the core package using npm, yarn, or pnpm. Requires Node 20.19 or newer. ```bash npm install @bloklabs/core # or: yarn add @bloklabs/core / pnpm add @bloklabs/core ``` -------------------------------- ### Build and run live eval replay Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-10-08-agent-control/plans/05-coverage-and-evals-plan.md Commands to build the test bundle and host, start the fixture server, and run the live eval tasks in replay mode. Expects two records with outcome 'pass' after Step 2; before that, writes no records (failing state). ```bash yarn build:test ``` ```bash dotnet build packages/server/dotnet/Blok.Server.Host/Blok.Server.Host.csproj --configuration Release --output .eval-server ``` ```bash export BLOK_CONFORMANCE_SERVER=$PWD/.eval-server/Blok.Server.Host ``` ```bash npx serve . -l 4444 --no-clipboard --no-compression ``` ```bash rm -f /private/tmp/claude-501/eval-live.jsonl*; BLOK_EVAL_REPLAY=1 BLOK_EVAL_TASKS=live-coedit,live-lifecycle BLOK_EVAL_TRIALS=1 BLOK_EVAL_MODEL=replay BLOK_EVAL_EFFORT=high BLOK_EVAL_SCHEMA=envelope BLOK_EVAL_MAX_TOTAL_TOKENS=1 BLOK_EVAL_OUT=/private/tmp/claude-501/eval-live.jsonl yarn vitest run --config test/evals/agent/vitest.evals.config.ts ``` -------------------------------- ### Run unit tests for release-manifest, build-all, and mcp package Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-10-08-agent-control/plans/04-outside-surface-plan.md Run the three unit test files sequentially. Each is expected to pass. ```bash yarn test test/unit/scripts/release-manifest.test.ts ``` ```bash yarn test test/unit/scripts/build-all.test.ts ``` ```bash yarn test test/unit/mcp/package.test.ts ``` -------------------------------- ### Install @bloklabs/vue and @bloklabs/core Source: https://github.com/jackuait/blok/blob/main/packages/vue/README.md Install the Vue bindings and core package. @bloklabs/core and vue are peer dependencies. ```bash npm install @bloklabs/vue @bloklabs/core ``` -------------------------------- ### Bash: Run server with --auth none Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-08-22-backend-service-plan.md Starts the server with --auth none. Expected to exit non-zero with a message naming --auth none. ```bash cd packages/server && go run ./cmd/blok-server --listen 0.0.0.0:4000 --auth none ``` -------------------------------- ### Install @bloklabs/cli locally as a dev dependency Source: https://github.com/jackuait/blok/blob/main/packages/cli/README.md Install the CLI as a local development dependency using npm. This is useful for project-specific usage. ```bash npm install --save-dev @bloklabs/cli ``` -------------------------------- ### Run affected suites, build, and lint (Step 4) Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-08-24-dotnet-runtime-probe-plan.md Runs the unit tests, builds the runtime, and lints changed files with ESLint. ```bash yarn vitest run --project=unit test/unit/scripts/build-server-runtime.test.ts test/unit/scripts/build-all.test.ts node scripts/build-server-runtime.mjs npx eslint scripts/build-server-runtime.mjs scripts/build-all.mjs test/unit/scripts/build-server-runtime.test.ts test/unit/scripts/build-all.test.ts --max-warnings=0 ``` -------------------------------- ### Run tests and lint after implementation Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-08-23-editor-server-wiring-plan.md Commands to run the bookmark unit test and lint the modified source file after implementing the fallback. ```bash yarn test test/unit/tools/link/bookmark.test.ts ``` ```bash yarn lint src/tools/link/bookmark/index.ts ``` -------------------------------- ### Install @bloklabs/angular and @bloklabs/core Source: https://github.com/jackuait/blok/blob/main/packages/angular/README.md Install the Angular bindings and core package. @bloklabs/core and @angular/core, @angular/common, and @angular/forms are peer dependencies. ```bash npm install @bloklabs/angular @bloklabs/core ``` -------------------------------- ### Install and run @bloklabs/cli with npx Source: https://github.com/jackuait/blok/blob/main/packages/cli/README.md Run the CLI directly with npx to see its help message. This is the quickest way to try the tool without installing it locally. ```bash npx @bloklabs/cli --help ``` -------------------------------- ### Run .NET test project and Go reference suite Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-08-24-dotnet-runtime-probe-plan.md Re-run the .NET test project and Go reference suite. ```bash dotnet test packages/server/dotnet/Blok.Server.Tests/Blok.Server.Tests.csproj ``` ```bash (cd packages/server && go vet ./... && go test ./...) ``` -------------------------------- ### Local proof on oldest tag: checkout, overlay, build, snapshot Source: https://github.com/jackuait/blok/blob/main/docs/superpowers/plans/2026-10-05-docs-versioning.md Commands to verify the overlay works on the oldest tag v1.7.0. Runs the overlay CLI, installs dependencies, builds, and creates a snapshot tarball. Expected exit 0; repeat for v1.15.2 with different --base values. ```bash cd ~/Packages/.blok-undo/wt/docs-v16 && git checkout -f v1.7.0 && git clean -fdq -e node_modules node /Users/jackuait/Packages/blok/docs/scripts/apply-versioning-overlay.mjs --tag-docs docs --source-docs /Users/jackuait/Packages/blok/docs yarn install --immutable && yarn build && (cd docs && yarn install --frozen-lockfile) node docs/scripts/build-snapshot.mjs --version 1.7 --base /v/1.7/ --out /tmp/claude-501/docsver/v1.7.tgz ``` -------------------------------- ### Run codemod with locally installed @bloklabs/core Source: https://github.com/jackuait/blok/blob/main/codemod/README.md Command to run the codemod directly when @bloklabs/core is already installed in the project. Uses npx without the -p flag. ```bash npx migrate-from-editorjs ./src --dry-run ``` -------------------------------- ### Darkroom shell: apply() and cancel() actions Source: https://github.com/jackuait/blok/blob/main/docs/superpowers/plans/2026-09-30-image-darkroom.md apply() finishes and leaves with the result or full rect, calling onApply. cancel() resets view to start rect and leaves with start rect, calling onCancel. ```typescript const apply = (): void => { if (doneBtn.disabled) return; const result = finish(); leave(result ?? FULL_RECT, roundOf(st.def.shape), () => opts.onApply(result)); }; const cancel = (): void => { const f = fitFrame(rectAspect(startRect, st.natural), st.stage, PAD); view.jump({ ...rectToCamera(startRect, st.natural, f), ...f }); leave({ ...startRect }, roundOf(initialDef.shape), () => opts.onCancel()); }; ``` -------------------------------- ### TabSync test setup - instantiate with fake platform and config Source: https://github.com/jackuait/blok/blob/main/docs/superpowers/plans/2026-10-03-tab-sync.md Shows how to build a TabSync under test: create with config and EventsDispatcher, assign the fake Blok via a cast through unknown, and set the fake platform. The cast is the only allowed one in this file because the fake implements only what TabSync touches. Config uses expandPersistenceConfig with a load returning null and a save returning version 'v-next'. ```TypeScript const sync = new TabSync({ config, eventsDispatcher: new EventsDispatcher() }); sync.state = fakeBlok as unknown as BlokModules; sync.setPlatform(platform); ``` ```TypeScript { documentId: 'doc', persistence: expanded } ``` ```TypeScript expanded = expandPersistenceConfig({ persistence: { load: async () => null, save: vi.fn(async () => ({ version: 'v-next' })) } }).persistence ``` -------------------------------- ### Run tests for tool descriptions, document schema, and purity Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-10-08-agent-control/plans/02-tool-self-description-plan.md Run these three test commands one at a time to verify the new descriptions and schema changes. All should pass after implementation. ```bash yarn test test/unit/shared/tool-descriptions/descriptions.test.ts ``` ```bash yarn test test/unit/view/document-schema.test.ts ``` ```bash yarn test test/unit/view/index.purity.test.ts ``` -------------------------------- ### Darkroom shell: photo load/error listeners and immediate start Source: https://github.com/jackuait/blok/blob/main/docs/superpowers/plans/2026-09-30-image-darkroom.md Attaches load and error event listeners to the photo element, sets its source, and starts immediately if the image is already complete with natural width. ```typescript photo.addEventListener('load', start); photo.addEventListener('error', fail); photo.src = opts.url; if (photo.complete && photo.naturalWidth > 0) start(); ``` -------------------------------- ### Run supabaseStorage test Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-08-23-storage-presets-plan.md Command to run the test suite for the supabaseStorage preset. Expected to fail initially because the module does not exist yet. ```bash yarn workspace @bloklabs/presets test src/supabase.test.ts ``` -------------------------------- ### Run blobstore and upload tests Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-08-22-backend-service-plan.md Runs the Go tests for the blobstore and httpapi packages, filtering to tests matching 'LocalDir|Upload'. Expected to fail initially because the blobstore package does not exist and Options has no Store field. ```bash cd packages/server && go test ./internal/blobstore/ ./internal/httpapi/ -run 'LocalDir|Upload' ``` -------------------------------- ### Install @bloklabs/core with framework adapter Source: https://github.com/jackuait/blok/blob/main/README.md Install the core package and one framework adapter (React, Vue, or Angular) to keep versions in lockstep and avoid bundling the editor engine twice. ```bash npm install @bloklabs/core @bloklabs/react # or @bloklabs/vue / @bloklabs/angular ``` -------------------------------- ### Presence test: signals activity once on start and then at most once a minute Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-09-08-collaboration-activity-server.md Failing test for the 60-second activity gate in presence.ts. Uses vi.setSystemTime to control time, expects onActivity to fire once on start, then at most once per minute after caret moves. ```typescript it('signals activity once on start and then at most once a minute', () => { vi.setSystemTime(new Date(1_700_000_000_000)); const onActivity = vi.fn(); const { target, presence } = setup({ onActivity }); presence.start(); expect(onActivity).toHaveBeenCalledTimes(1); vi.setSystemTime(new Date(1_700_000_030_000)); moveCaret(target); vi.advanceTimersByTime(200); expect(onActivity).toHaveBeenCalledTimes(1); vi.setSystemTime(new Date(1_700_000_061_000)); moveCaret(target); vi.advanceTimersByTime(200); expect(onActivity).toHaveBeenCalledTimes(2); }); ``` -------------------------------- ### Program.cs: Configure Blok server, auth, and page routes Source: https://github.com/jackuait/blok/blob/main/docs/maintainers/page-csharp-host.md Wires up the Blok server for a C# host. Requires the Blok:DocEndpointAuth and Blok:SelfUrl configuration values, throwing InvalidOperationException if unset. Registers PageStore, OtherDocuments, PageEvents, and DrainOnStop services, configures Blok documents with a 30-second timeout before AddBlokServer, enables collaboration with optional journal and directory settings, sets the doc endpoint and auth, and adds cookie authentication with custom redirect handling for /api/* paths. Maps the Blok server, pages, and document routes, then runs the app. ```csharp // File: Program.cs using Blok.Server.AspNetCore; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using PageHost; var builder = WebApplication.CreateBuilder(args); // The doc routes are guarded by this secret alone, so it must be set. var docAuth = builder.Configuration["Blok:DocEndpointAuth"] ?? throw new InvalidOperationException("Blok:DocEndpointAuth is not set"); // Where the rooms reach this app's doc routes. Plain HTTP is accepted only for // loopback, so this must be a loopback address Kestrel really listens on. // A wrong port fails every first open with 4503. var selfUrl = builder.Configuration["Blok:SelfUrl"] ?? throw new InvalidOperationException("Blok:SelfUrl is not set"); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddHostedService(); // Before AddBlokServer: it registers the converter with TryAdd, so a call // after it is silently ignored. The longer timeout is for pageIndex. builder.Services.AddBlokDocuments(timeout: TimeSpan.FromSeconds(30)); builder.Services .AddBlokServer(options => { options.CollabEnabled = true; options.CollabJournal = builder.Configuration.GetValue("Blok:Journal"); options.CollabDirectory = builder.Configuration["Blok:CollabDirectory"] ?? "./blok-collab"; options.DocEndpoint = $"{selfUrl}/internal/blok-docs"; options.DocEndpointAuth = docAuth; }) .UseAuthorization(); // Your sign-in. The page routes, MapBlokServer and PageRules read the user's // NameIdentifier claim from it. builder.Services .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { // A login redirect reaches fetch() as a followed 404, and the page tool // would show "Page not found" for an expired session. Answer /api/* with // a status instead. options.Events.OnRedirectToLogin = context => ApiStatus(context, StatusCodes.Status401Unauthorized); options.Events.OnRedirectToAccessDenied = context => ApiStatus(context, StatusCodes.Status403Forbidden); }); builder.Services.AddAuthorization(); var app = builder.Build(); app.UseAuthentication(); app.UseAuthorization(); app.UseWebSockets(); app.MapBlokServer("/api/blok").RequireAuthorization(); app.MapPages("/api/pages"); app.MapPageDocuments("/internal/blok-docs", docAuth); app.Run(); static Task ApiStatus(RedirectContext context, int status) { if (context.Request.Path.StartsWithSegments("/api")) { context.Response.StatusCode = status; } else { context.Response.Redirect(context.RedirectUri); } return Task.CompletedTask; } ``` -------------------------------- ### Widen setup options type in presence-renderer.test.ts Source: https://github.com/jackuait/blok/blob/main/docs/plans/2026-10-08-agent-control/plans/03-in-app-surface-plan.md Adds optional translate, isLocalAnonymous, resolvePersonName, and resolveAgentInput options to the setup function's options type. resolveAgentInput is used in Task 24 and passing undefined is harmless before then. ```TypeScript translate?: (key: string, vars?: Record) => string; isLocalAnonymous?: () => boolean; resolvePersonName?: (userId: string) => string | null; resolveAgentInput?: (blockId: string, field: string) => number | null; ```