@kivacore/ui-pro-agent-canvas
v0.33.0
Published
A canvas an agent and a person share: markdown and HTML documents, spreadsheets, diagrams and live views of KIVA data in one panel, kept in KIVA docbooks, with a command library the agent drives as a CLI.
Readme
@kivacore/ui-pro-agent-canvas
A canvas that an agent and a person share. Its tabs are:
| Kind | What it is | How the agent reads and writes it |
| --- | --- | --- |
| doc_markdown | A text document in the Kiva UI Plate editor | Markdown |
| doc_html | A richer document in the same editor: lists, tables, colours, alignment | HTML |
| sheet | A spreadsheet (@kivacore/ui-pro-sheets) | Cells, formulas, CSV |
| deck | An editable slide deck (@kivacore/ui-pro-slidedeck) | Versioned deck JSON |
| diagram | A tree, org chart or mind map (@kivacore/ui-pro-diagram) | Node and edge operations |
| map | Interactive locations from coordinates or a KIVA source | Marker data, selected locations, source settings |
| view | The live records of a KIVA data source: grid, kanban, calendar, pivot, form | Settings, live grid rows and controls, database-backed saved views |
| page | A small React app the agent writes as files in its workspace, built in the browser and run in a sandboxed frame | Files in a folder |
| media | An image, a video, a sound or a PDF from a file, shown with the browser's own viewer and players | A file it shows (it cannot read it) |
| email | An email the agent drafts, in the Kiva UI email composer, for the person to send through one of their accounts | Recipients, subject and HTML body |
| message | An SMS or WhatsApp message the agent drafts, in the Kiva UI instant message composer, for the person to send | Channel, phone numbers and text |
| email_thread | Emails the person received, one message or a thread, as their mail program shows them, with Reply, Reply all and Forward | Gmail or Microsoft Graph JSON in; text out |
| chat | An SMS or WhatsApp conversation with one person, as chat bubbles, with Reply | Conversation JSON in; text out |
| web | A page of a website, shown live by a host with a browser of its own, such as a desktop app | Its address (the host drives the page) |
| app | One of the tenant's KIVA apps, such as a CRM, signed in as the person, as the KIVA shell shows it | Its slug and the route it is on |
It comes with a command library, so an agent can open the panel and work on everything in it from its shell, and it connects to KIVA docbooks: the agent lists them, opens a doc on the canvas and saves an item back to a docbook.
The package has three parts:
| Part | Import | What it is |
| --- | --- | --- |
| Canvas | createAgentCanvas() | The canvas itself: an in-memory object that holds the items. No React. |
| Panel | <AgentCanvas> | The React component that shows a canvas and lets the person edit it. |
| Commands | createCanvasCli() | The canvas as a command line (canvas doc read, canvas sheet write A1 ...) for an agent. No React. |
| Page runtime | @kivacore/ui-pro-agent-canvas/page-runtime | Builds a page's files into one HTML document with esbuild-wasm, and answers the page's data calls. No React. |
| Item icon | @kivacore/ui-pro-agent-canvas/item-icon | <CanvasItemIcon>: an item's icon as its tab shows it, for showing items elsewhere without loading the panel. |
The panel and the commands both work on the same canvas object. That is what keeps them in step: the agent's write shows up in the panel as it happens, and the agent's next read includes what the person typed.
A canvas lives as long as the object does, and is gone on reload. What must outlive it is saved to a docbook with canvas save. A data view holds only its settings: the records stay in KIVA. A page is kept as its files in the agent's workspace, and canvas new page --dir puts it back. A media file is the file in the workspace it came from, and canvas new media --file puts it back. An email or a message is a draft for the person to send: a host keeps it as readEmail or readMessage gives it.
Install
pnpm add @kivacore/ui-pro-agent-canvas @kivacore/ui-pro-sharedData views use the peer dependencies @kivacore/api-client, @kivacore/app-utils (0.22.6 or later) and @tanstack/react-query. An app that signs in with @kivacore/signin already has the API client.
The package follows the same styling contract as the other Kiva UI Pro packages: it ships Tailwind v4 class names and your app's Tailwind build generates the CSS.
/* your app's globals.css */
@import "@kivacore/ui-pro-sheets/styles.css";
@import "@kivacore/ui-pro-slidedeck/styles.css";
@import "@kivacore/ui-pro-diagram/styles.css"; /* only where a diagram is shown: it styles .react-flow */
@source "../node_modules/@kivacore/ui-pro-diagram/dist/**/*.js";
@source "../node_modules/@kivacore/ui-pro-agent-canvas/dist/**/*.js";
@source "../node_modules/@kivacore/ui-pro-shared/src/**/*.{ts,tsx}";Theme tokens (--background, --foreground, --primary, --border, --muted and the rest of the shadcn set) come from your app.
@kivacore/ui-pro-shared ships TypeScript source, so your bundler compiles the Kiva UI components the views use. With Vite, list the packages those components import in optimizeDeps.include, or the dev server finds them one page reload at a time. Use one copy of react, react-dom, @tanstack/react-query, @tanstack/react-table and @tanstack/react-virtual (resolve.dedupe).
Use
import { useMemo } from 'react';
import { AgentCanvas, createAgentCanvas, useAgentCanvasState } from '@kivacore/ui-pro-agent-canvas';
function Workspace() {
const canvas = useMemo(() => createAgentCanvas(), []);
const { open } = useAgentCanvasState(canvas);
return (
<div className="flex h-screen">
<Conversation className="min-w-0 flex-1" />
{open && (
<aside className="w-1/2 min-w-0 border-l">
<AgentCanvas canvas={canvas} />
</aside>
)}
</div>
);
}The panel fills its parent, so give the parent a bounded size.
Whether the panel is on screen is the host's decision. The canvas only records what was asked for: canvas.open() and canvas.close() set open, and so do the agent's canvas open and canvas close commands and the panel's close button. The host reads open and shows or hides its side panel.
The host may unmount the panel while it is closed, or keep it mounted and hidden. Both work: when the panel unmounts, each editor saves its content back to the canvas, and the agent can keep reading and writing while nothing is mounted.
<AgentCanvas> props
| Prop | Description |
| --- | --- |
| canvas | The canvas to show. Required. |
| client | The signed-in person's KIVA API client (RestApiClient, for example from useKivaClient() in @kivacore/signin). Data views fetch with it, and emails and messages are sent with it. Without it a view tab asks the person to sign in, and a draft cannot be sent. |
| closable | Show a close button, which calls canvas.close(). Default true. |
| onSave | Saves an item to its doc. With it, the menu of a tab that is kept in a docbook offers Save. Pass item => cli.run(['save', '--item', item.id]). |
| itemActions | The host's own entries for the menu of a tab, after Save and Download: item => [{ id, label, icon?, disabled?, onSelect }]. It is called for each tab as it renders, so an entry can follow the item, as a Pin that becomes Unpin. They show on a read-only canvas too. |
| recentItems, onOpenRecent, onClearRecent | Items that were on the canvas and can be put back, most recent first: [{ id, kind, title, icon?, color? }], with the host's own ids. They show under Recent in the New menu and on the empty canvas, and onOpenRecent(id) puts the chosen one back. The canvas does not keep them: the host does, from the removing event, and drops one once it is on the canvas again (see Keep what was removed). Recent shows only with onOpenRecent, and not on a read-only canvas. With onClearRecent, it ends with Clear Recent. With Recent enabled, the close dialog explains how to reopen the items and warns about unsaved docbook changes. |
| user | The signed-in person, { id, name, avatarUrl? }: the author of comments and tracked changes in an HTML document. |
| mapBasemaps | The basemaps a map view offers: built-in ones by id (satellite, terrain) or { id, label, leafletUrl, leafletAttribution }. The first is the one a map starts on. |
| readOnly | The person can look but not edit. The agent can still write. |
| locale | en (default) or tr. |
| labels | Replaces single pieces of text, for a language that is not built in. |
| theme | Colour mode of the spreadsheet grid: light, dark or auto (follows a .dark ancestor). |
| headerExtra | Extra controls at the end of the header. |
| captureScreenshot | Optional host callback that captures the visible tab panel and returns a PNG blob. Use it to supply native capture in Electron. |
| layout | panel (default) or phone. See On a phone. |
| itemSheetOpen, onItemSheetOpenChange | With layout="phone", whether the sheet of the item in front is open, for a host that opens it from a button of its own. Without itemSheetOpen the panel keeps it itself, and onItemSheetOpenChange still hears it open and close. |
| apps | Shows KIVA apps signed in as the person: { apiUrl, session, refresh, subscribe?, api?, actor?, open?, render?, icon?, webMcpOrigins? }. See KIVA apps. Without it an app's tab gives the app's address, to open it in the browser. |
| className | Class names for the panel's root element. |
The document editor, the spreadsheet and each kind of data view are separate chunks. Each loads the first time an item of its kind is shown.
Open a tab's menu with its chevron or by right-clicking the tab. Close closes that tab, Close All empties the tab strip, and Close Others keeps the chosen tab open and brings it to the front.
Double-click a tab or use the header's fullscreen button to expand the panel to the browser viewport. Repeat either action or press Escape to restore the panel. The tab menu offers Rename.
On a phone
layout="phone" lays the panel out for a phone held in one hand, where a thumb reaches the bottom of the screen and not its top:
- The items are a strip of tabs at the bottom, scrolled sideways, with New at its end. A tap on a tab brings its item to the front; the tab in front stays in view.
- The top names the item in front, with the agent's status,
headerExtraand the close button. - A tap on the tab in front opens its sheet from the bottom. It offers the same actions as the tab menu, including Close, Close All and Close Others. A host with a button of its own for it, such as one in a row at the bottom of the screen, opens it with
itemSheetOpen. - New opens a sheet with what the person can make and, with
onOpenRecent, the recent items.
Which layout to use is the host's call, for example layout={useIsMobile() ? 'phone' : 'panel'}. The editors are the same in both.
<AgentCanvas
canvas={canvas}
layout="phone"
closable={false}
itemSheetOpen={sheetOpen}
onItemSheetOpenChange={setSheetOpen}
/>Docbooks
A docbook is a folder of docs in KIVA. Give the commands the signed-in person's API client and the agent can work with them:
import { createCanvasCli, createDocbooksApi } from '@kivacore/ui-pro-agent-canvas';
const cli = createCanvasCli(canvas, { docbooks: () => (client ? createDocbooksApi(client) : null) });canvas docbook listandcanvas docbook ls <docbook>show the docbooks and what is in them.canvas docbook open <doc>opensdocumentasdoc_html,markdownasdoc_markdown,spreadsheetassheet,diagramasdiagram, andpresentationasdeck.canvas savewrites an item back to its doc, or to a new doc with--to <docbook>. Documents store markdown text or the editor's value, sheets store a packed workbook, and diagrams store the diagram object. A presentation stores the complete deck JSON, including embedded media, underdata.deckwithdata.docTypeset topresentation. Saving preserves other fields in the doc's data.- The agent can also manage docbooks and docs: rename, move, archive and restore them, create an empty doc, and delete. A delete needs the name again with
--confirm, and a docbook that is not empty needs--recursiveas well. The commands say to archive unless the person asked for a delete.canvas docbook shareandcanvas docbook doc shareshow who has access and give or take it (--with,--remove, by email, full name or id), andcanvas docbook userslists the people. - The canvas works on a copy. It does not join the live collaboration room that Workspace uses for a doc, so a save replaces what the doc held.
canvas saverefuses when the doc changed in KIVA after it was opened, unless--forceis given. - A doc opened as
doc_htmlkeeps the blocks this editor does not know (an embedded doc, say): they are written to the agent as<div data-node="...">and go back whole.
Screenshots
canvas screenshot takes a PNG of the tab in front, as the person sees it. Give the commands a folder to keep screenshots in, and a writeFile on each run, and the agent gets a file it can look at:
const cli = createCanvasCli(canvas, { screenshotDir: '/workspace/.tmp/screenshots' });
await cli.run(['screenshot'], { writeFile });
// Saved a screenshot of doc-1 "Q3 budget" (1280×720 px) to /workspace/.tmp/screenshots/q3-budget-20261205-201530.png.- Each screenshot is a file of its own, named after its tab and the local time.
--out <file.png>writes it elsewhere. - Without
screenshotDiror--out, the panel downloads it for the person. - The panel captures the tab with
captureScreenshotwhen the host gives it (a desktop app's own renderer, which draws embedded pages too), and in the browser otherwise.canvas.screenshot()gives the PNG to a host that takes one itself, andcanvas.downloadScreenshot()downloads one.
Blocks, tracked changes and comments
An HTML document has three things a markdown document does not, and each has commands:
- Blocks by id.
canvas doc_html read --blocksprints every top-level block with its id.canvas doc_html applytakes a batch ofinsert,replace,remove,moveandsetoperations on those ids, with content as HTML or as the editor's own JSON, and applies it as one step or not at all.canvas doc_html node <id>prints a block as that JSON. - Tracked changes.
--suggestonwrite,append,prepend,replaceandapplyturns the edit into suggestions (the Plate suggestion plugin): added and removed text stays visible until someone accepts or rejects it. They are worked out word by word, and only for the blocks that changed.canvas doc_html suggestions,acceptandrejectlist and resolve them. In HTML they read as<ins data-suggestion="...">and<del data-suggestion="...">. - Comments.
canvas doc_html comment add --on "<exact text>"anchors a thread on that text (the Plate comment plugin), andcomments,comment reply,comment edit,comment resolve,comment reopenandcomment removemanage the threads. In HTML the anchored text reads as<span data-comment="...">.
Pass user to <AgentCanvas> so comments and tracked changes carry the signed-in person as their author. The agent's are made in that person's name too: it acts as them, and KIVA stores a comment under whoever sent it.
A doc opened from a docbook brings its comment threads from KIVA, and canvas save sends back what changed since: new threads and replies, edits, resolved state and deletions. A comment someone else added in the meantime is left alone. Tracked changes are part of the document's content and are saved with it.
These commands need the document's editor on screen. They bring the document to the front and wait for it.
Slide decks
Create one with New → Slide deck or canvas new deck "Review". Pass a PowerPoint or deck JSON file with --file to populate it, for example canvas new deck "Review" --file review.pptx. Use canvas deck write --item <id> --file review.pptx to replace an existing deck in one undoable change. canvas deck read prints its current JSON and canvas deck write applies a replacement as one undoable change. The model stays available when its editor is unmounted. Use the File menu to download reusable deck JSON or a PowerPoint presentation.
In the deck editor, open Presentation templates to preview 16 five-slide business presentations in English. Choose a template to insert its slides after the current slide. A new blank deck adopts the template’s theme. An existing presentation keeps its own theme. You can undo the insertion in one step.
Open Slide layouts to insert a single slide in the current theme. The ten layouts include Agenda, Three columns, Milestone timeline, Key metric, Chart + takeaway, and Action plan. Double-click the chart or table to edit its data. Both remain editable in PowerPoint.
Save a new deck with canvas save --to <docbook>, then use canvas save for subsequent edits. Reopen it with canvas docbook open <doc-id>. To start directly in a docbook, run canvas docbook doc new presentation "Q3 review" --in <docbook> and open the returned doc ID. It starts with one empty slide. The docbook accepts up to 5 MB per save, including embedded images, audio and video. Use canvas save --dry-run (with --to for a new deck) to check the size before writing.
For collaborative edits, canvas deck selection identifies the slide on screen and its selected objects. Browse any deck with deck slides, deck slide <slideId> and deck object <slideId> <objectId>. Media object reads return metadata including MIME type and byte length. Use deck object <slideId> <objectId> --include-data for the original embedded file and video poster. Pass --item <itemId> to keep working on the same presentation as the person moves between tabs. deck apply takes a JSON array of field patches and checks each target's revision before committing the batch. deck undo <undoToken> reverses the batch and preserves intervening changes to other objects.
Diagrams
The diagram editor keeps one state for the page, so the panel mounts only the diagram in front. The others keep their content and load when their tab is shown. The diagram commands need the editor on screen, bring the diagram to the front and wait for it. The editor has no read-only mode: with readOnly the panel puts a pane over it.
Maps
A map tab can show customers, depots, delivery routes and sales territories together. Start with authored markers or a live KIVA source, then add named layers.
canvas new map "Dispatch hubs" --text '[{"id":"north","title":"North depot","lat":41.11,"lng":29.04,"description":"Handles overnight deliveries"}]'
canvas map markers set --item "Dispatch hubs" --file hubs.json
canvas new map "Customers" --source crm/customers --location-field location --title-field name
canvas map info --item Customers
canvas map rows --item Customers --offset 0 --limit 50
canvas map row customer-42 --item Customers
canvas map cell read customer-42 name --item Customers
canvas map rows --selected --item CustomersAuthored markers require a unique string id, a title, and numeric lat and lng in degrees. An optional description appears in the popup. Inline text, stdin and workspace files accept the same JSON array. map markers set validates the whole replacement before applying it. An empty array clears the map. Authored maps can be created and read without signing in.
Live maps use the panel’s authenticated client. map rows reads the loaded mapped records. --all and range reads follow the active query across server pages. map set changes field mappings, filter, sort or limit, and map reload refreshes the records. Click a marker and use map rows --selected to identify the location the person is looking at.
The host API exposes canvas.createMap({ title, markers }), canvas.createMap({ title, source: { app, dataSource, locationField } }), readMap, setMapMarkers, mapStatus, updateMapSource, reloadMap and runMapAction with rows, row and cell actions. readMap(id) returns the base markers or source settings together with any named layers. A host can keep those settings and pass them back to createMap to reopen the map. Selection is transient. The panel renders maps automatically, and hosts can also render <CanvasMap canvas={canvas} itemId={id} client={client} />.
For compatibility, canvas new view map and createView({ spec: { type: 'map', ... } }) create a root item with kind: 'map' and a map-… ID. Use the ID returned by creation. Existing view reads and settings commands still work on source maps. Hosts that switch on item kind should handle map explicitly.
The map uses Leaflet. It starts on a street map from Esri and offers the Kiva UI satellite basemap. Pass mapBasemaps to use tile sources of your own, for example ones you hold a key for. On a cross-origin isolated page (Cross-Origin-Embedder-Policy: require-corp) the tiles are fetched with CORS, so the tile server must send Access-Control-Allow-Origin.
Layers and GeoJSON
canvas new map "Sales coverage" --source crm/customers --location-field location --title-field name
canvas map layer add depots --name "Dispatch depots" --source ops/depots --location-field location
canvas map import geojson --layer routes --file delivery-routes.geojson
canvas map import geojson --layer territories --file sales-territories.geojson
canvas map layer list
canvas map layer hide territories
canvas map layer show territoriesThe original markers or source have the reserved ID base. Toggle them with map layer hide base or show base. The checkboxes on the map and the agent commands share visibility state. Each KIVA layer uses its own source query, field mappings and filter under the signed-in client. Hiding a layer retains its settings. map layer remove <id> removes a named layer.
Import accepts a FeatureCollection, a Feature or a geometry through --file, --text or stdin. Positions are longitude first, latitude second. Points, lines, polygons with holes, multipart geometries and GeometryCollections share one map. Features with null geometry remain in the dataset. A popup displays the feature’s title or name and optional description. The geometry definitions follow the GeoJSON specification.
An import replaces the contents of its target GeoJSON layer after validating every feature. Reimporting preserves its name, order and visibility. IDs are local to a layer. Numeric and string IDs are matched as strings. The importer uses feature.id, then properties.id, and assigns feature-1, feature-2, etc. in file order when IDs are missing. Supply explicit IDs for datasets that get reordered or edited.
map feature list --layer routesreturns a FeatureCollection including properties and coordinates.map feature upsert --layer routes --file changed-routes.geojsonupdates the supplied IDs and retains other features. Each upsert requires an ID.map feature remove route-42 --layer routesremoves one feature.map rows --selectedidentifies an open overlay popup bylayerIdandid. Ordinary row and field reads continue to address the base dataset.
Host methods include listMapLayers, addMapLayer, importMapGeoJSON, setMapLayerVisible, removeMapLayer and removeMapFeature. Pass 'upsert' as the fourth argument to importMapGeoJSON to merge by ID. The snapshot from readMap(id) includes named layers, their visibility and the base visibility override. Pass it to createMap to restore the composition. Live layer snapshots contain the query settings only.
Viewport and inspection
These commands use the map currently on screen. Add --item to target a map by ID or title.
canvas map viewport get
canvas map viewport set --bounds '{"west":28.95,"south":40.95,"east":29.15,"north":41.12}'
canvas map identify --limit 25
canvas map focus customer-42
canvas map focus east --layer territories
canvas map fit --layer routes
canvas map fitViewport commands, fit and focus return the actual displayed bounds, center, zoom and open popup as selected: { layerId, id } or null. Leaflet fits the requested rectangle into the available screen space, so the returned bounds can be wider or taller. Focus moves the camera to the feature. The original customer layer is base. Hide or show a layer explicitly to change which features participate in a fit.
Use west > east for a rectangle crossing the date line. For example, {"west":170,"south":-20,"east":-170,"north":20} spans 20 degrees. Supply date-line routes and polygons as GeoJSON parts split at the meridian.
map identify returns one entry per intersecting feature with its layer ID, feature ID, title and geometry type. Routes crossing the screen and territories enclosing it count. An area entirely inside a territory's hole is excluded. Use --layer to inspect one visible layer and --offset with --limit to page through matches. The default page size is 100. Each call reads the current viewport, including any pan or zoom since the last call.
Fit, focus and inspection use the features loaded into visible layers. Inspection reports coverage: "complete" for authored and GeoJSON layers and "loaded" for KIVA sources. The count and match total for each live layer cover its loaded, filtered markers. Use map rows --all to read the base source across server pages.
Hosts can call getMapViewport, setMapBounds, fitMap, focusMapFeature and identifyMapFeatures on the canvas controller. Map exports capture the last displayed camera. Popup selection is transient.
Styling, legends and aggregation
On a customer map with an orders point layer and a territories polygon layer, the agent can apply both customer encodings and a territory count scale.
canvas map style set --layer base --text '{"color":{"field":"status","categories":{"active":"#15803d","prospect":"#2563eb"}},"size":{"field":"revenue","breaks":[10000,50000],"radii":[4,8,13],"unit":"USD"}}'
canvas map style set --layer territories --text '{"color":{"countFrom":"orders","breaks":[1,10],"colors":["#eff6ff","#60a5fa","#1d4ed8"],"unit":"orders"}}'
canvas map legend
canvas map aggregate --layer orders --by-territory territories
canvas map aggregate --layer orders --by-territory territories --scope viewportStyle rules. Supply an entire layer style through --text, stdin or --file. Read the current rules with map info and pass null to clear a layer style. Category keys match values as strings. Select objects use their value, ID, label or name in that order. Unmapped categories and missing values have separate legend entries. Numeric bands start a new band at each break. The example uses radii of 4, 8 and 13 pixels for revenue below 10,000, from 10,000 up to 50,000, and at least 50,000. Supply one color or radius per band. Numeric strings are accepted. A hollow marker indicates a missing size value. Use color.field with breaks and colors to shade features from an existing numeric property such as order_count.
Styles read GeoJSON properties, authored marker properties, or fields fetched by the signed-in KIVA client with the active layer filter. A styled point layer shows individual circles. The on-map legend and map legend share the same symbols, units, per-band counts and data coverage. The CLI includes the visibility of each styled layer. Styles survive GeoJSON replacement and a readMap / createMap round trip.
Territory counts. Each source feature counts once per territory containing one of its points. Polygon holes and multipart territories are supported. A point on a shared boundary counts in both territories. The result lists each territory, including zeros, and reports unmatched features, features with multiple matching territories, and features without points. The layer total counts each source feature once. A hidden order layer can still supply counts to a visible territory layer.
Counts use the entire loaded layer by default and stay stable during pans and zooms. Explicit viewport scope includes only orders in the displayed bounds. Authored and imported layers report complete coverage. KIVA layers report loaded coverage for their filtered, loaded page. Unavailable or loading inputs yield null territory counts and the no-data color. Map snapshots store the rules and source settings. Live records are fetched with the current viewer's credentials.
The host methods are setMapStyle(itemId, layerId, styleOrNull), mapLegend(itemId, layerId?) and aggregateMap(itemId, layerId, { byTerritory?, scope? }).
Saving maps and reviewing location changes
canvas map export --item "Sales coverage" --out sales-coverage.map.json
canvas map open --file sales-coverage.map.json
canvas map feature propose customer-42 --lat 41.06 --lng 29.02
canvas map feature propose depot-7 --layer depots --lat 40.99 --lng 29.13map export prints a versioned JSON document or writes it to the workspace with --out. It stores the tab title, authored markers, GeoJSON, layer order and visibility, style rules, configured KIVA sources and their query settings. It also stores the selected basemap ID and the last displayed center, zoom and bounds. The viewer’s panel size determines the bounds at that center and zoom. A map exported before its first display uses the usual initial fit.
map open accepts a file, stdin or --text and returns the ID of a new map tab. Add --background to keep the current tab active. Live layers fetch through the viewer’s signed-in client. Tile URLs come from the host’s basemap configuration. Pending reviews belong to the original map session.
map feature propose targets a record in the visible KIVA layer named by --layer (default base). Matching records can be proposed by ID even outside the loaded page. The review shows the record, layer and old and proposed coordinates. Save applies the reviewed location in KIVA and refreshes the map. Cancel discards it. Review checks the active filter, field editability and original value again before saving. A read-only host permits inspection only. The update preserves other location properties, including the address.
Hosts can use canvas.exportMap(itemId), canvas.openMap(file) and canvas.proposeMapLocation(itemId, recordId, { lat, lng }, layerId?).
Data views
A view tab shows the records of one data source in a Kiva UI component, wired by the matching Kiva UI hook (useKivaDataGrid, useKivaKanban, useKivaCalendar, useKivaMapView, useKivaPivotGrid, useKivaPivotCalendar, useKivaFormView):
import { useKivaClient } from '@kivacore/signin';
<AgentCanvas canvas={canvas} client={useKivaClient()} />- The records are fetched in the browser with
client, as the signed-in person. A view shows what that person may see, and the agent's own access plays no part in it. - A grid, kanban or calendar only shows records unless the view was created with
--editable. A form shows a record, edits it or creates one, by its--mode.readOnlyon the panel turns every view into a display. - The panel reports back what each view shows: loading, the number of records, or the error (a data source or a field that does not exist, a request the API refused). The agent reads that with
canvas view info, andcanvas new viewwaits for it. - The views keep their fetched data in a TanStack Query cache that the panel owns, one per
client. Toasts go throughsonner, so mount its<Toaster>once in your app to see them.
Agent grid commands
Use canvas view state to inspect the mounted grid, including the page, columns, available fields, active filter, sort, grouping and saved view ID. Grid commands accept --item to target a particular canvas tab and return JSON.
canvas view rows
canvas view rows --selected
canvas view rows --offset 100 --limit 50
canvas view rows --all
canvas view row deal-42
canvas view cell read deal-42 amount
canvas view page 3
canvas view filter '{"combinator":"and","rules":[{"field":"stage","operator":"=","value":"won"}]}'
canvas view sort amount:desc,name
canvas view group stage
canvas view column hide amount
canvas view column show amount
canvas view column move amount 2
canvas view column remove close_date
canvas view column add close_dateThe agent reads record IDs and visible fields through the signed-in user's client. Range and all-row reads follow the grid's current filters, search and sort across server pages. They leave the displayed page in place. Offsets start at zero. Page numbers and visible column positions start at one. Use none to clear a live filter, sort or grouping. Column operations affect the grid layout. The data source owns the field definitions.
In a grid opened with --editable, the agent can propose values using a record ID from view rows and a field marked editable in view state. The record can be on any page of the filtered view.
canvas view cell set deal-42 amount 12500
canvas view cell set deal-42 name --text "Annual renewal"
canvas view cell read deal-42 amountThe value argument is JSON. Use --text for a literal string, or pass JSON through stdin or --file. Row and cell reads include pending edits. A pending cell also returns originalValue and pending: true. Setting it back to its original value removes that proposal. The person can open the change count in the grid to review the old and new values, then choose Save or Cancel for a record. Drafts belong to the mounted grid.
canvas view saved list
canvas view saved get <id>
canvas view saved switch <id>
canvas view saved create "Closed deals"
canvas view saved edit <id> --text '{"name":"Won deals"}'
canvas view saved edit <id> --current
canvas view saved delete <id>Saved views use the same KIVA resource as the kiva studio data-view commands. Creation captures the current layout, filter and sort. Edit accepts a JSON body via stdin, --text or --file. Use --current to save the current layout to an existing view. A read-only canvas permits inspection and navigation and blocks database changes. Hosts can use the same operations with canvas.runGridAction(itemId, action, signal?).
Records and aggregates in other views
canvas view rows, view row <id>, and view cell read <id> <field> also work in kanban, calendar, map and form tabs. Use --item to target a tab. On a kanban, calendar or map, view rows returns the loaded records. Add --all to fetch every matching record across KIVA pages, or use --offset and --limit for a range. These reads follow the active view query and field projection. Offsets count cards with a group, events overlapping the displayed period and matching the calendar filters, or records with map coordinates. Row and cell reads by ID use the same scope and can reach unloaded records. Map --selected reads the selected marker. A form exposes its visible fields and current draft values. Use the ID new for a create form.
canvas view rows --offset 100 --limit 50 --item Pipeline
canvas view row deal-42 --item Pipeline
canvas view cell set deal-42 stage --text won --item Pipeline
canvas view cell set new name --text "Annual renewal" --item "New deal"
canvas view aggregates --item "Sales by region"In editable kanban and calendar views, view cell set can propose changes to any matching card or event by record ID, including records on other pages. Proposed changes shows the original and proposed field values in the current tab. Save rechecks that the record matches the current filters and that the proposed fields still have their original values, then saves those fields together. Cancel discards that record’s proposals. If a check or save fails, the proposal stays available for review.
Use canvas view cells set to propose edits for several records in an editable grid, kanban or calendar. Give each record ID once with its own field values. The command accepts inline JSON, stdin, --text or --file. Hosts can send the same array through canvas.runViewAction(itemId, { type: 'cells-set', records }). The result contains one cell result per input field, in order.
canvas view cells set '[{"id":"deal-42","fields":{"stage":"won","amount":12500}},{"id":"deal-73","fields":{"amount":9000}}]' --item PipelineAll records must match the active view, and all fields must be visible and editable. If an entry fails validation, the existing drafts stay as they were. In the review, use a record’s Save or Cancel, or use Save all or Discard all for everything shown. A record with several field changes also has save and discard controls beside each field. When several submissions are pending, Save batch and Discard batch act on the fields in that submission. Saving multiple records rechecks their original values and sends the reviewed fields in one KIVA bulk update.
In edit and create forms, Apply to form puts the proposed values into the draft. The form's Save or Create button runs its normal validation and submission. Use map feature propose to review a change to a KIVA location. Pivot results are read-only.
view aggregates returns the measures and cells of either pivot view. A pivot grid includes row and column paths, numeric and formatted values, total flags, and whether the source-record limit was reached. A pivot calendar includes the active date and period, selected groups, and numeric values keyed by bucket and measure. A null group ID identifies the displayed total. Hosts can use canvas.runViewAction(itemId, action, signal?) for all seven view types.
Pages
A page tab runs a small React app that the agent wrote as files: entry.tsx, which renders into #root, and the files it imports. The command library builds it, so a host that wants pages gives createCanvasCli a page builder and a way to list a folder:
import { createPageBuilder } from '@kivacore/ui-pro-agent-canvas/page-runtime';
import esbuildWasmUrl from '@kivacore/ui-pro-agent-canvas/esbuild.wasm?url';
const cli = createCanvasCli(canvas, { pageBuilder: createPageBuilder({ wasmUrl: esbuildWasmUrl }) });
await cli.run(['new', 'page', 'Sales', '--dir', 'pages/sales'], {
listFiles: async dir => /* paths under dir, relative to it */ [],
readFile: async path => /* the file's text */ ''
});- The build runs in the browser with esbuild-wasm, whose 14 MB binary ships with the package as
esbuild.wasm; serve it from your own origin. It loads on the first build, not before. Libraries are not bundled: React 19, recharts, lucide-react, framer-motion, date-fns and clsx come from esm.sh, and Tailwind's browser build from jsDelivr. All of them allow loading from a cross-origin isolated page. - A page is created or replaced only when it builds. A build error comes back to the agent with its file, line and column, and nothing on the canvas changes.
- The panel runs the page in an
<iframe sandbox="allow-scripts">: a null origin, no storage, no access to the host page or its session. Its data calls (window.Docyrus.client, the dashboard code runtime's bridge) go over aMessageChannelthat the page's first script opens with a per-mount token, so a document the frame navigates to cannot use them. The panel performs them withclient, as the signed-in person. OnlyGET,POST,PUTandPATCHto paths under/v1/go through, checked on the parsed path, and never the sign-in, security or administration APIs (/v1/auth,/v1/oauth2,/v1/super,/v1/tenant/security).DELETEis refused with 405, and printing with 501. - The page's document carries a Content Security Policy: scripts only inline or from the CDNs of its import map and Tailwind, no
fetchbeyond them, no forms and no frames. - The panel reports back what the page does: uncaught errors, a library that failed to load, a root that stayed empty, and its console output.
canvas new pageandcanvas page updatewait for that and fail with the errors, andcanvas page logsprints the console.
Media files
A media tab shows a file as the browser shows it: an image whole within the panel (a click shows it at its own size), a video or a sound with the browser's player, a PDF in the browser's viewer. A file the browser cannot open, such as a video in a format it does not play, says so and offers its download. The tab's icon says what the file is.
The agent shows one with canvas new media --file <path>, which reads the file with the host's readFile. A host can show one itself, such as a file the person attached:
import { mediaFromFile } from '@kivacore/ui-pro-agent-canvas/core';
const item = canvas.findMedia(path) ?? canvas.createMedia({ media: mediaFromFile(name, bytes, path), by: 'user' });
canvas.open(item.id);- What a file is comes from its first bytes where they say, and otherwise from its name.
mediaFromFilethrows, saying what the canvas shows, for anything else. - A file is kept and shown only under the media type it was checked as, whatever its blob or its name said, so the panel never shows one as a web page. An image is an
<img>, so an SVG runs no script. A PDF is in an unsandboxed frame, because a sandboxed one gets no PDF viewer: its blob is alwaysapplication/pdf. - The canvas keeps the file as a
Blob(canvas.media(id).data) with the workspace path it came from, which a host can keep to bring it back.
Web pages
A web tab is a page of a website. The canvas keeps its address; showing it is the host's, because a browser does not let a page show most other sites inside it. A host with a browser of its own, such as an Electron app, draws the page with renderWeb, and reports where it goes:
const item = canvas.createWeb({ url: 'https://example.com/', by: 'user' });
<AgentCanvas
canvas={canvas}
renderWeb={(item, web) => <MyBrowser key={item.id} url={web.url} onNavigate={(url, title) => canvas.updateWeb(item.id, { url, title }, 'user')} />}
/>;renderWebdraws in the item's tab panel, which stays mounted while another item is in front, so the page keeps its state. It is called again when the address changes, with a newwebobject, including after the host's ownupdateWeb: a browser compares the address with the one it shows before it loads it.updateWeb(id, { url, title }, by)follows the page: another address counts as a change by whoever took it there, and the page's own title becomes the tab's, as in a browser.- Only an
http:orhttps:address is a web page;createWebandupdateWebrefuse any other. Until the page names itself, the tab is the site's name. - No command makes a web page: the host opens them, with tools of its own for the agent. A web page has no docbook, no selection and no download. Without
renderWebits tab gives the address, to open it in the browser.
KIVA apps
An app tab is one of the tenant's KIVA apps, such as a CRM, signed in as the person. The panel loads it as the KIVA shell loads an embedded app and answers it as the shell does: the app says it listens and is sent the person's access token and tenant (never the refresh token), asks again when its token runs out, may ask the host to make API calls for it, and reports the route it is on. The host gives the session with apps:
const { tokens, user } = useKivaAuth();
const client = useKivaClient();
<AgentCanvas
canvas={canvas}
apps={{
apiUrl: 'https://api.kiva.app',
session: () => (tokens ? { accessToken: tokens.accessToken, tenantId: user?.tenant?.id ?? null } : null),
refresh: async () => /* a fresh session */,
api: client,
webMcpOrigins: ['https://crm.kiva.app']
}}
/>;The optional webMcpOrigins list delegates the browser's tools permission to selected built-in app iframes. Supply exact URL.origin values from trusted host configuration, including any non-default port. The default is an empty list. Changing a mounted app's grant reloads its iframe at its current route. Hosts with a custom render manage WebMCP in their own renderer.
For cross-origin discovery, the embedded app registers tools with exposedTo: [shellOrigin]. The shell calls document.modelContext.getTools({ fromOrigins: [appOrigin] }) and selects tools whose origin matches the app origin and whose source window matches the iframe's contentWindow. Use tool.source ?? tool.window for that comparison. The WebMCP draft calls the property source, and Chrome 158 exposes it as window. The iframe is inside the canvas tab panel marked with data-canvas-item-id. Feature-detect the discovery and execution methods before offering them to the agent. WebMCP tool interface
canvas.createApp({ app: { slug, name, url }, path })opens an app at a route, andcanvas.updateApp(id, { path })sends it to another. The panel sends the app there, and follows the app to the routes it reports (actorsays who took it there).- The app boots with
embedded=true,apiUrl,themeandlangon its address, which is loaded once; later changes of theme and language go to it as messages, so it keeps its place. - Without
renderthe panel shows the app in a frame. An app trusts the host it is framed by only on a KIVA host (https://*.kiva.apporhttps://*.docyrus.app), so elsewhere giverenderwith a browser of the host's own, such as an Electron<webview>: it loadsframe.srconce, passes what the app sends toframe.receive, givesframe.connecta way to send to the app, callsframe.loaded()each time the app's page loads, andframe.moved(address)when its page goes to another address, so the canvas follows an app that does not report its route. Pass and send messages only while the page is the app's (frame.origin): a page of another site must not get the person's session. icon(app)draws an app's icon as KIVA shows it, its logo or its icon on its colour, at the size of a tab's icon. The app's tabs show it in place of the app icon, on a phone too, until the person picks an icon of their own for the tab;nullkeeps the app icon.createAppsApilists each app with what it takes (icon,colorandlogoonKivaAppInfo), and the host draws it, as the KIVA shell's app avatar does.canvas.notifyApp(id, notification)hands an app one of the person's notifications that is for it, as the KIVA shell does (thenotificationmessage an app hears withuseKivaHostNotification). The app is sent it once it is signed in, so a tab opened for the notification, or shown only later, gets it too.KivaAppInfo.idis the app's id in the tenant, which a notification for it names astenant_app_id.createAppBridgeis the bridge on its own, for a host that shows apps somewhere other than the panel.- An app has no docbook, no selection and no download. Give the commands the tenant's apps with
createCanvasCli(canvas, { apps: createAppsApi(client) }), and the agent lists them and opens one withcanvas app list,canvas app open <app> --path <route>,canvas app go <route>andcanvas app read. AddcanvasAppInstructions()to its instructions too.
Emails and messages
The agent drafts an email or an SMS or WhatsApp message, and the person sends it. There is no command that sends: the agent writes the draft with canvas new email or canvas new message, and the person reads it in the composer, picks the account to send from, changes what they like and presses Send. The composer is Kiva UI's (EmailComposer with useKivaEmailComposer, and InstantMessageComposer with useKivaInstantMessageComposer), and it sends with client, as the person:
| Draft | Accounts | Sent through | Scope the token needs |
| --- | --- | --- | --- |
| Email | GET /v1/messaging/email/accounts: the person's connected Google and Microsoft mailboxes, and the tenant's accounts they may use | POST /v1/messaging/email/accounts/{id}/send | Messaging.Email.Send |
| SMS | GET /v1/messaging/sms/accounts | POST /v1/messaging/sms/accounts/{id}/send | Messaging.Sms.Send |
| WhatsApp | GET /v1/messaging/whatsapp/accounts | POST /v1/messaging/whatsapp/accounts/{id}/send | Messaging.Whatsapp.Send |
- Listing the accounts needs
Messaging.Read.All, whichRead.Allincludes. Sending needs the scope in the table, which no broader scope includes: add it to the host's OAuth client and to the scopes it signs in with. A token without it gets a 403, and the panel asks the person to sign out and sign in again. - The agent can suggest the account with
--from(an email address, or an SMS or WhatsApp account's name). Without one the composer picks the person's first account. With more than one SMS or WhatsApp account, the panel offers them above the message. - What the agent writes is checked: every address must be one, and phone numbers must be in international form (
+905321234567; spaces, dashes and a leading00are tidied). HTML is reduced to formatting, links and images, without scripts, event handlers, frames, forms or styles that load anything, because the composer puts it into the page. Plain text becomes paragraphs. - What the person types is kept as they typed it, and the agent's next read has it.
- Once sent, the draft records when, from which account, and which recipients the service took and refused (
sentincanvas email read), and it no longer changes, for the agent or the person. - Download saves an email as an
.emlfile marked unsent, which a mail program opens as a draft, and a message as text. - A draft is not kept in a docbook.
Received emails and conversations
The agent shows the person what they received: canvas new email_thread an email or a thread from their mailbox, canvas new chat an SMS or WhatsApp conversation. It hands over the JSON it read as it came, and the canvas reads:
| Item | Input |
| --- | --- |
| Email thread | A Gmail message read with format=full or a Gmail thread (users/me/threads/<id>); a Microsoft Graph message, or { "value": [...] } of the messages of a conversation; or { "subject", "messages": [{ "id", "from", "to", "cc", "date", "subject", "html" or "text", "attachments" }] }. |
| Conversation | { "channel", "contact": { "name", "phone" }, "account", "messages": [{ "id", "direction": "in" or "out", "at", "text", "status", "media" }] }; a WhatsApp Cloud API webhook payload, or a list of them; or a Twilio list of messages. |
Either may come in the { data } that kiva --json prints, and in the connector's answer that kiva connect curl prints within it.
- A thread shows its subject and its messages oldest first, the latest open and the others as a line each. Each body is shown in a frame of its own,
sandbox="allow-same-origin allow-popups allow-popups-to-escape-sandbox"without scripts, with a Content Security Policy that loads nothing from the web: the email keeps its own styles and nothing in it runs. Images from the web stay hidden, so a tracking pixel does not report the opening, until the person presses Show images. Links open in a new tab, without access to the page. - The HTML is cleaned before it is kept, too: scripts, frames, forms, event handlers,
javascript:links,<base>,<meta>and stylesheets from elsewhere go. Inline images (cid:) are not shown, and attachments are listed by name: their files stay in the mailbox. - Reply, Reply all and Forward open an email draft (see Emails and messages) with the original quoted, sent from the mailbox the thread was read from (
--account). Reply all leaves the person's own address out, and a reply to a message the person sent goes to its recipients. The agent drafts one withcanvas email_thread reply, with its text above the quote. - A conversation shows the contact's messages on the left and the account's on the right, by day, with media as a card (an image shows when its URL is
https:or adata:image), and how far each sent message got. Reply opens a message draft on the same channel, to the contact; the agent drafts one withcanvas chat reply. canvas email_thread readandcanvas chat readprint them as text for the agent, andaddadds messages that came in since: one the item has already, by id, is left out, and a conversation takes its newer status. What they say is written by others: the agent is told to treat it as data, not instructions.- A thread holds up to 100 messages and a conversation 500. Neither is kept in a docbook: the mailbox and the messaging service keep them.
Give it to an agent
createCanvasCli(canvas) turns the canvas into a command line. run takes the arguments and returns { stdout, stderr, exitCode }. It never throws.
import { canvasAgentInstructions, createCanvasCli } from '@kivacore/ui-pro-agent-canvas/commands';
const cli = createCanvasCli(canvas);
await cli.run(['new', 'doc', 'Launch plan'], { stdin: '# Launch plan\n\nShip in March.\n' });
await cli.run(['doc', 'replace', '--old', 'March', '--new', 'April']);
await cli.run(['sheet', 'write', 'A1', 'Region', 'Planned', 'Actual']);Register run as a command in whatever runs the agent's shell. With a shell that takes host commands of the form ({ argv, stdin, cwd, files }) => Promise<{ stdout, stderr, exitCode }>, that is one entry:
const hostCommands = {
canvas: ({ argv, stdin, cwd, files }) => cli.run(argv, {
stdin,
readFile: path => files.readFile(resolve(cwd, path)),
writeFile: (path, data) => files.writeFile(resolve(cwd, path), data)
})
};Here resolve stands for whatever turns the path the agent typed into one your file system accepts. readFile and writeFile are optional. They let the agent pass --file notes.md and --out budget.xlsx. Without them the agent pipes content in and out, which covers everything except binary workbook files.
Add canvasAgentInstructions() to the agent's instructions. It explains when to use the canvas and how to work beside a person who edits it too, and it points the agent at canvas --help for the command reference, so the two cannot drift apart.
Commands
canvas --help lists every command and canvas <command> --help shows its options and examples. In short:
| Command | What it does |
| --- | --- |
| canvas | List the items, which one is in front, what the person selected, and whether they changed anything since the agent last read it. |
| canvas open [item], canvas close, canvas show <item> | Show or hide the panel. |
| canvas screenshot [--out <file.png>] | A PNG of the tab in front, as the person sees it. Written to --out, or to a file of its own in screenshotDir, and the command prints where; on a host that gives neither, downloaded for the person. Open the tab before running the command. Use the desktop app for embedded pages, reports, media players, or images and map tiles the browser cannot access. |
| canvas new doc_markdown [title], new doc_html, new sheet, new diagram | Create an item. A document or sheet is filled from stdin, --file or --text. A sheet takes CSV, TSV, JSON or a workbook file. doc is short for doc_markdown. |
| canvas new map [title] | Plot marker JSON from stdin or --file, or pass --source <app>/<data_source> for live records. |
| canvas new view <type> <app>/<data_source> [title] | Show a data source as a grid, kanban, calendar, pivot, pivot-calendar or form. Options name the fields to use (--group-by, --date-field, --rows, --measure and so on), a --filter, a --sort and a --limit. |
| canvas rename, canvas remove, canvas selection | Manage items and read the person's selection. |
| canvas deck selection, slides, slide, object | Read the live selection, presentation order, slide properties or a complete object. |
| canvas deck apply, undo | Apply revision-checked edits or reverse a batch by its token. |
| canvas doc read, outline | Read a markdown document: all of it, one --section, or --lines 10:40. |
| canvas doc write, append, prepend, insert, replace, remove, clear | Edit a document: the whole of it, one section, a line position, or an exact piece of text. --dry-run prints the lines that would change and changes nothing. |
| canvas sheet info, read, find | Read a workbook: a grid with cell addresses, or CSV, TSV, JSON and markdown. |
| canvas sheet write, append, clear | Write values and formulas. |
| canvas sheet style, width, height, freeze, merge, unmerge, sort | Format and arrange. canvas sheet style [range] without formatting options prints the formatting the cells have. |
| canvas sheet rows, cols, tab, chart | Rows, columns, worksheets and charts. |
| canvas sheet export, undo, redo, call | Save a file, step through history, and reach the rest of the spreadsheet API. |
| canvas doc_html read, outline, write, append, prepend, replace, clear | Read and edit an HTML document as HTML, one block on a line. --suggest makes an edit a tracked change. |
| canvas doc_html read --blocks, apply, node | Work on blocks by id: a batch of operations, and a block as the editor's JSON. |
| canvas doc_html suggestions, accept, reject | List tracked changes and resolve them. |
| canvas doc_html comments, comment add, reply, edit, resolve, reopen, remove | Read and write comment threads anchored on text. |
| canvas diagram read, apply, add, update, remove, connect, disconnect, clear | Read a diagram as a tree with ids, and change it. read --layout prints positions, sizes and looks. apply takes a batch of JSON operations and is one step, and apply --dry-run checks the batch without changing anything. |
| canvas docbook list, ls, search, new, open | Browse the person's docbooks and open a doc on the canvas. |
| canvas docbook rename, move, archive, restore, delete, share | Manage a docbook, and who it is shared with. |
| canvas docbook users | List the people to share with. |
| canvas docbook doc new, rename, move, archive, restore, delete, share | Manage a doc without opening it. new creates an empty one. |
| canvas save | Save an item to its doc, or to a new doc with --to <docbook>. |
| canvas view info, set, reload | Print a view's settings and what it shows, change the settings, fetch the records again. |
| canvas new page [title] --dir <folder>, canvas page update | Build a page from a folder of files and show it, or build it again. A page that does not build changes nothing. Both wait for the page to run and fail with its errors. |
| canvas page info, logs | Print what a page is built from and whether it runs, and its console output. |
| canvas new media [title] --file <path> | Show the person an image, a video, a sound or a PDF from a file. The same file again shows it as it is now, in its own tab. |
| canvas new email [title], canvas email read, set | Draft an email (--to, --cc, --bcc, --subject, --from, the body from stdin, --file or --text), print it as JSON with whether it was sent, and change it. |
| canvas new message [title], canvas message read, set | Draft an SMS or WhatsApp message (--channel, --to, --from, the text), print it, and change it. |
| canvas new email_thread [title], canvas email_thread read, add, reply | Show received emails from Gmail or Graph JSON (--account names the mailbox), print them as text, add newer ones, and draft a reply (--all, --forward --to, --message). |
| canvas app list, open, go, read | List the tenant's KIVA apps, open one in a tab at a route, send it to another, and print where it is. Only with apps on createCanvasCli. |
| canvas new chat [title], canvas chat read, add, reply | Show an SMS or WhatsApp conversation (--channel, --contact, --name when the JSON does not say), print it, add to it, and draft a reply. |
Reads print content to stdout, so they compose with a shell: canvas doc read > notes.md, canvas sheet read --format csv | head. Writes print one line that says what changed. Errors go to stderr and say what to do next. The exit code is 1 when a command failed and 2 when it was malformed.
Pass { name: 'kiva-canvas' } to createCanvasCli to install the command under another name. The help, the errors and canvasAgentInstructions('kiva-canvas') follow it.
Use the canvas from code
Everything the commands do goes through the canvas object, which you can call directly.
const canvas = createAgentCanvas();
const doc = canvas.createDocument({ title: 'Plan', markdown: '# Plan' });
canvas.writeDocument(doc.id, '# Plan\n\nShip in April.');
canvas.readDocument(doc.id);
const sheet = canvas.createSheet({ title: 'Budget' });
canvas.editSheet(sheet.id, (workbook) => {
workbook.getActiveSheet().setValues(0, 0, [['Planned', 'Actual'], [12000, '=A2*1.1']]);
});
canvas.workbook(sheet.id).getActiveSheet().getValue(1, 1);
const view = canvas.createView({ spec: { type: 'kanban', app: 'crm', dataSource: 'deals', groupBy: 'stage' } });
canvas.updateView(view.id, { filters: { combinator: 'and', rules: [{ field: 'owner', operator: '=', value: 'me' }] } });
canvas.viewStatus(view.id); // { state: 'ready', records: 42 }, or null while the view is not on screen
const email = canvas.createEmail({ email: { to: '[email protected]', subject: 'Review', body: 'Hi Ada,\n\nCan we move it?' } });
canvas.updateEmail(email.id, { cc: '[email protected]' });
canvas.readEmail(email.id); // { to, cc, bcc, subject, body, from, sent: null until the person sends it }
canvas.on(event => console.log(event.type));canvas.workbook(id) is the Workbook from @kivacore/ui-pro-sheets/engine, so its whole API is available.
Keep what was removed
The canvas forgets an item once it is removed. Just before, it sends removing, while the item's content can still be read, so a host can keep what brings it back and pass it to the panel as recentItems:
canvas.on((event) => {
if (event.type !== 'removing') return;
const { item } = event;
if (item.source) keep(item, { docId: item.source.docId }); // opens from its docbook again
else if (item.kind === 'sheet') keep(item, { workbook: canvas.workbook(item.id) }); // stays usable once removed
else if (item.kind === 'view') keep(item, { spec: canvas.viewSpec(item.id) });
else if (item.kind === 'diagram') keep(item, { data: canvas.readDiagram(item.id, 'user') });
else if (item.kind === 'page') keep(item, { page: canvas.page(item.id) });
else if (item.kind === 'media') keep(item, { path: canvas.media(item.id).path }); // or the file itself: canvas.media(item.id).data
else if (item.kind === 'web') keep(item, { url: canvas.web(item.id).url }); // back with canvas.createWeb({ url })
else if (item.kind === 'app') keep(item, { app: canvas.app(item.id) }); // back with canvas.createApp({ app, path: app.path })
else if (item.kind === 'email') keep(item, { email: canvas.readEmail(item.id, 'user') }); // back with canvas.createEmail({ saved })
else if (item.kind === 'message') keep(item, { message: canvas.readMessage(item.id, 'user') }); // back with canvas.createMessage({ saved })
else if (item.kind === 'email_thread') keep(item, { thread: canvas.readMailThread(item.id, 'user') }); // back with canvas.createMailThread({ saved })
else if (item.kind === 'chat') keep(item, { chat: canvas.readChat(item.id, 'user') }); // back with canvas.createChat({ saved })
else keep(item, { content: canvas.readDocument(item.id, 'user'), discussions: canvas.discussions(item.id) });
});Read what you need in the listener itself: by the time anything asynchronous runs, the item is gone. A workbook object stays usable after its item is removed, so it can be packed (packWorkbook of @kivacore/ui-pro-sheets/io) afterwards. removed follows removing, once the item is off the canvas.
Icons and colours
The person gives a tab an icon and a colour from its menu, with Icon and color. Each item carries them as icon and color, each null for the default: the kind's icon, in the colour of the tab's text. Code sets them too:
canvas.setAppearance(doc.id, { icon: 'rocket', color: 'blue' }, 'user');
canvas.setAppearance(doc.id, { color: null }, 'user'); // the default colour again; the icon staysThe names are in CANVAS_ITEM_ICONS and CANVAS_ITEM_COLORS, and another name is refused. A change sends restyled. They are how the tab looks, not part of the item: the item does not become unread or unsaved, and a docbook does not keep them. A host that brings items back, as a list of recent or pinned items does, keeps them with the rest and sets them again.
To show an item elsewhere as its tab shows it, use <CanvasItemIcon kind icon color className />. It is also on its own entry, @kivacore/ui-pro-agent-canvas/item-icon, which does not load the panel.
Who changed what
Changes made through these methods count as the agent's, unless `by: 'u
