@open-artifact/runtime 0.1.0 → 0.2.1

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.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "The window.openartifact page runtime: capability contracts, the local provider and the Shell protocol.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -28,7 +28,7 @@
28
28
  "NOTICE"
29
29
  ],
30
30
  "dependencies": {
31
- "@open-artifact/protocol": "0.1.0"
31
+ "@open-artifact/protocol": "0.2.1"
32
32
  },
33
33
  "license": "Apache-2.0",
34
34
  "author": {
package/src/broker.js CHANGED
@@ -20,7 +20,7 @@
20
20
  * page on its fallback provider, the local type server.
21
21
  */
22
22
  import { CAP_NAME, CAP_PROTOCOL, REWIRED_MESSAGE, } from '@open-artifact/protocol';
23
- import { ArtifactError, } from "./capabilities.js";
23
+ import { ArtifactError, MCP_CALL_TIMEOUT, } from "./capabilities.js";
24
24
  import { createLocalProvider } from "./local-provider.js";
25
25
  import { shellOrigin } from "./shell.js";
26
26
  /**
@@ -39,6 +39,7 @@ export const BROKERED_METHODS = {
39
39
  db: ['get', 'list', 'write'],
40
40
  comments: ['list', 'create', 'reply', 'setResolved', 'move', 'remove', 'sendToAgent'],
41
41
  history: ['list', 'files', 'read', 'readBytes', 'diff', 'restore', 'dismissNotice'],
42
+ mcp: ['callTool', 'listTools'],
42
43
  };
43
44
  /**
44
45
  * The `cap_ev` event each listener method follows, per capability
@@ -62,7 +63,8 @@ const RESOLVES_NULL = new Set(['user']);
62
63
  /** Rebuilds the error a Shell sent. */
63
64
  function toArtifactError(error) {
64
65
  const code = (error?.code ?? 'unavailable');
65
- return new ArtifactError(code, error?.message ?? 'The Shell refused the call.', error?.paths);
66
+ const retryable = error?.retryable === true;
67
+ return new ArtifactError(code, error?.message ?? 'The Shell refused the call.', error?.paths, retryable);
66
68
  }
67
69
  /** A per-load prefix plus a counter, like the frame runtime's call ids. */
68
70
  function idMaker() {
@@ -195,11 +197,25 @@ export function createShellProvider(options = {}) {
195
197
  resolve(null);
196
198
  }, wantTimeoutMs);
197
199
  });
