@covia/covia-sdk 1.18.0 → 1.19.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/dist/index.mjs CHANGED
@@ -35,6 +35,13 @@ var CoviaError = class extends Error {
35
35
  this.message = message;
36
36
  }
37
37
  };
38
+ var MCPError = class extends CoviaError {
39
+ constructor(message, code, data) {
40
+ super(message, code);
41
+ this.name = "MCPError";
42
+ this.data = data;
43
+ }
44
+ };
38
45
  var GridError = class extends CoviaError {
39
46
  constructor(statusCode, message, responseBody = null) {
40
47
  super(`HTTP ${statusCode}: ${message}`, statusCode);
@@ -1596,17 +1603,17 @@ async function* parseSSEStream(response, options) {
1596
1603
  // src/asset-cache.ts
1597
1604
  var PREFIX = "covia:asset-meta:";
1598
1605
  var LocalStorageMetadataStore = class {
1599
- get(hash) {
1606
+ get(key) {
1600
1607
  try {
1601
- const raw = localStorage.getItem(PREFIX + hash);
1608
+ const raw = localStorage.getItem(PREFIX + key);
1602
1609
  return raw ? JSON.parse(raw) : void 0;
1603
1610
  } catch {
1604
1611
  return void 0;
1605
1612
  }
1606
1613
  }
1607
- put(hash, metadata) {
1614
+ put(key, metadata) {
1608
1615
  try {
1609
- localStorage.setItem(PREFIX + hash, JSON.stringify(metadata));
1616
+ localStorage.setItem(PREFIX + key, JSON.stringify(metadata));
1610
1617
  } catch {
1611
1618
  }
1612
1619
  }
@@ -1639,6 +1646,15 @@ function getAssetMetadataStore() {
1639
1646
  function normaliseHash(hash) {
1640
1647
  return (hash.startsWith("0x") ? hash.slice(2) : hash).toLowerCase();
1641
1648
  }
1649
+ function persistentCacheKey(ref) {
1650
+ const parsed = parseDidUrl(ref);
1651
+ if (!parsed.did) return null;
1652
+ if (parsed.namespace !== Namespace.ASSET) return null;
1653
+ const hash = assetHash(ref);
1654
+ if (!hash) return null;
1655
+ const bare = normaliseHash(hash);
1656
+ return /^[0-9a-f]+$/.test(bare) ? `${parsed.did}/${Namespace.ASSET}/${bare}` : null;
1657
+ }
1642
1658
 
1643
1659
  // src/AdapterManager.ts
1644
1660
  var ADAPTERS_PATH = "v/info/adapters";
@@ -2456,6 +2472,14 @@ var AssetManager = class {
2456
2472
  * a mutable lattice path the venue resolves (`w/my-assets/foo`, `o/my-op`,
2457
2473
  * `<DID>/w/...`). Only content-addressed (immutable) refs are cached;
2458
2474
  * mutable paths are always re-fetched, so a changed value is never served stale.
2475
+ *
2476
+ * **Content-addressed refs are caller-relative, not global** (covia#502). A
2477
+ * bare hash or `a/<hash>` names the asset in *your own* `a/` namespace, so it
2478
+ * 404s for a hash someone else registered, and for an anonymous request.
2479
+ * Address another owner's asset explicitly as `<ownerDID>/a/<hash>`, and the
2480
+ * venue's own catalog as `<venueDID>/a/<hash>`. Only the DID-qualified form
2481
+ * is portable, so only it is eligible for the cross-session metadata store;
2482
+ * caller-relative refs are cached in memory on this manager alone.
2459
2483
  * @param assetId - Asset identifier or lattice address
2460
2484
  * @returns Returns either an Operation or DataAsset based on the asset's metadata
2461
2485
  */
@@ -2464,8 +2488,9 @@ var AssetManager = class {
2464
2488
  return this._wrap(assetId, this.cache.get(assetId));
2465
2489
  }
2466
2490
  const hash = assetHash(assetId);
2467
- if (hash) {
2468
- const persisted = getAssetMetadataStore()?.get(normaliseHash(hash));
2491
+ const storeKey = persistentCacheKey(assetId);
2492
+ if (storeKey) {
2493
+ const persisted = getAssetMetadataStore()?.get(storeKey);
2469
2494
  if (persisted) {
2470
2495
  this.cache.set(assetId, persisted);
2471
2496
  return this._wrap(assetId, persisted);
@@ -2479,7 +2504,7 @@ var AssetManager = class {
2479
2504
  );
2480
2505
  if (hash) {
2481
2506
  this.cache.set(assetId, data);
2482
- getAssetMetadataStore()?.put(normaliseHash(hash), data);
2507
+ if (storeKey) getAssetMetadataStore()?.put(storeKey, data);
2483
2508
  }
2484
2509
  return this._wrap(assetId, data);
2485
2510
  } catch (error) {
@@ -2715,6 +2740,7 @@ var OperationManager = class {
2715
2740
  // src/WorkspaceManager.ts
2716
2741
  var SCOPED_NAMESPACES = ["t", "n", "c"];
2717
2742
  var SCOPE_UNEXPANDED = /Cannot use '[tnc]\/' prefix outside/;
2743
+ var MAX_PROJECT_FIELDS = 16;
2718
2744
  function scopedNamespaceOf(path) {
2719
2745
  const head = path.split("/", 1)[0];
2720
2746
  return SCOPED_NAMESPACES.includes(head) ? head : void 0;
@@ -2759,6 +2785,11 @@ var WorkspaceManager = class {
2759
2785
  // selector-bearing read by complaining the shorthand has no execution scope,
2760
2786
  // after which scoped reads expand client-side instead.
2761
2787
  this.scopeExpansionSupported = true;
2788
+ // Whether this venue projects fields on `list` (covia#191). A venue without
2789
+ // it ignores the unknown `fields` param and answers a plain list, so the
2790
+ // probe is "asked for fields, got no values" — never a version check, which
2791
+ // covia-sdk#36 showed an embedded venue can misreport.
2792
+ this.fieldsSupported = true;
2762
2793
  }
2763
2794
  /** GET a job-free `/api/v1/values/{op}` read; omit undefined params. */
2764
2795
  _values(op, params) {
@@ -2848,6 +2879,76 @@ var WorkspaceManager = class {
2848
2879
  if (ucans?.length) return this.unsupported("UCAN-authorised workspace listings");
2849
2880
  return this.valuesRead("list", { path, limit, offset });
2850
2881
  }
2882
+ /**
2883
+ * List a node's children *and* read named subpaths of each one, in a single
2884
+ * round trip (covia#191) — the standard partial-response / sparse-fieldset
2885
+ * pattern, and the cure for the collection-view N+1 that list-then-read-each
2886
+ * forces on every page.
2887
+ *
2888
+ * ```ts
2889
+ * const page = await venue.workspace.listFields('j', ['status', 'meta/updated'], { limit: 50 });
2890
+ * page.values['<jobid>']['status']; // → { exists: true, value: 'COMPLETE' }
2891
+ * ```
2892
+ *
2893
+ * Each field is defined as a `read` of `<path>/<key>/<field>` and carries
2894
+ * single-read semantics verbatim: stored null is present, absent is
2895
+ * `{exists:false}`, and a value past `maxSize` withholds `value` and sets
2896
+ * `truncated`. Projection applies *after* the `limit`/`offset` key page, so
2897
+ * work is bounded by `limit × fields.length`.
2898
+ *
2899
+ * Output shape only — no filtering, no ordering. Filter the projected
2900
+ * records locally; for a recency subset use key design plus `slice`.
2901
+ *
2902
+ * On a venue that predates projection this falls back to `list()` plus a
2903
+ * bounded `read()` per (key, field), returning the identical shape, and
2904
+ * remembers not to ask that venue again.
2905
+ *
2906
+ * @param path Parent node. Must be a keyed node (map/Index) — a sequence or
2907
+ * scalar is a venue 400.
2908
+ * @param fields Subpaths to project per key; may be nested (`meta/updated`).
2909
+ * At most 16, the venue's cap.
2910
+ */
2911
+ async listFields(path, fields, opts = {}) {
2912
+ const { limit, offset, maxSize } = opts;
2913
+ if (fields.length === 0) throw new CoviaError("listFields needs at least one field");
2914
+ if (fields.length > MAX_PROJECT_FIELDS) {
2915
+ throw new CoviaError(
2916
+ `A fields projection may name at most ${MAX_PROJECT_FIELDS} subpaths; got ${fields.length}`
2917
+ );
2918
+ }
2919
+ if (this.fieldsSupported) {
2920
+ const result = await this.valuesRead(
2921
+ "list",
2922
+ { path, limit, offset, fields: fields.join(","), maxSize }
2923
+ );
2924
+ if (result.values) return result;
2925
+ if (!result.exists || result.keys === void 0) return { ...result, values: {} };
2926
+ this.fieldsSupported = false;
2927
+ }
2928
+ return this.projectClientSide(path, fields, { limit, offset, maxSize });
2929
+ }
2930
+ /**
2931
+ * The pre-covia#191 fallback: one `list`, then a `read` per (key, field).
2932
+ * Fan-out is bounded by the page the list already returned, so this costs
2933
+ * `keys.length × fields.length` reads for the page — exactly the N+1 the
2934
+ * server-side projection exists to remove, which is why it is the fallback
2935
+ * and not the default.
2936
+ */
2937
+ async projectClientSide(path, fields, opts) {
2938
+ const base = await this.valuesRead(
2939
+ "list",
2940
+ { path, limit: opts.limit, offset: opts.offset }
2941
+ );
2942
+ const keys = base.keys ?? [];
2943
+ const parent = path.replace(/\/+$/, "");
2944
+ const rows = await Promise.all(keys.map(async (key) => {
2945
+ const projected = await Promise.all(fields.map(async (field) => {
2946
+ return [field, await this.read(`${parent}/${key}/${field}`, opts.maxSize)];
2947
+ }));
2948
+ return [key, Object.fromEntries(projected)];
2949
+ }));
2950
+ return { ...base, values: Object.fromEntries(rows) };
2951
+ }
2851
2952
  async slice(path, offset, limit, ucans) {
2852
2953
  if (ucans?.length) return this.unsupported("UCAN-authorised workspace slices");
2853
2954
  return this.valuesRead("slice", { path, offset, limit });
@@ -3244,6 +3345,185 @@ var A2AManager = class {
3244
3345
  }
3245
3346
  };
3246
3347
 
3348
+ // src/MCPManager.ts
3349
+ var TOOL_CALL_OP = "v/ops/mcp/tools-call";
3350
+ var DEFAULT_MCP_PATH = "/mcp";
3351
+ var HEADER_SESSION_ID = "Mcp-Session-Id";
3352
+ function isResponseFrame(value) {
3353
+ return typeof value === "object" && value !== null && ("result" in value || "error" in value);
3354
+ }
3355
+ var MCPManager = class {
3356
+ constructor(venue) {
3357
+ this.venue = venue;
3358
+ this.nextId = 1;
3359
+ }
3360
+ /** The venue's MCP discovery document (`GET /.well-known/mcp`). */
3361
+ discovery() {
3362
+ return this.venue.mcpDiscovery();
3363
+ }
3364
+ /**
3365
+ * List the tools this venue bridges, job-free.
3366
+ *
3367
+ * @param options.cursor Continue a previous page. MCP pagination is opaque:
3368
+ * pass back the `nextCursor` a page returned, and stop when it is absent.
3369
+ */
3370
+ async listTools(options = {}) {
3371
+ const params = options.cursor !== void 0 ? { cursor: options.cursor } : {};
3372
+ const result = await this.request(
3373
+ "tools/list",
3374
+ params,
3375
+ { signal: options.signal }
3376
+ );
3377
+ const page = { tools: result?.tools ?? [] };
3378
+ if (result?.nextCursor !== void 0) page.nextCursor = result.nextCursor;
3379
+ return page;
3380
+ }
3381
+ /**
3382
+ * Every tool the venue bridges, draining the cursor.
3383
+ *
3384
+ * A server that never stops handing back a cursor would loop forever, so a
3385
+ * repeated cursor is treated as the end rather than trusted.
3386
+ */
3387
+ async listAllTools(options = {}) {
3388
+ const tools = [];
3389
+ const seen = /* @__PURE__ */ new Set();
3390
+ let cursor;
3391
+ for (; ; ) {
3392
+ const page = await this.listTools({ cursor, signal: options.signal });
3393
+ tools.push(...page.tools);
3394
+ if (page.nextCursor === void 0 || seen.has(page.nextCursor)) return tools;
3395
+ seen.add(page.nextCursor);
3396
+ cursor = page.nextCursor;
3397
+ }
3398
+ }
3399
+ /**
3400
+ * Call a bridged tool natively and return its MCP result.
3401
+ *
3402
+ * This is the direct protocol call: the answer comes back in the response,
3403
+ * and the caller never holds a Job. The venue still runs the tool through
3404
+ * its job machinery and records it — "direct" describes what *this* call
3405
+ * hands back, not whether the venue keeps a record.
3406
+ *
3407
+ * Use {@link callToolTracked} when you want the `Job` itself: to stream it,
3408
+ * inspect its steps, link to its receipt, or continue it when it pauses.
3409
+ *
3410
+ * An MCP tool that fails *its own* execution answers with `isError: true`
3411
+ * and the failure in `content` — a successful protocol call reporting a
3412
+ * failed tool, which is not thrown. Only a protocol-level error throws.
3413
+ */
3414
+ async callTool(name, args = {}, options = {}) {
3415
+ return this.request(
3416
+ "tools/call",
3417
+ { name, arguments: args },
3418
+ { signal: options.signal }
3419
+ );
3420
+ }
3421
+ /**
3422
+ * Call a tool through the `v/ops/mcp/tools-call` operation, returning the
3423
+ * `Job` so the run is an inspectable, linkable record.
3424
+ *
3425
+ * The operation is the venue's bridge to *any* MCP server, so `server`
3426
+ * defaults to this venue's own base URL — pointing the bridge back at the
3427
+ * venue, which is how a local tool gets called with a Job in hand. Name a
3428
+ * different `server` (with a `token` if it needs one) to reach a third-party
3429
+ * MCP server through the venue instead, which the native endpoint cannot do.
3430
+ *
3431
+ * Unlike {@link callTool} this always persists a job, so it belongs to a
3432
+ * user-driven execution, never a page load.
3433
+ */
3434
+ async callToolTracked(name, args = {}, options = {}) {
3435
+ const { server, token, ...invokeOptions } = options;
3436
+ const input = {
3437
+ server: server ?? this.venue.baseUrl,
3438
+ toolName: name,
3439
+ arguments: args
3440
+ };
3441
+ if (token !== void 0) input.token = token;
3442
+ return this.venue.operations.invoke(TOOL_CALL_OP, input, invokeOptions);
3443
+ }
3444
+ /**
3445
+ * Send an arbitrary JSON-RPC method to the venue's MCP endpoint — the escape
3446
+ * hatch for methods this manager does not wrap (`resources/list`,
3447
+ * `prompts/list`, …).
3448
+ *
3449
+ * Request ids are minted and correlated here, so callers never supply one.
3450
+ */
3451
+ async request(method, params = {}, options = {}) {
3452
+ const id = this.nextId++;
3453
+ const endpoint = await this.endpoint();
3454
+ const headers = {
3455
+ // The venue may answer either way; advertise both and branch on what
3456
+ // comes back rather than assuming JSON (which is the bug in every
3457
+ // hand-rolled copy of this call).
3458
+ Accept: "application/json, text/event-stream"
3459
+ };
3460
+ if (this.sessionId) headers[HEADER_SESSION_ID] = this.sessionId;
3461
+ const response = await venueStream(this.venue, endpoint, {
3462
+ method: "POST",
3463
+ headers,
3464
+ body: JSON.stringify({ jsonrpc: "2.0", id, method, params }),
3465
+ signal: options.signal
3466
+ });
3467
+ const session = response.headers?.get?.(HEADER_SESSION_ID);
3468
+ if (session) this.sessionId = session;
3469
+ const frame = (response.headers?.get?.("Content-Type") ?? "").includes("text/event-stream") ? await this.readSSEFrame(response, id, options.signal) : await response.json();
3470
+ return this.unwrap(frame, method, id);
3471
+ }
3472
+ /** The resolved MCP endpoint path, from discovery, probed once. */
3473
+ endpoint() {
3474
+ return this.endpointPromise ?? (this.endpointPromise = this.resolveEndpoint());
3475
+ }
3476
+ /**
3477
+ * Discovery names the endpoint; `${baseUrl}/mcp` is the compatibility
3478
+ * default. Discovery failing is not fatal — a venue that serves `/mcp`
3479
+ * without advertising it still works, so a failed probe falls through to the
3480
+ * default rather than failing the call that triggered it.
3481
+ */
3482
+ async resolveEndpoint() {
3483
+ try {
3484
+ const doc = await this.discovery();
3485
+ const advertised = [doc?.server_url, typeof doc?.endpoint === "string" ? doc.endpoint : void 0].find((v) => typeof v === "string" && v.length > 0);
3486
+ if (advertised) {
3487
+ if (/^https?:\/\//i.test(advertised)) {
3488
+ return advertised.startsWith(this.venue.baseUrl) ? advertised.slice(this.venue.baseUrl.length) || DEFAULT_MCP_PATH : advertised;
3489
+ }
3490
+ return advertised.startsWith("/") ? advertised : `/${advertised}`;
3491
+ }
3492
+ } catch {
3493
+ }
3494
+ return DEFAULT_MCP_PATH;
3495
+ }
3496
+ /**
3497
+ * Read the response frame from an SSE-framed answer: the first event whose
3498
+ * JSON-RPC id matches the request. Notifications and unrelated frames are
3499
+ * skipped rather than mistaken for the answer.
3500
+ */
3501
+ async readSSEFrame(response, id, signal) {
3502
+ for await (const event of parseSSEStream(response, signal ? { signal } : void 0)) {
3503
+ let payload;
3504
+ try {
3505
+ payload = event.json();
3506
+ } catch {
3507
+ continue;
3508
+ }
3509
+ if (isResponseFrame(payload) && payload.id === id) return payload;
3510
+ }
3511
+ throw new CoviaError(
3512
+ `MCP stream ended without a response to request ${id}`
3513
+ );
3514
+ }
3515
+ /** JSON-RPC envelope → result, or a typed error. */
3516
+ unwrap(frame, method, id) {
3517
+ if (frame?.error) {
3518
+ throw new MCPError(frame.error.message || `MCP ${method} failed`, frame.error.code, frame.error.data);
3519
+ }
3520
+ if (!frame || !("result" in frame)) {
3521
+ throw new CoviaError(`MCP ${method} returned no result for request ${id}`);
3522
+ }
3523
+ return frame.result;
3524
+ }
3525
+ };
3526
+
3247
3527
  // src/Agent.ts
3248
3528
  var Agent = class _Agent {
3249
3529
  constructor(id, venue) {
@@ -3461,6 +3741,9 @@ var Venue = class _Venue {
3461
3741
  get users() {
3462
3742
  return this._users ?? (this._users = new UserManager(this));
3463
3743
  }
3744
+ get mcp() {
3745
+ return this._mcp ?? (this._mcp = new MCPManager(this));
3746
+ }
3464
3747
  get a2a() {
3465
3748
  return this._a2a ?? (this._a2a = new A2AManager(this));
3466
3749
  }
@@ -3800,4 +4083,4 @@ function relayDelegation(privateKey, venueDID, lifetimeSeconds, caps = []) {
3800
4083
  (*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
3801
4084
  */
3802
4085
 
3803
- export { A2AManager, AdapterManager, Agent, AgentManager, AgentSessionNotFoundError, AgentStatus, Asset, AssetManager, AssetNotFoundError, Auth, BasicAuth, BearerAuth, ChatSession, CoviaConnectionError, CoviaError, CoviaTimeoutError, CredentialsHTTP, DLFSManager, DataAsset, Ed25519Auth, Grid, GridError, Job, JobFailedError, JobManager, JobNotFoundError, JobStatus, KeyPairAuth, MemoryManager, Namespace, NoAuth, NotFoundError, Operation, OperationManager, RateLimitError, RunStatus, ScopedWorkspace, SecretManager, SkillManager, UCANManager, UnsupportedVenueFeatureError, UserManager, VENUE_RELAY, Venue, VenueIdentityChangedError, WorkspaceManager, assetHash, createSSEEvent, createUCANJWT, decodePublicKey, didFor, didFromPublicKey, didMethod, didUrl, encodePublicKey, fetchStreamWithError, fetchWithError, generateKeyPair, getAssetIdFromPath, getAssetIdFromVenueId, getAssetMetadataStore, getParsedAssetId, grant, hexToPrivateKey, identityToken, isDid, isJobComplete, isJobFinished, isJobPaused, logger, parseDidUrl, parseRetryAfterMs, parseSSEStream, privateKeyToHex, relayDelegation, retryDelayMs, setAssetMetadataStore, venueBaseUrlCandidates };
4086
+ export { A2AManager, AdapterManager, Agent, AgentManager, AgentSessionNotFoundError, AgentStatus, Asset, AssetManager, AssetNotFoundError, Auth, BasicAuth, BearerAuth, ChatSession, CoviaConnectionError, CoviaError, CoviaTimeoutError, CredentialsHTTP, DLFSManager, DataAsset, Ed25519Auth, Grid, GridError, Job, JobFailedError, JobManager, JobNotFoundError, JobStatus, KeyPairAuth, MCPError, MCPManager, MemoryManager, Namespace, NoAuth, NotFoundError, Operation, OperationManager, RateLimitError, RunStatus, ScopedWorkspace, SecretManager, SkillManager, UCANManager, UnsupportedVenueFeatureError, UserManager, VENUE_RELAY, Venue, VenueIdentityChangedError, WorkspaceManager, assetHash, createSSEEvent, createUCANJWT, decodePublicKey, didFor, didFromPublicKey, didMethod, didUrl, encodePublicKey, fetchStreamWithError, fetchWithError, generateKeyPair, getAssetIdFromPath, getAssetIdFromVenueId, getAssetMetadataStore, getParsedAssetId, grant, hexToPrivateKey, identityToken, isDid, isJobComplete, isJobFinished, isJobPaused, logger, parseDidUrl, parseRetryAfterMs, parseSSEStream, privateKeyToHex, relayDelegation, retryDelayMs, setAssetMetadataStore, venueBaseUrlCandidates };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@covia/covia-sdk",
3
- "version": "1.18.0",
3
+ "version": "1.19.0",
4
4
  "description": "Typescript library for covia-ai",
5
5
  "packageManager": "pnpm@11.9.0",
6
6
  "main": "./dist/index.js",
@@ -28,7 +28,7 @@
28
28
  "lint:fix": "eslint src --fix",
29
29
  "test": "jest",
30
30
  "test:unit": "jest src/__tests__/",
31
- "test:integration": "jest venue.test.ts",
31
+ "test:integration": "jest --runTestsByPath venue.test.ts",
32
32
  "prepublishOnly": "npm run build && npm run test:unit",
33
33
  "prepare": "npm run build"
34
34
  },