@open-artifact/runtime 0.2.1 → 0.9.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-artifact/runtime",
3
- "version": "0.2.1",
3
+ "version": "0.9.0",
4
4
  "description": "The window.openartifact page runtime: capability contracts, the local provider and the Shell protocol.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -20,6 +20,14 @@
20
20
  "types": "./src/untrusted.d.ts",
21
21
  "default": "./src/untrusted.js"
22
22
  },
23
+ "./sheet-api": {
24
+ "types": "./src/sheet-api.d.ts",
25
+ "default": "./src/sheet-api.js"
26
+ },
27
+ "./doc-api": {
28
+ "types": "./src/doc-api.d.ts",
29
+ "default": "./src/doc-api.js"
30
+ },
23
31
  "./package.json": "./package.json"
24
32
  },
25
33
  "files": [
@@ -28,7 +36,7 @@
28
36
  "NOTICE"
29
37
  ],
30
38
  "dependencies": {
31
- "@open-artifact/protocol": "0.2.1"
39
+ "@open-artifact/protocol": "0.9.0"
32
40
  },
33
41
  "license": "Apache-2.0",
34
42
  "author": {
package/src/broker.d.ts CHANGED
@@ -55,6 +55,12 @@ export declare const BROKERED_EVENTS: {
55
55
  readonly history: {
56
56
  readonly onChange: "change";
57
57
  };
58
+ readonly sheet: {
59
+ readonly onFrame: "frame";
60
+ };
61
+ readonly doc: {
62
+ readonly onFrame: "frame";
63
+ };
58
64
  };
59
65
  /** Options of {@link createShellProvider}. */
60
66
  export interface ShellProviderOptions {
package/src/broker.js CHANGED
@@ -37,9 +37,11 @@ export const BROKERED_METHODS = {
37
37
  room: ['self', 'presence', 'peers', 'emit'],
38
38
  downloads: ['save'],
39
39
  db: ['get', 'list', 'write'],
40
- comments: ['list', 'create', 'reply', 'setResolved', 'move', 'remove', 'sendToAgent'],
40
+ comments: ['list', 'create', 'reply', 'edit', 'react', 'setResolved', 'move', 'remove', 'sendToAgent'],
41
41
  history: ['list', 'files', 'read', 'readBytes', 'diff', 'restore', 'dismissNotice'],
42
+ doc: ['session', 'read', 'call', 'history', 'version', 'restore', 'importFile', 'exportFile'],
42
43
  mcp: ['callTool', 'listTools'],
44
+ sheet: ['read', 'send', 'widget', 'importFile'],
43
45
  };
44
46
  /**
45
47
  * The `cap_ev` event each listener method follows, per capability
@@ -53,6 +55,8 @@ export const BROKERED_EVENTS = {
53
55
  db: { onChange: 'change' },
54
56
  comments: { onChange: 'threads' },
55
57
  history: { onChange: 'change' },
58
+ sheet: { onFrame: 'frame' },
59
+ doc: { onFrame: 'frame' },
56
60
  };
57
61
  const CALL_TIMEOUT = { downloads: 150_000, assets: 272_000, user: 20_000 };
58
62
  const DEFAULT_CALL_TIMEOUT = 130_000;
@@ -284,15 +288,28 @@ export function createShellProvider(options = {}) {
284
288
  const ns = {
285
289
  list: () => c('list'),
286
290
  create: (input) => c('create', [input]),
287
- reply: (threadId, text) => c('reply', [threadId, text]),
291
+ reply: (threadId, text, options) => c('reply', options ? [threadId, text, options] : [threadId, text]),
292
+ edit: (threadId, messageId, text, options) => c('edit', options ? [threadId, messageId, text, options] : [threadId, messageId, text]),
293
+ react: (threadId, messageId, emoji, on) => c('react', [threadId, messageId, emoji, on]),
288
294
  setResolved: (threadId, resolved) => c('setResolved', [threadId, resolved]),
289
295
  move: (threadId, anchor, location) => c('move', location ? [threadId, anchor, location] : [threadId, anchor]),
290
296
  remove: (threadId, messageId) => c('remove', messageId ? [threadId, messageId] : [threadId]),
291
- sendToAgent: (threadId) => c('sendToAgent', [threadId], true),
297
+ // A host hears only threads people send: one the page would send unasked is not handed over there.
298
+ sendToAgent: (threadId, options) => (options?.unasked ? Promise.reject(new Error('This host takes only threads that ask the agent.')) : c('sendToAgent', [threadId], true)),
292
299
  onChange: (listener) => listen('comments', BROKERED_EVENTS.comments.onChange, listener),
293
300
  };
294
301
  return ns;
295
302
  }
303
+ case 'sheet': {
304
+ const ns = {
305
+ read: (request) => c('read', [request]),
306
+ send: (request) => c('send', [request]),
307
+ widget: (request) => c('widget', [request]),
308
+ importFile: (file, name) => c('importFile', [file, name], true),
309
+ onFrame: (listener) => listen('sheet', BROKERED_EVENTS.sheet.onFrame, listener),
310
+ };
311
+ return ns;
312
+ }
296
313
  case 'history': {
297
314
  const ns = {
298
315
  list: () => c('list'),
@@ -306,6 +323,20 @@ export function createShellProvider(options = {}) {
306
323
  };
307
324
  return ns;
308
325
  }
326
+ case 'doc': {
327
+ const ns = {
328
+ session: () => c('session'),
329
+ read: (tab) => c('read', [tab]),
330
+ call: (request) => c('call', [request]),
331
+ history: (tab) => c('history', [tab]),
332
+ version: (tab, rev) => c('version', [tab, rev]),
333
+ restore: (request) => c('restore', [request]),
334
+ importFile: (name, bytes, tabName) => c('importFile', tabName === undefined ? [name, bytes] : [name, bytes, tabName], true),
335
+ exportFile: (query) => c('exportFile', [query], true),
336
+ onFrame: (listener) => listen('doc', BROKERED_EVENTS.doc.onFrame, listener),
337
+ };
338
+ return ns;
339
+ }
309
340
  case 'downloads': {
310
341
  const ns = { save: (file) => c('save', [file], true) };
311
342
  return ns;
@@ -9,8 +9,10 @@
9
9
  *
10
10
  * Every method is asynchronous and may reject with an {@link ArtifactError}.
11
11
  */
12
+ import type { ImportFileResponse, SheetFrame, SheetReadAnswers, SheetReadRefusal, SheetReadRequest, SheetSendRequest, SheetSendResponse, WidgetRequest, WidgetResponse } from './sheet-api.ts';
13
+ import type { DocCallAnswer, DocCallRequest, DocExportFormat, DocFrame, DocHistoryResponse, DocImportResponse, DocPaper, DocRestoreRequest, DocRestoreResponse, DocSessionResponse, DocTabResponse, DocVersionResponse } from './doc-api.ts';
12
14
  /** Version of the capability contract described in this file. */
13
- export declare const CONTRACT_VERSION = "1.3.0";
15
+ export declare const CONTRACT_VERSION = "1.4.0";
14
16
  /** Machine-readable error codes a capability call may reject with. */
15
17
  export type ArtifactErrorCode =
16
18
  /** A write lost a race: at least one `ifMatch` hash no longer matches. */
@@ -90,7 +92,14 @@ export interface FilesChangedEvent {
90
92
  author?: string;
91
93
  }
92
94
  /** The `artifact` capability. */
95
+ export interface SystemCopyStatus {
96
+ state: 'current' | 'behind' | 'missing' | 'unavailable';
97
+ changed: number;
98
+ removed: number;
99
+ }
93
100
  export interface ArtifactCapability {
101
+ /** Compare or refresh an installed design system from its recorded source. */
102
+ systemCopy?(namespace: string, action: 'status' | 'sync'): Promise<SystemCopyStatus>;
94
103
  /** Stable artifact id. */
95
104
  readonly id: string;
96
105
  /** Current title as recorded by the host. */
@@ -313,6 +322,11 @@ export interface CommentAuthor {
313
322
  kind: 'person' | 'agent';
314
323
  name: string;
315
324
  }
325
+ /** People who reacted to a message with one emoji. */
326
+ export interface CommentReaction {
327
+ emoji: string;
328
+ authors: CommentAuthor[];
329
+ }
316
330
  /** One message of a thread. */
317
331
  export interface CommentMessage {
318
332
  id: string;
@@ -320,6 +334,25 @@ export interface CommentMessage {
320
334
  text: string;
321
335
  /** ISO 8601 time. */
322
336
  at: string;
337
+ /** ISO 8601 time of the last edit. */
338
+ editedAt?: string;
339
+ /** Who the message asks, as the page named them (`agent` asks the agent). */
340
+ to?: string[];
341
+ reactions?: CommentReaction[];
342
+ /** The agent's reply to a message sent to it without asking it: it joined without being asked. */
343
+ joined?: boolean;
344
+ }
345
+ /** What {@link CommentsCapability.sendToAgent} takes besides the thread. */
346
+ export interface CommentSendOptions {
347
+ /**
348
+ * The newest message does not ask the agent (no `@agent`) but goes to it because it took part in the thread: it
349
+ * decides whether to answer, and the thread keeps its status.
350
+ */
351
+ unasked?: boolean;
352
+ }
353
+ /** What {@link CommentsCapability.reply} takes besides the text. */
354
+ export interface CommentReplyOptions {
355
+ to?: string[];
323
356
  }
324
357
  /** Where a thread stands with the agent. */
325
358
  export interface CommentAgentState {
@@ -341,6 +374,8 @@ export interface CommentThread {
341
374
  /** Extra structured location (coordinates, element ids), for the agent. */
342
375
  location: JsonRecord;
343
376
  status: 'open' | 'resolved';
377
+ /** Who resolved it, while it is resolved (when the host knows). */
378
+ resolvedBy?: CommentAuthor;
344
379
  agent?: CommentAgentState;
345
380
  messages: CommentMessage[];
346
381
  }
@@ -352,20 +387,26 @@ export interface CommentCreate {
352
387
  location?: JsonRecord;
353
388
  /** The first message. */
354
389
  text: string;
390
+ /** Who the first message asks. */
391
+ to?: string[];
355
392
  }
356
393
  /** The `comments` capability, granted to types whose manifest declares `comments: true`. */
357
394
  export interface CommentsCapability {
358
395
  /** Every thread, open and resolved. */
359
396
  list(): Promise<CommentThread[]>;
360
397
  create(input: CommentCreate): Promise<CommentThread>;
361
- reply(threadId: string, text: string): Promise<CommentThread>;
398
+ reply(threadId: string, text: string, options?: CommentReplyOptions): Promise<CommentThread>;
399
+ /** Changes the text of one of the viewer's own messages. */
400
+ edit(threadId: string, messageId: string, text: string, options?: CommentReplyOptions): Promise<CommentThread>;
401
+ /** Adds (`on`) or takes back the viewer's reaction to a message. */
402
+ react(threadId: string, messageId: string, emoji: string, on: boolean): Promise<CommentThread>;
362
403
  setResolved(threadId: string, resolved: boolean): Promise<CommentThread>;
363
404
  /** Re-anchors a thread (its content moved or was replaced). */
364
405
  move(threadId: string, anchor: string, location?: JsonRecord): Promise<CommentThread>;
365
406
  /** Deletes one message, or the whole thread when `messageId` is omitted. */
366
407
  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>;
408
+ /** Hands the thread to the agent (status `pending` until it reads it; `unasked` keeps the status). */
409
+ sendToAgent(threadId: string, options?: CommentSendOptions): Promise<CommentThread>;
369
410
  /** Subscribes to the full thread list whenever anyone changes it. */
370
411
  onChange(listener: (threads: CommentThread[]) => void): () => void;
371
412
  }
@@ -481,6 +522,50 @@ export interface HistoryCapability {
481
522
  /** Subscribes to new versions. Returns an unsubscribe function. */
482
523
  onChange(listener: (event: HistoryChangeEvent) => void): () => void;
483
524
  }
525
+ /** What {@link DocCapability.exportFile} asks for. */
526
+ export interface DocExportQuery {
527
+ format: DocExportFormat;
528
+ /** One tab (default: every tab). */
529
+ tab?: string;
530
+ paper?: DocPaper;
531
+ }
532
+ /** An exported file. */
533
+ export interface DocExportedFile {
534
+ name: string;
535
+ mime: string;
536
+ bytes: Uint8Array;
537
+ /** What the file could not carry over. */
538
+ notes: {
539
+ code: string;
540
+ message: string;
541
+ count?: number;
542
+ }[];
543
+ }
544
+ /**
545
+ * The `doc` capability, granted to types whose manifest declares `store: "doc"`. A page takes a writing session,
546
+ * reads tabs and sends its edits as ops on the revision it holds; every write anyone else makes arrives as a frame.
547
+ * A write is refused in the answer (`verdict: "deny"`), not by a rejection.
548
+ */
549
+ export interface DocCapability {
550
+ /** This page's writing session (`sess` is `null` for a reader) and the doc. */
551
+ session(): Promise<DocSessionResponse>;
552
+ /** A tab as the host holds it. */
553
+ read(tab: string): Promise<DocTabResponse>;
554
+ /** One member or a batch, on the session's behalf; `opId` makes it safe to send again. */
555
+ call(request: DocCallRequest): Promise<DocCallAnswer>;
556
+ /** A tab's kept versions, newest first. */
557
+ history(tab: string): Promise<DocHistoryResponse>;
558
+ /** A tab as it stood at a kept rev. */
559
+ version(tab: string, rev: number): Promise<DocVersionResponse>;
560
+ /** Brings a tab back as it was at `rev`, as a new write. */
561
+ restore(request: DocRestoreRequest): Promise<DocRestoreResponse>;
562
+ /** A .md, .docx or .pdf file as a new tab (`tabName`: its name). */
563
+ importFile(name: string, bytes: Uint8Array, tabName?: string): Promise<DocImportResponse>;
564
+ /** The doc, or one tab, as a file. */
565
+ exportFile(query: DocExportQuery): Promise<DocExportedFile>;
566
+ /** Subscribes to every write, tab and list change. Returns an unsubscribe function. */
567
+ onFrame(listener: (frame: DocFrame) => void): () => void;
568
+ }
484
569
  /**
485
570
  * Codes a connector call rejects with (on an {@link ArtifactError}, whose
486
571
  * `retryable` says when asking again later may work):
@@ -598,6 +683,23 @@ export interface McpCapability {
598
683
  servers: McpServerEntry[];
599
684
  }>;
600
685
  }
686
+ /**
687
+ * The `sheet` capability, granted to types whose manifest declares
688
+ * `store: "workbook"`. The page runs its own workbook engine and keeps it in
689
+ * step with the server's edit log: it loads the log with `read`, hears every
690
+ * later edit with `onFrame`, and saves its own with `send`.
691
+ */
692
+ export interface SheetCapability {
693
+ read<K extends SheetReadRequest['kind']>(request: Extract<SheetReadRequest, {
694
+ kind: K;
695
+ }>): Promise<SheetReadAnswers[K] | SheetReadRefusal>;
696
+ send(request: SheetSendRequest): Promise<SheetSendResponse>;
697
+ widget(request: WidgetRequest): Promise<WidgetResponse>;
698
+ /** Keeps a file for the agent to bring in (Import from Excel) and asks it to. */
699
+ importFile(file: Blob, name: string): Promise<ImportFileResponse>;
700
+ /** Subscribes to the stream's frames: a snapshot first on every (re)connect, then edits, clocks and widgets. */
701
+ onFrame(listener: (frame: SheetFrame) => void): () => void;
702
+ }
601
703
  /** Every capability by name. */
602
704
  export interface CapabilityMap {
603
705
  artifact: ArtifactCapability;
@@ -609,7 +711,9 @@ export interface CapabilityMap {
609
711
  db: DbCapability;
610
712
  comments: CommentsCapability;
611
713
  history: HistoryCapability;
714
+ doc: DocCapability;
612
715
  mcp: McpCapability;
716
+ sheet: SheetCapability;
613
717
  }
614
718
  export type CapabilityName = keyof CapabilityMap;
615
719
  /** The object installed at `window.openartifact`. */
@@ -10,7 +10,7 @@
10
10
  * Every method is asynchronous and may reject with an {@link ArtifactError}.
11
11
  */
12
12
  /** Version of the capability contract described in this file. */
13
- export const CONTRACT_VERSION = '1.3.0';
13
+ export const CONTRACT_VERSION = '1.4.0';
14
14
  /** The error object every capability rejects with. */
15
15
  export class ArtifactError extends Error {
16
16
  code;
@@ -0,0 +1,280 @@
1
+ /**
2
+ * The contract between a Docs page and its server (the `doc` capability).
3
+ *
4
+ * A doc is a list of tabs; each tab's body is a tree of blocks whose blocks
5
+ * and characters carry stable ids (`<session>.<n>`), and a revision number
6
+ * (`rev`) the server raises on every write. A page takes a writing session
7
+ * (`session`), reads a tab (`read`), and sends its edits as ops on the
8
+ * revision it holds (`call`, an `update` of the tab's body node). Every
9
+ * write anyone makes is announced on the `doc` event of `_api/events`; a
10
+ * page that did not make it reads the tab again.
11
+ *
12
+ * Every route is relative to the artifact's page base, as the runtime's
13
+ * `API` routes are.
14
+ */
15
+ export type DocJson = null | boolean | number | string | DocJson[] | {
16
+ [key: string]: DocJson;
17
+ };
18
+ export type DocJsonObject = {
19
+ [key: string]: DocJson;
20
+ };
21
+ /** Route paths, relative to the page base. */
22
+ export declare const DOC_API: {
23
+ /** `POST` {@link DocSessionRequest} → {@link DocSessionResponse}. */
24
+ readonly session: "_api/doc/session";
25
+ /** `POST` {@link DocReadRequest} → {@link DocTabResponse}. */
26
+ readonly read: "_api/doc/read";
27
+ /** `POST` {@link DocCallRequest} → {@link DocCallAnswer}. */
28
+ readonly call: "_api/doc/call";
29
+ /** `POST` {@link DocHistoryRequest} → {@link DocHistoryResponse}. */
30
+ readonly history: "_api/doc/history";
31
+ /** `POST` {@link DocVersionRequest} → {@link DocVersionResponse}. */
32
+ readonly version: "_api/doc/version";
33
+ /** `POST` {@link DocRestoreRequest} → {@link DocRestoreResponse}. */
34
+ readonly restore: "_api/doc/restore";
35
+ /** `POST` a file's bytes (`?name=`, optional `&tabName=`) → {@link DocImportResponse}. */
36
+ readonly importFile: "_api/doc/import";
37
+ /** `GET ?format=&tab=&paper=` → the file's bytes. */
38
+ readonly exportFile: "_api/doc/export";
39
+ };
40
+ /** The server-sent event name the frames arrive under on `_api/events`. */
41
+ export declare const DOC_EVENT = "doc";
42
+ /** The doc's export formats. */
43
+ export type DocExportFormat = 'markdown' | 'docx' | 'pdf' | 'html';
44
+ /** Paper sizes of a printed export. */
45
+ export type DocPaper = 'a4' | 'letter';
46
+ /** What the page asks of a dropdown list's option. */
47
+ export interface DocEnumOption {
48
+ name: string;
49
+ order: number;
50
+ disabled: boolean;
51
+ color?: string;
52
+ }
53
+ /** A dropdown list (a dropdown chip names its option by position). */
54
+ export interface DocEnum {
55
+ id: string;
56
+ name: string;
57
+ options: DocEnumOption[];
58
+ }
59
+ /** A tab, as the doc lists it. */
60
+ export interface DocFile {
61
+ id: string;
62
+ name: string;
63
+ /** Sort key: tabs are shown in the string order of these. */
64
+ order: string;
65
+ /** The tab this one sits under in the tab list. */
66
+ subtabOf?: string;
67
+ rev: number;
68
+ /** The tab's body node: the page writes the tab through it. */
69
+ content: {
70
+ kind: 'node';
71
+ id: string;
72
+ engine: 'prose';
73
+ };
74
+ }
75
+ /** The doc: its name, tabs, dropdown lists and display record. */
76
+ export interface DocProject {
77
+ id: string;
78
+ name: string;
79
+ /** Raised on every write anywhere in the doc. */
80
+ head: number;
81
+ updated: string;
82
+ files: DocFile[];
83
+ enums: DocEnum[];
84
+ /** How the page shows the doc (fonts, page width, where the tabs go). The page owns the keys. */
85
+ display?: DocJsonObject;
86
+ /** Set while an owner has locked the doc: nobody can edit it until an owner unlocks it. */
87
+ locked?: DocLockInfo;
88
+ }
89
+ /** Who locked a doc, when, and why. */
90
+ export interface DocLockInfo {
91
+ by: {
92
+ id: string;
93
+ name: string;
94
+ };
95
+ at: string;
96
+ note?: string;
97
+ }
98
+ /** `POST session`: a writing session for this page connection (`client` is the event stream's id). */
99
+ export interface DocSessionRequest {
100
+ client: string;
101
+ }
102
+ export interface DocSessionResponse {
103
+ /** The writing session: new ids the page makes are `<sess>.<n>` from `next` on. `null` for a reader. */
104
+ sess: string | null;
105
+ next: number;
106
+ writable: boolean;
107
+ commentable: boolean;
108
+ /** The person, as suggestions name them (`by`). */
109
+ me: {
110
+ id: string;
111
+ name: string;
112
+ };
113
+ project: DocProject;
114
+ /** The names of the people who worked on the doc, by the id versions and suggestions name them with. */
115
+ people?: Record<string, string>;
116
+ }
117
+ /** `POST read`: a tab as the server holds it. */
118
+ export interface DocReadRequest {
119
+ tab: string;
120
+ }
121
+ /** Who made an open suggestion. */
122
+ export interface DocSuggestion {
123
+ id: string;
124
+ by: string;
125
+ /** The name `by` goes by, when the doc knows it (not for the agent's). */
126
+ name?: string;
127
+ at: string;
128
+ /** `agent`: the agent laid it. */
129
+ via?: string;
130
+ mine: boolean;
131
+ /** A hash of what the suggestion holds now: a decision is made on it. */
132
+ asOf: string;
133
+ }
134
+ export interface DocTabResponse {
135
+ tab: string;
136
+ rev: number;
137
+ /** The tab's content as stored (`{rev, blocks, suggestions?}`, text kept as runs). */
138
+ doc: DocJsonObject;
139
+ suggestions: DocSuggestion[];
140
+ }
141
+ /** One member of a call: a verb on an object (`project`, `file`, `node`, `enum`). */
142
+ export interface DocMember {
143
+ verb: 'read' | 'create' | 'update' | 'delete';
144
+ object?: 'project' | 'file' | 'node' | 'enum';
145
+ ref?: {
146
+ object: 'project' | 'file' | 'node' | 'enum';
147
+ id: string;
148
+ };
149
+ payload?: DocJsonObject;
150
+ engine?: string;
151
+ /** An alias later members name as `$lid:<alias>` for what this one makes. */
152
+ $lid?: string;
153
+ }
154
+ /**
155
+ * `POST call`: one member, or a batch that lands whole. `opId` makes a call
156
+ * safe to send again (after a reconnect): an allowed call is answered again,
157
+ * not run twice.
158
+ */
159
+ export type DocCallRequest = {
160
+ sess: string;
161
+ opId?: string;
162
+ member: DocMember;
163
+ } | {
164
+ sess: string;
165
+ opId?: string;
166
+ batch: DocMember[];
167
+ };
168
+ export type DocCallAnswer = ({
169
+ verdict: 'allow';
170
+ replayed?: true;
171
+ } & DocJsonObject) | {
172
+ verdict: 'deny';
173
+ /** A refusal code (`guard_mismatch`, `block_gone`, `not_your_session`, …). */
174
+ reason: string;
175
+ detail: string;
176
+ /** The batch member, or the op of an update, that was refused. */
177
+ index?: number;
178
+ data?: DocJsonObject;
179
+ };
180
+ /** A write somebody made to a tab. */
181
+ export interface DocTabFrame {
182
+ kind: 'tab';
183
+ tab: string;
184
+ rev: number;
185
+ by: 'person' | 'agent';
186
+ /** The session that wrote it, and the page's own id for the call. */
187
+ sess?: string;
188
+ opId?: string;
189
+ /** The blocks the write changed, added or removed (the agent's writes). */
190
+ blocks?: string[];
191
+ }
192
+ /** The doc's name, tabs or display record changed. */
193
+ export interface DocProjectFrame {
194
+ kind: 'project';
195
+ project: DocProject;
196
+ }
197
+ /** Dropdown lists made or changed. */
198
+ export interface DocEnumsFrame {
199
+ kind: 'enums';
200
+ enums: DocEnum[];
201
+ }
202
+ /** The page's event stream opened: sent first on every connection, so a page that was cut off reads what it missed. */
203
+ export interface DocStreamFrame {
204
+ kind: 'stream';
205
+ }
206
+ export type DocFrame = DocTabFrame | DocProjectFrame | DocEnumsFrame | DocStreamFrame;
207
+ /** `POST history`: a tab's kept versions. */
208
+ export interface DocHistoryRequest {
209
+ tab: string;
210
+ }
211
+ /** A kept version of a tab. */
212
+ export interface DocVersion {
213
+ rev: number;
214
+ /** `human`: a person on the page; `agent`: the agent; `system`: from before the history began. */
215
+ by: 'human' | 'agent' | 'system';
216
+ /** The person's id. */
217
+ user?: string;
218
+ /** The name that person goes by, when the doc knows it. */
219
+ name?: string;
220
+ at: string;
221
+ /** A restore: the rev it brought back. */
222
+ restoredFrom?: number;
223
+ }
224
+ export interface DocHistoryResponse {
225
+ tab: string;
226
+ rev: number;
227
+ /** Newest first. */
228
+ versions: DocVersion[];
229
+ }
230
+ /** `POST version`: a tab as it stood at a kept rev. */
231
+ export interface DocVersionRequest {
232
+ tab: string;
233
+ rev: number;
234
+ }
235
+ export interface DocVersionResponse {
236
+ tab: string;
237
+ rev: number;
238
+ /** As {@link DocTabResponse.doc}, without open suggestions. */
239
+ doc: DocJsonObject;
240
+ }
241
+ /** `POST restore`: the tab back as it was at `rev`, as a new write; `ifRev` is the rev the page last saw. */
242
+ export interface DocRestoreRequest {
243
+ tab: string;
244
+ rev: number;
245
+ ifRev?: number;
246
+ }
247
+ export interface DocRestoreResponse {
248
+ restored: boolean;
249
+ /** The tab's rev now, and before the restore. */
250
+ rev: number;
251
+ before: number;
252
+ }
253
+ /** The kinds of file an import reads. */
254
+ export type DocImportFormat = 'markdown' | 'docx' | 'pdf';
255
+ /** What didn't come across whole, counted: `what` says it in a few words, shown as it is. */
256
+ export interface DocImportNote {
257
+ what: string;
258
+ count: number;
259
+ }
260
+ /** What an import added. */
261
+ export interface DocImportResponse {
262
+ ok: true;
263
+ format: DocImportFormat;
264
+ /** The new tabs, in order. */
265
+ tabs: {
266
+ id: string;
267
+ name: string;
268
+ }[];
269
+ /** The file's size. */
270
+ bytes: number;
271
+ /** How many pictures it brought. */
272
+ images: number;
273
+ notes: DocImportNote[];
274
+ /** A doc made from the file, when the folder held none. */
275
+ created?: {
276
+ id: string;
277
+ name: string;
278
+ root: string;
279
+ };
280
+ }
package/src/doc-api.js ADDED
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The contract between a Docs page and its server (the `doc` capability).
3
+ *
4
+ * A doc is a list of tabs; each tab's body is a tree of blocks whose blocks
5
+ * and characters carry stable ids (`<session>.<n>`), and a revision number
6
+ * (`rev`) the server raises on every write. A page takes a writing session
7
+ * (`session`), reads a tab (`read`), and sends its edits as ops on the
8
+ * revision it holds (`call`, an `update` of the tab's body node). Every
9
+ * write anyone makes is announced on the `doc` event of `_api/events`; a
10
+ * page that did not make it reads the tab again.
11
+ *
12
+ * Every route is relative to the artifact's page base, as the runtime's
13
+ * `API` routes are.
14
+ */
15
+ /** Route paths, relative to the page base. */
16
+ export const DOC_API = {
17
+ /** `POST` {@link DocSessionRequest} → {@link DocSessionResponse}. */
18
+ session: '_api/doc/session',
19
+ /** `POST` {@link DocReadRequest} → {@link DocTabResponse}. */
20
+ read: '_api/doc/read',
21
+ /** `POST` {@link DocCallRequest} → {@link DocCallAnswer}. */
22
+ call: '_api/doc/call',
23
+ /** `POST` {@link DocHistoryRequest} → {@link DocHistoryResponse}. */
24
+ history: '_api/doc/history',
25
+ /** `POST` {@link DocVersionRequest} → {@link DocVersionResponse}. */
26
+ version: '_api/doc/version',
27
+ /** `POST` {@link DocRestoreRequest} → {@link DocRestoreResponse}. */
28
+ restore: '_api/doc/restore',
29
+ /** `POST` a file's bytes (`?name=`, optional `&tabName=`) → {@link DocImportResponse}. */
30
+ importFile: '_api/doc/import',
31
+ /** `GET ?format=&tab=&paper=` → the file's bytes. */
32
+ exportFile: '_api/doc/export',
33
+ };
34
+ /** The server-sent event name the frames arrive under on `_api/events`. */
35
+ export const DOC_EVENT = 'doc';
package/src/http-api.d.ts CHANGED
@@ -7,6 +7,8 @@
7
7
  * import these names and shapes, so the two sides cannot drift apart.
8
8
  */
9
9
  import type { AgentDelivery, AgentRequest, AgentSendResult, AgentStatus, ArtifactErrorCode, CommentCreate, CommentThread, ConflictPath, DbChangeEvent, DbDocument, DbWrite, FileListing, FilesChangedEvent, HistoryChangeEvent, HistoryFileDiff, HistoryListing, HistoryRestoreResult, JsonRecord, JsonValue, McpServerEntry, McpToolResult, Peer, PublishBatch, PublishResult, RoomMessage, Viewer } from './capabilities.ts';
10
+ import type { SheetFrame } from './sheet-api.ts';
11
+ import type { DocFrame } from './doc-api.ts';
10
12
  /** Route paths, relative to the page base. */
11
13
  export declare const API: {
12
14
  readonly session: "_api/session";
@@ -26,6 +28,8 @@ export declare const API: {
26
28
  readonly comments: "_api/comments";
27
29
  readonly commentsCreate: "_api/comments/create";
28
30
  readonly commentsReply: "_api/comments/reply";
31
+ readonly commentsEdit: "_api/comments/edit";
32
+ readonly commentsReact: "_api/comments/react";
29
33
  readonly commentsResolve: "_api/comments/resolve";
30
34
  readonly commentsMove: "_api/comments/move";
31
35
  readonly commentsRemove: "_api/comments/remove";
@@ -36,6 +40,7 @@ export declare const API: {
36
40
  readonly historyDiff: "_api/history/diff";
37
41
  readonly historyRestore: "_api/history/restore";
38
42
  readonly historyDismiss: "_api/history/dismiss";
43
+ readonly systemCopy: "_api/design/system-copy";
39
44
  readonly mcpTools: "_api/mcp/tools";
40
45
  readonly mcpCall: "_api/mcp/call";
41
46
  };
@@ -52,9 +57,12 @@ export interface SessionResponse {
52
57
  agent: AgentStatus;
53
58
  /** Stores the type keeps beside its files; absent ones are not offered (`db` / `comments` resolve `null`). */
54
59
  stores?: {
60
+ systemCopy?: boolean;
55
61
  db?: boolean;
56
62
  comments?: boolean;
57
63
  history?: boolean;
64
+ sheet?: boolean;
65
+ doc?: boolean;
58
66
  };
59
67
  }
60
68
  /** `GET _api/files` */
@@ -127,6 +135,21 @@ export interface CommentCreateRequest {
127
135
  export interface CommentReplyRequest {
128
136
  threadId: string;
129
137
  text: string;
138
+ to?: string[];
139
+ }
140
+ /** `POST _api/comments/edit` request body. */
141
+ export interface CommentEditRequest {
142
+ threadId: string;
143
+ messageId: string;
144
+ text: string;
145
+ to?: string[];
146
+ }
147
+ /** `POST _api/comments/react` request body. */
148
+ export interface CommentReactRequest {
149
+ threadId: string;
150
+ messageId: string;
151
+ emoji: string;
152
+ on: boolean;
130
153
  }
131
154
  /** `POST _api/comments/resolve` request body. */
132
155
  export interface CommentResolveRequest {
@@ -147,6 +170,8 @@ export interface CommentRemoveRequest {
147
170
  /** `POST _api/comments/send` request body. */
148
171
  export interface CommentSendRequest {
149
172
  threadId: string;
173
+ /** A reply that does not ask the agent, sent because it took part in the thread. */
174
+ unasked?: boolean;
150
175
  }
151
176
  /** 200 body of the comment routes that change one thread. */
152
177
  export interface CommentThreadResponse {
@@ -212,5 +237,9 @@ export interface ServerEvents {
212
237
  room: RoomMessage;
213
238
  /** A version was recorded (or grew). */
214
239
  history: HistoryChangeEvent;
240
+ /** A frame of the workbook's edit log (types with `store: "workbook"`). */
241
+ sheet: SheetFrame;
242
+ /** A write to a doc, its tabs or its dropdown lists (types with `store: "doc"`). */
243
+ doc: DocFrame;
215
244
  }
216
245
  export type ServerEventName = keyof ServerEvents;
package/src/http-api.js CHANGED
@@ -25,6 +25,8 @@ export const API = {
25
25
  comments: '_api/comments',
26
26
  commentsCreate: '_api/comments/create',
27
27
  commentsReply: '_api/comments/reply',
28
+ commentsEdit: '_api/comments/edit',
29
+ commentsReact: '_api/comments/react',
28
30
  commentsResolve: '_api/comments/resolve',
29
31
  commentsMove: '_api/comments/move',
30
32
  commentsRemove: '_api/comments/remove',
@@ -35,6 +37,7 @@ export const API = {
35
37
  historyDiff: '_api/history/diff',
36
38
  historyRestore: '_api/history/restore',
37
39
  historyDismiss: '_api/history/dismiss',
40
+ systemCopy: '_api/design/system-copy',
38
41
  mcpTools: '_api/mcp/tools',
39
42
  mcpCall: '_api/mcp/call',
40
43
  };
package/src/index.d.ts CHANGED
@@ -6,6 +6,8 @@
6
6
  * - `local-provider.ts`: the provider backed by the local type server.
7
7
  * - `broker.ts`: the provider that brokers calls through the Shell (and `createPageProvider`).
8
8
  * - `http-api.ts`: the HTTP contract shared with `@open-artifact/type-server`.
9
+ * - `sheet-api.ts`: the `sheet` capability's own routes and frames.
10
+ * - `doc-api.ts`: the Docs type's HTTP contract (the `doc` capability).
9
11
  * - `shell.ts`: the page side of the Open Artifact Shell protocol.
10
12
  * - `untrusted.ts`: fencing untrusted text before it reaches a model.
11
13
  */
@@ -14,5 +16,7 @@ export * from './client.ts';
14
16
  export * from './local-provider.ts';
15
17
  export * from './broker.ts';
16
18
  export * from './http-api.ts';
19
+ export * from './sheet-api.ts';
20
+ export * from './doc-api.ts';
17
21
  export * from './shell.ts';
18
22
  export * from './untrusted.ts';
package/src/index.js CHANGED
@@ -6,6 +6,8 @@
6
6
  * - `local-provider.ts`: the provider backed by the local type server.
7
7
  * - `broker.ts`: the provider that brokers calls through the Shell (and `createPageProvider`).
8
8
  * - `http-api.ts`: the HTTP contract shared with `@open-artifact/type-server`.
9
+ * - `sheet-api.ts`: the `sheet` capability's own routes and frames.
10
+ * - `doc-api.ts`: the Docs type's HTTP contract (the `doc` capability).
9
11
  * - `shell.ts`: the page side of the Open Artifact Shell protocol.
10
12
  * - `untrusted.ts`: fencing untrusted text before it reaches a model.
11
13
  */
@@ -14,5 +16,7 @@ export * from "./client.js";
14
16
  export * from "./local-provider.js";
15
17
  export * from "./broker.js";
16
18
  export * from "./http-api.js";
19
+ export * from "./sheet-api.js";
20
+ export * from "./doc-api.js";
17
21
  export * from "./shell.js";
18
22
  export * from "./untrusted.js";
@@ -7,6 +7,8 @@
7
7
  */
8
8
  import { ArtifactError, canEdit, } from "./capabilities.js";
9
9
  import { API, } from "./http-api.js";
10
+ import { SHEET_API, SHEET_EVENT } from "./sheet-api.js";
11
+ import { DOC_API, } from "./doc-api.js";
10
12
  /**
11
13
  * What a session answer means for a page that started as `was`: `null` when
12
14
  * nothing changed, else how its access changed. `status` is the HTTP status
@@ -207,9 +209,12 @@ export function createLocalProvider(options = {}) {
207
209
  const getSession = () => (session ??= json(API.session));
208
210
  const builders = {
209
211
  async artifact() {
210
- const { artifact } = await getSession();
212
+ const { artifact, stores } = await getSession();
211
213
  const capability = {
212
214
  id: artifact.id,
215
+ ...(stores?.systemCopy ? {
216
+ systemCopy: (namespace, action) => json(API.systemCopy, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ namespace, action }) }),
217
+ } : {}),
213
218
  title: async () => (await json(API.session)).artifact.title,
214
219
  list: async () => (await json(API.files)).files,
215
220
  readText: async (path) => new TextDecoder().decode(await readBytes(path)),
@@ -299,17 +304,56 @@ export function createLocalProvider(options = {}) {
299
304
  const capability = {
300
305
  list: async () => (await json(API.comments, { cache: 'no-store' })).threads,
301
306
  create: (input) => thread(API.commentsCreate, { input }),
302
- reply: (threadId, text) => thread(API.commentsReply, { threadId, text }),
307
+ reply: (threadId, text, options) => thread(API.commentsReply, { threadId, text, ...(options?.to?.length ? { to: options.to } : {}) }),
308
+ edit: (threadId, messageId, text, options) => thread(API.commentsEdit, { threadId, messageId, text, ...(options?.to ? { to: options.to } : {}) }),
309
+ react: (threadId, messageId, emoji, on) => thread(API.commentsReact, { threadId, messageId, emoji, on }),
303
310
  setResolved: (threadId, resolved) => thread(API.commentsResolve, { threadId, resolved }),
304
311
  move: (threadId, anchor, location) => thread(API.commentsMove, { threadId, anchor, ...(location ? { location } : {}) }),
305
312
  remove: async (threadId, messageId) => {
306
313
  await post(API.commentsRemove, { threadId, ...(messageId ? { messageId } : {}) });
307
314
  },
308
- sendToAgent: (threadId) => thread(API.commentsSend, { threadId }),
315
+ sendToAgent: (threadId, options) => thread(API.commentsSend, { threadId, ...(options?.unasked ? { unasked: true } : {}) }),
309
316
  onChange: (listener) => subscribe('comments', listener),
310
317
  };
311
318
  return capability;
312
319
  },
320
+ async doc() {
321
+ const { stores } = await getSession();
322
+ if (!stores?.doc)
323
+ return null;
324
+ const capability = {
325
+ session: () => post(DOC_API.session, { client }),
326
+ read: (tab) => post(DOC_API.read, { tab }),
327
+ call: (request) => post(DOC_API.call, { ...request, client }),
328
+ history: (tab) => post(DOC_API.history, { tab }),
329
+ version: (tab, rev) => post(DOC_API.version, { tab, rev }),
330
+ restore: (request) => post(DOC_API.restore, request),
331
+ importFile: (name, bytes, tabName) => json(DOC_API.importFile, { method: 'POST', headers: { 'content-type': 'application/octet-stream' }, body: bytes }, { name, ...(tabName ? { tabName } : {}) }),
332
+ exportFile: async (query) => {
333
+ let response;
334
+ try {
335
+ response = await fetch(url(DOC_API.exportFile, { format: query.format, ...(query.tab ? { tab: query.tab } : {}), ...(query.paper ? { paper: query.paper } : {}) }), { cache: 'no-store' });
336
+ }
337
+ catch (error) {
338
+ throw new ArtifactError('unavailable', error instanceof Error ? error.message : String(error));
339
+ }
340
+ if (!response.ok)
341
+ throw await toError(response);
342
+ const disposition = response.headers.get('content-disposition') ?? '';
343
+ const name = decodeURIComponent(/filename\*=UTF-8''([^;]+)/.exec(disposition)?.[1] ?? '') || `doc.${query.format === 'markdown' ? 'md' : query.format}`;
344
+ let notes = [];
345
+ try {
346
+ notes = JSON.parse(decodeURIComponent(response.headers.get('x-doc-export-notes') ?? '%5B%5D'));
347
+ }
348
+ catch {
349
+ /* no notes */
350
+ }
351
+ return { name, mime: response.headers.get('content-type') ?? 'application/octet-stream', bytes: new Uint8Array(await response.arrayBuffer()), notes };
352
+ },
353
+ onFrame: (listener) => subscribe('doc', listener),
354
+ };
355
+ return capability;
356
+ },
313
357
  async history() {
314
358
  const { stores } = await getSession();
315
359
  if (!stores?.history)
@@ -357,6 +401,19 @@ export function createLocalProvider(options = {}) {
357
401
  };
358
402
  return capability;
359
403
  },
404
+ async sheet() {
405
+ const { stores } = await getSession();
406
+ if (!stores?.sheet)
407
+ return null;
408
+ const capability = {
409
+ read: (request) => post(SHEET_API.read, request),
410
+ send: (request) => post(SHEET_API.send, request),
411
+ widget: (request) => post(SHEET_API.widget, request),
412
+ importFile: (file, name) => json(SHEET_API.importFile, { method: 'POST', headers: { 'content-type': file.type || 'application/octet-stream' }, body: file }, { name }),
413
+ onFrame: (listener) => subscribe(SHEET_EVENT, listener),
414
+ };
415
+ return capability;
416
+ },
360
417
  async downloads() {
361
418
  const capability = {
362
419
  save: async ({ name, data }) => json(API.downloads, { method: 'POST', headers: { 'content-type': data.type || 'application/octet-stream' }, body: data }, { name }),
@@ -0,0 +1,282 @@
1
+ /**
2
+ * The contract between a Sheets page and its server (the `sheet` capability).
3
+ *
4
+ * The workbook is an edit log: revision n is the workbook after the first n
5
+ * edits, each a list of engine operations written in a format version `v`
6
+ * and made on revision `base`. A page keeps its own engine session in step
7
+ * with the log: it reads a snapshot and loads the operations, hears every
8
+ * later edit on the `sheet` event of `_api/events`, and sends its own edits
9
+ * to `send`. Every new event connection gets a snapshot frame first, so a
10
+ * page that reconnects learns how far the log moved meanwhile.
11
+ *
12
+ * Every route is relative to the artifact's page base, as the runtime's
13
+ * `API` routes are.
14
+ */
15
+ export type Json = null | boolean | number | string | Json[] | {
16
+ [key: string]: Json;
17
+ };
18
+ export type JsonObject = {
19
+ [key: string]: Json;
20
+ };
21
+ /** Route paths, relative to the page base. */
22
+ export declare const SHEET_API: {
23
+ /** `POST` {@link SheetReadRequest} → the read's answer. */
24
+ readonly read: "_api/sheet/read";
25
+ /** `POST` {@link SheetSendRequest} → {@link SheetSendResponse}. */
26
+ readonly send: "_api/sheet/send";
27
+ /** `POST` {@link WidgetRequest} → {@link WidgetResponse}. */
28
+ readonly widget: "_api/sheet/widget";
29
+ /** `POST` a file's bytes (`?name=`), kept for the agent to import → {@link ImportFileResponse}. */
30
+ readonly importFile: "_api/sheet/import";
31
+ };
32
+ /** The server-sent event name the frames arrive under on `_api/events`. */
33
+ export declare const SHEET_EVENT = "sheet";
34
+ /** Who made an edit, as pages show them. */
35
+ export interface EditActor {
36
+ /** The id the engine knows the person by (`u_` and 22 letters and digits). */
37
+ personId: string;
38
+ /** True for the agent's edits (made for the owner). */
39
+ isAgent: boolean;
40
+ }
41
+ /** A person as the page names them in cells (people chips) and history. */
42
+ export interface SheetPerson {
43
+ personId: string;
44
+ name: string;
45
+ /** Present only for the owner and the people viewing now. */
46
+ color?: string;
47
+ }
48
+ /** The first frame of a stream: where the log stands and who the page's person is. */
49
+ export interface SnapshotFrame {
50
+ phase: 'snapshot';
51
+ /** The workbook's id (a UUID). */
52
+ workbookId: string;
53
+ /** When the workbook was made, ISO 8601. */
54
+ createdAt: string;
55
+ revision: number;
56
+ /** The newest format version the server takes. */
57
+ newestFormatVersion: number;
58
+ widgets: WidgetVersion[];
59
+ viewer: {
60
+ personId: string;
61
+ canEdit: boolean;
62
+ };
63
+ }
64
+ /** An edit saved to the log (anyone's, the page's own among them). */
65
+ export interface EditFrame {
66
+ phase: 'edit';
67
+ revision: number;
68
+ v: number;
69
+ base: number;
70
+ ops: Json[];
71
+ actor: EditActor;
72
+ }
73
+ /** The clock, for `NOW()` and `TODAY()`: sent at the start, each minute and when the workbook's time zone changes. */
74
+ export interface ClockFrame {
75
+ phase: 'clock';
76
+ unixMilliseconds: number;
77
+ utcOffsetInMinutes: number;
78
+ timeZone: string | null;
79
+ }
80
+ /** A widget's code was published (its charts draw it again). */
81
+ export interface WidgetFrame {
82
+ phase: 'widget';
83
+ id: string;
84
+ pub: number;
85
+ }
86
+ export type SheetFrame = SnapshotFrame | EditFrame | ClockFrame | WidgetFrame;
87
+ /** A widget and its published version. */
88
+ export interface WidgetVersion {
89
+ id: string;
90
+ pub: number;
91
+ }
92
+ /** `POST send`: one of the page's edits, as the engine recorded it. */
93
+ export interface SheetOpsRequest {
94
+ opId: string;
95
+ v: number;
96
+ base: number;
97
+ ops: Json[];
98
+ }
99
+ /**
100
+ * `POST send`: edits a page asks the server to make on revision `base`, as the agent's are (a new workbook's first
101
+ * sheet, its locale).
102
+ */
103
+ export interface SheetEditsRequest {
104
+ opId: string;
105
+ base: number;
106
+ edits: JsonObject[];
107
+ }
108
+ export type SheetSendRequest = SheetOpsRequest | SheetEditsRequest;
109
+ export type SheetSendResponse = {
110
+ kind: 'saved';
111
+ revision: number;
112
+ }
113
+ /** `revision` is where the log stands, for an edits request whose base it is not. */
114
+ | {
115
+ kind: 'refused';
116
+ refusal: SendRefusal;
117
+ revision?: number;
118
+ };
119
+ /**
120
+ * Why a save is refused: the engine's refusal, or one of the store's own.
121
+ * `changedSince` means the edit no longer applies on the edits made since its base.
122
+ */
123
+ export type SendRefusal = 'changedSince' | 'pageIsBehind' | 'unknownFormatVersion' | 'unreadableEdit' | 'tooLarge' | 'notWriter' | (string & {});
124
+ /** The workbook's operations from a revision on, one page (the engine's `receiveLoadPage`). */
125
+ export interface LoadPage {
126
+ kind: 'loadPage';
127
+ from: number;
128
+ revision: number;
129
+ v: number;
130
+ ops: Json[];
131
+ next: number | null;
132
+ }
133
+ /** A version of the history pane: the edits from `firstRevision` to `revision`, newest first. */
134
+ export interface VersionRow {
135
+ revision: number;
136
+ firstRevision: number;
137
+ /** When its last edit was made, ISO 8601. */
138
+ at: string;
139
+ authors: EditActor[];
140
+ }
141
+ /** Edits a page saves as one edit to take others back (restoring a version, undoing an agent's turn). */
142
+ export interface EditsToTakeBack {
143
+ kind: 'editsToTakeBack';
144
+ revision: number;
145
+ edits: JsonObject[];
146
+ }
147
+ /** What a cell or a row held after an edit that changed it, newest first. */
148
+ export interface CellHistoryRow {
149
+ revision: number;
150
+ at: string;
151
+ actor: EditActor;
152
+ [held: string]: Json | EditActor;
153
+ }
154
+ export interface CellHistory {
155
+ kind: 'cellHistory';
156
+ rows: CellHistoryRow[];
157
+ /** Earlier changes were left out. */
158
+ truncated: boolean;
159
+ }
160
+ /** A revision range of edits, both ends included. */
161
+ export interface RevisionRange {
162
+ first: number;
163
+ last: number;
164
+ }
165
+ /** `POST read`: what the page asks the server. */
166
+ export type SheetReadRequest = {
167
+ kind: 'snapshot';
168
+ } | {
169
+ kind: 'load';
170
+ from?: number;
171
+ } | {
172
+ kind: 'loadAtRevision';
173
+ revision: number;
174
+ } | {
175
+ kind: 'versions';
176
+ limit?: number;
177
+ before?: number;
178
+ } | {
179
+ kind: 'editsThatRestore';
180
+ revision: number;
181
+ } | {
182
+ kind: 'editsThatUndo';
183
+ ranges: RevisionRange[];
184
+ } | {
185
+ kind: 'cellHistory';
186
+ sheetId: string;
187
+ r: string;
188
+ c: string;
189
+ } | {
190
+ kind: 'rowHistory';
191
+ sheetId: string;
192
+ r: string;
193
+ } | {
194
+ kind: 'people';
195
+ } | {
196
+ kind: 'sheets';
197
+ } | {
198
+ kind: 'xlsxCharts';
199
+ charts: JsonObject[];
200
+ };
201
+ /** The answers to {@link SheetReadRequest}, by kind. */
202
+ export interface SheetReadAnswers {
203
+ snapshot: SnapshotFrame;
204
+ load: LoadPage;
205
+ loadAtRevision: LoadPage;
206
+ versions: {
207
+ kind: 'versions';
208
+ rows: VersionRow[];
209
+ };
210
+ editsThatRestore: EditsToTakeBack;
211
+ editsThatUndo: EditsToTakeBack;
212
+ cellHistory: CellHistory;
213
+ rowHistory: CellHistory;
214
+ people: {
215
+ kind: 'people';
216
+ people: SheetPerson[];
217
+ };
218
+ sheets: SheetsList;
219
+ xlsxCharts: {
220
+ kind: 'xlsxCharts';
221
+ descriptions: Json[];
222
+ };
223
+ }
224
+ /** The workbook's sheets as the engine lists them (`readSheets`), with its locale. */
225
+ export interface SheetsList {
226
+ kind: 'sheets';
227
+ revision: number;
228
+ locale: string;
229
+ sheets: JsonObject[];
230
+ }
231
+ /** A read the server turned away. */
232
+ export interface SheetReadRefusal {
233
+ kind: 'refused';
234
+ refusal: string;
235
+ }
236
+ /** `POST widget`: a chart widget's node. */
237
+ export type WidgetRequest = {
238
+ verb: 'create';
239
+ opId: string;
240
+ code: string;
241
+ } | {
242
+ verb: 'read';
243
+ id: string;
244
+ } | {
245
+ verb: 'projection';
246
+ id: string;
247
+ } | {
248
+ verb: 'draft';
249
+ id: string;
250
+ basePub: number;
251
+ code: string;
252
+ } | {
253
+ verb: 'delete';
254
+ id: string;
255
+ };
256
+ export interface WidgetState {
257
+ id: string;
258
+ code: string;
259
+ pub: number;
260
+ /** Why the newest code is not published (it is staged), empty when it is. */
261
+ errors: string[];
262
+ }
263
+ export type WidgetResponse = {
264
+ kind: 'widget';
265
+ widget: WidgetState;
266
+ } | {
267
+ kind: 'projection';
268
+ id: string;
269
+ module: string;
270
+ } | {
271
+ kind: 'deleted';
272
+ } | {
273
+ kind: 'refused';
274
+ refusal: string;
275
+ chartId?: string;
276
+ pub?: number;
277
+ };
278
+ /** `POST importFile`: where the file was kept, and whether the agent was asked to import it. */
279
+ export interface ImportFileResponse {
280
+ path: string;
281
+ sentToAgent: boolean;
282
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The contract between a Sheets page and its server (the `sheet` capability).
3
+ *
4
+ * The workbook is an edit log: revision n is the workbook after the first n
5
+ * edits, each a list of engine operations written in a format version `v`
6
+ * and made on revision `base`. A page keeps its own engine session in step
7
+ * with the log: it reads a snapshot and loads the operations, hears every
8
+ * later edit on the `sheet` event of `_api/events`, and sends its own edits
9
+ * to `send`. Every new event connection gets a snapshot frame first, so a
10
+ * page that reconnects learns how far the log moved meanwhile.
11
+ *
12
+ * Every route is relative to the artifact's page base, as the runtime's
13
+ * `API` routes are.
14
+ */
15
+ /** Route paths, relative to the page base. */
16
+ export const SHEET_API = {
17
+ /** `POST` {@link SheetReadRequest} → the read's answer. */
18
+ read: '_api/sheet/read',
19
+ /** `POST` {@link SheetSendRequest} → {@link SheetSendResponse}. */
20
+ send: '_api/sheet/send',
21
+ /** `POST` {@link WidgetRequest} → {@link WidgetResponse}. */
22
+ widget: '_api/sheet/widget',
23
+ /** `POST` a file's bytes (`?name=`), kept for the agent to import → {@link ImportFileResponse}. */
24
+ importFile: '_api/sheet/import',
25
+ };
26
+ /** The server-sent event name the frames arrive under on `_api/events`. */
27
+ export const SHEET_EVENT = 'sheet';
package/src/shell.d.ts CHANGED
@@ -28,6 +28,13 @@ export interface ShellConnection {
28
28
  exportState(request: string, state: ChromeExportState, reason?: string): void;
29
29
  /** Sends the full report; call again whenever any part changes. */
30
30
  report(report: ChromeReport): void;
31
+ currentSheetPage(page: string | null): void;
32
+ copySheetLink(page: string): void;
33
+ currentDesignPage(page: string | null): void;
34
+ currentDocPlace(hash: string): void;
35
+ currentSlide(hash: string): void;
36
+ copySlideLink(hash: string): void;
37
+ requestCommentMode(on: boolean, anchor?: string): void;
31
38
  /** Handles commands; return the export items for `exports`. */
32
39
  onCommand(handler: (command: ChromeCommand) => ChromeExportItem[] | void): () => void;
33
40
  /**
package/src/shell.js CHANGED
@@ -91,6 +91,21 @@ export function connectShell() {
91
91
  exportState(request, state, reason) {
92
92
  post({ openArtifact: 'chrome_export', request, state, ...(reason ? { reason } : {}) });
93
93
  },
94
+ requestCommentMode(on, anchor) {
95
+ post({ openArtifact: 'request_comment_mode', on, ...(anchor ? { anchor } : {}) });
96
+ },
97
+ copySlideLink(hash) {
98
+ post({ openArtifact: 'copy_slide_link', hash });
99
+ },
100
+ currentSheetPage(page) { post({ openArtifact: 'sheet_page', page }); },
101
+ copySheetLink(page) { post({ openArtifact: 'copy_sheet_link', page }); },
102
+ currentDesignPage(page) {
103
+ post({ openArtifact: 'design_page', page });
104
+ },
105
+ currentDocPlace(hash) { post({ openArtifact: 'doc_place', hash }); },
106
+ currentSlide(hash) {
107
+ post({ openArtifact: 'current_slide', hash });
108
+ },
94
109
  report(report) {
95
110
  lastReport = report;
96
111
  post({ openArtifact: 'chrome_report', protocol: SHELL_PROTOCOL, report });