@open-artifact/runtime 0.0.0-stage → 0.2.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,629 @@
1
+ /**
2
+ * Capability contracts of the Open Artifact 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.openartifact.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
+ /** Version of the capability contract described in this file. */
13
+ export declare const CONTRACT_VERSION = "1.3.0";
14
+ /** Machine-readable error codes a capability call may reject with. */
15
+ export type ArtifactErrorCode =
16
+ /** A write lost a race: at least one `ifMatch` hash no longer matches. */
17
+ 'conflict'
18
+ /** The viewer may not write (viewer or commenter role). */
19
+ | 'not_writer'
20
+ /** The capability exists but the viewer declined or was never granted it. */
21
+ | 'not_granted'
22
+ /** The request was malformed (bad path, too large, wrong shape). */
23
+ | 'invalid'
24
+ /** The file or resource does not exist. */
25
+ | 'not_found'
26
+ /** The host could not be reached or answered with an unexpected status. */
27
+ | 'unavailable'
28
+ /** A connector (`mcp`) call failed; see {@link McpErrorCode}. */
29
+ | McpErrorCode;
30
+ /** One path that failed an optimistic-concurrency check. */
31
+ export interface ConflictPath {
32
+ /** Artifact-relative path, e.g. `project/Main.dc.html`. */
33
+ path: string;
34
+ /** The hash the writer expected (`null`: expected the file to be absent). */
35
+ expected: string | null;
36
+ /** The hash currently stored (`null`: the file is absent). */
37
+ actual: string | null;
38
+ }
39
+ /** The error object every capability rejects with. */
40
+ export declare class ArtifactError extends Error {
41
+ readonly code: ArtifactErrorCode;
42
+ /** Present for `conflict`: every path whose `ifMatch` failed. */
43
+ readonly paths?: ConflictPath[];
44
+ /** Present when asking again later may succeed (a busy or timed-out connector). */
45
+ readonly retryable?: boolean;
46
+ constructor(code: ArtifactErrorCode, message: string, paths?: ConflictPath[], retryable?: boolean);
47
+ }
48
+ /** Type guard for {@link ArtifactError} that also works across realms (iframes). */
49
+ export declare function isArtifactError(value: unknown, code?: ArtifactErrorCode): value is ArtifactError;
50
+ /** A JSON value. */
51
+ export type JsonValue = null | boolean | number | string | JsonValue[] | {
52
+ [key: string]: JsonValue;
53
+ };
54
+ /** A JSON object. */
55
+ export type JsonRecord = {
56
+ [key: string]: JsonValue;
57
+ };
58
+ /** Metadata of one stored file. */
59
+ export interface FileEntry {
60
+ /** Lower-case hex SHA-256 of the file's bytes. */
61
+ sha256: string;
62
+ /** Size in bytes. */
63
+ size: number;
64
+ }
65
+ /** A listing of every file of the artifact, keyed by artifact-relative path. */
66
+ export type FileListing = Record<string, FileEntry>;
67
+ /** One file in a publish batch. */
68
+ export interface PublishFile {
69
+ /** Text content (UTF-8), or base64 when `encoding` is `base64`. */
70
+ content: string;
71
+ encoding?: 'utf8' | 'base64';
72
+ /**
73
+ * Optimistic-concurrency guard: the hash the writer last saw.
74
+ * `null` means "the file must not exist yet". Omit to write unconditionally.
75
+ */
76
+ ifMatch?: string | null;
77
+ }
78
+ /** A publish batch: `null` deletes the path. */
79
+ export type PublishBatch = Record<string, PublishFile | null>;
80
+ /** The result of a successful publish. */
81
+ export interface PublishResult {
82
+ /** New hash of every written path; `null` for deleted paths. */
83
+ hashes: Record<string, string | null>;
84
+ }
85
+ /** A change pushed by the host: written by someone else (agent, another tab). */
86
+ export interface FilesChangedEvent {
87
+ /** Path → new hash, or `null` when the file was deleted. */
88
+ changes: Record<string, string | null>;
89
+ /** Who made the change, when the host knows (`agent`, `owner`, `guest:<name>`). */
90
+ author?: string;
91
+ }
92
+ /** The `artifact` capability. */
93
+ export interface ArtifactCapability {
94
+ /** Stable artifact id. */
95
+ readonly id: string;
96
+ /** Current title as recorded by the host. */
97
+ title(): Promise<string>;
98
+ /** Lists every file with its hash. */
99
+ list(): Promise<FileListing>;
100
+ /** Reads a text file; rejects with `not_found` when absent. */
101
+ readText(path: string): Promise<string>;
102
+ /** Reads a file as bytes. */
103
+ readBytes(path: string): Promise<Uint8Array>;
104
+ /**
105
+ * Writes a batch atomically. Rejects with `conflict` (listing every stale
106
+ * path, nothing written) or `not_writer`.
107
+ */
108
+ publish(batch: PublishBatch): Promise<PublishResult>;
109
+ /**
110
+ * Subscribes to changes made by anyone else. The host suppresses echoes of
111
+ * this page's own publishes. Returns an unsubscribe function.
112
+ */
113
+ onChange(listener: (event: FilesChangedEvent) => void): () => void;
114
+ }
115
+ /** A stored upload. Pages reference it only by `url` (`/_blob/<id>`). */
116
+ export interface AssetRecord {
117
+ /** First 32 hex digits of the SHA-256 of the bytes. */
118
+ id: string;
119
+ /** Root-relative URL, always `/_blob/<id>`. */
120
+ url: string;
121
+ sizeBytes: number;
122
+ contentType: string;
123
+ }
124
+ /** The `assets` capability. */
125
+ export interface AssetsCapability {
126
+ /** Uploads bytes; identical bytes always produce the same record. */
127
+ upload(data: Blob, options?: {
128
+ name?: string;
129
+ }): Promise<AssetRecord>;
130
+ }
131
+ /** Roles, from most to least privileged. */
132
+ export type Role = 'owner' | 'editor' | 'commenter' | 'viewer';
133
+ /** The current viewer. */
134
+ export interface Viewer {
135
+ id: string;
136
+ name: string;
137
+ role: Role;
138
+ }
139
+ /** The `user` capability. */
140
+ export interface UserCapability {
141
+ me(): Promise<Viewer>;
142
+ }
143
+ /** True when the role may change files and upload assets. */
144
+ export declare function canEdit(role: Role): boolean;
145
+ /** A request a page sends to the agent ("Send to agent", "Ask agent to fix"). */
146
+ export interface AgentRequest {
147
+ /** What the person asked for, in their words (already fenced if untrusted). */
148
+ text: string;
149
+ /** Short label for cards and logs, e.g. `Ask agent to fix`. */
150
+ title?: string;
151
+ /** Structured context: selection ids, labels, error text. Data, never instructions. */
152
+ context?: Record<string, unknown>;
153
+ }
154
+ /** How the request should arrive. */
155
+ export type AgentDelivery =
156
+ /** Start an agent turn now (falls back to queueing when the agent is away). */
157
+ 'send'
158
+ /** Only prefill the person's composer; never start a turn. */
159
+ | 'stage';
160
+ /** The outcome of {@link AgentCapability.send}. */
161
+ export interface AgentSendResult {
162
+ status: 'delivered' | 'queued' | 'staged' | 'failed';
163
+ /** Human-readable reason when `failed`. */
164
+ reason?: string;
165
+ }
166
+ /** Whether an agent is reachable and working. */
167
+ export interface AgentStatus {
168
+ /** An agent can receive requests (it waits, or a harness can wake it). */
169
+ available: boolean;
170
+ /** The agent is currently changing this artifact. */
171
+ busy: boolean;
172
+ /** Display name, e.g. `Agent`. */
173
+ name: string;
174
+ /** false: an idle agent is not woken; what is sent waits until the person next talks to it. Left out: it is woken. */
175
+ wakesIdle?: boolean;
176
+ }
177
+ /** The `agent` capability. */
178
+ export interface AgentCapability {
179
+ send(request: AgentRequest, options?: {
180
+ deliver?: AgentDelivery;
181
+ }): Promise<AgentSendResult>;
182
+ status(): Promise<AgentStatus>;
183
+ onStatus(listener: (status: AgentStatus) => void): () => void;
184
+ }
185
+ /** One viewer (or the agent) present on the artifact. */
186
+ export interface Peer {
187
+ id: string;
188
+ name: string;
189
+ kind: 'person' | 'agent';
190
+ /** Whatever the peer last published with {@link RoomCapability.presence}. */
191
+ state: Record<string, unknown>;
192
+ }
193
+ /**
194
+ * An ephemeral message between the pages of one artifact (live strokes,
195
+ * drag previews, reactions). Never stored; a page that is not connected
196
+ * when it is sent never sees it.
197
+ */
198
+ export interface RoomMessage {
199
+ /** Peer id of the sender (see {@link RoomCapability.self}). */
200
+ from: string;
201
+ /** Free-form channel name chosen by the type, e.g. `gesture`. */
202
+ topic: string;
203
+ /** JSON payload, at most {@link ROOM_MESSAGE_MAX_BYTES} once serialized. */
204
+ data: JsonValue;
205
+ }
206
+ /** Largest serialized {@link RoomMessage.data} a host relays. */
207
+ export declare const ROOM_MESSAGE_MAX_BYTES = 16384;
208
+ /** The `room` capability. */
209
+ export interface RoomCapability {
210
+ /** This page's own peer id (its entry in {@link peers}). */
211
+ self(): Promise<string>;
212
+ /**
213
+ * Publishes (merges) this viewer's presence state; a `null` value removes
214
+ * a key. The `viewContext` key is what the agent receives before the
215
+ * viewer's next message.
216
+ */
217
+ presence(patch: Record<string, unknown>): Promise<void>;
218
+ peers(): Promise<Peer[]>;
219
+ onPeers(listener: (peers: Peer[]) => void): () => void;
220
+ /** Relays an ephemeral message to every other page of the artifact. */
221
+ emit(topic: string, data: JsonValue): Promise<void>;
222
+ /** Subscribes to ephemeral messages from other pages. */
223
+ onMessage(listener: (message: RoomMessage) => void): () => void;
224
+ }
225
+ /** The `downloads` capability. */
226
+ export interface DownloadsCapability {
227
+ /** Saves a file. Hosts cap a single file at 16 MB. */
228
+ save(file: {
229
+ name: string;
230
+ data: Blob;
231
+ }): Promise<{
232
+ savedTo?: string;
233
+ }>;
234
+ }
235
+ /**
236
+ * A document path: an even number of segments alternating collection and
237
+ * document id (`elements/n-12`, `data/users/u1/idea`). Segments match
238
+ * `[A-Za-z0-9_.~:@+-]+` and are never `.` or `..`.
239
+ */
240
+ export type DbPath = string;
241
+ /** One stored document. */
242
+ export interface DbDocument {
243
+ path: DbPath;
244
+ data: JsonRecord;
245
+ }
246
+ /**
247
+ * A write's precondition: write only while the document is still the one the
248
+ * writer read. `ifMatch` is that document's sha256 (lowercase hex of its data
249
+ * as compact JSON, `JSON.stringify`, UTF-8: what the agent's tools call
250
+ * `sha256`), or `null` for "only while it does not exist". When one fails
251
+ * the whole batch is refused with `conflict`, its `paths` naming each
252
+ * document (`expected`, `actual`), and nothing is written. Omit it to write
253
+ * unconditionally.
254
+ */
255
+ export interface DbWriteGuard {
256
+ ifMatch?: string | null;
257
+ }
258
+ /** One write of a {@link DbCapability.write} batch. */
259
+ export type DbWrite =
260
+ /** Replaces the document (creating it when absent). */
261
+ ({
262
+ op: 'set';
263
+ path: DbPath;
264
+ data: JsonRecord;
265
+ } & DbWriteGuard)
266
+ /**
267
+ * Applies a JSON merge patch (RFC 7396): objects merge, arrays and
268
+ * scalars replace, `null` removes a key. An absent document starts empty.
269
+ */
270
+ | ({
271
+ op: 'update';
272
+ path: DbPath;
273
+ patch: JsonRecord;
274
+ } & DbWriteGuard)
275
+ /** Removes the document (a no-op when it is absent). */
276
+ | ({
277
+ op: 'delete';
278
+ path: DbPath;
279
+ } & DbWriteGuard);
280
+ /** Documents changed by someone else (agent, another page). */
281
+ export interface DbChangeEvent {
282
+ /** Path → the document's new data, or `null` when it was deleted. */
283
+ changes: Record<DbPath, JsonRecord | null>;
284
+ /** Who made the change, when the host knows (`agent`, `owner`, a peer id). */
285
+ author?: string;
286
+ }
287
+ /** Limits every host enforces on the document store. */
288
+ export declare const DB_LIMITS: {
289
+ /** Writes in one batch. */
290
+ readonly maxWrites: 500;
291
+ /** Bytes of one document's JSON. */
292
+ readonly maxDocumentBytes: 262144;
293
+ /** Nesting depth of one document. */
294
+ readonly maxDepth: 32;
295
+ };
296
+ /** The `db` capability, granted to types whose manifest declares `store: "db"`. */
297
+ export interface DbCapability {
298
+ /** Reads one document; `null` when absent. */
299
+ get(path: DbPath): Promise<JsonRecord | null>;
300
+ /** Every document of one collection (`elements`, `data/users/u1/ideas`), sorted by path. */
301
+ list(collection: string): Promise<DbDocument[]>;
302
+ /**
303
+ * Applies a batch in order, all or nothing. Rejects with `invalid` (bad
304
+ * path, too large), `conflict` (an `ifMatch` no longer holds) or `not_writer`. The host never echoes the batch back
305
+ * through {@link onChange}.
306
+ */
307
+ write(writes: DbWrite[]): Promise<void>;
308
+ /** Subscribes to changes made by anyone else. Returns an unsubscribe function. */
309
+ onChange(listener: (event: DbChangeEvent) => void): () => void;
310
+ }
311
+ /** Who wrote a comment message. */
312
+ export interface CommentAuthor {
313
+ kind: 'person' | 'agent';
314
+ name: string;
315
+ }
316
+ /** One message of a thread. */
317
+ export interface CommentMessage {
318
+ id: string;
319
+ author: CommentAuthor;
320
+ text: string;
321
+ /** ISO 8601 time. */
322
+ at: string;
323
+ }
324
+ /** Where a thread stands with the agent. */
325
+ export interface CommentAgentState {
326
+ /** `pending`: sent, not yet read; `delivered`: the agent has it; `replied`: it answered. */
327
+ status: 'pending' | 'delivered' | 'replied';
328
+ }
329
+ /** A comment thread. */
330
+ export interface CommentThread {
331
+ id: string;
332
+ /**
333
+ * The type's own anchor, serialized (a board stores a JSON object naming
334
+ * an element and an offset). Opaque to the host.
335
+ */
336
+ anchor: string;
337
+ /** Short human label of what the thread is about (`Note "Q3 goals"`). */
338
+ label: string;
339
+ /** Longer description of the anchored content, for the agent. */
340
+ detail?: string;
341
+ /** Extra structured location (coordinates, element ids), for the agent. */
342
+ location: JsonRecord;
343
+ status: 'open' | 'resolved';
344
+ agent?: CommentAgentState;
345
+ messages: CommentMessage[];
346
+ }
347
+ /** What {@link CommentsCapability.create} takes. */
348
+ export interface CommentCreate {
349
+ anchor: string;
350
+ label: string;
351
+ detail?: string;
352
+ location?: JsonRecord;
353
+ /** The first message. */
354
+ text: string;
355
+ }
356
+ /** The `comments` capability, granted to types whose manifest declares `comments: true`. */
357
+ export interface CommentsCapability {
358
+ /** Every thread, open and resolved. */
359
+ list(): Promise<CommentThread[]>;
360
+ create(input: CommentCreate): Promise<CommentThread>;
361
+ reply(threadId: string, text: string): Promise<CommentThread>;
362
+ setResolved(threadId: string, resolved: boolean): Promise<CommentThread>;
363
+ /** Re-anchors a thread (its content moved or was replaced). */
364
+ move(threadId: string, anchor: string, location?: JsonRecord): Promise<CommentThread>;
365
+ /** Deletes one message, or the whole thread when `messageId` is omitted. */
366
+ remove(threadId: string, messageId?: string): Promise<void>;
367
+ /** Hands the thread to the agent (status `pending` until it reads it). */
368
+ sendToAgent(threadId: string): Promise<CommentThread>;
369
+ /** Subscribes to the full thread list whenever anyone changes it. */
370
+ onChange(listener: (threads: CommentThread[]) => void): () => void;
371
+ }
372
+ /** Who made a version: a person on the page, the agent (any change on disk), or the system (the first version). */
373
+ export interface HistoryAuthor {
374
+ kind: 'person' | 'agent' | 'system';
375
+ id: string;
376
+ name: string;
377
+ }
378
+ /** One path a version changed. Paths are `project/…` files or `db/<collection>/<doc>` documents. */
379
+ export interface HistoryFileChange {
380
+ path: string;
381
+ op: 'added' | 'edited' | 'deleted';
382
+ }
383
+ /**
384
+ * One version: an author's burst of changes (it ends after a 30 s pause or
385
+ * 5 min), or a restore.
386
+ */
387
+ export interface HistoryVersion {
388
+ /** Numbers the versions from 1, never reused. */
389
+ n: number;
390
+ /** First and last change in it (ISO 8601). */
391
+ first: string;
392
+ at: string;
393
+ author: HistoryAuthor;
394
+ /** What it changed, sorted by path. */
395
+ files: HistoryFileChange[];
396
+ /** A restore: the version it brought back. */
397
+ restoredFrom?: number;
398
+ /** The newest version: what the files hold now. */
399
+ current?: true;
400
+ /** Changes made moments before by someone else that this version undid, at least in part. */
401
+ overwrote?: {
402
+ path: string;
403
+ n: number;
404
+ author: HistoryAuthor;
405
+ }[];
406
+ }
407
+ /**
408
+ * A notice to the viewer: someone else's version `n` undid part of their
409
+ * change to `path` (version `lost.n`). Bring it back with
410
+ * `restore(lost.n, [path])`; it goes away by itself then.
411
+ */
412
+ export interface HistoryNotice {
413
+ id: string;
414
+ at: string;
415
+ path: string;
416
+ n: number;
417
+ author: HistoryAuthor;
418
+ lost: {
419
+ n: number;
420
+ author: HistoryAuthor;
421
+ deleted?: true;
422
+ };
423
+ }
424
+ /** What {@link HistoryCapability.list} answers. */
425
+ export interface HistoryListing {
426
+ /** Newest first. */
427
+ versions: HistoryVersion[];
428
+ /** The viewer's notices, newest first. */
429
+ notices: HistoryNotice[];
430
+ /** The viewer may restore (owner or editor). */
431
+ canRestore: boolean;
432
+ }
433
+ /**
434
+ * One path before and after a version, for a diff. `null`: the file did
435
+ * not exist on that side. Contents are left out (`null`) when `binary` or
436
+ * `tooLarge`.
437
+ */
438
+ export interface HistoryFileDiff {
439
+ path: string;
440
+ n: number;
441
+ op: HistoryFileChange['op'];
442
+ before: string | null;
443
+ after: string | null;
444
+ binary?: true;
445
+ tooLarge?: true;
446
+ }
447
+ /** What {@link HistoryCapability.restore} answers. */
448
+ export interface HistoryRestoreResult {
449
+ /** The version the restore made (`null`: everything already matched). */
450
+ version: number | null;
451
+ /** The paths it wrote or deleted. */
452
+ changed: string[];
453
+ }
454
+ /** The history changed: `n` is the newest version (it may be one that grew). */
455
+ export interface HistoryChangeEvent {
456
+ n: number | null;
457
+ }
458
+ /**
459
+ * The `history` capability: the artifact's versions, read-only previews of
460
+ * them, and restores. A restore writes through the host's normal write path
461
+ * (every open page hears of it) and is a version of its own.
462
+ */
463
+ export interface HistoryCapability {
464
+ /** Every kept version (newest first) and the viewer's notices. */
465
+ list(): Promise<HistoryListing>;
466
+ /** Every path as it was right after version `n`, with its hash and size. */
467
+ files(n: number): Promise<FileListing>;
468
+ /** A text file (or a document's JSON) as it was right after version `n`; rejects `not_found`. */
469
+ read(n: number, path: string): Promise<string>;
470
+ /** The same as bytes. */
471
+ readBytes(n: number, path: string): Promise<Uint8Array>;
472
+ /** One path right before and right after version `n` (a path version `n` changed). */
473
+ diff(n: number, path: string): Promise<HistoryFileDiff>;
474
+ /**
475
+ * Brings version `n` back: every path (default) or only `paths`. Rejects
476
+ * `not_writer` for readers, `not_found` for a version no longer kept.
477
+ */
478
+ restore(n: number, paths?: string[]): Promise<HistoryRestoreResult>;
479
+ /** Dismisses one of the viewer's notices. */
480
+ dismissNotice(id: string): Promise<void>;
481
+ /** Subscribes to new versions. Returns an unsubscribe function. */
482
+ onChange(listener: (event: HistoryChangeEvent) => void): () => void;
483
+ }
484
+ /**
485
+ * Codes a connector call rejects with (on an {@link ArtifactError}, whose
486
+ * `retryable` says when asking again later may work):
487
+ *
488
+ * - `server_not_connected`: no connector by that name, or it could not be
489
+ * started or reached;
490
+ * - `needs_reauth`: the connector refused its credentials (HTTP 401/403);
491
+ * - `not_granted`: this viewer may not use connectors (only the owner may);
492
+ * - `rate_limited`: the connector is busy (HTTP 429);
493
+ * - `upstream_error`: the connector answered with a protocol error, failed,
494
+ * or did not answer in time;
495
+ * - `tool_error`, `consent_required`, `selection_required`, `not_in_manifest`,
496
+ * `not_declared`, `capability_disabled`, `capability_removed`,
497
+ * `server_unavailable`, `response_too_large`: reserved for hosts that
498
+ * mediate connectors further; pages handle them.
499
+ *
500
+ * A tool that ran and failed is not an error: it resolves with `isError`.
501
+ */
502
+ 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';
503
+ /** Every {@link McpErrorCode}. */
504
+ export declare const MCP_ERROR_CODES: readonly McpErrorCode[];
505
+ /** One content item of a tool result (MCP `CallToolResult.content`). */
506
+ export type McpContent = {
507
+ type: 'text';
508
+ text: string;
509
+ annotations?: JsonRecord;
510
+ _meta?: JsonRecord;
511
+ } | {
512
+ type: 'image';
513
+ data: string;
514
+ mimeType: string;
515
+ annotations?: JsonRecord;
516
+ _meta?: JsonRecord;
517
+ } | {
518
+ type: 'audio';
519
+ data: string;
520
+ mimeType: string;
521
+ annotations?: JsonRecord;
522
+ _meta?: JsonRecord;
523
+ } | {
524
+ type: 'resource';
525
+ resource: {
526
+ uri: string;
527
+ mimeType?: string;
528
+ text?: string;
529
+ blob?: string;
530
+ _meta?: JsonRecord;
531
+ };
532
+ annotations?: JsonRecord;
533
+ _meta?: JsonRecord;
534
+ } | {
535
+ type: 'resource_link';
536
+ uri: string;
537
+ name: string;
538
+ title?: string;
539
+ description?: string;
540
+ mimeType?: string;
541
+ annotations?: JsonRecord;
542
+ _meta?: JsonRecord;
543
+ };
544
+ /** What a tool answered: the MCP `CallToolResult`, as the connector sent it. */
545
+ export interface McpToolResult {
546
+ content: McpContent[];
547
+ structuredContent?: JsonRecord;
548
+ /** The tool ran and failed; `content` says why. */
549
+ isError?: boolean;
550
+ _meta?: JsonRecord;
551
+ }
552
+ /** One tool of a connector (MCP `Tool`, the fields pages use). */
553
+ export interface McpToolInfo {
554
+ name: string;
555
+ title?: string;
556
+ description?: string;
557
+ /** JSON Schema of the tool's arguments. */
558
+ inputSchema?: JsonRecord;
559
+ }
560
+ /**
561
+ * Where a connector stands: `connected` (it answered, `tools` lists its
562
+ * tools), `needs_auth` (it refused its credentials), `error` (it could not
563
+ * be started or reached), `disconnected` (turned off in the configuration).
564
+ */
565
+ export type McpAuthStatus = 'connected' | 'needs_auth' | 'error' | 'disconnected';
566
+ /** One connector, as {@link McpCapability.listTools} lists it. */
567
+ export interface McpServerEntry {
568
+ /** Its name in the configuration, what {@link McpCapability.callTool} takes. */
569
+ server: string;
570
+ kind: 'connector';
571
+ authStatus: McpAuthStatus;
572
+ /** Present when `connected`. */
573
+ tools?: McpToolInfo[];
574
+ /** Why it is not connected. */
575
+ error?: string;
576
+ }
577
+ /** Options of {@link McpCapability.callTool}. */
578
+ export interface McpCallOptions {
579
+ /** Cancels the call (it rejects with the signal's reason). */
580
+ signal?: AbortSignal;
581
+ /** Milliseconds before the call fails with a retryable `upstream_error`. Default 120 000, at most 600 000. */
582
+ timeoutMs?: number;
583
+ }
584
+ /** Default and largest {@link McpCallOptions.timeoutMs}. */
585
+ export declare const MCP_CALL_TIMEOUT: {
586
+ readonly defaultMs: 120000;
587
+ readonly maxMs: 600000;
588
+ };
589
+ /**
590
+ * The `mcp` capability: calls tools of the connectors (MCP servers) the
591
+ * owner configured on their computer. Only the owner gets it.
592
+ */
593
+ export interface McpCapability {
594
+ /** Calls `tool` of connector `server`; rejects with an {@link McpErrorCode} (see there). */
595
+ callTool(server: string, tool: string, args: Record<string, unknown>, options?: McpCallOptions): Promise<McpToolResult>;
596
+ /** Every connector (or only `server`) and, for those connected, their tools. */
597
+ listTools(server?: string): Promise<{
598
+ servers: McpServerEntry[];
599
+ }>;
600
+ }
601
+ /** Every capability by name. */
602
+ export interface CapabilityMap {
603
+ artifact: ArtifactCapability;
604
+ assets: AssetsCapability;
605
+ user: UserCapability;
606
+ agent: AgentCapability;
607
+ room: RoomCapability;
608
+ downloads: DownloadsCapability;
609
+ db: DbCapability;
610
+ comments: CommentsCapability;
611
+ history: HistoryCapability;
612
+ mcp: McpCapability;
613
+ }
614
+ export type CapabilityName = keyof CapabilityMap;
615
+ /** The object installed at `window.openartifact`. */
616
+ export interface OpenArtifactRuntime {
617
+ /** Contract version, see {@link CONTRACT_VERSION}. */
618
+ readonly version: string;
619
+ /**
620
+ * Resolves the namespace of a capability, or `null` when this view may not
621
+ * use it. Results are memoized and frozen.
622
+ */
623
+ use<K extends CapabilityName>(name: K): Promise<CapabilityMap[K] | null>;
624
+ }
625
+ declare global {
626
+ interface Window {
627
+ openartifact?: OpenArtifactRuntime;
628
+ }
629
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Capability contracts of the Open Artifact 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.openartifact.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
+ /** Version of the capability contract described in this file. */
13
+ export const CONTRACT_VERSION = '1.3.0';
14
+ /** The error object every capability rejects with. */
15
+ export class ArtifactError extends Error {
16
+ code;
17
+ /** Present for `conflict`: every path whose `ifMatch` failed. */
18
+ paths;
19
+ /** Present when asking again later may succeed (a busy or timed-out connector). */
20
+ retryable;
21
+ constructor(code, message, paths, retryable) {
22
+ super(message);
23
+ this.name = 'ArtifactError';
24
+ this.code = code;
25
+ if (paths)
26
+ this.paths = paths;
27
+ if (retryable)
28
+ this.retryable = true;
29
+ }
30
+ }
31
+ /** Type guard for {@link ArtifactError} that also works across realms (iframes). */
32
+ export function isArtifactError(value, code) {
33
+ if (!value || typeof value !== 'object')
34
+ return false;
35
+ const candidate = value;
36
+ if (candidate.name !== 'ArtifactError' || typeof candidate.code !== 'string')
37
+ return false;
38
+ return code === undefined || candidate.code === code;
39
+ }
40
+ /** True when the role may change files and upload assets. */
41
+ export function canEdit(role) {
42
+ return role === 'owner' || role === 'editor';
43
+ }
44
+ /** Largest serialized {@link RoomMessage.data} a host relays. */
45
+ export const ROOM_MESSAGE_MAX_BYTES = 16_384;
46
+ /** Limits every host enforces on the document store. */
47
+ export const DB_LIMITS = {
48
+ /** Writes in one batch. */
49
+ maxWrites: 500,
50
+ /** Bytes of one document's JSON. */
51
+ maxDocumentBytes: 262_144,
52
+ /** Nesting depth of one document. */
53
+ maxDepth: 32,
54
+ };
55
+ /** Every {@link McpErrorCode}. */
56
+ export const MCP_ERROR_CODES = [
57
+ 'server_not_connected',
58
+ 'needs_reauth',
59
+ 'not_granted',
60
+ 'not_declared',
61
+ 'not_in_manifest',
62
+ 'consent_required',
63
+ 'selection_required',
64
+ 'rate_limited',
65
+ 'upstream_error',
66
+ 'tool_error',
67
+ 'capability_disabled',
68
+ 'capability_removed',
69
+ 'server_unavailable',
70
+ 'response_too_large',
71
+ ];
72
+ /** Default and largest {@link McpCallOptions.timeoutMs}. */
73
+ export const MCP_CALL_TIMEOUT = { defaultMs: 120_000, maxMs: 600_000 };