198
- const call = (cap, method, args, gesture = false) => new Promise((resolve, reject) => {
200
+ const call = (cap, method, args, gesture = false, timeoutMs, signal) => new Promise((resolve, reject) => {
199
201
  const id = nextId();
200
202
  const entry = { cap, gen, resolve, reject, timer: null };
201
203
  pending.set(id, entry);
202
- armTimer(id, entry, CALL_TIMEOUT[cap] ?? DEFAULT_CALL_TIMEOUT);
204
+ armTimer(id, entry, timeoutMs ?? CALL_TIMEOUT[cap] ?? DEFAULT_CALL_TIMEOUT);
205
+ if (signal) {
206
+ // A signal cannot cross postMessage: the call is dropped here and its answer ignored.
207
+ const abort = () => {
208
+ if (pending.get(id) !== entry)
209
+ return;
210
+ pending.delete(id);
211
+ if (entry.timer)
212
+ clearTimeout(entry.timer);
213
+ reject(signal.reason);
214
+ };
215
+ if (signal.aborted)
216
+ return abort();
217
+ signal.addEventListener('abort', abort, { once: true });
218
+ }
203
219
  post({ openArtifact: 'cap', id, cap, method, args, gen }, gesture);
204
220
  });
205
221
  const listen = (cap, event, listener) => {
@@ -294,6 +310,19 @@ export function createShellProvider(options = {}) {
294
310
  const ns = { save: (file) => c('save', [file], true) };
295
311
  return ns;
296
312
  }
313
+ case 'mcp': {
314
+ const ns = {
315
+ callTool: (server, tool, args, opts) => {
316
+ const timeoutMs = opts?.timeoutMs;
317
+ const wire = timeoutMs === undefined ? [server, tool, args] : [server, tool, args, { timeoutMs }];
318
+ // The page waits a little longer than the host does, so the host's own timeout error arrives.
319
+ const budget = Math.min(timeoutMs ?? MCP_CALL_TIMEOUT.defaultMs, MCP_CALL_TIMEOUT.maxMs) + 15_000;
320
+ return call('mcp', 'callTool', wire, false, budget, opts?.signal);
321
+ },
322
+ listTools: (server) => c('listTools', server === undefined ? [] : [server]),
323
+ };
324
+ return ns;
325
+ }
297
326
  default:
298
327
  return null;
299
328
  }
@@ -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 declare const CONTRACT_VERSION = "1.2.0";
13
+ export declare const CONTRACT_VERSION = "1.3.0";
14
14
  /** Machine-readable error codes a capability call may reject with. */
15
15
  export type ArtifactErrorCode =
16
16
  /** A write lost a race: at least one `ifMatch` hash no longer matches. */
@@ -24,7 +24,9 @@ export type ArtifactErrorCode =
24
24
  /** The file or resource does not exist. */
25
25
  | 'not_found'
26
26
  /** The host could not be reached or answered with an unexpected status. */
27
- | 'unavailable';
27
+ | 'unavailable'
28
+ /** A connector (`mcp`) call failed; see {@link McpErrorCode}. */
29
+ | McpErrorCode;
28
30
  /** One path that failed an optimistic-concurrency check. */
29
31
  export interface ConflictPath {
30
32
  /** Artifact-relative path, e.g. `project/Main.dc.html`. */
@@ -39,7 +41,9 @@ export declare class ArtifactError extends Error {
39
41
  readonly code: ArtifactErrorCode;
40
42
  /** Present for `conflict`: every path whose `ifMatch` failed. */
41
43
  readonly paths?: ConflictPath[];
42
- constructor(code: ArtifactErrorCode, message: string, 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);
43
47
  }
44
48
  /** Type guard for {@link ArtifactError} that also works across realms (iframes). */
45
49
  export declare function isArtifactError(value: unknown, code?: ArtifactErrorCode): value is ArtifactError;
@@ -167,6 +171,8 @@ export interface AgentStatus {
167
171
  busy: boolean;
168
172
  /** Display name, e.g. `Agent`. */
169
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;
170
176
  }
171
177
  /** The `agent` capability. */
172
178
  export interface AgentCapability {
@@ -475,6 +481,123 @@ export interface HistoryCapability {
475
481
  /** Subscribes to new versions. Returns an unsubscribe function. */
476
482
  onChange(listener: (event: HistoryChangeEvent) => void): () => void;
477
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
+ }
478
601
  /** Every capability by name. */
479
602
  export interface CapabilityMap {
480
603
  artifact: ArtifactCapability;
@@ -486,6 +609,7 @@ export interface CapabilityMap {
486
609
  db: DbCapability;
487
610
  comments: CommentsCapability;
488
611
  history: HistoryCapability;
612
+ mcp: McpCapability;
489
613
  }
490
614
  export type CapabilityName = keyof CapabilityMap;
491
615
  /** The object installed at `window.openartifact`. */
@@ -10,18 +10,22 @@
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.2.0';
13
+ export const CONTRACT_VERSION = '1.3.0';
14
14
  /** The error object every capability rejects with. */
15
15
  export class ArtifactError extends Error {
16
16
  code;
17
17
  /** Present for `conflict`: every path whose `ifMatch` failed. */
18
18
  paths;
19
- constructor(code, message, paths) {
19
+ /** Present when asking again later may succeed (a busy or timed-out connector). */
20
+ retryable;
21
+ constructor(code, message, paths, retryable) {
20
22
  super(message);
21
23
  this.name = 'ArtifactError';
22
24
  this.code = code;
23
25
  if (paths)
24
26
  this.paths = paths;
27
+ if (retryable)
28
+ this.retryable = true;
25
29
  }
26
30
  }
27
31
  /** Type guard for {@link ArtifactError} that also works across realms (iframes). */
@@ -48,3 +52,22 @@ export const DB_LIMITS = {
48
52
  /** Nesting depth of one document. */
49
53
  maxDepth: 32,
50
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 };
package/src/http-api.d.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  * ({@link ./local-provider.ts}) and the Node server (`@open-artifact/type-server`)
7
7
  * import these names and shapes, so the two sides cannot drift apart.
8
8
  */
9
- import type { AgentDelivery, AgentRequest, AgentSendResult, AgentStatus, ArtifactErrorCode, CommentCreate, CommentThread, ConflictPath, DbChangeEvent, DbDocument, DbWrite, FileListing, FilesChangedEvent, HistoryChangeEvent, HistoryFileDiff, HistoryListing, HistoryRestoreResult, JsonRecord, JsonValue, Peer, PublishBatch, PublishResult, RoomMessage, Viewer } from './capabilities.ts';
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
10
  /** Route paths, relative to the page base. */
11
11
  export declare const API: {
12
12
  readonly session: "_api/session";
@@ -36,6 +36,8 @@ export declare const API: {
36
36
  readonly historyDiff: "_api/history/diff";
37
37
  readonly historyRestore: "_api/history/restore";
38
38
  readonly historyDismiss: "_api/history/dismiss";
39
+ readonly mcpTools: "_api/mcp/tools";
40
+ readonly mcpCall: "_api/mcp/call";
39
41
  };
40
42
  /** Root-relative prefix every upload is served under. */
41
43
  export declare const BLOB_PREFIX = "/_blob/";
@@ -74,6 +76,8 @@ export interface ErrorResponse {
74
76
  code: ArtifactErrorCode;
75
77
  message: string;
76
78
  paths?: ConflictPath[];
79
+ /** Asking again later may succeed (connector calls). */
80
+ retryable?: boolean;
77
81
  }
78
82
  /** `POST _api/agent/send` request body. */
79
83
  export interface AgentSendRequest {
@@ -174,6 +178,24 @@ export type HistoryRestoreResponse = HistoryRestoreResult;
174
178
  export interface HistoryDismissRequest {
175
179
  id: string;
176
180
  }
181
+ /** `GET _api/mcp/tools[?server=]` 200 body (the owner only; others get `not_granted`). */
182
+ export interface McpToolsResponse {
183
+ servers: McpServerEntry[];
184
+ }
185
+ /**
186
+ * `POST _api/mcp/call` request body (the owner only). The 200 body is the
187
+ * tool's {@link McpToolResult}; failures are an {@link ErrorResponse} with an
188
+ * `McpErrorCode`. Closing the request cancels the call.
189
+ */
190
+ export interface McpCallRequest {
191
+ server: string;
192
+ tool: string;
193
+ args: Record<string, unknown>;
194
+ /** Default `MCP_CALL_TIMEOUT.defaultMs`. */
195
+ timeoutMs?: number;
196
+ }
197
+ /** `POST _api/mcp/call` 200 body. */
198
+ export type McpCallResponse = McpToolResult;
177
199
  /** Server-sent events on `GET _api/events?client=<id>`, by event name. */
178
200
  export interface ServerEvents {
179
201
  /** Files changed by someone other than the subscribing client. */
package/src/http-api.js CHANGED
@@ -35,6 +35,8 @@ export const API = {
35
35
  historyDiff: '_api/history/diff',
36
36
  historyRestore: '_api/history/restore',
37
37
  historyDismiss: '_api/history/dismiss',
38
+ mcpTools: '_api/mcp/tools',
39
+ mcpCall: '_api/mcp/call',
38
40
  };
39
41
  /** Root-relative prefix every upload is served under. */
40
42
  export const BLOB_PREFIX = '/_blob/';
@@ -29,7 +29,7 @@ async function toError(response) {
29
29
  /* not JSON: fall through to a status-based code */
30
30
  }
31
31
  const fallback = response.status === 409 ? 'conflict' : response.status === 403 ? 'not_writer' : response.status === 404 ? 'not_found' : 'unavailable';
32
- return new ArtifactError(body.code ?? fallback, body.message ?? `HTTP ${response.status}`, body.paths);
32
+ return new ArtifactError(body.code ?? fallback, body.message ?? `HTTP ${response.status}`, body.paths, body.retryable === true);
33
33
  }
34
34
  /** A random id for this page load, used to suppress echoes of our own writes. */
35
35
  function makeClientId() {
@@ -329,6 +329,34 @@ export function createLocalProvider(options = {}) {
329
329
  };
330
330
  return capability;
331
331
  },
332
+ async mcp() {
333
+ const { viewer } = await getSession();
334
+ if (viewer.role !== 'owner')
335
+ return null;
336
+ const capability = {
337
+ callTool: async (server, tool, args, opts) => {
338
+ const signal = opts?.signal;
339
+ signal?.throwIfAborted();
340
+ const body = { server, tool, args, ...(opts?.timeoutMs === undefined ? {} : { timeoutMs: opts.timeoutMs }) };
341
+ try {
342
+ return await json(API.mcpCall, {
343
+ method: 'POST',
344
+ headers: { 'content-type': 'application/json' },
345
+ body: JSON.stringify(body),
346
+ ...(signal ? { signal } : {}),
347
+ });
348
+ }
349
+ catch (error) {
350
+ // Closing the request cancels the call on the server too.
351
+ if (signal?.aborted)
352
+ throw signal.reason;
353
+ throw error;
354
+ }
355
+ },
356
+ listTools: (server) => json(API.mcpTools, { cache: 'no-store' }, server === undefined ? undefined : { server }),
357
+ };
358
+ return capability;
359
+ },
332
360
  async downloads() {
333
361
  const capability = {
334
362
  save: async ({ name, data }) => json(API.downloads, { method: 'POST', headers: { 'content-type': data.type || 'application/octet-stream' }, body: data }, { name }),