@openartifactsai/runtime 0.0.0-stage → 0.23.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,915 @@
1
+ /**
2
+ * Capability contracts of the Open Artifacts page runtime.
3
+ *
4
+ * A type's page (an editor such as Design or Design System) never talks to its
5
+ * host directly. It asks `window.openartifacts.use(name)` for a capability
6
+ * namespace and calls the methods below. The host decides which capabilities a
7
+ * given viewer gets: `use()` resolves to `null` when a capability is not
8
+ * available for this view (read-only viewer, no host, unknown name).
9
+ *
10
+ * Every method is asynchronous and may reject with an {@link ArtifactError}.
11
+ */
12
+ import type { ImportFileResponse, SheetFrame, SheetWalkthrough, SheetReadAnswers, SheetReadRefusal, SheetReadRequest, SheetSendRequest, SheetSendResponse, WidgetRequest, WidgetResponse } from './sheet-api.js';
13
+ import type { DocCallAnswer, DocCallRequest, DocExportFormat, DocFrame, DocHistoryResponse, DocImportResponse, DocPaper, DocRestoreRequest, DocRestoreResponse, DocSessionResponse, DocTabResponse, DocVersionResponse } from './doc-api.js';
14
+ import type { ArtifactRequest, SelectionSnapshot, SelectionSnapshotItem } from '@openartifactsai/protocol';
15
+ import type { SampleCapability } from './sample.js';
16
+ export type { SelectionSnapshot, SelectionSnapshotItem };
17
+ /** Version of the capability contract described in this file. */
18
+ export declare const CONTRACT_VERSION = "1.8.0";
19
+ /** Machine-readable error codes a capability call may reject with. */
20
+ export type ArtifactErrorCode =
21
+ /** A write lost a race: at least one `ifMatch` hash no longer matches. */
22
+ 'conflict'
23
+ /** The viewer may not write (viewer or commenter role). */
24
+ | 'not_writer'
25
+ /** The capability exists but the viewer declined or was never granted it. */
26
+ | 'not_granted'
27
+ /** The request was malformed (bad path, too large, wrong shape). */
28
+ | 'invalid'
29
+ /** The file or resource does not exist. */
30
+ | 'not_found'
31
+ /** The host could not be reached or answered with an unexpected status. */
32
+ | 'unavailable'
33
+ /** A connector (`mcp`) call failed; see {@link McpErrorCode}. */
34
+ | McpErrorCode;
35
+ /** One path that failed an optimistic-concurrency check. */
36
+ export interface ConflictPath {
37
+ /** Artifact-relative path, e.g. `project/Main.dc.html`. */
38
+ path: string;
39
+ /** The hash the writer expected (`null`: expected the file to be absent). */
40
+ expected: string | null;
41
+ /** The hash currently stored (`null`: the file is absent). */
42
+ actual: string | null;
43
+ }
44
+ /** The error object every capability rejects with. */
45
+ export declare class ArtifactError extends Error {
46
+ readonly code: ArtifactErrorCode;
47
+ /** Present for `conflict`: every path whose `ifMatch` failed. */
48
+ readonly paths?: ConflictPath[];
49
+ /** Present when asking again later may succeed (a busy or timed-out connector). */
50
+ readonly retryable?: boolean;
51
+ constructor(code: ArtifactErrorCode, message: string, paths?: ConflictPath[], retryable?: boolean);
52
+ }
53
+ /** Type guard for {@link ArtifactError} that also works across realms (iframes). */
54
+ export declare function isArtifactError(value: unknown, code?: ArtifactErrorCode): value is ArtifactError;
55
+ /** A JSON value. */
56
+ export type JsonValue = null | boolean | number | string | JsonValue[] | {
57
+ [key: string]: JsonValue;
58
+ };
59
+ /** A JSON object. */
60
+ export type JsonRecord = {
61
+ [key: string]: JsonValue;
62
+ };
63
+ /** Metadata of one stored file. */
64
+ export interface FileEntry {
65
+ /** Lower-case hex SHA-256 of the file's bytes. */
66
+ sha256: string;
67
+ /** Size in bytes. */
68
+ size: number;
69
+ }
70
+ /** A listing of every file of the artifact, keyed by artifact-relative path. */
71
+ export type FileListing = Record<string, FileEntry>;
72
+ /** One file in a publish batch. */
73
+ export interface PublishFile {
74
+ /** Text content (UTF-8), or base64 when `encoding` is `base64`. */
75
+ content: string;
76
+ encoding?: 'utf8' | 'base64';
77
+ /**
78
+ * Optimistic-concurrency guard: the hash the writer last saw.
79
+ * `null` means "the file must not exist yet". Omit to write unconditionally.
80
+ */
81
+ ifMatch?: string | null;
82
+ }
83
+ /** A publish batch: `null` deletes the path. */
84
+ export type PublishBatch = Record<string, PublishFile | null>;
85
+ /** The result of a successful publish. */
86
+ export interface PublishResult {
87
+ /** New hash of every written path; `null` for deleted paths. */
88
+ hashes: Record<string, string | null>;
89
+ }
90
+ /** A change pushed by the host: written by someone else (agent, another tab). */
91
+ export interface FilesChangedEvent {
92
+ /** Path → new hash, or `null` when the file was deleted. */
93
+ changes: Record<string, string | null>;
94
+ /** Who made the change, when the host knows (`agent`, `owner`, `guest:<name>`). */
95
+ author?: string;
96
+ /**
97
+ * The change stream started again after it was down, with empty `changes`:
98
+ * changes made meanwhile were not heard, so a page that keeps files open
99
+ * compares the listing with what it holds.
100
+ */
101
+ resync?: boolean;
102
+ }
103
+ /** The `artifact` capability. */
104
+ export interface SystemCopyStatus {
105
+ state: 'current' | 'behind' | 'missing' | 'unavailable';
106
+ changed: number;
107
+ removed: number;
108
+ }
109
+ export interface ArtifactCapability {
110
+ /** Compare or refresh an installed design system from its recorded source. */
111
+ systemCopy?(namespace: string, action: 'status' | 'sync'): Promise<SystemCopyStatus>;
112
+ /** Stable artifact id. */
113
+ readonly id: string;
114
+ /** Current title as recorded by the host. */
115
+ title(): Promise<string>;
116
+ /** Lists every file with its hash. */
117
+ list(): Promise<FileListing>;
118
+ /** Reads a text file; rejects with `not_found` when absent. */
119
+ readText(path: string): Promise<string>;
120
+ /** Reads a file as bytes. */
121
+ readBytes(path: string): Promise<Uint8Array>;
122
+ /**
123
+ * Writes a batch atomically. Rejects with `conflict` (listing every stale
124
+ * path, nothing written) or `not_writer`.
125
+ */
126
+ publish(batch: PublishBatch): Promise<PublishResult>;
127
+ /**
128
+ * Subscribes to changes made by anyone else. The host suppresses echoes of
129
+ * this page's own publishes. Returns an unsubscribe function.
130
+ */
131
+ onChange(listener: (event: FilesChangedEvent) => void): () => void;
132
+ }
133
+ /** A stored upload. Pages reference it only by `url` (`/_blob/<id>`). */
134
+ export interface AssetRecord {
135
+ /** First 32 hex digits of the SHA-256 of the bytes. */
136
+ id: string;
137
+ /** Root-relative URL, always `/_blob/<id>`. */
138
+ url: string;
139
+ sizeBytes: number;
140
+ contentType: string;
141
+ }
142
+ /** The `assets` capability. */
143
+ export interface AssetsCapability {
144
+ /** Uploads bytes; identical bytes always produce the same record. */
145
+ upload(data: Blob, options?: {
146
+ name?: string;
147
+ }): Promise<AssetRecord>;
148
+ /** The largest file `upload` takes here, in bytes (since 1.8.0). Left out: 20 MB. */
149
+ readonly maxBytes?: number;
150
+ }
151
+ /** A byte count a host may give as an upload limit (`maxBytes`): a positive whole number. */
152
+ export declare function validByteLimit(value: unknown): value is number;
153
+ /** Roles, from most to least privileged. */
154
+ export type Role = 'owner' | 'editor' | 'commenter' | 'viewer';
155
+ /** The current viewer. */
156
+ export interface Viewer {
157
+ id: string;
158
+ name: string;
159
+ role: Role;
160
+ /** Who they are on a cloud host: a signed-in person, a link guest, an agent or an anonymous visitor. Unset locally. */
161
+ kind?: 'user' | 'guest' | 'agent' | 'anonymous';
162
+ /** Their address, on a cloud host that knows it. */
163
+ email?: string;
164
+ /** Their picture's URL, on a cloud host that knows it. */
165
+ avatar?: string;
166
+ }
167
+ /** The `user` capability. */
168
+ export interface UserCapability {
169
+ me(): Promise<Viewer>;
170
+ }
171
+ /** True when the role may change files and upload assets. */
172
+ export declare function canEdit(role: Role): boolean;
173
+ /** A request a page sends to the agent ("Send to agent", "Ask agent to fix"). */
174
+ export interface AgentRequest {
175
+ /** What the person asked for, in their words (already fenced if untrusted). */
176
+ text: string;
177
+ /** Short label for cards and logs, e.g. `Ask agent to fix`. */
178
+ title?: string;
179
+ /** Structured context: selection ids, labels, error text. Data, never instructions. */
180
+ context?: Record<string, unknown>;
181
+ /**
182
+ * The words the person typed, as typed, when the request is theirs: an app shows them as their message. `text` must
183
+ * start with them, else they are left out. A request the page wrote itself has none.
184
+ */
185
+ userText?: string;
186
+ /** What was selected when the person pressed Send, for an app to show beside their words (data). */
187
+ selectionSnapshot?: SelectionSnapshot;
188
+ }
189
+ /** How the request should arrive. */
190
+ export type AgentDelivery =
191
+ /** Start an agent turn now (falls back to queueing when the agent is away). */
192
+ 'send'
193
+ /** Only prefill the person's composer; never start a turn. */
194
+ | 'stage';
195
+ /** The outcome of {@link AgentCapability.send}. */
196
+ export interface AgentSendResult {
197
+ status: 'delivered' | 'queued' | 'staged' | 'failed';
198
+ /**
199
+ * The request's id: {@link AgentStatus.requests} says where it stands from here on, by this id. `status` is how the
200
+ * send went at the moment it answered; what became of the request after is read there. Left out by a host that does
201
+ * not follow requests.
202
+ */
203
+ id?: string;
204
+ /** Human-readable reason when `failed`. */
205
+ reason?: string;
206
+ /** With `delivered`: it was put in the agent's conversation for the person to send there. */
207
+ drafted?: true;
208
+ }
209
+ /** Whether an agent is reachable and working. */
210
+ export interface AgentStatus {
211
+ /** An agent can receive requests (it waits, or a harness can wake it). */
212
+ available: boolean;
213
+ /**
214
+ * The agent is at work: the artifact's owner session runs a turn that works on this artifact (from the moment it
215
+ * reads, makes or opens it, or takes a comment on it, before anything is written), or the agent changed this artifact
216
+ * a moment ago. A turn about something else leaves it `false`.
217
+ */
218
+ busy: boolean;
219
+ /** Display name, e.g. `Agent`. */
220
+ name: string;
221
+ /** false: an idle agent is not woken; what is sent waits until the person next talks to it. Left out: it is woken. */
222
+ wakesIdle?: boolean;
223
+ /**
224
+ * true: the agent asked the person something (a form, a question in the chat) and its work waits on the answer.
225
+ * It is still at work, so pages show that it waits on them rather than that it stopped. Left out: it does not.
226
+ */
227
+ waitingForPerson?: boolean;
228
+ /**
229
+ * How many requests sent about this artifact (by any page) still wait for the agent to take them. Left out when this
230
+ * cannot be told. A count says nothing of one request: read {@link requests} by the id the send answered.
231
+ */
232
+ queued?: number;
233
+ /**
234
+ * Where each request and comment thread sent about this artifact stands, by id ({@link AgentSendResult.id}; a
235
+ * thread's own id): `waiting` for the agent to take it, `taken` (the agent has it), `drafted` (in the agent's
236
+ * conversation for the person to send there), then `done` (the turn that took it ended), `stopped` or `failed`.
237
+ * Those not settled and those settled in the last minutes, oldest first. A page shows the state it reads here and
238
+ * works nothing out from `busy`, `queued` or the order of events. Left out by a host that does not follow requests.
239
+ */
240
+ requests?: ArtifactRequest[];
241
+ /** A place the agent asked open pages to bring into view a moment ago (since 1.7.0). Left out: none. */
242
+ shows?: AgentView;
243
+ }
244
+ /**
245
+ * A place the agent asks the open pages to show (`open-artifacts show`): artboards, a page, an area, or a few words
246
+ * inside one artboard. Names and words come from the agent: a page only looks them up.
247
+ */
248
+ export interface AgentView {
249
+ /** Differs with each request: a page acts on each value once, and not on the one it finds when it opens. */
250
+ n: number;
251
+ /** Artboards, by their paths under `project/` (at most 64). */
252
+ boards?: string[];
253
+ /** A page, by its id or its name. */
254
+ page?: string;
255
+ /** An area of the canvas, in canvas px. */
256
+ area?: {
257
+ x: number;
258
+ y: number;
259
+ w: number;
260
+ h: number;
261
+ };
262
+ /** With one artboard: up to three pieces of its text; the page frames the smallest element that shows them all. */
263
+ text?: string[];
264
+ /** With one artboard: open it on its own, filling the window. */
265
+ present?: true;
266
+ }
267
+ /** The `agent` capability. */
268
+ export interface AgentCapability {
269
+ send(request: AgentRequest, options?: {
270
+ deliver?: AgentDelivery;
271
+ }): Promise<AgentSendResult>;
272
+ status(): Promise<AgentStatus>;
273
+ onStatus(listener: (status: AgentStatus) => void): () => void;
274
+ }
275
+ /** One viewer (or the agent) present on the artifact. */
276
+ export interface Peer {
277
+ id: string;
278
+ name: string;
279
+ kind: 'person' | 'agent';
280
+ /** Whatever the peer last published with {@link RoomCapability.presence}. */
281
+ state: Record<string, unknown>;
282
+ }
283
+ /** Someone who has the artifact: its owner, or a person it is shared with. */
284
+ export interface Participant {
285
+ id: string;
286
+ name: string;
287
+ /** The artifact's owner. */
288
+ owner?: true;
289
+ }
290
+ /**
291
+ * An ephemeral message between the pages of one artifact (live strokes,
292
+ * drag previews, reactions). Never stored; a page that is not connected
293
+ * when it is sent never sees it.
294
+ */
295
+ export interface RoomMessage {
296
+ /** Peer id of the sender (see {@link RoomCapability.self}). */
297
+ from: string;
298
+ /** Free-form channel name chosen by the type, e.g. `gesture`. */
299
+ topic: string;
300
+ /** JSON payload, at most {@link ROOM_MESSAGE_MAX_BYTES} once serialized. */
301
+ data: JsonValue;
302
+ }
303
+ /** Largest serialized {@link RoomMessage.data} a host relays. */
304
+ export declare const ROOM_MESSAGE_MAX_BYTES = 16384;
305
+ /** The `room` capability. */
306
+ export interface RoomCapability {
307
+ /** This page's own peer id (its entry in {@link peers}). */
308
+ self(): Promise<string>;
309
+ /**
310
+ * Publishes (merges) this viewer's presence state; a `null` value removes
311
+ * a key. The `viewContext` key is what the agent receives before the
312
+ * viewer's next message.
313
+ */
314
+ presence(patch: Record<string, unknown>): Promise<void>;
315
+ peers(): Promise<Peer[]>;
316
+ onPeers(listener: (peers: Peer[]) => void): () => void;
317
+ /** Who has the artifact, present or not (names only). A host that keeps no such list leaves it out. */
318
+ participants?(): Promise<Participant[]>;
319
+ /** Relays an ephemeral message to every other page of the artifact. */
320
+ emit(topic: string, data: JsonValue): Promise<void>;
321
+ /** Subscribes to ephemeral messages from other pages. */
322
+ onMessage(listener: (message: RoomMessage) => void): () => void;
323
+ }
324
+ /** The `downloads` capability. */
325
+ export interface DownloadsCapability {
326
+ /** Saves a file. The local host takes a single file of up to 512 MB; other hosts may take less. */
327
+ save(file: {
328
+ name: string;
329
+ data: Blob;
330
+ }): Promise<{
331
+ savedTo?: string;
332
+ }>;
333
+ /**
334
+ * True when the host saves each file as this browser's own download rather than on a computer of its own (a cloud
335
+ * host, or the owner's Shell in a browser on another device than the computer that serves it): any role may then
336
+ * ask, the host decides whether the person may export, and there is no size limit but the browser's.
337
+ */
338
+ readonly browser?: boolean;
339
+ /**
340
+ * Where `browser` is true: resolves when the person may export now, else rejects with `not_writer` and the host's
341
+ * words. For an export that is not a file (a print): it follows the same switch. That keeps the product's own
342
+ * buttons consistent; it is no security boundary (a viewer can always print from the browser or take a screenshot).
343
+ */
344
+ check?(): Promise<void>;
345
+ }
346
+ /**
347
+ * A document path: an even number of segments alternating collection and
348
+ * document id (`elements/n-12`, `data/users/u1/idea`). Segments match
349
+ * `[A-Za-z0-9_.~:@+-]+` and are never `.` or `..`.
350
+ */
351
+ export type DbPath = string;
352
+ /** One stored document. */
353
+ export interface DbDocument {
354
+ path: DbPath;
355
+ data: JsonRecord;
356
+ }
357
+ /**
358
+ * A write's precondition: write only while the document is still the one the
359
+ * writer read. `ifMatch` is that document's sha256 (lowercase hex of its data
360
+ * as compact JSON, `JSON.stringify`, UTF-8: what the agent's tools call
361
+ * `sha256`), or `null` for "only while it does not exist". When one fails
362
+ * the whole batch is refused with `conflict`, its `paths` naming each
363
+ * document (`expected`, `actual`), and nothing is written. Omit it to write
364
+ * unconditionally.
365
+ */
366
+ export interface DbWriteGuard {
367
+ ifMatch?: string | null;
368
+ }
369
+ /** One write of a {@link DbCapability.write} batch. */
370
+ export type DbWrite =
371
+ /** Replaces the document (creating it when absent). */
372
+ ({
373
+ op: 'set';
374
+ path: DbPath;
375
+ data: JsonRecord;
376
+ } & DbWriteGuard)
377
+ /**
378
+ * Applies a JSON merge patch (RFC 7396): objects merge, arrays and
379
+ * scalars replace, `null` removes a key. An absent document starts empty.
380
+ */
381
+ | ({
382
+ op: 'update';
383
+ path: DbPath;
384
+ patch: JsonRecord;
385
+ } & DbWriteGuard)
386
+ /** Removes the document (a no-op when it is absent). */
387
+ | ({
388
+ op: 'delete';
389
+ path: DbPath;
390
+ } & DbWriteGuard);
391
+ /** Documents changed by someone else (agent, another page). */
392
+ export interface DbChangeEvent {
393
+ /** Path → the document's new data, or `null` when it was deleted. */
394
+ changes: Record<DbPath, JsonRecord | null>;
395
+ /** Who made the change, when the host knows (`agent`, `owner`, a peer id). */
396
+ author?: string;
397
+ /**
398
+ * The change's place in the host's order ({@link DbOrder}), when the host
399
+ * keeps one. Events reach a page in this order; write receipts may not.
400
+ */
401
+ epoch?: string;
402
+ seq?: number;
403
+ /**
404
+ * The first event of every event stream (each connect and reconnect), with
405
+ * empty `changes`: `epoch` and `seq` say where the host stood as the stream
406
+ * started. Changes up to it were sent before this stream, so a page that
407
+ * heard and read less (its stream was down) reads its documents again.
408
+ */
409
+ resync?: boolean;
410
+ }
411
+ /**
412
+ * Where a host's documents stand: `seq` counts the host's db change events
413
+ * since `epoch` began (a new epoch, such as after a restart, starts over).
414
+ * A write's receipt says the written documents are as of `seq`.
415
+ */
416
+ export interface DbOrder {
417
+ epoch: string;
418
+ seq: number;
419
+ }
420
+ /**
421
+ * A write's receipt: the host's order after the batch, and each written
422
+ * document as stored (`null`: absent), so a page shows what the host holds
423
+ * even when the host merged in a change it had not reported yet.
424
+ */
425
+ export interface DbReceipt extends DbOrder {
426
+ documents: Record<DbPath, JsonRecord | null>;
427
+ }
428
+ /** One collection's documents and, when the host keeps an order, where it stood when they were read. */
429
+ export interface DbListing extends Partial<DbOrder> {
430
+ documents: DbDocument[];
431
+ }
432
+ /** Limits every host enforces on the document store. */
433
+ export declare const DB_LIMITS: {
434
+ /** Writes in one batch. */
435
+ readonly maxWrites: 500;
436
+ /** Bytes of one document's JSON. */
437
+ readonly maxDocumentBytes: 262144;
438
+ /** Nesting depth of one document. */
439
+ readonly maxDepth: 32;
440
+ };
441
+ /** The `db` capability, granted to types whose manifest declares `store: "db"`. */
442
+ export interface DbCapability {
443
+ /** Reads one document; `null` when absent. */
444
+ get(path: DbPath): Promise<JsonRecord | null>;
445
+ /** Every document of one collection (`elements`, `data/users/u1/ideas`), sorted by path. */
446
+ list(collection: string): Promise<DbDocument[]>;
447
+ /** {@link list} with the host's {@link DbOrder} at the read, for pages that keep documents in sync. */
448
+ listing?(collection: string): Promise<DbListing>;
449
+ /**
450
+ * Applies a batch in order, all or nothing. Rejects with `invalid` (bad
451
+ * path, too large), `conflict` (an `ifMatch` no longer holds) or `not_writer`. The host never echoes the batch back
452
+ * through {@link onChange}. Resolves with a {@link DbReceipt}, when the host keeps an order.
453
+ */
454
+ write(writes: DbWrite[]): Promise<DbReceipt | void>;
455
+ /** Subscribes to changes made by anyone else. Returns an unsubscribe function. */
456
+ onChange(listener: (event: DbChangeEvent) => void): () => void;
457
+ }
458
+ /** Who wrote a comment message. */
459
+ export interface CommentAuthor {
460
+ kind: 'person' | 'agent';
461
+ name: string;
462
+ }
463
+ /** People who reacted to a message with one emoji. */
464
+ export interface CommentReaction {
465
+ emoji: string;
466
+ authors: CommentAuthor[];
467
+ }
468
+ /** One message of a thread. */
469
+ export interface CommentMessage {
470
+ id: string;
471
+ author: CommentAuthor;
472
+ text: string;
473
+ /** ISO 8601 time. */
474
+ at: string;
475
+ /** ISO 8601 time of the last edit. */
476
+ editedAt?: string;
477
+ /** Who the message asks, as the page named them (`agent` asks the agent). */
478
+ to?: string[];
479
+ reactions?: CommentReaction[];
480
+ /** The agent's reply to a message sent to it without asking it: it joined without being asked. */
481
+ joined?: boolean;
482
+ /** The message assigned the thread to this person; `null`: it left the thread unassigned. */
483
+ assignee?: string | null;
484
+ }
485
+ /** What {@link CommentsCapability.sendToAgent} takes besides the thread. */
486
+ export interface CommentSendOptions {
487
+ /**
488
+ * The newest message does not ask the agent (no `@agent`) but goes to it because it took part in the thread: it
489
+ * decides whether to answer, and the thread keeps its status.
490
+ */
491
+ unasked?: boolean;
492
+ /**
493
+ * The words the person typed in the newest message, as typed: the host keeps them only when that message is them
494
+ * (an `@agent` mention before them aside), and the agent reads them first. Not with `unasked`.
495
+ */
496
+ userText?: string;
497
+ /** What the message is on, at Send, for an app to show (data). Not with `unasked`. */
498
+ selectionSnapshot?: SelectionSnapshot;
499
+ }
500
+ /** What {@link CommentsCapability.edit} takes besides the text. */
501
+ export interface CommentEditOptions {
502
+ to?: string[];
503
+ }
504
+ /** What {@link CommentsCapability.reply} takes besides the text. */
505
+ export interface CommentReplyOptions extends CommentEditOptions {
506
+ /** Assigns the thread to this person with the reply (`null`: unassigns it). */
507
+ assignee?: string | null;
508
+ }
509
+ /** Where a thread stands with the agent. */
510
+ export interface CommentAgentState {
511
+ /** `pending`: sent, not yet read; `delivered`: the agent has it; `replied`: it answered. */
512
+ status: 'pending' | 'delivered' | 'replied';
513
+ /** With `delivered`: it was put in the agent's conversation for the person to send there. */
514
+ drafted?: true;
515
+ }
516
+ /** A comment thread. */
517
+ export interface CommentThread {
518
+ id: string;
519
+ /**
520
+ * The type's own anchor, serialized (a board stores a JSON object naming
521
+ * an element and an offset). Opaque to the host.
522
+ */
523
+ anchor: string;
524
+ /** Short human label of what the thread is about (`Note "Q3 goals"`). */
525
+ label: string;
526
+ /** Longer description of the anchored content, for the agent. */
527
+ detail?: string;
528
+ /** Extra structured location (coordinates, element ids), for the agent. */
529
+ location: JsonRecord;
530
+ status: 'open' | 'resolved';
531
+ /** Who resolved it, while it is resolved (when the host knows). */
532
+ resolvedBy?: CommentAuthor;
533
+ agent?: CommentAgentState;
534
+ messages: CommentMessage[];
535
+ }
536
+ /** What {@link CommentsCapability.create} takes. */
537
+ export interface CommentCreate {
538
+ anchor: string;
539
+ label: string;
540
+ detail?: string;
541
+ location?: JsonRecord;
542
+ /** The first message. */
543
+ text: string;
544
+ /** Who the first message asks. */
545
+ to?: string[];
546
+ /** Assigns the new thread to this person. */
547
+ assignee?: string;
548
+ }
549
+ /** Options of {@link CommentsCapability.move}. */
550
+ export interface CommentMoveOptions {
551
+ /** The anchor the viewer saw before dragging the pin: the move is refused (409) when the thread is no longer there. */
552
+ from?: string;
553
+ }
554
+ /** The `comments` capability, granted to types whose manifest declares `comments: true`. */
555
+ export interface CommentsCapability {
556
+ /** Every thread, open and resolved. */
557
+ list(): Promise<CommentThread[]>;
558
+ create(input: CommentCreate): Promise<CommentThread>;
559
+ reply(threadId: string, text: string, options?: CommentReplyOptions): Promise<CommentThread>;
560
+ /** Changes the text of one of the viewer's own messages. */
561
+ edit(threadId: string, messageId: string, text: string, options?: CommentEditOptions): Promise<CommentThread>;
562
+ /** Adds (`on`) or takes back the viewer's reaction to a message. */
563
+ react(threadId: string, messageId: string, emoji: string, on: boolean): Promise<CommentThread>;
564
+ setResolved(threadId: string, resolved: boolean): Promise<CommentThread>;
565
+ /**
566
+ * Re-anchors a thread (its content moved or was replaced). With `options.from` (a pin the person dragged), the
567
+ * server refuses the move unless the thread is still open at that anchor and the viewer started it or owns the
568
+ * artifact.
569
+ */
570
+ move(threadId: string, anchor: string, location?: JsonRecord, options?: CommentMoveOptions): Promise<CommentThread>;
571
+ /** Deletes one message, or the whole thread when `messageId` is omitted. */
572
+ remove(threadId: string, messageId?: string): Promise<void>;
573
+ /** Hands the thread to the agent (status `pending` until it reads it; `unasked` keeps the status). */
574
+ sendToAgent(threadId: string, options?: CommentSendOptions): Promise<CommentThread>;
575
+ /** Subscribes to the full thread list whenever anyone changes it. */
576
+ onChange(listener: (threads: CommentThread[]) => void): () => void;
577
+ }
578
+ /** Who made a version: a person on the page, the agent (any change on disk), or the system (the first version). */
579
+ export interface HistoryAuthor {
580
+ kind: 'person' | 'agent' | 'system';
581
+ id: string;
582
+ name: string;
583
+ }
584
+ /** One path a version changed. Paths are `project/…` files or `db/<collection>/<doc>` documents. */
585
+ export interface HistoryFileChange {
586
+ path: string;
587
+ op: 'added' | 'edited' | 'deleted';
588
+ }
589
+ /**
590
+ * One version: an author's burst of changes (it ends after a 30 s pause or
591
+ * 5 min), or a restore.
592
+ */
593
+ export interface HistoryVersion {
594
+ /** Numbers the versions from 1, never reused. */
595
+ n: number;
596
+ /** First and last change in it (ISO 8601). */
597
+ first: string;
598
+ at: string;
599
+ author: HistoryAuthor;
600
+ /** What it changed, sorted by path. */
601
+ files: HistoryFileChange[];
602
+ /** A restore: the version it brought back. */
603
+ restoredFrom?: number;
604
+ /** The newest version: what the files hold now. */
605
+ current?: true;
606
+ /** Changes made moments before by someone else that this version undid, at least in part. */
607
+ overwrote?: {
608
+ path: string;
609
+ n: number;
610
+ author: HistoryAuthor;
611
+ }[];
612
+ /** What someone who can edit wrote about this version (never empty). A version with a note takes no later changes. */
613
+ note?: string;
614
+ }
615
+ /**
616
+ * A notice to the viewer: someone else's version `n` undid part of their
617
+ * change to `path` (version `lost.n`). Bring it back with
618
+ * `restore(lost.n, [path])`; it goes away by itself then.
619
+ */
620
+ export interface HistoryNotice {
621
+ id: string;
622
+ at: string;
623
+ path: string;
624
+ n: number;
625
+ author: HistoryAuthor;
626
+ lost: {
627
+ n: number;
628
+ author: HistoryAuthor;
629
+ deleted?: true;
630
+ };
631
+ }
632
+ /** What {@link HistoryCapability.list} answers. */
633
+ export interface HistoryListing {
634
+ /** Newest first. */
635
+ versions: HistoryVersion[];
636
+ /** The viewer's notices, newest first. */
637
+ notices: HistoryNotice[];
638
+ /** The viewer may restore (owner or editor). */
639
+ canRestore: boolean;
640
+ }
641
+ /**
642
+ * One path before and after a version, for a diff. `null`: the file did
643
+ * not exist on that side. Contents are left out (`null`) when `binary` or
644
+ * `tooLarge`.
645
+ */
646
+ export interface HistoryFileDiff {
647
+ path: string;
648
+ n: number;
649
+ op: HistoryFileChange['op'];
650
+ before: string | null;
651
+ after: string | null;
652
+ binary?: true;
653
+ tooLarge?: true;
654
+ }
655
+ /** What {@link HistoryCapability.restore} answers. */
656
+ export interface HistoryRestoreResult {
657
+ /** The version the restore made (`null`: everything already matched). */
658
+ version: number | null;
659
+ /** The paths it wrote or deleted. */
660
+ changed: string[];
661
+ }
662
+ /** The history changed: `n` is the newest version (it may be one that grew). */
663
+ export interface HistoryChangeEvent {
664
+ n: number | null;
665
+ }
666
+ /**
667
+ * The `history` capability: the artifact's versions, read-only previews of
668
+ * them, and restores. A restore writes through the host's normal write path
669
+ * (every open page hears of it) and is a version of its own.
670
+ */
671
+ export interface HistoryCapability {
672
+ /** Every kept version (newest first) and the viewer's notices. */
673
+ list(): Promise<HistoryListing>;
674
+ /** Every path as it was right after version `n`, with its hash and size. */
675
+ files(n: number): Promise<FileListing>;
676
+ /** A text file (or a document's JSON) as it was right after version `n`; rejects `not_found`. */
677
+ read(n: number, path: string): Promise<string>;
678
+ /** The same as bytes. */
679
+ readBytes(n: number, path: string): Promise<Uint8Array>;
680
+ /** One path right before and right after version `n` (a path version `n` changed). */
681
+ diff(n: number, path: string): Promise<HistoryFileDiff>;
682
+ /**
683
+ * Brings version `n` back: every path (default) or only `paths`. Rejects
684
+ * `not_writer` for readers, `not_found` for a version no longer kept.
685
+ */
686
+ restore(n: number, paths?: string[]): Promise<HistoryRestoreResult>;
687
+ /** Dismisses one of the viewer's notices. */
688
+ dismissNotice(id: string): Promise<void>;
689
+ /**
690
+ * Sets the note on version `n` (`""` removes it; since 1.6.0). Rejects
691
+ * `not_writer` for readers, `not_found` for a version no longer kept.
692
+ */
693
+ note(n: number, text: string): Promise<void>;
694
+ /** Subscribes to new versions. Returns an unsubscribe function. */
695
+ onChange(listener: (event: HistoryChangeEvent) => void): () => void;
696
+ }
697
+ /** What {@link DocCapability.exportFile} asks for. */
698
+ export interface DocExportQuery {
699
+ format: DocExportFormat;
700
+ /** One tab (default: every tab). */
701
+ tab?: string;
702
+ paper?: DocPaper;
703
+ }
704
+ /** An exported file. */
705
+ export interface DocExportedFile {
706
+ name: string;
707
+ mime: string;
708
+ bytes: Uint8Array;
709
+ /** What the file could not carry over. */
710
+ notes: {
711
+ code: string;
712
+ message: string;
713
+ count?: number;
714
+ }[];
715
+ }
716
+ /**
717
+ * The `doc` capability, granted to types whose manifest declares `store: "doc"`. A page takes a writing session,
718
+ * reads tabs and sends its edits as ops on the revision it holds; every write anyone else makes arrives as a frame.
719
+ * A write is refused in the answer (`verdict: "deny"`), not by a rejection.
720
+ */
721
+ export interface DocCapability {
722
+ /** This page's writing session (`sess` is `null` for a reader) and the doc. */
723
+ session(): Promise<DocSessionResponse>;
724
+ /** A tab as the host holds it. */
725
+ read(tab: string): Promise<DocTabResponse>;
726
+ /** One member or a batch, on the session's behalf; `opId` makes it safe to send again. */
727
+ call(request: DocCallRequest): Promise<DocCallAnswer>;
728
+ /** A tab's kept versions, newest first. */
729
+ history(tab: string): Promise<DocHistoryResponse>;
730
+ /** A tab as it stood at a kept rev. */
731
+ version(tab: string, rev: number): Promise<DocVersionResponse>;
732
+ /** Brings a tab back as it was at `rev`, as a new write. */
733
+ restore(request: DocRestoreRequest): Promise<DocRestoreResponse>;
734
+ /** A .md, .docx or .pdf file as a new tab (`tabName`: its name). */
735
+ importFile(name: string, bytes: Uint8Array, tabName?: string): Promise<DocImportResponse>;
736
+ /** The doc, or one tab, as a file. */
737
+ exportFile(query: DocExportQuery): Promise<DocExportedFile>;
738
+ /** Subscribes to every write, tab and list change. Returns an unsubscribe function. */
739
+ onFrame(listener: (frame: DocFrame) => void): () => void;
740
+ }
741
+ /**
742
+ * Codes a connector call rejects with (on an {@link ArtifactError}, whose
743
+ * `retryable` says when asking again later may work):
744
+ *
745
+ * - `server_not_connected`: no connector by that name, or it could not be
746
+ * started or reached;
747
+ * - `needs_reauth`: the connector refused its credentials (HTTP 401/403);
748
+ * - `not_granted`: this viewer may not use connectors (only the owner may);
749
+ * - `rate_limited`: the connector is busy (HTTP 429);
750
+ * - `upstream_error`: the connector answered with a protocol error, failed,
751
+ * or did not answer in time;
752
+ * - `tool_error`, `consent_required`, `selection_required`, `not_in_manifest`,
753
+ * `not_declared`, `capability_disabled`, `capability_removed`,
754
+ * `server_unavailable`, `response_too_large`: reserved for hosts that
755
+ * mediate connectors further; pages handle them.
756
+ *
757
+ * A tool that ran and failed is not an error: it resolves with `isError`.
758
+ */
759
+ export type McpErrorCode = 'server_not_connected' | 'needs_reauth' | 'not_granted' | 'not_declared' | 'not_in_manifest' | 'consent_required' | 'selection_required' | 'rate_limited' | 'upstream_error' | 'tool_error' | 'capability_disabled' | 'capability_removed' | 'server_unavailable' | 'response_too_large';
760
+ /** Every {@link McpErrorCode}. */
761
+ export declare const MCP_ERROR_CODES: readonly McpErrorCode[];
762
+ /** One content item of a tool result (MCP `CallToolResult.content`). */
763
+ export type McpContent = {
764
+ type: 'text';
765
+ text: string;
766
+ annotations?: JsonRecord;
767
+ _meta?: JsonRecord;
768
+ } | {
769
+ type: 'image';
770
+ data: string;
771
+ mimeType: string;
772
+ annotations?: JsonRecord;
773
+ _meta?: JsonRecord;
774
+ } | {
775
+ type: 'audio';
776
+ data: string;
777
+ mimeType: string;
778
+ annotations?: JsonRecord;
779
+ _meta?: JsonRecord;
780
+ } | {
781
+ type: 'resource';
782
+ resource: {
783
+ uri: string;
784
+ mimeType?: string;
785
+ text?: string;
786
+ blob?: string;
787
+ _meta?: JsonRecord;
788
+ };
789
+ annotations?: JsonRecord;
790
+ _meta?: JsonRecord;
791
+ } | {
792
+ type: 'resource_link';
793
+ uri: string;
794
+ name: string;
795
+ title?: string;
796
+ description?: string;
797
+ mimeType?: string;
798
+ annotations?: JsonRecord;
799
+ _meta?: JsonRecord;
800
+ };
801
+ /** What a tool answered: the MCP `CallToolResult`, as the connector sent it. */
802
+ export interface McpToolResult {
803
+ content: McpContent[];
804
+ structuredContent?: JsonRecord;
805
+ /** The tool ran and failed; `content` says why. */
806
+ isError?: boolean;
807
+ _meta?: JsonRecord;
808
+ }
809
+ /** One tool of a connector (MCP `Tool`, the fields pages use). */
810
+ export interface McpToolInfo {
811
+ name: string;
812
+ title?: string;
813
+ description?: string;
814
+ /** JSON Schema of the tool's arguments. */
815
+ inputSchema?: JsonRecord;
816
+ }
817
+ /**
818
+ * Where a connector stands: `connected` (it answered, `tools` lists its
819
+ * tools), `needs_auth` (it refused its credentials), `error` (it could not
820
+ * be started or reached), `disconnected` (turned off in the configuration).
821
+ */
822
+ export type McpAuthStatus = 'connected' | 'needs_auth' | 'error' | 'disconnected';
823
+ /** One connector, as {@link McpCapability.listTools} lists it. */
824
+ export interface McpServerEntry {
825
+ /** Its name in the configuration, what {@link McpCapability.callTool} takes. */
826
+ server: string;
827
+ kind: 'connector';
828
+ authStatus: McpAuthStatus;
829
+ /** Present when `connected`. */
830
+ tools?: McpToolInfo[];
831
+ /** Why it is not connected. */
832
+ error?: string;
833
+ }
834
+ /** Options of {@link McpCapability.callTool}. */
835
+ export interface McpCallOptions {
836
+ /** Cancels the call (it rejects with the signal's reason). */
837
+ signal?: AbortSignal;
838
+ /** Milliseconds before the call fails with a retryable `upstream_error`. Default 120 000, at most 600 000. */
839
+ timeoutMs?: number;
840
+ }
841
+ /** Default and largest {@link McpCallOptions.timeoutMs}. */
842
+ export declare const MCP_CALL_TIMEOUT: {
843
+ readonly defaultMs: 120000;
844
+ readonly maxMs: 600000;
845
+ };
846
+ /**
847
+ * The `mcp` capability: calls tools of the connectors (MCP servers) the
848
+ * owner configured on their computer. Only the owner gets it.
849
+ */
850
+ export interface McpCapability {
851
+ /** Calls `tool` of connector `server`; rejects with an {@link McpErrorCode} (see there). */
852
+ callTool(server: string, tool: string, args: Record<string, unknown>, options?: McpCallOptions): Promise<McpToolResult>;
853
+ /** Every connector (or only `server`) and, for those connected, their tools. */
854
+ listTools(server?: string): Promise<{
855
+ servers: McpServerEntry[];
856
+ }>;
857
+ }
858
+ /**
859
+ * The `sheet` capability, granted to types whose manifest declares
860
+ * `store: "workbook"`. The page runs its own workbook engine and keeps it in
861
+ * step with the server's edit log: it loads the log with `read`, hears every
862
+ * later edit with `onFrame`, and saves its own with `send`.
863
+ */
864
+ export interface SheetCapability {
865
+ read<K extends SheetReadRequest['kind']>(request: Extract<SheetReadRequest, {
866
+ kind: K;
867
+ }>): Promise<SheetReadAnswers[K] | SheetReadRefusal>;
868
+ send(request: SheetSendRequest): Promise<SheetSendResponse>;
869
+ widget(request: WidgetRequest): Promise<WidgetResponse>;
870
+ /** Keeps a file for the agent to bring in (Import from Excel) and asks it to. */
871
+ importFile(file: Blob, name: string): Promise<ImportFileResponse>;
872
+ /** Subscribes to the stream's frames: a snapshot first on every (re)connect, then edits, clocks and widgets. */
873
+ onFrame(listener: (frame: SheetFrame) => void): () => void;
874
+ /**
875
+ * Subscribes to the walkthroughs the agent sends the person. Only one page of the owner's hears each, the one
876
+ * they used last; guests hear none. A walkthrough sent while no listener is attached is not kept here.
877
+ */
878
+ onWalkthrough(listener: (walkthrough: SheetWalkthrough) => void): () => void;
879
+ }
880
+ /** Every capability by name. */
881
+ export interface CapabilityMap {
882
+ artifact: ArtifactCapability;
883
+ assets: AssetsCapability;
884
+ user: UserCapability;
885
+ agent: AgentCapability;
886
+ room: RoomCapability;
887
+ downloads: DownloadsCapability;
888
+ db: DbCapability;
889
+ comments: CommentsCapability;
890
+ history: HistoryCapability;
891
+ doc: DocCapability;
892
+ mcp: McpCapability;
893
+ sheet: SheetCapability;
894
+ /**
895
+ * Asks the person's model (since 1.5.0; `null` on an older host, for a guest, or where the host serves no models).
896
+ * The page-facing `sample` function, `json` and `limits` on it, plus `state()` (see `sample.ts`).
897
+ */
898
+ sample: SampleCapability;
899
+ }
900
+ export type CapabilityName = keyof CapabilityMap;
901
+ /** The object installed at `window.openartifacts`. */
902
+ export interface OpenArtifactsRuntime {
903
+ /** Contract version, see {@link CONTRACT_VERSION}. */
904
+ readonly version: string;
905
+ /**
906
+ * Resolves the namespace of a capability, or `null` when this view may not
907
+ * use it. Results are memoized and frozen.
908
+ */
909
+ use<K extends CapabilityName>(name: K): Promise<CapabilityMap[K] | null>;
910
+ }
911
+ declare global {
912
+ interface Window {
913
+ openartifacts?: OpenArtifactsRuntime;
914
+ }
915
+ }