From 7df6752eeb21f59125430e467efef688438a20b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20Andr=C3=A9-Micolon?= Date: Mon, 23 Nov 2026 04:49:47 +0000 Subject: [PATCH 01/12] feat: expose typed browser PDF building and documentation --- .changeset/build-pdf-browser.md | 6 + embed/README.md | 6 +- embed/embed-api.json | 1524 +++++++++++++++++++++++++-- embed/etc/index.api.md | 161 +++ embed/etc/protocol.api.md | 24 +- embed/etc/schemas.api.md | 51 + embed/etc/tanstack-ai.api.md | 2 +- embed/etc/tools.api.md | 47 + embed/scripts/generate.mjs | 1 + embed/src/bridge.ts | 2 + embed/src/generated/contract.ts | 30 +- embed/src/generated/drift.ts | 2 + embed/src/generated/method-names.ts | 2 +- embed/src/generated/schemas.ts | 34 + embed/src/generated/tools.ts | 2 + embed/src/generated/webmcp-tools.ts | 27 +- embed/src/tools.ts | 6 + embed/src/types.ts | 10 + embed/src/webmcp.ts | 65 ++ embed/test/helpers.ts | 2 + embed/test/mount.test.ts | 2 +- embed/test/tanstack-ai.test.ts | 8 +- embed/test/tools.test.ts | 22 +- embed/test/webmcp.test.ts | 44 + embed/tsup.config.ts | 1 + react/src/embed-pdf.tsx | 2 + 26 files changed, 1970 insertions(+), 113 deletions(-) create mode 100644 .changeset/build-pdf-browser.md diff --git a/.changeset/build-pdf-browser.md b/.changeset/build-pdf-browser.md new file mode 100644 index 00000000..05c6fff6 --- /dev/null +++ b/.changeset/build-pdf-browser.md @@ -0,0 +1,6 @@ +--- +'@simplepdf/embed': minor +'@simplepdf/react-embed-pdf': minor +--- + +Add typed browser PDF building, task documentation and revision-bound inspection. Build results discriminate job status and WebMCP returns inspection images separately from text. Existing field operations keep their contracts. diff --git a/embed/README.md b/embed/README.md index 6e992a79..20aa521a 100644 --- a/embed/README.md +++ b/embed/README.md @@ -170,6 +170,8 @@ else r.error.code // a closed BridgeErrorCode `embed.actions.*`: method names + arguments are camelCase (the snake_case wire is generated + transformed for you; [`/embed/json`](https://simplepdf.com/embed/json) or `@simplepdf/embed/schemas` carry every field): ```ts +await embed.actions.getDocumentation({ topic: 'build_pdf' }) +await embed.actions.buildPdf({ action: 'build', code: '= Hello', idempotencyKey: 'draft-1', inspect: {} }) await embed.actions.loadDocument({ dataUrl, name, page }) await embed.actions.goTo({ page: 3 }) await embed.actions.selectTool({ tool: 'TEXT' }) // 'CHECKBOX' | 'SIGNATURE' | 'PICTURE' | 'COMB_TEXT' | null @@ -184,7 +186,9 @@ await embed.actions.rotatePage({ page: 1 }) await embed.actions.download() ``` -Full set: `batchSetFieldValues`, `createField`, `deleteFields`, `deletePages`, `detectFields`, `download`, `focusField`, `getAnnotatedPage`, `getDocumentContent`, `getFields`, `goTo`, `loadDocument`, `movePage`, `rotatePage`, `selectTool`, `setFieldValue`, `submit`. +Full set: `buildPdf`, `getDocumentation`, `batchSetFieldValues`, `createField`, `deleteFields`, `deletePages`, `detectFields`, `download`, `focusField`, `getAnnotatedPage`, `getDocumentContent`, `getFields`, `goTo`, `loadDocument`, `movePage`, `rotatePage`, `selectTool`, `setFieldValue`, `submit`. + +PDF building requires an empty editor. Successful builds publish automatically; queued/running results carry the job ID for polling. Results discriminate by `status`; compilation failures carry repair diagnostics inside `error`. Manual edits block replacement. Bind later inspection with `expectedBuildSessionId` and `expectedRevision`. The WebMCP projection carries compound inspection PNGs as image blocks. Documentation returns an index or one English topic, discriminated by `kind`. Building never downloads or shares the document. **"Fill and read this document for me"** is just these operations in sequence, exactly what the agentic tools expose to a model: diff --git a/embed/embed-api.json b/embed/embed-api.json index 65df2c4f..8fe6fdaf 100644 --- a/embed/embed-api.json +++ b/embed/embed-api.json @@ -1,5 +1,4 @@ { - "editor_version": "6f020890-20261114T210959Z", "description": "This is the SimplePDF editor interface contract. Drive the editor programmatically over window.postMessage with the editor iframe: post a JSON string { \"type\": {{operation request_type}}, \"request_id\": {{a request correlation id you generate}}, \"data\": {{input matching input_schema}} } to the iframe; the editor replies with { \"type\": \"REQUEST_RESULT\", \"data\": { \"request_id\": {{the same correlation id}}, \"result\": {{result}} } } (match each reply to its request by this id), where result is { \"success\": true, \"data\": {{a value matching the operation's output_schema; null for ops that return nothing}} } or { \"success\": false, \"error\": { code, message } }. Each operation lists the op-specific `error_codes` it can return; on top of those, any op may also fail with a gateway/permission code (origin/plan/signup gating, editor-not-ready, or an internal error). Every code is within `editor_error_schema` (the complete closed union to narrow against), where each code const carries a `description` of its meaning. Outbound events (see `events`) are pushed the same way. `operations` lists every operation the editor supports. Most require the embedding origin to be allowlisted (\"whitelisted\") for the tenant in the SimplePDF admin dashboard, and the tenant plan to permit them (LOAD_DOCUMENT is always available). A call the current setup does not permit returns the matching gateway code: forbidden:origin_not_whitelisted when the origin is not allowlisted, or bad_request:plan_upgrade_required when the plan excludes it. All JSON schemas use the json_schema_dialect declared at the root. We recommend the @simplepdf/embed package for a typed, ergonomic wrapper over this contract (https://github.com/SimplePDF/simplepdf-embed).", "json_schema_dialect": "https://json-schema.org/draft/2020-12/schema", "protocol": { @@ -18,7 +17,11 @@ "description": "The operation's input payload, matching that operation's input_schema." } }, - "required": ["type", "request_id", "data"] + "required": [ + "type", + "request_id", + "data" + ] }, "result_envelope_schema": { "type": "object", @@ -47,35 +50,1149 @@ "description": "Matches the operation's output_schema; null for ops that return nothing." } }, - "required": ["success", "data"] + "required": [ + "success", + "data" + ] + }, + { + "type": "object", + "properties": { + "success": { + "type": "boolean", + "const": false + }, + "error": { + "description": "The error object when success is false: a `code` plus a human-readable `message` (with typed `details` for bad_request:batch_validation_failed and bad_request:missing_required_fields). Its full shape and code set are editor_error_schema, where each code const carries a description of its meaning." + } + }, + "required": [ + "success", + "error" + ] + } + ] + } + }, + "required": [ + "request_id", + "result" + ] + } + }, + "required": [ + "type", + "data" + ] + }, + "correlation": { + "id_field": "request_id", + "generated_by": "consumer" + } + }, + "operations": [ + { + "request_type": "BUILD_PDF", + "description": "Build and display a PDF locally from Typst code. Read get_documentation for task recipes, templates, fonts and limits. Request inspect:{} for revision-bound page images in the same response. Use a stable idempotency key; poll the job if needed. Inspect the successful revision with simplepdf_embed_get_annotated_page. Manual edits block replacement. Does not submit or share.", + "input_schema": { + "description": "Build and display a PDF locally from Typst code. Read get_documentation for task recipes, templates, fonts and limits. Request inspect:{} for revision-bound page images in the same response. Use a stable idempotency key; poll the job if needed. Inspect the successful revision with simplepdf_embed_get_annotated_page. Manual edits block replacement. Does not submit or share.", + "anyOf": [ + { + "type": "object", + "properties": { + "action": { + "type": "string", + "const": "build" + }, + "inspect": { + "type": "object", + "properties": { + "pages": { + "type": "array", + "items": { + "type": "integer" + } + } + } + }, + "code": { + "type": "string" + }, + "idempotency_key": { + "type": "string" + }, + "build_session_id": { + "type": "string" + }, + "base_revision": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "assets": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "string" + }, + "data_url": { + "type": "string" + } + }, + "required": [ + "path", + "data_url" + ] + } + }, + "wait_ms": { + "type": "integer" + } + }, + "required": [ + "action", + "code", + "idempotency_key" + ] + }, + { + "type": "object", + "properties": { + "action": { + "type": "string", + "const": "status" + }, + "job_id": { + "type": "string" + }, + "wait_ms": { + "type": "integer" + }, + "inspect": { + "type": "object", + "properties": { + "pages": { + "type": "array", + "items": { + "type": "integer" + } + } + } + } + }, + "required": [ + "action", + "job_id" + ] + }, + { + "type": "object", + "properties": { + "action": { + "type": "string", + "const": "cancel" + }, + "job_id": { + "type": "string" + } + }, + "required": [ + "action", + "job_id" + ] + } + ] + }, + "output_schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "job_id": { + "type": "string" + }, + "build_session_id": { + "type": "string" + }, + "revision": { + "type": "integer" + }, + "published_revision": { + "type": "integer" + }, + "status": { + "type": "string", + "const": "queued" + }, + "poll_after_ms": { + "type": "integer" + } + }, + "required": [ + "job_id", + "build_session_id", + "revision", + "published_revision", + "status", + "poll_after_ms" + ] + }, + { + "type": "object", + "properties": { + "job_id": { + "type": "string" + }, + "build_session_id": { + "type": "string" + }, + "revision": { + "type": "integer" + }, + "published_revision": { + "type": "integer" + }, + "status": { + "type": "string", + "const": "running" + }, + "stage": { + "type": "string", + "enum": [ + "queued", + "initializing", + "compiling", + "validating", + "loading", + "ready" + ] + }, + "poll_after_ms": { + "type": "integer" + } + }, + "required": [ + "job_id", + "build_session_id", + "revision", + "published_revision", + "status", + "stage", + "poll_after_ms" + ] + }, + { + "type": "object", + "properties": { + "job_id": { + "type": "string" + }, + "build_session_id": { + "type": "string" + }, + "revision": { + "type": "integer" + }, + "published_revision": { + "type": "integer" + }, + "status": { + "type": "string", + "const": "succeeded" + }, + "page_count": { + "type": "integer" + }, + "warnings": { + "type": "array", + "items": { + "type": "object", + "properties": { + "severity": { + "type": "string", + "const": "warning" + }, + "code": { + "type": "string", + "enum": [ + "typst", + "unsupported_dependency" + ] + }, + "message": { + "type": "string" + }, + "file": { + "type": "string" + }, + "line": { + "type": "integer" + }, + "column": { + "type": "integer" + }, + "hint": { + "type": "string" + } + }, + "required": [ + "severity", + "code", + "message" + ] + } + }, + "warnings_truncated": { + "type": "boolean" + }, + "inspection": { + "anyOf": [ + { + "type": "object", + "properties": { + "success": { + "type": "boolean", + "const": true + }, + "data": { + "type": "object", + "properties": { + "pages": { + "type": "array", + "items": { + "type": "object", + "properties": { + "build_session_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "revision": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + }, + "editor_state_version": { + "type": "integer" + }, + "page": { + "type": "integer", + "description": "1-based page position this render shows." + }, + "image_data_url": { + "type": "string", + "description": "PNG render of the page as a data URL, with every field outlined and a numbered badge drawn inside it on the right, or just to its left when the field is too small to hold it." + }, + "image_width": { + "type": "integer", + "description": "Render width in pixels." + }, + "image_height": { + "type": "integer", + "description": "Render height in pixels." + }, + "badges": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "Badge number (as drawn on the render) to field_id, for every field on the page." + } + }, + "required": [ + "build_session_id", + "revision", + "editor_state_version", + "page", + "image_data_url", + "image_width", + "image_height", + "badges" + ] + } + }, + "omitted_pages": { + "type": "array", + "items": { + "type": "integer" + } + } + }, + "required": [ + "pages", + "omitted_pages" + ] + } + }, + "required": [ + "success", + "data" + ] + }, + { + "type": "object", + "properties": { + "success": { + "type": "boolean", + "const": false + }, + "error": { + "anyOf": [ + { + "type": "object", + "properties": { + "code": { + "type": "string", + "const": "bad_request:batch_validation_failed", + "description": "At least one update of batch_set_field_values was rejected, so no field changed. details.failures lists every rejected update with its field_id and the set_field_value code and message explaining why." + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "properties": { + "failures": { + "type": "array", + "items": { + "type": "object", + "properties": { + "field_id": { + "type": "string" + }, + "code": { + "anyOf": [ + { + "type": "string", + "const": "bad_request:field_not_found", + "description": "No field on the loaded document matches the provided field_id." + }, + { + "type": "string", + "const": "bad_request:invalid_signature_url", + "description": "The signature value is not a valid, reachable image URL." + }, + { + "type": "string", + "const": "bad_request:invalid_value", + "description": "The provided value is missing or not valid for this operation or field type." + }, + { + "type": "string", + "const": "bad_request:read_only", + "description": "The document or field is read-only and cannot be modified." + } + ] + }, + "message": { + "type": "string" + } + }, + "required": [ + "field_id", + "code", + "message" + ] + } + } + }, + "required": [ + "failures" + ] + } + }, + "required": [ + "code", + "message", + "details" + ] + }, + { + "type": "object", + "properties": { + "code": { + "type": "string", + "const": "bad_request:missing_required_fields", + "description": "Submission was blocked because required fields are unfilled. details.unfilled_required_fields_count reports how many remain." + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "properties": { + "unfilled_required_fields_count": { + "type": "integer" + } + }, + "required": [ + "unfilled_required_fields_count" + ] + } + }, + "required": [ + "code", + "message", + "details" + ] + }, + { + "type": "object", + "properties": { + "code": { + "anyOf": [ + { + "type": "string", + "const": "conflict:build_session_mismatch", + "description": "Different editor session. Read the guide again." + }, + { + "type": "string", + "const": "conflict:base_revision_mismatch", + "description": "Published revision changed. Inspect before rebuilding." + }, + { + "type": "string", + "const": "conflict:idempotency_key_reused", + "description": "Different input for this key. Use a new key." + }, + { + "type": "string", + "const": "conflict:editor_modified", + "description": "Edits block rebuilding. Start a new session in an empty editor." + }, + { + "type": "string", + "const": "conflict:unmanaged_document", + "description": "Open an empty editor before building." + }, + { + "type": "string", + "const": "not_found:job", + "description": "Unknown job in this editor session." + }, + { + "type": "string", + "const": "not_found:job_expired", + "description": "Job expired. Its key cannot be reused." + }, + { + "type": "string", + "const": "resource:session_limit", + "description": "Session job limit reached. Open an empty editor." + }, + { + "type": "string", + "const": "conflict:inspection_revision_mismatch", + "description": "The requested revision is not displayed." + }, + { + "type": "string", + "const": "conflict:inspection_state_changed", + "description": "The editor changed during inspection. Inspect again." + }, + { + "type": "string", + "const": "bad_request:download_blocked", + "description": "The browser blocked delivering the generated document (share sheet or new tab denied without a user gesture, or a popup blocker). Retry the download from a direct user interaction." + }, + { + "type": "string", + "const": "bad_request:editor_not_ready", + "description": "The editor is still initializing and cannot accept this operation yet. Retry the operation shortly." + }, + { + "type": "string", + "const": "bad_request:event_not_allowed", + "description": "This operation is not available in this context (the portal configuration or this page does not offer it); the message says why." + }, + { + "type": "string", + "const": "bad_request:failed_to_load_document", + "description": "The document LOAD_DOCUMENT was given could not be loaded (unreachable, not a PDF or image, corrupted, password-protected, superseded by another load, or the editor could not prepare it: the server never resolved it, storing it failed, or it carries more form fields than a document can); the message says which." + }, + { + "type": "string", + "const": "bad_request:field_not_found", + "description": "No field on the loaded document matches the provided field_id." + }, + { + "type": "string", + "const": "bad_request:invalid_dimensions", + "description": "The provided x, y, width, or height is missing or not a valid number." + }, + { + "type": "string", + "const": "bad_request:invalid_event_type", + "description": "The posted message `type` is not a supported operation request_type." + }, + { + "type": "string", + "const": "bad_request:invalid_field_ids", + "description": "field_ids is missing or is not an array of field id strings." + }, + { + "type": "string", + "const": "bad_request:invalid_field_type", + "description": "The provided field type is not one of the supported overlay tool types." + }, + { + "type": "string", + "const": "bad_request:invalid_page", + "description": "page is missing or is not a positive integer." + }, + { + "type": "string", + "const": "bad_request:invalid_signature_url", + "description": "The signature value is not a valid, reachable image URL." + }, + { + "type": "string", + "const": "bad_request:invalid_tool", + "description": "The provided tool is not one of the selectable tools." + }, + { + "type": "string", + "const": "bad_request:invalid_value", + "description": "The provided value is missing or not valid for this operation or field type." + }, + { + "type": "string", + "const": "bad_request:no_document_loaded", + "description": "No document is loaded. Load a document before calling this operation." + }, + { + "type": "string", + "const": "bad_request:page_not_found", + "description": "The referenced page does not exist in the document." + }, + { + "type": "string", + "const": "bad_request:page_out_of_range", + "description": "page is outside the document range (1 to the document page_count)." + }, + { + "type": "string", + "const": "bad_request:plan_upgrade_required", + "description": "The tenant's plan does not include this operation. Upgrade the plan in the SimplePDF admin dashboard." + }, + { + "type": "string", + "const": "bad_request:read_only", + "description": "The document or field is read-only and cannot be modified." + }, + { + "type": "string", + "const": "bad_request:signup_required", + "description": "This operation requires the end user to sign up or authenticate first at https://simplepdf.com/auth/signup." + }, + { + "type": "string", + "const": "forbidden:editing_not_allowed", + "description": "Editing is disabled for this document or configuration; field-mutating operations are rejected." + }, + { + "type": "string", + "const": "forbidden:origin_not_whitelisted", + "description": "The embedding origin is not allowlisted for this tenant, or is not the allowlisted origin the editor was loaded from. Allowlist it in the SimplePDF admin dashboard and let the embedding page's Referer reach the editor." + }, + { + "type": "string", + "const": "forbidden:whitelist_required", + "description": "This tenant requires the embedding origin to be allowlisted before any operation is accepted. Configure it in the admin dashboard." + }, + { + "type": "string", + "const": "unexpected:internal_error", + "description": "An unexpected internal error occurred. Try again, and if the issue persists, reach out to support@simplepdf.com." + } + ] + }, + "message": { + "type": "string" + } + }, + "required": [ + "code", + "message" + ] + } + ] + } + }, + "required": [ + "success", + "error" + ] + } + ] + } + }, + "required": [ + "job_id", + "build_session_id", + "revision", + "published_revision", + "status", + "page_count", + "warnings", + "warnings_truncated" + ] + }, + { + "type": "object", + "properties": { + "job_id": { + "type": "string" + }, + "build_session_id": { + "type": "string" + }, + "revision": { + "type": "integer" + }, + "published_revision": { + "type": "integer" + }, + "status": { + "type": "string", + "const": "failed" + }, + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "unsupported_dependency", + "engine_initialization_failed", + "compile_error", + "compile_timeout", + "job_timeout", + "resource_limit", + "invalid_pdf", + "editor_load_failed", + "editor_conflict", + "worker_crashed", + "internal_error" + ] + }, + "message": { + "type": "string" + }, + "stage": { + "type": "string", + "enum": [ + "queued", + "initializing", + "compiling", + "validating", + "loading", + "ready" + ] + }, + "retryable": { + "type": "boolean" + }, + "diagnostics": { + "type": "array", + "items": { + "type": "object", + "properties": { + "severity": { + "type": "string", + "enum": [ + "error", + "warning" + ] + }, + "code": { + "type": "string", + "enum": [ + "typst", + "unsupported_dependency" + ] + }, + "message": { + "type": "string" + }, + "file": { + "type": "string" + }, + "line": { + "type": "integer" + }, + "column": { + "type": "integer" + }, + "hint": { + "type": "string" + } + }, + "required": [ + "severity", + "code", + "message" + ] + } + }, + "diagnostics_truncated": { + "type": "boolean" + } + }, + "required": [ + "code", + "message", + "stage", + "retryable", + "diagnostics", + "diagnostics_truncated" + ] + } + }, + "required": [ + "job_id", + "build_session_id", + "revision", + "published_revision", + "status", + "error" + ] + }, + { + "type": "object", + "properties": { + "job_id": { + "type": "string" + }, + "build_session_id": { + "type": "string" + }, + "revision": { + "type": "integer" + }, + "published_revision": { + "type": "integer" + }, + "status": { + "type": "string", + "const": "cancelled" + } + }, + "required": [ + "job_id", + "build_session_id", + "revision", + "published_revision", + "status" + ] + }, + { + "type": "object", + "properties": { + "job_id": { + "type": "string" + }, + "build_session_id": { + "type": "string" + }, + "revision": { + "type": "integer" + }, + "published_revision": { + "type": "integer" + }, + "status": { + "type": "string", + "const": "superseded" + } + }, + "required": [ + "job_id", + "build_session_id", + "revision", + "published_revision", + "status" + ] + } + ] + }, + "error_codes": [ + "conflict:build_session_mismatch", + "conflict:base_revision_mismatch", + "conflict:idempotency_key_reused", + "conflict:editor_modified", + "conflict:unmanaged_document", + "not_found:job", + "not_found:job_expired", + "resource:session_limit", + "conflict:inspection_revision_mismatch", + "conflict:inspection_state_changed", + "bad_request:invalid_value", + "forbidden:editing_not_allowed" + ], + "tool": { + "name": "build_pdf", + "description": "Build and display a PDF locally from Typst code. Read get_documentation for task recipes, templates, fonts and limits. Request inspect:{} for revision-bound page images in the same response. Use a stable idempotency key; poll the job if needed. Inspect the successful revision with simplepdf_embed_get_annotated_page. Manual edits block replacement. Does not submit or share.", + "input_schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "action": { + "type": "string", + "const": "build" + }, + "inspect": { + "type": "object", + "properties": { + "pages": { + "type": "array", + "items": { + "type": "integer" + } + } + } + }, + "code": { + "type": "string" + }, + "idempotency_key": { + "type": "string" + }, + "build_session_id": { + "type": "string" + }, + "base_revision": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "assets": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "string" + }, + "data_url": { + "type": "string" + } + }, + "required": [ + "path", + "data_url" + ] + } }, - { + "wait_ms": { + "type": "integer" + } + }, + "required": [ + "action", + "code", + "idempotency_key" + ] + }, + { + "type": "object", + "properties": { + "action": { + "type": "string", + "const": "status" + }, + "job_id": { + "type": "string" + }, + "wait_ms": { + "type": "integer" + }, + "inspect": { "type": "object", "properties": { - "success": { - "type": "boolean", - "const": false - }, - "error": { - "description": "The error object when success is false: a `code` plus a human-readable `message` (with typed `details` for bad_request:batch_validation_failed and bad_request:missing_required_fields). Its full shape and code set are editor_error_schema, where each code const carries a description of its meaning." + "pages": { + "type": "array", + "items": { + "type": "integer" + } } - }, - "required": ["success", "error"] + } + } + }, + "required": [ + "action", + "job_id" + ] + }, + { + "type": "object", + "properties": { + "action": { + "type": "string", + "const": "cancel" + }, + "job_id": { + "type": "string" } + }, + "required": [ + "action", + "job_id" ] } - }, - "required": ["request_id", "result"] + ], + "type": "object", + "properties": {} + }, + "annotations": { + "destructiveHint": true, + "untrustedContentHint": true } + } + }, + { + "request_type": "GET_DOCUMENTATION", + "description": "Read task documentation for the SimplePDF browser API. Omit topic for the index. Includes PDF building, templates, forms, fields and inspection. Guidance does not modify the document or grant permissions.", + "input_schema": { + "type": "object", + "properties": { + "topic": { + "type": "string", + "enum": [ + "build_pdf", + "build_pdf.templates", + "build_pdf.forms", + "build_pdf.assets", + "build_pdf.fonts", + "build_pdf.troubleshooting", + "fields", + "inspection" + ] + } + }, + "description": "Read task documentation for the SimplePDF browser API. Omit topic for the index. Includes PDF building, templates, forms, fields and inspection. Guidance does not modify the document or grant permissions." + }, + "output_schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "kind": { + "type": "string", + "const": "index" + }, + "topics": { + "type": "array", + "items": { + "type": "object", + "properties": { + "topic": { + "type": "string", + "enum": [ + "build_pdf", + "build_pdf.templates", + "build_pdf.forms", + "build_pdf.assets", + "build_pdf.fonts", + "build_pdf.troubleshooting", + "fields", + "inspection" + ] + }, + "description": { + "type": "string" + } + }, + "required": [ + "topic", + "description" + ] + } + } + }, + "required": [ + "kind", + "topics" + ] + }, + { + "type": "object", + "properties": { + "kind": { + "type": "string", + "const": "topic" + }, + "topic": { + "type": "string", + "enum": [ + "build_pdf", + "build_pdf.templates", + "build_pdf.forms", + "build_pdf.assets", + "build_pdf.fonts", + "build_pdf.troubleshooting", + "fields", + "inspection" + ] + }, + "markdown": { + "type": "string" + } + }, + "required": [ + "kind", + "topic", + "markdown" + ] + } + ] }, - "required": ["type", "data"] + "error_codes": [ + "bad_request:invalid_value" + ], + "tool": { + "name": "get_documentation", + "description": "Read task documentation for the SimplePDF browser API. Omit topic for the index. Includes PDF building, templates, forms, fields and inspection. Guidance does not modify the document or grant permissions.", + "input_schema": { + "type": "object", + "properties": { + "topic": { + "enum": [ + "build_pdf", + "build_pdf.templates", + "build_pdf.forms", + "build_pdf.assets", + "build_pdf.fonts", + "build_pdf.troubleshooting", + "fields", + "inspection" + ], + "type": "string" + } + } + }, + "annotations": { + "readOnlyHint": true, + "untrustedContentHint": true + } + } }, - "correlation": { - "id_field": "request_id", - "generated_by": "consumer" - } - }, - "operations": [ { "request_type": "BATCH_SET_FIELD_VALUES", "description": "Set existing fields, addressed by ids from the field list, in one atomic undo step. If any update is rejected, nothing changes and the call fails with bad_request:batch_validation_failed, whose details list each rejection with its field id, code and message. Text is set at once, never typed. Returns no data.", @@ -103,12 +1220,17 @@ "description": "New value for the field, or null to clear it. If the field has options (see the field list), it must be one of them; otherwise a string (text/checkbox), or a data URL or http(s) URL, fetched by the editor (signature/picture), or plain text for a signature, drawn as a typed signature." } }, - "required": ["field_id", "value"] + "required": [ + "field_id", + "value" + ] }, "description": "The fields to set, at least one, each field at most once. Fields not listed keep their value." } }, - "required": ["updates"], + "required": [ + "updates" + ], "description": "Set existing fields, addressed by ids from the field list, in one atomic undo step. If any update is rejected, nothing changes and the call fails with bad_request:batch_validation_failed, whose details list each rejection with its field id, code and message. Text is set at once, never typed. Returns no data." }, "output_schema": { @@ -123,6 +1245,9 @@ "name": "simplepdf_embed_batch_set_field_values", "description": "Set existing fields, addressed by ids from the field list, in one atomic undo step. If any update is rejected, nothing changes and the call fails with bad_request:batch_validation_failed, whose details list each rejection with its field id, code and message. Text is set at once, never typed. Returns no data.", "input_schema": { + "required": [ + "updates" + ], "type": "object", "properties": { "updates": { @@ -145,13 +1270,15 @@ "description": "New value for the field, or null to clear it. If the field has options (see the field list), it must be one of them; otherwise a string (text/checkbox), or a data URL or http(s) URL, fetched by the editor (signature/picture), or plain text for a signature, drawn as a typed signature." } }, - "required": ["field_id", "value"] + "required": [ + "field_id", + "value" + ] }, "description": "The fields to set, at least one, each field at most once. Fields not listed keep their value.", "type": "array" } - }, - "required": ["updates"] + } }, "annotations": { "destructiveHint": false, @@ -167,7 +1294,13 @@ "properties": { "type": { "type": "string", - "enum": ["TEXT", "SIGNATURE", "PICTURE", "CHECKBOX", "COMB_TEXT"], + "enum": [ + "TEXT", + "SIGNATURE", + "PICTURE", + "CHECKBOX", + "COMB_TEXT" + ], "description": "Field type to create." }, "x": { @@ -195,7 +1328,14 @@ "type": "string" } }, - "required": ["type", "x", "y", "width", "height", "page"], + "required": [ + "type", + "x", + "y", + "width", + "height", + "page" + ], "description": "Create a new overlay field on a page. Returns the id of the created field." }, "output_schema": { @@ -205,7 +1345,9 @@ "type": "string" } }, - "required": ["field_id"] + "required": [ + "field_id" + ] }, "error_codes": [ "forbidden:editing_not_allowed", @@ -222,10 +1364,24 @@ "name": "simplepdf_embed_create_field", "description": "Create a new overlay field on a page. Returns the id of the created field.", "input_schema": { + "required": [ + "type", + "x", + "y", + "width", + "height", + "page" + ], "type": "object", "properties": { "type": { - "enum": ["TEXT", "SIGNATURE", "PICTURE", "CHECKBOX", "COMB_TEXT"], + "enum": [ + "TEXT", + "SIGNATURE", + "PICTURE", + "CHECKBOX", + "COMB_TEXT" + ], "description": "Field type to create.", "type": "string" }, @@ -253,8 +1409,7 @@ "description": "Optional initial value. A string for text/checkbox fields; a data URL or http(s) URL (fetched by the editor) for signature/picture fields, or plain text for a signature, drawn as a typed signature.", "type": "string" } - }, - "required": ["type", "x", "y", "width", "height", "page"] + } }, "annotations": { "destructiveHint": false, @@ -289,7 +1444,9 @@ "type": "integer" } }, - "required": ["deleted_count"] + "required": [ + "deleted_count" + ] }, "error_codes": [ "forbidden:editing_not_allowed", @@ -337,7 +1494,9 @@ "description": "1-based page numbers to delete." } }, - "required": ["pages"], + "required": [ + "pages" + ], "description": "Delete pages from the document (it cannot delete every visible page). Returns no data. Destructive." }, "output_schema": { @@ -354,6 +1513,9 @@ "name": "simplepdf_embed_delete_pages", "description": "Delete pages from the document (it cannot delete every visible page). Returns no data. Destructive.", "input_schema": { + "required": [ + "pages" + ], "type": "object", "properties": { "pages": { @@ -363,8 +1525,7 @@ "description": "1-based page numbers to delete.", "type": "array" } - }, - "required": ["pages"] + } }, "annotations": { "destructiveHint": true @@ -386,7 +1547,9 @@ "type": "integer" } }, - "required": ["detected_count"] + "required": [ + "detected_count" + ] }, "error_codes": [ "forbidden:editing_not_allowed", @@ -443,7 +1606,9 @@ "description": "ID of the field to focus and scroll into view." } }, - "required": ["field_id"], + "required": [ + "field_id" + ], "description": "Scroll an existing field into view and focus it, addressed by its id from the field list. Returns a hint describing the user action expected next." }, "output_schema": { @@ -460,10 +1625,15 @@ "type": "string" } }, - "required": ["type", "message"] + "required": [ + "type", + "message" + ] } }, - "required": ["hint"] + "required": [ + "hint" + ] }, "error_codes": [ "bad_request:invalid_value", @@ -474,14 +1644,16 @@ "name": "simplepdf_embed_focus_field", "description": "Scroll an existing field into view and focus it, addressed by its id from the field list. Returns a hint describing the user action expected next.", "input_schema": { + "required": [ + "field_id" + ], "type": "object", "properties": { "field_id": { "description": "ID of the field to focus and scroll into view.", "type": "string" } - }, - "required": ["field_id"] + } }, "annotations": { "destructiveHint": false @@ -497,14 +1669,48 @@ "page": { "type": "integer", "description": "1-based page to render, at its current position." + }, + "expected_build_session_id": { + "type": "string" + }, + "expected_revision": { + "type": "integer" + }, + "expected_editor_state_version": { + "type": "integer" } }, - "required": ["page"], + "required": [ + "page" + ], "description": "Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block." }, "output_schema": { "type": "object", "properties": { + "build_session_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "revision": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + }, + "editor_state_version": { + "type": "integer" + }, "page": { "type": "integer", "description": "1-based page position this render shows." @@ -530,6 +1736,9 @@ } }, "required": [ + "build_session_id", + "revision", + "editor_state_version", "page", "image_data_url", "image_width", @@ -540,20 +1749,34 @@ "error_codes": [ "bad_request:no_document_loaded", "bad_request:invalid_page", - "bad_request:page_out_of_range" + "bad_request:page_out_of_range", + "bad_request:invalid_value", + "conflict:inspection_revision_mismatch", + "conflict:inspection_state_changed" ], "tool": { "name": "simplepdf_embed_get_annotated_page", "description": "Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block.", "input_schema": { + "required": [ + "page" + ], "type": "object", "properties": { "page": { "description": "1-based page to render, at its current position.", "type": "integer" + }, + "expected_build_session_id": { + "type": "string" + }, + "expected_revision": { + "type": "integer" + }, + "expected_editor_state_version": { + "type": "integer" } - }, - "required": ["page"] + } }, "annotations": { "readOnlyHint": true, @@ -570,7 +1793,10 @@ "extraction_mode": { "description": "Extraction strategy: 'auto' (default) or 'ocr' to force optical recognition.", "type": "string", - "enum": ["auto", "ocr"] + "enum": [ + "auto", + "ocr" + ] } }, "description": "Extract the document's content page by page as Markdown, or as plain text when optical recognition is forced. Use it to read what the document says. Returns the document name and each page's content." @@ -593,11 +1819,17 @@ "type": "string" } }, - "required": ["page", "content"] + "required": [ + "page", + "content" + ] } } }, - "required": ["name", "pages"] + "required": [ + "name", + "pages" + ] }, "error_codes": [ "bad_request:invalid_value", @@ -611,7 +1843,10 @@ "properties": { "extraction_mode": { "description": "Extraction strategy: 'auto' (default) or 'ocr' to force optical recognition.", - "enum": ["auto", "ocr"], + "enum": [ + "auto", + "ocr" + ], "type": "string" } } @@ -704,9 +1939,13 @@ } } }, - "required": ["fields"] + "required": [ + "fields" + ] }, - "error_codes": ["bad_request:no_document_loaded"], + "error_codes": [ + "bad_request:no_document_loaded" + ], "tool": { "name": "simplepdf_embed_get_fields", "description": "List every fillable field in the loaded document, including native dropdown and radio AcroFields. Each field reports its id, name, type, page, current value, and the options its value must be one of, if any. Call this first to discover field ids before reading or setting values. To SEE where each field sits on the printed page, render the annotated page. Returns the field list.", @@ -731,7 +1970,9 @@ "description": "1-based page to navigate to." } }, - "required": ["page"], + "required": [ + "page" + ], "description": "Scroll the editor to a page. Returns no data." }, "output_schema": { @@ -746,14 +1987,16 @@ "name": "simplepdf_embed_go_to", "description": "Scroll the editor to a page. Returns no data.", "input_schema": { + "required": [ + "page" + ], "type": "object", "properties": { "page": { "description": "1-based page to navigate to.", "type": "integer" } - }, - "required": ["page"] + } }, "annotations": { "destructiveHint": false @@ -779,7 +2022,9 @@ "type": "integer" } }, - "required": ["data_url"], + "required": [ + "data_url" + ], "description": "Replace the document in the editor with one supplied as a base64 data URL or an http(s) URL the editor fetches. Destructive: the current document and every edit in it are discarded. Replies once the document and its fields are ready, so the next operation can act on it, and DOCUMENT_LOADED follows the reply; the URL already open is left as is and answers once it settles; a document that cannot be loaded or prepared answers bad_request:failed_to_load_document. Returns no data." }, "output_schema": { @@ -794,6 +2039,9 @@ "name": "simplepdf_embed_load_document", "description": "Replace the document in the editor with one supplied as a base64 data URL or an http(s) URL the editor fetches. Destructive: the current document and every edit in it are discarded. Replies once the document and its fields are ready, so the next operation can act on it, and DOCUMENT_LOADED follows the reply; the URL already open is left as is and answers once it settles; a document that cannot be loaded or prepared answers bad_request:failed_to_load_document. Returns no data.", "input_schema": { + "required": [ + "data_url" + ], "type": "object", "properties": { "data_url": { @@ -808,8 +2056,7 @@ "description": "Optional 1-based page to open the document on.", "type": "integer" } - }, - "required": ["data_url"] + } }, "annotations": { "destructiveHint": true, @@ -832,7 +2079,10 @@ "description": "1-based destination position for the page." } }, - "required": ["from_page", "to_page"], + "required": [ + "from_page", + "to_page" + ], "description": "Move a page to another position, reordering the document. Returns no data. Destructive." }, "output_schema": { @@ -849,6 +2099,10 @@ "name": "simplepdf_embed_move_page", "description": "Move a page to another position, reordering the document. Returns no data. Destructive.", "input_schema": { + "required": [ + "from_page", + "to_page" + ], "type": "object", "properties": { "from_page": { @@ -859,8 +2113,7 @@ "description": "1-based destination position for the page.", "type": "integer" } - }, - "required": ["from_page", "to_page"] + } }, "annotations": { "destructiveHint": true @@ -878,7 +2131,9 @@ "description": "1-based page to rotate." } }, - "required": ["page"], + "required": [ + "page" + ], "description": "Rotate a page 90 degrees clockwise. Returns no data. Destructive." }, "output_schema": { @@ -895,14 +2150,16 @@ "name": "simplepdf_embed_rotate_page", "description": "Rotate a page 90 degrees clockwise. Returns no data. Destructive.", "input_schema": { + "required": [ + "page" + ], "type": "object", "properties": { "page": { "description": "1-based page to rotate.", "type": "integer" } - }, - "required": ["page"] + } }, "annotations": { "destructiveHint": true @@ -934,7 +2191,9 @@ "description": "Tool to activate, or null to deselect." } }, - "required": ["tool"], + "required": [ + "tool" + ], "description": "Activate a field-placement tool in the editor toolbar so the user can draw that field type, or pass null to clear the active tool. Returns no data." }, "output_schema": { @@ -948,6 +2207,9 @@ "name": "simplepdf_embed_select_tool", "description": "Activate a field-placement tool in the editor toolbar so the user can draw that field type, or pass null to clear the active tool. Returns no data.", "input_schema": { + "required": [ + "tool" + ], "type": "object", "properties": { "tool": { @@ -968,8 +2230,7 @@ ], "description": "Tool to activate, or null to deselect." } - }, - "required": ["tool"] + } }, "annotations": { "destructiveHint": false @@ -1002,7 +2263,10 @@ "description": "New value for the field, or null to clear it. If the field has options (see the field list), it must be one of them; otherwise a string (text/checkbox), or a data URL or http(s) URL, fetched by the editor (signature/picture), or plain text for a signature, drawn as a typed signature." } }, - "required": ["field_id", "value"], + "required": [ + "field_id", + "value" + ], "description": "Set or clear (null) one existing field, addressed by its id from the field list. Text is typed out unless animate is false. Returns no data." }, "output_schema": { @@ -1019,6 +2283,10 @@ "name": "simplepdf_embed_set_field_value", "description": "Set or clear (null) one existing field, addressed by its id from the field list. Text is typed out unless animate is false. Returns no data.", "input_schema": { + "required": [ + "field_id", + "value" + ], "type": "object", "properties": { "animate": { @@ -1040,8 +2308,7 @@ ], "description": "New value for the field, or null to clear it. If the field has options (see the field list), it must be one of them; otherwise a string (text/checkbox), or a data URL or http(s) URL, fetched by the editor (signature/picture), or plain text for a signature, drawn as a typed signature." } - }, - "required": ["field_id", "value"] + } }, "annotations": { "destructiveHint": false, @@ -1060,7 +2327,9 @@ "description": "When true, the signer also receives a downloaded copy on submit." } }, - "required": ["download_copy"], + "required": [ + "download_copy" + ], "description": "Submit the completed document through the editor's finalization flow. This is irreversible. Fails with bad_request:missing_required_fields when required fields are unfilled. Returns no data." }, "output_schema": { @@ -1075,14 +2344,16 @@ "name": "simplepdf_embed_submit", "description": "Submit the completed document through the editor's finalization flow. This is irreversible. Fails with bad_request:missing_required_fields when required fields are unfilled. Returns no data.", "input_schema": { + "required": [ + "download_copy" + ], "type": "object", "properties": { "download_copy": { "description": "When true, the signer also receives a downloaded copy on submit.", "type": "boolean" } - }, - "required": ["download_copy"] + } }, "annotations": { "destructiveHint": true @@ -1109,7 +2380,9 @@ "type": "string" } }, - "required": ["document_id"] + "required": [ + "document_id" + ] } }, { @@ -1135,7 +2408,11 @@ "type": "integer" } }, - "required": ["previous_page", "current_page", "total_pages"] + "required": [ + "previous_page", + "current_page", + "total_pages" + ] } }, { @@ -1151,11 +2428,23 @@ "type": "string" } }, - "required": ["document_id", "submission_id"] + "required": [ + "document_id", + "submission_id" + ] } } ], - "locales": ["fr", "en", "it", "de", "pt", "es", "ja", "nl"], + "locales": [ + "fr", + "en", + "it", + "de", + "pt", + "es", + "ja", + "nl" + ], "editor_error_schema": { "anyOf": [ { @@ -1208,14 +2497,24 @@ "type": "string" } }, - "required": ["field_id", "code", "message"] + "required": [ + "field_id", + "code", + "message" + ] } } }, - "required": ["failures"] + "required": [ + "failures" + ] } }, - "required": ["code", "message", "details"] + "required": [ + "code", + "message", + "details" + ] }, { "type": "object", @@ -1235,16 +2534,72 @@ "type": "integer" } }, - "required": ["unfilled_required_fields_count"] + "required": [ + "unfilled_required_fields_count" + ] } }, - "required": ["code", "message", "details"] + "required": [ + "code", + "message", + "details" + ] }, { "type": "object", "properties": { "code": { "anyOf": [ + { + "type": "string", + "const": "conflict:build_session_mismatch", + "description": "Different editor session. Read the guide again." + }, + { + "type": "string", + "const": "conflict:base_revision_mismatch", + "description": "Published revision changed. Inspect before rebuilding." + }, + { + "type": "string", + "const": "conflict:idempotency_key_reused", + "description": "Different input for this key. Use a new key." + }, + { + "type": "string", + "const": "conflict:editor_modified", + "description": "Edits block rebuilding. Start a new session in an empty editor." + }, + { + "type": "string", + "const": "conflict:unmanaged_document", + "description": "Open an empty editor before building." + }, + { + "type": "string", + "const": "not_found:job", + "description": "Unknown job in this editor session." + }, + { + "type": "string", + "const": "not_found:job_expired", + "description": "Job expired. Its key cannot be reused." + }, + { + "type": "string", + "const": "resource:session_limit", + "description": "Session job limit reached. Open an empty editor." + }, + { + "type": "string", + "const": "conflict:inspection_revision_mismatch", + "description": "The requested revision is not displayed." + }, + { + "type": "string", + "const": "conflict:inspection_state_changed", + "description": "The editor changed during inspection. Inspect again." + }, { "type": "string", "const": "bad_request:download_blocked", @@ -1366,7 +2721,10 @@ "type": "string" } }, - "required": ["code", "message"] + "required": [ + "code", + "message" + ] } ] } diff --git a/embed/etc/index.api.md b/embed/etc/index.api.md index 3b7195b0..1730e19b 100644 --- a/embed/etc/index.api.md +++ b/embed/etc/index.api.md @@ -70,6 +70,141 @@ export class BridgeUnwrapError extends Error { readonly error: BridgeError; } +// @public (undocumented) +export type BuildPdfInput = { + action: "build"; + inspect?: { + pages?: number[]; + }; + code: string; + idempotencyKey: string; + buildSessionId?: string; + baseRevision?: number; + name?: string; + assets?: Array<{ + path: string; + dataUrl: string; + }>; + waitMs?: number; +} | { + action: "status"; + jobId: string; + waitMs?: number; + inspect?: { + pages?: number[]; + }; +} | { + action: "cancel"; + jobId: string; +}; + +// @public (undocumented) +export type BuildPdfOutput = { + jobId: string; + buildSessionId: string; + revision: number; + publishedRevision: number; + status: "queued"; + pollAfterMs: number; +} | { + jobId: string; + buildSessionId: string; + revision: number; + publishedRevision: number; + status: "running"; + stage: "queued" | "initializing" | "compiling" | "validating" | "loading" | "ready"; + pollAfterMs: number; +} | { + jobId: string; + buildSessionId: string; + revision: number; + publishedRevision: number; + status: "succeeded"; + pageCount: number; + warnings: Array<{ + severity: "warning"; + code: "typst" | "unsupported_dependency"; + message: string; + file?: string; + line?: number; + column?: number; + hint?: string; + }>; + warningsTruncated: boolean; + inspection?: { + success: true; + data: { + pages: Array<{ + buildSessionId: string | null; + revision: number | null; + editorStateVersion: number; + page: number; + imageDataUrl: string; + imageWidth: number; + imageHeight: number; + badges: Record; + }>; + omittedPages: number[]; + }; + } | { + success: false; + error: { + code: "bad_request:batch_validation_failed"; + message: string; + details: { + failures: Array<{ + fieldId: string; + code: "bad_request:field_not_found" | "bad_request:invalid_signature_url" | "bad_request:invalid_value" | "bad_request:read_only"; + message: string; + }>; + }; + } | { + code: "bad_request:missing_required_fields"; + message: string; + details: { + unfilledRequiredFieldsCount: number; + }; + } | { + code: "conflict:build_session_mismatch" | "conflict:base_revision_mismatch" | "conflict:idempotency_key_reused" | "conflict:editor_modified" | "conflict:unmanaged_document" | "not_found:job" | "not_found:job_expired" | "resource:session_limit" | "conflict:inspection_revision_mismatch" | "conflict:inspection_state_changed" | "bad_request:download_blocked" | "bad_request:editor_not_ready" | "bad_request:event_not_allowed" | "bad_request:failed_to_load_document" | "bad_request:field_not_found" | "bad_request:invalid_dimensions" | "bad_request:invalid_event_type" | "bad_request:invalid_field_ids" | "bad_request:invalid_field_type" | "bad_request:invalid_page" | "bad_request:invalid_signature_url" | "bad_request:invalid_tool" | "bad_request:invalid_value" | "bad_request:no_document_loaded" | "bad_request:page_not_found" | "bad_request:page_out_of_range" | "bad_request:plan_upgrade_required" | "bad_request:read_only" | "bad_request:signup_required" | "forbidden:editing_not_allowed" | "forbidden:origin_not_whitelisted" | "forbidden:whitelist_required" | "unexpected:internal_error"; + message: string; + }; + }; +} | { + jobId: string; + buildSessionId: string; + revision: number; + publishedRevision: number; + status: "failed"; + error: { + code: "unsupported_dependency" | "engine_initialization_failed" | "compile_error" | "compile_timeout" | "job_timeout" | "resource_limit" | "invalid_pdf" | "editor_load_failed" | "editor_conflict" | "worker_crashed" | "internal_error"; + message: string; + stage: "queued" | "initializing" | "compiling" | "validating" | "loading" | "ready"; + retryable: boolean; + diagnostics: Array<{ + severity: "error" | "warning"; + code: "typst" | "unsupported_dependency"; + message: string; + file?: string; + line?: number; + column?: number; + hint?: string; + }>; + diagnosticsTruncated: boolean; + }; +} | { + jobId: string; + buildSessionId: string; + revision: number; + publishedRevision: number; + status: "cancelled"; +} | { + jobId: string; + buildSessionId: string; + revision: number; + publishedRevision: number; + status: "superseded"; +}; + // @public (undocumented) export const createEmbed: (args: CreateEmbedArgs) => Embed; @@ -236,10 +371,16 @@ export type FocusFieldOutput = { // @public (undocumented) export type GetAnnotatedPageInput = { page: number; + expectedBuildSessionId?: string; + expectedRevision?: number; + expectedEditorStateVersion?: number; }; // @public (undocumented) export type GetAnnotatedPageOutput = { + buildSessionId: string | null; + revision: number | null; + editorStateVersion: number; page: number; imageDataUrl: string; imageWidth: number; @@ -247,6 +388,24 @@ export type GetAnnotatedPageOutput = { badges: Record; }; +// @public (undocumented) +export type GetDocumentationInput = { + topic?: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.troubleshooting" | "fields" | "inspection"; +}; + +// @public (undocumented) +export type GetDocumentationOutput = { + kind: "index"; + topics: Array<{ + topic: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.troubleshooting" | "fields" | "inspection"; + description: string; + }>; +} | { + kind: "topic"; + topic: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.troubleshooting" | "fields" | "inspection"; + markdown: string; +}; + // @public (undocumented) export type GetDocumentContentInput = { extractionMode?: ExtractionMode; @@ -280,6 +439,8 @@ export type GoToInput = { // @public (undocumented) export type IframeActions = { + buildPdf: (input: BuildPdfInput) => Promise>; + getDocumentation: (input?: GetDocumentationInput) => Promise>; batchSetFieldValues: (input: BatchSetFieldValuesInput) => Promise; createField: (input: CreateFieldInput) => Promise>; deleteFields: (input?: DeleteFieldsInput) => Promise>; diff --git a/embed/etc/protocol.api.md b/embed/etc/protocol.api.md index 46a405dd..3e3e555b 100644 --- a/embed/etc/protocol.api.md +++ b/embed/etc/protocol.api.md @@ -5,7 +5,7 @@ ```ts // @public (undocumented) -export const EDITOR_ERROR_CODES: readonly ["bad_request:batch_validation_failed", "bad_request:download_blocked", "bad_request:editor_not_ready", "bad_request:event_not_allowed", "bad_request:failed_to_load_document", "bad_request:field_not_found", "bad_request:invalid_dimensions", "bad_request:invalid_event_type", "bad_request:invalid_field_ids", "bad_request:invalid_field_type", "bad_request:invalid_page", "bad_request:invalid_signature_url", "bad_request:invalid_tool", "bad_request:invalid_value", "bad_request:missing_required_fields", "bad_request:no_document_loaded", "bad_request:page_not_found", "bad_request:page_out_of_range", "bad_request:plan_upgrade_required", "bad_request:read_only", "bad_request:signup_required", "forbidden:editing_not_allowed", "forbidden:origin_not_whitelisted", "forbidden:whitelist_required", "unexpected:internal_error"]; +export const EDITOR_ERROR_CODES: readonly ["bad_request:batch_validation_failed", "bad_request:download_blocked", "bad_request:editor_not_ready", "bad_request:event_not_allowed", "bad_request:failed_to_load_document", "bad_request:field_not_found", "bad_request:invalid_dimensions", "bad_request:invalid_event_type", "bad_request:invalid_field_ids", "bad_request:invalid_field_type", "bad_request:invalid_page", "bad_request:invalid_signature_url", "bad_request:invalid_tool", "bad_request:invalid_value", "bad_request:missing_required_fields", "bad_request:no_document_loaded", "bad_request:page_not_found", "bad_request:page_out_of_range", "bad_request:plan_upgrade_required", "bad_request:read_only", "bad_request:signup_required", "conflict:base_revision_mismatch", "conflict:build_session_mismatch", "conflict:editor_modified", "conflict:idempotency_key_reused", "conflict:inspection_revision_mismatch", "conflict:inspection_state_changed", "conflict:unmanaged_document", "forbidden:editing_not_allowed", "forbidden:origin_not_whitelisted", "forbidden:whitelist_required", "not_found:job", "not_found:job_expired", "resource:session_limit", "unexpected:internal_error"]; // @public (undocumented) export const EXTRACTION_MODES: readonly ["auto", "ocr"]; @@ -27,6 +27,22 @@ export const LOCALES: readonly ["fr", "en", "it", "de", "pt", "es", "ja", "nl"]; // @public (undocumented) export const OPERATIONS: readonly [{ + readonly request_type: "BUILD_PDF"; + readonly wire_type: "BUILD_PDF"; + readonly method: "buildPdf"; + readonly description: "Build and display a PDF locally from Typst code. Read get_documentation for task recipes, templates, fonts and limits. Request inspect:{} for revision-bound page images in the same response. Use a stable idempotency key; poll the job if needed. Inspect the successful revision with simplepdf_embed_get_annotated_page. Manual edits block replacement. Does not submit or share."; + readonly error_codes: readonly ["conflict:build_session_mismatch", "conflict:base_revision_mismatch", "conflict:idempotency_key_reused", "conflict:editor_modified", "conflict:unmanaged_document", "not_found:job", "not_found:job_expired", "resource:session_limit", "conflict:inspection_revision_mismatch", "conflict:inspection_state_changed", "bad_request:invalid_value", "forbidden:editing_not_allowed"]; + readonly is_agentic_tool: true; + readonly has_output: true; +}, { + readonly request_type: "GET_DOCUMENTATION"; + readonly wire_type: "GET_DOCUMENTATION"; + readonly method: "getDocumentation"; + readonly description: "Read task documentation for the SimplePDF browser API. Omit topic for the index. Includes PDF building, templates, forms, fields and inspection. Guidance does not modify the document or grant permissions."; + readonly error_codes: readonly ["bad_request:invalid_value"]; + readonly is_agentic_tool: true; + readonly has_output: true; +}, { readonly request_type: "BATCH_SET_FIELD_VALUES"; readonly wire_type: "BATCH_SET_FIELD_VALUES"; readonly method: "batchSetFieldValues"; @@ -87,7 +103,7 @@ export const OPERATIONS: readonly [{ readonly wire_type: "GET_ANNOTATED_PAGE"; readonly method: "getAnnotatedPage"; readonly description: "Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block."; - readonly error_codes: readonly ["bad_request:no_document_loaded", "bad_request:invalid_page", "bad_request:page_out_of_range"]; + readonly error_codes: readonly ["bad_request:no_document_loaded", "bad_request:invalid_page", "bad_request:page_out_of_range", "bad_request:invalid_value", "conflict:inspection_revision_mismatch", "conflict:inspection_state_changed"]; readonly is_agentic_tool: true; readonly has_output: true; }, { @@ -192,13 +208,13 @@ export const OVERLAY_TOOL_TYPES: readonly ["TEXT", "SIGNATURE", "PICTURE", "CHEC export type OverlayToolType = (typeof OVERLAY_TOOL_TYPES)[number]; // @public (undocumented) -export const REQUEST_TYPES: ("BATCH_SET_FIELD_VALUES" | "CREATE_FIELD" | "DELETE_FIELDS" | "DELETE_PAGES" | "DETECT_FIELDS" | "DOWNLOAD" | "FOCUS_FIELD" | "GET_ANNOTATED_PAGE" | "GET_DOCUMENT_CONTENT" | "GET_FIELDS" | "GO_TO" | "LOAD_DOCUMENT" | "MOVE_PAGE" | "ROTATE_PAGE" | "SELECT_TOOL" | "SET_FIELD_VALUE" | "SUBMIT")[]; +export const REQUEST_TYPES: ("BUILD_PDF" | "GET_DOCUMENTATION" | "BATCH_SET_FIELD_VALUES" | "CREATE_FIELD" | "DELETE_FIELDS" | "DELETE_PAGES" | "DETECT_FIELDS" | "DOWNLOAD" | "FOCUS_FIELD" | "GET_ANNOTATED_PAGE" | "GET_DOCUMENT_CONTENT" | "GET_FIELDS" | "GO_TO" | "LOAD_DOCUMENT" | "MOVE_PAGE" | "ROTATE_PAGE" | "SELECT_TOOL" | "SET_FIELD_VALUE" | "SUBMIT")[]; // @public (undocumented) export type RequestType = (typeof OPERATIONS)[number]["request_type"]; // @public (undocumented) -export const WIRE_TYPES: ("BATCH_SET_FIELD_VALUES" | "CREATE_FIELD" | "DELETE_FIELDS" | "DELETE_PAGES" | "DETECT_FIELDS" | "DOWNLOAD" | "FOCUS_FIELD" | "GET_ANNOTATED_PAGE" | "GET_DOCUMENT_CONTENT" | "GET_FIELDS" | "GO_TO" | "LOAD_DOCUMENT" | "MOVE_PAGE" | "ROTATE_PAGE" | "SELECT_TOOL" | "SET_FIELD_VALUE" | "SUBMIT")[]; +export const WIRE_TYPES: ("BUILD_PDF" | "GET_DOCUMENTATION" | "BATCH_SET_FIELD_VALUES" | "CREATE_FIELD" | "DELETE_FIELDS" | "DELETE_PAGES" | "DETECT_FIELDS" | "DOWNLOAD" | "FOCUS_FIELD" | "GET_ANNOTATED_PAGE" | "GET_DOCUMENT_CONTENT" | "GET_FIELDS" | "GO_TO" | "LOAD_DOCUMENT" | "MOVE_PAGE" | "ROTATE_PAGE" | "SELECT_TOOL" | "SET_FIELD_VALUE" | "SUBMIT")[]; // @public (undocumented) export type WireType = (typeof OPERATIONS)[number]["wire_type"]; diff --git a/embed/etc/schemas.api.md b/embed/etc/schemas.api.md index 6becd80f..579de73a 100644 --- a/embed/etc/schemas.api.md +++ b/embed/etc/schemas.api.md @@ -17,6 +17,37 @@ export const BatchSetFieldValuesInput: z.ZodObject<{ // @public (undocumented) export type BatchSetFieldValuesInput = z.infer; +// @public (undocumented) +export const BuildPdfInput: z.ZodUnion; + inspect: z.ZodOptional>; + }, z.core.$strip>>; + code: z.ZodString; + idempotencyKey: z.ZodString; + buildSessionId: z.ZodOptional; + baseRevision: z.ZodOptional; + name: z.ZodOptional; + assets: z.ZodOptional>>; + waitMs: z.ZodOptional; +}, z.core.$strip>, z.ZodObject<{ + action: z.ZodLiteral<"status">; + jobId: z.ZodString; + waitMs: z.ZodOptional; + inspect: z.ZodOptional>; + }, z.core.$strip>>; +}, z.core.$strip>, z.ZodObject<{ + action: z.ZodLiteral<"cancel">; + jobId: z.ZodString; +}, z.core.$strip>]>; + +// @public (undocumented) +export type BuildPdfInput = z.infer; + // @public (undocumented) export const CreateFieldInput: z.ZodObject<{ type: z.ZodEnum<{ @@ -77,11 +108,31 @@ export type FocusFieldInput = z.infer; // @public (undocumented) export const GetAnnotatedPageInput: z.ZodObject<{ page: z.ZodNumber; + expectedBuildSessionId: z.ZodOptional; + expectedRevision: z.ZodOptional; + expectedEditorStateVersion: z.ZodOptional; }, z.core.$strip>; // @public (undocumented) export type GetAnnotatedPageInput = z.infer; +// @public (undocumented) +export const GetDocumentationInput: z.ZodObject<{ + topic: z.ZodOptional>; +}, z.core.$strip>; + +// @public (undocumented) +export type GetDocumentationInput = z.infer; + // @public (undocumented) export const GetDocumentContentInput: z.ZodObject<{ extractionMode: z.ZodOptional; + inspect: zod.ZodOptional>; + }, zod_v4_core.$strip>>; + code: zod.ZodString; + idempotencyKey: zod.ZodString; + buildSessionId: zod.ZodOptional; + baseRevision: zod.ZodOptional; + name: zod.ZodOptional; + assets: zod.ZodOptional>>; + waitMs: zod.ZodOptional; + }, zod_v4_core.$strip>, zod.ZodObject<{ + action: zod.ZodLiteral<"status">; + jobId: zod.ZodString; + waitMs: zod.ZodOptional; + inspect: zod.ZodOptional>; + }, zod_v4_core.$strip>>; + }, zod_v4_core.$strip>, zod.ZodObject<{ + action: zod.ZodLiteral<"cancel">; + jobId: zod.ZodString; + }, zod_v4_core.$strip>]>; + }; + readonly getDocumentation: { + readonly description: "Read task documentation for the SimplePDF browser API. Omit topic for the index. Includes PDF building, templates, forms, fields and inspection. Guidance does not modify the document or grant permissions."; + readonly inputSchema: zod.ZodObject<{ + topic: zod.ZodOptional>; + }, zod_v4_core.$strip>; + }; readonly batchSetFieldValues: { readonly description: "Set existing fields, addressed by ids from the field list, in one atomic undo step. If any update is rejected, nothing changes and the call fails with bad_request:batch_validation_failed, whose details list each rejection with its field id, code and message. Text is set at once, never typed. Returns no data."; readonly inputSchema: zod.ZodObject<{ @@ -76,6 +120,9 @@ export const SIMPLEPDF_TOOLS: { readonly description: "Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block."; readonly inputSchema: zod.ZodObject<{ page: zod.ZodNumber; + expectedBuildSessionId: zod.ZodOptional; + expectedRevision: zod.ZodOptional; + expectedEditorStateVersion: zod.ZodOptional; }, zod_v4_core.$strip>; }; readonly getDocumentContent: { diff --git a/embed/scripts/generate.mjs b/embed/scripts/generate.mjs index d10c9508..0e22ad26 100644 --- a/embed/scripts/generate.mjs +++ b/embed/scripts/generate.mjs @@ -512,6 +512,7 @@ webmcpToolLines.push(' readonly inputSchema: {') webmcpToolLines.push(" readonly type: 'object'") webmcpToolLines.push(' readonly properties?: Readonly>') webmcpToolLines.push(' readonly required?: readonly string[]') +webmcpToolLines.push(' readonly anyOf?: readonly unknown[]') webmcpToolLines.push(' }') webmcpToolLines.push(' readonly annotations: {') for (const hint of WEBMCP_ANNOTATION_KEYS) { diff --git a/embed/src/bridge.ts b/embed/src/bridge.ts index 80a99669..1c8c3477 100644 --- a/embed/src/bridge.ts +++ b/embed/src/bridge.ts @@ -515,6 +515,8 @@ export const attachEmbed = ({ // ordering, input validation, and typed errors, and always replies. Each method // posts the request and correlates the reply; no client-side validation. const methods = { + buildPdf: (input) => sendRequest('BUILD_PDF', input), + getDocumentation: (input) => sendRequest('GET_DOCUMENTATION', input), batchSetFieldValues: (input) => sendRequest('BATCH_SET_FIELD_VALUES', input), createField: (input) => sendRequest('CREATE_FIELD', input), // All-optional input: deleteFields() with no args clears every field. diff --git a/embed/src/generated/contract.ts b/embed/src/generated/contract.ts index 6addc71b..d29bd8c3 100644 --- a/embed/src/generated/contract.ts +++ b/embed/src/generated/contract.ts @@ -5,7 +5,7 @@ import type { METHOD_NAMES } from './method-names' export const LOCALES = ["fr", "en", "it", "de", "pt", "es", "ja", "nl"] as const export type Locale = (typeof LOCALES)[number] -export const EDITOR_ERROR_CODES = ["bad_request:batch_validation_failed", "bad_request:download_blocked", "bad_request:editor_not_ready", "bad_request:event_not_allowed", "bad_request:failed_to_load_document", "bad_request:field_not_found", "bad_request:invalid_dimensions", "bad_request:invalid_event_type", "bad_request:invalid_field_ids", "bad_request:invalid_field_type", "bad_request:invalid_page", "bad_request:invalid_signature_url", "bad_request:invalid_tool", "bad_request:invalid_value", "bad_request:missing_required_fields", "bad_request:no_document_loaded", "bad_request:page_not_found", "bad_request:page_out_of_range", "bad_request:plan_upgrade_required", "bad_request:read_only", "bad_request:signup_required", "forbidden:editing_not_allowed", "forbidden:origin_not_whitelisted", "forbidden:whitelist_required", "unexpected:internal_error"] as const +export const EDITOR_ERROR_CODES = ["bad_request:batch_validation_failed", "bad_request:download_blocked", "bad_request:editor_not_ready", "bad_request:event_not_allowed", "bad_request:failed_to_load_document", "bad_request:field_not_found", "bad_request:invalid_dimensions", "bad_request:invalid_event_type", "bad_request:invalid_field_ids", "bad_request:invalid_field_type", "bad_request:invalid_page", "bad_request:invalid_signature_url", "bad_request:invalid_tool", "bad_request:invalid_value", "bad_request:missing_required_fields", "bad_request:no_document_loaded", "bad_request:page_not_found", "bad_request:page_out_of_range", "bad_request:plan_upgrade_required", "bad_request:read_only", "bad_request:signup_required", "conflict:base_revision_mismatch", "conflict:build_session_mismatch", "conflict:editor_modified", "conflict:idempotency_key_reused", "conflict:inspection_revision_mismatch", "conflict:inspection_state_changed", "conflict:unmanaged_document", "forbidden:editing_not_allowed", "forbidden:origin_not_whitelisted", "forbidden:whitelist_required", "not_found:job", "not_found:job_expired", "resource:session_limit", "unexpected:internal_error"] as const export type EditorErrorCode = (typeof EDITOR_ERROR_CODES)[number] export const FIELD_TYPES = ["TEXT", "SIGNATURE", "PICTURE", "CHECKBOX", "COMB_TEXT", "DROPDOWN", "RADIO"] as const @@ -17,6 +17,10 @@ export type OverlayToolType = (typeof OVERLAY_TOOL_TYPES)[number] export const EXTRACTION_MODES = ["auto", "ocr"] as const export type ExtractionMode = (typeof EXTRACTION_MODES)[number] +export type BuildPdfInput = { action: "build"; inspect?: { pages?: number[] }; code: string; idempotencyKey: string; buildSessionId?: string; baseRevision?: number; name?: string; assets?: Array<{ path: string; dataUrl: string }>; waitMs?: number } | { action: "status"; jobId: string; waitMs?: number; inspect?: { pages?: number[] } } | { action: "cancel"; jobId: string } +export type BuildPdfOutput = { jobId: string; buildSessionId: string; revision: number; publishedRevision: number; status: "queued"; pollAfterMs: number } | { jobId: string; buildSessionId: string; revision: number; publishedRevision: number; status: "running"; stage: "queued" | "initializing" | "compiling" | "validating" | "loading" | "ready"; pollAfterMs: number } | { jobId: string; buildSessionId: string; revision: number; publishedRevision: number; status: "succeeded"; pageCount: number; warnings: Array<{ severity: "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number; hint?: string }>; warningsTruncated: boolean; inspection?: { success: true; data: { pages: Array<{ buildSessionId: string | null; revision: number | null; editorStateVersion: number; page: number; imageDataUrl: string; imageWidth: number; imageHeight: number; badges: Record }>; omittedPages: number[] } } | { success: false; error: { code: "bad_request:batch_validation_failed"; message: string; details: { failures: Array<{ fieldId: string; code: "bad_request:field_not_found" | "bad_request:invalid_signature_url" | "bad_request:invalid_value" | "bad_request:read_only"; message: string }> } } | { code: "bad_request:missing_required_fields"; message: string; details: { unfilledRequiredFieldsCount: number } } | { code: "conflict:build_session_mismatch" | "conflict:base_revision_mismatch" | "conflict:idempotency_key_reused" | "conflict:editor_modified" | "conflict:unmanaged_document" | "not_found:job" | "not_found:job_expired" | "resource:session_limit" | "conflict:inspection_revision_mismatch" | "conflict:inspection_state_changed" | "bad_request:download_blocked" | "bad_request:editor_not_ready" | "bad_request:event_not_allowed" | "bad_request:failed_to_load_document" | "bad_request:field_not_found" | "bad_request:invalid_dimensions" | "bad_request:invalid_event_type" | "bad_request:invalid_field_ids" | "bad_request:invalid_field_type" | "bad_request:invalid_page" | "bad_request:invalid_signature_url" | "bad_request:invalid_tool" | "bad_request:invalid_value" | "bad_request:no_document_loaded" | "bad_request:page_not_found" | "bad_request:page_out_of_range" | "bad_request:plan_upgrade_required" | "bad_request:read_only" | "bad_request:signup_required" | "forbidden:editing_not_allowed" | "forbidden:origin_not_whitelisted" | "forbidden:whitelist_required" | "unexpected:internal_error"; message: string } } } | { jobId: string; buildSessionId: string; revision: number; publishedRevision: number; status: "failed"; error: { code: "unsupported_dependency" | "engine_initialization_failed" | "compile_error" | "compile_timeout" | "job_timeout" | "resource_limit" | "invalid_pdf" | "editor_load_failed" | "editor_conflict" | "worker_crashed" | "internal_error"; message: string; stage: "queued" | "initializing" | "compiling" | "validating" | "loading" | "ready"; retryable: boolean; diagnostics: Array<{ severity: "error" | "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number; hint?: string }>; diagnosticsTruncated: boolean } } | { jobId: string; buildSessionId: string; revision: number; publishedRevision: number; status: "cancelled" } | { jobId: string; buildSessionId: string; revision: number; publishedRevision: number; status: "superseded" } +export type GetDocumentationInput = { topic?: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.troubleshooting" | "fields" | "inspection" } +export type GetDocumentationOutput = { kind: "index"; topics: Array<{ topic: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.troubleshooting" | "fields" | "inspection"; description: string }> } | { kind: "topic"; topic: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.troubleshooting" | "fields" | "inspection"; markdown: string } export type BatchSetFieldValuesInput = { updates: Array<{ fieldId: string; value: string | null }> } export type BatchSetFieldValuesOutput = null export type CreateFieldInput = { type: OverlayToolType; x: number; y: number; width: number; height: number; page: number; value?: string } @@ -31,8 +35,8 @@ export type DownloadInput = Record export type DownloadOutput = null export type FocusFieldInput = { fieldId: string } export type FocusFieldOutput = { hint: { type: "user_action_expected"; message: string } } -export type GetAnnotatedPageInput = { page: number } -export type GetAnnotatedPageOutput = { page: number; imageDataUrl: string; imageWidth: number; imageHeight: number; badges: Record } +export type GetAnnotatedPageInput = { page: number; expectedBuildSessionId?: string; expectedRevision?: number; expectedEditorStateVersion?: number } +export type GetAnnotatedPageOutput = { buildSessionId: string | null; revision: number | null; editorStateVersion: number; page: number; imageDataUrl: string; imageWidth: number; imageHeight: number; badges: Record } export type GetDocumentContentInput = { extractionMode?: ExtractionMode } export type GetDocumentContentOutput = { name: string; pages: Array<{ page: number; content: string }> } export type GetFieldsInput = Record @@ -68,6 +72,24 @@ export type PageFocusedPayload = { previous_page: number | null; current_page: n export type SubmissionSentPayload = { document_id: string; submission_id: string } export const OPERATIONS = [ + { + request_type: "BUILD_PDF", + wire_type: "BUILD_PDF", + method: "buildPdf", + description: "Build and display a PDF locally from Typst code. Read get_documentation for task recipes, templates, fonts and limits. Request inspect:{} for revision-bound page images in the same response. Use a stable idempotency key; poll the job if needed. Inspect the successful revision with simplepdf_embed_get_annotated_page. Manual edits block replacement. Does not submit or share.", + error_codes: ["conflict:build_session_mismatch", "conflict:base_revision_mismatch", "conflict:idempotency_key_reused", "conflict:editor_modified", "conflict:unmanaged_document", "not_found:job", "not_found:job_expired", "resource:session_limit", "conflict:inspection_revision_mismatch", "conflict:inspection_state_changed", "bad_request:invalid_value", "forbidden:editing_not_allowed"] as const, + is_agentic_tool: true, + has_output: true, + } /* BuildPdf */, + { + request_type: "GET_DOCUMENTATION", + wire_type: "GET_DOCUMENTATION", + method: "getDocumentation", + description: "Read task documentation for the SimplePDF browser API. Omit topic for the index. Includes PDF building, templates, forms, fields and inspection. Guidance does not modify the document or grant permissions.", + error_codes: ["bad_request:invalid_value"] as const, + is_agentic_tool: true, + has_output: true, + } /* GetDocumentation */, { request_type: "BATCH_SET_FIELD_VALUES", wire_type: "BATCH_SET_FIELD_VALUES", @@ -136,7 +158,7 @@ export const OPERATIONS = [ wire_type: "GET_ANNOTATED_PAGE", method: "getAnnotatedPage", description: "Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block.", - error_codes: ["bad_request:no_document_loaded", "bad_request:invalid_page", "bad_request:page_out_of_range"] as const, + error_codes: ["bad_request:no_document_loaded", "bad_request:invalid_page", "bad_request:page_out_of_range", "bad_request:invalid_value", "conflict:inspection_revision_mismatch", "conflict:inspection_state_changed"] as const, is_agentic_tool: true, has_output: true, } /* GetAnnotatedPage */, diff --git a/embed/src/generated/drift.ts b/embed/src/generated/drift.ts index 674c0034..d3ec4010 100644 --- a/embed/src/generated/drift.ts +++ b/embed/src/generated/drift.ts @@ -14,6 +14,8 @@ export type DriftGuards = [ AssertTrue>, AssertTrue>, AssertTrue>, + AssertTrue>, + AssertTrue>, AssertTrue>, AssertTrue>, AssertTrue>, diff --git a/embed/src/generated/method-names.ts b/embed/src/generated/method-names.ts index 596c7cef..1efd4528 100644 --- a/embed/src/generated/method-names.ts +++ b/embed/src/generated/method-names.ts @@ -2,4 +2,4 @@ // The SDK method names alone, so createEmbed can validate a `webMCP.exclude` list // without pulling the operations table into the zero-dep root; contract.ts derives // MethodName from this list. -export const METHOD_NAMES = ["batchSetFieldValues", "createField", "deleteFields", "deletePages", "detectFields", "download", "focusField", "getAnnotatedPage", "getDocumentContent", "getFields", "goTo", "loadDocument", "movePage", "rotatePage", "selectTool", "setFieldValue", "submit"] as const +export const METHOD_NAMES = ["buildPdf", "getDocumentation", "batchSetFieldValues", "createField", "deleteFields", "deletePages", "detectFields", "download", "focusField", "getAnnotatedPage", "getDocumentContent", "getFields", "goTo", "loadDocument", "movePage", "rotatePage", "selectTool", "setFieldValue", "submit"] as const diff --git a/embed/src/generated/schemas.ts b/embed/src/generated/schemas.ts index eaa4055d..b175baaa 100644 --- a/embed/src/generated/schemas.ts +++ b/embed/src/generated/schemas.ts @@ -1,6 +1,37 @@ // AUTO-GENERATED from embed-api.json by scripts/generate.mjs. Do not edit by hand. import { z } from 'zod' +export const BuildPdfInput = z.union([z.object({ + action: z.literal("build"), + inspect: z.object({ + pages: z.array(z.number().int()).optional(), +}).optional(), + code: z.string(), + idempotencyKey: z.string(), + buildSessionId: z.string().optional(), + baseRevision: z.number().int().optional(), + name: z.string().optional(), + assets: z.array(z.object({ + path: z.string(), + dataUrl: z.string(), +})).optional(), + waitMs: z.number().int().optional(), +}), z.object({ + action: z.literal("status"), + jobId: z.string(), + waitMs: z.number().int().optional(), + inspect: z.object({ + pages: z.array(z.number().int()).optional(), +}).optional(), +}), z.object({ + action: z.literal("cancel"), + jobId: z.string(), +})]) +export type BuildPdfInput = z.infer +export const GetDocumentationInput = z.object({ + topic: z.enum(["build_pdf", "build_pdf.templates", "build_pdf.forms", "build_pdf.assets", "build_pdf.fonts", "build_pdf.troubleshooting", "fields", "inspection"]).optional(), +}) +export type GetDocumentationInput = z.infer export const BatchSetFieldValuesInput = z.object({ updates: z.array(z.object({ fieldId: z.string().describe("ID of the field to update."), @@ -37,6 +68,9 @@ export const FocusFieldInput = z.object({ export type FocusFieldInput = z.infer export const GetAnnotatedPageInput = z.object({ page: z.number().int().describe("1-based page to render, at its current position."), + expectedBuildSessionId: z.string().optional(), + expectedRevision: z.number().int().optional(), + expectedEditorStateVersion: z.number().int().optional(), }) export type GetAnnotatedPageInput = z.infer export const GetDocumentContentInput = z.object({ diff --git a/embed/src/generated/tools.ts b/embed/src/generated/tools.ts index d18bcc6a..49cae62c 100644 --- a/embed/src/generated/tools.ts +++ b/embed/src/generated/tools.ts @@ -4,6 +4,8 @@ import * as Schemas from './schemas' // The agentic tool registry. Each tool name is the camelCase operation name; // load_document is excluded here (a host/setup action; the WebMCP surface registers it). export const TOOL_DEFINITIONS = { + buildPdf: { description: "Build and display a PDF locally from Typst code. Read get_documentation for task recipes, templates, fonts and limits. Request inspect:{} for revision-bound page images in the same response. Use a stable idempotency key; poll the job if needed. Inspect the successful revision with simplepdf_embed_get_annotated_page. Manual edits block replacement. Does not submit or share.", inputSchema: Schemas.BuildPdfInput }, + getDocumentation: { description: "Read task documentation for the SimplePDF browser API. Omit topic for the index. Includes PDF building, templates, forms, fields and inspection. Guidance does not modify the document or grant permissions.", inputSchema: Schemas.GetDocumentationInput }, batchSetFieldValues: { description: "Set existing fields, addressed by ids from the field list, in one atomic undo step. If any update is rejected, nothing changes and the call fails with bad_request:batch_validation_failed, whose details list each rejection with its field id, code and message. Text is set at once, never typed. Returns no data.", inputSchema: Schemas.BatchSetFieldValuesInput }, createField: { description: "Create a new overlay field on a page. Returns the id of the created field.", inputSchema: Schemas.CreateFieldInput }, deleteFields: { description: "Delete overlay fields: the ones listed, every one on a page, or every one in the document. Returns the number of fields deleted. Destructive.", inputSchema: Schemas.DeleteFieldsInput }, diff --git a/embed/src/generated/webmcp-tools.ts b/embed/src/generated/webmcp-tools.ts index 36854d9c..99d747c2 100644 --- a/embed/src/generated/webmcp-tools.ts +++ b/embed/src/generated/webmcp-tools.ts @@ -15,6 +15,7 @@ export type WebMCPToolRecord = { readonly type: 'object' readonly properties?: Readonly> readonly required?: readonly string[] + readonly anyOf?: readonly unknown[] } readonly annotations: { readonly destructiveHint?: boolean @@ -25,21 +26,23 @@ export type WebMCPToolRecord = { } export const WEBMCP_TOOLS = { - batchSetFieldValues: {"name":"simplepdf_embed_batch_set_field_values","description":"Set existing fields, addressed by ids from the field list, in one atomic undo step. If any update is rejected, nothing changes and the call fails with bad_request:batch_validation_failed, whose details list each rejection with its field id, code and message. Text is set at once, never typed. Returns no data.","inputSchema":{"type":"object","properties":{"updates":{"items":{"type":"object","properties":{"field_id":{"type":"string","description":"ID of the field to update."},"value":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"New value for the field, or null to clear it. If the field has options (see the field list), it must be one of them; otherwise a string (text/checkbox), or a data URL or http(s) URL, fetched by the editor (signature/picture), or plain text for a signature, drawn as a typed signature."}},"required":["field_id","value"]},"description":"The fields to set, at least one, each field at most once. Fields not listed keep their value.","type":"array"}},"required":["updates"]},"annotations":{"destructiveHint":false,"openWorldHint":true},"wireType":"BATCH_SET_FIELD_VALUES"}, - createField: {"name":"simplepdf_embed_create_field","description":"Create a new overlay field on a page. Returns the id of the created field.","inputSchema":{"type":"object","properties":{"type":{"enum":["TEXT","SIGNATURE","PICTURE","CHECKBOX","COMB_TEXT"],"description":"Field type to create.","type":"string"},"x":{"description":"Field x position, in PDF points.","type":"number"},"y":{"description":"Field y position, in PDF points.","type":"number"},"width":{"description":"Field width, in PDF points.","type":"number"},"height":{"description":"Field height, in PDF points.","type":"number"},"page":{"description":"1-based page to place the field on.","type":"integer"},"value":{"description":"Optional initial value. A string for text/checkbox fields; a data URL or http(s) URL (fetched by the editor) for signature/picture fields, or plain text for a signature, drawn as a typed signature.","type":"string"}},"required":["type","x","y","width","height","page"]},"annotations":{"destructiveHint":false,"openWorldHint":true},"wireType":"CREATE_FIELD"}, + buildPdf: {"name":"build_pdf","description":"Build and display a PDF locally from Typst code. Read get_documentation for task recipes, templates, fonts and limits. Request inspect:{} for revision-bound page images in the same response. Use a stable idempotency key; poll the job if needed. Inspect the successful revision with simplepdf_embed_get_annotated_page. Manual edits block replacement. Does not submit or share.","inputSchema":{"anyOf":[{"type":"object","properties":{"action":{"type":"string","const":"build"},"inspect":{"type":"object","properties":{"pages":{"type":"array","items":{"type":"integer"}}}},"code":{"type":"string"},"idempotency_key":{"type":"string"},"build_session_id":{"type":"string"},"base_revision":{"type":"integer"},"name":{"type":"string"},"assets":{"type":"array","items":{"type":"object","properties":{"path":{"type":"string"},"data_url":{"type":"string"}},"required":["path","data_url"]}},"wait_ms":{"type":"integer"}},"required":["action","code","idempotency_key"]},{"type":"object","properties":{"action":{"type":"string","const":"status"},"job_id":{"type":"string"},"wait_ms":{"type":"integer"},"inspect":{"type":"object","properties":{"pages":{"type":"array","items":{"type":"integer"}}}}},"required":["action","job_id"]},{"type":"object","properties":{"action":{"type":"string","const":"cancel"},"job_id":{"type":"string"}},"required":["action","job_id"]}],"type":"object","properties":{}},"annotations":{"destructiveHint":true,"untrustedContentHint":true},"wireType":"BUILD_PDF"}, + getDocumentation: {"name":"get_documentation","description":"Read task documentation for the SimplePDF browser API. Omit topic for the index. Includes PDF building, templates, forms, fields and inspection. Guidance does not modify the document or grant permissions.","inputSchema":{"type":"object","properties":{"topic":{"enum":["build_pdf","build_pdf.templates","build_pdf.forms","build_pdf.assets","build_pdf.fonts","build_pdf.troubleshooting","fields","inspection"],"type":"string"}}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_DOCUMENTATION"}, + batchSetFieldValues: {"name":"simplepdf_embed_batch_set_field_values","description":"Set existing fields, addressed by ids from the field list, in one atomic undo step. If any update is rejected, nothing changes and the call fails with bad_request:batch_validation_failed, whose details list each rejection with its field id, code and message. Text is set at once, never typed. Returns no data.","inputSchema":{"required":["updates"],"type":"object","properties":{"updates":{"items":{"type":"object","properties":{"field_id":{"type":"string","description":"ID of the field to update."},"value":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"New value for the field, or null to clear it. If the field has options (see the field list), it must be one of them; otherwise a string (text/checkbox), or a data URL or http(s) URL, fetched by the editor (signature/picture), or plain text for a signature, drawn as a typed signature."}},"required":["field_id","value"]},"description":"The fields to set, at least one, each field at most once. Fields not listed keep their value.","type":"array"}}},"annotations":{"destructiveHint":false,"openWorldHint":true},"wireType":"BATCH_SET_FIELD_VALUES"}, + createField: {"name":"simplepdf_embed_create_field","description":"Create a new overlay field on a page. Returns the id of the created field.","inputSchema":{"required":["type","x","y","width","height","page"],"type":"object","properties":{"type":{"enum":["TEXT","SIGNATURE","PICTURE","CHECKBOX","COMB_TEXT"],"description":"Field type to create.","type":"string"},"x":{"description":"Field x position, in PDF points.","type":"number"},"y":{"description":"Field y position, in PDF points.","type":"number"},"width":{"description":"Field width, in PDF points.","type":"number"},"height":{"description":"Field height, in PDF points.","type":"number"},"page":{"description":"1-based page to place the field on.","type":"integer"},"value":{"description":"Optional initial value. A string for text/checkbox fields; a data URL or http(s) URL (fetched by the editor) for signature/picture fields, or plain text for a signature, drawn as a typed signature.","type":"string"}}},"annotations":{"destructiveHint":false,"openWorldHint":true},"wireType":"CREATE_FIELD"}, deleteFields: {"name":"simplepdf_embed_delete_fields","description":"Delete overlay fields: the ones listed, every one on a page, or every one in the document. Returns the number of fields deleted. Destructive.","inputSchema":{"type":"object","properties":{"field_ids":{"description":"IDs of the fields to delete. Omit to delete every field on the target page.","items":{"type":"string"},"type":"array"},"page":{"description":"1-based page to scope the deletion to. Omit to target all pages.","type":"integer"}}},"annotations":{"destructiveHint":true},"wireType":"DELETE_FIELDS"}, - deletePages: {"name":"simplepdf_embed_delete_pages","description":"Delete pages from the document (it cannot delete every visible page). Returns no data. Destructive.","inputSchema":{"type":"object","properties":{"pages":{"items":{"type":"integer"},"description":"1-based page numbers to delete.","type":"array"}},"required":["pages"]},"annotations":{"destructiveHint":true},"wireType":"DELETE_PAGES"}, + deletePages: {"name":"simplepdf_embed_delete_pages","description":"Delete pages from the document (it cannot delete every visible page). Returns no data. Destructive.","inputSchema":{"required":["pages"],"type":"object","properties":{"pages":{"items":{"type":"integer"},"description":"1-based page numbers to delete.","type":"array"}}},"annotations":{"destructiveHint":true},"wireType":"DELETE_PAGES"}, detectFields: {"name":"simplepdf_embed_detect_fields","description":"Automatically detect fillable fields in the loaded document and add them as editable fields. Returns the number of fields detected.","inputSchema":{"type":"object","properties":{}},"annotations":{"destructiveHint":false},"wireType":"DETECT_FIELDS"}, download: {"name":"simplepdf_embed_download","description":"Generate and download the current document as a PDF. Returns no data.","inputSchema":{"type":"object","properties":{}},"annotations":{"destructiveHint":false},"wireType":"DOWNLOAD"}, - focusField: {"name":"simplepdf_embed_focus_field","description":"Scroll an existing field into view and focus it, addressed by its id from the field list. Returns a hint describing the user action expected next.","inputSchema":{"type":"object","properties":{"field_id":{"description":"ID of the field to focus and scroll into view.","type":"string"}},"required":["field_id"]},"annotations":{"destructiveHint":false},"wireType":"FOCUS_FIELD"}, - getAnnotatedPage: {"name":"simplepdf_embed_get_annotated_page","description":"Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block.","inputSchema":{"type":"object","properties":{"page":{"description":"1-based page to render, at its current position.","type":"integer"}},"required":["page"]},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_ANNOTATED_PAGE"}, + focusField: {"name":"simplepdf_embed_focus_field","description":"Scroll an existing field into view and focus it, addressed by its id from the field list. Returns a hint describing the user action expected next.","inputSchema":{"required":["field_id"],"type":"object","properties":{"field_id":{"description":"ID of the field to focus and scroll into view.","type":"string"}}},"annotations":{"destructiveHint":false},"wireType":"FOCUS_FIELD"}, + getAnnotatedPage: {"name":"simplepdf_embed_get_annotated_page","description":"Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block.","inputSchema":{"required":["page"],"type":"object","properties":{"page":{"description":"1-based page to render, at its current position.","type":"integer"},"expected_build_session_id":{"type":"string"},"expected_revision":{"type":"integer"},"expected_editor_state_version":{"type":"integer"}}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_ANNOTATED_PAGE"}, getDocumentContent: {"name":"simplepdf_embed_get_document_content","description":"Extract the document's content page by page as Markdown, or as plain text when optical recognition is forced. Use it to read what the document says. Returns the document name and each page's content.","inputSchema":{"type":"object","properties":{"extraction_mode":{"description":"Extraction strategy: 'auto' (default) or 'ocr' to force optical recognition.","enum":["auto","ocr"],"type":"string"}}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_DOCUMENT_CONTENT"}, getFields: {"name":"simplepdf_embed_get_fields","description":"List every fillable field in the loaded document, including native dropdown and radio AcroFields. Each field reports its id, name, type, page, current value, and the options its value must be one of, if any. Call this first to discover field ids before reading or setting values. To SEE where each field sits on the printed page, render the annotated page. Returns the field list.","inputSchema":{"type":"object","properties":{}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_FIELDS"}, - goTo: {"name":"simplepdf_embed_go_to","description":"Scroll the editor to a page. Returns no data.","inputSchema":{"type":"object","properties":{"page":{"description":"1-based page to navigate to.","type":"integer"}},"required":["page"]},"annotations":{"destructiveHint":false},"wireType":"GO_TO"}, - loadDocument: {"name":"simplepdf_embed_load_document","description":"Replace the document in the editor with one supplied as a base64 data URL or an http(s) URL the editor fetches. Destructive: the current document and every edit in it are discarded. Replies once the document and its fields are ready, so the next operation can act on it, and DOCUMENT_LOADED follows the reply; the URL already open is left as is and answers once it settles; a document that cannot be loaded or prepared answers bad_request:failed_to_load_document. Returns no data.","inputSchema":{"type":"object","properties":{"data_url":{"description":"The document to load: a data URL, or an http(s) URL the editor fetches.","type":"string"},"name":{"description":"Optional display name for the document.","type":"string"},"page":{"description":"Optional 1-based page to open the document on.","type":"integer"}},"required":["data_url"]},"annotations":{"destructiveHint":true,"openWorldHint":true},"wireType":"LOAD_DOCUMENT"}, - movePage: {"name":"simplepdf_embed_move_page","description":"Move a page to another position, reordering the document. Returns no data. Destructive.","inputSchema":{"type":"object","properties":{"from_page":{"description":"1-based current position of the page to move.","type":"integer"},"to_page":{"description":"1-based destination position for the page.","type":"integer"}},"required":["from_page","to_page"]},"annotations":{"destructiveHint":true},"wireType":"MOVE_PAGE"}, - rotatePage: {"name":"simplepdf_embed_rotate_page","description":"Rotate a page 90 degrees clockwise. Returns no data. Destructive.","inputSchema":{"type":"object","properties":{"page":{"description":"1-based page to rotate.","type":"integer"}},"required":["page"]},"annotations":{"destructiveHint":true},"wireType":"ROTATE_PAGE"}, - selectTool: {"name":"simplepdf_embed_select_tool","description":"Activate a field-placement tool in the editor toolbar so the user can draw that field type, or pass null to clear the active tool. Returns no data.","inputSchema":{"type":"object","properties":{"tool":{"anyOf":[{"type":"string","enum":["TEXT","SIGNATURE","PICTURE","CHECKBOX","COMB_TEXT"]},{"type":"null"}],"description":"Tool to activate, or null to deselect."}},"required":["tool"]},"annotations":{"destructiveHint":false},"wireType":"SELECT_TOOL"}, - setFieldValue: {"name":"simplepdf_embed_set_field_value","description":"Set or clear (null) one existing field, addressed by its id from the field list. Text is typed out unless animate is false. Returns no data.","inputSchema":{"type":"object","properties":{"animate":{"description":"Type a text value out character by character (true, the default) so a person watching the editor can follow the field being filled, or set it at once (false) for headless or batch filling where speed matters. Only text values are typed: checkbox, option, signature, picture and null values are always set at once.","type":"boolean"},"field_id":{"description":"ID of the field to update.","type":"string"},"value":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"New value for the field, or null to clear it. If the field has options (see the field list), it must be one of them; otherwise a string (text/checkbox), or a data URL or http(s) URL, fetched by the editor (signature/picture), or plain text for a signature, drawn as a typed signature."}},"required":["field_id","value"]},"annotations":{"destructiveHint":false,"openWorldHint":true},"wireType":"SET_FIELD_VALUE"}, - submit: {"name":"simplepdf_embed_submit","description":"Submit the completed document through the editor's finalization flow. This is irreversible. Fails with bad_request:missing_required_fields when required fields are unfilled. Returns no data.","inputSchema":{"type":"object","properties":{"download_copy":{"description":"When true, the signer also receives a downloaded copy on submit.","type":"boolean"}},"required":["download_copy"]},"annotations":{"destructiveHint":true},"wireType":"SUBMIT"}, + goTo: {"name":"simplepdf_embed_go_to","description":"Scroll the editor to a page. Returns no data.","inputSchema":{"required":["page"],"type":"object","properties":{"page":{"description":"1-based page to navigate to.","type":"integer"}}},"annotations":{"destructiveHint":false},"wireType":"GO_TO"}, + loadDocument: {"name":"simplepdf_embed_load_document","description":"Replace the document in the editor with one supplied as a base64 data URL or an http(s) URL the editor fetches. Destructive: the current document and every edit in it are discarded. Replies once the document and its fields are ready, so the next operation can act on it, and DOCUMENT_LOADED follows the reply; the URL already open is left as is and answers once it settles; a document that cannot be loaded or prepared answers bad_request:failed_to_load_document. Returns no data.","inputSchema":{"required":["data_url"],"type":"object","properties":{"data_url":{"description":"The document to load: a data URL, or an http(s) URL the editor fetches.","type":"string"},"name":{"description":"Optional display name for the document.","type":"string"},"page":{"description":"Optional 1-based page to open the document on.","type":"integer"}}},"annotations":{"destructiveHint":true,"openWorldHint":true},"wireType":"LOAD_DOCUMENT"}, + movePage: {"name":"simplepdf_embed_move_page","description":"Move a page to another position, reordering the document. Returns no data. Destructive.","inputSchema":{"required":["from_page","to_page"],"type":"object","properties":{"from_page":{"description":"1-based current position of the page to move.","type":"integer"},"to_page":{"description":"1-based destination position for the page.","type":"integer"}}},"annotations":{"destructiveHint":true},"wireType":"MOVE_PAGE"}, + rotatePage: {"name":"simplepdf_embed_rotate_page","description":"Rotate a page 90 degrees clockwise. Returns no data. Destructive.","inputSchema":{"required":["page"],"type":"object","properties":{"page":{"description":"1-based page to rotate.","type":"integer"}}},"annotations":{"destructiveHint":true},"wireType":"ROTATE_PAGE"}, + selectTool: {"name":"simplepdf_embed_select_tool","description":"Activate a field-placement tool in the editor toolbar so the user can draw that field type, or pass null to clear the active tool. Returns no data.","inputSchema":{"required":["tool"],"type":"object","properties":{"tool":{"anyOf":[{"type":"string","enum":["TEXT","SIGNATURE","PICTURE","CHECKBOX","COMB_TEXT"]},{"type":"null"}],"description":"Tool to activate, or null to deselect."}}},"annotations":{"destructiveHint":false},"wireType":"SELECT_TOOL"}, + setFieldValue: {"name":"simplepdf_embed_set_field_value","description":"Set or clear (null) one existing field, addressed by its id from the field list. Text is typed out unless animate is false. Returns no data.","inputSchema":{"required":["field_id","value"],"type":"object","properties":{"animate":{"description":"Type a text value out character by character (true, the default) so a person watching the editor can follow the field being filled, or set it at once (false) for headless or batch filling where speed matters. Only text values are typed: checkbox, option, signature, picture and null values are always set at once.","type":"boolean"},"field_id":{"description":"ID of the field to update.","type":"string"},"value":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"New value for the field, or null to clear it. If the field has options (see the field list), it must be one of them; otherwise a string (text/checkbox), or a data URL or http(s) URL, fetched by the editor (signature/picture), or plain text for a signature, drawn as a typed signature."}}},"annotations":{"destructiveHint":false,"openWorldHint":true},"wireType":"SET_FIELD_VALUE"}, + submit: {"name":"simplepdf_embed_submit","description":"Submit the completed document through the editor's finalization flow. This is irreversible. Fails with bad_request:missing_required_fields when required fields are unfilled. Returns no data.","inputSchema":{"required":["download_copy"],"type":"object","properties":{"download_copy":{"description":"When true, the signer also receives a downloaded copy on submit.","type":"boolean"}}},"annotations":{"destructiveHint":true},"wireType":"SUBMIT"}, } as const satisfies Record diff --git a/embed/src/tools.ts b/embed/src/tools.ts index fc2eb598..19e95e7e 100644 --- a/embed/src/tools.ts +++ b/embed/src/tools.ts @@ -7,6 +7,8 @@ import type { z } from 'zod' import { TOOL_DEFINITIONS, type SimplePDFToolName } from './generated/tools' import { + BuildPdfInput, + GetDocumentationInput, BatchSetFieldValuesInput, CreateFieldInput, DeleteFieldsInput, @@ -59,6 +61,10 @@ export const routeToolCall = ( input: unknown, ): Promise> => { switch (toolName) { + case 'buildPdf': + return dispatch(BuildPdfInput, input, (value) => actions.buildPdf(value)) + case 'getDocumentation': + return dispatch(GetDocumentationInput, input ?? {}, (value) => actions.getDocumentation(value)) case 'batchSetFieldValues': return dispatch(BatchSetFieldValuesInput, input, (value) => actions.batchSetFieldValues(value)) case 'createField': diff --git a/embed/src/types.ts b/embed/src/types.ts index afc4e310..2199b69f 100644 --- a/embed/src/types.ts +++ b/embed/src/types.ts @@ -4,6 +4,10 @@ // the single source of truth; nothing in this file restates a wire shape. import type { + BuildPdfInput, + BuildPdfOutput, + GetDocumentationInput, + GetDocumentationOutput, BatchSetFieldValuesInput, CreateFieldInput, CreateFieldOutput, @@ -34,6 +38,10 @@ import type { } from './generated/contract' export type { + BuildPdfInput, + BuildPdfOutput, + GetDocumentationInput, + GetDocumentationOutput, BatchSetFieldValuesInput, BatchValidationFailedDetails, CreateFieldInput, @@ -139,6 +147,8 @@ export type EditorEventMap = { [TEvent in EditorEvent as TEvent['type']]: TEvent // throws. Drift-guarded against the generated operation set in ./generated/drift.ts // (a new operation fails the build until added here). export type IframeActions = { + buildPdf: (input: BuildPdfInput) => Promise> + getDocumentation: (input?: GetDocumentationInput) => Promise> batchSetFieldValues: (input: BatchSetFieldValuesInput) => Promise createField: (input: CreateFieldInput) => Promise> deleteFields: (input?: DeleteFieldsInput) => Promise> diff --git a/embed/src/webmcp.ts b/embed/src/webmcp.ts index 156b1fd6..b7d6b55b 100644 --- a/embed/src/webmcp.ts +++ b/embed/src/webmcp.ts @@ -66,10 +66,75 @@ const toAnnotatedPageToolResult = (result: BridgeResult): CallToolResul } } +// Compound inspection carries each PNG once, with the remaining job/page metadata in text. +const toBuildPdfToolResult = ( + result: BridgeResult +): CallToolResult => { + if (!result.success) return toTextToolResult(result) + const job = result.data + if (typeof job !== 'object' || job === null || !('inspection' in job)) + return toTextToolResult(result) + const inspection = job.inspection + if ( + typeof inspection !== 'object' || + inspection === null || + !('success' in inspection) || + inspection.success !== true || + !('data' in inspection) + ) + return toTextToolResult(result) + const data = inspection.data + if ( + typeof data !== 'object' || + data === null || + !('pages' in data) || + !Array.isArray(data.pages) + ) + return toTextToolResult(result) + const images: ToolContent[] = [] + const pages: Record[] = [] + for (const page of data.pages) { + if ( + typeof page !== 'object' || + page === null || + !('image_data_url' in page) + ) + return toTextToolResult(result) + const { image_data_url: image, ...metadata } = page + if (typeof image !== 'string' || !image.startsWith(PNG_DATA_URL_PREFIX)) + return toTextToolResult(result) + images.push({ + type: 'image', + data: image.slice(PNG_DATA_URL_PREFIX.length), + mimeType: 'image/png', + }) + pages.push(metadata) + } + return { + content: [ + ...images, + { + type: 'text', + text: JSON.stringify({ + success: true, + data: { + ...job, + inspection: { ...inspection, data: { ...data, pages } }, + }, + }), + }, + ], + } +} + // One arm per operation on purpose: a new operation must decide here whether its result // is text or a picture instead of taking the text envelope unnoticed. const toCallToolResult = (wireType: WireType, result: BridgeResult): CallToolResult => { switch (wireType) { + case 'BUILD_PDF': + return toBuildPdfToolResult(result) + case 'GET_DOCUMENTATION': + return toTextToolResult(result) case 'GET_ANNOTATED_PAGE': return toAnnotatedPageToolResult(result) case 'BATCH_SET_FIELD_VALUES': diff --git a/embed/test/helpers.ts b/embed/test/helpers.ts index 823ea02c..f1c5b1d1 100644 --- a/embed/test/helpers.ts +++ b/embed/test/helpers.ts @@ -8,6 +8,8 @@ const okResult: BridgeResult = { success: true, data: null } export const makeActionsStub = (): IframeActions => { const method = (): Promise> => Promise.resolve(okResult) return { + buildPdf: vi.fn(method), + getDocumentation: vi.fn(method), createField: vi.fn(method), deleteFields: vi.fn(method), deletePages: vi.fn(method), diff --git a/embed/test/mount.test.ts b/embed/test/mount.test.ts index 33f76536..e4c06347 100644 --- a/embed/test/mount.test.ts +++ b/embed/test/mount.test.ts @@ -414,6 +414,6 @@ describe(createEmbed.name, () => { document.body.innerHTML = '
' const misspelled: unknown = { target: '#root', companyIdentifier: 'acme', webMCP: { enabled: true, exclude: ['sumbit'] } } // @ts-expect-error exercising the runtime guard for untyped JS callers - expect(() => createEmbed(misspelled)).toThrow(/webMCP\.exclude names no tool: sumbit \(known: batchSetFieldValues, createField/) + expect(() => createEmbed(misspelled)).toThrow(/webMCP\.exclude names no tool: sumbit \(known: buildPdf, getDocumentation, batchSetFieldValues, createField/) }) }) diff --git a/embed/test/tanstack-ai.test.ts b/embed/test/tanstack-ai.test.ts index 4f2658cc..30b8252b 100644 --- a/embed/test/tanstack-ai.test.ts +++ b/embed/test/tanstack-ai.test.ts @@ -4,9 +4,9 @@ import type { BridgeResult } from '../src/types' import { makeEmbedStub } from './helpers' describe('simplePDFToolDefinitions', () => { - it('returns the 16 agentic operations as execute-less definitions (loadDocument excluded)', () => { + it('returns the 18 agentic operations as execute-less definitions (loadDocument excluded)', () => { const definitions = simplePDFToolDefinitions() - expect(definitions).toHaveLength(16) + expect(definitions).toHaveLength(18) expect(definitions.map((definition) => definition.name)).not.toContain('loadDocument') for (const definition of definitions) { expect(typeof definition.description).toBe('string') @@ -16,9 +16,9 @@ describe('simplePDFToolDefinitions', () => { }) describe('createSimplePDFTools', () => { - it('produces a client tool for each of the 16 agentic operations', () => { + it('produces a client tool for each of the 18 agentic operations', () => { const tools = createSimplePDFTools({ embed: makeEmbedStub() }) - expect(tools).toHaveLength(16) + expect(tools).toHaveLength(18) expect(tools.every((tool) => typeof tool.execute === 'function')).toBe(true) }) diff --git a/embed/test/tools.test.ts b/embed/test/tools.test.ts index 955742bb..26a777c6 100644 --- a/embed/test/tools.test.ts +++ b/embed/test/tools.test.ts @@ -5,6 +5,8 @@ import { makeActionsStub } from './helpers' describe(isSimplePDFToolName.name, () => { it('accepts agentic tool names', () => { expect(isSimplePDFToolName('getFields')).toBe(true) + expect(isSimplePDFToolName('buildPdf')).toBe(true) + expect(isSimplePDFToolName('getDocumentation')).toBe(true) expect(isSimplePDFToolName('goTo')).toBe(true) expect(isSimplePDFToolName('createField')).toBe(true) }) @@ -17,9 +19,9 @@ describe(isSimplePDFToolName.name, () => { }) describe('SIMPLEPDF_TOOLS', () => { - it('exposes the 16 agentic operations with descriptions + input schemas (loadDocument excluded)', () => { + it('exposes the 18 agentic operations with descriptions + input schemas (loadDocument excluded)', () => { const names = Object.keys(SIMPLEPDF_TOOLS) - expect(names).toHaveLength(16) + expect(names).toHaveLength(18) expect(names).not.toContain('loadDocument') for (const definition of Object.values(SIMPLEPDF_TOOLS)) { expect(typeof definition.description).toBe('string') @@ -41,6 +43,22 @@ describe(routeToolCall.name, () => { expect(actions.goTo).toHaveBeenCalledWith({ page: 2 }) }) + it('routes build actions and the documentation index with camelCase inputs', async () => { + const actions = makeActionsStub() + await routeToolCall(actions, 'buildPdf', { + action: 'build', + code: 'Hello', + idempotencyKey: 'first', + }) + expect(actions.buildPdf).toHaveBeenCalledWith({ + action: 'build', + code: 'Hello', + idempotencyKey: 'first', + }) + await routeToolCall(actions, 'getDocumentation', undefined) + expect(actions.getDocumentation).toHaveBeenCalledWith({}) + }) + it('returns bad_request:invalid_input on schema-invalid input without dispatching', async () => { const actions = makeActionsStub() const result = await routeToolCall(actions, 'goTo', { page: 'not-a-number' }) diff --git a/embed/test/webmcp.test.ts b/embed/test/webmcp.test.ts index 50c97fef..d40593b2 100644 --- a/embed/test/webmcp.test.ts +++ b/embed/test/webmcp.test.ts @@ -266,6 +266,50 @@ describe('attachEmbed({ webMCP })', () => { ]) }) + it('returns build inspection as native images without duplicating PNG bytes in text', async () => { + const modelContext = installModelContext(document) + const harness = mountReady({ webMCP: { enabled: true } }) + await waitForTools(modelContext, TOOL_COUNT) + const pending = findTool(modelContext, 'build_pdf').execute({ + action: 'status', + job_id: 'job', + inspect: {}, + }) + const request = await waitForRequest(harness, 'BUILD_PDF') + const page = { + page: 1, + image_data_url: 'data:image/png;base64,iVBORw0KGgo=', + image_width: 10, + image_height: 12, + badges: {}, + } + harness.reply(request, { + success: true, + data: { + job_id: 'job', + build_session_id: 'session', + revision: 1, + published_revision: 1, + status: 'succeeded', + page_count: 1, + warnings: [], + warnings_truncated: false, + inspection: { + success: true, + data: { pages: [page], omitted_pages: [] }, + }, + }, + }) + const result = await pending + expect(result.content[0]).toEqual({ + type: 'image', + data: 'iVBORw0KGgo=', + mimeType: 'image/png', + }) + expect(JSON.stringify(result.content[1])).not.toContain('base64') + expect(JSON.stringify(result.content[1])).toContain('published_revision') + }) + it('keeps the text envelope for a failed annotated page render', async () => { const modelContext = installModelContext(document) const harness = mountReady({ webMCP: { enabled: true } }) diff --git a/embed/tsup.config.ts b/embed/tsup.config.ts index d86ffe95..170807d1 100644 --- a/embed/tsup.config.ts +++ b/embed/tsup.config.ts @@ -18,6 +18,7 @@ export default defineConfig({ format: ['esm', 'cjs'], dts: true, treeshake: true, + minify: true, splitting: true, clean: true, external: ['zod', '@tanstack/ai'], diff --git a/react/src/embed-pdf.tsx b/react/src/embed-pdf.tsx index f4ee7bac..065b8c6e 100644 --- a/react/src/embed-pdf.tsx +++ b/react/src/embed-pdf.tsx @@ -408,6 +408,8 @@ export const useEmbed = (): { const actions = React.useMemo( () => ({ + buildPdf: (input) => embedRef.current?.buildPdf(input) ?? notMounted(), + getDocumentation: (input) => embedRef.current?.getDocumentation(input) ?? notMounted(), batchSetFieldValues: (input) => embedRef.current?.batchSetFieldValues(input) ?? notMounted(), createField: (input) => embedRef.current?.createField(input) ?? notMounted(), deleteFields: (input) => embedRef.current?.deleteFields(input) ?? notMounted(), From c479a479b314ec2467241f2fc33320f704e47ee0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20Andr=C3=A9-Micolon?= Date: Mon, 23 Nov 2026 05:45:55 +0000 Subject: [PATCH 02/12] fix: preserve strict PDF build contracts across SDK adapters --- .changeset/build-pdf-browser.md | 5 +- embed/README.md | 2 +- embed/embed-api.json | 103 +++++++---- embed/etc/ai-sdk.api.md | 5 +- embed/etc/protocol.api.md | 8 +- embed/etc/schemas.api.md | 16 +- embed/etc/tanstack-ai.api.md | 3 +- embed/etc/tools.api.md | 172 +++++++++--------- embed/scripts/generate.mjs | 72 +++++--- embed/src/bridge.ts | 27 ++- embed/src/case-transform.ts | 6 +- .../{method-names.ts => bridge-vocabulary.ts} | 5 +- embed/src/generated/contract.ts | 12 +- embed/src/generated/schemas.ts | 16 +- embed/src/generated/tools.ts | 21 ++- embed/src/generated/webmcp-tools.ts | 7 +- embed/src/mount.ts | 2 +- embed/src/result.ts | 10 +- embed/src/webmcp.ts | 85 +++------ embed/test/bridge.test.ts | 18 ++ embed/test/helpers.ts | 7 +- embed/test/tanstack-ai.test.ts | 4 + embed/test/tools.test.ts | 29 +++ embed/test/webmcp.test.ts | 37 +++- embed/tsup.config.ts | 2 + react/README.md | 2 +- skills/build-with-simplepdf/SKILL.md | 4 +- 27 files changed, 397 insertions(+), 283 deletions(-) rename embed/src/generated/{method-names.ts => bridge-vocabulary.ts} (66%) diff --git a/.changeset/build-pdf-browser.md b/.changeset/build-pdf-browser.md index 05c6fff6..560714bf 100644 --- a/.changeset/build-pdf-browser.md +++ b/.changeset/build-pdf-browser.md @@ -3,4 +3,7 @@ '@simplepdf/react-embed-pdf': minor --- -Add typed browser PDF building, task documentation and revision-bound inspection. Build results discriminate job status and WebMCP returns inspection images separately from text. Existing field operations keep their contracts. +**Build and revise PDFs directly in the browser editor.** +- Use typed JavaScript and React methods for PDF building and task documentation. +- Inspect the published revision through native WebMCP images. +- Existing field operations keep their contracts. diff --git a/embed/README.md b/embed/README.md index 20aa521a..2e77b715 100644 --- a/embed/README.md +++ b/embed/README.md @@ -92,7 +92,7 @@ createEmbed({ target: '#editor', companyIdentifier: 'acme', document: { url: 'ht ``` - **Off by default.** `{ enabled: false }` and omitting the option are the same state. -- **The tools are the editor's own.** Each one is the record the editor publishes in its manifest (`https://simplepdf.com/embed/json`, `operations[].tool`) and registers on its own page: the `simplepdf_embed_*` name, description, snake_case input schema and behavior hints (the readers carry the specification's `readOnlyHint` and `untrustedContentHint`; every other tool MCP's `destructiveHint`; the three that fetch an agent-supplied URL `openWorldHint`). A page gets the same tools whether the editor is embedded or opened directly. `exclude` takes SDK method names. +- **The tools are the editor's own.** Each one is the record the editor publishes in its manifest (`https://simplepdf.com/embed/json`, `operations[].tool`) and registers on its own page: the published tool name, description, snake_case input schema and behavior hints (the readers carry the specification's `readOnlyHint` and `untrustedContentHint`; every other tool MCP's `destructiveHint`; the three that fetch an agent-supplied URL `openWorldHint`). `build_pdf` and `get_documentation` use those names; existing tools retain the `simplepdf_embed_` prefix. A page gets the same tools whether the editor is embedded or opened directly. `exclude` takes SDK method names. - **Data path.** Every operation an agent can call runs in the browser, and nothing the agent reads (field values, extracted text, a page render) is computed server-side; it goes to the agent runtime the person attached, so treat that runtime as you would any other party that sees the filled document. Document storage is unchanged by this option: it follows your account's configuration exactly as it does without WebMCP (SimplePDF-managed storage, or your own S3, Azure Blob Storage or SharePoint), and `submit` sends the document through the same submission flow as a click on Submit. - **Timing.** Tools register once the editor is ready. While no usable model context has been found, the page is probed again on each later lifecycle transition, so a context installed after `EDITOR_READY` is still picked up, and until one appears nothing is loaded (`webmcp.unavailable` is logged, with the reason). - **Results.** The editor validates each call like any other request (its permission model applies at call time: editing, allowlisted origin, plan, so a tool your configuration refuses resolves with the matching error code). A call resolves with an MCP tool result whose text is the editor's wire-shaped `{ success, data | error }` Result (`isError` on failure); `simplepdf_embed_get_annotated_page` carries its PNG as an `image` content block, with the badges map in the text block. A call the runtime aborted before it ran rejects and never reaches the editor. diff --git a/embed/embed-api.json b/embed/embed-api.json index 8fe6fdaf..afc1f130 100644 --- a/embed/embed-api.json +++ b/embed/embed-api.json @@ -93,9 +93,8 @@ "operations": [ { "request_type": "BUILD_PDF", - "description": "Build and display a PDF locally from Typst code. Read get_documentation for task recipes, templates, fonts and limits. Request inspect:{} for revision-bound page images in the same response. Use a stable idempotency key; poll the job if needed. Inspect the successful revision with simplepdf_embed_get_annotated_page. Manual edits block replacement. Does not submit or share.", + "description": "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Add inspect for page images. Edits block rebuilding. No sharing.", "input_schema": { - "description": "Build and display a PDF locally from Typst code. Read get_documentation for task recipes, templates, fonts and limits. Request inspect:{} for revision-bound page images in the same response. Use a stable idempotency key; poll the job if needed. Inspect the successful revision with simplepdf_embed_get_annotated_page. Manual edits block replacement. Does not submit or share.", "anyOf": [ { "type": "object", @@ -113,7 +112,8 @@ "type": "integer" } } - } + }, + "additionalProperties": false }, "code": { "type": "string" @@ -145,7 +145,8 @@ "required": [ "path", "data_url" - ] + ], + "additionalProperties": false } }, "wait_ms": { @@ -156,7 +157,8 @@ "action", "code", "idempotency_key" - ] + ], + "additionalProperties": false }, { "type": "object", @@ -180,13 +182,15 @@ "type": "integer" } } - } + }, + "additionalProperties": false } }, "required": [ "action", "job_id" - ] + ], + "additionalProperties": false }, { "type": "object", @@ -202,9 +206,11 @@ "required": [ "action", "job_id" - ] + ], + "additionalProperties": false } - ] + ], + "description": "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Add inspect for page images. Edits block rebuilding. No sharing." }, "output_schema": { "anyOf": [ @@ -238,7 +244,8 @@ "published_revision", "status", "poll_after_ms" - ] + ], + "additionalProperties": false }, { "type": "object", @@ -282,7 +289,8 @@ "status", "stage", "poll_after_ms" - ] + ], + "additionalProperties": false }, { "type": "object", @@ -342,7 +350,8 @@ "severity", "code", "message" - ] + ], + "additionalProperties": false } }, "warnings_truncated": { @@ -434,13 +443,15 @@ "required": [ "pages", "omitted_pages" - ] + ], + "additionalProperties": false } }, "required": [ "success", "data" - ] + ], + "additionalProperties": false }, { "type": "object", @@ -736,7 +747,8 @@ "required": [ "success", "error" - ] + ], + "additionalProperties": false } ] } @@ -750,7 +762,8 @@ "page_count", "warnings", "warnings_truncated" - ] + ], + "additionalProperties": false }, { "type": "object", @@ -846,7 +859,8 @@ "severity", "code", "message" - ] + ], + "additionalProperties": false } }, "diagnostics_truncated": { @@ -860,7 +874,8 @@ "retryable", "diagnostics", "diagnostics_truncated" - ] + ], + "additionalProperties": false } }, "required": [ @@ -870,7 +885,8 @@ "published_revision", "status", "error" - ] + ], + "additionalProperties": false }, { "type": "object", @@ -898,7 +914,8 @@ "revision", "published_revision", "status" - ] + ], + "additionalProperties": false }, { "type": "object", @@ -926,7 +943,8 @@ "revision", "published_revision", "status" - ] + ], + "additionalProperties": false } ] }, @@ -946,7 +964,7 @@ ], "tool": { "name": "build_pdf", - "description": "Build and display a PDF locally from Typst code. Read get_documentation for task recipes, templates, fonts and limits. Request inspect:{} for revision-bound page images in the same response. Use a stable idempotency key; poll the job if needed. Inspect the successful revision with simplepdf_embed_get_annotated_page. Manual edits block replacement. Does not submit or share.", + "description": "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Add inspect for page images. Edits block rebuilding. No sharing.", "input_schema": { "anyOf": [ { @@ -965,7 +983,8 @@ "type": "integer" } } - } + }, + "additionalProperties": false }, "code": { "type": "string" @@ -997,7 +1016,8 @@ "required": [ "path", "data_url" - ] + ], + "additionalProperties": false } }, "wait_ms": { @@ -1008,7 +1028,8 @@ "action", "code", "idempotency_key" - ] + ], + "additionalProperties": false }, { "type": "object", @@ -1032,13 +1053,15 @@ "type": "integer" } } - } + }, + "additionalProperties": false } }, "required": [ "action", "job_id" - ] + ], + "additionalProperties": false }, { "type": "object", @@ -1054,7 +1077,8 @@ "required": [ "action", "job_id" - ] + ], + "additionalProperties": false } ], "type": "object", @@ -1068,7 +1092,7 @@ }, { "request_type": "GET_DOCUMENTATION", - "description": "Read task documentation for the SimplePDF browser API. Omit topic for the index. Includes PDF building, templates, forms, fields and inspection. Guidance does not modify the document or grant permissions.", + "description": "Read task guidance and tested PDF recipes. Omit topic for the index.", "input_schema": { "type": "object", "properties": { @@ -1086,7 +1110,8 @@ ] } }, - "description": "Read task documentation for the SimplePDF browser API. Omit topic for the index. Includes PDF building, templates, forms, fields and inspection. Guidance does not modify the document or grant permissions." + "additionalProperties": false, + "description": "Read task guidance and tested PDF recipes. Omit topic for the index." }, "output_schema": { "anyOf": [ @@ -1122,14 +1147,16 @@ "required": [ "topic", "description" - ] + ], + "additionalProperties": false } } }, "required": [ "kind", "topics" - ] + ], + "additionalProperties": false }, { "type": "object", @@ -1159,7 +1186,8 @@ "kind", "topic", "markdown" - ] + ], + "additionalProperties": false } ] }, @@ -1168,8 +1196,9 @@ ], "tool": { "name": "get_documentation", - "description": "Read task documentation for the SimplePDF browser API. Omit topic for the index. Includes PDF building, templates, forms, fields and inspection. Guidance does not modify the document or grant permissions.", + "description": "Read task guidance and tested PDF recipes. Omit topic for the index.", "input_schema": { + "additionalProperties": false, "type": "object", "properties": { "topic": { @@ -1683,6 +1712,7 @@ "required": [ "page" ], + "additionalProperties": false, "description": "Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block." }, "output_schema": { @@ -1761,6 +1791,7 @@ "required": [ "page" ], + "additionalProperties": false, "type": "object", "properties": { "page": { @@ -2364,7 +2395,7 @@ "events": [ { "event_type": "EDITOR_READY", - "description": "Pushed once when the editor iframe boots in loading-placeholder mode (the loadingPlaceholder=true iframe query flag, which @simplepdf/embed sets while it waits to post LOAD_DOCUMENT) and accepts operations; before it, LOAD_DOCUMENT fails with bad_request:editor_not_ready and every other operation with bad_request:no_document_loaded. An iframe opened with a document instead goes straight to DOCUMENT_LOADED. It is not replayed: a listener attached after boot never receives it, so treat bad_request:editor_not_ready as \"retry shortly\" rather than waiting for this event.", + "description": "Pushed once when the editor iframe boots in loading-placeholder mode (the loadingPlaceholder=true iframe query flag, which @simplepdf/embed sets while it waits to post LOAD_DOCUMENT) and accepts operations; before it, LOAD_DOCUMENT fails with bad_request:editor_not_ready and document-dependent operations with bad_request:no_document_loaded; PDF building and documentation are available in an empty editor. An iframe opened with a document instead goes straight to DOCUMENT_LOADED. It is not replayed: a listener attached after boot never receives it, so treat bad_request:editor_not_ready as \"retry shortly\" rather than waiting for this event.", "payload_schema": { "type": "object", "properties": {} @@ -2372,7 +2403,7 @@ }, { "event_type": "DOCUMENT_LOADED", - "description": "Pushed exactly once per loaded document, when the document and its fields are ready; the payload carries the document_id. It follows the LOAD_DOCUMENT reply, which is itself sent once the document is ready, so a request sent after that reply acts on the new document; before any document, operations other than LOAD_DOCUMENT fail with bad_request:no_document_loaded, and until it fires for a document the page opened itself GET_FIELDS may report an incomplete field list. On a blank editor it fires once a document is loaded, by LOAD_DOCUMENT or by the user.", + "description": "Pushed exactly once per loaded document, when the document and its fields are ready; the payload carries the document_id. It follows the LOAD_DOCUMENT reply, which is itself sent once the document is ready, so a request sent after that reply acts on the new document; before any document, document-dependent operations fail with bad_request:no_document_loaded; PDF building and documentation are available in an empty editor, and until it fires for a document the page opened itself GET_FIELDS may report an incomplete field list. On a blank editor it fires once a document is loaded, by LOAD_DOCUMENT or by the user.", "payload_schema": { "type": "object", "properties": { diff --git a/embed/etc/ai-sdk.api.md b/embed/etc/ai-sdk.api.md index 1c565a7f..eabf065e 100644 --- a/embed/etc/ai-sdk.api.md +++ b/embed/etc/ai-sdk.api.md @@ -4,8 +4,7 @@ ```ts -import * as zod from 'zod'; -import * as zod_v4_core from 'zod/v4/core'; +import { z } from 'zod'; // Warning: (ae-forgotten-export) The symbol "BridgeResult" needs to be exported by the entry point ai-sdk.d.ts // @@ -24,7 +23,7 @@ export type SimplePDFToolName = keyof typeof TOOL_DEFINITIONS; // Warnings were encountered during analysis: // -// dist/ai-sdk.d.ts:10:5 - (ae-forgotten-export) The symbol "Embed" needs to be exported by the entry point ai-sdk.d.ts +// dist/ai-sdk.d.ts:9:5 - (ae-forgotten-export) The symbol "Embed" needs to be exported by the entry point ai-sdk.d.ts // (No @packageDocumentation comment for this package) diff --git a/embed/etc/protocol.api.md b/embed/etc/protocol.api.md index 3e3e555b..8b19de8f 100644 --- a/embed/etc/protocol.api.md +++ b/embed/etc/protocol.api.md @@ -30,7 +30,7 @@ export const OPERATIONS: readonly [{ readonly request_type: "BUILD_PDF"; readonly wire_type: "BUILD_PDF"; readonly method: "buildPdf"; - readonly description: "Build and display a PDF locally from Typst code. Read get_documentation for task recipes, templates, fonts and limits. Request inspect:{} for revision-bound page images in the same response. Use a stable idempotency key; poll the job if needed. Inspect the successful revision with simplepdf_embed_get_annotated_page. Manual edits block replacement. Does not submit or share."; + readonly description: "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Add inspect for page images. Edits block rebuilding. No sharing."; readonly error_codes: readonly ["conflict:build_session_mismatch", "conflict:base_revision_mismatch", "conflict:idempotency_key_reused", "conflict:editor_modified", "conflict:unmanaged_document", "not_found:job", "not_found:job_expired", "resource:session_limit", "conflict:inspection_revision_mismatch", "conflict:inspection_state_changed", "bad_request:invalid_value", "forbidden:editing_not_allowed"]; readonly is_agentic_tool: true; readonly has_output: true; @@ -38,7 +38,7 @@ export const OPERATIONS: readonly [{ readonly request_type: "GET_DOCUMENTATION"; readonly wire_type: "GET_DOCUMENTATION"; readonly method: "getDocumentation"; - readonly description: "Read task documentation for the SimplePDF browser API. Omit topic for the index. Includes PDF building, templates, forms, fields and inspection. Guidance does not modify the document or grant permissions."; + readonly description: "Read task guidance and tested PDF recipes. Omit topic for the index."; readonly error_codes: readonly ["bad_request:invalid_value"]; readonly is_agentic_tool: true; readonly has_output: true; @@ -186,10 +186,10 @@ export const OUTBOUND_EVENT_TYPES: ("EDITOR_READY" | "DOCUMENT_LOADED" | "PAGE_F // @public (undocumented) export const OUTBOUND_EVENTS: readonly [{ readonly event_type: "EDITOR_READY"; - readonly description: "Pushed once when the editor iframe boots in loading-placeholder mode (the loadingPlaceholder=true iframe query flag, which @simplepdf/embed sets while it waits to post LOAD_DOCUMENT) and accepts operations; before it, LOAD_DOCUMENT fails with bad_request:editor_not_ready and every other operation with bad_request:no_document_loaded. An iframe opened with a document instead goes straight to DOCUMENT_LOADED. It is not replayed: a listener attached after boot never receives it, so treat bad_request:editor_not_ready as \"retry shortly\" rather than waiting for this event."; + readonly description: "Pushed once when the editor iframe boots in loading-placeholder mode (the loadingPlaceholder=true iframe query flag, which @simplepdf/embed sets while it waits to post LOAD_DOCUMENT) and accepts operations; before it, LOAD_DOCUMENT fails with bad_request:editor_not_ready and document-dependent operations with bad_request:no_document_loaded; PDF building and documentation are available in an empty editor. An iframe opened with a document instead goes straight to DOCUMENT_LOADED. It is not replayed: a listener attached after boot never receives it, so treat bad_request:editor_not_ready as \"retry shortly\" rather than waiting for this event."; }, { readonly event_type: "DOCUMENT_LOADED"; - readonly description: "Pushed exactly once per loaded document, when the document and its fields are ready; the payload carries the document_id. It follows the LOAD_DOCUMENT reply, which is itself sent once the document is ready, so a request sent after that reply acts on the new document; before any document, operations other than LOAD_DOCUMENT fail with bad_request:no_document_loaded, and until it fires for a document the page opened itself GET_FIELDS may report an incomplete field list. On a blank editor it fires once a document is loaded, by LOAD_DOCUMENT or by the user."; + readonly description: "Pushed exactly once per loaded document, when the document and its fields are ready; the payload carries the document_id. It follows the LOAD_DOCUMENT reply, which is itself sent once the document is ready, so a request sent after that reply acts on the new document; before any document, document-dependent operations fail with bad_request:no_document_loaded; PDF building and documentation are available in an empty editor, and until it fires for a document the page opened itself GET_FIELDS may report an incomplete field list. On a blank editor it fires once a document is loaded, by LOAD_DOCUMENT or by the user."; }, { readonly event_type: "PAGE_FOCUSED"; readonly description: "Pushed when the focused page changes (the user scrolls to a new page, or a GO_TO completes). The payload reports the current page."; diff --git a/embed/etc/schemas.api.md b/embed/etc/schemas.api.md index 579de73a..fbcf6d94 100644 --- a/embed/etc/schemas.api.md +++ b/embed/etc/schemas.api.md @@ -22,7 +22,7 @@ export const BuildPdfInput: z.ZodUnion; inspect: z.ZodOptional>; - }, z.core.$strip>>; + }, z.core.$strict>>; code: z.ZodString; idempotencyKey: z.ZodString; buildSessionId: z.ZodOptional; @@ -31,19 +31,19 @@ export const BuildPdfInput: z.ZodUnion>>; + }, z.core.$strict>>>; waitMs: z.ZodOptional; -}, z.core.$strip>, z.ZodObject<{ +}, z.core.$strict>, z.ZodObject<{ action: z.ZodLiteral<"status">; jobId: z.ZodString; waitMs: z.ZodOptional; inspect: z.ZodOptional>; - }, z.core.$strip>>; -}, z.core.$strip>, z.ZodObject<{ + }, z.core.$strict>>; +}, z.core.$strict>, z.ZodObject<{ action: z.ZodLiteral<"cancel">; jobId: z.ZodString; -}, z.core.$strip>]>; +}, z.core.$strict>]>; // @public (undocumented) export type BuildPdfInput = z.infer; @@ -111,7 +111,7 @@ export const GetAnnotatedPageInput: z.ZodObject<{ expectedBuildSessionId: z.ZodOptional; expectedRevision: z.ZodOptional; expectedEditorStateVersion: z.ZodOptional; -}, z.core.$strip>; +}, z.core.$strict>; // @public (undocumented) export type GetAnnotatedPageInput = z.infer; @@ -128,7 +128,7 @@ export const GetDocumentationInput: z.ZodObject<{ fields: "fields"; inspection: "inspection"; }>>; -}, z.core.$strip>; +}, z.core.$strict>; // @public (undocumented) export type GetDocumentationInput = z.infer; diff --git a/embed/etc/tanstack-ai.api.md b/embed/etc/tanstack-ai.api.md index 4bb34bb4..b85846e7 100644 --- a/embed/etc/tanstack-ai.api.md +++ b/embed/etc/tanstack-ai.api.md @@ -6,6 +6,7 @@ import { AnyClientTool } from '@tanstack/ai'; import * as _tanstack_ai from '@tanstack/ai'; +import { z } from 'zod'; import * as zod from 'zod'; import * as zod_v4_core from 'zod/v4/core'; @@ -26,7 +27,7 @@ export type SimplePDFToolName = keyof typeof TOOL_DEFINITIONS; // Warnings were encountered during analysis: // -// dist/tanstack-ai.d.ts:105:5 - (ae-forgotten-export) The symbol "Embed" needs to be exported by the entry point tanstack-ai.d.ts +// dist/tanstack-ai.d.ts:96:5 - (ae-forgotten-export) The symbol "Embed" needs to be exported by the entry point tanstack-ai.d.ts // (No @packageDocumentation comment for this package) diff --git a/embed/etc/tools.api.md b/embed/etc/tools.api.md index d49efa25..dc65b7f7 100644 --- a/embed/etc/tools.api.md +++ b/embed/etc/tools.api.md @@ -4,8 +4,7 @@ ```ts -import * as zod from 'zod'; -import * as zod_v4_core from 'zod/v4/core'; +import { z } from 'zod'; // @public (undocumented) export const isSimplePDFToolName: (value: unknown) => value is SimplePDFToolName; @@ -19,38 +18,29 @@ export const routeToolCall: (actions: IframeActions, toolName: SimplePDFToolName // @public (undocumented) export const SIMPLEPDF_TOOLS: { readonly buildPdf: { - readonly description: "Build and display a PDF locally from Typst code. Read get_documentation for task recipes, templates, fonts and limits. Request inspect:{} for revision-bound page images in the same response. Use a stable idempotency key; poll the job if needed. Inspect the successful revision with simplepdf_embed_get_annotated_page. Manual edits block replacement. Does not submit or share."; - readonly inputSchema: zod.ZodUnion; - inspect: zod.ZodOptional>; - }, zod_v4_core.$strip>>; - code: zod.ZodString; - idempotencyKey: zod.ZodString; - buildSessionId: zod.ZodOptional; - baseRevision: zod.ZodOptional; - name: zod.ZodOptional; - assets: zod.ZodOptional>>; - waitMs: zod.ZodOptional; - }, zod_v4_core.$strip>, zod.ZodObject<{ - action: zod.ZodLiteral<"status">; - jobId: zod.ZodString; - waitMs: zod.ZodOptional; - inspect: zod.ZodOptional>; - }, zod_v4_core.$strip>>; - }, zod_v4_core.$strip>, zod.ZodObject<{ - action: zod.ZodLiteral<"cancel">; - jobId: zod.ZodString; - }, zod_v4_core.$strip>]>; + readonly description: "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Add inspect for page images. Edits block rebuilding. No sharing."; + readonly inputSchema: z.ZodObject<{ + action: z.ZodUnion, z.ZodLiteral<"status">, z.ZodLiteral<"cancel">]>; + inspect: z.ZodOptional>; + }, z.core.$strict>>; + code: z.ZodOptional; + idempotencyKey: z.ZodOptional; + buildSessionId: z.ZodOptional; + baseRevision: z.ZodOptional; + name: z.ZodOptional; + assets: z.ZodOptional>>; + waitMs: z.ZodOptional; + jobId: z.ZodOptional; + }, z.core.$strict>; }; readonly getDocumentation: { - readonly description: "Read task documentation for the SimplePDF browser API. Omit topic for the index. Includes PDF building, templates, forms, fields and inspection. Guidance does not modify the document or grant permissions."; - readonly inputSchema: zod.ZodObject<{ - topic: zod.ZodOptional>; - }, zod_v4_core.$strip>; + }, z.core.$strict>; }; readonly batchSetFieldValues: { readonly description: "Set existing fields, addressed by ids from the field list, in one atomic undo step. If any update is rejected, nothing changes and the call fails with bad_request:batch_validation_failed, whose details list each rejection with its field id, code and message. Text is set at once, never typed. Returns no data."; - readonly inputSchema: zod.ZodObject<{ - updates: zod.ZodArray; - }, zod_v4_core.$strip>>; - }, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{ + updates: z.ZodArray; + }, z.core.$strip>>; + }, z.core.$strip>; }; readonly createField: { readonly description: "Create a new overlay field on a page. Returns the id of the created field."; - readonly inputSchema: zod.ZodObject<{ - type: zod.ZodEnum<{ + readonly inputSchema: z.ZodObject<{ + type: z.ZodEnum<{ TEXT: "TEXT"; SIGNATURE: "SIGNATURE"; PICTURE: "PICTURE"; CHECKBOX: "CHECKBOX"; COMB_TEXT: "COMB_TEXT"; }>; - x: zod.ZodNumber; - y: zod.ZodNumber; - width: zod.ZodNumber; - height: zod.ZodNumber; - page: zod.ZodNumber; - value: zod.ZodOptional; - }, zod_v4_core.$strip>; + x: z.ZodNumber; + y: z.ZodNumber; + width: z.ZodNumber; + height: z.ZodNumber; + page: z.ZodNumber; + value: z.ZodOptional; + }, z.core.$strip>; }; readonly deleteFields: { readonly description: "Delete overlay fields: the ones listed, every one on a page, or every one in the document. Returns the number of fields deleted. Destructive."; - readonly inputSchema: zod.ZodObject<{ - fieldIds: zod.ZodOptional>; - page: zod.ZodOptional; - }, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{ + fieldIds: z.ZodOptional>; + page: z.ZodOptional; + }, z.core.$strip>; }; readonly deletePages: { readonly description: "Delete pages from the document (it cannot delete every visible page). Returns no data. Destructive."; - readonly inputSchema: zod.ZodObject<{ - pages: zod.ZodArray; - }, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{ + pages: z.ZodArray; + }, z.core.$strip>; }; readonly detectFields: { readonly description: "Automatically detect fillable fields in the loaded document and add them as editable fields. Returns the number of fields detected."; - readonly inputSchema: zod.ZodObject<{}, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{}, z.core.$strip>; }; readonly download: { readonly description: "Generate and download the current document as a PDF. Returns no data."; - readonly inputSchema: zod.ZodObject<{}, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{}, z.core.$strip>; }; readonly focusField: { readonly description: "Scroll an existing field into view and focus it, addressed by its id from the field list. Returns a hint describing the user action expected next."; - readonly inputSchema: zod.ZodObject<{ - fieldId: zod.ZodString; - }, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{ + fieldId: z.ZodString; + }, z.core.$strip>; }; readonly getAnnotatedPage: { readonly description: "Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block."; - readonly inputSchema: zod.ZodObject<{ - page: zod.ZodNumber; - expectedBuildSessionId: zod.ZodOptional; - expectedRevision: zod.ZodOptional; - expectedEditorStateVersion: zod.ZodOptional; - }, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{ + page: z.ZodNumber; + expectedBuildSessionId: z.ZodOptional; + expectedRevision: z.ZodOptional; + expectedEditorStateVersion: z.ZodOptional; + }, z.core.$strict>; }; readonly getDocumentContent: { readonly description: "Extract the document's content page by page as Markdown, or as plain text when optical recognition is forced. Use it to read what the document says. Returns the document name and each page's content."; - readonly inputSchema: zod.ZodObject<{ - extractionMode: zod.ZodOptional>; - }, zod_v4_core.$strip>; + }, z.core.$strip>; }; readonly getFields: { readonly description: "List every fillable field in the loaded document, including native dropdown and radio AcroFields. Each field reports its id, name, type, page, current value, and the options its value must be one of, if any. Call this first to discover field ids before reading or setting values. To SEE where each field sits on the printed page, render the annotated page. Returns the field list."; - readonly inputSchema: zod.ZodObject<{}, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{}, z.core.$strip>; }; readonly goTo: { readonly description: "Scroll the editor to a page. Returns no data."; - readonly inputSchema: zod.ZodObject<{ - page: zod.ZodNumber; - }, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{ + page: z.ZodNumber; + }, z.core.$strip>; }; readonly movePage: { readonly description: "Move a page to another position, reordering the document. Returns no data. Destructive."; - readonly inputSchema: zod.ZodObject<{ - fromPage: zod.ZodNumber; - toPage: zod.ZodNumber; - }, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{ + fromPage: z.ZodNumber; + toPage: z.ZodNumber; + }, z.core.$strip>; }; readonly rotatePage: { readonly description: "Rotate a page 90 degrees clockwise. Returns no data. Destructive."; - readonly inputSchema: zod.ZodObject<{ - page: zod.ZodNumber; - }, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{ + page: z.ZodNumber; + }, z.core.$strip>; }; readonly selectTool: { readonly description: "Activate a field-placement tool in the editor toolbar so the user can draw that field type, or pass null to clear the active tool. Returns no data."; - readonly inputSchema: zod.ZodObject<{ - tool: zod.ZodNullable>; - }, zod_v4_core.$strip>; + }, z.core.$strip>; }; readonly setFieldValue: { readonly description: "Set or clear (null) one existing field, addressed by its id from the field list. Text is typed out unless animate is false. Returns no data."; - readonly inputSchema: zod.ZodObject<{ - animate: zod.ZodOptional; - fieldId: zod.ZodString; - value: zod.ZodNullable; - }, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{ + animate: z.ZodOptional; + fieldId: z.ZodString; + value: z.ZodNullable; + }, z.core.$strip>; }; readonly submit: { readonly description: "Submit the completed document through the editor's finalization flow. This is irreversible. Fails with bad_request:missing_required_fields when required fields are unfilled. Returns no data."; - readonly inputSchema: zod.ZodObject<{ - downloadCopy: zod.ZodBoolean; - }, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{ + downloadCopy: z.ZodBoolean; + }, z.core.$strip>; }; }; diff --git a/embed/scripts/generate.mjs b/embed/scripts/generate.mjs index 0e22ad26..3a339ac5 100644 --- a/embed/scripts/generate.mjs +++ b/embed/scripts/generate.mjs @@ -3,20 +3,8 @@ // source of truth; this script is the only consumer that re-materializes it as // TypeScript. Run via `npm run generate` (wired into prebuild + pretest). // -// Four outputs, all derived from one source so they cannot hand-drift: -// - src/generated/contract.ts : zero-runtime-dep plain TS types + const tables -// (locales, error codes, operations, events). -// The zero-dep root imports only from here and -// from method-names.ts. -// - src/generated/schemas.ts : zod schemas (peer dep). Each schema is compile-time -// drift-guarded against the plain type in contract.ts, -// so a divergence fails `tsc`. -// - src/generated/method-names.ts : the SDK method names alone, the one generated -// VALUE the zero-dep root imports (to validate -// `webMCP.exclude`). -// - src/generated/webmcp-tools.ts : each operation's WebMCP tool record (manifest -// `tool`), verbatim, read only by the lazily-loaded -// WebMCP module. +// The bridge vocabulary is separate from the full contract so the zero-dependency +// root does not download the operations table. Runtime schemas remain opt-in. // // The JSON Schema vocabulary in embed-api.json is closed and small (object/string/ // integer/number/boolean/null/array/enum/const/anyOf), so the emitter below covers @@ -69,8 +57,8 @@ const NAMED_ENUMS = new Map() // The closed vocabulary the emitter understands. A node carrying any other // keyword (minLength, pattern, format, minimum, oneOf, allOf, $ref, ...) fails // loud so a new manifest constraint can never be silently dropped from the -// generated types/schemas. `additionalProperties` is honored only as a schema on -// an object with no `properties` (a map: Record / z.record). +// generated types/schemas. `additionalProperties:false` preserves strict objects; a schema on an object +// without properties describes a map (Record / z.record). const KNOWN_SCHEMA_KEYWORDS = new Set([ 'type', 'enum', @@ -90,9 +78,9 @@ const assertKnownKeywords = (node) => { ) } } - if (node.additionalProperties !== undefined && !isMapNode(node)) { + if (node.additionalProperties !== undefined && node.additionalProperties !== false && !isMapNode(node)) { throw new Error( - `Unsupported 'additionalProperties' in ${JSON.stringify(node)} — only a schema on an object without 'properties' is honored (a map)`, + `Unsupported 'additionalProperties' in ${JSON.stringify(node)} — only false or a schema on an object without 'properties' is honored`, ) } if (isMapNode(node) && node.required !== undefined) { @@ -249,15 +237,16 @@ const zodForObject = (node) => { const properties = node.properties ?? {} const required = new Set(node.required ?? []) const keys = Object.keys(properties) + const constructor = node.additionalProperties === false ? 'z.strictObject' : 'z.object' if (keys.length === 0) { - return 'z.object({})' + return `${constructor}({})` } const members = keys.map((key) => { const inner = zodForNode(properties[key], { withDescription: true }) const withOptional = required.has(key) ? inner : `${inner}.optional()` return ` ${toCamel(key)}: ${withOptional},` }) - return `z.object({\n${members.join('\n')}\n})` + return `${constructor}({\n${members.join('\n')}\n})` } // --------------------------------------------------------------------------- @@ -333,8 +322,8 @@ const constArray = (name, values, typeName) => { const contractLines = [] contractLines.push('// AUTO-GENERATED from embed-api.json by scripts/generate.mjs. Do not edit by hand.') -contractLines.push('// Zero runtime dependencies: the zero-dep root imports only from this module and method-names.ts.') -contractLines.push("import type { METHOD_NAMES } from './method-names'") +contractLines.push('// Zero runtime dependencies: the zero-dep root imports only from this module and bridge-vocabulary.ts.') +contractLines.push("import type { METHOD_NAMES } from './bridge-vocabulary'") contractLines.push('') contractLines.push(constArray('LOCALES', contract.locales, 'Locale')) contractLines.push(constArray('EDITOR_ERROR_CODES', editorErrorCodes, 'EditorErrorCode')) @@ -445,17 +434,16 @@ schemaLines.push('') writeFileSync(join(GENERATED_DIR, 'schemas.ts'), renderFile(schemaLines)) -// --- method-names.ts (zero runtime deps; the one generated value the root imports) --- +// --- bridge-vocabulary.ts (the small runtime subset used by the root) --- const methodNames = contract.operations.map((op) => toCamel(op.request_type)) writeFileSync( - join(GENERATED_DIR, 'method-names.ts'), + join(GENERATED_DIR, 'bridge-vocabulary.ts'), renderFile([ '// AUTO-GENERATED from embed-api.json by scripts/generate.mjs. Do not edit by hand.', - '// The SDK method names alone, so createEmbed can validate a `webMCP.exclude` list', - '// without pulling the operations table into the zero-dep root; contract.ts derives', - '// MethodName from this list.', + '// Kept separate from the full manifest to preserve the root entry bundle boundary.', `export const METHOD_NAMES = [${methodNames.map((name) => JSON.stringify(name)).join(', ')}] as const`, + `export const EDITOR_ERROR_PREFIXES = ${JSON.stringify([...new Set(editorErrorCodes.map((code) => code.slice(0, code.indexOf(':') + 1)))])} as const\n`, ]), ) @@ -513,6 +501,7 @@ webmcpToolLines.push(" readonly type: 'object'") webmcpToolLines.push(' readonly properties?: Readonly>') webmcpToolLines.push(' readonly required?: readonly string[]') webmcpToolLines.push(' readonly anyOf?: readonly unknown[]') +webmcpToolLines.push(' readonly additionalProperties?: false') webmcpToolLines.push(' }') webmcpToolLines.push(' readonly annotations: {') for (const hint of WEBMCP_ANNOTATION_KEYS) { @@ -565,17 +554,42 @@ writeFileSync(join(GENERATED_DIR, 'drift.ts'), renderFile(driftLines)) const agenticOperations = contract.operations.filter( (op) => !NON_AGENTIC_OPERATIONS.has(op.request_type.toLowerCase()), ) +// Provider tools require an object root. The broad advertisement is derived from the +// same variants; dispatch still validates the exact action-specific input union. +const toolInputObject = (schema) => { + if (!schema.anyOf) return null + const variants = schema.anyOf + if (variants.some((variant) => variant.type !== 'object')) { + throw new Error('Tool input variants must be objects') + } + const keys = [...new Set(variants.flatMap((variant) => Object.keys(variant.properties ?? {})))] + return { + type: 'object', + additionalProperties: false, + properties: Object.fromEntries(keys.map((key) => { + const values = [...new Map(variants.flatMap((variant) => + variant.properties?.[key] ? [[JSON.stringify(variant.properties[key]), variant.properties[key]]] : [], + )).values()] + return [key, values.length === 1 ? values[0] : { anyOf: values }] + })), + required: keys.filter((key) => variants.every((variant) => variant.required?.includes(key))), + } +} + const toolLines = [] toolLines.push('// AUTO-GENERATED from embed-api.json by scripts/generate.mjs. Do not edit by hand.') toolLines.push("import * as Schemas from './schemas'") +toolLines.push("import { z } from 'zod'") toolLines.push('') toolLines.push('// The agentic tool registry. Each tool name is the camelCase operation name;') toolLines.push('// load_document is excluded here (a host/setup action; the WebMCP surface registers it).') toolLines.push('export const TOOL_DEFINITIONS = {') for (const op of agenticOperations) { const stem = toPascal(op.request_type) + const advertisement = toolInputObject(op.input_schema) + const inputSchema = advertisement ? zodForObject(advertisement) : `Schemas.${stem}Input` toolLines.push( - ` ${toCamel(op.request_type)}: { description: ${JSON.stringify(op.description)}, inputSchema: Schemas.${stem}Input },`, + ` ${toCamel(op.request_type)}: { description: ${JSON.stringify(op.description)}, inputSchema: ${inputSchema} },`, ) } toolLines.push('} as const') @@ -587,5 +601,5 @@ writeFileSync(join(GENERATED_DIR, 'tools.ts'), renderFile(toolLines)) console.log( `Generated contract.ts (${contract.operations.length} ops, ${contract.events.length} events, ` + - `${contract.locales.length} locales, ${editorErrorCodes.length} editor error codes) + schemas.ts + method-names.ts + webmcp-tools.ts`, + `${contract.locales.length} locales, ${editorErrorCodes.length} editor error codes) + schemas.ts + bridge-vocabulary.ts + webmcp-tools.ts`, ) diff --git a/embed/src/bridge.ts b/embed/src/bridge.ts index 1c8c3477..f33217e4 100644 --- a/embed/src/bridge.ts +++ b/embed/src/bridge.ts @@ -75,11 +75,11 @@ const relabelResult = (result: BridgeResult): BridgeResult) => void - resultShape: ResultShape + payloadShape: PayloadShape wireType: WireType startedAtMs: number timeoutId: ReturnType @@ -215,7 +215,7 @@ export const attachEmbed = ({ } } - const postRequest = (wireType: WireType, data: unknown, resultShape: ResultShape): Promise> => + const postRequest = (wireType: WireType, data: unknown, payloadShape: PayloadShape): Promise> => new Promise>((resolve) => { if (disposed) { resolve({ @@ -253,7 +253,7 @@ export const attachEmbed = ({ pending.set(requestId, { resolve: (result) => resolve(relabelResult(result)), - resultShape, + payloadShape, wireType, startedAtMs, timeoutId, @@ -262,7 +262,18 @@ export const attachEmbed = ({ // Serializing (circular / BigInt input) or posting (dead contentWindow) can // throw; convert that into a Result rather than rejecting the promise. try { - const outbound = JSON.stringify({ type: wireType, request_id: requestId, data: toWireData(data) }) + let wireData: unknown + switch (payloadShape) { + case 'sdk': + wireData = toWireData(data) + break + case 'wire': + wireData = data + break + default: + payloadShape satisfies never + } + const outbound = JSON.stringify({ type: wireType, request_id: requestId, data: wireData }) iframe.contentWindow.postMessage(outbound, editorOrigin) logger.debug('iframe.request_posted', { request_id: requestId, type: wireType, char_count: outbound.length }) } catch (error) { @@ -479,7 +490,7 @@ export const attachEmbed = ({ if (rawResult.success === true && !('data' in rawResult)) { return { success: true, data: null } } - switch (entry.resultShape) { + switch (entry.payloadShape) { case 'wire': return rawResult case 'sdk': { @@ -496,7 +507,7 @@ export const attachEmbed = ({ return camelCased } default: - entry.resultShape satisfies never + entry.payloadShape satisfies never return rawResult } })() @@ -516,7 +527,7 @@ export const attachEmbed = ({ // posts the request and correlates the reply; no client-side validation. const methods = { buildPdf: (input) => sendRequest('BUILD_PDF', input), - getDocumentation: (input) => sendRequest('GET_DOCUMENTATION', input), + getDocumentation: (input) => sendRequest('GET_DOCUMENTATION', input ?? {}), batchSetFieldValues: (input) => sendRequest('BATCH_SET_FIELD_VALUES', input), createField: (input) => sendRequest('CREATE_FIELD', input), // All-optional input: deleteFields() with no args clears every field. diff --git a/embed/src/case-transform.ts b/embed/src/case-transform.ts index 5173199c..8bc57ae1 100644 --- a/embed/src/case-transform.ts +++ b/embed/src/case-transform.ts @@ -46,10 +46,10 @@ const transformKeysDeep = (value: unknown, mapKey: (key: string) => string): unk return value } -// SDK (camelCase) -> wire (snake_case), applied to every outbound request payload. +// SDK (camelCase) -> wire (snake_case), applied to SDK requests; WebMCP wire input passes through unchanged. export const toWireData = (input: unknown): unknown => transformKeysDeep(input, camelToSnakeKey) -// wire (snake_case) -> SDK (camelCase), applied to every inbound operation RESULT -// payload. Editor EVENTS are NOT transformed — they are forwarded verbatim (snake) to +// wire (snake_case) -> SDK (camelCase), applied to SDK operation results. WebMCP results remain wire-shaped. +// Editor EVENTS are NOT transformed — they are forwarded verbatim (snake) to // keep the established EmbedEvent contract. export const fromWireData = (data: unknown): unknown => transformKeysDeep(data, snakeToCamelKey) diff --git a/embed/src/generated/method-names.ts b/embed/src/generated/bridge-vocabulary.ts similarity index 66% rename from embed/src/generated/method-names.ts rename to embed/src/generated/bridge-vocabulary.ts index 1efd4528..7054d5e7 100644 --- a/embed/src/generated/method-names.ts +++ b/embed/src/generated/bridge-vocabulary.ts @@ -1,5 +1,4 @@ // AUTO-GENERATED from embed-api.json by scripts/generate.mjs. Do not edit by hand. -// The SDK method names alone, so createEmbed can validate a `webMCP.exclude` list -// without pulling the operations table into the zero-dep root; contract.ts derives -// MethodName from this list. +// Kept separate from the full manifest to preserve the root entry bundle boundary. export const METHOD_NAMES = ["buildPdf", "getDocumentation", "batchSetFieldValues", "createField", "deleteFields", "deletePages", "detectFields", "download", "focusField", "getAnnotatedPage", "getDocumentContent", "getFields", "goTo", "loadDocument", "movePage", "rotatePage", "selectTool", "setFieldValue", "submit"] as const +export const EDITOR_ERROR_PREFIXES = ["bad_request:","conflict:","forbidden:","not_found:","resource:","unexpected:"] as const diff --git a/embed/src/generated/contract.ts b/embed/src/generated/contract.ts index d29bd8c3..a56f09a4 100644 --- a/embed/src/generated/contract.ts +++ b/embed/src/generated/contract.ts @@ -1,6 +1,6 @@ // AUTO-GENERATED from embed-api.json by scripts/generate.mjs. Do not edit by hand. -// Zero runtime dependencies: the zero-dep root imports only from this module and method-names.ts. -import type { METHOD_NAMES } from './method-names' +// Zero runtime dependencies: the zero-dep root imports only from this module and bridge-vocabulary.ts. +import type { METHOD_NAMES } from './bridge-vocabulary' export const LOCALES = ["fr", "en", "it", "de", "pt", "es", "ja", "nl"] as const export type Locale = (typeof LOCALES)[number] @@ -76,7 +76,7 @@ export const OPERATIONS = [ request_type: "BUILD_PDF", wire_type: "BUILD_PDF", method: "buildPdf", - description: "Build and display a PDF locally from Typst code. Read get_documentation for task recipes, templates, fonts and limits. Request inspect:{} for revision-bound page images in the same response. Use a stable idempotency key; poll the job if needed. Inspect the successful revision with simplepdf_embed_get_annotated_page. Manual edits block replacement. Does not submit or share.", + description: "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Add inspect for page images. Edits block rebuilding. No sharing.", error_codes: ["conflict:build_session_mismatch", "conflict:base_revision_mismatch", "conflict:idempotency_key_reused", "conflict:editor_modified", "conflict:unmanaged_document", "not_found:job", "not_found:job_expired", "resource:session_limit", "conflict:inspection_revision_mismatch", "conflict:inspection_state_changed", "bad_request:invalid_value", "forbidden:editing_not_allowed"] as const, is_agentic_tool: true, has_output: true, @@ -85,7 +85,7 @@ export const OPERATIONS = [ request_type: "GET_DOCUMENTATION", wire_type: "GET_DOCUMENTATION", method: "getDocumentation", - description: "Read task documentation for the SimplePDF browser API. Omit topic for the index. Includes PDF building, templates, forms, fields and inspection. Guidance does not modify the document or grant permissions.", + description: "Read task guidance and tested PDF recipes. Omit topic for the index.", error_codes: ["bad_request:invalid_value"] as const, is_agentic_tool: true, has_output: true, @@ -250,8 +250,8 @@ export type RequestType = (typeof OPERATIONS)[number]["request_type"] export type MethodName = (typeof METHOD_NAMES)[number] export const OUTBOUND_EVENTS = [ - { event_type: "EDITOR_READY", description: "Pushed once when the editor iframe boots in loading-placeholder mode (the loadingPlaceholder=true iframe query flag, which @simplepdf/embed sets while it waits to post LOAD_DOCUMENT) and accepts operations; before it, LOAD_DOCUMENT fails with bad_request:editor_not_ready and every other operation with bad_request:no_document_loaded. An iframe opened with a document instead goes straight to DOCUMENT_LOADED. It is not replayed: a listener attached after boot never receives it, so treat bad_request:editor_not_ready as \"retry shortly\" rather than waiting for this event." }, - { event_type: "DOCUMENT_LOADED", description: "Pushed exactly once per loaded document, when the document and its fields are ready; the payload carries the document_id. It follows the LOAD_DOCUMENT reply, which is itself sent once the document is ready, so a request sent after that reply acts on the new document; before any document, operations other than LOAD_DOCUMENT fail with bad_request:no_document_loaded, and until it fires for a document the page opened itself GET_FIELDS may report an incomplete field list. On a blank editor it fires once a document is loaded, by LOAD_DOCUMENT or by the user." }, + { event_type: "EDITOR_READY", description: "Pushed once when the editor iframe boots in loading-placeholder mode (the loadingPlaceholder=true iframe query flag, which @simplepdf/embed sets while it waits to post LOAD_DOCUMENT) and accepts operations; before it, LOAD_DOCUMENT fails with bad_request:editor_not_ready and document-dependent operations with bad_request:no_document_loaded; PDF building and documentation are available in an empty editor. An iframe opened with a document instead goes straight to DOCUMENT_LOADED. It is not replayed: a listener attached after boot never receives it, so treat bad_request:editor_not_ready as \"retry shortly\" rather than waiting for this event." }, + { event_type: "DOCUMENT_LOADED", description: "Pushed exactly once per loaded document, when the document and its fields are ready; the payload carries the document_id. It follows the LOAD_DOCUMENT reply, which is itself sent once the document is ready, so a request sent after that reply acts on the new document; before any document, document-dependent operations fail with bad_request:no_document_loaded; PDF building and documentation are available in an empty editor, and until it fires for a document the page opened itself GET_FIELDS may report an incomplete field list. On a blank editor it fires once a document is loaded, by LOAD_DOCUMENT or by the user." }, { event_type: "PAGE_FOCUSED", description: "Pushed when the focused page changes (the user scrolls to a new page, or a GO_TO completes). The payload reports the current page." }, { event_type: "SUBMISSION_SENT", description: "Pushed after a SUBMIT completes successfully. This is how you confirm a submission landed: the SUBMIT operation itself resolves with data: null, so listen for this event to get the resulting document_id and submission_id." }, ] as const diff --git a/embed/src/generated/schemas.ts b/embed/src/generated/schemas.ts index b175baaa..02ec41f6 100644 --- a/embed/src/generated/schemas.ts +++ b/embed/src/generated/schemas.ts @@ -1,9 +1,9 @@ // AUTO-GENERATED from embed-api.json by scripts/generate.mjs. Do not edit by hand. import { z } from 'zod' -export const BuildPdfInput = z.union([z.object({ +export const BuildPdfInput = z.union([z.strictObject({ action: z.literal("build"), - inspect: z.object({ + inspect: z.strictObject({ pages: z.array(z.number().int()).optional(), }).optional(), code: z.string(), @@ -11,24 +11,24 @@ export const BuildPdfInput = z.union([z.object({ buildSessionId: z.string().optional(), baseRevision: z.number().int().optional(), name: z.string().optional(), - assets: z.array(z.object({ + assets: z.array(z.strictObject({ path: z.string(), dataUrl: z.string(), })).optional(), waitMs: z.number().int().optional(), -}), z.object({ +}), z.strictObject({ action: z.literal("status"), jobId: z.string(), waitMs: z.number().int().optional(), - inspect: z.object({ + inspect: z.strictObject({ pages: z.array(z.number().int()).optional(), }).optional(), -}), z.object({ +}), z.strictObject({ action: z.literal("cancel"), jobId: z.string(), })]) export type BuildPdfInput = z.infer -export const GetDocumentationInput = z.object({ +export const GetDocumentationInput = z.strictObject({ topic: z.enum(["build_pdf", "build_pdf.templates", "build_pdf.forms", "build_pdf.assets", "build_pdf.fonts", "build_pdf.troubleshooting", "fields", "inspection"]).optional(), }) export type GetDocumentationInput = z.infer @@ -66,7 +66,7 @@ export const FocusFieldInput = z.object({ fieldId: z.string().describe("ID of the field to focus and scroll into view."), }) export type FocusFieldInput = z.infer -export const GetAnnotatedPageInput = z.object({ +export const GetAnnotatedPageInput = z.strictObject({ page: z.number().int().describe("1-based page to render, at its current position."), expectedBuildSessionId: z.string().optional(), expectedRevision: z.number().int().optional(), diff --git a/embed/src/generated/tools.ts b/embed/src/generated/tools.ts index 49cae62c..e4c32bd4 100644 --- a/embed/src/generated/tools.ts +++ b/embed/src/generated/tools.ts @@ -1,11 +1,28 @@ // AUTO-GENERATED from embed-api.json by scripts/generate.mjs. Do not edit by hand. import * as Schemas from './schemas' +import { z } from 'zod' // The agentic tool registry. Each tool name is the camelCase operation name; // load_document is excluded here (a host/setup action; the WebMCP surface registers it). export const TOOL_DEFINITIONS = { - buildPdf: { description: "Build and display a PDF locally from Typst code. Read get_documentation for task recipes, templates, fonts and limits. Request inspect:{} for revision-bound page images in the same response. Use a stable idempotency key; poll the job if needed. Inspect the successful revision with simplepdf_embed_get_annotated_page. Manual edits block replacement. Does not submit or share.", inputSchema: Schemas.BuildPdfInput }, - getDocumentation: { description: "Read task documentation for the SimplePDF browser API. Omit topic for the index. Includes PDF building, templates, forms, fields and inspection. Guidance does not modify the document or grant permissions.", inputSchema: Schemas.GetDocumentationInput }, + buildPdf: { description: "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Add inspect for page images. Edits block rebuilding. No sharing.", inputSchema: z.strictObject({ + action: z.union([z.literal("build"), z.literal("status"), z.literal("cancel")]), + inspect: z.strictObject({ + pages: z.array(z.number().int()).optional(), +}).optional(), + code: z.string().optional(), + idempotencyKey: z.string().optional(), + buildSessionId: z.string().optional(), + baseRevision: z.number().int().optional(), + name: z.string().optional(), + assets: z.array(z.strictObject({ + path: z.string(), + dataUrl: z.string(), +})).optional(), + waitMs: z.number().int().optional(), + jobId: z.string().optional(), +}) }, + getDocumentation: { description: "Read task guidance and tested PDF recipes. Omit topic for the index.", inputSchema: Schemas.GetDocumentationInput }, batchSetFieldValues: { description: "Set existing fields, addressed by ids from the field list, in one atomic undo step. If any update is rejected, nothing changes and the call fails with bad_request:batch_validation_failed, whose details list each rejection with its field id, code and message. Text is set at once, never typed. Returns no data.", inputSchema: Schemas.BatchSetFieldValuesInput }, createField: { description: "Create a new overlay field on a page. Returns the id of the created field.", inputSchema: Schemas.CreateFieldInput }, deleteFields: { description: "Delete overlay fields: the ones listed, every one on a page, or every one in the document. Returns the number of fields deleted. Destructive.", inputSchema: Schemas.DeleteFieldsInput }, diff --git a/embed/src/generated/webmcp-tools.ts b/embed/src/generated/webmcp-tools.ts index 99d747c2..1b3b6b81 100644 --- a/embed/src/generated/webmcp-tools.ts +++ b/embed/src/generated/webmcp-tools.ts @@ -16,6 +16,7 @@ export type WebMCPToolRecord = { readonly properties?: Readonly> readonly required?: readonly string[] readonly anyOf?: readonly unknown[] + readonly additionalProperties?: false } readonly annotations: { readonly destructiveHint?: boolean @@ -26,8 +27,8 @@ export type WebMCPToolRecord = { } export const WEBMCP_TOOLS = { - buildPdf: {"name":"build_pdf","description":"Build and display a PDF locally from Typst code. Read get_documentation for task recipes, templates, fonts and limits. Request inspect:{} for revision-bound page images in the same response. Use a stable idempotency key; poll the job if needed. Inspect the successful revision with simplepdf_embed_get_annotated_page. Manual edits block replacement. Does not submit or share.","inputSchema":{"anyOf":[{"type":"object","properties":{"action":{"type":"string","const":"build"},"inspect":{"type":"object","properties":{"pages":{"type":"array","items":{"type":"integer"}}}},"code":{"type":"string"},"idempotency_key":{"type":"string"},"build_session_id":{"type":"string"},"base_revision":{"type":"integer"},"name":{"type":"string"},"assets":{"type":"array","items":{"type":"object","properties":{"path":{"type":"string"},"data_url":{"type":"string"}},"required":["path","data_url"]}},"wait_ms":{"type":"integer"}},"required":["action","code","idempotency_key"]},{"type":"object","properties":{"action":{"type":"string","const":"status"},"job_id":{"type":"string"},"wait_ms":{"type":"integer"},"inspect":{"type":"object","properties":{"pages":{"type":"array","items":{"type":"integer"}}}}},"required":["action","job_id"]},{"type":"object","properties":{"action":{"type":"string","const":"cancel"},"job_id":{"type":"string"}},"required":["action","job_id"]}],"type":"object","properties":{}},"annotations":{"destructiveHint":true,"untrustedContentHint":true},"wireType":"BUILD_PDF"}, - getDocumentation: {"name":"get_documentation","description":"Read task documentation for the SimplePDF browser API. Omit topic for the index. Includes PDF building, templates, forms, fields and inspection. Guidance does not modify the document or grant permissions.","inputSchema":{"type":"object","properties":{"topic":{"enum":["build_pdf","build_pdf.templates","build_pdf.forms","build_pdf.assets","build_pdf.fonts","build_pdf.troubleshooting","fields","inspection"],"type":"string"}}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_DOCUMENTATION"}, + buildPdf: {"name":"build_pdf","description":"Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Add inspect for page images. Edits block rebuilding. No sharing.","inputSchema":{"anyOf":[{"type":"object","properties":{"action":{"type":"string","const":"build"},"inspect":{"type":"object","properties":{"pages":{"type":"array","items":{"type":"integer"}}},"additionalProperties":false},"code":{"type":"string"},"idempotency_key":{"type":"string"},"build_session_id":{"type":"string"},"base_revision":{"type":"integer"},"name":{"type":"string"},"assets":{"type":"array","items":{"type":"object","properties":{"path":{"type":"string"},"data_url":{"type":"string"}},"required":["path","data_url"],"additionalProperties":false}},"wait_ms":{"type":"integer"}},"required":["action","code","idempotency_key"],"additionalProperties":false},{"type":"object","properties":{"action":{"type":"string","const":"status"},"job_id":{"type":"string"},"wait_ms":{"type":"integer"},"inspect":{"type":"object","properties":{"pages":{"type":"array","items":{"type":"integer"}}},"additionalProperties":false}},"required":["action","job_id"],"additionalProperties":false},{"type":"object","properties":{"action":{"type":"string","const":"cancel"},"job_id":{"type":"string"}},"required":["action","job_id"],"additionalProperties":false}],"type":"object","properties":{}},"annotations":{"destructiveHint":true,"untrustedContentHint":true},"wireType":"BUILD_PDF"}, + getDocumentation: {"name":"get_documentation","description":"Read task guidance and tested PDF recipes. Omit topic for the index.","inputSchema":{"additionalProperties":false,"type":"object","properties":{"topic":{"enum":["build_pdf","build_pdf.templates","build_pdf.forms","build_pdf.assets","build_pdf.fonts","build_pdf.troubleshooting","fields","inspection"],"type":"string"}}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_DOCUMENTATION"}, batchSetFieldValues: {"name":"simplepdf_embed_batch_set_field_values","description":"Set existing fields, addressed by ids from the field list, in one atomic undo step. If any update is rejected, nothing changes and the call fails with bad_request:batch_validation_failed, whose details list each rejection with its field id, code and message. Text is set at once, never typed. Returns no data.","inputSchema":{"required":["updates"],"type":"object","properties":{"updates":{"items":{"type":"object","properties":{"field_id":{"type":"string","description":"ID of the field to update."},"value":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"New value for the field, or null to clear it. If the field has options (see the field list), it must be one of them; otherwise a string (text/checkbox), or a data URL or http(s) URL, fetched by the editor (signature/picture), or plain text for a signature, drawn as a typed signature."}},"required":["field_id","value"]},"description":"The fields to set, at least one, each field at most once. Fields not listed keep their value.","type":"array"}}},"annotations":{"destructiveHint":false,"openWorldHint":true},"wireType":"BATCH_SET_FIELD_VALUES"}, createField: {"name":"simplepdf_embed_create_field","description":"Create a new overlay field on a page. Returns the id of the created field.","inputSchema":{"required":["type","x","y","width","height","page"],"type":"object","properties":{"type":{"enum":["TEXT","SIGNATURE","PICTURE","CHECKBOX","COMB_TEXT"],"description":"Field type to create.","type":"string"},"x":{"description":"Field x position, in PDF points.","type":"number"},"y":{"description":"Field y position, in PDF points.","type":"number"},"width":{"description":"Field width, in PDF points.","type":"number"},"height":{"description":"Field height, in PDF points.","type":"number"},"page":{"description":"1-based page to place the field on.","type":"integer"},"value":{"description":"Optional initial value. A string for text/checkbox fields; a data URL or http(s) URL (fetched by the editor) for signature/picture fields, or plain text for a signature, drawn as a typed signature.","type":"string"}}},"annotations":{"destructiveHint":false,"openWorldHint":true},"wireType":"CREATE_FIELD"}, deleteFields: {"name":"simplepdf_embed_delete_fields","description":"Delete overlay fields: the ones listed, every one on a page, or every one in the document. Returns the number of fields deleted. Destructive.","inputSchema":{"type":"object","properties":{"field_ids":{"description":"IDs of the fields to delete. Omit to delete every field on the target page.","items":{"type":"string"},"type":"array"},"page":{"description":"1-based page to scope the deletion to. Omit to target all pages.","type":"integer"}}},"annotations":{"destructiveHint":true},"wireType":"DELETE_FIELDS"}, @@ -35,7 +36,7 @@ export const WEBMCP_TOOLS = { detectFields: {"name":"simplepdf_embed_detect_fields","description":"Automatically detect fillable fields in the loaded document and add them as editable fields. Returns the number of fields detected.","inputSchema":{"type":"object","properties":{}},"annotations":{"destructiveHint":false},"wireType":"DETECT_FIELDS"}, download: {"name":"simplepdf_embed_download","description":"Generate and download the current document as a PDF. Returns no data.","inputSchema":{"type":"object","properties":{}},"annotations":{"destructiveHint":false},"wireType":"DOWNLOAD"}, focusField: {"name":"simplepdf_embed_focus_field","description":"Scroll an existing field into view and focus it, addressed by its id from the field list. Returns a hint describing the user action expected next.","inputSchema":{"required":["field_id"],"type":"object","properties":{"field_id":{"description":"ID of the field to focus and scroll into view.","type":"string"}}},"annotations":{"destructiveHint":false},"wireType":"FOCUS_FIELD"}, - getAnnotatedPage: {"name":"simplepdf_embed_get_annotated_page","description":"Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block.","inputSchema":{"required":["page"],"type":"object","properties":{"page":{"description":"1-based page to render, at its current position.","type":"integer"},"expected_build_session_id":{"type":"string"},"expected_revision":{"type":"integer"},"expected_editor_state_version":{"type":"integer"}}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_ANNOTATED_PAGE"}, + getAnnotatedPage: {"name":"simplepdf_embed_get_annotated_page","description":"Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block.","inputSchema":{"required":["page"],"additionalProperties":false,"type":"object","properties":{"page":{"description":"1-based page to render, at its current position.","type":"integer"},"expected_build_session_id":{"type":"string"},"expected_revision":{"type":"integer"},"expected_editor_state_version":{"type":"integer"}}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_ANNOTATED_PAGE"}, getDocumentContent: {"name":"simplepdf_embed_get_document_content","description":"Extract the document's content page by page as Markdown, or as plain text when optical recognition is forced. Use it to read what the document says. Returns the document name and each page's content.","inputSchema":{"type":"object","properties":{"extraction_mode":{"description":"Extraction strategy: 'auto' (default) or 'ocr' to force optical recognition.","enum":["auto","ocr"],"type":"string"}}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_DOCUMENT_CONTENT"}, getFields: {"name":"simplepdf_embed_get_fields","description":"List every fillable field in the loaded document, including native dropdown and radio AcroFields. Each field reports its id, name, type, page, current value, and the options its value must be one of, if any. Call this first to discover field ids before reading or setting values. To SEE where each field sits on the printed page, render the annotated page. Returns the field list.","inputSchema":{"type":"object","properties":{}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_FIELDS"}, goTo: {"name":"simplepdf_embed_go_to","description":"Scroll the editor to a page. Returns no data.","inputSchema":{"required":["page"],"type":"object","properties":{"page":{"description":"1-based page to navigate to.","type":"integer"}}},"annotations":{"destructiveHint":false},"wireType":"GO_TO"}, diff --git a/embed/src/mount.ts b/embed/src/mount.ts index c396c4b8..60075eba 100644 --- a/embed/src/mount.ts +++ b/embed/src/mount.ts @@ -1,7 +1,7 @@ import { attachEmbed } from './bridge' import { type BridgeLogger, makeSafeLogger, NOOP_LOGGER } from './logger' import type { BridgeState, Embed } from './types' -import { METHOD_NAMES } from './generated/method-names' +import { METHOD_NAMES } from './generated/bridge-vocabulary' import type { Locale } from './generated/contract' import type { WebMCPOptions } from './webmcp-shared' diff --git a/embed/src/result.ts b/embed/src/result.ts index ca0feaf5..3ee598b8 100644 --- a/embed/src/result.ts +++ b/embed/src/result.ts @@ -1,4 +1,5 @@ import type { BridgeResult } from './types' +import { EDITOR_ERROR_PREFIXES } from './generated/bridge-vocabulary' // Runtime guard for the result envelope received from the editor. The payload is // JSON parsed from the editor origin; same-origin policy narrows the attacker @@ -29,12 +30,9 @@ export const isBridgeResultLike = (value: unknown): value is BridgeResult code.startsWith(prefix)) } return false } diff --git a/embed/src/webmcp.ts b/embed/src/webmcp.ts index b7d6b55b..5c4dcc6d 100644 --- a/embed/src/webmcp.ts +++ b/embed/src/webmcp.ts @@ -12,7 +12,6 @@ // CF: https://webmachinelearning.github.io/webmcp/ import type { MethodName, WireType } from './generated/contract' -import { METHOD_NAMES } from './generated/method-names' import { WEBMCP_TOOLS, type WebMCPToolRecord } from './generated/webmcp-tools' import type { BridgeLogger } from './logger' import type { BridgeResult } from './types' @@ -36,33 +35,25 @@ const PNG_DATA_URL_PREFIX = 'data:image/png;base64,' const isModelContext = (value: unknown): value is ModelContext => typeof value === 'object' && value !== null && 'registerTool' in value && typeof value.registerTool === 'function' -const readModelContext = (): ModelContext | null => modelContextCandidates().find(isModelContext) ?? null - const toTextToolResult = (result: BridgeResult): CallToolResult => ({ content: [{ type: 'text', text: JSON.stringify(result) }], ...(result.success ? {} : { isError: true }), }) -// The render travels once, as the image block a vision-capable runtime shows the -// model; the text block keeps the rest of the result (page, size, badges). Anything -// but a successful PNG render takes the plain text envelope. +// Keep the image bytes separate from metadata on both inspection paths. +const splitPageImage = (render: unknown): { image: ToolContent; metadata: Record } | null => { + if (typeof render !== 'object' || render === null || !('image_data_url' in render)) return null + const { image_data_url: image, ...metadata } = render + if (typeof image !== 'string' || !image.startsWith(PNG_DATA_URL_PREFIX)) return null + return { image: { type: 'image', data: image.slice(PNG_DATA_URL_PREFIX.length), mimeType: 'image/png' }, metadata } +} + const toAnnotatedPageToolResult = (result: BridgeResult): CallToolResult => { - if (!result.success) { - return toTextToolResult(result) - } - const render: unknown = result.data - if (typeof render !== 'object' || render === null || !('image_data_url' in render)) { - return toTextToolResult(result) - } - const { image_data_url: imageDataUrl, ...renderWithoutImage } = render - if (typeof imageDataUrl !== 'string' || !imageDataUrl.startsWith(PNG_DATA_URL_PREFIX)) { - return toTextToolResult(result) - } + if (!result.success) return toTextToolResult(result) + const page = splitPageImage(result.data) + if (page === null) return toTextToolResult(result) return { - content: [ - { type: 'image', data: imageDataUrl.slice(PNG_DATA_URL_PREFIX.length), mimeType: 'image/png' }, - { type: 'text', text: JSON.stringify({ success: true, data: renderWithoutImage }) }, - ], + content: [page.image, ...toTextToolResult({ success: true, data: page.metadata }).content], } } @@ -94,35 +85,18 @@ const toBuildPdfToolResult = ( const images: ToolContent[] = [] const pages: Record[] = [] for (const page of data.pages) { - if ( - typeof page !== 'object' || - page === null || - !('image_data_url' in page) - ) - return toTextToolResult(result) - const { image_data_url: image, ...metadata } = page - if (typeof image !== 'string' || !image.startsWith(PNG_DATA_URL_PREFIX)) - return toTextToolResult(result) - images.push({ - type: 'image', - data: image.slice(PNG_DATA_URL_PREFIX.length), - mimeType: 'image/png', - }) - pages.push(metadata) + const split = splitPageImage(page) + if (split === null) return toTextToolResult(result) + images.push(split.image) + pages.push(split.metadata) } return { content: [ ...images, - { - type: 'text', - text: JSON.stringify({ - success: true, - data: { - ...job, - inspection: { ...inspection, data: { ...data, pages } }, - }, - }), - }, + ...toTextToolResult({ + success: true, + data: { ...job, inspection: { ...inspection, data: { ...data, pages } } }, + }).content, ], } } @@ -133,10 +107,9 @@ const toCallToolResult = (wireType: WireType, result: BridgeResult): Ca switch (wireType) { case 'BUILD_PDF': return toBuildPdfToolResult(result) - case 'GET_DOCUMENTATION': - return toTextToolResult(result) case 'GET_ANNOTATED_PAGE': return toAnnotatedPageToolResult(result) + case 'GET_DOCUMENTATION': case 'BATCH_SET_FIELD_VALUES': case 'CREATE_FIELD': case 'DELETE_FIELDS': @@ -189,32 +162,28 @@ export const registerWebMCPTools = ({ if (signal.aborted) { return false } - const modelContext = readModelContext() - if (modelContext === null) { + const modelContext = modelContextCandidates().find(isModelContext) + if (modelContext === undefined) { logger.info('webmcp.unavailable', { reason: 'invalid_model_context' }) return false } - const excluded = new Set(exclude) - for (const method of METHOD_NAMES) { + const excluded = new Set(exclude) + for (const [method, { wireType, ...record }] of Object.entries(WEBMCP_TOOLS)) { if (excluded.has(method)) { continue } - const record = WEBMCP_TOOLS[method] if (liveTools.has(record.name)) { logger.warn('webmcp.tool_already_registered', { tool: record.name }) continue } const tool: WebMCPTool = { - name: record.name, - description: record.description, - inputSchema: record.inputSchema, - annotations: record.annotations, + ...record, // A call the runtime already aborted never reaches the editor; one aborted after it // was posted still runs there (the wire has no cancel frame). A nullish input becomes // an empty payload (the no-input operations' wire shape). execute: async (input, options) => { options?.signal.throwIfAborted() - return toCallToolResult(record.wireType, await dispatch(record.wireType, input ?? {})) + return toCallToolResult(wireType, await dispatch(wireType, input ?? {})) }, } liveTools.set(tool.name, signal) diff --git a/embed/test/bridge.test.ts b/embed/test/bridge.test.ts index 8de61194..9bfd9843 100644 --- a/embed/test/bridge.test.ts +++ b/embed/test/bridge.test.ts @@ -91,6 +91,24 @@ describe(attachEmbed.name, () => { await expect(promise).resolves.toEqual({ success: true, data: null }) }) + it('posts an empty documentation input when called without arguments', async () => { + const harness = makeHarness() + const pending = harness.embed.actions.getDocumentation() + expect(harness.posted.at(-1)).toMatchObject({ type: 'GET_DOCUMENTATION', data: {} }) + replyResult(harness, harness.lastRequestId(), { success: true, data: { kind: 'index', topics: [] } }) + expect(await pending).toEqual({ success: true, data: { kind: 'index', topics: [] } }) + }) + + it.each(['conflict:editor_modified', 'not_found:job', 'resource:session_limit'])( + 'preserves the build error %s', async (code) => { + const harness = makeHarness() + const pending = harness.embed.actions.buildPdf({ action: 'status', jobId: 'job' }) + const result = { success: false, error: { code, message: 'Build request rejected' } } + replyResult(harness, harness.lastRequestId(), result) + expect(await pending).toEqual(result) + } + ) + it('forwards a typed editor error and camelCases its details payload', async () => { const harness = makeHarness() const promise = harness.embed.actions.submit({ downloadCopy: false }) diff --git a/embed/test/helpers.ts b/embed/test/helpers.ts index f1c5b1d1..ecd54ed9 100644 --- a/embed/test/helpers.ts +++ b/embed/test/helpers.ts @@ -1,13 +1,14 @@ import { vi } from 'vitest' import type { BridgeResult, Embed, IframeActions } from '../src/types' -const okResult: BridgeResult = { success: true, data: null } +const result: BridgeResult = { success: false, error: { code: 'bad_request:invalid_input', message: 'Test action' } } // A fully-stubbed actions group: every editor operation is a vi.fn resolving to a -// success Result. Shared by the tools + adapter tests. +// failure Result. Shared by the tools + adapter tests. export const makeActionsStub = (): IframeActions => { - const method = (): Promise> => Promise.resolve(okResult) + const method = (): Promise> => Promise.resolve(result) return { + batchSetFieldValues: vi.fn(method), buildPdf: vi.fn(method), getDocumentation: vi.fn(method), createField: vi.fn(method), diff --git a/embed/test/tanstack-ai.test.ts b/embed/test/tanstack-ai.test.ts index 30b8252b..d510ec9e 100644 --- a/embed/test/tanstack-ai.test.ts +++ b/embed/test/tanstack-ai.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest' +import { convertSchemaToJsonSchema } from '@tanstack/ai' import { createSimplePDFTools, simplePDFToolDefinitions } from '../src/tanstack-ai' import type { BridgeResult } from '../src/types' import { makeEmbedStub } from './helpers' @@ -11,6 +12,9 @@ describe('simplePDFToolDefinitions', () => { for (const definition of definitions) { expect(typeof definition.description).toBe('string') expect(definition.inputSchema).toBeDefined() + const schema = convertSchemaToJsonSchema(definition.inputSchema) + expect(schema?.type).toBe('object') + expect(schema?.anyOf).toBeUndefined() } }) }) diff --git a/embed/test/tools.test.ts b/embed/test/tools.test.ts index 26a777c6..900ef62f 100644 --- a/embed/test/tools.test.ts +++ b/embed/test/tools.test.ts @@ -55,10 +55,28 @@ describe(routeToolCall.name, () => { code: 'Hello', idempotencyKey: 'first', }) + await routeToolCall(actions, 'buildPdf', { action: 'status', jobId: 'job' }) + expect(actions.buildPdf).toHaveBeenCalledWith({ action: 'status', jobId: 'job' }) await routeToolCall(actions, 'getDocumentation', undefined) expect(actions.getDocumentation).toHaveBeenCalledWith({}) }) + // Router validation must preserve the caller's intended preconditions before any editor call. + it.each([ + { action: 'build', code: 'Hello', idempotencyKey: 'key', baseRevison: 2 }, + { action: 'build', code: 'Hello', idempotencyKey: 'key', inspect: { page: [1] } }, + { action: 'build', code: 'Hello', idempotencyKey: 'key', assets: [{ path: 'a.png', dataUrl: 'data', extra: true }] }, + { action: 'cancel', jobId: 'job', code: 'Hello' }, + { action: 'build', code: 'Hello' }, + ])('rejects invalid build input without losing fields: %j', async (input) => { + const actions = makeActionsStub() + expect(await routeToolCall(actions, 'buildPdf', input)).toMatchObject({ + success: false, + error: { code: 'bad_request:invalid_input' }, + }) + expect(actions.buildPdf).not.toHaveBeenCalled() + }) + it('returns bad_request:invalid_input on schema-invalid input without dispatching', async () => { const actions = makeActionsStub() const result = await routeToolCall(actions, 'goTo', { page: 'not-a-number' }) @@ -69,6 +87,17 @@ describe(routeToolCall.name, () => { expect(actions.goTo).not.toHaveBeenCalled() }) + it('rejects misspelled inspection preconditions before dispatch', async () => { + const actions = makeActionsStub() + const result = await routeToolCall(actions, 'getAnnotatedPage', { + page: 1, expectedBuildSessionId: 'session', expectedRevision: 7, expectedEditorStateVerison: 4, + }) + expect(result).toMatchObject({ success: false, error: { code: 'bad_request:invalid_input' } }) + expect(actions.getAnnotatedPage).not.toHaveBeenCalled() + await routeToolCall(actions, 'getAnnotatedPage', { page: 1 }) + expect(actions.getAnnotatedPage).toHaveBeenCalledWith({ page: 1 }) + }) + it('routes getAnnotatedPage to its action with the validated page', async () => { const actions = makeActionsStub() await routeToolCall(actions, 'getAnnotatedPage', { page: 1 }) diff --git a/embed/test/webmcp.test.ts b/embed/test/webmcp.test.ts index d40593b2..0033637c 100644 --- a/embed/test/webmcp.test.ts +++ b/embed/test/webmcp.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { attachEmbed, type AttachEmbedArgs } from '../src/bridge' import type { BridgeLogger } from '../src/logger' import type { Embed } from '../src/types' -import { METHOD_NAMES } from '../src/generated/method-names' +import { METHOD_NAMES } from '../src/generated/bridge-vocabulary' import { WEBMCP_TOOLS } from '../src/generated/webmcp-tools' const EDITOR_ORIGIN = 'https://tenant.simplepdf.com' @@ -235,6 +235,22 @@ describe('attachEmbed({ webMCP })', () => { expect(toolResult.content).toEqual([{ type: 'text', text: JSON.stringify({ success: true, data: null }) }]) }) + it('preserves raw WebMCP keys so the editor can reject misspelled build preconditions', async () => { + const modelContext = installModelContext(document) + const harness = mountReady({ webMCP: { enabled: true } }) + await waitForTools(modelContext, TOOL_COUNT) + const input = { + action: 'build', code: 'Draft', idempotency_key: 'wire-keys', base_revision: 1, baseRevision: 0, + assets: [{ path: 'image.png', dataUrl: 'invalid' }], + } + const pending = findTool(modelContext, 'build_pdf').execute(input) + const request = await waitForRequest(harness, 'BUILD_PDF') + expect(request.data).toEqual(input) + const result = { success: false, error: { code: 'bad_request:invalid_value', message: 'Unknown input keys' } } + harness.reply(request, result) + expect(await pending).toEqual({ isError: true, content: [{ type: 'text', text: JSON.stringify(result) }] }) + }) + it('hands the agent the wire-shaped result its tool description promises (snake_case, not the SDK camelCase)', async () => { const modelContext = installModelContext(document) const harness = mountReady({ webMCP: { enabled: true } }) @@ -278,6 +294,9 @@ describe('attachEmbed({ webMCP })', () => { const request = await waitForRequest(harness, 'BUILD_PDF') const page = { page: 1, + build_session_id: 'session', + revision: 1, + editor_state_version: 3, image_data_url: 'data:image/png;base64,iVBORw0KGgo=', image_width: 10, image_height: 12, @@ -291,12 +310,12 @@ describe('attachEmbed({ webMCP })', () => { revision: 1, published_revision: 1, status: 'succeeded', - page_count: 1, + page_count: 2, warnings: [], warnings_truncated: false, inspection: { success: true, - data: { pages: [page], omitted_pages: [] }, + data: { pages: [page, { ...page, page: 2, image_data_url: 'data:image/png;base64,cGFnZTI=' }], omitted_pages: [] }, }, }, }) @@ -306,8 +325,16 @@ describe('attachEmbed({ webMCP })', () => { data: 'iVBORw0KGgo=', mimeType: 'image/png', }) - expect(JSON.stringify(result.content[1])).not.toContain('base64') - expect(JSON.stringify(result.content[1])).toContain('published_revision') + expect(result.content[1]).toEqual({ type: 'image', data: 'cGFnZTI=', mimeType: 'image/png' }) + const text = result.content[2] + if (text.type !== 'text') throw new Error('Expected inspection metadata') + const metadata = JSON.parse(text.text) + expect(metadata.data.inspection.data.pages).toEqual([1, 2].map((page) => ({ + page, build_session_id: 'session', revision: 1, editor_state_version: 3, + image_width: 10, image_height: 12, badges: {}, + }))) + expect(metadata.data.published_revision).toBe(1) + expect(text.text).not.toContain('image_data_url') }) it('keeps the text envelope for a failed annotated page render', async () => { diff --git a/embed/tsup.config.ts b/embed/tsup.config.ts index 170807d1..a8bb7ad1 100644 --- a/embed/tsup.config.ts +++ b/embed/tsup.config.ts @@ -19,6 +19,8 @@ export default defineConfig({ dts: true, treeshake: true, minify: true, + keepNames: true, + sourcemap: true, splitting: true, clean: true, external: ['zod', '@tanstack/ai'], diff --git a/react/README.md b/react/README.md index cccdbf70..8fe609dd 100644 --- a/react/README.md +++ b/react/README.md @@ -158,7 +158,7 @@ Actions are camelCase (the editor's snake_case wire is transformed for you). `us | `actions.batchSetFieldValues({ updates })` | Set several fields at once (`updates: [{ fieldId, value }]`): all apply, or none do | | `actions.submit({ downloadCopy })` | Submit the document | -…plus `createField`, `getFields`, `getAnnotatedPage`, `focusField`, `movePage`, `rotatePage`, `deletePages`, `download`, and `loadDocument`. All actions return a `Promise` with a result object: `{ success: true, data: ... }` or `{ success: false, error: { code, message } }`. +See the [core action reference](../embed/README.md#actions) for `buildPdf`, `getDocumentation` and all input shapes. Other actions include `createField`, `getFields`, `getAnnotatedPage`, `focusField`, `movePage`, `rotatePage`, `deletePages`, `download`, and `loadDocument`. All actions return a `Promise` with a result object: `{ success: true, data: ... }` or `{ success: false, error: { code, message } }`. ```jsx import { EmbedPDF, useEmbed } from '@simplepdf/react-embed-pdf'; diff --git a/skills/build-with-simplepdf/SKILL.md b/skills/build-with-simplepdf/SKILL.md index f86c7a97..329fe1ac 100644 --- a/skills/build-with-simplepdf/SKILL.md +++ b/skills/build-with-simplepdf/SKILL.md @@ -137,9 +137,9 @@ export function ControlledEditor() { Typical operations: `getFields()`, `setFieldValue({ fieldId, value })`, `getDocumentContent({ extractionMode })`, `getAnnotatedPage({ page })`, `goTo({ page })`, `focusField({ fieldId })`, `selectTool({ tool })`, `detectFields()`, `deleteFields({ fieldIds?, page? })`, `submit({ downloadCopy })`. Verify the exact current method names and input shapes from the installed package/docs before coding. -Editor events arrive via the `onEmbedEvent` prop (React) or `embed.events` (core) — the outbound events are `EDITOR_READY`, `DOCUMENT_LOADED`, `PAGE_FOCUSED` and `SUBMISSION_SENT` (`submit()` itself resolves with `data: null`; the event carries the resulting ids). Wait for `DOCUMENT_LOADED` before operating on the document; until then actions other than `loadDocument()` fail with `bad_request:editor_not_ready` or `bad_request:no_document_loaded` (and `getFields()` may report an incomplete list) — handle or retry rather than racing mount. +Editor events arrive via the `onEmbedEvent` prop (React) or `embed.events` (core) — the outbound events are `EDITOR_READY`, `DOCUMENT_LOADED`, `PAGE_FOCUSED` and `SUBMISSION_SENT` (`submit()` itself resolves with `data: null`; the event carries the resulting ids). In an empty editor, call `loadDocument()`, `buildPdf()` or `getDocumentation()` without waiting for a document event. `EDITOR_READY` is only emitted in loading-placeholder mode; a normal blank editor does not emit it. Retry `bad_request:editor_not_ready` shortly. Wait for `DOCUMENT_LOADED` before document-dependent operations (and `getFields()` may report an incomplete list before then); handle `bad_request:no_document_loaded` rather than racing the load. -Browser agents (WebMCP): `webMCP: { enabled: true, exclude: ['submit'] }` on `createEmbed` / `` registers the editor's operations as tools on the host page (`simplepdf_embed_*`, the same records the editor registers on its own page; `exclude` takes SDK method names). Off by default; one WebMCP-enabled embed per page. +Browser agents (WebMCP): `webMCP: { enabled: true, exclude: ['submit'] }` on `createEmbed` / `` registers the editor's operations as tools on the host page (`build_pdf`, `get_documentation`, and the existing `simplepdf_embed_*` tools, the same records the editor registers on its own page; `exclude` takes SDK method names). Off by default; one WebMCP-enabled embed per page. When relevant (`AskUserQuestion`, header `Editor UI`): From cbea5cc97209f2571926533e177f91a78d4feec2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20Andr=C3=A9-Micolon?= Date: Mon, 23 Nov 2026 08:23:14 +0000 Subject: [PATCH 03/12] feat: simplify PDF building to opinionated job outcomes --- .changeset/build-pdf-browser.md | 3 +- embed/README.md | 8 +- embed/embed-api.json | 808 +++++----------------------- embed/etc/index.api.md | 64 +-- embed/etc/protocol.api.md | 8 +- embed/etc/schemas.api.md | 14 +- embed/etc/tanstack-ai.api.md | 2 +- embed/etc/tools.api.md | 12 +- embed/src/generated/contract.ts | 18 +- embed/src/generated/schemas.ts | 14 +- embed/src/generated/tools.ts | 8 +- embed/src/generated/webmcp-tools.ts | 4 +- embed/src/webmcp.ts | 47 +- embed/test/tools.test.ts | 20 +- embed/test/webmcp.test.ts | 63 +-- 15 files changed, 200 insertions(+), 893 deletions(-) diff --git a/.changeset/build-pdf-browser.md b/.changeset/build-pdf-browser.md index 560714bf..f8d30377 100644 --- a/.changeset/build-pdf-browser.md +++ b/.changeset/build-pdf-browser.md @@ -5,5 +5,4 @@ **Build and revise PDFs directly in the browser editor.** - Use typed JavaScript and React methods for PDF building and task documentation. -- Inspect the published revision through native WebMCP images. -- Existing field operations keep their contracts. +- View the first-page preview with the build result and inspect other pages by job ID. WebMCP returns each preview as a native image. diff --git a/embed/README.md b/embed/README.md index 2e77b715..c3dbae58 100644 --- a/embed/README.md +++ b/embed/README.md @@ -95,7 +95,7 @@ createEmbed({ target: '#editor', companyIdentifier: 'acme', document: { url: 'ht - **The tools are the editor's own.** Each one is the record the editor publishes in its manifest (`https://simplepdf.com/embed/json`, `operations[].tool`) and registers on its own page: the published tool name, description, snake_case input schema and behavior hints (the readers carry the specification's `readOnlyHint` and `untrustedContentHint`; every other tool MCP's `destructiveHint`; the three that fetch an agent-supplied URL `openWorldHint`). `build_pdf` and `get_documentation` use those names; existing tools retain the `simplepdf_embed_` prefix. A page gets the same tools whether the editor is embedded or opened directly. `exclude` takes SDK method names. - **Data path.** Every operation an agent can call runs in the browser, and nothing the agent reads (field values, extracted text, a page render) is computed server-side; it goes to the agent runtime the person attached, so treat that runtime as you would any other party that sees the filled document. Document storage is unchanged by this option: it follows your account's configuration exactly as it does without WebMCP (SimplePDF-managed storage, or your own S3, Azure Blob Storage or SharePoint), and `submit` sends the document through the same submission flow as a click on Submit. - **Timing.** Tools register once the editor is ready. While no usable model context has been found, the page is probed again on each later lifecycle transition, so a context installed after `EDITOR_READY` is still picked up, and until one appears nothing is loaded (`webmcp.unavailable` is logged, with the reason). -- **Results.** The editor validates each call like any other request (its permission model applies at call time: editing, allowlisted origin, plan, so a tool your configuration refuses resolves with the matching error code). A call resolves with an MCP tool result whose text is the editor's wire-shaped `{ success, data | error }` Result (`isError` on failure); `simplepdf_embed_get_annotated_page` carries its PNG as an `image` content block, with the badges map in the text block. A call the runtime aborted before it ran rejects and never reaches the editor. +- **Results.** The editor validates each call like any other request (its permission model applies at call time: editing, allowlisted origin, plan, so a tool your configuration refuses resolves with the matching error code). A call resolves with an MCP tool result whose text is the editor's wire-shaped `{ success, data | error }` Result (`isError` on failure). A successful page render from `build_pdf` or `simplepdf_embed_get_annotated_page` carries its PNG as an `image` content block and its field badges in the text block. A call the runtime aborted before it ran rejects and never reaches the editor. - **One embed per page.** A model context is one per page and keyed by tool name: a second WebMCP-enabled embed registers only the names the first did not take, and is reported for the rest (`webmcp.tool_already_registered`). `dispose()` unregisters everything. ## Subpaths @@ -171,7 +171,7 @@ else r.error.code // a closed BridgeErrorCode ```ts await embed.actions.getDocumentation({ topic: 'build_pdf' }) -await embed.actions.buildPdf({ action: 'build', code: '= Hello', idempotencyKey: 'draft-1', inspect: {} }) +await embed.actions.buildPdf({ action: 'build', code: '= Hello', idempotencyKey: 'draft-1' }) await embed.actions.loadDocument({ dataUrl, name, page }) await embed.actions.goTo({ page: 3 }) await embed.actions.selectTool({ tool: 'TEXT' }) // 'CHECKBOX' | 'SIGNATURE' | 'PICTURE' | 'COMB_TEXT' | null @@ -188,7 +188,9 @@ await embed.actions.download() Full set: `buildPdf`, `getDocumentation`, `batchSetFieldValues`, `createField`, `deleteFields`, `deletePages`, `detectFields`, `download`, `focusField`, `getAnnotatedPage`, `getDocumentContent`, `getFields`, `goTo`, `loadDocument`, `movePage`, `rotatePage`, `selectTool`, `setFieldValue`, `submit`. -PDF building requires an empty editor. Successful builds publish automatically; queued/running results carry the job ID for polling. Results discriminate by `status`; compilation failures carry repair diagnostics inside `error`. Manual edits block replacement. Bind later inspection with `expectedBuildSessionId` and `expectedRevision`. The WebMCP projection carries compound inspection PNGs as image blocks. Documentation returns an index or one English topic, discriminated by `kind`. Building never downloads or shares the document. +Start a build in an empty editor. If the job is still `queued` or `running` after five seconds, call `buildPdf({ action: 'status', jobId })` until it finishes. A failed build reports diagnostics in `error`. A successful build opens the PDF and returns its page count, warnings and a first-page `preview`. Check `preview.success` before reading `preview.data.imageDataUrl`. To view another page of the same build, call `getAnnotatedPage({ page: 2, expectedJobId: jobId })`. Manual edits protect the document from replacement by a subsequent build. + +Call `getDocumentation()` for the topic index, then `getDocumentation({ topic })` to read a topic. **"Fill and read this document for me"** is just these operations in sequence, exactly what the agentic tools expose to a model: diff --git a/embed/embed-api.json b/embed/embed-api.json index afc1f130..b192f54f 100644 --- a/embed/embed-api.json +++ b/embed/embed-api.json @@ -17,11 +17,7 @@ "description": "The operation's input payload, matching that operation's input_schema." } }, - "required": [ - "type", - "request_id", - "data" - ] + "required": ["type", "request_id", "data"] }, "result_envelope_schema": { "type": "object", @@ -50,10 +46,7 @@ "description": "Matches the operation's output_schema; null for ops that return nothing." } }, - "required": [ - "success", - "data" - ] + "required": ["success", "data"] }, { "type": "object", @@ -66,24 +59,15 @@ "description": "The error object when success is false: a `code` plus a human-readable `message` (with typed `details` for bad_request:batch_validation_failed and bad_request:missing_required_fields). Its full shape and code set are editor_error_schema, where each code const carries a description of its meaning." } }, - "required": [ - "success", - "error" - ] + "required": ["success", "error"] } ] } }, - "required": [ - "request_id", - "result" - ] + "required": ["request_id", "result"] } }, - "required": [ - "type", - "data" - ] + "required": ["type", "data"] }, "correlation": { "id_field": "request_id", @@ -93,7 +77,7 @@ "operations": [ { "request_type": "BUILD_PDF", - "description": "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Add inspect for page images. Edits block rebuilding. No sharing.", + "description": "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing.", "input_schema": { "anyOf": [ { @@ -103,30 +87,12 @@ "type": "string", "const": "build" }, - "inspect": { - "type": "object", - "properties": { - "pages": { - "type": "array", - "items": { - "type": "integer" - } - } - }, - "additionalProperties": false - }, "code": { "type": "string" }, "idempotency_key": { "type": "string" }, - "build_session_id": { - "type": "string" - }, - "base_revision": { - "type": "integer" - }, "name": { "type": "string" }, @@ -142,22 +108,12 @@ "type": "string" } }, - "required": [ - "path", - "data_url" - ], + "required": ["path", "data_url"], "additionalProperties": false } - }, - "wait_ms": { - "type": "integer" } }, - "required": [ - "action", - "code", - "idempotency_key" - ], + "required": ["action", "code", "idempotency_key"], "additionalProperties": false }, { @@ -169,27 +125,9 @@ }, "job_id": { "type": "string" - }, - "wait_ms": { - "type": "integer" - }, - "inspect": { - "type": "object", - "properties": { - "pages": { - "type": "array", - "items": { - "type": "integer" - } - } - }, - "additionalProperties": false } }, - "required": [ - "action", - "job_id" - ], + "required": ["action", "job_id"], "additionalProperties": false }, { @@ -203,14 +141,11 @@ "type": "string" } }, - "required": [ - "action", - "job_id" - ], + "required": ["action", "job_id"], "additionalProperties": false } ], - "description": "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Add inspect for page images. Edits block rebuilding. No sharing." + "description": "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing." }, "output_schema": { "anyOf": [ @@ -220,31 +155,12 @@ "job_id": { "type": "string" }, - "build_session_id": { - "type": "string" - }, - "revision": { - "type": "integer" - }, - "published_revision": { - "type": "integer" - }, "status": { "type": "string", "const": "queued" - }, - "poll_after_ms": { - "type": "integer" } }, - "required": [ - "job_id", - "build_session_id", - "revision", - "published_revision", - "status", - "poll_after_ms" - ], + "required": ["job_id", "status"], "additionalProperties": false }, { @@ -253,43 +169,12 @@ "job_id": { "type": "string" }, - "build_session_id": { - "type": "string" - }, - "revision": { - "type": "integer" - }, - "published_revision": { - "type": "integer" - }, "status": { "type": "string", "const": "running" - }, - "stage": { - "type": "string", - "enum": [ - "queued", - "initializing", - "compiling", - "validating", - "loading", - "ready" - ] - }, - "poll_after_ms": { - "type": "integer" } }, - "required": [ - "job_id", - "build_session_id", - "revision", - "published_revision", - "status", - "stage", - "poll_after_ms" - ], + "required": ["job_id", "status"], "additionalProperties": false }, { @@ -298,15 +183,6 @@ "job_id": { "type": "string" }, - "build_session_id": { - "type": "string" - }, - "revision": { - "type": "integer" - }, - "published_revision": { - "type": "integer" - }, "status": { "type": "string", "const": "succeeded" @@ -325,10 +201,7 @@ }, "code": { "type": "string", - "enum": [ - "typst", - "unsupported_dependency" - ] + "enum": ["typst", "unsupported_dependency"] }, "message": { "type": "string" @@ -346,18 +219,11 @@ "type": "string" } }, - "required": [ - "severity", - "code", - "message" - ], + "required": ["severity", "code", "message"], "additionalProperties": false } }, - "warnings_truncated": { - "type": "boolean" - }, - "inspection": { + "preview": { "anyOf": [ { "type": "object", @@ -369,88 +235,51 @@ "data": { "type": "object", "properties": { - "pages": { - "type": "array", - "items": { - "type": "object", - "properties": { - "build_session_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] - }, - "revision": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ] - }, - "editor_state_version": { - "type": "integer" - }, - "page": { - "type": "integer", - "description": "1-based page position this render shows." - }, - "image_data_url": { - "type": "string", - "description": "PNG render of the page as a data URL, with every field outlined and a numbered badge drawn inside it on the right, or just to its left when the field is too small to hold it." - }, - "image_width": { - "type": "integer", - "description": "Render width in pixels." - }, - "image_height": { - "type": "integer", - "description": "Render height in pixels." - }, - "badges": { - "type": "object", - "additionalProperties": { - "type": "string" - }, - "description": "Badge number (as drawn on the render) to field_id, for every field on the page." - } + "job_id": { + "anyOf": [ + { + "type": "string" }, - "required": [ - "build_session_id", - "revision", - "editor_state_version", - "page", - "image_data_url", - "image_width", - "image_height", - "badges" - ] - } + { + "type": "null" + } + ] + }, + "page": { + "type": "integer", + "description": "1-based page position this render shows." + }, + "image_data_url": { + "type": "string", + "description": "PNG render of the page as a data URL, with every field outlined and a numbered badge drawn inside it on the right, or just to its left when the field is too small to hold it." + }, + "image_width": { + "type": "integer", + "description": "Render width in pixels." }, - "omitted_pages": { - "type": "array", - "items": { - "type": "integer" - } + "image_height": { + "type": "integer", + "description": "Render height in pixels." + }, + "badges": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "Badge number (as drawn on the render) to field_id, for every field on the page." } }, "required": [ - "pages", - "omitted_pages" - ], - "additionalProperties": false + "job_id", + "page", + "image_data_url", + "image_width", + "image_height", + "badges" + ] } }, - "required": [ - "success", - "data" - ], + "required": ["success", "data"], "additionalProperties": false }, { @@ -520,16 +349,10 @@ } } }, - "required": [ - "failures" - ] + "required": ["failures"] } }, - "required": [ - "code", - "message", - "details" - ] + "required": ["code", "message", "details"] }, { "type": "object", @@ -549,32 +372,16 @@ "type": "integer" } }, - "required": [ - "unfilled_required_fields_count" - ] + "required": ["unfilled_required_fields_count"] } }, - "required": [ - "code", - "message", - "details" - ] + "required": ["code", "message", "details"] }, { "type": "object", "properties": { "code": { "anyOf": [ - { - "type": "string", - "const": "conflict:build_session_mismatch", - "description": "Different editor session. Read the guide again." - }, - { - "type": "string", - "const": "conflict:base_revision_mismatch", - "description": "Published revision changed. Inspect before rebuilding." - }, { "type": "string", "const": "conflict:idempotency_key_reused", @@ -605,11 +412,6 @@ "const": "resource:session_limit", "description": "Session job limit reached. Open an empty editor." }, - { - "type": "string", - "const": "conflict:inspection_revision_mismatch", - "description": "The requested revision is not displayed." - }, { "type": "string", "const": "conflict:inspection_state_changed", @@ -736,18 +538,12 @@ "type": "string" } }, - "required": [ - "code", - "message" - ] + "required": ["code", "message"] } ] } }, - "required": [ - "success", - "error" - ], + "required": ["success", "error"], "additionalProperties": false } ] @@ -755,13 +551,10 @@ }, "required": [ "job_id", - "build_session_id", - "revision", - "published_revision", "status", "page_count", "warnings", - "warnings_truncated" + "preview" ], "additionalProperties": false }, @@ -771,15 +564,6 @@ "job_id": { "type": "string" }, - "build_session_id": { - "type": "string" - }, - "revision": { - "type": "integer" - }, - "published_revision": { - "type": "integer" - }, "status": { "type": "string", "const": "failed" @@ -806,17 +590,6 @@ "message": { "type": "string" }, - "stage": { - "type": "string", - "enum": [ - "queued", - "initializing", - "compiling", - "validating", - "loading", - "ready" - ] - }, "retryable": { "type": "boolean" }, @@ -827,17 +600,11 @@ "properties": { "severity": { "type": "string", - "enum": [ - "error", - "warning" - ] + "enum": ["error", "warning"] }, "code": { "type": "string", - "enum": [ - "typst", - "unsupported_dependency" - ] + "enum": ["typst", "unsupported_dependency"] }, "message": { "type": "string" @@ -855,37 +622,16 @@ "type": "string" } }, - "required": [ - "severity", - "code", - "message" - ], + "required": ["severity", "code", "message"], "additionalProperties": false } - }, - "diagnostics_truncated": { - "type": "boolean" } }, - "required": [ - "code", - "message", - "stage", - "retryable", - "diagnostics", - "diagnostics_truncated" - ], + "required": ["code", "message", "retryable", "diagnostics"], "additionalProperties": false } }, - "required": [ - "job_id", - "build_session_id", - "revision", - "published_revision", - "status", - "error" - ], + "required": ["job_id", "status", "error"], "additionalProperties": false }, { @@ -894,27 +640,12 @@ "job_id": { "type": "string" }, - "build_session_id": { - "type": "string" - }, - "revision": { - "type": "integer" - }, - "published_revision": { - "type": "integer" - }, "status": { "type": "string", "const": "cancelled" } }, - "required": [ - "job_id", - "build_session_id", - "revision", - "published_revision", - "status" - ], + "required": ["job_id", "status"], "additionalProperties": false }, { @@ -923,48 +654,30 @@ "job_id": { "type": "string" }, - "build_session_id": { - "type": "string" - }, - "revision": { - "type": "integer" - }, - "published_revision": { - "type": "integer" - }, "status": { "type": "string", "const": "superseded" } }, - "required": [ - "job_id", - "build_session_id", - "revision", - "published_revision", - "status" - ], + "required": ["job_id", "status"], "additionalProperties": false } ] }, "error_codes": [ - "conflict:build_session_mismatch", - "conflict:base_revision_mismatch", "conflict:idempotency_key_reused", "conflict:editor_modified", "conflict:unmanaged_document", "not_found:job", "not_found:job_expired", "resource:session_limit", - "conflict:inspection_revision_mismatch", "conflict:inspection_state_changed", "bad_request:invalid_value", "forbidden:editing_not_allowed" ], "tool": { "name": "build_pdf", - "description": "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Add inspect for page images. Edits block rebuilding. No sharing.", + "description": "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing.", "input_schema": { "anyOf": [ { @@ -974,30 +687,12 @@ "type": "string", "const": "build" }, - "inspect": { - "type": "object", - "properties": { - "pages": { - "type": "array", - "items": { - "type": "integer" - } - } - }, - "additionalProperties": false - }, "code": { "type": "string" }, "idempotency_key": { "type": "string" }, - "build_session_id": { - "type": "string" - }, - "base_revision": { - "type": "integer" - }, "name": { "type": "string" }, @@ -1013,22 +708,12 @@ "type": "string" } }, - "required": [ - "path", - "data_url" - ], + "required": ["path", "data_url"], "additionalProperties": false } - }, - "wait_ms": { - "type": "integer" } }, - "required": [ - "action", - "code", - "idempotency_key" - ], + "required": ["action", "code", "idempotency_key"], "additionalProperties": false }, { @@ -1040,27 +725,9 @@ }, "job_id": { "type": "string" - }, - "wait_ms": { - "type": "integer" - }, - "inspect": { - "type": "object", - "properties": { - "pages": { - "type": "array", - "items": { - "type": "integer" - } - } - }, - "additionalProperties": false } }, - "required": [ - "action", - "job_id" - ], + "required": ["action", "job_id"], "additionalProperties": false }, { @@ -1074,10 +741,7 @@ "type": "string" } }, - "required": [ - "action", - "job_id" - ], + "required": ["action", "job_id"], "additionalProperties": false } ], @@ -1144,18 +808,12 @@ "type": "string" } }, - "required": [ - "topic", - "description" - ], + "required": ["topic", "description"], "additionalProperties": false } } }, - "required": [ - "kind", - "topics" - ], + "required": ["kind", "topics"], "additionalProperties": false }, { @@ -1165,35 +823,16 @@ "type": "string", "const": "topic" }, - "topic": { - "type": "string", - "enum": [ - "build_pdf", - "build_pdf.templates", - "build_pdf.forms", - "build_pdf.assets", - "build_pdf.fonts", - "build_pdf.troubleshooting", - "fields", - "inspection" - ] - }, "markdown": { "type": "string" } }, - "required": [ - "kind", - "topic", - "markdown" - ], + "required": ["kind", "markdown"], "additionalProperties": false } ] }, - "error_codes": [ - "bad_request:invalid_value" - ], + "error_codes": ["bad_request:invalid_value"], "tool": { "name": "get_documentation", "description": "Read task guidance and tested PDF recipes. Omit topic for the index.", @@ -1249,17 +888,12 @@ "description": "New value for the field, or null to clear it. If the field has options (see the field list), it must be one of them; otherwise a string (text/checkbox), or a data URL or http(s) URL, fetched by the editor (signature/picture), or plain text for a signature, drawn as a typed signature." } }, - "required": [ - "field_id", - "value" - ] + "required": ["field_id", "value"] }, "description": "The fields to set, at least one, each field at most once. Fields not listed keep their value." } }, - "required": [ - "updates" - ], + "required": ["updates"], "description": "Set existing fields, addressed by ids from the field list, in one atomic undo step. If any update is rejected, nothing changes and the call fails with bad_request:batch_validation_failed, whose details list each rejection with its field id, code and message. Text is set at once, never typed. Returns no data." }, "output_schema": { @@ -1274,9 +908,7 @@ "name": "simplepdf_embed_batch_set_field_values", "description": "Set existing fields, addressed by ids from the field list, in one atomic undo step. If any update is rejected, nothing changes and the call fails with bad_request:batch_validation_failed, whose details list each rejection with its field id, code and message. Text is set at once, never typed. Returns no data.", "input_schema": { - "required": [ - "updates" - ], + "required": ["updates"], "type": "object", "properties": { "updates": { @@ -1299,10 +931,7 @@ "description": "New value for the field, or null to clear it. If the field has options (see the field list), it must be one of them; otherwise a string (text/checkbox), or a data URL or http(s) URL, fetched by the editor (signature/picture), or plain text for a signature, drawn as a typed signature." } }, - "required": [ - "field_id", - "value" - ] + "required": ["field_id", "value"] }, "description": "The fields to set, at least one, each field at most once. Fields not listed keep their value.", "type": "array" @@ -1323,13 +952,7 @@ "properties": { "type": { "type": "string", - "enum": [ - "TEXT", - "SIGNATURE", - "PICTURE", - "CHECKBOX", - "COMB_TEXT" - ], + "enum": ["TEXT", "SIGNATURE", "PICTURE", "CHECKBOX", "COMB_TEXT"], "description": "Field type to create." }, "x": { @@ -1357,14 +980,7 @@ "type": "string" } }, - "required": [ - "type", - "x", - "y", - "width", - "height", - "page" - ], + "required": ["type", "x", "y", "width", "height", "page"], "description": "Create a new overlay field on a page. Returns the id of the created field." }, "output_schema": { @@ -1374,9 +990,7 @@ "type": "string" } }, - "required": [ - "field_id" - ] + "required": ["field_id"] }, "error_codes": [ "forbidden:editing_not_allowed", @@ -1393,24 +1007,11 @@ "name": "simplepdf_embed_create_field", "description": "Create a new overlay field on a page. Returns the id of the created field.", "input_schema": { - "required": [ - "type", - "x", - "y", - "width", - "height", - "page" - ], + "required": ["type", "x", "y", "width", "height", "page"], "type": "object", "properties": { "type": { - "enum": [ - "TEXT", - "SIGNATURE", - "PICTURE", - "CHECKBOX", - "COMB_TEXT" - ], + "enum": ["TEXT", "SIGNATURE", "PICTURE", "CHECKBOX", "COMB_TEXT"], "description": "Field type to create.", "type": "string" }, @@ -1473,9 +1074,7 @@ "type": "integer" } }, - "required": [ - "deleted_count" - ] + "required": ["deleted_count"] }, "error_codes": [ "forbidden:editing_not_allowed", @@ -1523,9 +1122,7 @@ "description": "1-based page numbers to delete." } }, - "required": [ - "pages" - ], + "required": ["pages"], "description": "Delete pages from the document (it cannot delete every visible page). Returns no data. Destructive." }, "output_schema": { @@ -1542,9 +1139,7 @@ "name": "simplepdf_embed_delete_pages", "description": "Delete pages from the document (it cannot delete every visible page). Returns no data. Destructive.", "input_schema": { - "required": [ - "pages" - ], + "required": ["pages"], "type": "object", "properties": { "pages": { @@ -1576,9 +1171,7 @@ "type": "integer" } }, - "required": [ - "detected_count" - ] + "required": ["detected_count"] }, "error_codes": [ "forbidden:editing_not_allowed", @@ -1635,9 +1228,7 @@ "description": "ID of the field to focus and scroll into view." } }, - "required": [ - "field_id" - ], + "required": ["field_id"], "description": "Scroll an existing field into view and focus it, addressed by its id from the field list. Returns a hint describing the user action expected next." }, "output_schema": { @@ -1654,15 +1245,10 @@ "type": "string" } }, - "required": [ - "type", - "message" - ] + "required": ["type", "message"] } }, - "required": [ - "hint" - ] + "required": ["hint"] }, "error_codes": [ "bad_request:invalid_value", @@ -1673,9 +1259,7 @@ "name": "simplepdf_embed_focus_field", "description": "Scroll an existing field into view and focus it, addressed by its id from the field list. Returns a hint describing the user action expected next.", "input_schema": { - "required": [ - "field_id" - ], + "required": ["field_id"], "type": "object", "properties": { "field_id": { @@ -1699,26 +1283,18 @@ "type": "integer", "description": "1-based page to render, at its current position." }, - "expected_build_session_id": { + "expected_job_id": { "type": "string" - }, - "expected_revision": { - "type": "integer" - }, - "expected_editor_state_version": { - "type": "integer" } }, - "required": [ - "page" - ], + "required": ["page"], "additionalProperties": false, "description": "Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block." }, "output_schema": { "type": "object", "properties": { - "build_session_id": { + "job_id": { "anyOf": [ { "type": "string" @@ -1728,19 +1304,6 @@ } ] }, - "revision": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ] - }, - "editor_state_version": { - "type": "integer" - }, "page": { "type": "integer", "description": "1-based page position this render shows." @@ -1766,9 +1329,7 @@ } }, "required": [ - "build_session_id", - "revision", - "editor_state_version", + "job_id", "page", "image_data_url", "image_width", @@ -1781,16 +1342,13 @@ "bad_request:invalid_page", "bad_request:page_out_of_range", "bad_request:invalid_value", - "conflict:inspection_revision_mismatch", "conflict:inspection_state_changed" ], "tool": { "name": "simplepdf_embed_get_annotated_page", "description": "Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block.", "input_schema": { - "required": [ - "page" - ], + "required": ["page"], "additionalProperties": false, "type": "object", "properties": { @@ -1798,14 +1356,8 @@ "description": "1-based page to render, at its current position.", "type": "integer" }, - "expected_build_session_id": { + "expected_job_id": { "type": "string" - }, - "expected_revision": { - "type": "integer" - }, - "expected_editor_state_version": { - "type": "integer" } } }, @@ -1824,10 +1376,7 @@ "extraction_mode": { "description": "Extraction strategy: 'auto' (default) or 'ocr' to force optical recognition.", "type": "string", - "enum": [ - "auto", - "ocr" - ] + "enum": ["auto", "ocr"] } }, "description": "Extract the document's content page by page as Markdown, or as plain text when optical recognition is forced. Use it to read what the document says. Returns the document name and each page's content." @@ -1850,17 +1399,11 @@ "type": "string" } }, - "required": [ - "page", - "content" - ] + "required": ["page", "content"] } } }, - "required": [ - "name", - "pages" - ] + "required": ["name", "pages"] }, "error_codes": [ "bad_request:invalid_value", @@ -1874,10 +1417,7 @@ "properties": { "extraction_mode": { "description": "Extraction strategy: 'auto' (default) or 'ocr' to force optical recognition.", - "enum": [ - "auto", - "ocr" - ], + "enum": ["auto", "ocr"], "type": "string" } } @@ -1970,13 +1510,9 @@ } } }, - "required": [ - "fields" - ] + "required": ["fields"] }, - "error_codes": [ - "bad_request:no_document_loaded" - ], + "error_codes": ["bad_request:no_document_loaded"], "tool": { "name": "simplepdf_embed_get_fields", "description": "List every fillable field in the loaded document, including native dropdown and radio AcroFields. Each field reports its id, name, type, page, current value, and the options its value must be one of, if any. Call this first to discover field ids before reading or setting values. To SEE where each field sits on the printed page, render the annotated page. Returns the field list.", @@ -2001,9 +1537,7 @@ "description": "1-based page to navigate to." } }, - "required": [ - "page" - ], + "required": ["page"], "description": "Scroll the editor to a page. Returns no data." }, "output_schema": { @@ -2018,9 +1552,7 @@ "name": "simplepdf_embed_go_to", "description": "Scroll the editor to a page. Returns no data.", "input_schema": { - "required": [ - "page" - ], + "required": ["page"], "type": "object", "properties": { "page": { @@ -2053,9 +1585,7 @@ "type": "integer" } }, - "required": [ - "data_url" - ], + "required": ["data_url"], "description": "Replace the document in the editor with one supplied as a base64 data URL or an http(s) URL the editor fetches. Destructive: the current document and every edit in it are discarded. Replies once the document and its fields are ready, so the next operation can act on it, and DOCUMENT_LOADED follows the reply; the URL already open is left as is and answers once it settles; a document that cannot be loaded or prepared answers bad_request:failed_to_load_document. Returns no data." }, "output_schema": { @@ -2070,9 +1600,7 @@ "name": "simplepdf_embed_load_document", "description": "Replace the document in the editor with one supplied as a base64 data URL or an http(s) URL the editor fetches. Destructive: the current document and every edit in it are discarded. Replies once the document and its fields are ready, so the next operation can act on it, and DOCUMENT_LOADED follows the reply; the URL already open is left as is and answers once it settles; a document that cannot be loaded or prepared answers bad_request:failed_to_load_document. Returns no data.", "input_schema": { - "required": [ - "data_url" - ], + "required": ["data_url"], "type": "object", "properties": { "data_url": { @@ -2110,10 +1638,7 @@ "description": "1-based destination position for the page." } }, - "required": [ - "from_page", - "to_page" - ], + "required": ["from_page", "to_page"], "description": "Move a page to another position, reordering the document. Returns no data. Destructive." }, "output_schema": { @@ -2130,10 +1655,7 @@ "name": "simplepdf_embed_move_page", "description": "Move a page to another position, reordering the document. Returns no data. Destructive.", "input_schema": { - "required": [ - "from_page", - "to_page" - ], + "required": ["from_page", "to_page"], "type": "object", "properties": { "from_page": { @@ -2162,9 +1684,7 @@ "description": "1-based page to rotate." } }, - "required": [ - "page" - ], + "required": ["page"], "description": "Rotate a page 90 degrees clockwise. Returns no data. Destructive." }, "output_schema": { @@ -2181,9 +1701,7 @@ "name": "simplepdf_embed_rotate_page", "description": "Rotate a page 90 degrees clockwise. Returns no data. Destructive.", "input_schema": { - "required": [ - "page" - ], + "required": ["page"], "type": "object", "properties": { "page": { @@ -2222,9 +1740,7 @@ "description": "Tool to activate, or null to deselect." } }, - "required": [ - "tool" - ], + "required": ["tool"], "description": "Activate a field-placement tool in the editor toolbar so the user can draw that field type, or pass null to clear the active tool. Returns no data." }, "output_schema": { @@ -2238,9 +1754,7 @@ "name": "simplepdf_embed_select_tool", "description": "Activate a field-placement tool in the editor toolbar so the user can draw that field type, or pass null to clear the active tool. Returns no data.", "input_schema": { - "required": [ - "tool" - ], + "required": ["tool"], "type": "object", "properties": { "tool": { @@ -2294,10 +1808,7 @@ "description": "New value for the field, or null to clear it. If the field has options (see the field list), it must be one of them; otherwise a string (text/checkbox), or a data URL or http(s) URL, fetched by the editor (signature/picture), or plain text for a signature, drawn as a typed signature." } }, - "required": [ - "field_id", - "value" - ], + "required": ["field_id", "value"], "description": "Set or clear (null) one existing field, addressed by its id from the field list. Text is typed out unless animate is false. Returns no data." }, "output_schema": { @@ -2314,10 +1825,7 @@ "name": "simplepdf_embed_set_field_value", "description": "Set or clear (null) one existing field, addressed by its id from the field list. Text is typed out unless animate is false. Returns no data.", "input_schema": { - "required": [ - "field_id", - "value" - ], + "required": ["field_id", "value"], "type": "object", "properties": { "animate": { @@ -2358,9 +1866,7 @@ "description": "When true, the signer also receives a downloaded copy on submit." } }, - "required": [ - "download_copy" - ], + "required": ["download_copy"], "description": "Submit the completed document through the editor's finalization flow. This is irreversible. Fails with bad_request:missing_required_fields when required fields are unfilled. Returns no data." }, "output_schema": { @@ -2375,9 +1881,7 @@ "name": "simplepdf_embed_submit", "description": "Submit the completed document through the editor's finalization flow. This is irreversible. Fails with bad_request:missing_required_fields when required fields are unfilled. Returns no data.", "input_schema": { - "required": [ - "download_copy" - ], + "required": ["download_copy"], "type": "object", "properties": { "download_copy": { @@ -2411,9 +1915,7 @@ "type": "string" } }, - "required": [ - "document_id" - ] + "required": ["document_id"] } }, { @@ -2439,11 +1941,7 @@ "type": "integer" } }, - "required": [ - "previous_page", - "current_page", - "total_pages" - ] + "required": ["previous_page", "current_page", "total_pages"] } }, { @@ -2459,23 +1957,11 @@ "type": "string" } }, - "required": [ - "document_id", - "submission_id" - ] + "required": ["document_id", "submission_id"] } } ], - "locales": [ - "fr", - "en", - "it", - "de", - "pt", - "es", - "ja", - "nl" - ], + "locales": ["fr", "en", "it", "de", "pt", "es", "ja", "nl"], "editor_error_schema": { "anyOf": [ { @@ -2528,24 +2014,14 @@ "type": "string" } }, - "required": [ - "field_id", - "code", - "message" - ] + "required": ["field_id", "code", "message"] } } }, - "required": [ - "failures" - ] + "required": ["failures"] } }, - "required": [ - "code", - "message", - "details" - ] + "required": ["code", "message", "details"] }, { "type": "object", @@ -2565,32 +2041,16 @@ "type": "integer" } }, - "required": [ - "unfilled_required_fields_count" - ] + "required": ["unfilled_required_fields_count"] } }, - "required": [ - "code", - "message", - "details" - ] + "required": ["code", "message", "details"] }, { "type": "object", "properties": { "code": { "anyOf": [ - { - "type": "string", - "const": "conflict:build_session_mismatch", - "description": "Different editor session. Read the guide again." - }, - { - "type": "string", - "const": "conflict:base_revision_mismatch", - "description": "Published revision changed. Inspect before rebuilding." - }, { "type": "string", "const": "conflict:idempotency_key_reused", @@ -2621,11 +2081,6 @@ "const": "resource:session_limit", "description": "Session job limit reached. Open an empty editor." }, - { - "type": "string", - "const": "conflict:inspection_revision_mismatch", - "description": "The requested revision is not displayed." - }, { "type": "string", "const": "conflict:inspection_state_changed", @@ -2752,10 +2207,7 @@ "type": "string" } }, - "required": [ - "code", - "message" - ] + "required": ["code", "message"] } ] } diff --git a/embed/etc/index.api.md b/embed/etc/index.api.md index 1730e19b..c6c1214c 100644 --- a/embed/etc/index.api.md +++ b/embed/etc/index.api.md @@ -73,26 +73,16 @@ export class BridgeUnwrapError extends Error { // @public (undocumented) export type BuildPdfInput = { action: "build"; - inspect?: { - pages?: number[]; - }; code: string; idempotencyKey: string; - buildSessionId?: string; - baseRevision?: number; name?: string; assets?: Array<{ path: string; dataUrl: string; }>; - waitMs?: number; } | { action: "status"; jobId: string; - waitMs?: number; - inspect?: { - pages?: number[]; - }; } | { action: "cancel"; jobId: string; @@ -101,24 +91,12 @@ export type BuildPdfInput = { // @public (undocumented) export type BuildPdfOutput = { jobId: string; - buildSessionId: string; - revision: number; - publishedRevision: number; status: "queued"; - pollAfterMs: number; } | { jobId: string; - buildSessionId: string; - revision: number; - publishedRevision: number; status: "running"; - stage: "queued" | "initializing" | "compiling" | "validating" | "loading" | "ready"; - pollAfterMs: number; } | { jobId: string; - buildSessionId: string; - revision: number; - publishedRevision: number; status: "succeeded"; pageCount: number; warnings: Array<{ @@ -130,21 +108,15 @@ export type BuildPdfOutput = { column?: number; hint?: string; }>; - warningsTruncated: boolean; - inspection?: { + preview: { success: true; data: { - pages: Array<{ - buildSessionId: string | null; - revision: number | null; - editorStateVersion: number; - page: number; - imageDataUrl: string; - imageWidth: number; - imageHeight: number; - badges: Record; - }>; - omittedPages: number[]; + jobId: string | null; + page: number; + imageDataUrl: string; + imageWidth: number; + imageHeight: number; + badges: Record; }; } | { success: false; @@ -165,20 +137,16 @@ export type BuildPdfOutput = { unfilledRequiredFieldsCount: number; }; } | { - code: "conflict:build_session_mismatch" | "conflict:base_revision_mismatch" | "conflict:idempotency_key_reused" | "conflict:editor_modified" | "conflict:unmanaged_document" | "not_found:job" | "not_found:job_expired" | "resource:session_limit" | "conflict:inspection_revision_mismatch" | "conflict:inspection_state_changed" | "bad_request:download_blocked" | "bad_request:editor_not_ready" | "bad_request:event_not_allowed" | "bad_request:failed_to_load_document" | "bad_request:field_not_found" | "bad_request:invalid_dimensions" | "bad_request:invalid_event_type" | "bad_request:invalid_field_ids" | "bad_request:invalid_field_type" | "bad_request:invalid_page" | "bad_request:invalid_signature_url" | "bad_request:invalid_tool" | "bad_request:invalid_value" | "bad_request:no_document_loaded" | "bad_request:page_not_found" | "bad_request:page_out_of_range" | "bad_request:plan_upgrade_required" | "bad_request:read_only" | "bad_request:signup_required" | "forbidden:editing_not_allowed" | "forbidden:origin_not_whitelisted" | "forbidden:whitelist_required" | "unexpected:internal_error"; + code: "conflict:idempotency_key_reused" | "conflict:editor_modified" | "conflict:unmanaged_document" | "not_found:job" | "not_found:job_expired" | "resource:session_limit" | "conflict:inspection_state_changed" | "bad_request:download_blocked" | "bad_request:editor_not_ready" | "bad_request:event_not_allowed" | "bad_request:failed_to_load_document" | "bad_request:field_not_found" | "bad_request:invalid_dimensions" | "bad_request:invalid_event_type" | "bad_request:invalid_field_ids" | "bad_request:invalid_field_type" | "bad_request:invalid_page" | "bad_request:invalid_signature_url" | "bad_request:invalid_tool" | "bad_request:invalid_value" | "bad_request:no_document_loaded" | "bad_request:page_not_found" | "bad_request:page_out_of_range" | "bad_request:plan_upgrade_required" | "bad_request:read_only" | "bad_request:signup_required" | "forbidden:editing_not_allowed" | "forbidden:origin_not_whitelisted" | "forbidden:whitelist_required" | "unexpected:internal_error"; message: string; }; }; } | { jobId: string; - buildSessionId: string; - revision: number; - publishedRevision: number; status: "failed"; error: { code: "unsupported_dependency" | "engine_initialization_failed" | "compile_error" | "compile_timeout" | "job_timeout" | "resource_limit" | "invalid_pdf" | "editor_load_failed" | "editor_conflict" | "worker_crashed" | "internal_error"; message: string; - stage: "queued" | "initializing" | "compiling" | "validating" | "loading" | "ready"; retryable: boolean; diagnostics: Array<{ severity: "error" | "warning"; @@ -189,19 +157,12 @@ export type BuildPdfOutput = { column?: number; hint?: string; }>; - diagnosticsTruncated: boolean; }; } | { jobId: string; - buildSessionId: string; - revision: number; - publishedRevision: number; status: "cancelled"; } | { jobId: string; - buildSessionId: string; - revision: number; - publishedRevision: number; status: "superseded"; }; @@ -371,16 +332,12 @@ export type FocusFieldOutput = { // @public (undocumented) export type GetAnnotatedPageInput = { page: number; - expectedBuildSessionId?: string; - expectedRevision?: number; - expectedEditorStateVersion?: number; + expectedJobId?: string; }; // @public (undocumented) export type GetAnnotatedPageOutput = { - buildSessionId: string | null; - revision: number | null; - editorStateVersion: number; + jobId: string | null; page: number; imageDataUrl: string; imageWidth: number; @@ -402,7 +359,6 @@ export type GetDocumentationOutput = { }>; } | { kind: "topic"; - topic: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.troubleshooting" | "fields" | "inspection"; markdown: string; }; diff --git a/embed/etc/protocol.api.md b/embed/etc/protocol.api.md index 8b19de8f..da9d2345 100644 --- a/embed/etc/protocol.api.md +++ b/embed/etc/protocol.api.md @@ -5,7 +5,7 @@ ```ts // @public (undocumented) -export const EDITOR_ERROR_CODES: readonly ["bad_request:batch_validation_failed", "bad_request:download_blocked", "bad_request:editor_not_ready", "bad_request:event_not_allowed", "bad_request:failed_to_load_document", "bad_request:field_not_found", "bad_request:invalid_dimensions", "bad_request:invalid_event_type", "bad_request:invalid_field_ids", "bad_request:invalid_field_type", "bad_request:invalid_page", "bad_request:invalid_signature_url", "bad_request:invalid_tool", "bad_request:invalid_value", "bad_request:missing_required_fields", "bad_request:no_document_loaded", "bad_request:page_not_found", "bad_request:page_out_of_range", "bad_request:plan_upgrade_required", "bad_request:read_only", "bad_request:signup_required", "conflict:base_revision_mismatch", "conflict:build_session_mismatch", "conflict:editor_modified", "conflict:idempotency_key_reused", "conflict:inspection_revision_mismatch", "conflict:inspection_state_changed", "conflict:unmanaged_document", "forbidden:editing_not_allowed", "forbidden:origin_not_whitelisted", "forbidden:whitelist_required", "not_found:job", "not_found:job_expired", "resource:session_limit", "unexpected:internal_error"]; +export const EDITOR_ERROR_CODES: readonly ["bad_request:batch_validation_failed", "bad_request:download_blocked", "bad_request:editor_not_ready", "bad_request:event_not_allowed", "bad_request:failed_to_load_document", "bad_request:field_not_found", "bad_request:invalid_dimensions", "bad_request:invalid_event_type", "bad_request:invalid_field_ids", "bad_request:invalid_field_type", "bad_request:invalid_page", "bad_request:invalid_signature_url", "bad_request:invalid_tool", "bad_request:invalid_value", "bad_request:missing_required_fields", "bad_request:no_document_loaded", "bad_request:page_not_found", "bad_request:page_out_of_range", "bad_request:plan_upgrade_required", "bad_request:read_only", "bad_request:signup_required", "conflict:editor_modified", "conflict:idempotency_key_reused", "conflict:inspection_state_changed", "conflict:unmanaged_document", "forbidden:editing_not_allowed", "forbidden:origin_not_whitelisted", "forbidden:whitelist_required", "not_found:job", "not_found:job_expired", "resource:session_limit", "unexpected:internal_error"]; // @public (undocumented) export const EXTRACTION_MODES: readonly ["auto", "ocr"]; @@ -30,8 +30,8 @@ export const OPERATIONS: readonly [{ readonly request_type: "BUILD_PDF"; readonly wire_type: "BUILD_PDF"; readonly method: "buildPdf"; - readonly description: "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Add inspect for page images. Edits block rebuilding. No sharing."; - readonly error_codes: readonly ["conflict:build_session_mismatch", "conflict:base_revision_mismatch", "conflict:idempotency_key_reused", "conflict:editor_modified", "conflict:unmanaged_document", "not_found:job", "not_found:job_expired", "resource:session_limit", "conflict:inspection_revision_mismatch", "conflict:inspection_state_changed", "bad_request:invalid_value", "forbidden:editing_not_allowed"]; + readonly description: "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing."; + readonly error_codes: readonly ["conflict:idempotency_key_reused", "conflict:editor_modified", "conflict:unmanaged_document", "not_found:job", "not_found:job_expired", "resource:session_limit", "conflict:inspection_state_changed", "bad_request:invalid_value", "forbidden:editing_not_allowed"]; readonly is_agentic_tool: true; readonly has_output: true; }, { @@ -103,7 +103,7 @@ export const OPERATIONS: readonly [{ readonly wire_type: "GET_ANNOTATED_PAGE"; readonly method: "getAnnotatedPage"; readonly description: "Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block."; - readonly error_codes: readonly ["bad_request:no_document_loaded", "bad_request:invalid_page", "bad_request:page_out_of_range", "bad_request:invalid_value", "conflict:inspection_revision_mismatch", "conflict:inspection_state_changed"]; + readonly error_codes: readonly ["bad_request:no_document_loaded", "bad_request:invalid_page", "bad_request:page_out_of_range", "bad_request:invalid_value", "conflict:inspection_state_changed"]; readonly is_agentic_tool: true; readonly has_output: true; }, { diff --git a/embed/etc/schemas.api.md b/embed/etc/schemas.api.md index fbcf6d94..ae917e30 100644 --- a/embed/etc/schemas.api.md +++ b/embed/etc/schemas.api.md @@ -20,26 +20,16 @@ export type BatchSetFieldValuesInput = z.infer; // @public (undocumented) export const BuildPdfInput: z.ZodUnion; - inspect: z.ZodOptional>; - }, z.core.$strict>>; code: z.ZodString; idempotencyKey: z.ZodString; - buildSessionId: z.ZodOptional; - baseRevision: z.ZodOptional; name: z.ZodOptional; assets: z.ZodOptional>>; - waitMs: z.ZodOptional; }, z.core.$strict>, z.ZodObject<{ action: z.ZodLiteral<"status">; jobId: z.ZodString; - waitMs: z.ZodOptional; - inspect: z.ZodOptional>; - }, z.core.$strict>>; }, z.core.$strict>, z.ZodObject<{ action: z.ZodLiteral<"cancel">; jobId: z.ZodString; @@ -108,9 +98,7 @@ export type FocusFieldInput = z.infer; // @public (undocumented) export const GetAnnotatedPageInput: z.ZodObject<{ page: z.ZodNumber; - expectedBuildSessionId: z.ZodOptional; - expectedRevision: z.ZodOptional; - expectedEditorStateVersion: z.ZodOptional; + expectedJobId: z.ZodOptional; }, z.core.$strict>; // @public (undocumented) diff --git a/embed/etc/tanstack-ai.api.md b/embed/etc/tanstack-ai.api.md index b85846e7..3feeb870 100644 --- a/embed/etc/tanstack-ai.api.md +++ b/embed/etc/tanstack-ai.api.md @@ -27,7 +27,7 @@ export type SimplePDFToolName = keyof typeof TOOL_DEFINITIONS; // Warnings were encountered during analysis: // -// dist/tanstack-ai.d.ts:96:5 - (ae-forgotten-export) The symbol "Embed" needs to be exported by the entry point tanstack-ai.d.ts +// dist/tanstack-ai.d.ts:88:5 - (ae-forgotten-export) The symbol "Embed" needs to be exported by the entry point tanstack-ai.d.ts // (No @packageDocumentation comment for this package) diff --git a/embed/etc/tools.api.md b/embed/etc/tools.api.md index dc65b7f7..8412bc83 100644 --- a/embed/etc/tools.api.md +++ b/embed/etc/tools.api.md @@ -18,22 +18,16 @@ export const routeToolCall: (actions: IframeActions, toolName: SimplePDFToolName // @public (undocumented) export const SIMPLEPDF_TOOLS: { readonly buildPdf: { - readonly description: "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Add inspect for page images. Edits block rebuilding. No sharing."; + readonly description: "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing."; readonly inputSchema: z.ZodObject<{ action: z.ZodUnion, z.ZodLiteral<"status">, z.ZodLiteral<"cancel">]>; - inspect: z.ZodOptional>; - }, z.core.$strict>>; code: z.ZodOptional; idempotencyKey: z.ZodOptional; - buildSessionId: z.ZodOptional; - baseRevision: z.ZodOptional; name: z.ZodOptional; assets: z.ZodOptional>>; - waitMs: z.ZodOptional; jobId: z.ZodOptional; }, z.core.$strict>; }; @@ -110,9 +104,7 @@ export const SIMPLEPDF_TOOLS: { readonly description: "Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block."; readonly inputSchema: z.ZodObject<{ page: z.ZodNumber; - expectedBuildSessionId: z.ZodOptional; - expectedRevision: z.ZodOptional; - expectedEditorStateVersion: z.ZodOptional; + expectedJobId: z.ZodOptional; }, z.core.$strict>; }; readonly getDocumentContent: { diff --git a/embed/src/generated/contract.ts b/embed/src/generated/contract.ts index a56f09a4..a65c0fea 100644 --- a/embed/src/generated/contract.ts +++ b/embed/src/generated/contract.ts @@ -5,7 +5,7 @@ import type { METHOD_NAMES } from './bridge-vocabulary' export const LOCALES = ["fr", "en", "it", "de", "pt", "es", "ja", "nl"] as const export type Locale = (typeof LOCALES)[number] -export const EDITOR_ERROR_CODES = ["bad_request:batch_validation_failed", "bad_request:download_blocked", "bad_request:editor_not_ready", "bad_request:event_not_allowed", "bad_request:failed_to_load_document", "bad_request:field_not_found", "bad_request:invalid_dimensions", "bad_request:invalid_event_type", "bad_request:invalid_field_ids", "bad_request:invalid_field_type", "bad_request:invalid_page", "bad_request:invalid_signature_url", "bad_request:invalid_tool", "bad_request:invalid_value", "bad_request:missing_required_fields", "bad_request:no_document_loaded", "bad_request:page_not_found", "bad_request:page_out_of_range", "bad_request:plan_upgrade_required", "bad_request:read_only", "bad_request:signup_required", "conflict:base_revision_mismatch", "conflict:build_session_mismatch", "conflict:editor_modified", "conflict:idempotency_key_reused", "conflict:inspection_revision_mismatch", "conflict:inspection_state_changed", "conflict:unmanaged_document", "forbidden:editing_not_allowed", "forbidden:origin_not_whitelisted", "forbidden:whitelist_required", "not_found:job", "not_found:job_expired", "resource:session_limit", "unexpected:internal_error"] as const +export const EDITOR_ERROR_CODES = ["bad_request:batch_validation_failed", "bad_request:download_blocked", "bad_request:editor_not_ready", "bad_request:event_not_allowed", "bad_request:failed_to_load_document", "bad_request:field_not_found", "bad_request:invalid_dimensions", "bad_request:invalid_event_type", "bad_request:invalid_field_ids", "bad_request:invalid_field_type", "bad_request:invalid_page", "bad_request:invalid_signature_url", "bad_request:invalid_tool", "bad_request:invalid_value", "bad_request:missing_required_fields", "bad_request:no_document_loaded", "bad_request:page_not_found", "bad_request:page_out_of_range", "bad_request:plan_upgrade_required", "bad_request:read_only", "bad_request:signup_required", "conflict:editor_modified", "conflict:idempotency_key_reused", "conflict:inspection_state_changed", "conflict:unmanaged_document", "forbidden:editing_not_allowed", "forbidden:origin_not_whitelisted", "forbidden:whitelist_required", "not_found:job", "not_found:job_expired", "resource:session_limit", "unexpected:internal_error"] as const export type EditorErrorCode = (typeof EDITOR_ERROR_CODES)[number] export const FIELD_TYPES = ["TEXT", "SIGNATURE", "PICTURE", "CHECKBOX", "COMB_TEXT", "DROPDOWN", "RADIO"] as const @@ -17,10 +17,10 @@ export type OverlayToolType = (typeof OVERLAY_TOOL_TYPES)[number] export const EXTRACTION_MODES = ["auto", "ocr"] as const export type ExtractionMode = (typeof EXTRACTION_MODES)[number] -export type BuildPdfInput = { action: "build"; inspect?: { pages?: number[] }; code: string; idempotencyKey: string; buildSessionId?: string; baseRevision?: number; name?: string; assets?: Array<{ path: string; dataUrl: string }>; waitMs?: number } | { action: "status"; jobId: string; waitMs?: number; inspect?: { pages?: number[] } } | { action: "cancel"; jobId: string } -export type BuildPdfOutput = { jobId: string; buildSessionId: string; revision: number; publishedRevision: number; status: "queued"; pollAfterMs: number } | { jobId: string; buildSessionId: string; revision: number; publishedRevision: number; status: "running"; stage: "queued" | "initializing" | "compiling" | "validating" | "loading" | "ready"; pollAfterMs: number } | { jobId: string; buildSessionId: string; revision: number; publishedRevision: number; status: "succeeded"; pageCount: number; warnings: Array<{ severity: "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number; hint?: string }>; warningsTruncated: boolean; inspection?: { success: true; data: { pages: Array<{ buildSessionId: string | null; revision: number | null; editorStateVersion: number; page: number; imageDataUrl: string; imageWidth: number; imageHeight: number; badges: Record }>; omittedPages: number[] } } | { success: false; error: { code: "bad_request:batch_validation_failed"; message: string; details: { failures: Array<{ fieldId: string; code: "bad_request:field_not_found" | "bad_request:invalid_signature_url" | "bad_request:invalid_value" | "bad_request:read_only"; message: string }> } } | { code: "bad_request:missing_required_fields"; message: string; details: { unfilledRequiredFieldsCount: number } } | { code: "conflict:build_session_mismatch" | "conflict:base_revision_mismatch" | "conflict:idempotency_key_reused" | "conflict:editor_modified" | "conflict:unmanaged_document" | "not_found:job" | "not_found:job_expired" | "resource:session_limit" | "conflict:inspection_revision_mismatch" | "conflict:inspection_state_changed" | "bad_request:download_blocked" | "bad_request:editor_not_ready" | "bad_request:event_not_allowed" | "bad_request:failed_to_load_document" | "bad_request:field_not_found" | "bad_request:invalid_dimensions" | "bad_request:invalid_event_type" | "bad_request:invalid_field_ids" | "bad_request:invalid_field_type" | "bad_request:invalid_page" | "bad_request:invalid_signature_url" | "bad_request:invalid_tool" | "bad_request:invalid_value" | "bad_request:no_document_loaded" | "bad_request:page_not_found" | "bad_request:page_out_of_range" | "bad_request:plan_upgrade_required" | "bad_request:read_only" | "bad_request:signup_required" | "forbidden:editing_not_allowed" | "forbidden:origin_not_whitelisted" | "forbidden:whitelist_required" | "unexpected:internal_error"; message: string } } } | { jobId: string; buildSessionId: string; revision: number; publishedRevision: number; status: "failed"; error: { code: "unsupported_dependency" | "engine_initialization_failed" | "compile_error" | "compile_timeout" | "job_timeout" | "resource_limit" | "invalid_pdf" | "editor_load_failed" | "editor_conflict" | "worker_crashed" | "internal_error"; message: string; stage: "queued" | "initializing" | "compiling" | "validating" | "loading" | "ready"; retryable: boolean; diagnostics: Array<{ severity: "error" | "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number; hint?: string }>; diagnosticsTruncated: boolean } } | { jobId: string; buildSessionId: string; revision: number; publishedRevision: number; status: "cancelled" } | { jobId: string; buildSessionId: string; revision: number; publishedRevision: number; status: "superseded" } +export type BuildPdfInput = { action: "build"; code: string; idempotencyKey: string; name?: string; assets?: Array<{ path: string; dataUrl: string }> } | { action: "status"; jobId: string } | { action: "cancel"; jobId: string } +export type BuildPdfOutput = { jobId: string; status: "queued" } | { jobId: string; status: "running" } | { jobId: string; status: "succeeded"; pageCount: number; warnings: Array<{ severity: "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number; hint?: string }>; preview: { success: true; data: { jobId: string | null; page: number; imageDataUrl: string; imageWidth: number; imageHeight: number; badges: Record } } | { success: false; error: { code: "bad_request:batch_validation_failed"; message: string; details: { failures: Array<{ fieldId: string; code: "bad_request:field_not_found" | "bad_request:invalid_signature_url" | "bad_request:invalid_value" | "bad_request:read_only"; message: string }> } } | { code: "bad_request:missing_required_fields"; message: string; details: { unfilledRequiredFieldsCount: number } } | { code: "conflict:idempotency_key_reused" | "conflict:editor_modified" | "conflict:unmanaged_document" | "not_found:job" | "not_found:job_expired" | "resource:session_limit" | "conflict:inspection_state_changed" | "bad_request:download_blocked" | "bad_request:editor_not_ready" | "bad_request:event_not_allowed" | "bad_request:failed_to_load_document" | "bad_request:field_not_found" | "bad_request:invalid_dimensions" | "bad_request:invalid_event_type" | "bad_request:invalid_field_ids" | "bad_request:invalid_field_type" | "bad_request:invalid_page" | "bad_request:invalid_signature_url" | "bad_request:invalid_tool" | "bad_request:invalid_value" | "bad_request:no_document_loaded" | "bad_request:page_not_found" | "bad_request:page_out_of_range" | "bad_request:plan_upgrade_required" | "bad_request:read_only" | "bad_request:signup_required" | "forbidden:editing_not_allowed" | "forbidden:origin_not_whitelisted" | "forbidden:whitelist_required" | "unexpected:internal_error"; message: string } } } | { jobId: string; status: "failed"; error: { code: "unsupported_dependency" | "engine_initialization_failed" | "compile_error" | "compile_timeout" | "job_timeout" | "resource_limit" | "invalid_pdf" | "editor_load_failed" | "editor_conflict" | "worker_crashed" | "internal_error"; message: string; retryable: boolean; diagnostics: Array<{ severity: "error" | "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number; hint?: string }> } } | { jobId: string; status: "cancelled" } | { jobId: string; status: "superseded" } export type GetDocumentationInput = { topic?: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.troubleshooting" | "fields" | "inspection" } -export type GetDocumentationOutput = { kind: "index"; topics: Array<{ topic: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.troubleshooting" | "fields" | "inspection"; description: string }> } | { kind: "topic"; topic: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.troubleshooting" | "fields" | "inspection"; markdown: string } +export type GetDocumentationOutput = { kind: "index"; topics: Array<{ topic: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.troubleshooting" | "fields" | "inspection"; description: string }> } | { kind: "topic"; markdown: string } export type BatchSetFieldValuesInput = { updates: Array<{ fieldId: string; value: string | null }> } export type BatchSetFieldValuesOutput = null export type CreateFieldInput = { type: OverlayToolType; x: number; y: number; width: number; height: number; page: number; value?: string } @@ -35,8 +35,8 @@ export type DownloadInput = Record export type DownloadOutput = null export type FocusFieldInput = { fieldId: string } export type FocusFieldOutput = { hint: { type: "user_action_expected"; message: string } } -export type GetAnnotatedPageInput = { page: number; expectedBuildSessionId?: string; expectedRevision?: number; expectedEditorStateVersion?: number } -export type GetAnnotatedPageOutput = { buildSessionId: string | null; revision: number | null; editorStateVersion: number; page: number; imageDataUrl: string; imageWidth: number; imageHeight: number; badges: Record } +export type GetAnnotatedPageInput = { page: number; expectedJobId?: string } +export type GetAnnotatedPageOutput = { jobId: string | null; page: number; imageDataUrl: string; imageWidth: number; imageHeight: number; badges: Record } export type GetDocumentContentInput = { extractionMode?: ExtractionMode } export type GetDocumentContentOutput = { name: string; pages: Array<{ page: number; content: string }> } export type GetFieldsInput = Record @@ -76,8 +76,8 @@ export const OPERATIONS = [ request_type: "BUILD_PDF", wire_type: "BUILD_PDF", method: "buildPdf", - description: "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Add inspect for page images. Edits block rebuilding. No sharing.", - error_codes: ["conflict:build_session_mismatch", "conflict:base_revision_mismatch", "conflict:idempotency_key_reused", "conflict:editor_modified", "conflict:unmanaged_document", "not_found:job", "not_found:job_expired", "resource:session_limit", "conflict:inspection_revision_mismatch", "conflict:inspection_state_changed", "bad_request:invalid_value", "forbidden:editing_not_allowed"] as const, + description: "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing.", + error_codes: ["conflict:idempotency_key_reused", "conflict:editor_modified", "conflict:unmanaged_document", "not_found:job", "not_found:job_expired", "resource:session_limit", "conflict:inspection_state_changed", "bad_request:invalid_value", "forbidden:editing_not_allowed"] as const, is_agentic_tool: true, has_output: true, } /* BuildPdf */, @@ -158,7 +158,7 @@ export const OPERATIONS = [ wire_type: "GET_ANNOTATED_PAGE", method: "getAnnotatedPage", description: "Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block.", - error_codes: ["bad_request:no_document_loaded", "bad_request:invalid_page", "bad_request:page_out_of_range", "bad_request:invalid_value", "conflict:inspection_revision_mismatch", "conflict:inspection_state_changed"] as const, + error_codes: ["bad_request:no_document_loaded", "bad_request:invalid_page", "bad_request:page_out_of_range", "bad_request:invalid_value", "conflict:inspection_state_changed"] as const, is_agentic_tool: true, has_output: true, } /* GetAnnotatedPage */, diff --git a/embed/src/generated/schemas.ts b/embed/src/generated/schemas.ts index 02ec41f6..426e0874 100644 --- a/embed/src/generated/schemas.ts +++ b/embed/src/generated/schemas.ts @@ -3,26 +3,16 @@ import { z } from 'zod' export const BuildPdfInput = z.union([z.strictObject({ action: z.literal("build"), - inspect: z.strictObject({ - pages: z.array(z.number().int()).optional(), -}).optional(), code: z.string(), idempotencyKey: z.string(), - buildSessionId: z.string().optional(), - baseRevision: z.number().int().optional(), name: z.string().optional(), assets: z.array(z.strictObject({ path: z.string(), dataUrl: z.string(), })).optional(), - waitMs: z.number().int().optional(), }), z.strictObject({ action: z.literal("status"), jobId: z.string(), - waitMs: z.number().int().optional(), - inspect: z.strictObject({ - pages: z.array(z.number().int()).optional(), -}).optional(), }), z.strictObject({ action: z.literal("cancel"), jobId: z.string(), @@ -68,9 +58,7 @@ export const FocusFieldInput = z.object({ export type FocusFieldInput = z.infer export const GetAnnotatedPageInput = z.strictObject({ page: z.number().int().describe("1-based page to render, at its current position."), - expectedBuildSessionId: z.string().optional(), - expectedRevision: z.number().int().optional(), - expectedEditorStateVersion: z.number().int().optional(), + expectedJobId: z.string().optional(), }) export type GetAnnotatedPageInput = z.infer export const GetDocumentContentInput = z.object({ diff --git a/embed/src/generated/tools.ts b/embed/src/generated/tools.ts index e4c32bd4..7c9a39b1 100644 --- a/embed/src/generated/tools.ts +++ b/embed/src/generated/tools.ts @@ -5,21 +5,15 @@ import { z } from 'zod' // The agentic tool registry. Each tool name is the camelCase operation name; // load_document is excluded here (a host/setup action; the WebMCP surface registers it). export const TOOL_DEFINITIONS = { - buildPdf: { description: "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Add inspect for page images. Edits block rebuilding. No sharing.", inputSchema: z.strictObject({ + buildPdf: { description: "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing.", inputSchema: z.strictObject({ action: z.union([z.literal("build"), z.literal("status"), z.literal("cancel")]), - inspect: z.strictObject({ - pages: z.array(z.number().int()).optional(), -}).optional(), code: z.string().optional(), idempotencyKey: z.string().optional(), - buildSessionId: z.string().optional(), - baseRevision: z.number().int().optional(), name: z.string().optional(), assets: z.array(z.strictObject({ path: z.string(), dataUrl: z.string(), })).optional(), - waitMs: z.number().int().optional(), jobId: z.string().optional(), }) }, getDocumentation: { description: "Read task guidance and tested PDF recipes. Omit topic for the index.", inputSchema: Schemas.GetDocumentationInput }, diff --git a/embed/src/generated/webmcp-tools.ts b/embed/src/generated/webmcp-tools.ts index 1b3b6b81..b5dcbc91 100644 --- a/embed/src/generated/webmcp-tools.ts +++ b/embed/src/generated/webmcp-tools.ts @@ -27,7 +27,7 @@ export type WebMCPToolRecord = { } export const WEBMCP_TOOLS = { - buildPdf: {"name":"build_pdf","description":"Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Add inspect for page images. Edits block rebuilding. No sharing.","inputSchema":{"anyOf":[{"type":"object","properties":{"action":{"type":"string","const":"build"},"inspect":{"type":"object","properties":{"pages":{"type":"array","items":{"type":"integer"}}},"additionalProperties":false},"code":{"type":"string"},"idempotency_key":{"type":"string"},"build_session_id":{"type":"string"},"base_revision":{"type":"integer"},"name":{"type":"string"},"assets":{"type":"array","items":{"type":"object","properties":{"path":{"type":"string"},"data_url":{"type":"string"}},"required":["path","data_url"],"additionalProperties":false}},"wait_ms":{"type":"integer"}},"required":["action","code","idempotency_key"],"additionalProperties":false},{"type":"object","properties":{"action":{"type":"string","const":"status"},"job_id":{"type":"string"},"wait_ms":{"type":"integer"},"inspect":{"type":"object","properties":{"pages":{"type":"array","items":{"type":"integer"}}},"additionalProperties":false}},"required":["action","job_id"],"additionalProperties":false},{"type":"object","properties":{"action":{"type":"string","const":"cancel"},"job_id":{"type":"string"}},"required":["action","job_id"],"additionalProperties":false}],"type":"object","properties":{}},"annotations":{"destructiveHint":true,"untrustedContentHint":true},"wireType":"BUILD_PDF"}, + buildPdf: {"name":"build_pdf","description":"Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing.","inputSchema":{"anyOf":[{"type":"object","properties":{"action":{"type":"string","const":"build"},"code":{"type":"string"},"idempotency_key":{"type":"string"},"name":{"type":"string"},"assets":{"type":"array","items":{"type":"object","properties":{"path":{"type":"string"},"data_url":{"type":"string"}},"required":["path","data_url"],"additionalProperties":false}}},"required":["action","code","idempotency_key"],"additionalProperties":false},{"type":"object","properties":{"action":{"type":"string","const":"status"},"job_id":{"type":"string"}},"required":["action","job_id"],"additionalProperties":false},{"type":"object","properties":{"action":{"type":"string","const":"cancel"},"job_id":{"type":"string"}},"required":["action","job_id"],"additionalProperties":false}],"type":"object","properties":{}},"annotations":{"destructiveHint":true,"untrustedContentHint":true},"wireType":"BUILD_PDF"}, getDocumentation: {"name":"get_documentation","description":"Read task guidance and tested PDF recipes. Omit topic for the index.","inputSchema":{"additionalProperties":false,"type":"object","properties":{"topic":{"enum":["build_pdf","build_pdf.templates","build_pdf.forms","build_pdf.assets","build_pdf.fonts","build_pdf.troubleshooting","fields","inspection"],"type":"string"}}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_DOCUMENTATION"}, batchSetFieldValues: {"name":"simplepdf_embed_batch_set_field_values","description":"Set existing fields, addressed by ids from the field list, in one atomic undo step. If any update is rejected, nothing changes and the call fails with bad_request:batch_validation_failed, whose details list each rejection with its field id, code and message. Text is set at once, never typed. Returns no data.","inputSchema":{"required":["updates"],"type":"object","properties":{"updates":{"items":{"type":"object","properties":{"field_id":{"type":"string","description":"ID of the field to update."},"value":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"New value for the field, or null to clear it. If the field has options (see the field list), it must be one of them; otherwise a string (text/checkbox), or a data URL or http(s) URL, fetched by the editor (signature/picture), or plain text for a signature, drawn as a typed signature."}},"required":["field_id","value"]},"description":"The fields to set, at least one, each field at most once. Fields not listed keep their value.","type":"array"}}},"annotations":{"destructiveHint":false,"openWorldHint":true},"wireType":"BATCH_SET_FIELD_VALUES"}, createField: {"name":"simplepdf_embed_create_field","description":"Create a new overlay field on a page. Returns the id of the created field.","inputSchema":{"required":["type","x","y","width","height","page"],"type":"object","properties":{"type":{"enum":["TEXT","SIGNATURE","PICTURE","CHECKBOX","COMB_TEXT"],"description":"Field type to create.","type":"string"},"x":{"description":"Field x position, in PDF points.","type":"number"},"y":{"description":"Field y position, in PDF points.","type":"number"},"width":{"description":"Field width, in PDF points.","type":"number"},"height":{"description":"Field height, in PDF points.","type":"number"},"page":{"description":"1-based page to place the field on.","type":"integer"},"value":{"description":"Optional initial value. A string for text/checkbox fields; a data URL or http(s) URL (fetched by the editor) for signature/picture fields, or plain text for a signature, drawn as a typed signature.","type":"string"}}},"annotations":{"destructiveHint":false,"openWorldHint":true},"wireType":"CREATE_FIELD"}, @@ -36,7 +36,7 @@ export const WEBMCP_TOOLS = { detectFields: {"name":"simplepdf_embed_detect_fields","description":"Automatically detect fillable fields in the loaded document and add them as editable fields. Returns the number of fields detected.","inputSchema":{"type":"object","properties":{}},"annotations":{"destructiveHint":false},"wireType":"DETECT_FIELDS"}, download: {"name":"simplepdf_embed_download","description":"Generate and download the current document as a PDF. Returns no data.","inputSchema":{"type":"object","properties":{}},"annotations":{"destructiveHint":false},"wireType":"DOWNLOAD"}, focusField: {"name":"simplepdf_embed_focus_field","description":"Scroll an existing field into view and focus it, addressed by its id from the field list. Returns a hint describing the user action expected next.","inputSchema":{"required":["field_id"],"type":"object","properties":{"field_id":{"description":"ID of the field to focus and scroll into view.","type":"string"}}},"annotations":{"destructiveHint":false},"wireType":"FOCUS_FIELD"}, - getAnnotatedPage: {"name":"simplepdf_embed_get_annotated_page","description":"Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block.","inputSchema":{"required":["page"],"additionalProperties":false,"type":"object","properties":{"page":{"description":"1-based page to render, at its current position.","type":"integer"},"expected_build_session_id":{"type":"string"},"expected_revision":{"type":"integer"},"expected_editor_state_version":{"type":"integer"}}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_ANNOTATED_PAGE"}, + getAnnotatedPage: {"name":"simplepdf_embed_get_annotated_page","description":"Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block.","inputSchema":{"required":["page"],"additionalProperties":false,"type":"object","properties":{"page":{"description":"1-based page to render, at its current position.","type":"integer"},"expected_job_id":{"type":"string"}}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_ANNOTATED_PAGE"}, getDocumentContent: {"name":"simplepdf_embed_get_document_content","description":"Extract the document's content page by page as Markdown, or as plain text when optical recognition is forced. Use it to read what the document says. Returns the document name and each page's content.","inputSchema":{"type":"object","properties":{"extraction_mode":{"description":"Extraction strategy: 'auto' (default) or 'ocr' to force optical recognition.","enum":["auto","ocr"],"type":"string"}}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_DOCUMENT_CONTENT"}, getFields: {"name":"simplepdf_embed_get_fields","description":"List every fillable field in the loaded document, including native dropdown and radio AcroFields. Each field reports its id, name, type, page, current value, and the options its value must be one of, if any. Call this first to discover field ids before reading or setting values. To SEE where each field sits on the printed page, render the annotated page. Returns the field list.","inputSchema":{"type":"object","properties":{}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_FIELDS"}, goTo: {"name":"simplepdf_embed_go_to","description":"Scroll the editor to a page. Returns no data.","inputSchema":{"required":["page"],"type":"object","properties":{"page":{"description":"1-based page to navigate to.","type":"integer"}}},"annotations":{"destructiveHint":false},"wireType":"GO_TO"}, diff --git a/embed/src/webmcp.ts b/embed/src/webmcp.ts index 5c4dcc6d..d6de1904 100644 --- a/embed/src/webmcp.ts +++ b/embed/src/webmcp.ts @@ -40,7 +40,7 @@ const toTextToolResult = (result: BridgeResult): CallToolResult => ({ ...(result.success ? {} : { isError: true }), }) -// Keep the image bytes separate from metadata on both inspection paths. +// Both an annotated page and a build preview carry their PNG once as a native MCP image. const splitPageImage = (render: unknown): { image: ToolContent; metadata: Record } | null => { if (typeof render !== 'object' || render === null || !('image_data_url' in render)) return null const { image_data_url: image, ...metadata } = render @@ -57,46 +57,21 @@ const toAnnotatedPageToolResult = (result: BridgeResult): CallToolResul } } -// Compound inspection carries each PNG once, with the remaining job/page metadata in text. -const toBuildPdfToolResult = ( - result: BridgeResult -): CallToolResult => { +const toBuildPdfToolResult = (result: BridgeResult): CallToolResult => { if (!result.success) return toTextToolResult(result) const job = result.data - if (typeof job !== 'object' || job === null || !('inspection' in job)) - return toTextToolResult(result) - const inspection = job.inspection + if (typeof job !== 'object' || job === null || !('preview' in job)) return toTextToolResult(result) + const preview = job.preview if ( - typeof inspection !== 'object' || - inspection === null || - !('success' in inspection) || - inspection.success !== true || - !('data' in inspection) - ) - return toTextToolResult(result) - const data = inspection.data - if ( - typeof data !== 'object' || - data === null || - !('pages' in data) || - !Array.isArray(data.pages) - ) - return toTextToolResult(result) - const images: ToolContent[] = [] - const pages: Record[] = [] - for (const page of data.pages) { - const split = splitPageImage(page) - if (split === null) return toTextToolResult(result) - images.push(split.image) - pages.push(split.metadata) - } + typeof preview !== 'object' || preview === null || + !('success' in preview) || preview.success !== true || !('data' in preview) + ) return toTextToolResult(result) + const page = splitPageImage(preview.data) + if (page === null) return toTextToolResult(result) return { content: [ - ...images, - ...toTextToolResult({ - success: true, - data: { ...job, inspection: { ...inspection, data: { ...data, pages } } }, - }).content, + page.image, + ...toTextToolResult({ success: true, data: { ...job, preview: { success: true, data: page.metadata } } }).content, ], } } diff --git a/embed/test/tools.test.ts b/embed/test/tools.test.ts index 900ef62f..9a6558de 100644 --- a/embed/test/tools.test.ts +++ b/embed/test/tools.test.ts @@ -61,10 +61,10 @@ describe(routeToolCall.name, () => { expect(actions.getDocumentation).toHaveBeenCalledWith({}) }) - // Router validation must preserve the caller's intended preconditions before any editor call. + // Reject unrecognized keys on each action and in nested assets before dispatch. it.each([ - { action: 'build', code: 'Hello', idempotencyKey: 'key', baseRevison: 2 }, - { action: 'build', code: 'Hello', idempotencyKey: 'key', inspect: { page: [1] } }, + { action: 'build', code: 'Hello', idempotencyKey: 'key', jobId: 'job' }, + { action: 'build', code: 'Hello', idempotencyKey: 'key', inspect: {} }, { action: 'build', code: 'Hello', idempotencyKey: 'key', assets: [{ path: 'a.png', dataUrl: 'data', extra: true }] }, { action: 'cancel', jobId: 'job', code: 'Hello' }, { action: 'build', code: 'Hello' }, @@ -87,21 +87,17 @@ describe(routeToolCall.name, () => { expect(actions.goTo).not.toHaveBeenCalled() }) - it('rejects misspelled inspection preconditions before dispatch', async () => { + it('rejects a misspelled expected job ID before dispatch', async () => { const actions = makeActionsStub() - const result = await routeToolCall(actions, 'getAnnotatedPage', { - page: 1, expectedBuildSessionId: 'session', expectedRevision: 7, expectedEditorStateVerison: 4, - }) + const result = await routeToolCall(actions, 'getAnnotatedPage', { page: 1, expectedJobID: 'job' }) expect(result).toMatchObject({ success: false, error: { code: 'bad_request:invalid_input' } }) expect(actions.getAnnotatedPage).not.toHaveBeenCalled() - await routeToolCall(actions, 'getAnnotatedPage', { page: 1 }) - expect(actions.getAnnotatedPage).toHaveBeenCalledWith({ page: 1 }) }) - it('routes getAnnotatedPage to its action with the validated page', async () => { + it.each([{ page: 1 }, { page: 2, expectedJobId: 'job' }])('routes getAnnotatedPage with %j', async (input) => { const actions = makeActionsStub() - await routeToolCall(actions, 'getAnnotatedPage', { page: 1 }) - expect(actions.getAnnotatedPage).toHaveBeenCalledWith({ page: 1 }) + await routeToolCall(actions, 'getAnnotatedPage', input) + expect(actions.getAnnotatedPage).toHaveBeenCalledWith(input) }) it('dispatches no-input tools without requiring input', async () => { diff --git a/embed/test/webmcp.test.ts b/embed/test/webmcp.test.ts index 0033637c..5585dc0d 100644 --- a/embed/test/webmcp.test.ts +++ b/embed/test/webmcp.test.ts @@ -235,12 +235,12 @@ describe('attachEmbed({ webMCP })', () => { expect(toolResult.content).toEqual([{ type: 'text', text: JSON.stringify({ success: true, data: null }) }]) }) - it('preserves raw WebMCP keys so the editor can reject misspelled build preconditions', async () => { + it('preserves raw WebMCP keys so the editor can reject misspelled build inputs', async () => { const modelContext = installModelContext(document) const harness = mountReady({ webMCP: { enabled: true } }) await waitForTools(modelContext, TOOL_COUNT) const input = { - action: 'build', code: 'Draft', idempotency_key: 'wire-keys', base_revision: 1, baseRevision: 0, + action: 'build', code: 'Draft', idempotency_key: 'wire-keys', idempotencyKey: 'duplicate', assets: [{ path: 'image.png', dataUrl: 'invalid' }], } const pending = findTool(modelContext, 'build_pdf').execute(input) @@ -272,69 +272,34 @@ describe('attachEmbed({ webMCP })', () => { const request = await waitForRequest(harness, 'GET_ANNOTATED_PAGE') harness.reply(request, { success: true, - data: { page: 1, image_data_url: 'data:image/png;base64,iVBORw0KGgo=', image_width: 10, image_height: 12, badges: { '1': 'f1' } }, + data: { page: 1, job_id: null, image_data_url: 'data:image/png;base64,iVBORw0KGgo=', image_width: 10, image_height: 12, badges: { '1': 'f1' } }, }) const toolResult = await pendingResult expect(toolResult.isError).toBeUndefined() expect(toolResult.content).toEqual([ { type: 'image', data: 'iVBORw0KGgo=', mimeType: 'image/png' }, - { type: 'text', text: JSON.stringify({ success: true, data: { page: 1, image_width: 10, image_height: 12, badges: { '1': 'f1' } } }) }, + { type: 'text', text: JSON.stringify({ success: true, data: { page: 1, job_id: null, image_width: 10, image_height: 12, badges: { '1': 'f1' } } }) }, ]) }) - it('returns build inspection as native images without duplicating PNG bytes in text', async () => { + it('returns the first-page build preview as a native image alongside the job metadata', async () => { const modelContext = installModelContext(document) const harness = mountReady({ webMCP: { enabled: true } }) await waitForTools(modelContext, TOOL_COUNT) - const pending = findTool(modelContext, 'build_pdf').execute({ - action: 'status', - job_id: 'job', - inspect: {}, - }) + const pending = findTool(modelContext, 'build_pdf').execute({ action: 'status', job_id: 'job' }) const request = await waitForRequest(harness, 'BUILD_PDF') - const page = { - page: 1, - build_session_id: 'session', - revision: 1, - editor_state_version: 3, - image_data_url: 'data:image/png;base64,iVBORw0KGgo=', - image_width: 10, - image_height: 12, - badges: {}, - } + const page = { page: 1, job_id: 'job', image_width: 10, image_height: 12, badges: {} } + const job = { job_id: 'job', status: 'succeeded', page_count: 2, warnings: [] } harness.reply(request, { success: true, - data: { - job_id: 'job', - build_session_id: 'session', - revision: 1, - published_revision: 1, - status: 'succeeded', - page_count: 2, - warnings: [], - warnings_truncated: false, - inspection: { - success: true, - data: { pages: [page, { ...page, page: 2, image_data_url: 'data:image/png;base64,cGFnZTI=' }], omitted_pages: [] }, - }, - }, + data: { ...job, preview: { success: true, data: { ...page, image_data_url: 'data:image/png;base64,iVBORw0KGgo=' } } }, }) - const result = await pending - expect(result.content[0]).toEqual({ - type: 'image', - data: 'iVBORw0KGgo=', - mimeType: 'image/png', + expect(await pending).toEqual({ + content: [ + { type: 'image', data: 'iVBORw0KGgo=', mimeType: 'image/png' }, + { type: 'text', text: JSON.stringify({ success: true, data: { ...job, preview: { success: true, data: page } } }) }, + ], }) - expect(result.content[1]).toEqual({ type: 'image', data: 'cGFnZTI=', mimeType: 'image/png' }) - const text = result.content[2] - if (text.type !== 'text') throw new Error('Expected inspection metadata') - const metadata = JSON.parse(text.text) - expect(metadata.data.inspection.data.pages).toEqual([1, 2].map((page) => ({ - page, build_session_id: 'session', revision: 1, editor_state_version: 3, - image_width: 10, image_height: 12, badges: {}, - }))) - expect(metadata.data.published_revision).toBe(1) - expect(text.text).not.toContain('image_data_url') }) it('keeps the text envelope for a failed annotated page render', async () => { From 694a09b22e0ff54f99d6b40acdab945eba03aa86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20Andr=C3=A9-Micolon?= Date: Mon, 23 Nov 2026 08:31:53 +0000 Subject: [PATCH 04/12] fix: sync inspection conflict with editor error catalog --- embed/embed-api.json | 21 ++++++++++----------- embed/etc/index.api.md | 2 +- embed/etc/protocol.api.md | 2 +- embed/src/generated/contract.ts | 4 ++-- 4 files changed, 14 insertions(+), 15 deletions(-) diff --git a/embed/embed-api.json b/embed/embed-api.json index b192f54f..5adcec01 100644 --- a/embed/embed-api.json +++ b/embed/embed-api.json @@ -412,11 +412,6 @@ "const": "resource:session_limit", "description": "Session job limit reached. Open an empty editor." }, - { - "type": "string", - "const": "conflict:inspection_state_changed", - "description": "The editor changed during inspection. Inspect again." - }, { "type": "string", "const": "bad_request:download_blocked", @@ -512,6 +507,11 @@ "const": "bad_request:signup_required", "description": "This operation requires the end user to sign up or authenticate first at https://simplepdf.com/auth/signup." }, + { + "type": "string", + "const": "conflict:inspection_state_changed", + "description": "The expected job is not displayed or the editor changed during inspection." + }, { "type": "string", "const": "forbidden:editing_not_allowed", @@ -671,7 +671,6 @@ "not_found:job", "not_found:job_expired", "resource:session_limit", - "conflict:inspection_state_changed", "bad_request:invalid_value", "forbidden:editing_not_allowed" ], @@ -2081,11 +2080,6 @@ "const": "resource:session_limit", "description": "Session job limit reached. Open an empty editor." }, - { - "type": "string", - "const": "conflict:inspection_state_changed", - "description": "The editor changed during inspection. Inspect again." - }, { "type": "string", "const": "bad_request:download_blocked", @@ -2181,6 +2175,11 @@ "const": "bad_request:signup_required", "description": "This operation requires the end user to sign up or authenticate first at https://simplepdf.com/auth/signup." }, + { + "type": "string", + "const": "conflict:inspection_state_changed", + "description": "The expected job is not displayed or the editor changed during inspection." + }, { "type": "string", "const": "forbidden:editing_not_allowed", diff --git a/embed/etc/index.api.md b/embed/etc/index.api.md index c6c1214c..3cbf2227 100644 --- a/embed/etc/index.api.md +++ b/embed/etc/index.api.md @@ -137,7 +137,7 @@ export type BuildPdfOutput = { unfilledRequiredFieldsCount: number; }; } | { - code: "conflict:idempotency_key_reused" | "conflict:editor_modified" | "conflict:unmanaged_document" | "not_found:job" | "not_found:job_expired" | "resource:session_limit" | "conflict:inspection_state_changed" | "bad_request:download_blocked" | "bad_request:editor_not_ready" | "bad_request:event_not_allowed" | "bad_request:failed_to_load_document" | "bad_request:field_not_found" | "bad_request:invalid_dimensions" | "bad_request:invalid_event_type" | "bad_request:invalid_field_ids" | "bad_request:invalid_field_type" | "bad_request:invalid_page" | "bad_request:invalid_signature_url" | "bad_request:invalid_tool" | "bad_request:invalid_value" | "bad_request:no_document_loaded" | "bad_request:page_not_found" | "bad_request:page_out_of_range" | "bad_request:plan_upgrade_required" | "bad_request:read_only" | "bad_request:signup_required" | "forbidden:editing_not_allowed" | "forbidden:origin_not_whitelisted" | "forbidden:whitelist_required" | "unexpected:internal_error"; + code: "conflict:idempotency_key_reused" | "conflict:editor_modified" | "conflict:unmanaged_document" | "not_found:job" | "not_found:job_expired" | "resource:session_limit" | "bad_request:download_blocked" | "bad_request:editor_not_ready" | "bad_request:event_not_allowed" | "bad_request:failed_to_load_document" | "bad_request:field_not_found" | "bad_request:invalid_dimensions" | "bad_request:invalid_event_type" | "bad_request:invalid_field_ids" | "bad_request:invalid_field_type" | "bad_request:invalid_page" | "bad_request:invalid_signature_url" | "bad_request:invalid_tool" | "bad_request:invalid_value" | "bad_request:no_document_loaded" | "bad_request:page_not_found" | "bad_request:page_out_of_range" | "bad_request:plan_upgrade_required" | "bad_request:read_only" | "bad_request:signup_required" | "conflict:inspection_state_changed" | "forbidden:editing_not_allowed" | "forbidden:origin_not_whitelisted" | "forbidden:whitelist_required" | "unexpected:internal_error"; message: string; }; }; diff --git a/embed/etc/protocol.api.md b/embed/etc/protocol.api.md index da9d2345..31e6468e 100644 --- a/embed/etc/protocol.api.md +++ b/embed/etc/protocol.api.md @@ -31,7 +31,7 @@ export const OPERATIONS: readonly [{ readonly wire_type: "BUILD_PDF"; readonly method: "buildPdf"; readonly description: "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing."; - readonly error_codes: readonly ["conflict:idempotency_key_reused", "conflict:editor_modified", "conflict:unmanaged_document", "not_found:job", "not_found:job_expired", "resource:session_limit", "conflict:inspection_state_changed", "bad_request:invalid_value", "forbidden:editing_not_allowed"]; + readonly error_codes: readonly ["conflict:idempotency_key_reused", "conflict:editor_modified", "conflict:unmanaged_document", "not_found:job", "not_found:job_expired", "resource:session_limit", "bad_request:invalid_value", "forbidden:editing_not_allowed"]; readonly is_agentic_tool: true; readonly has_output: true; }, { diff --git a/embed/src/generated/contract.ts b/embed/src/generated/contract.ts index a65c0fea..712a650f 100644 --- a/embed/src/generated/contract.ts +++ b/embed/src/generated/contract.ts @@ -18,7 +18,7 @@ export const EXTRACTION_MODES = ["auto", "ocr"] as const export type ExtractionMode = (typeof EXTRACTION_MODES)[number] export type BuildPdfInput = { action: "build"; code: string; idempotencyKey: string; name?: string; assets?: Array<{ path: string; dataUrl: string }> } | { action: "status"; jobId: string } | { action: "cancel"; jobId: string } -export type BuildPdfOutput = { jobId: string; status: "queued" } | { jobId: string; status: "running" } | { jobId: string; status: "succeeded"; pageCount: number; warnings: Array<{ severity: "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number; hint?: string }>; preview: { success: true; data: { jobId: string | null; page: number; imageDataUrl: string; imageWidth: number; imageHeight: number; badges: Record } } | { success: false; error: { code: "bad_request:batch_validation_failed"; message: string; details: { failures: Array<{ fieldId: string; code: "bad_request:field_not_found" | "bad_request:invalid_signature_url" | "bad_request:invalid_value" | "bad_request:read_only"; message: string }> } } | { code: "bad_request:missing_required_fields"; message: string; details: { unfilledRequiredFieldsCount: number } } | { code: "conflict:idempotency_key_reused" | "conflict:editor_modified" | "conflict:unmanaged_document" | "not_found:job" | "not_found:job_expired" | "resource:session_limit" | "conflict:inspection_state_changed" | "bad_request:download_blocked" | "bad_request:editor_not_ready" | "bad_request:event_not_allowed" | "bad_request:failed_to_load_document" | "bad_request:field_not_found" | "bad_request:invalid_dimensions" | "bad_request:invalid_event_type" | "bad_request:invalid_field_ids" | "bad_request:invalid_field_type" | "bad_request:invalid_page" | "bad_request:invalid_signature_url" | "bad_request:invalid_tool" | "bad_request:invalid_value" | "bad_request:no_document_loaded" | "bad_request:page_not_found" | "bad_request:page_out_of_range" | "bad_request:plan_upgrade_required" | "bad_request:read_only" | "bad_request:signup_required" | "forbidden:editing_not_allowed" | "forbidden:origin_not_whitelisted" | "forbidden:whitelist_required" | "unexpected:internal_error"; message: string } } } | { jobId: string; status: "failed"; error: { code: "unsupported_dependency" | "engine_initialization_failed" | "compile_error" | "compile_timeout" | "job_timeout" | "resource_limit" | "invalid_pdf" | "editor_load_failed" | "editor_conflict" | "worker_crashed" | "internal_error"; message: string; retryable: boolean; diagnostics: Array<{ severity: "error" | "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number; hint?: string }> } } | { jobId: string; status: "cancelled" } | { jobId: string; status: "superseded" } +export type BuildPdfOutput = { jobId: string; status: "queued" } | { jobId: string; status: "running" } | { jobId: string; status: "succeeded"; pageCount: number; warnings: Array<{ severity: "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number; hint?: string }>; preview: { success: true; data: { jobId: string | null; page: number; imageDataUrl: string; imageWidth: number; imageHeight: number; badges: Record } } | { success: false; error: { code: "bad_request:batch_validation_failed"; message: string; details: { failures: Array<{ fieldId: string; code: "bad_request:field_not_found" | "bad_request:invalid_signature_url" | "bad_request:invalid_value" | "bad_request:read_only"; message: string }> } } | { code: "bad_request:missing_required_fields"; message: string; details: { unfilledRequiredFieldsCount: number } } | { code: "conflict:idempotency_key_reused" | "conflict:editor_modified" | "conflict:unmanaged_document" | "not_found:job" | "not_found:job_expired" | "resource:session_limit" | "bad_request:download_blocked" | "bad_request:editor_not_ready" | "bad_request:event_not_allowed" | "bad_request:failed_to_load_document" | "bad_request:field_not_found" | "bad_request:invalid_dimensions" | "bad_request:invalid_event_type" | "bad_request:invalid_field_ids" | "bad_request:invalid_field_type" | "bad_request:invalid_page" | "bad_request:invalid_signature_url" | "bad_request:invalid_tool" | "bad_request:invalid_value" | "bad_request:no_document_loaded" | "bad_request:page_not_found" | "bad_request:page_out_of_range" | "bad_request:plan_upgrade_required" | "bad_request:read_only" | "bad_request:signup_required" | "conflict:inspection_state_changed" | "forbidden:editing_not_allowed" | "forbidden:origin_not_whitelisted" | "forbidden:whitelist_required" | "unexpected:internal_error"; message: string } } } | { jobId: string; status: "failed"; error: { code: "unsupported_dependency" | "engine_initialization_failed" | "compile_error" | "compile_timeout" | "job_timeout" | "resource_limit" | "invalid_pdf" | "editor_load_failed" | "editor_conflict" | "worker_crashed" | "internal_error"; message: string; retryable: boolean; diagnostics: Array<{ severity: "error" | "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number; hint?: string }> } } | { jobId: string; status: "cancelled" } | { jobId: string; status: "superseded" } export type GetDocumentationInput = { topic?: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.troubleshooting" | "fields" | "inspection" } export type GetDocumentationOutput = { kind: "index"; topics: Array<{ topic: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.troubleshooting" | "fields" | "inspection"; description: string }> } | { kind: "topic"; markdown: string } export type BatchSetFieldValuesInput = { updates: Array<{ fieldId: string; value: string | null }> } @@ -77,7 +77,7 @@ export const OPERATIONS = [ wire_type: "BUILD_PDF", method: "buildPdf", description: "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing.", - error_codes: ["conflict:idempotency_key_reused", "conflict:editor_modified", "conflict:unmanaged_document", "not_found:job", "not_found:job_expired", "resource:session_limit", "conflict:inspection_state_changed", "bad_request:invalid_value", "forbidden:editing_not_allowed"] as const, + error_codes: ["conflict:idempotency_key_reused", "conflict:editor_modified", "conflict:unmanaged_document", "not_found:job", "not_found:job_expired", "resource:session_limit", "bad_request:invalid_value", "forbidden:editing_not_allowed"] as const, is_agentic_tool: true, has_output: true, } /* BuildPdf */, From a9d7f70b3fde67965d991276fa5b25f3c9d9aa81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20Andr=C3=A9-Micolon?= Date: Mon, 23 Nov 2026 08:38:03 +0000 Subject: [PATCH 05/12] fix: expose reachable build states and diagnostic fields --- embed/README.md | 2 +- embed/embed-api.json | 20 -------------------- embed/etc/index.api.md | 5 ----- embed/src/generated/contract.ts | 2 +- 4 files changed, 2 insertions(+), 27 deletions(-) diff --git a/embed/README.md b/embed/README.md index c3dbae58..999bafc7 100644 --- a/embed/README.md +++ b/embed/README.md @@ -188,7 +188,7 @@ await embed.actions.download() Full set: `buildPdf`, `getDocumentation`, `batchSetFieldValues`, `createField`, `deleteFields`, `deletePages`, `detectFields`, `download`, `focusField`, `getAnnotatedPage`, `getDocumentContent`, `getFields`, `goTo`, `loadDocument`, `movePage`, `rotatePage`, `selectTool`, `setFieldValue`, `submit`. -Start a build in an empty editor. If the job is still `queued` or `running` after five seconds, call `buildPdf({ action: 'status', jobId })` until it finishes. A failed build reports diagnostics in `error`. A successful build opens the PDF and returns its page count, warnings and a first-page `preview`. Check `preview.success` before reading `preview.data.imageDataUrl`. To view another page of the same build, call `getAnnotatedPage({ page: 2, expectedJobId: jobId })`. Manual edits protect the document from replacement by a subsequent build. +Start a build in an empty editor. If the job is still `running` after five seconds, call `buildPdf({ action: 'status', jobId })` until it finishes. A failed build reports diagnostics in `error`. A successful build opens the PDF and returns its page count, warnings and a first-page `preview`. Check `preview.success` before reading `preview.data.imageDataUrl`. To view another page of the same build, call `getAnnotatedPage({ page: 2, expectedJobId: jobId })`. Manual edits protect the document from replacement by a subsequent build. Call `getDocumentation()` for the topic index, then `getDocumentation({ topic })` to read a topic. diff --git a/embed/embed-api.json b/embed/embed-api.json index 5adcec01..f345e8aa 100644 --- a/embed/embed-api.json +++ b/embed/embed-api.json @@ -149,20 +149,6 @@ }, "output_schema": { "anyOf": [ - { - "type": "object", - "properties": { - "job_id": { - "type": "string" - }, - "status": { - "type": "string", - "const": "queued" - } - }, - "required": ["job_id", "status"], - "additionalProperties": false - }, { "type": "object", "properties": { @@ -214,9 +200,6 @@ }, "column": { "type": "integer" - }, - "hint": { - "type": "string" } }, "required": ["severity", "code", "message"], @@ -617,9 +600,6 @@ }, "column": { "type": "integer" - }, - "hint": { - "type": "string" } }, "required": ["severity", "code", "message"], diff --git a/embed/etc/index.api.md b/embed/etc/index.api.md index 3cbf2227..a4e52701 100644 --- a/embed/etc/index.api.md +++ b/embed/etc/index.api.md @@ -90,9 +90,6 @@ export type BuildPdfInput = { // @public (undocumented) export type BuildPdfOutput = { - jobId: string; - status: "queued"; -} | { jobId: string; status: "running"; } | { @@ -106,7 +103,6 @@ export type BuildPdfOutput = { file?: string; line?: number; column?: number; - hint?: string; }>; preview: { success: true; @@ -155,7 +151,6 @@ export type BuildPdfOutput = { file?: string; line?: number; column?: number; - hint?: string; }>; }; } | { diff --git a/embed/src/generated/contract.ts b/embed/src/generated/contract.ts index 712a650f..e1e85925 100644 --- a/embed/src/generated/contract.ts +++ b/embed/src/generated/contract.ts @@ -18,7 +18,7 @@ export const EXTRACTION_MODES = ["auto", "ocr"] as const export type ExtractionMode = (typeof EXTRACTION_MODES)[number] export type BuildPdfInput = { action: "build"; code: string; idempotencyKey: string; name?: string; assets?: Array<{ path: string; dataUrl: string }> } | { action: "status"; jobId: string } | { action: "cancel"; jobId: string } -export type BuildPdfOutput = { jobId: string; status: "queued" } | { jobId: string; status: "running" } | { jobId: string; status: "succeeded"; pageCount: number; warnings: Array<{ severity: "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number; hint?: string }>; preview: { success: true; data: { jobId: string | null; page: number; imageDataUrl: string; imageWidth: number; imageHeight: number; badges: Record } } | { success: false; error: { code: "bad_request:batch_validation_failed"; message: string; details: { failures: Array<{ fieldId: string; code: "bad_request:field_not_found" | "bad_request:invalid_signature_url" | "bad_request:invalid_value" | "bad_request:read_only"; message: string }> } } | { code: "bad_request:missing_required_fields"; message: string; details: { unfilledRequiredFieldsCount: number } } | { code: "conflict:idempotency_key_reused" | "conflict:editor_modified" | "conflict:unmanaged_document" | "not_found:job" | "not_found:job_expired" | "resource:session_limit" | "bad_request:download_blocked" | "bad_request:editor_not_ready" | "bad_request:event_not_allowed" | "bad_request:failed_to_load_document" | "bad_request:field_not_found" | "bad_request:invalid_dimensions" | "bad_request:invalid_event_type" | "bad_request:invalid_field_ids" | "bad_request:invalid_field_type" | "bad_request:invalid_page" | "bad_request:invalid_signature_url" | "bad_request:invalid_tool" | "bad_request:invalid_value" | "bad_request:no_document_loaded" | "bad_request:page_not_found" | "bad_request:page_out_of_range" | "bad_request:plan_upgrade_required" | "bad_request:read_only" | "bad_request:signup_required" | "conflict:inspection_state_changed" | "forbidden:editing_not_allowed" | "forbidden:origin_not_whitelisted" | "forbidden:whitelist_required" | "unexpected:internal_error"; message: string } } } | { jobId: string; status: "failed"; error: { code: "unsupported_dependency" | "engine_initialization_failed" | "compile_error" | "compile_timeout" | "job_timeout" | "resource_limit" | "invalid_pdf" | "editor_load_failed" | "editor_conflict" | "worker_crashed" | "internal_error"; message: string; retryable: boolean; diagnostics: Array<{ severity: "error" | "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number; hint?: string }> } } | { jobId: string; status: "cancelled" } | { jobId: string; status: "superseded" } +export type BuildPdfOutput = { jobId: string; status: "running" } | { jobId: string; status: "succeeded"; pageCount: number; warnings: Array<{ severity: "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number }>; preview: { success: true; data: { jobId: string | null; page: number; imageDataUrl: string; imageWidth: number; imageHeight: number; badges: Record } } | { success: false; error: { code: "bad_request:batch_validation_failed"; message: string; details: { failures: Array<{ fieldId: string; code: "bad_request:field_not_found" | "bad_request:invalid_signature_url" | "bad_request:invalid_value" | "bad_request:read_only"; message: string }> } } | { code: "bad_request:missing_required_fields"; message: string; details: { unfilledRequiredFieldsCount: number } } | { code: "conflict:idempotency_key_reused" | "conflict:editor_modified" | "conflict:unmanaged_document" | "not_found:job" | "not_found:job_expired" | "resource:session_limit" | "bad_request:download_blocked" | "bad_request:editor_not_ready" | "bad_request:event_not_allowed" | "bad_request:failed_to_load_document" | "bad_request:field_not_found" | "bad_request:invalid_dimensions" | "bad_request:invalid_event_type" | "bad_request:invalid_field_ids" | "bad_request:invalid_field_type" | "bad_request:invalid_page" | "bad_request:invalid_signature_url" | "bad_request:invalid_tool" | "bad_request:invalid_value" | "bad_request:no_document_loaded" | "bad_request:page_not_found" | "bad_request:page_out_of_range" | "bad_request:plan_upgrade_required" | "bad_request:read_only" | "bad_request:signup_required" | "conflict:inspection_state_changed" | "forbidden:editing_not_allowed" | "forbidden:origin_not_whitelisted" | "forbidden:whitelist_required" | "unexpected:internal_error"; message: string } } } | { jobId: string; status: "failed"; error: { code: "unsupported_dependency" | "engine_initialization_failed" | "compile_error" | "compile_timeout" | "job_timeout" | "resource_limit" | "invalid_pdf" | "editor_load_failed" | "editor_conflict" | "worker_crashed" | "internal_error"; message: string; retryable: boolean; diagnostics: Array<{ severity: "error" | "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number }> } } | { jobId: string; status: "cancelled" } | { jobId: string; status: "superseded" } export type GetDocumentationInput = { topic?: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.troubleshooting" | "fields" | "inspection" } export type GetDocumentationOutput = { kind: "index"; topics: Array<{ topic: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.troubleshooting" | "fields" | "inspection"; description: string }> } | { kind: "topic"; markdown: string } export type BatchSetFieldValuesInput = { updates: Array<{ fieldId: string; value: string | null }> } From 809ae21c01c20690113000e302a97a22d38757fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20Andr=C3=A9-Micolon?= Date: Mon, 23 Nov 2026 08:45:08 +0000 Subject: [PATCH 06/12] fix: narrow build preview errors to the page inspection contract --- embed/embed-api.json | 305 +++++++------------------------- embed/etc/index.api.md | 18 +- embed/src/generated/contract.ts | 2 +- 3 files changed, 65 insertions(+), 260 deletions(-) diff --git a/embed/embed-api.json b/embed/embed-api.json index f345e8aa..66d226ce 100644 --- a/embed/embed-api.json +++ b/embed/embed-api.json @@ -273,257 +273,78 @@ "const": false }, "error": { - "anyOf": [ - { - "type": "object", - "properties": { - "code": { + "type": "object", + "properties": { + "code": { + "anyOf": [ + { "type": "string", - "const": "bad_request:batch_validation_failed", - "description": "At least one update of batch_set_field_values was rejected, so no field changed. details.failures lists every rejected update with its field_id and the set_field_value code and message explaining why." + "const": "bad_request:no_document_loaded", + "description": "No document is loaded. Load a document before calling this operation." }, - "message": { - "type": "string" + { + "type": "string", + "const": "bad_request:invalid_page", + "description": "page is missing or is not a positive integer." }, - "details": { - "type": "object", - "properties": { - "failures": { - "type": "array", - "items": { - "type": "object", - "properties": { - "field_id": { - "type": "string" - }, - "code": { - "anyOf": [ - { - "type": "string", - "const": "bad_request:field_not_found", - "description": "No field on the loaded document matches the provided field_id." - }, - { - "type": "string", - "const": "bad_request:invalid_signature_url", - "description": "The signature value is not a valid, reachable image URL." - }, - { - "type": "string", - "const": "bad_request:invalid_value", - "description": "The provided value is missing or not valid for this operation or field type." - }, - { - "type": "string", - "const": "bad_request:read_only", - "description": "The document or field is read-only and cannot be modified." - } - ] - }, - "message": { - "type": "string" - } - }, - "required": [ - "field_id", - "code", - "message" - ] - } - } - }, - "required": ["failures"] - } - }, - "required": ["code", "message", "details"] - }, - { - "type": "object", - "properties": { - "code": { + { "type": "string", - "const": "bad_request:missing_required_fields", - "description": "Submission was blocked because required fields are unfilled. details.unfilled_required_fields_count reports how many remain." + "const": "bad_request:page_out_of_range", + "description": "page is outside the document range (1 to the document page_count)." }, - "message": { - "type": "string" + { + "type": "string", + "const": "bad_request:invalid_value", + "description": "The provided value is missing or not valid for this operation or field type." }, - "details": { - "type": "object", - "properties": { - "unfilled_required_fields_count": { - "type": "integer" - } - }, - "required": ["unfilled_required_fields_count"] - } - }, - "required": ["code", "message", "details"] - }, - { - "type": "object", - "properties": { - "code": { - "anyOf": [ - { - "type": "string", - "const": "conflict:idempotency_key_reused", - "description": "Different input for this key. Use a new key." - }, - { - "type": "string", - "const": "conflict:editor_modified", - "description": "Edits block rebuilding. Start a new session in an empty editor." - }, - { - "type": "string", - "const": "conflict:unmanaged_document", - "description": "Open an empty editor before building." - }, - { - "type": "string", - "const": "not_found:job", - "description": "Unknown job in this editor session." - }, - { - "type": "string", - "const": "not_found:job_expired", - "description": "Job expired. Its key cannot be reused." - }, - { - "type": "string", - "const": "resource:session_limit", - "description": "Session job limit reached. Open an empty editor." - }, - { - "type": "string", - "const": "bad_request:download_blocked", - "description": "The browser blocked delivering the generated document (share sheet or new tab denied without a user gesture, or a popup blocker). Retry the download from a direct user interaction." - }, - { - "type": "string", - "const": "bad_request:editor_not_ready", - "description": "The editor is still initializing and cannot accept this operation yet. Retry the operation shortly." - }, - { - "type": "string", - "const": "bad_request:event_not_allowed", - "description": "This operation is not available in this context (the portal configuration or this page does not offer it); the message says why." - }, - { - "type": "string", - "const": "bad_request:failed_to_load_document", - "description": "The document LOAD_DOCUMENT was given could not be loaded (unreachable, not a PDF or image, corrupted, password-protected, superseded by another load, or the editor could not prepare it: the server never resolved it, storing it failed, or it carries more form fields than a document can); the message says which." - }, - { - "type": "string", - "const": "bad_request:field_not_found", - "description": "No field on the loaded document matches the provided field_id." - }, - { - "type": "string", - "const": "bad_request:invalid_dimensions", - "description": "The provided x, y, width, or height is missing or not a valid number." - }, - { - "type": "string", - "const": "bad_request:invalid_event_type", - "description": "The posted message `type` is not a supported operation request_type." - }, - { - "type": "string", - "const": "bad_request:invalid_field_ids", - "description": "field_ids is missing or is not an array of field id strings." - }, - { - "type": "string", - "const": "bad_request:invalid_field_type", - "description": "The provided field type is not one of the supported overlay tool types." - }, - { - "type": "string", - "const": "bad_request:invalid_page", - "description": "page is missing or is not a positive integer." - }, - { - "type": "string", - "const": "bad_request:invalid_signature_url", - "description": "The signature value is not a valid, reachable image URL." - }, - { - "type": "string", - "const": "bad_request:invalid_tool", - "description": "The provided tool is not one of the selectable tools." - }, - { - "type": "string", - "const": "bad_request:invalid_value", - "description": "The provided value is missing or not valid for this operation or field type." - }, - { - "type": "string", - "const": "bad_request:no_document_loaded", - "description": "No document is loaded. Load a document before calling this operation." - }, - { - "type": "string", - "const": "bad_request:page_not_found", - "description": "The referenced page does not exist in the document." - }, - { - "type": "string", - "const": "bad_request:page_out_of_range", - "description": "page is outside the document range (1 to the document page_count)." - }, - { - "type": "string", - "const": "bad_request:plan_upgrade_required", - "description": "The tenant's plan does not include this operation. Upgrade the plan in the SimplePDF admin dashboard." - }, - { - "type": "string", - "const": "bad_request:read_only", - "description": "The document or field is read-only and cannot be modified." - }, - { - "type": "string", - "const": "bad_request:signup_required", - "description": "This operation requires the end user to sign up or authenticate first at https://simplepdf.com/auth/signup." - }, - { - "type": "string", - "const": "conflict:inspection_state_changed", - "description": "The expected job is not displayed or the editor changed during inspection." - }, - { - "type": "string", - "const": "forbidden:editing_not_allowed", - "description": "Editing is disabled for this document or configuration; field-mutating operations are rejected." - }, - { - "type": "string", - "const": "forbidden:origin_not_whitelisted", - "description": "The embedding origin is not allowlisted for this tenant, or is not the allowlisted origin the editor was loaded from. Allowlist it in the SimplePDF admin dashboard and let the embedding page's Referer reach the editor." - }, - { - "type": "string", - "const": "forbidden:whitelist_required", - "description": "This tenant requires the embedding origin to be allowlisted before any operation is accepted. Configure it in the admin dashboard." - }, - { - "type": "string", - "const": "unexpected:internal_error", - "description": "An unexpected internal error occurred. Try again, and if the issue persists, reach out to support@simplepdf.com." - } - ] + { + "type": "string", + "const": "conflict:inspection_state_changed", + "description": "The expected job is not displayed or the editor changed during inspection." }, - "message": { - "type": "string" + { + "type": "string", + "const": "bad_request:editor_not_ready", + "description": "The editor is still initializing and cannot accept this operation yet. Retry the operation shortly." + }, + { + "type": "string", + "const": "bad_request:event_not_allowed", + "description": "This operation is not available in this context (the portal configuration or this page does not offer it); the message says why." + }, + { + "type": "string", + "const": "bad_request:plan_upgrade_required", + "description": "The tenant's plan does not include this operation. Upgrade the plan in the SimplePDF admin dashboard." + }, + { + "type": "string", + "const": "bad_request:signup_required", + "description": "This operation requires the end user to sign up or authenticate first at https://simplepdf.com/auth/signup." + }, + { + "type": "string", + "const": "forbidden:origin_not_whitelisted", + "description": "The embedding origin is not allowlisted for this tenant, or is not the allowlisted origin the editor was loaded from. Allowlist it in the SimplePDF admin dashboard and let the embedding page's Referer reach the editor." + }, + { + "type": "string", + "const": "forbidden:whitelist_required", + "description": "This tenant requires the embedding origin to be allowlisted before any operation is accepted. Configure it in the admin dashboard." + }, + { + "type": "string", + "const": "unexpected:internal_error", + "description": "An unexpected internal error occurred. Try again, and if the issue persists, reach out to support@simplepdf.com." } - }, - "required": ["code", "message"] + ] + }, + "message": { + "type": "string" } - ] + }, + "required": ["code", "message"], + "additionalProperties": false } }, "required": ["success", "error"], diff --git a/embed/etc/index.api.md b/embed/etc/index.api.md index a4e52701..40edf4a2 100644 --- a/embed/etc/index.api.md +++ b/embed/etc/index.api.md @@ -117,23 +117,7 @@ export type BuildPdfOutput = { } | { success: false; error: { - code: "bad_request:batch_validation_failed"; - message: string; - details: { - failures: Array<{ - fieldId: string; - code: "bad_request:field_not_found" | "bad_request:invalid_signature_url" | "bad_request:invalid_value" | "bad_request:read_only"; - message: string; - }>; - }; - } | { - code: "bad_request:missing_required_fields"; - message: string; - details: { - unfilledRequiredFieldsCount: number; - }; - } | { - code: "conflict:idempotency_key_reused" | "conflict:editor_modified" | "conflict:unmanaged_document" | "not_found:job" | "not_found:job_expired" | "resource:session_limit" | "bad_request:download_blocked" | "bad_request:editor_not_ready" | "bad_request:event_not_allowed" | "bad_request:failed_to_load_document" | "bad_request:field_not_found" | "bad_request:invalid_dimensions" | "bad_request:invalid_event_type" | "bad_request:invalid_field_ids" | "bad_request:invalid_field_type" | "bad_request:invalid_page" | "bad_request:invalid_signature_url" | "bad_request:invalid_tool" | "bad_request:invalid_value" | "bad_request:no_document_loaded" | "bad_request:page_not_found" | "bad_request:page_out_of_range" | "bad_request:plan_upgrade_required" | "bad_request:read_only" | "bad_request:signup_required" | "conflict:inspection_state_changed" | "forbidden:editing_not_allowed" | "forbidden:origin_not_whitelisted" | "forbidden:whitelist_required" | "unexpected:internal_error"; + code: "bad_request:no_document_loaded" | "bad_request:invalid_page" | "bad_request:page_out_of_range" | "bad_request:invalid_value" | "conflict:inspection_state_changed" | "bad_request:editor_not_ready" | "bad_request:event_not_allowed" | "bad_request:plan_upgrade_required" | "bad_request:signup_required" | "forbidden:origin_not_whitelisted" | "forbidden:whitelist_required" | "unexpected:internal_error"; message: string; }; }; diff --git a/embed/src/generated/contract.ts b/embed/src/generated/contract.ts index e1e85925..36a182f2 100644 --- a/embed/src/generated/contract.ts +++ b/embed/src/generated/contract.ts @@ -18,7 +18,7 @@ export const EXTRACTION_MODES = ["auto", "ocr"] as const export type ExtractionMode = (typeof EXTRACTION_MODES)[number] export type BuildPdfInput = { action: "build"; code: string; idempotencyKey: string; name?: string; assets?: Array<{ path: string; dataUrl: string }> } | { action: "status"; jobId: string } | { action: "cancel"; jobId: string } -export type BuildPdfOutput = { jobId: string; status: "running" } | { jobId: string; status: "succeeded"; pageCount: number; warnings: Array<{ severity: "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number }>; preview: { success: true; data: { jobId: string | null; page: number; imageDataUrl: string; imageWidth: number; imageHeight: number; badges: Record } } | { success: false; error: { code: "bad_request:batch_validation_failed"; message: string; details: { failures: Array<{ fieldId: string; code: "bad_request:field_not_found" | "bad_request:invalid_signature_url" | "bad_request:invalid_value" | "bad_request:read_only"; message: string }> } } | { code: "bad_request:missing_required_fields"; message: string; details: { unfilledRequiredFieldsCount: number } } | { code: "conflict:idempotency_key_reused" | "conflict:editor_modified" | "conflict:unmanaged_document" | "not_found:job" | "not_found:job_expired" | "resource:session_limit" | "bad_request:download_blocked" | "bad_request:editor_not_ready" | "bad_request:event_not_allowed" | "bad_request:failed_to_load_document" | "bad_request:field_not_found" | "bad_request:invalid_dimensions" | "bad_request:invalid_event_type" | "bad_request:invalid_field_ids" | "bad_request:invalid_field_type" | "bad_request:invalid_page" | "bad_request:invalid_signature_url" | "bad_request:invalid_tool" | "bad_request:invalid_value" | "bad_request:no_document_loaded" | "bad_request:page_not_found" | "bad_request:page_out_of_range" | "bad_request:plan_upgrade_required" | "bad_request:read_only" | "bad_request:signup_required" | "conflict:inspection_state_changed" | "forbidden:editing_not_allowed" | "forbidden:origin_not_whitelisted" | "forbidden:whitelist_required" | "unexpected:internal_error"; message: string } } } | { jobId: string; status: "failed"; error: { code: "unsupported_dependency" | "engine_initialization_failed" | "compile_error" | "compile_timeout" | "job_timeout" | "resource_limit" | "invalid_pdf" | "editor_load_failed" | "editor_conflict" | "worker_crashed" | "internal_error"; message: string; retryable: boolean; diagnostics: Array<{ severity: "error" | "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number }> } } | { jobId: string; status: "cancelled" } | { jobId: string; status: "superseded" } +export type BuildPdfOutput = { jobId: string; status: "running" } | { jobId: string; status: "succeeded"; pageCount: number; warnings: Array<{ severity: "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number }>; preview: { success: true; data: { jobId: string | null; page: number; imageDataUrl: string; imageWidth: number; imageHeight: number; badges: Record } } | { success: false; error: { code: "bad_request:no_document_loaded" | "bad_request:invalid_page" | "bad_request:page_out_of_range" | "bad_request:invalid_value" | "conflict:inspection_state_changed" | "bad_request:editor_not_ready" | "bad_request:event_not_allowed" | "bad_request:plan_upgrade_required" | "bad_request:signup_required" | "forbidden:origin_not_whitelisted" | "forbidden:whitelist_required" | "unexpected:internal_error"; message: string } } } | { jobId: string; status: "failed"; error: { code: "unsupported_dependency" | "engine_initialization_failed" | "compile_error" | "compile_timeout" | "job_timeout" | "resource_limit" | "invalid_pdf" | "editor_load_failed" | "editor_conflict" | "worker_crashed" | "internal_error"; message: string; retryable: boolean; diagnostics: Array<{ severity: "error" | "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number }> } } | { jobId: string; status: "cancelled" } | { jobId: string; status: "superseded" } export type GetDocumentationInput = { topic?: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.troubleshooting" | "fields" | "inspection" } export type GetDocumentationOutput = { kind: "index"; topics: Array<{ topic: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.troubleshooting" | "fields" | "inspection"; description: string }> } | { kind: "topic"; markdown: string } export type BatchSetFieldValuesInput = { updates: Array<{ fieldId: string; value: string | null }> } From c624e519d8f6bcb6a8ae08916995543ff35c7893 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20Andr=C3=A9-Micolon?= Date: Mon, 23 Nov 2026 22:45:20 +0000 Subject: [PATCH 07/12] refactor: restore page-only inspection contract --- .changeset/build-pdf-browser.md | 2 +- embed/README.md | 2 +- embed/embed-api.json | 52 +++++------------------------ embed/etc/index.api.md | 5 +-- embed/etc/protocol.api.md | 2 +- embed/etc/schemas.api.md | 3 +- embed/etc/tanstack-ai.api.md | 2 +- embed/etc/tools.api.md | 3 +- embed/src/generated/contract.ts | 8 ++--- embed/src/generated/schemas.ts | 3 +- embed/src/generated/webmcp-tools.ts | 2 +- embed/test/tools.test.ts | 13 ++------ 12 files changed, 24 insertions(+), 73 deletions(-) diff --git a/.changeset/build-pdf-browser.md b/.changeset/build-pdf-browser.md index f8d30377..1e10faaf 100644 --- a/.changeset/build-pdf-browser.md +++ b/.changeset/build-pdf-browser.md @@ -5,4 +5,4 @@ **Build and revise PDFs directly in the browser editor.** - Use typed JavaScript and React methods for PDF building and task documentation. -- View the first-page preview with the build result and inspect other pages by job ID. WebMCP returns each preview as a native image. +- View the first-page preview with the build result and inspect other open-document pages by page number. WebMCP returns each preview as a native image. diff --git a/embed/README.md b/embed/README.md index 999bafc7..2d9ac4e8 100644 --- a/embed/README.md +++ b/embed/README.md @@ -188,7 +188,7 @@ await embed.actions.download() Full set: `buildPdf`, `getDocumentation`, `batchSetFieldValues`, `createField`, `deleteFields`, `deletePages`, `detectFields`, `download`, `focusField`, `getAnnotatedPage`, `getDocumentContent`, `getFields`, `goTo`, `loadDocument`, `movePage`, `rotatePage`, `selectTool`, `setFieldValue`, `submit`. -Start a build in an empty editor. If the job is still `running` after five seconds, call `buildPdf({ action: 'status', jobId })` until it finishes. A failed build reports diagnostics in `error`. A successful build opens the PDF and returns its page count, warnings and a first-page `preview`. Check `preview.success` before reading `preview.data.imageDataUrl`. To view another page of the same build, call `getAnnotatedPage({ page: 2, expectedJobId: jobId })`. Manual edits protect the document from replacement by a subsequent build. +Start a build in an empty editor. If the job is still `running` after five seconds, call `buildPdf({ action: 'status', jobId })` until it finishes. A failed build reports diagnostics in `error`. A successful build opens the PDF and returns its page count, warnings and a first-page `preview`. Check `preview.success` before reading `preview.data.imageDataUrl`. To inspect another page of the currently open document, call `getAnnotatedPage({ page: 2 })`. Build preview identity is checked internally; page inspection has no build-specific parameters. Manual edits protect the document from replacement by a subsequent build. Call `getDocumentation()` for the topic index, then `getDocumentation({ topic })` to read a topic. diff --git a/embed/embed-api.json b/embed/embed-api.json index 66d226ce..fdc213e8 100644 --- a/embed/embed-api.json +++ b/embed/embed-api.json @@ -1,4 +1,5 @@ { + "editor_version": null, "description": "This is the SimplePDF editor interface contract. Drive the editor programmatically over window.postMessage with the editor iframe: post a JSON string { \"type\": {{operation request_type}}, \"request_id\": {{a request correlation id you generate}}, \"data\": {{input matching input_schema}} } to the iframe; the editor replies with { \"type\": \"REQUEST_RESULT\", \"data\": { \"request_id\": {{the same correlation id}}, \"result\": {{result}} } } (match each reply to its request by this id), where result is { \"success\": true, \"data\": {{a value matching the operation's output_schema; null for ops that return nothing}} } or { \"success\": false, \"error\": { code, message } }. Each operation lists the op-specific `error_codes` it can return; on top of those, any op may also fail with a gateway/permission code (origin/plan/signup gating, editor-not-ready, or an internal error). Every code is within `editor_error_schema` (the complete closed union to narrow against), where each code const carries a `description` of its meaning. Outbound events (see `events`) are pushed the same way. `operations` lists every operation the editor supports. Most require the embedding origin to be allowlisted (\"whitelisted\") for the tenant in the SimplePDF admin dashboard, and the tenant plan to permit them (LOAD_DOCUMENT is always available). A call the current setup does not permit returns the matching gateway code: forbidden:origin_not_whitelisted when the origin is not allowlisted, or bad_request:plan_upgrade_required when the plan excludes it. All JSON schemas use the json_schema_dialect declared at the root. We recommend the @simplepdf/embed package for a typed, ergonomic wrapper over this contract (https://github.com/SimplePDF/simplepdf-embed).", "json_schema_dialect": "https://json-schema.org/draft/2020-12/schema", "protocol": { @@ -218,16 +219,6 @@ "data": { "type": "object", "properties": { - "job_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] - }, "page": { "type": "integer", "description": "1-based page position this render shows." @@ -253,7 +244,6 @@ } }, "required": [ - "job_id", "page", "image_data_url", "image_width", @@ -292,16 +282,6 @@ "const": "bad_request:page_out_of_range", "description": "page is outside the document range (1 to the document page_count)." }, - { - "type": "string", - "const": "bad_request:invalid_value", - "description": "The provided value is missing or not valid for this operation or field type." - }, - { - "type": "string", - "const": "conflict:inspection_state_changed", - "description": "The expected job is not displayed or the editor changed during inspection." - }, { "type": "string", "const": "bad_request:editor_not_ready", @@ -332,6 +312,11 @@ "const": "forbidden:whitelist_required", "description": "This tenant requires the embedding origin to be allowlisted before any operation is accepted. Configure it in the admin dashboard." }, + { + "type": "string", + "const": "conflict:inspection_state_changed", + "description": "The build is no longer displayed or the editor changed during its automatic preview." + }, { "type": "string", "const": "unexpected:internal_error", @@ -1082,28 +1067,14 @@ "page": { "type": "integer", "description": "1-based page to render, at its current position." - }, - "expected_job_id": { - "type": "string" } }, "required": ["page"], - "additionalProperties": false, "description": "Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block." }, "output_schema": { "type": "object", "properties": { - "job_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] - }, "page": { "type": "integer", "description": "1-based page position this render shows." @@ -1129,7 +1100,6 @@ } }, "required": [ - "job_id", "page", "image_data_url", "image_width", @@ -1140,24 +1110,18 @@ "error_codes": [ "bad_request:no_document_loaded", "bad_request:invalid_page", - "bad_request:page_out_of_range", - "bad_request:invalid_value", - "conflict:inspection_state_changed" + "bad_request:page_out_of_range" ], "tool": { "name": "simplepdf_embed_get_annotated_page", "description": "Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block.", "input_schema": { "required": ["page"], - "additionalProperties": false, "type": "object", "properties": { "page": { "description": "1-based page to render, at its current position.", "type": "integer" - }, - "expected_job_id": { - "type": "string" } } }, @@ -1979,7 +1943,7 @@ { "type": "string", "const": "conflict:inspection_state_changed", - "description": "The expected job is not displayed or the editor changed during inspection." + "description": "The build is no longer displayed or the editor changed during its automatic preview." }, { "type": "string", diff --git a/embed/etc/index.api.md b/embed/etc/index.api.md index 40edf4a2..70ff5cb5 100644 --- a/embed/etc/index.api.md +++ b/embed/etc/index.api.md @@ -107,7 +107,6 @@ export type BuildPdfOutput = { preview: { success: true; data: { - jobId: string | null; page: number; imageDataUrl: string; imageWidth: number; @@ -117,7 +116,7 @@ export type BuildPdfOutput = { } | { success: false; error: { - code: "bad_request:no_document_loaded" | "bad_request:invalid_page" | "bad_request:page_out_of_range" | "bad_request:invalid_value" | "conflict:inspection_state_changed" | "bad_request:editor_not_ready" | "bad_request:event_not_allowed" | "bad_request:plan_upgrade_required" | "bad_request:signup_required" | "forbidden:origin_not_whitelisted" | "forbidden:whitelist_required" | "unexpected:internal_error"; + code: "bad_request:no_document_loaded" | "bad_request:invalid_page" | "bad_request:page_out_of_range" | "bad_request:editor_not_ready" | "bad_request:event_not_allowed" | "bad_request:plan_upgrade_required" | "bad_request:signup_required" | "forbidden:origin_not_whitelisted" | "forbidden:whitelist_required" | "conflict:inspection_state_changed" | "unexpected:internal_error"; message: string; }; }; @@ -311,12 +310,10 @@ export type FocusFieldOutput = { // @public (undocumented) export type GetAnnotatedPageInput = { page: number; - expectedJobId?: string; }; // @public (undocumented) export type GetAnnotatedPageOutput = { - jobId: string | null; page: number; imageDataUrl: string; imageWidth: number; diff --git a/embed/etc/protocol.api.md b/embed/etc/protocol.api.md index 31e6468e..4e5c58fb 100644 --- a/embed/etc/protocol.api.md +++ b/embed/etc/protocol.api.md @@ -103,7 +103,7 @@ export const OPERATIONS: readonly [{ readonly wire_type: "GET_ANNOTATED_PAGE"; readonly method: "getAnnotatedPage"; readonly description: "Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block."; - readonly error_codes: readonly ["bad_request:no_document_loaded", "bad_request:invalid_page", "bad_request:page_out_of_range", "bad_request:invalid_value", "conflict:inspection_state_changed"]; + readonly error_codes: readonly ["bad_request:no_document_loaded", "bad_request:invalid_page", "bad_request:page_out_of_range"]; readonly is_agentic_tool: true; readonly has_output: true; }, { diff --git a/embed/etc/schemas.api.md b/embed/etc/schemas.api.md index ae917e30..686fdae2 100644 --- a/embed/etc/schemas.api.md +++ b/embed/etc/schemas.api.md @@ -98,8 +98,7 @@ export type FocusFieldInput = z.infer; // @public (undocumented) export const GetAnnotatedPageInput: z.ZodObject<{ page: z.ZodNumber; - expectedJobId: z.ZodOptional; -}, z.core.$strict>; +}, z.core.$strip>; // @public (undocumented) export type GetAnnotatedPageInput = z.infer; diff --git a/embed/etc/tanstack-ai.api.md b/embed/etc/tanstack-ai.api.md index 3feeb870..050d721f 100644 --- a/embed/etc/tanstack-ai.api.md +++ b/embed/etc/tanstack-ai.api.md @@ -27,7 +27,7 @@ export type SimplePDFToolName = keyof typeof TOOL_DEFINITIONS; // Warnings were encountered during analysis: // -// dist/tanstack-ai.d.ts:88:5 - (ae-forgotten-export) The symbol "Embed" needs to be exported by the entry point tanstack-ai.d.ts +// dist/tanstack-ai.d.ts:87:5 - (ae-forgotten-export) The symbol "Embed" needs to be exported by the entry point tanstack-ai.d.ts // (No @packageDocumentation comment for this package) diff --git a/embed/etc/tools.api.md b/embed/etc/tools.api.md index 8412bc83..2c919fdf 100644 --- a/embed/etc/tools.api.md +++ b/embed/etc/tools.api.md @@ -104,8 +104,7 @@ export const SIMPLEPDF_TOOLS: { readonly description: "Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block."; readonly inputSchema: z.ZodObject<{ page: z.ZodNumber; - expectedJobId: z.ZodOptional; - }, z.core.$strict>; + }, z.core.$strip>; }; readonly getDocumentContent: { readonly description: "Extract the document's content page by page as Markdown, or as plain text when optical recognition is forced. Use it to read what the document says. Returns the document name and each page's content."; diff --git a/embed/src/generated/contract.ts b/embed/src/generated/contract.ts index 36a182f2..b6eb6d6e 100644 --- a/embed/src/generated/contract.ts +++ b/embed/src/generated/contract.ts @@ -18,7 +18,7 @@ export const EXTRACTION_MODES = ["auto", "ocr"] as const export type ExtractionMode = (typeof EXTRACTION_MODES)[number] export type BuildPdfInput = { action: "build"; code: string; idempotencyKey: string; name?: string; assets?: Array<{ path: string; dataUrl: string }> } | { action: "status"; jobId: string } | { action: "cancel"; jobId: string } -export type BuildPdfOutput = { jobId: string; status: "running" } | { jobId: string; status: "succeeded"; pageCount: number; warnings: Array<{ severity: "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number }>; preview: { success: true; data: { jobId: string | null; page: number; imageDataUrl: string; imageWidth: number; imageHeight: number; badges: Record } } | { success: false; error: { code: "bad_request:no_document_loaded" | "bad_request:invalid_page" | "bad_request:page_out_of_range" | "bad_request:invalid_value" | "conflict:inspection_state_changed" | "bad_request:editor_not_ready" | "bad_request:event_not_allowed" | "bad_request:plan_upgrade_required" | "bad_request:signup_required" | "forbidden:origin_not_whitelisted" | "forbidden:whitelist_required" | "unexpected:internal_error"; message: string } } } | { jobId: string; status: "failed"; error: { code: "unsupported_dependency" | "engine_initialization_failed" | "compile_error" | "compile_timeout" | "job_timeout" | "resource_limit" | "invalid_pdf" | "editor_load_failed" | "editor_conflict" | "worker_crashed" | "internal_error"; message: string; retryable: boolean; diagnostics: Array<{ severity: "error" | "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number }> } } | { jobId: string; status: "cancelled" } | { jobId: string; status: "superseded" } +export type BuildPdfOutput = { jobId: string; status: "running" } | { jobId: string; status: "succeeded"; pageCount: number; warnings: Array<{ severity: "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number }>; preview: { success: true; data: { page: number; imageDataUrl: string; imageWidth: number; imageHeight: number; badges: Record } } | { success: false; error: { code: "bad_request:no_document_loaded" | "bad_request:invalid_page" | "bad_request:page_out_of_range" | "bad_request:editor_not_ready" | "bad_request:event_not_allowed" | "bad_request:plan_upgrade_required" | "bad_request:signup_required" | "forbidden:origin_not_whitelisted" | "forbidden:whitelist_required" | "conflict:inspection_state_changed" | "unexpected:internal_error"; message: string } } } | { jobId: string; status: "failed"; error: { code: "unsupported_dependency" | "engine_initialization_failed" | "compile_error" | "compile_timeout" | "job_timeout" | "resource_limit" | "invalid_pdf" | "editor_load_failed" | "editor_conflict" | "worker_crashed" | "internal_error"; message: string; retryable: boolean; diagnostics: Array<{ severity: "error" | "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number }> } } | { jobId: string; status: "cancelled" } | { jobId: string; status: "superseded" } export type GetDocumentationInput = { topic?: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.troubleshooting" | "fields" | "inspection" } export type GetDocumentationOutput = { kind: "index"; topics: Array<{ topic: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.troubleshooting" | "fields" | "inspection"; description: string }> } | { kind: "topic"; markdown: string } export type BatchSetFieldValuesInput = { updates: Array<{ fieldId: string; value: string | null }> } @@ -35,8 +35,8 @@ export type DownloadInput = Record export type DownloadOutput = null export type FocusFieldInput = { fieldId: string } export type FocusFieldOutput = { hint: { type: "user_action_expected"; message: string } } -export type GetAnnotatedPageInput = { page: number; expectedJobId?: string } -export type GetAnnotatedPageOutput = { jobId: string | null; page: number; imageDataUrl: string; imageWidth: number; imageHeight: number; badges: Record } +export type GetAnnotatedPageInput = { page: number } +export type GetAnnotatedPageOutput = { page: number; imageDataUrl: string; imageWidth: number; imageHeight: number; badges: Record } export type GetDocumentContentInput = { extractionMode?: ExtractionMode } export type GetDocumentContentOutput = { name: string; pages: Array<{ page: number; content: string }> } export type GetFieldsInput = Record @@ -158,7 +158,7 @@ export const OPERATIONS = [ wire_type: "GET_ANNOTATED_PAGE", method: "getAnnotatedPage", description: "Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block.", - error_codes: ["bad_request:no_document_loaded", "bad_request:invalid_page", "bad_request:page_out_of_range", "bad_request:invalid_value", "conflict:inspection_state_changed"] as const, + error_codes: ["bad_request:no_document_loaded", "bad_request:invalid_page", "bad_request:page_out_of_range"] as const, is_agentic_tool: true, has_output: true, } /* GetAnnotatedPage */, diff --git a/embed/src/generated/schemas.ts b/embed/src/generated/schemas.ts index 426e0874..ee661485 100644 --- a/embed/src/generated/schemas.ts +++ b/embed/src/generated/schemas.ts @@ -56,9 +56,8 @@ export const FocusFieldInput = z.object({ fieldId: z.string().describe("ID of the field to focus and scroll into view."), }) export type FocusFieldInput = z.infer -export const GetAnnotatedPageInput = z.strictObject({ +export const GetAnnotatedPageInput = z.object({ page: z.number().int().describe("1-based page to render, at its current position."), - expectedJobId: z.string().optional(), }) export type GetAnnotatedPageInput = z.infer export const GetDocumentContentInput = z.object({ diff --git a/embed/src/generated/webmcp-tools.ts b/embed/src/generated/webmcp-tools.ts index b5dcbc91..d5395c3f 100644 --- a/embed/src/generated/webmcp-tools.ts +++ b/embed/src/generated/webmcp-tools.ts @@ -36,7 +36,7 @@ export const WEBMCP_TOOLS = { detectFields: {"name":"simplepdf_embed_detect_fields","description":"Automatically detect fillable fields in the loaded document and add them as editable fields. Returns the number of fields detected.","inputSchema":{"type":"object","properties":{}},"annotations":{"destructiveHint":false},"wireType":"DETECT_FIELDS"}, download: {"name":"simplepdf_embed_download","description":"Generate and download the current document as a PDF. Returns no data.","inputSchema":{"type":"object","properties":{}},"annotations":{"destructiveHint":false},"wireType":"DOWNLOAD"}, focusField: {"name":"simplepdf_embed_focus_field","description":"Scroll an existing field into view and focus it, addressed by its id from the field list. Returns a hint describing the user action expected next.","inputSchema":{"required":["field_id"],"type":"object","properties":{"field_id":{"description":"ID of the field to focus and scroll into view.","type":"string"}}},"annotations":{"destructiveHint":false},"wireType":"FOCUS_FIELD"}, - getAnnotatedPage: {"name":"simplepdf_embed_get_annotated_page","description":"Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block.","inputSchema":{"required":["page"],"additionalProperties":false,"type":"object","properties":{"page":{"description":"1-based page to render, at its current position.","type":"integer"},"expected_job_id":{"type":"string"}}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_ANNOTATED_PAGE"}, + getAnnotatedPage: {"name":"simplepdf_embed_get_annotated_page","description":"Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block.","inputSchema":{"required":["page"],"type":"object","properties":{"page":{"description":"1-based page to render, at its current position.","type":"integer"}}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_ANNOTATED_PAGE"}, getDocumentContent: {"name":"simplepdf_embed_get_document_content","description":"Extract the document's content page by page as Markdown, or as plain text when optical recognition is forced. Use it to read what the document says. Returns the document name and each page's content.","inputSchema":{"type":"object","properties":{"extraction_mode":{"description":"Extraction strategy: 'auto' (default) or 'ocr' to force optical recognition.","enum":["auto","ocr"],"type":"string"}}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_DOCUMENT_CONTENT"}, getFields: {"name":"simplepdf_embed_get_fields","description":"List every fillable field in the loaded document, including native dropdown and radio AcroFields. Each field reports its id, name, type, page, current value, and the options its value must be one of, if any. Call this first to discover field ids before reading or setting values. To SEE where each field sits on the printed page, render the annotated page. Returns the field list.","inputSchema":{"type":"object","properties":{}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_FIELDS"}, goTo: {"name":"simplepdf_embed_go_to","description":"Scroll the editor to a page. Returns no data.","inputSchema":{"required":["page"],"type":"object","properties":{"page":{"description":"1-based page to navigate to.","type":"integer"}}},"annotations":{"destructiveHint":false},"wireType":"GO_TO"}, diff --git a/embed/test/tools.test.ts b/embed/test/tools.test.ts index 9a6558de..7b120762 100644 --- a/embed/test/tools.test.ts +++ b/embed/test/tools.test.ts @@ -87,17 +87,10 @@ describe(routeToolCall.name, () => { expect(actions.goTo).not.toHaveBeenCalled() }) - it('rejects a misspelled expected job ID before dispatch', async () => { + it('routes getAnnotatedPage to its action with the validated page', async () => { const actions = makeActionsStub() - const result = await routeToolCall(actions, 'getAnnotatedPage', { page: 1, expectedJobID: 'job' }) - expect(result).toMatchObject({ success: false, error: { code: 'bad_request:invalid_input' } }) - expect(actions.getAnnotatedPage).not.toHaveBeenCalled() - }) - - it.each([{ page: 1 }, { page: 2, expectedJobId: 'job' }])('routes getAnnotatedPage with %j', async (input) => { - const actions = makeActionsStub() - await routeToolCall(actions, 'getAnnotatedPage', input) - expect(actions.getAnnotatedPage).toHaveBeenCalledWith(input) + await routeToolCall(actions, 'getAnnotatedPage', { page: 1 }) + expect(actions.getAnnotatedPage).toHaveBeenCalledWith({ page: 1 }) }) it('dispatches no-input tools without requiring input', async () => { From 6b003917701c15885c643464430dc61211b483be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20Andr=C3=A9-Micolon?= Date: Tue, 24 Nov 2026 10:30:21 +0000 Subject: [PATCH 08/12] test: align WebMCP preview fixtures with the manifest --- embed/README.md | 2 +- embed/test/webmcp.test.ts | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/embed/README.md b/embed/README.md index 2d9ac4e8..8317254a 100644 --- a/embed/README.md +++ b/embed/README.md @@ -92,7 +92,7 @@ createEmbed({ target: '#editor', companyIdentifier: 'acme', document: { url: 'ht ``` - **Off by default.** `{ enabled: false }` and omitting the option are the same state. -- **The tools are the editor's own.** Each one is the record the editor publishes in its manifest (`https://simplepdf.com/embed/json`, `operations[].tool`) and registers on its own page: the published tool name, description, snake_case input schema and behavior hints (the readers carry the specification's `readOnlyHint` and `untrustedContentHint`; every other tool MCP's `destructiveHint`; the three that fetch an agent-supplied URL `openWorldHint`). `build_pdf` and `get_documentation` use those names; existing tools retain the `simplepdf_embed_` prefix. A page gets the same tools whether the editor is embedded or opened directly. `exclude` takes SDK method names. +- **The tools are the editor's own.** Each one is the record the editor publishes in its manifest (`https://simplepdf.com/embed/json`, `operations[].tool`) and registers on its own page: the published tool name, description, snake_case input schema and behavior hints (the readers carry the specification's `readOnlyHint` and `untrustedContentHint`; every other tool MCP's `destructiveHint`; those that fetch an agent-supplied URL `openWorldHint`). `build_pdf` and `get_documentation` use those names; existing tools retain the `simplepdf_embed_` prefix. A page gets the same tools whether the editor is embedded or opened directly. `exclude` takes SDK method names. - **Data path.** Every operation an agent can call runs in the browser, and nothing the agent reads (field values, extracted text, a page render) is computed server-side; it goes to the agent runtime the person attached, so treat that runtime as you would any other party that sees the filled document. Document storage is unchanged by this option: it follows your account's configuration exactly as it does without WebMCP (SimplePDF-managed storage, or your own S3, Azure Blob Storage or SharePoint), and `submit` sends the document through the same submission flow as a click on Submit. - **Timing.** Tools register once the editor is ready. While no usable model context has been found, the page is probed again on each later lifecycle transition, so a context installed after `EDITOR_READY` is still picked up, and until one appears nothing is loaded (`webmcp.unavailable` is logged, with the reason). - **Results.** The editor validates each call like any other request (its permission model applies at call time: editing, allowlisted origin, plan, so a tool your configuration refuses resolves with the matching error code). A call resolves with an MCP tool result whose text is the editor's wire-shaped `{ success, data | error }` Result (`isError` on failure). A successful page render from `build_pdf` or `simplepdf_embed_get_annotated_page` carries its PNG as an `image` content block and its field badges in the text block. A call the runtime aborted before it ran rejects and never reaches the editor. diff --git a/embed/test/webmcp.test.ts b/embed/test/webmcp.test.ts index 5585dc0d..a74110cc 100644 --- a/embed/test/webmcp.test.ts +++ b/embed/test/webmcp.test.ts @@ -272,13 +272,13 @@ describe('attachEmbed({ webMCP })', () => { const request = await waitForRequest(harness, 'GET_ANNOTATED_PAGE') harness.reply(request, { success: true, - data: { page: 1, job_id: null, image_data_url: 'data:image/png;base64,iVBORw0KGgo=', image_width: 10, image_height: 12, badges: { '1': 'f1' } }, + data: { page: 1, image_data_url: 'data:image/png;base64,iVBORw0KGgo=', image_width: 10, image_height: 12, badges: { '1': 'f1' } }, }) const toolResult = await pendingResult expect(toolResult.isError).toBeUndefined() expect(toolResult.content).toEqual([ { type: 'image', data: 'iVBORw0KGgo=', mimeType: 'image/png' }, - { type: 'text', text: JSON.stringify({ success: true, data: { page: 1, job_id: null, image_width: 10, image_height: 12, badges: { '1': 'f1' } } }) }, + { type: 'text', text: JSON.stringify({ success: true, data: { page: 1, image_width: 10, image_height: 12, badges: { '1': 'f1' } } }) }, ]) }) @@ -288,7 +288,7 @@ describe('attachEmbed({ webMCP })', () => { await waitForTools(modelContext, TOOL_COUNT) const pending = findTool(modelContext, 'build_pdf').execute({ action: 'status', job_id: 'job' }) const request = await waitForRequest(harness, 'BUILD_PDF') - const page = { page: 1, job_id: 'job', image_width: 10, image_height: 12, badges: {} } + const page = { page: 1, image_width: 10, image_height: 12, badges: {} } const job = { job_id: 'job', status: 'succeeded', page_count: 2, warnings: [] } harness.reply(request, { success: true, From 720d4f9df926e8e2ff2f0ecc85dddc59726cbb7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20Andr=C3=A9-Micolon?= Date: Tue, 24 Nov 2026 16:58:59 +0000 Subject: [PATCH 09/12] refactor: remove PDF build idempotency input --- embed/README.md | 2 +- embed/embed-api.json | 24 ++++++------------------ embed/etc/index.api.md | 1 - embed/etc/protocol.api.md | 6 +++--- embed/etc/schemas.api.md | 1 - embed/etc/tanstack-ai.api.md | 2 +- embed/etc/tools.api.md | 3 +-- embed/src/generated/contract.ts | 8 ++++---- embed/src/generated/schemas.ts | 1 - embed/src/generated/tools.ts | 3 +-- embed/src/generated/webmcp-tools.ts | 2 +- embed/test/tools.test.ts | 11 +++++------ embed/test/webmcp.test.ts | 2 +- 13 files changed, 24 insertions(+), 42 deletions(-) diff --git a/embed/README.md b/embed/README.md index 8317254a..eed12b56 100644 --- a/embed/README.md +++ b/embed/README.md @@ -171,7 +171,7 @@ else r.error.code // a closed BridgeErrorCode ```ts await embed.actions.getDocumentation({ topic: 'build_pdf' }) -await embed.actions.buildPdf({ action: 'build', code: '= Hello', idempotencyKey: 'draft-1' }) +await embed.actions.buildPdf({ action: 'build', code: '= Hello' }) await embed.actions.loadDocument({ dataUrl, name, page }) await embed.actions.goTo({ page: 3 }) await embed.actions.selectTool({ tool: 'TEXT' }) // 'CHECKBOX' | 'SIGNATURE' | 'PICTURE' | 'COMB_TEXT' | null diff --git a/embed/embed-api.json b/embed/embed-api.json index fdc213e8..beeca670 100644 --- a/embed/embed-api.json +++ b/embed/embed-api.json @@ -78,7 +78,7 @@ "operations": [ { "request_type": "BUILD_PDF", - "description": "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing.", + "description": "Build and display Typst PDFs. See documentation. Each build starts a new attempt; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing.", "input_schema": { "anyOf": [ { @@ -91,9 +91,6 @@ "code": { "type": "string" }, - "idempotency_key": { - "type": "string" - }, "name": { "type": "string" }, @@ -114,7 +111,7 @@ } } }, - "required": ["action", "code", "idempotency_key"], + "required": ["action", "code"], "additionalProperties": false }, { @@ -146,7 +143,7 @@ "additionalProperties": false } ], - "description": "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing." + "description": "Build and display Typst PDFs. See documentation. Each build starts a new attempt; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing." }, "output_schema": { "anyOf": [ @@ -451,7 +448,6 @@ ] }, "error_codes": [ - "conflict:idempotency_key_reused", "conflict:editor_modified", "conflict:unmanaged_document", "not_found:job", @@ -462,7 +458,7 @@ ], "tool": { "name": "build_pdf", - "description": "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing.", + "description": "Build and display Typst PDFs. See documentation. Each build starts a new attempt; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing.", "input_schema": { "anyOf": [ { @@ -475,9 +471,6 @@ "code": { "type": "string" }, - "idempotency_key": { - "type": "string" - }, "name": { "type": "string" }, @@ -498,7 +491,7 @@ } } }, - "required": ["action", "code", "idempotency_key"], + "required": ["action", "code"], "additionalProperties": false }, { @@ -1815,11 +1808,6 @@ "properties": { "code": { "anyOf": [ - { - "type": "string", - "const": "conflict:idempotency_key_reused", - "description": "Different input for this key. Use a new key." - }, { "type": "string", "const": "conflict:editor_modified", @@ -1838,7 +1826,7 @@ { "type": "string", "const": "not_found:job_expired", - "description": "Job expired. Its key cannot be reused." + "description": "Job expired. Submit a new build." }, { "type": "string", diff --git a/embed/etc/index.api.md b/embed/etc/index.api.md index 70ff5cb5..9d054df9 100644 --- a/embed/etc/index.api.md +++ b/embed/etc/index.api.md @@ -74,7 +74,6 @@ export class BridgeUnwrapError extends Error { export type BuildPdfInput = { action: "build"; code: string; - idempotencyKey: string; name?: string; assets?: Array<{ path: string; diff --git a/embed/etc/protocol.api.md b/embed/etc/protocol.api.md index 4e5c58fb..70418136 100644 --- a/embed/etc/protocol.api.md +++ b/embed/etc/protocol.api.md @@ -5,7 +5,7 @@ ```ts // @public (undocumented) -export const EDITOR_ERROR_CODES: readonly ["bad_request:batch_validation_failed", "bad_request:download_blocked", "bad_request:editor_not_ready", "bad_request:event_not_allowed", "bad_request:failed_to_load_document", "bad_request:field_not_found", "bad_request:invalid_dimensions", "bad_request:invalid_event_type", "bad_request:invalid_field_ids", "bad_request:invalid_field_type", "bad_request:invalid_page", "bad_request:invalid_signature_url", "bad_request:invalid_tool", "bad_request:invalid_value", "bad_request:missing_required_fields", "bad_request:no_document_loaded", "bad_request:page_not_found", "bad_request:page_out_of_range", "bad_request:plan_upgrade_required", "bad_request:read_only", "bad_request:signup_required", "conflict:editor_modified", "conflict:idempotency_key_reused", "conflict:inspection_state_changed", "conflict:unmanaged_document", "forbidden:editing_not_allowed", "forbidden:origin_not_whitelisted", "forbidden:whitelist_required", "not_found:job", "not_found:job_expired", "resource:session_limit", "unexpected:internal_error"]; +export const EDITOR_ERROR_CODES: readonly ["bad_request:batch_validation_failed", "bad_request:download_blocked", "bad_request:editor_not_ready", "bad_request:event_not_allowed", "bad_request:failed_to_load_document", "bad_request:field_not_found", "bad_request:invalid_dimensions", "bad_request:invalid_event_type", "bad_request:invalid_field_ids", "bad_request:invalid_field_type", "bad_request:invalid_page", "bad_request:invalid_signature_url", "bad_request:invalid_tool", "bad_request:invalid_value", "bad_request:missing_required_fields", "bad_request:no_document_loaded", "bad_request:page_not_found", "bad_request:page_out_of_range", "bad_request:plan_upgrade_required", "bad_request:read_only", "bad_request:signup_required", "conflict:editor_modified", "conflict:inspection_state_changed", "conflict:unmanaged_document", "forbidden:editing_not_allowed", "forbidden:origin_not_whitelisted", "forbidden:whitelist_required", "not_found:job", "not_found:job_expired", "resource:session_limit", "unexpected:internal_error"]; // @public (undocumented) export const EXTRACTION_MODES: readonly ["auto", "ocr"]; @@ -30,8 +30,8 @@ export const OPERATIONS: readonly [{ readonly request_type: "BUILD_PDF"; readonly wire_type: "BUILD_PDF"; readonly method: "buildPdf"; - readonly description: "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing."; - readonly error_codes: readonly ["conflict:idempotency_key_reused", "conflict:editor_modified", "conflict:unmanaged_document", "not_found:job", "not_found:job_expired", "resource:session_limit", "bad_request:invalid_value", "forbidden:editing_not_allowed"]; + readonly description: "Build and display Typst PDFs. See documentation. Each build starts a new attempt; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing."; + readonly error_codes: readonly ["conflict:editor_modified", "conflict:unmanaged_document", "not_found:job", "not_found:job_expired", "resource:session_limit", "bad_request:invalid_value", "forbidden:editing_not_allowed"]; readonly is_agentic_tool: true; readonly has_output: true; }, { diff --git a/embed/etc/schemas.api.md b/embed/etc/schemas.api.md index 686fdae2..677b3730 100644 --- a/embed/etc/schemas.api.md +++ b/embed/etc/schemas.api.md @@ -21,7 +21,6 @@ export type BatchSetFieldValuesInput = z.infer; export const BuildPdfInput: z.ZodUnion; code: z.ZodString; - idempotencyKey: z.ZodString; name: z.ZodOptional; assets: z.ZodOptional, z.ZodLiteral<"status">, z.ZodLiteral<"cancel">]>; code: z.ZodOptional; - idempotencyKey: z.ZodOptional; name: z.ZodOptional; assets: z.ZodOptional } | { action: "status"; jobId: string } | { action: "cancel"; jobId: string } +export type BuildPdfInput = { action: "build"; code: string; name?: string; assets?: Array<{ path: string; dataUrl: string }> } | { action: "status"; jobId: string } | { action: "cancel"; jobId: string } export type BuildPdfOutput = { jobId: string; status: "running" } | { jobId: string; status: "succeeded"; pageCount: number; warnings: Array<{ severity: "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number }>; preview: { success: true; data: { page: number; imageDataUrl: string; imageWidth: number; imageHeight: number; badges: Record } } | { success: false; error: { code: "bad_request:no_document_loaded" | "bad_request:invalid_page" | "bad_request:page_out_of_range" | "bad_request:editor_not_ready" | "bad_request:event_not_allowed" | "bad_request:plan_upgrade_required" | "bad_request:signup_required" | "forbidden:origin_not_whitelisted" | "forbidden:whitelist_required" | "conflict:inspection_state_changed" | "unexpected:internal_error"; message: string } } } | { jobId: string; status: "failed"; error: { code: "unsupported_dependency" | "engine_initialization_failed" | "compile_error" | "compile_timeout" | "job_timeout" | "resource_limit" | "invalid_pdf" | "editor_load_failed" | "editor_conflict" | "worker_crashed" | "internal_error"; message: string; retryable: boolean; diagnostics: Array<{ severity: "error" | "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number }> } } | { jobId: string; status: "cancelled" } | { jobId: string; status: "superseded" } export type GetDocumentationInput = { topic?: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.troubleshooting" | "fields" | "inspection" } export type GetDocumentationOutput = { kind: "index"; topics: Array<{ topic: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.troubleshooting" | "fields" | "inspection"; description: string }> } | { kind: "topic"; markdown: string } @@ -76,8 +76,8 @@ export const OPERATIONS = [ request_type: "BUILD_PDF", wire_type: "BUILD_PDF", method: "buildPdf", - description: "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing.", - error_codes: ["conflict:idempotency_key_reused", "conflict:editor_modified", "conflict:unmanaged_document", "not_found:job", "not_found:job_expired", "resource:session_limit", "bad_request:invalid_value", "forbidden:editing_not_allowed"] as const, + description: "Build and display Typst PDFs. See documentation. Each build starts a new attempt; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing.", + error_codes: ["conflict:editor_modified", "conflict:unmanaged_document", "not_found:job", "not_found:job_expired", "resource:session_limit", "bad_request:invalid_value", "forbidden:editing_not_allowed"] as const, is_agentic_tool: true, has_output: true, } /* BuildPdf */, diff --git a/embed/src/generated/schemas.ts b/embed/src/generated/schemas.ts index ee661485..74172efc 100644 --- a/embed/src/generated/schemas.ts +++ b/embed/src/generated/schemas.ts @@ -4,7 +4,6 @@ import { z } from 'zod' export const BuildPdfInput = z.union([z.strictObject({ action: z.literal("build"), code: z.string(), - idempotencyKey: z.string(), name: z.string().optional(), assets: z.array(z.strictObject({ path: z.string(), diff --git a/embed/src/generated/tools.ts b/embed/src/generated/tools.ts index 7c9a39b1..da4a7db0 100644 --- a/embed/src/generated/tools.ts +++ b/embed/src/generated/tools.ts @@ -5,10 +5,9 @@ import { z } from 'zod' // The agentic tool registry. Each tool name is the camelCase operation name; // load_document is excluded here (a host/setup action; the WebMCP surface registers it). export const TOOL_DEFINITIONS = { - buildPdf: { description: "Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing.", inputSchema: z.strictObject({ + buildPdf: { description: "Build and display Typst PDFs. See documentation. Each build starts a new attempt; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing.", inputSchema: z.strictObject({ action: z.union([z.literal("build"), z.literal("status"), z.literal("cancel")]), code: z.string().optional(), - idempotencyKey: z.string().optional(), name: z.string().optional(), assets: z.array(z.strictObject({ path: z.string(), diff --git a/embed/src/generated/webmcp-tools.ts b/embed/src/generated/webmcp-tools.ts index d5395c3f..1ef0fedb 100644 --- a/embed/src/generated/webmcp-tools.ts +++ b/embed/src/generated/webmcp-tools.ts @@ -27,7 +27,7 @@ export type WebMCPToolRecord = { } export const WEBMCP_TOOLS = { - buildPdf: {"name":"build_pdf","description":"Build and display Typst PDFs. See documentation. Reuse keys for retries; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing.","inputSchema":{"anyOf":[{"type":"object","properties":{"action":{"type":"string","const":"build"},"code":{"type":"string"},"idempotency_key":{"type":"string"},"name":{"type":"string"},"assets":{"type":"array","items":{"type":"object","properties":{"path":{"type":"string"},"data_url":{"type":"string"}},"required":["path","data_url"],"additionalProperties":false}}},"required":["action","code","idempotency_key"],"additionalProperties":false},{"type":"object","properties":{"action":{"type":"string","const":"status"},"job_id":{"type":"string"}},"required":["action","job_id"],"additionalProperties":false},{"type":"object","properties":{"action":{"type":"string","const":"cancel"},"job_id":{"type":"string"}},"required":["action","job_id"],"additionalProperties":false}],"type":"object","properties":{}},"annotations":{"destructiveHint":true,"untrustedContentHint":true},"wireType":"BUILD_PDF"}, + buildPdf: {"name":"build_pdf","description":"Build and display Typst PDFs. See documentation. Each build starts a new attempt; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing.","inputSchema":{"anyOf":[{"type":"object","properties":{"action":{"type":"string","const":"build"},"code":{"type":"string"},"name":{"type":"string"},"assets":{"type":"array","items":{"type":"object","properties":{"path":{"type":"string"},"data_url":{"type":"string"}},"required":["path","data_url"],"additionalProperties":false}}},"required":["action","code"],"additionalProperties":false},{"type":"object","properties":{"action":{"type":"string","const":"status"},"job_id":{"type":"string"}},"required":["action","job_id"],"additionalProperties":false},{"type":"object","properties":{"action":{"type":"string","const":"cancel"},"job_id":{"type":"string"}},"required":["action","job_id"],"additionalProperties":false}],"type":"object","properties":{}},"annotations":{"destructiveHint":true,"untrustedContentHint":true},"wireType":"BUILD_PDF"}, getDocumentation: {"name":"get_documentation","description":"Read task guidance and tested PDF recipes. Omit topic for the index.","inputSchema":{"additionalProperties":false,"type":"object","properties":{"topic":{"enum":["build_pdf","build_pdf.templates","build_pdf.forms","build_pdf.assets","build_pdf.fonts","build_pdf.troubleshooting","fields","inspection"],"type":"string"}}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_DOCUMENTATION"}, batchSetFieldValues: {"name":"simplepdf_embed_batch_set_field_values","description":"Set existing fields, addressed by ids from the field list, in one atomic undo step. If any update is rejected, nothing changes and the call fails with bad_request:batch_validation_failed, whose details list each rejection with its field id, code and message. Text is set at once, never typed. Returns no data.","inputSchema":{"required":["updates"],"type":"object","properties":{"updates":{"items":{"type":"object","properties":{"field_id":{"type":"string","description":"ID of the field to update."},"value":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"New value for the field, or null to clear it. If the field has options (see the field list), it must be one of them; otherwise a string (text/checkbox), or a data URL or http(s) URL, fetched by the editor (signature/picture), or plain text for a signature, drawn as a typed signature."}},"required":["field_id","value"]},"description":"The fields to set, at least one, each field at most once. Fields not listed keep their value.","type":"array"}}},"annotations":{"destructiveHint":false,"openWorldHint":true},"wireType":"BATCH_SET_FIELD_VALUES"}, createField: {"name":"simplepdf_embed_create_field","description":"Create a new overlay field on a page. Returns the id of the created field.","inputSchema":{"required":["type","x","y","width","height","page"],"type":"object","properties":{"type":{"enum":["TEXT","SIGNATURE","PICTURE","CHECKBOX","COMB_TEXT"],"description":"Field type to create.","type":"string"},"x":{"description":"Field x position, in PDF points.","type":"number"},"y":{"description":"Field y position, in PDF points.","type":"number"},"width":{"description":"Field width, in PDF points.","type":"number"},"height":{"description":"Field height, in PDF points.","type":"number"},"page":{"description":"1-based page to place the field on.","type":"integer"},"value":{"description":"Optional initial value. A string for text/checkbox fields; a data URL or http(s) URL (fetched by the editor) for signature/picture fields, or plain text for a signature, drawn as a typed signature.","type":"string"}}},"annotations":{"destructiveHint":false,"openWorldHint":true},"wireType":"CREATE_FIELD"}, diff --git a/embed/test/tools.test.ts b/embed/test/tools.test.ts index 7b120762..50f42068 100644 --- a/embed/test/tools.test.ts +++ b/embed/test/tools.test.ts @@ -48,12 +48,10 @@ describe(routeToolCall.name, () => { await routeToolCall(actions, 'buildPdf', { action: 'build', code: 'Hello', - idempotencyKey: 'first', }) expect(actions.buildPdf).toHaveBeenCalledWith({ action: 'build', code: 'Hello', - idempotencyKey: 'first', }) await routeToolCall(actions, 'buildPdf', { action: 'status', jobId: 'job' }) expect(actions.buildPdf).toHaveBeenCalledWith({ action: 'status', jobId: 'job' }) @@ -63,11 +61,12 @@ describe(routeToolCall.name, () => { // Reject unrecognized keys on each action and in nested assets before dispatch. it.each([ - { action: 'build', code: 'Hello', idempotencyKey: 'key', jobId: 'job' }, - { action: 'build', code: 'Hello', idempotencyKey: 'key', inspect: {} }, - { action: 'build', code: 'Hello', idempotencyKey: 'key', assets: [{ path: 'a.png', dataUrl: 'data', extra: true }] }, + { action: 'build', code: 'Hello', idempotencyKey: 'removed' }, + { action: 'build', code: 'Hello', jobId: 'job' }, + { action: 'build', code: 'Hello', inspect: {} }, + { action: 'build', code: 'Hello', assets: [{ path: 'a.png', dataUrl: 'data', extra: true }] }, { action: 'cancel', jobId: 'job', code: 'Hello' }, - { action: 'build', code: 'Hello' }, + { action: 'build' }, ])('rejects invalid build input without losing fields: %j', async (input) => { const actions = makeActionsStub() expect(await routeToolCall(actions, 'buildPdf', input)).toMatchObject({ diff --git a/embed/test/webmcp.test.ts b/embed/test/webmcp.test.ts index a74110cc..2a9f17e4 100644 --- a/embed/test/webmcp.test.ts +++ b/embed/test/webmcp.test.ts @@ -240,7 +240,7 @@ describe('attachEmbed({ webMCP })', () => { const harness = mountReady({ webMCP: { enabled: true } }) await waitForTools(modelContext, TOOL_COUNT) const input = { - action: 'build', code: 'Draft', idempotency_key: 'wire-keys', idempotencyKey: 'duplicate', + action: 'status', job_id: 'wire-id', jobId: 'duplicate', assets: [{ path: 'image.png', dataUrl: 'invalid' }], } const pending = findTool(modelContext, 'build_pdf').execute(input) From 628edb248c1d6252b05ffc81d259cd2ca8096d23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20Andr=C3=A9-Micolon?= Date: Tue, 24 Nov 2026 20:12:07 +0000 Subject: [PATCH 10/12] fix: enforce build action unions without changing legacy bridge keys --- embed/etc/tanstack-ai.api.md | 2 +- embed/etc/tools.api.md | 48 +++++++++++++++++++++++- embed/scripts/generate.mjs | 7 +++- embed/src/agentic.test-d.ts | 9 +++++ embed/src/bridge.ts | 11 ++++-- embed/src/case-transform.ts | 13 +++++-- embed/src/generated/bridge-vocabulary.ts | 1 + embed/src/generated/contract.ts | 2 +- embed/src/generated/tools.ts | 2 +- embed/src/types.ts | 4 +- embed/test/bridge.test.ts | 11 ++++-- embed/test/tools.test.ts | 1 + 12 files changed, 92 insertions(+), 19 deletions(-) diff --git a/embed/etc/tanstack-ai.api.md b/embed/etc/tanstack-ai.api.md index 71d985aa..22d3940e 100644 --- a/embed/etc/tanstack-ai.api.md +++ b/embed/etc/tanstack-ai.api.md @@ -27,7 +27,7 @@ export type SimplePDFToolName = keyof typeof TOOL_DEFINITIONS; // Warnings were encountered during analysis: // -// dist/tanstack-ai.d.ts:86:5 - (ae-forgotten-export) The symbol "Embed" needs to be exported by the entry point tanstack-ai.d.ts +// dist/tanstack-ai.d.ts:132:5 - (ae-forgotten-export) The symbol "Embed" needs to be exported by the entry point tanstack-ai.d.ts // (No @packageDocumentation comment for this package) diff --git a/embed/etc/tools.api.md b/embed/etc/tools.api.md index 2f7a81f4..adfaee94 100644 --- a/embed/etc/tools.api.md +++ b/embed/etc/tools.api.md @@ -28,7 +28,53 @@ export const SIMPLEPDF_TOOLS: { dataUrl: z.ZodString; }, z.core.$strict>>>; jobId: z.ZodOptional; - }, z.core.$strict>; + }, z.core.$strict> & z.ZodType<{ + action: "build"; + code: string; + name?: string | undefined; + assets?: { + path: string; + dataUrl: string; + }[] | undefined; + } | { + action: "status"; + jobId: string; + } | { + action: "cancel"; + jobId: string; + }, { + action: "build" | "status" | "cancel"; + code?: string | undefined; + name?: string | undefined; + assets?: { + path: string; + dataUrl: string; + }[] | undefined; + jobId?: string | undefined; + }, z.core.$ZodTypeInternals<{ + action: "build"; + code: string; + name?: string | undefined; + assets?: { + path: string; + dataUrl: string; + }[] | undefined; + } | { + action: "status"; + jobId: string; + } | { + action: "cancel"; + jobId: string; + }, { + action: "build" | "status" | "cancel"; + code?: string | undefined; + name?: string | undefined; + assets?: { + path: string; + dataUrl: string; + }[] | undefined; + jobId?: string | undefined; + }>>; }; readonly getDocumentation: { readonly description: "Read task guidance and tested PDF recipes. Omit topic for the index."; diff --git a/embed/scripts/generate.mjs b/embed/scripts/generate.mjs index 3a339ac5..7d89eee9 100644 --- a/embed/scripts/generate.mjs +++ b/embed/scripts/generate.mjs @@ -323,7 +323,7 @@ const constArray = (name, values, typeName) => { const contractLines = [] contractLines.push('// AUTO-GENERATED from embed-api.json by scripts/generate.mjs. Do not edit by hand.') contractLines.push('// Zero runtime dependencies: the zero-dep root imports only from this module and bridge-vocabulary.ts.') -contractLines.push("import type { METHOD_NAMES } from './bridge-vocabulary'") +contractLines.push("import type { METHOD_NAMES } from './bridge-vocabulary.js'") contractLines.push('') contractLines.push(constArray('LOCALES', contract.locales, 'Locale')) contractLines.push(constArray('EDITOR_ERROR_CODES', editorErrorCodes, 'EditorErrorCode')) @@ -443,6 +443,7 @@ writeFileSync( '// AUTO-GENERATED from embed-api.json by scripts/generate.mjs. Do not edit by hand.', '// Kept separate from the full manifest to preserve the root entry bundle boundary.', `export const METHOD_NAMES = [${methodNames.map((name) => JSON.stringify(name)).join(', ')}] as const`, + `export const STRICT_INPUT_REQUEST_TYPES = ${JSON.stringify(contract.operations.filter((op) => (op.input_schema.anyOf ?? [op.input_schema]).every((schema) => schema.additionalProperties === false)).map((op) => op.request_type))} as const`, `export const EDITOR_ERROR_PREFIXES = ${JSON.stringify([...new Set(editorErrorCodes.map((code) => code.slice(0, code.indexOf(':') + 1)))])} as const\n`, ]), ) @@ -587,7 +588,9 @@ toolLines.push('export const TOOL_DEFINITIONS = {') for (const op of agenticOperations) { const stem = toPascal(op.request_type) const advertisement = toolInputObject(op.input_schema) - const inputSchema = advertisement ? zodForObject(advertisement) : `Schemas.${stem}Input` + const inputSchema = advertisement + ? `${zodForObject(advertisement)}.refine((input): input is z.infer => Schemas.${stem}Input.safeParse(input).success, { message: 'Invalid action input' })` + : `Schemas.${stem}Input` toolLines.push( ` ${toCamel(op.request_type)}: { description: ${JSON.stringify(op.description)}, inputSchema: ${inputSchema} },`, ) diff --git a/embed/src/agentic.test-d.ts b/embed/src/agentic.test-d.ts index 5a515914..7a23d15a 100644 --- a/embed/src/agentic.test-d.ts +++ b/embed/src/agentic.test-d.ts @@ -14,3 +14,12 @@ expectTypeOf[number]['name']>().toEq // Browser tools are the documented `AnyClientTool[]`, passed straight to useChat({ tools }). expectTypeOf>().toEqualTypeOf() + +// Provider-compatible JSON must retain the canonical discriminated input in TypeScript. +import type { z } from 'zod' +import { SIMPLEPDF_TOOLS } from './tools' +import type { BuildPdfInput } from './types' +type AdvertisedBuildInput = z.infer +expectTypeOf().toExtend() +expectTypeOf<{ action: 'build' }>().not.toExtend() +expectTypeOf['code']>().toEqualTypeOf() diff --git a/embed/src/bridge.ts b/embed/src/bridge.ts index f33217e4..44fb453b 100644 --- a/embed/src/bridge.ts +++ b/embed/src/bridge.ts @@ -1,4 +1,5 @@ -import { fromWireData, toWireData } from './case-transform' +import { fromWireData, toWireData, InvalidSdkInputError } from './case-transform' +import { STRICT_INPUT_REQUEST_TYPES } from './generated/bridge-vocabulary' import { type BridgeLogger, makeSafeLogger, NOOP_LOGGER } from './logger' import { isBridgeResultLike } from './result' import type { OutboundEventType, WireType } from './generated/contract' @@ -233,6 +234,7 @@ export const attachEmbed = ({ return } + const strictInput = STRICT_INPUT_REQUEST_TYPES.some((type) => type === wireType) const requestId = generateRequestId() const startedAtMs = Date.now() // Log identifiers + timing only — never the payload body (it can carry the @@ -265,10 +267,11 @@ export const attachEmbed = ({ let wireData: unknown switch (payloadShape) { case 'sdk': - wireData = toWireData(data) + wireData = toWireData(data, strictInput) break case 'wire': - wireData = data + // Preserve strict inputs for editor validation; established operations retain SDK-key conversion. + wireData = strictInput ? data : toWireData(data) break default: payloadShape satisfies never @@ -282,7 +285,7 @@ export const attachEmbed = ({ resolve({ success: false, error: { - code: 'unexpected:unknown', + code: error instanceof InvalidSdkInputError ? 'bad_request:invalid_value' : 'unexpected:unknown', message: `Failed to post '${wireType}': ${error instanceof Error ? error.message : String(error)}`, }, }) diff --git a/embed/src/case-transform.ts b/embed/src/case-transform.ts index 8bc57ae1..a23db127 100644 --- a/embed/src/case-transform.ts +++ b/embed/src/case-transform.ts @@ -4,7 +4,7 @@ // // KEYS ONLY: string / number / boolean values pass through untouched, so a field // value that happens to contain underscores is never mangled. Payload keys are the -// contract's (SDK callers) or an agent's (the WebMCP path forwards its input as-is); +// contract's (SDK callers) or an agent's (legacy WebMCP calls also normalize keys); // `__proto__` is dropped below and the editor validates every payload, so a // data-controlled key can neither pollute a prototype nor reach an operation unchecked. // The editor `context` is baked into the iframe URL at mount and never travels as an op payload. @@ -46,8 +46,15 @@ const transformKeysDeep = (value: unknown, mapKey: (key: string) => string): unk return value } -// SDK (camelCase) -> wire (snake_case), applied to SDK requests; WebMCP wire input passes through unchanged. -export const toWireData = (input: unknown): unknown => transformKeysDeep(input, camelToSnakeKey) +// Distinguish rejected SDK input from browser transport failures at the bridge boundary. +export class InvalidSdkInputError extends Error {} + +// SDK (camelCase) -> wire (snake_case). Strict WebMCP inputs bypass conversion so unknown keys reach validation. +export const toWireData = (input: unknown, strict = false): unknown => transformKeysDeep(input, (key) => { + // Strict SDK inputs are camelCase: reject wire aliases before conversion can collapse two keys. + if (strict && key.includes('_')) throw new InvalidSdkInputError('Use camelCase keys for SDK actions.') + return camelToSnakeKey(key) +}) // wire (snake_case) -> SDK (camelCase), applied to SDK operation results. WebMCP results remain wire-shaped. // Editor EVENTS are NOT transformed — they are forwarded verbatim (snake) to diff --git a/embed/src/generated/bridge-vocabulary.ts b/embed/src/generated/bridge-vocabulary.ts index 7054d5e7..e0784a79 100644 --- a/embed/src/generated/bridge-vocabulary.ts +++ b/embed/src/generated/bridge-vocabulary.ts @@ -1,4 +1,5 @@ // AUTO-GENERATED from embed-api.json by scripts/generate.mjs. Do not edit by hand. // Kept separate from the full manifest to preserve the root entry bundle boundary. export const METHOD_NAMES = ["buildPdf", "getDocumentation", "batchSetFieldValues", "createField", "deleteFields", "deletePages", "detectFields", "download", "focusField", "getAnnotatedPage", "getDocumentContent", "getFields", "goTo", "loadDocument", "movePage", "rotatePage", "selectTool", "setFieldValue", "submit"] as const +export const STRICT_INPUT_REQUEST_TYPES = ["BUILD_PDF","GET_DOCUMENTATION"] as const export const EDITOR_ERROR_PREFIXES = ["bad_request:","conflict:","forbidden:","not_found:","resource:","unexpected:"] as const diff --git a/embed/src/generated/contract.ts b/embed/src/generated/contract.ts index 08436423..f89ac69a 100644 --- a/embed/src/generated/contract.ts +++ b/embed/src/generated/contract.ts @@ -1,6 +1,6 @@ // AUTO-GENERATED from embed-api.json by scripts/generate.mjs. Do not edit by hand. // Zero runtime dependencies: the zero-dep root imports only from this module and bridge-vocabulary.ts. -import type { METHOD_NAMES } from './bridge-vocabulary' +import type { METHOD_NAMES } from './bridge-vocabulary.js' export const LOCALES = ["fr", "en", "it", "de", "pt", "es", "ja", "nl"] as const export type Locale = (typeof LOCALES)[number] diff --git a/embed/src/generated/tools.ts b/embed/src/generated/tools.ts index da4a7db0..42900f58 100644 --- a/embed/src/generated/tools.ts +++ b/embed/src/generated/tools.ts @@ -14,7 +14,7 @@ export const TOOL_DEFINITIONS = { dataUrl: z.string(), })).optional(), jobId: z.string().optional(), -}) }, +}).refine((input): input is z.infer => Schemas.BuildPdfInput.safeParse(input).success, { message: 'Invalid action input' }) }, getDocumentation: { description: "Read task guidance and tested PDF recipes. Omit topic for the index.", inputSchema: Schemas.GetDocumentationInput }, batchSetFieldValues: { description: "Set existing fields, addressed by ids from the field list, in one atomic undo step. If any update is rejected, nothing changes and the call fails with bad_request:batch_validation_failed, whose details list each rejection with its field id, code and message. Text is set at once, never typed. Returns no data.", inputSchema: Schemas.BatchSetFieldValuesInput }, createField: { description: "Create a new overlay field on a page. Returns the id of the created field.", inputSchema: Schemas.CreateFieldInput }, diff --git a/embed/src/types.ts b/embed/src/types.ts index 2199b69f..c4419108 100644 --- a/embed/src/types.ts +++ b/embed/src/types.ts @@ -35,7 +35,7 @@ import type { SetFieldValueInput, SubmissionSentPayload, SubmitInput, -} from './generated/contract' +} from './generated/contract.js' export type { BuildPdfInput, @@ -77,7 +77,7 @@ export type { SetFieldValueInput, SubmissionSentPayload, SubmitInput, -} from './generated/contract' +} from './generated/contract.js' // A single field as reported by get_fields. Alias kept for ergonomics; the // shape is owned by the generated GetFieldsOutput. diff --git a/embed/test/bridge.test.ts b/embed/test/bridge.test.ts index 9bfd9843..ab91cb94 100644 --- a/embed/test/bridge.test.ts +++ b/embed/test/bridge.test.ts @@ -203,10 +203,13 @@ describe(attachEmbed.name, () => { vi.spyOn(harness.contentWindow, 'postMessage').mockImplementation(() => { throw new Error('dead window') }) - const result = await harness.embed.actions.getFields() - expect(result.success).toBe(false) - if (!result.success) { - expect(result.error.code).toBe('unexpected:unknown') + // A dead contentWindow is an injected browser failure, not reproducible through a live host. + for (const result of await Promise.all([ + harness.embed.actions.getFields(), + harness.embed.actions.buildPdf({ action: 'build', code: 'Valid source' }), + harness.embed.actions.getDocumentation(), + ])) { + expect(result).toMatchObject({ success: false, error: { code: 'unexpected:unknown' } }) } }) diff --git a/embed/test/tools.test.ts b/embed/test/tools.test.ts index 50f42068..f8578a96 100644 --- a/embed/test/tools.test.ts +++ b/embed/test/tools.test.ts @@ -68,6 +68,7 @@ describe(routeToolCall.name, () => { { action: 'cancel', jobId: 'job', code: 'Hello' }, { action: 'build' }, ])('rejects invalid build input without losing fields: %j', async (input) => { + expect(SIMPLEPDF_TOOLS.buildPdf.inputSchema.safeParse(input).success).toBe(false) const actions = makeActionsStub() expect(await routeToolCall(actions, 'buildPdf', input)).toMatchObject({ success: false, From c02c98e31fc80d5720669eeb3bfa740a1ca332f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20Andr=C3=A9-Micolon?= Date: Wed, 25 Nov 2026 00:51:50 +0000 Subject: [PATCH 11/12] feat: expose sandboxed graphics and Google font selection --- embed/README.md | 2 +- embed/embed-api.json | 258 ++++++++++++++++++++++------ embed/etc/index.api.md | 26 ++- embed/etc/schemas.api.md | 32 +++- embed/etc/tanstack-ai.api.md | 2 +- embed/etc/tools.api.md | 116 +++++++++++-- embed/src/generated/contract.ts | 8 +- embed/src/generated/schemas.ts | 26 ++- embed/src/generated/tools.ts | 22 ++- embed/src/generated/webmcp-tools.ts | 4 +- 10 files changed, 405 insertions(+), 91 deletions(-) diff --git a/embed/README.md b/embed/README.md index eed12b56..5eb9a5f7 100644 --- a/embed/README.md +++ b/embed/README.md @@ -92,7 +92,7 @@ createEmbed({ target: '#editor', companyIdentifier: 'acme', document: { url: 'ht ``` - **Off by default.** `{ enabled: false }` and omitting the option are the same state. -- **The tools are the editor's own.** Each one is the record the editor publishes in its manifest (`https://simplepdf.com/embed/json`, `operations[].tool`) and registers on its own page: the published tool name, description, snake_case input schema and behavior hints (the readers carry the specification's `readOnlyHint` and `untrustedContentHint`; every other tool MCP's `destructiveHint`; those that fetch an agent-supplied URL `openWorldHint`). `build_pdf` and `get_documentation` use those names; existing tools retain the `simplepdf_embed_` prefix. A page gets the same tools whether the editor is embedded or opened directly. `exclude` takes SDK method names. +- **The tools are the editor's own.** Each one is the record the editor publishes in its manifest (`https://simplepdf.com/embed/json`, `operations[].tool`) and registers on its own page: the published tool name, description, snake_case input schema and behavior hints (the readers carry the specification's `readOnlyHint` and `untrustedContentHint`; every other tool MCP's `destructiveHint`; those that fetch an agent-supplied URL or requested Google Fonts `openWorldHint`). `build_pdf` and `get_documentation` use those names; existing tools retain the `simplepdf_embed_` prefix. A page gets the same tools whether the editor is embedded or opened directly. `exclude` takes SDK method names. - **Data path.** Every operation an agent can call runs in the browser, and nothing the agent reads (field values, extracted text, a page render) is computed server-side; it goes to the agent runtime the person attached, so treat that runtime as you would any other party that sees the filled document. Document storage is unchanged by this option: it follows your account's configuration exactly as it does without WebMCP (SimplePDF-managed storage, or your own S3, Azure Blob Storage or SharePoint), and `submit` sends the document through the same submission flow as a click on Submit. - **Timing.** Tools register once the editor is ready. While no usable model context has been found, the page is probed again on each later lifecycle transition, so a context installed after `EDITOR_READY` is still picked up, and until one appears nothing is loaded (`webmcp.unavailable` is logged, with the reason). - **Results.** The editor validates each call like any other request (its permission model applies at call time: editing, allowlisted origin, plan, so a tool your configuration refuses resolves with the matching error code). A call resolves with an MCP tool result whose text is the editor's wire-shaped `{ success, data | error }` Result (`isError` on failure). A successful page render from `build_pdf` or `simplepdf_embed_get_annotated_page` carries its PNG as an `image` content block and its field badges in the text block. A call the runtime aborted before it ran rejects and never reaches the editor. diff --git a/embed/embed-api.json b/embed/embed-api.json index beeca670..f8e30dcc 100644 --- a/embed/embed-api.json +++ b/embed/embed-api.json @@ -91,24 +91,80 @@ "code": { "type": "string" }, - "name": { - "type": "string" - }, - "assets": { + "fonts": { "type": "array", "items": { "type": "object", "properties": { - "path": { + "family": { "type": "string" }, - "data_url": { - "type": "string" + "weight": { + "type": "integer" + }, + "style": { + "type": "string", + "enum": ["normal", "italic"] } }, - "required": ["path", "data_url"], + "required": ["family"], "additionalProperties": false } + }, + "name": { + "type": "string" + }, + "assets": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "object", + "properties": { + "path": { + "type": "string" + }, + "data_url": { + "type": "string" + } + }, + "required": ["path", "data_url"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "path": { + "type": "string" + }, + "shader": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "width": { + "type": "integer" + }, + "height": { + "type": "integer" + }, + "textures": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": ["code", "width", "height"], + "additionalProperties": false + } + }, + "required": ["path", "shader"], + "additionalProperties": false + } + ] + } } }, "required": ["action", "code"], @@ -185,7 +241,7 @@ }, "code": { "type": "string", - "enum": ["typst", "unsupported_dependency"] + "enum": ["typst", "shader", "unsupported_dependency"] }, "message": { "type": "string" @@ -361,6 +417,7 @@ "type": "string", "enum": [ "unsupported_dependency", + "font_unavailable", "engine_initialization_failed", "compile_error", "compile_timeout", @@ -390,7 +447,7 @@ }, "code": { "type": "string", - "enum": ["typst", "unsupported_dependency"] + "enum": ["typst", "shader", "unsupported_dependency"] }, "message": { "type": "string" @@ -471,24 +528,80 @@ "code": { "type": "string" }, - "name": { - "type": "string" - }, - "assets": { + "fonts": { "type": "array", "items": { "type": "object", "properties": { - "path": { + "family": { "type": "string" }, - "data_url": { - "type": "string" + "weight": { + "type": "integer" + }, + "style": { + "type": "string", + "enum": ["normal", "italic"] } }, - "required": ["path", "data_url"], + "required": ["family"], "additionalProperties": false } + }, + "name": { + "type": "string" + }, + "assets": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "object", + "properties": { + "path": { + "type": "string" + }, + "data_url": { + "type": "string" + } + }, + "required": ["path", "data_url"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "path": { + "type": "string" + }, + "shader": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "width": { + "type": "integer" + }, + "height": { + "type": "integer" + }, + "textures": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": ["code", "width", "height"], + "additionalProperties": false + } + }, + "required": ["path", "shader"], + "additionalProperties": false + } + ] + } } }, "required": ["action", "code"], @@ -528,7 +641,8 @@ }, "annotations": { "destructiveHint": true, - "untrustedContentHint": true + "untrustedContentHint": true, + "openWorldHint": true } } }, @@ -536,23 +650,42 @@ "request_type": "GET_DOCUMENTATION", "description": "Read task guidance and tested PDF recipes. Omit topic for the index.", "input_schema": { - "type": "object", - "properties": { - "topic": { - "type": "string", - "enum": [ - "build_pdf", - "build_pdf.templates", - "build_pdf.forms", - "build_pdf.assets", - "build_pdf.fonts", - "build_pdf.troubleshooting", - "fields", - "inspection" - ] + "anyOf": [ + { + "type": "object", + "properties": { + "topic": { + "type": "string", + "enum": [ + "build_pdf", + "build_pdf.templates", + "build_pdf.forms", + "build_pdf.assets", + "build_pdf.graphics", + "build_pdf.shaders", + "build_pdf.troubleshooting", + "fields", + "inspection" + ] + } + }, + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "topic": { + "type": "string", + "enum": ["build_pdf.fonts"] + }, + "query": { + "type": "string" + } + }, + "required": ["topic"], + "additionalProperties": false } - }, - "additionalProperties": false, + ], "description": "Read task guidance and tested PDF recipes. Omit topic for the index." }, "output_schema": { @@ -577,6 +710,8 @@ "build_pdf.forms", "build_pdf.assets", "build_pdf.fonts", + "build_pdf.graphics", + "build_pdf.shaders", "build_pdf.troubleshooting", "fields", "inspection" @@ -615,23 +750,44 @@ "name": "get_documentation", "description": "Read task guidance and tested PDF recipes. Omit topic for the index.", "input_schema": { - "additionalProperties": false, - "type": "object", - "properties": { - "topic": { - "enum": [ - "build_pdf", - "build_pdf.templates", - "build_pdf.forms", - "build_pdf.assets", - "build_pdf.fonts", - "build_pdf.troubleshooting", - "fields", - "inspection" - ], - "type": "string" + "anyOf": [ + { + "type": "object", + "properties": { + "topic": { + "type": "string", + "enum": [ + "build_pdf", + "build_pdf.templates", + "build_pdf.forms", + "build_pdf.assets", + "build_pdf.graphics", + "build_pdf.shaders", + "build_pdf.troubleshooting", + "fields", + "inspection" + ] + } + }, + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "topic": { + "type": "string", + "enum": ["build_pdf.fonts"] + }, + "query": { + "type": "string" + } + }, + "required": ["topic"], + "additionalProperties": false } - } + ], + "type": "object", + "properties": {} }, "annotations": { "readOnlyHint": true, diff --git a/embed/etc/index.api.md b/embed/etc/index.api.md index 9d054df9..7cdf09b9 100644 --- a/embed/etc/index.api.md +++ b/embed/etc/index.api.md @@ -74,10 +74,23 @@ export class BridgeUnwrapError extends Error { export type BuildPdfInput = { action: "build"; code: string; + fonts?: Array<{ + family: string; + weight?: number; + style?: "normal" | "italic"; + }>; name?: string; assets?: Array<{ path: string; dataUrl: string; + } | { + path: string; + shader: { + code: string; + width: number; + height: number; + textures?: string[]; + }; }>; } | { action: "status"; @@ -97,7 +110,7 @@ export type BuildPdfOutput = { pageCount: number; warnings: Array<{ severity: "warning"; - code: "typst" | "unsupported_dependency"; + code: "typst" | "shader" | "unsupported_dependency"; message: string; file?: string; line?: number; @@ -123,12 +136,12 @@ export type BuildPdfOutput = { jobId: string; status: "failed"; error: { - code: "unsupported_dependency" | "engine_initialization_failed" | "compile_error" | "compile_timeout" | "job_timeout" | "resource_limit" | "invalid_pdf" | "editor_load_failed" | "editor_conflict" | "worker_crashed" | "internal_error"; + code: "unsupported_dependency" | "font_unavailable" | "engine_initialization_failed" | "compile_error" | "compile_timeout" | "job_timeout" | "resource_limit" | "invalid_pdf" | "editor_load_failed" | "editor_conflict" | "worker_crashed" | "internal_error"; message: string; retryable: boolean; diagnostics: Array<{ severity: "error" | "warning"; - code: "typst" | "unsupported_dependency"; + code: "typst" | "shader" | "unsupported_dependency"; message: string; file?: string; line?: number; @@ -322,14 +335,17 @@ export type GetAnnotatedPageOutput = { // @public (undocumented) export type GetDocumentationInput = { - topic?: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.troubleshooting" | "fields" | "inspection"; + topic?: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.graphics" | "build_pdf.shaders" | "build_pdf.troubleshooting" | "fields" | "inspection"; +} | { + topic: "build_pdf.fonts"; + query?: string; }; // @public (undocumented) export type GetDocumentationOutput = { kind: "index"; topics: Array<{ - topic: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.troubleshooting" | "fields" | "inspection"; + topic: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.graphics" | "build_pdf.shaders" | "build_pdf.troubleshooting" | "fields" | "inspection"; description: string; }>; } | { diff --git a/embed/etc/schemas.api.md b/embed/etc/schemas.api.md index 677b3730..b8955821 100644 --- a/embed/etc/schemas.api.md +++ b/embed/etc/schemas.api.md @@ -21,11 +21,27 @@ export type BatchSetFieldValuesInput = z.infer; export const BuildPdfInput: z.ZodUnion; code: z.ZodString; + fonts: z.ZodOptional; + style: z.ZodOptional>; + }, z.core.$strict>>>; name: z.ZodOptional; - assets: z.ZodOptional>>; + }, z.core.$strict>, z.ZodObject<{ + path: z.ZodString; + shader: z.ZodObject<{ + code: z.ZodString; + width: z.ZodNumber; + height: z.ZodNumber; + textures: z.ZodOptional>; + }, z.core.$strict>; + }, z.core.$strict>]>>>; }, z.core.$strict>, z.ZodObject<{ action: z.ZodLiteral<"status">; jobId: z.ZodString; @@ -103,18 +119,24 @@ export const GetAnnotatedPageInput: z.ZodObject<{ export type GetAnnotatedPageInput = z.infer; // @public (undocumented) -export const GetDocumentationInput: z.ZodObject<{ +export const GetDocumentationInput: z.ZodUnion>; -}, z.core.$strict>; +}, z.core.$strict>, z.ZodObject<{ + topic: z.ZodEnum<{ + "build_pdf.fonts": "build_pdf.fonts"; + }>; + query: z.ZodOptional; +}, z.core.$strict>]>; // @public (undocumented) export type GetDocumentationInput = z.infer; diff --git a/embed/etc/tanstack-ai.api.md b/embed/etc/tanstack-ai.api.md index 22d3940e..fa5a5a73 100644 --- a/embed/etc/tanstack-ai.api.md +++ b/embed/etc/tanstack-ai.api.md @@ -27,7 +27,7 @@ export type SimplePDFToolName = keyof typeof TOOL_DEFINITIONS; // Warnings were encountered during analysis: // -// dist/tanstack-ai.d.ts:132:5 - (ae-forgotten-export) The symbol "Embed" needs to be exported by the entry point tanstack-ai.d.ts +// dist/tanstack-ai.d.ts:220:5 - (ae-forgotten-export) The symbol "Embed" needs to be exported by the entry point tanstack-ai.d.ts // (No @packageDocumentation comment for this package) diff --git a/embed/etc/tools.api.md b/embed/etc/tools.api.md index adfaee94..8c064c75 100644 --- a/embed/etc/tools.api.md +++ b/embed/etc/tools.api.md @@ -22,20 +22,49 @@ export const SIMPLEPDF_TOOLS: { readonly inputSchema: z.ZodObject<{ action: z.ZodUnion, z.ZodLiteral<"status">, z.ZodLiteral<"cancel">]>; code: z.ZodOptional; + fonts: z.ZodOptional; + style: z.ZodOptional>; + }, z.core.$strict>>>; name: z.ZodOptional; - assets: z.ZodOptional>>; + }, z.core.$strict>, z.ZodObject<{ + path: z.ZodString; + shader: z.ZodObject<{ + code: z.ZodString; + width: z.ZodNumber; + height: z.ZodNumber; + textures: z.ZodOptional>; + }, z.core.$strict>; + }, z.core.$strict>]>>>; jobId: z.ZodOptional; }, z.core.$strict> & z.ZodType<{ action: "build"; code: string; + fonts?: { + family: string; + weight?: number | undefined; + style?: "normal" | "italic" | undefined; + }[] | undefined; name?: string | undefined; - assets?: { + assets?: ({ path: string; dataUrl: string; - }[] | undefined; + } | { + path: string; + shader: { + code: string; + width: number; + height: number; + textures?: string[] | undefined; + }; + })[] | undefined; } | { action: "status"; jobId: string; @@ -45,20 +74,46 @@ export const SIMPLEPDF_TOOLS: { }, { action: "build" | "status" | "cancel"; code?: string | undefined; + fonts?: { + family: string; + weight?: number | undefined; + style?: "normal" | "italic" | undefined; + }[] | undefined; name?: string | undefined; - assets?: { + assets?: ({ path: string; dataUrl: string; - }[] | undefined; + } | { + path: string; + shader: { + code: string; + width: number; + height: number; + textures?: string[] | undefined; + }; + })[] | undefined; jobId?: string | undefined; }, z.core.$ZodTypeInternals<{ action: "build"; code: string; + fonts?: { + family: string; + weight?: number | undefined; + style?: "normal" | "italic" | undefined; + }[] | undefined; name?: string | undefined; - assets?: { + assets?: ({ path: string; dataUrl: string; - }[] | undefined; + } | { + path: string; + shader: { + code: string; + width: number; + height: number; + textures?: string[] | undefined; + }; + })[] | undefined; } | { action: "status"; jobId: string; @@ -68,28 +123,61 @@ export const SIMPLEPDF_TOOLS: { }, { action: "build" | "status" | "cancel"; code?: string | undefined; + fonts?: { + family: string; + weight?: number | undefined; + style?: "normal" | "italic" | undefined; + }[] | undefined; name?: string | undefined; - assets?: { + assets?: ({ path: string; dataUrl: string; - }[] | undefined; + } | { + path: string; + shader: { + code: string; + width: number; + height: number; + textures?: string[] | undefined; + }; + })[] | undefined; jobId?: string | undefined; }>>; }; readonly getDocumentation: { readonly description: "Read task guidance and tested PDF recipes. Omit topic for the index."; readonly inputSchema: z.ZodObject<{ - topic: z.ZodOptional>; - }, z.core.$strict>; + }>, z.ZodEnum<{ + "build_pdf.fonts": "build_pdf.fonts"; + }>]>>; + query: z.ZodOptional; + }, z.core.$strict> & z.ZodType<{ + topic?: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.graphics" | "build_pdf.shaders" | "build_pdf.troubleshooting" | "fields" | "inspection" | undefined; + } | { + topic: "build_pdf.fonts"; + query?: string | undefined; + }, { + topic?: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.graphics" | "build_pdf.shaders" | "build_pdf.troubleshooting" | "fields" | "inspection" | "build_pdf.fonts" | undefined; + query?: string | undefined; + }, z.core.$ZodTypeInternals<{ + topic?: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.graphics" | "build_pdf.shaders" | "build_pdf.troubleshooting" | "fields" | "inspection" | undefined; + } | { + topic: "build_pdf.fonts"; + query?: string | undefined; + }, { + topic?: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.graphics" | "build_pdf.shaders" | "build_pdf.troubleshooting" | "fields" | "inspection" | "build_pdf.fonts" | undefined; + query?: string | undefined; + }>>; }; readonly batchSetFieldValues: { readonly description: "Set existing fields, addressed by ids from the field list, in one atomic undo step. If any update is rejected, nothing changes and the call fails with bad_request:batch_validation_failed, whose details list each rejection with its field id, code and message. Text is set at once, never typed. Returns no data."; diff --git a/embed/src/generated/contract.ts b/embed/src/generated/contract.ts index f89ac69a..67c93887 100644 --- a/embed/src/generated/contract.ts +++ b/embed/src/generated/contract.ts @@ -17,10 +17,10 @@ export type OverlayToolType = (typeof OVERLAY_TOOL_TYPES)[number] export const EXTRACTION_MODES = ["auto", "ocr"] as const export type ExtractionMode = (typeof EXTRACTION_MODES)[number] -export type BuildPdfInput = { action: "build"; code: string; name?: string; assets?: Array<{ path: string; dataUrl: string }> } | { action: "status"; jobId: string } | { action: "cancel"; jobId: string } -export type BuildPdfOutput = { jobId: string; status: "running" } | { jobId: string; status: "succeeded"; pageCount: number; warnings: Array<{ severity: "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number }>; preview: { success: true; data: { page: number; imageDataUrl: string; imageWidth: number; imageHeight: number; badges: Record } } | { success: false; error: { code: "bad_request:no_document_loaded" | "bad_request:invalid_page" | "bad_request:page_out_of_range" | "bad_request:editor_not_ready" | "bad_request:event_not_allowed" | "bad_request:plan_upgrade_required" | "bad_request:signup_required" | "forbidden:origin_not_whitelisted" | "forbidden:whitelist_required" | "conflict:inspection_state_changed" | "unexpected:internal_error"; message: string } } } | { jobId: string; status: "failed"; error: { code: "unsupported_dependency" | "engine_initialization_failed" | "compile_error" | "compile_timeout" | "job_timeout" | "resource_limit" | "invalid_pdf" | "editor_load_failed" | "editor_conflict" | "worker_crashed" | "internal_error"; message: string; retryable: boolean; diagnostics: Array<{ severity: "error" | "warning"; code: "typst" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number }> } } | { jobId: string; status: "cancelled" } | { jobId: string; status: "superseded" } -export type GetDocumentationInput = { topic?: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.troubleshooting" | "fields" | "inspection" } -export type GetDocumentationOutput = { kind: "index"; topics: Array<{ topic: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.troubleshooting" | "fields" | "inspection"; description: string }> } | { kind: "topic"; markdown: string } +export type BuildPdfInput = { action: "build"; code: string; fonts?: Array<{ family: string; weight?: number; style?: "normal" | "italic" }>; name?: string; assets?: Array<{ path: string; dataUrl: string } | { path: string; shader: { code: string; width: number; height: number; textures?: string[] } }> } | { action: "status"; jobId: string } | { action: "cancel"; jobId: string } +export type BuildPdfOutput = { jobId: string; status: "running" } | { jobId: string; status: "succeeded"; pageCount: number; warnings: Array<{ severity: "warning"; code: "typst" | "shader" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number }>; preview: { success: true; data: { page: number; imageDataUrl: string; imageWidth: number; imageHeight: number; badges: Record } } | { success: false; error: { code: "bad_request:no_document_loaded" | "bad_request:invalid_page" | "bad_request:page_out_of_range" | "bad_request:editor_not_ready" | "bad_request:event_not_allowed" | "bad_request:plan_upgrade_required" | "bad_request:signup_required" | "forbidden:origin_not_whitelisted" | "forbidden:whitelist_required" | "conflict:inspection_state_changed" | "unexpected:internal_error"; message: string } } } | { jobId: string; status: "failed"; error: { code: "unsupported_dependency" | "font_unavailable" | "engine_initialization_failed" | "compile_error" | "compile_timeout" | "job_timeout" | "resource_limit" | "invalid_pdf" | "editor_load_failed" | "editor_conflict" | "worker_crashed" | "internal_error"; message: string; retryable: boolean; diagnostics: Array<{ severity: "error" | "warning"; code: "typst" | "shader" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number }> } } | { jobId: string; status: "cancelled" } | { jobId: string; status: "superseded" } +export type GetDocumentationInput = { topic?: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.graphics" | "build_pdf.shaders" | "build_pdf.troubleshooting" | "fields" | "inspection" } | { topic: "build_pdf.fonts"; query?: string } +export type GetDocumentationOutput = { kind: "index"; topics: Array<{ topic: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.graphics" | "build_pdf.shaders" | "build_pdf.troubleshooting" | "fields" | "inspection"; description: string }> } | { kind: "topic"; markdown: string } export type BatchSetFieldValuesInput = { updates: Array<{ fieldId: string; value: string | null }> } export type BatchSetFieldValuesOutput = null export type CreateFieldInput = { type: OverlayToolType; x: number; y: number; width: number; height: number; page: number; value?: string } diff --git a/embed/src/generated/schemas.ts b/embed/src/generated/schemas.ts index 74172efc..20a5498c 100644 --- a/embed/src/generated/schemas.ts +++ b/embed/src/generated/schemas.ts @@ -4,11 +4,24 @@ import { z } from 'zod' export const BuildPdfInput = z.union([z.strictObject({ action: z.literal("build"), code: z.string(), + fonts: z.array(z.strictObject({ + family: z.string(), + weight: z.number().int().optional(), + style: z.enum(["normal", "italic"]).optional(), +})).optional(), name: z.string().optional(), - assets: z.array(z.strictObject({ + assets: z.array(z.union([z.strictObject({ path: z.string(), dataUrl: z.string(), -})).optional(), +}), z.strictObject({ + path: z.string(), + shader: z.strictObject({ + code: z.string(), + width: z.number().int(), + height: z.number().int(), + textures: z.array(z.string()).optional(), +}), +})])).optional(), }), z.strictObject({ action: z.literal("status"), jobId: z.string(), @@ -17,9 +30,12 @@ export const BuildPdfInput = z.union([z.strictObject({ jobId: z.string(), })]) export type BuildPdfInput = z.infer -export const GetDocumentationInput = z.strictObject({ - topic: z.enum(["build_pdf", "build_pdf.templates", "build_pdf.forms", "build_pdf.assets", "build_pdf.fonts", "build_pdf.troubleshooting", "fields", "inspection"]).optional(), -}) +export const GetDocumentationInput = z.union([z.strictObject({ + topic: z.enum(["build_pdf", "build_pdf.templates", "build_pdf.forms", "build_pdf.assets", "build_pdf.graphics", "build_pdf.shaders", "build_pdf.troubleshooting", "fields", "inspection"]).optional(), +}), z.strictObject({ + topic: z.enum(["build_pdf.fonts"]), + query: z.string().optional(), +})]) export type GetDocumentationInput = z.infer export const BatchSetFieldValuesInput = z.object({ updates: z.array(z.object({ diff --git a/embed/src/generated/tools.ts b/embed/src/generated/tools.ts index 42900f58..c0a2f727 100644 --- a/embed/src/generated/tools.ts +++ b/embed/src/generated/tools.ts @@ -8,14 +8,30 @@ export const TOOL_DEFINITIONS = { buildPdf: { description: "Build and display Typst PDFs. See documentation. Each build starts a new attempt; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing.", inputSchema: z.strictObject({ action: z.union([z.literal("build"), z.literal("status"), z.literal("cancel")]), code: z.string().optional(), + fonts: z.array(z.strictObject({ + family: z.string(), + weight: z.number().int().optional(), + style: z.enum(["normal", "italic"]).optional(), +})).optional(), name: z.string().optional(), - assets: z.array(z.strictObject({ + assets: z.array(z.union([z.strictObject({ path: z.string(), dataUrl: z.string(), -})).optional(), +}), z.strictObject({ + path: z.string(), + shader: z.strictObject({ + code: z.string(), + width: z.number().int(), + height: z.number().int(), + textures: z.array(z.string()).optional(), +}), +})])).optional(), jobId: z.string().optional(), }).refine((input): input is z.infer => Schemas.BuildPdfInput.safeParse(input).success, { message: 'Invalid action input' }) }, - getDocumentation: { description: "Read task guidance and tested PDF recipes. Omit topic for the index.", inputSchema: Schemas.GetDocumentationInput }, + getDocumentation: { description: "Read task guidance and tested PDF recipes. Omit topic for the index.", inputSchema: z.strictObject({ + topic: z.union([z.enum(["build_pdf", "build_pdf.templates", "build_pdf.forms", "build_pdf.assets", "build_pdf.graphics", "build_pdf.shaders", "build_pdf.troubleshooting", "fields", "inspection"]), z.enum(["build_pdf.fonts"])]).optional(), + query: z.string().optional(), +}).refine((input): input is z.infer => Schemas.GetDocumentationInput.safeParse(input).success, { message: 'Invalid action input' }) }, batchSetFieldValues: { description: "Set existing fields, addressed by ids from the field list, in one atomic undo step. If any update is rejected, nothing changes and the call fails with bad_request:batch_validation_failed, whose details list each rejection with its field id, code and message. Text is set at once, never typed. Returns no data.", inputSchema: Schemas.BatchSetFieldValuesInput }, createField: { description: "Create a new overlay field on a page. Returns the id of the created field.", inputSchema: Schemas.CreateFieldInput }, deleteFields: { description: "Delete overlay fields: the ones listed, every one on a page, or every one in the document. Returns the number of fields deleted. Destructive.", inputSchema: Schemas.DeleteFieldsInput }, diff --git a/embed/src/generated/webmcp-tools.ts b/embed/src/generated/webmcp-tools.ts index 1ef0fedb..ecefbd3a 100644 --- a/embed/src/generated/webmcp-tools.ts +++ b/embed/src/generated/webmcp-tools.ts @@ -27,8 +27,8 @@ export type WebMCPToolRecord = { } export const WEBMCP_TOOLS = { - buildPdf: {"name":"build_pdf","description":"Build and display Typst PDFs. See documentation. Each build starts a new attempt; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing.","inputSchema":{"anyOf":[{"type":"object","properties":{"action":{"type":"string","const":"build"},"code":{"type":"string"},"name":{"type":"string"},"assets":{"type":"array","items":{"type":"object","properties":{"path":{"type":"string"},"data_url":{"type":"string"}},"required":["path","data_url"],"additionalProperties":false}}},"required":["action","code"],"additionalProperties":false},{"type":"object","properties":{"action":{"type":"string","const":"status"},"job_id":{"type":"string"}},"required":["action","job_id"],"additionalProperties":false},{"type":"object","properties":{"action":{"type":"string","const":"cancel"},"job_id":{"type":"string"}},"required":["action","job_id"],"additionalProperties":false}],"type":"object","properties":{}},"annotations":{"destructiveHint":true,"untrustedContentHint":true},"wireType":"BUILD_PDF"}, - getDocumentation: {"name":"get_documentation","description":"Read task guidance and tested PDF recipes. Omit topic for the index.","inputSchema":{"additionalProperties":false,"type":"object","properties":{"topic":{"enum":["build_pdf","build_pdf.templates","build_pdf.forms","build_pdf.assets","build_pdf.fonts","build_pdf.troubleshooting","fields","inspection"],"type":"string"}}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_DOCUMENTATION"}, + buildPdf: {"name":"build_pdf","description":"Build and display Typst PDFs. See documentation. Each build starts a new attempt; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing.","inputSchema":{"anyOf":[{"type":"object","properties":{"action":{"type":"string","const":"build"},"code":{"type":"string"},"fonts":{"type":"array","items":{"type":"object","properties":{"family":{"type":"string"},"weight":{"type":"integer"},"style":{"type":"string","enum":["normal","italic"]}},"required":["family"],"additionalProperties":false}},"name":{"type":"string"},"assets":{"type":"array","items":{"anyOf":[{"type":"object","properties":{"path":{"type":"string"},"data_url":{"type":"string"}},"required":["path","data_url"],"additionalProperties":false},{"type":"object","properties":{"path":{"type":"string"},"shader":{"type":"object","properties":{"code":{"type":"string"},"width":{"type":"integer"},"height":{"type":"integer"},"textures":{"type":"array","items":{"type":"string"}}},"required":["code","width","height"],"additionalProperties":false}},"required":["path","shader"],"additionalProperties":false}]}}},"required":["action","code"],"additionalProperties":false},{"type":"object","properties":{"action":{"type":"string","const":"status"},"job_id":{"type":"string"}},"required":["action","job_id"],"additionalProperties":false},{"type":"object","properties":{"action":{"type":"string","const":"cancel"},"job_id":{"type":"string"}},"required":["action","job_id"],"additionalProperties":false}],"type":"object","properties":{}},"annotations":{"destructiveHint":true,"untrustedContentHint":true,"openWorldHint":true},"wireType":"BUILD_PDF"}, + getDocumentation: {"name":"get_documentation","description":"Read task guidance and tested PDF recipes. Omit topic for the index.","inputSchema":{"anyOf":[{"type":"object","properties":{"topic":{"type":"string","enum":["build_pdf","build_pdf.templates","build_pdf.forms","build_pdf.assets","build_pdf.graphics","build_pdf.shaders","build_pdf.troubleshooting","fields","inspection"]}},"additionalProperties":false},{"type":"object","properties":{"topic":{"type":"string","enum":["build_pdf.fonts"]},"query":{"type":"string"}},"required":["topic"],"additionalProperties":false}],"type":"object","properties":{}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_DOCUMENTATION"}, batchSetFieldValues: {"name":"simplepdf_embed_batch_set_field_values","description":"Set existing fields, addressed by ids from the field list, in one atomic undo step. If any update is rejected, nothing changes and the call fails with bad_request:batch_validation_failed, whose details list each rejection with its field id, code and message. Text is set at once, never typed. Returns no data.","inputSchema":{"required":["updates"],"type":"object","properties":{"updates":{"items":{"type":"object","properties":{"field_id":{"type":"string","description":"ID of the field to update."},"value":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"New value for the field, or null to clear it. If the field has options (see the field list), it must be one of them; otherwise a string (text/checkbox), or a data URL or http(s) URL, fetched by the editor (signature/picture), or plain text for a signature, drawn as a typed signature."}},"required":["field_id","value"]},"description":"The fields to set, at least one, each field at most once. Fields not listed keep their value.","type":"array"}}},"annotations":{"destructiveHint":false,"openWorldHint":true},"wireType":"BATCH_SET_FIELD_VALUES"}, createField: {"name":"simplepdf_embed_create_field","description":"Create a new overlay field on a page. Returns the id of the created field.","inputSchema":{"required":["type","x","y","width","height","page"],"type":"object","properties":{"type":{"enum":["TEXT","SIGNATURE","PICTURE","CHECKBOX","COMB_TEXT"],"description":"Field type to create.","type":"string"},"x":{"description":"Field x position, in PDF points.","type":"number"},"y":{"description":"Field y position, in PDF points.","type":"number"},"width":{"description":"Field width, in PDF points.","type":"number"},"height":{"description":"Field height, in PDF points.","type":"number"},"page":{"description":"1-based page to place the field on.","type":"integer"},"value":{"description":"Optional initial value. A string for text/checkbox fields; a data URL or http(s) URL (fetched by the editor) for signature/picture fields, or plain text for a signature, drawn as a typed signature.","type":"string"}}},"annotations":{"destructiveHint":false,"openWorldHint":true},"wireType":"CREATE_FIELD"}, deleteFields: {"name":"simplepdf_embed_delete_fields","description":"Delete overlay fields: the ones listed, every one on a page, or every one in the document. Returns the number of fields deleted. Destructive.","inputSchema":{"type":"object","properties":{"field_ids":{"description":"IDs of the fields to delete. Omit to delete every field on the target page.","items":{"type":"string"},"type":"array"},"page":{"description":"1-based page to scope the deletion to. Omit to target all pages.","type":"integer"}}},"annotations":{"destructiveHint":true},"wireType":"DELETE_FIELDS"}, From f05cda23f15c71bc0c22436906f125b74627a61b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20Andr=C3=A9-Micolon?= Date: Wed, 25 Nov 2026 09:43:04 +0000 Subject: [PATCH 12/12] chore: sync recipient-link error from the merged editor contract --- embed/embed-api.json | 8 +++++++- embed/etc/protocol.api.md | 4 ++-- embed/src/generated/contract.ts | 4 ++-- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/embed/embed-api.json b/embed/embed-api.json index f8e30dcc..9f5e56b3 100644 --- a/embed/embed-api.json +++ b/embed/embed-api.json @@ -1788,7 +1788,8 @@ "error_codes": [ "bad_request:no_document_loaded", "bad_request:invalid_value", - "bad_request:missing_required_fields" + "bad_request:missing_required_fields", + "forbidden:recipient_link_used" ], "tool": { "name": "simplepdf_embed_submit", @@ -2099,6 +2100,11 @@ "const": "forbidden:origin_not_whitelisted", "description": "The embedding origin is not allowlisted for this tenant, or is not the allowlisted origin the editor was loaded from. Allowlist it in the SimplePDF admin dashboard and let the embedding page's Referer reach the editor." }, + { + "type": "string", + "const": "forbidden:recipient_link_used", + "description": "The document was opened through a recipient link that has already been submitted (each link takes one submission), so this submit was refused and no submission was completed. The editor keeps the entered values and shows the end user a dialog saying so. Do not retry: the document owner reopens the link by deleting its submission, or shares a new one." + }, { "type": "string", "const": "forbidden:whitelist_required", diff --git a/embed/etc/protocol.api.md b/embed/etc/protocol.api.md index 70418136..75f34dbf 100644 --- a/embed/etc/protocol.api.md +++ b/embed/etc/protocol.api.md @@ -5,7 +5,7 @@ ```ts // @public (undocumented) -export const EDITOR_ERROR_CODES: readonly ["bad_request:batch_validation_failed", "bad_request:download_blocked", "bad_request:editor_not_ready", "bad_request:event_not_allowed", "bad_request:failed_to_load_document", "bad_request:field_not_found", "bad_request:invalid_dimensions", "bad_request:invalid_event_type", "bad_request:invalid_field_ids", "bad_request:invalid_field_type", "bad_request:invalid_page", "bad_request:invalid_signature_url", "bad_request:invalid_tool", "bad_request:invalid_value", "bad_request:missing_required_fields", "bad_request:no_document_loaded", "bad_request:page_not_found", "bad_request:page_out_of_range", "bad_request:plan_upgrade_required", "bad_request:read_only", "bad_request:signup_required", "conflict:editor_modified", "conflict:inspection_state_changed", "conflict:unmanaged_document", "forbidden:editing_not_allowed", "forbidden:origin_not_whitelisted", "forbidden:whitelist_required", "not_found:job", "not_found:job_expired", "resource:session_limit", "unexpected:internal_error"]; +export const EDITOR_ERROR_CODES: readonly ["bad_request:batch_validation_failed", "bad_request:download_blocked", "bad_request:editor_not_ready", "bad_request:event_not_allowed", "bad_request:failed_to_load_document", "bad_request:field_not_found", "bad_request:invalid_dimensions", "bad_request:invalid_event_type", "bad_request:invalid_field_ids", "bad_request:invalid_field_type", "bad_request:invalid_page", "bad_request:invalid_signature_url", "bad_request:invalid_tool", "bad_request:invalid_value", "bad_request:missing_required_fields", "bad_request:no_document_loaded", "bad_request:page_not_found", "bad_request:page_out_of_range", "bad_request:plan_upgrade_required", "bad_request:read_only", "bad_request:signup_required", "conflict:editor_modified", "conflict:inspection_state_changed", "conflict:unmanaged_document", "forbidden:editing_not_allowed", "forbidden:origin_not_whitelisted", "forbidden:recipient_link_used", "forbidden:whitelist_required", "not_found:job", "not_found:job_expired", "resource:session_limit", "unexpected:internal_error"]; // @public (undocumented) export const EXTRACTION_MODES: readonly ["auto", "ocr"]; @@ -175,7 +175,7 @@ export const OPERATIONS: readonly [{ readonly wire_type: "SUBMIT"; readonly method: "submit"; readonly description: "Submit the completed document through the editor's finalization flow. This is irreversible. Fails with bad_request:missing_required_fields when required fields are unfilled. Returns no data."; - readonly error_codes: readonly ["bad_request:no_document_loaded", "bad_request:invalid_value", "bad_request:missing_required_fields"]; + readonly error_codes: readonly ["bad_request:no_document_loaded", "bad_request:invalid_value", "bad_request:missing_required_fields", "forbidden:recipient_link_used"]; readonly is_agentic_tool: true; readonly has_output: false; }]; diff --git a/embed/src/generated/contract.ts b/embed/src/generated/contract.ts index 67c93887..f0ac8928 100644 --- a/embed/src/generated/contract.ts +++ b/embed/src/generated/contract.ts @@ -5,7 +5,7 @@ import type { METHOD_NAMES } from './bridge-vocabulary.js' export const LOCALES = ["fr", "en", "it", "de", "pt", "es", "ja", "nl"] as const export type Locale = (typeof LOCALES)[number] -export const EDITOR_ERROR_CODES = ["bad_request:batch_validation_failed", "bad_request:download_blocked", "bad_request:editor_not_ready", "bad_request:event_not_allowed", "bad_request:failed_to_load_document", "bad_request:field_not_found", "bad_request:invalid_dimensions", "bad_request:invalid_event_type", "bad_request:invalid_field_ids", "bad_request:invalid_field_type", "bad_request:invalid_page", "bad_request:invalid_signature_url", "bad_request:invalid_tool", "bad_request:invalid_value", "bad_request:missing_required_fields", "bad_request:no_document_loaded", "bad_request:page_not_found", "bad_request:page_out_of_range", "bad_request:plan_upgrade_required", "bad_request:read_only", "bad_request:signup_required", "conflict:editor_modified", "conflict:inspection_state_changed", "conflict:unmanaged_document", "forbidden:editing_not_allowed", "forbidden:origin_not_whitelisted", "forbidden:whitelist_required", "not_found:job", "not_found:job_expired", "resource:session_limit", "unexpected:internal_error"] as const +export const EDITOR_ERROR_CODES = ["bad_request:batch_validation_failed", "bad_request:download_blocked", "bad_request:editor_not_ready", "bad_request:event_not_allowed", "bad_request:failed_to_load_document", "bad_request:field_not_found", "bad_request:invalid_dimensions", "bad_request:invalid_event_type", "bad_request:invalid_field_ids", "bad_request:invalid_field_type", "bad_request:invalid_page", "bad_request:invalid_signature_url", "bad_request:invalid_tool", "bad_request:invalid_value", "bad_request:missing_required_fields", "bad_request:no_document_loaded", "bad_request:page_not_found", "bad_request:page_out_of_range", "bad_request:plan_upgrade_required", "bad_request:read_only", "bad_request:signup_required", "conflict:editor_modified", "conflict:inspection_state_changed", "conflict:unmanaged_document", "forbidden:editing_not_allowed", "forbidden:origin_not_whitelisted", "forbidden:recipient_link_used", "forbidden:whitelist_required", "not_found:job", "not_found:job_expired", "resource:session_limit", "unexpected:internal_error"] as const export type EditorErrorCode = (typeof EDITOR_ERROR_CODES)[number] export const FIELD_TYPES = ["TEXT", "SIGNATURE", "PICTURE", "CHECKBOX", "COMB_TEXT", "DROPDOWN", "RADIO"] as const @@ -239,7 +239,7 @@ export const OPERATIONS = [ wire_type: "SUBMIT", method: "submit", description: "Submit the completed document through the editor's finalization flow. This is irreversible. Fails with bad_request:missing_required_fields when required fields are unfilled. Returns no data.", - error_codes: ["bad_request:no_document_loaded", "bad_request:invalid_value", "bad_request:missing_required_fields"] as const, + error_codes: ["bad_request:no_document_loaded", "bad_request:invalid_value", "bad_request:missing_required_fields", "forbidden:recipient_link_used"] as const, is_agentic_tool: true, has_output: false, } /* Submit */,