@pstdio/sdk 0.45.0 → 0.46.0-nightly.20261024001730

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.
@@ -1,3 +1,3 @@
1
- import { Bf as SessionCreateRequest, Gf as SessionFollowUpResponse, Gt as WorkspaceListItem, Hf as SessionDetails, If as SessionAttachmentDetails, Js as Skill, Nc as Page, Pc as PageQuery, Pf as Session, Qs as SkillWithContentDetails, S as ProjectUpdateRequest, T as FileRecord, Uf as SessionFollowUpDecision, Vf as SessionCreateResponse, Wf as SessionFollowUpRequest, Wt as Workspace, Xs as SkillFile, Ys as SkillDetails, Zs as SkillWithContent, ac as NotificationActorType, ah as AgentDetails, b as ProjectCreateRequest, cc as NotificationOrigin, ch as AgentSkillsLayout, dc as SetNotificationStatusInput, dh as ActivityEntry, ec as CreateNotificationInput, fc as UpdateNotificationInput, fh as ActivityPage, ic as NotificationAction, ih as AgentAvailabilityType, lc as NotificationPriority, nc as ListNotificationsResponse, nh as AssetReference, oc as NotificationFinalStatus, oh as AgentInfo, p as Settings, qf as SessionStatus, rc as Notification, rh as AssetTransfer, s as WorkspaceEntryMoveInput, sc as NotificationKind, sh as AgentModel, tc as ListNotificationsQuery, uc as NotificationStatus, uh as harnessLocalId, v as InitialWorkspaceRequest, x as ProjectDetails, y as Project } from "./index-j28tAAxd.js";
1
+ import { Ah as AgentInfo, Ao as NotificationFinalStatus, C as ProjectUpdateRequest, Cd as SessionStatus, Dh as AssetTransfer, Do as Notification, E as FileRecord, Eh as AssetReference, Eo as ListNotificationsResponse, Fh as ActivityEntry, Fo as SetNotificationStatusInput, Gt as Workspace, Ih as ActivityPage, Io as UpdateNotificationInput, Kt as WorkspaceListItem, Mh as AgentSkillsLayout, Mo as NotificationOrigin, No as NotificationPriority, Oh as AgentAvailabilityType, Oo as NotificationAction, Ph as harnessLocalId, Po as NotificationStatus, S as ProjectDetails, So as SkillWithContentDetails, To as ListNotificationsQuery, _d as SessionCreateResponse, b as Project, bd as SessionFollowUpRequest, bo as SkillFile, fd as SessionAttachmentDetails, gd as SessionCreateRequest, is as PageQuery, jh as AgentModel, jo as NotificationKind, kh as AgentDetails, ko as NotificationActorType, p as Settings, rs as Page, s as WorkspaceEntryMoveInput, ud as Session, vd as SessionDetails, vo as Skill, wo as CreateNotificationInput, x as ProjectCreateRequest, xd as SessionFollowUpResponse, xo as SkillWithContent, y as InitialWorkspaceRequest, yd as SessionFollowUpDecision, yo as SkillDetails } from "./index-DWpHZ0Dd.js";
2
2
  export { type ActivityEntry, type ActivityPage, type AgentAvailabilityType, type AgentDetails, type AgentInfo, type AgentModel, type AgentSkillsLayout, type AssetReference, type AssetTransfer, type CreateNotificationInput, type FileRecord, type InitialWorkspaceRequest, type ListNotificationsQuery, type ListNotificationsResponse, type Notification, type NotificationAction, type NotificationActorType, type NotificationFinalStatus, type NotificationKind, type NotificationOrigin, type NotificationPriority, type NotificationStatus, type Page, type PageQuery, type Project, type ProjectCreateRequest, type ProjectDetails, type ProjectUpdateRequest, type Session, type SessionAttachmentDetails, type SessionCreateRequest, type SessionCreateResponse, type SessionDetails, type SessionFollowUpDecision, type SessionFollowUpRequest, type SessionFollowUpResponse, type SessionStatus, type SetNotificationStatusInput, type Settings, type Skill, type SkillDetails, type SkillFile, type SkillWithContent, type SkillWithContentDetails, type UpdateNotificationInput, type Workspace, type WorkspaceEntryMoveInput, type WorkspaceListItem, harnessLocalId };
3
3
  export {};
@@ -0,0 +1,2 @@
1
+ import "./index-DWpHZ0Dd.js";
2
+ export {};
@@ -0,0 +1,2 @@
1
+ import "./index-DWpHZ0Dd.js";
2
+ export {};
@@ -935,10 +935,31 @@ var createCommandContextDefaults = (input) => {
935
935
  delete: unavailable
936
936
  },
937
937
  sessions: {
938
+ getConversation: unavailable,
939
+ getConversationSources: unavailable,
940
+ getQueuedMessages: unavailable,
941
+ stream: unavailable,
942
+ retainResources: unavailable,
943
+ approve: unavailable,
944
+ rename: unavailable,
945
+ archive: unavailable,
946
+ delete: unavailable,
947
+ updateStatus: unavailable,
948
+ listActivity: unavailable,
949
+ removeQueuedFollowUp: unavailable,
950
+ moveQueuedFollowUp: unavailable,
951
+ getDraftHarnessCommands: unavailable,
952
+ getHarnessCommands: unavailable,
953
+ invokeHarnessOperation: unavailable,
954
+ resolveSessionId: unavailable,
955
+ uploadAttachment: unavailable,
956
+ readAttachment: unavailable,
957
+ deleteAttachment: unavailable,
938
958
  query: async () => ({ items: [], nextCursor: null }),
939
959
  get: async () => null,
940
960
  create: unavailable,
941
961
  followup: unavailable,
962
+ stop: unavailable,
942
963
  addAnchors: async (id, anchors) => {
943
964
  await resources.addAnchors(coreResource("session", id), anchors);
944
965
  },
@@ -955,7 +976,7 @@ var createCommandContextDefaults = (input) => {
955
976
  return;
956
977
  }, list: async () => [], cancel: unavailable },
957
978
  account: {
958
- status: async () => ({ login: null, cloudProjects: [], cloudProjectsLoaded: true }),
979
+ status: async () => ({ login: null, cloudProjects: [], cloudProjectsLoaded: true, features: null }),
959
980
  login: unavailable,
960
981
  loginStatus: unavailable,
961
982
  cancelLogin: unavailable,
@@ -7021,6 +7042,9 @@ var environmentTargetSchema = environmentIdentitySchema.extend({
7021
7042
  workbenchId: identitySchema,
7022
7043
  workspaceId: identitySchema
7023
7044
  });
7045
+ // ../pstdio-sync-contracts/src/protocol/blob-references.ts
7046
+ var blobReferenceFanout = 256;
7047
+
7024
7048
  // ../pstdio-sync-contracts/src/protocol/envelopes.ts
7025
7049
  var syncIdSchema = string2().regex(/^[A-Za-z0-9_-]{16,128}$/);
7026
7050
  var sequenceSchema = number2().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
@@ -7124,16 +7148,9 @@ var syncErrorSchema = discriminatedUnion("error", [
7124
7148
  ])
7125
7149
  })
7126
7150
  ]);
7127
- // ../pstdio-sync-contracts/src/protocol/keys.ts
7128
- var spaceKeySchema = strictObject({
7129
- generation: number2().int().positive(),
7130
- secret: base64url2().length(43)
7131
- });
7132
- var spaceKeysSchema = strictObject({
7133
- project: array(spaceKeySchema).min(1),
7134
- personal: array(spaceKeySchema).min(1)
7135
- });
7151
+
7136
7152
  // ../pstdio-sync-contracts/src/protocol/routes.ts
7153
+ var syncProtocolVersion = 1;
7137
7154
  var space = { projectId: identitySchema, spaceOwner: identitySchema.nullable() };
7138
7155
  var routeSchema = discriminatedUnion("kind", [
7139
7156
  strictObject({
@@ -7147,7 +7164,7 @@ var routeSchema = discriminatedUnion("kind", [
7147
7164
  kind: literal("blob"),
7148
7165
  ...space,
7149
7166
  blobId: syncIdSchema,
7150
- operation: _enum(["begin", "finish", "read"])
7167
+ operation: _enum(["begin", "begin-manifest", "finish", "read"])
7151
7168
  }),
7152
7169
  strictObject({
7153
7170
  kind: literal("part"),
@@ -7155,8 +7172,27 @@ var routeSchema = discriminatedUnion("kind", [
7155
7172
  blobId: syncIdSchema,
7156
7173
  number: number2().int().min(1).max(1e4)
7157
7174
  }),
7158
- strictObject({ kind: literal("live"), projectId: identitySchema })
7175
+ strictObject({ kind: literal("live"), projectId: identitySchema }),
7176
+ strictObject({ kind: literal("capabilities"), projectId: identitySchema })
7159
7177
  ]);
7178
+
7179
+ // ../pstdio-sync-contracts/src/protocol/blob-manifests.ts
7180
+ var syncCapabilitiesSchema = strictObject({
7181
+ protocolVersion: literal(syncProtocolVersion),
7182
+ features: array(string2().min(1))
7183
+ });
7184
+ var blobManifestBeginSchema = blobBeginSchema.extend({
7185
+ children: array(syncIdSchema).max(blobReferenceFanout).refine((ids) => new Set(ids).size === ids.length, "Child blob IDs must be unique")
7186
+ });
7187
+ // ../pstdio-sync-contracts/src/protocol/keys.ts
7188
+ var spaceKeySchema = strictObject({
7189
+ generation: number2().int().positive(),
7190
+ secret: base64url2().length(43)
7191
+ });
7192
+ var spaceKeysSchema = strictObject({
7193
+ project: array(spaceKeySchema).min(1),
7194
+ personal: array(spaceKeySchema).min(1)
7195
+ });
7160
7196
  // ../pstdio-sync-contracts/src/state.ts
7161
7197
  var checkpointSchema = strictObject({ epoch: identitySchema, sequence: revisionSchema });
7162
7198
  var recordSchema = strictObject({
@@ -7804,6 +7840,14 @@ var createMemoryResources = (prefixes, sequences = new Map, links = createMemory
7804
7840
  const found = resources.get(id);
7805
7841
  return found?.scope === scope && found.identity.kind === kind ? structuredClone(found.identity) : null;
7806
7842
  },
7843
+ identityMany: async ({ kind, ids }) => {
7844
+ if (ids.length > 100)
7845
+ throw new Error("An identity batch can read at most 100 resources");
7846
+ return ids.map((id) => {
7847
+ const found = resources.get(id);
7848
+ return found?.scope === scope && found.identity.kind === kind ? structuredClone(found.identity) : null;
7849
+ });
7850
+ },
7807
7851
  findByShorthand: async ({ kind, shorthand }) => [...resources.values()].filter((entry) => entry.scope === scope).map((entry) => entry.identity).filter((resource) => resource.kind === kind && (resource.shorthand === shorthand || resource.aliases.includes(shorthand))).sort((a, b) => Number(b.shorthand === shorthand) - Number(a.shorthand === shorthand)).map((resource) => structuredClone(resource))
7808
7852
  };
7809
7853
  };
@@ -13945,7 +13989,15 @@ var readValue = (value, document2) => {
13945
13989
  if (reference.kind === "list") {
13946
13990
  const items = document2.getMap(`${reference.name}:items`);
13947
13991
  const order = document2.getArray(`${reference.name}:order`).toArray();
13948
- return order.filter((key, index) => items.has(key) && order.lastIndexOf(key) === index).map((key) => readValue(items.get(key), document2));
13992
+ const seen = new Set;
13993
+ const visible = [];
13994
+ for (let index = order.length - 1;index >= 0; index--) {
13995
+ const key = order[index];
13996
+ if (items.has(key) && !seen.has(key))
13997
+ visible.push(key);
13998
+ seen.add(key);
13999
+ }
14000
+ return visible.reverse().map((key) => readValue(items.get(key), document2));
13949
14001
  }
13950
14002
  return Object.fromEntries([...document2.getMap(reference.name)].map(([key, entry]) => [key, readValue(entry, document2)]));
13951
14003
  };
@@ -13989,9 +14041,11 @@ var writeList = (document2, name, values, author) => {
13989
14041
  for (let index = 0;index < keys.length; index++)
13990
14042
  writeValue(items, keys[index], values[index], `${name}:items`, author);
13991
14043
  const current = order.toArray();
14044
+ const seen = new Set;
13992
14045
  for (let index = current.length - 1;index >= 0; index--) {
13993
- if (!wanted.has(current[index]) || current.lastIndexOf(current[index]) !== index)
14046
+ if (!wanted.has(current[index]) || seen.has(current[index]))
13994
14047
  order.delete(index, 1);
14048
+ seen.add(current[index]);
13995
14049
  }
13996
14050
  for (let index = 0;index < keys.length; index++) {
13997
14051
  if (order.get(index) === keys[index])
@@ -14045,6 +14099,25 @@ var seedText = (document2, name, value) => {
14045
14099
  }
14046
14100
  };
14047
14101
 
14102
+ // ../pstdio-sync/src/document-record.ts
14103
+ var readDocumentRecord = async (document2, recordId) => {
14104
+ const name = document2.getMap("records").get(recordId);
14105
+ const record = name ? document2.getMap(name) : undefined;
14106
+ const deleted = !record && document2.getMap("deleted").has(recordId);
14107
+ const shared = record?.get("sharedKind");
14108
+ const value = record ? readValue(record.get("value"), document2) : null;
14109
+ const asset = structuredClone(record?.get("asset") ?? null);
14110
+ const sharedValue = shared ? { kind: shared, value: readValue(record?.get("shared"), document2) } : null;
14111
+ return {
14112
+ recordId,
14113
+ exists: !!record || deleted,
14114
+ deleted,
14115
+ value,
14116
+ asset,
14117
+ shared: sharedValue,
14118
+ revision: await fingerprint({ value, asset, shared: sharedValue, deleted })
14119
+ };
14120
+ };
14048
14121
  // ../pstdio-sync/src/document-replacements.ts
14049
14122
  var snapshotDocumentRecords = (document2) => {
14050
14123
  const records = new Map;
@@ -14119,6 +14192,26 @@ var findDocumentReplacements = (base, first, second, merged) => {
14119
14192
  }
14120
14193
  return replacements;
14121
14194
  };
14195
+ // ../pstdio-sync/src/document-json.ts
14196
+ var wellFormedText = (value) => value.replace(/[\uD800-\uDFFF]/gu, "�");
14197
+ var normalizeDocumentJson = (value) => {
14198
+ let result = value;
14199
+ if (typeof value === "string")
14200
+ result = wellFormedText(value);
14201
+ else if (Array.isArray(value)) {
14202
+ const items = [];
14203
+ for (const item of value)
14204
+ items.push(normalizeDocumentJson(item));
14205
+ result = items;
14206
+ } else if (value !== null && typeof value === "object") {
14207
+ const entries = [];
14208
+ for (const [key, item] of Object.entries(value))
14209
+ entries.push([wellFormedText(key), normalizeDocumentJson(item)]);
14210
+ result = Object.fromEntries(entries);
14211
+ }
14212
+ return result;
14213
+ };
14214
+
14122
14215
  // ../pstdio-sync/src/document-edits.ts
14123
14216
  var applyShared = (document2, record, name, shared, author) => {
14124
14217
  const kind = shared.kind.split(".")[0];
@@ -14174,10 +14267,14 @@ var applyDocumentEdit = (document2, edit, author) => {
14174
14267
  }
14175
14268
  const record = document2.getMap(name);
14176
14269
  if (Object.hasOwn(edit, "replace"))
14177
- writeValue(record, "value", edit.replace, name, author);
14178
- if (edit.asset !== undefined && canonicalJson(record.get("asset") ?? null) !== canonicalJson(edit.asset))
14179
- record.set("asset", structuredClone(edit.asset));
14180
- for (const shared of edit.shared ?? []) {
14270
+ writeValue(record, "value", normalizeDocumentJson(edit.replace), name, author);
14271
+ if (edit.asset !== undefined) {
14272
+ const asset = normalizeDocumentJson(edit.asset);
14273
+ if (canonicalJson(record.get("asset") ?? null) !== canonicalJson(asset))
14274
+ record.set("asset", asset);
14275
+ }
14276
+ for (const input of edit.shared ?? []) {
14277
+ const shared = normalizeDocumentJson(input);
14181
14278
  const apply = () => applyShared(document2, record, name, shared, author);
14182
14279
  if (author)
14183
14280
  author(name, "shared", shared, apply);
@@ -14241,34 +14338,338 @@ var validateDocumentGroup = (document2, group) => {
14241
14338
  }
14242
14339
  };
14243
14340
 
14341
+ // ../pstdio-sync/src/record-query.ts
14342
+ var fieldValue = (value, path) => {
14343
+ let current = value;
14344
+ for (const key of path) {
14345
+ if (current === null || typeof current !== "object" || Array.isArray(current))
14346
+ return;
14347
+ current = current[key];
14348
+ }
14349
+ return current;
14350
+ };
14351
+ var typedFieldValue = (value, field) => {
14352
+ const current = fieldValue(value, field.path);
14353
+ if (current == null)
14354
+ return current;
14355
+ if (field.type === "array")
14356
+ return Array.isArray(current) && current.every((item) => typeof item === "string") ? current : undefined;
14357
+ return typeof current === field.type ? current : undefined;
14358
+ };
14359
+ var validateIndex = (index) => {
14360
+ if (!Object.keys(index.fields).length)
14361
+ throw new Error("An index needs fields");
14362
+ for (const [name, field] of Object.entries(index.fields)) {
14363
+ if (!name || !["string", "number", "boolean", "array"].includes(field.type))
14364
+ throw new Error("Invalid index field");
14365
+ if (!field.path.length || field.path.some((part) => typeof part !== "string" || !part))
14366
+ throw new Error("Invalid field path");
14367
+ }
14368
+ for (const name of [...index.equality ?? [], ...(index.orderBy ?? []).map((sort) => sort.field)]) {
14369
+ if (!Object.hasOwn(index.fields, name))
14370
+ throw new Error(`Unknown index field: ${name}`);
14371
+ if (index.fields[name].type === "array")
14372
+ throw new Error("Array fields cannot order a page");
14373
+ }
14374
+ for (const sort of index.orderBy ?? [])
14375
+ if (sort.direction !== "asc" && sort.direction !== "desc")
14376
+ throw new Error("Invalid sort direction");
14377
+ };
14378
+ var validateIndexes = (indexes) => {
14379
+ const names = new Set;
14380
+ for (const index of indexes) {
14381
+ if (!index.name || names.has(index.name))
14382
+ throw new Error("Index names must be unique and nonempty");
14383
+ names.add(index.name);
14384
+ validateIndex(index);
14385
+ }
14386
+ };
14387
+ var queryField = (index, name) => {
14388
+ if (!Object.hasOwn(index.fields, name))
14389
+ throw new Error(`Unknown index field: ${name}`);
14390
+ return index.fields[name];
14391
+ };
14392
+ var validateOperator = (field, predicate) => {
14393
+ if (predicate.op === "equalsIgnoreCase" && field.type !== "string")
14394
+ throw new Error("Case-insensitive equality requires a string field");
14395
+ if (predicate.op === "contains" && field.type !== "string" && field.type !== "array")
14396
+ throw new Error("Contains requires a string or array field");
14397
+ if (field.type === "array" && ["gt", "gte", "lt", "lte"].includes(predicate.op))
14398
+ throw new Error("Array fields do not support ordering predicates");
14399
+ if (!["eq", "ne", "gt", "gte", "lt", "lte", "contains", "equalsIgnoreCase", "textContains", "in", "notIn"].includes(predicate.op))
14400
+ throw new Error("Unsupported query predicate");
14401
+ };
14402
+ var validatePredicateValues = (field, predicate) => {
14403
+ validateOperator(field, predicate);
14404
+ const values = predicate.op === "in" || predicate.op === "notIn" ? predicate.value : [predicate.value];
14405
+ for (const value of values) {
14406
+ if (value === null && predicate.op !== "contains" && predicate.op !== "equalsIgnoreCase")
14407
+ continue;
14408
+ const type = Array.isArray(value) ? "array" : typeof value;
14409
+ const expected = predicate.op === "contains" && field.type === "array" ? "string" : field.type;
14410
+ if (type !== expected)
14411
+ throw new Error(`Query value must be ${expected}`);
14412
+ if (Array.isArray(value) && value.some((item) => typeof item !== "string"))
14413
+ throw new Error("Query arrays contain strings");
14414
+ if (typeof value === "number" && !Number.isFinite(value))
14415
+ throw new Error("Query number must be finite");
14416
+ }
14417
+ };
14418
+ var validateScalarTextPredicate = (field, value) => {
14419
+ if (field.type === "array")
14420
+ throw new Error("Text contains requires a scalar field");
14421
+ if (typeof value !== "string")
14422
+ throw new Error("Query value must be string");
14423
+ };
14424
+ var validatePredicate = (index, predicate, depth = 0) => {
14425
+ if (!predicate)
14426
+ return;
14427
+ if (depth > 8)
14428
+ throw new Error("Query predicate is too deep");
14429
+ if ("not" in predicate) {
14430
+ validatePredicate(index, predicate.not, depth + 1);
14431
+ return;
14432
+ }
14433
+ if ("all" in predicate || "any" in predicate) {
14434
+ const children = "all" in predicate ? predicate.all : predicate.any;
14435
+ if (children.length > 100)
14436
+ throw new Error("Too many query predicates");
14437
+ for (const child of children)
14438
+ validatePredicate(index, child, depth + 1);
14439
+ return;
14440
+ }
14441
+ const field = queryField(index, predicate.field);
14442
+ if (["empty", "notEmpty", "exists", "missing"].includes(predicate.op))
14443
+ return;
14444
+ if (!("value" in predicate))
14445
+ throw new Error("Query predicate needs a value");
14446
+ if (predicate.op === "textContains")
14447
+ return validateScalarTextPredicate(field, predicate.value);
14448
+ validatePredicateValues(field, predicate);
14449
+ };
14450
+ var compareStrings = (left, right) => {
14451
+ const a = Array.from(left, (character) => character.codePointAt(0));
14452
+ const b = Array.from(right, (character) => character.codePointAt(0));
14453
+ for (let position = 0;position < Math.min(a.length, b.length); position++)
14454
+ if (a[position] !== b[position])
14455
+ return a[position] - b[position];
14456
+ return a.length - b.length;
14457
+ };
14458
+ var compareQueryValues = (left, right) => {
14459
+ if (left === right || left == null && right == null)
14460
+ return 0;
14461
+ if (left == null)
14462
+ return 1;
14463
+ if (right == null)
14464
+ return -1;
14465
+ if (typeof left === "string" && typeof right === "string")
14466
+ return compareStrings(left, right);
14467
+ if (Array.isArray(left) && Array.isArray(right)) {
14468
+ if (left.length !== right.length)
14469
+ return left.length - right.length;
14470
+ for (let position = 0;position < left.length; position++) {
14471
+ const order = compareStrings(String(left[position]), String(right[position]));
14472
+ if (order)
14473
+ return order;
14474
+ }
14475
+ return 0;
14476
+ }
14477
+ return left < right ? -1 : 1;
14478
+ };
14479
+ var matchesPredicate = (index, value, predicate) => {
14480
+ if (!predicate)
14481
+ return true;
14482
+ if ("not" in predicate) {
14483
+ if (matchesPredicate(index, value, predicate.not))
14484
+ return false;
14485
+ return true;
14486
+ }
14487
+ if ("all" in predicate) {
14488
+ for (const child of predicate.all)
14489
+ if (!matchesPredicate(index, value, child))
14490
+ return false;
14491
+ return true;
14492
+ }
14493
+ if ("any" in predicate) {
14494
+ for (const child of predicate.any)
14495
+ if (matchesPredicate(index, value, child))
14496
+ return true;
14497
+ return false;
14498
+ }
14499
+ return matchesFieldPredicate(index, value, predicate);
14500
+ };
14501
+ var matchesFieldPredicate = (index, value, predicate) => {
14502
+ const actual = typedFieldValue(value, queryField(index, predicate.field));
14503
+ const empty = actual == null || actual === "" || Array.isArray(actual) && !actual.length;
14504
+ switch (predicate.op) {
14505
+ case "exists":
14506
+ return actual !== undefined;
14507
+ case "missing":
14508
+ return actual === undefined;
14509
+ case "empty":
14510
+ return empty;
14511
+ case "notEmpty":
14512
+ return !empty;
14513
+ case "eq":
14514
+ return canonicalJson(actual ?? null) === canonicalJson(predicate.value);
14515
+ case "ne":
14516
+ return canonicalJson(actual ?? null) !== canonicalJson(predicate.value);
14517
+ case "equalsIgnoreCase":
14518
+ return typeof actual === "string" && actual.toLowerCase() === String(predicate.value).toLowerCase();
14519
+ case "textContains":
14520
+ return actual != null && String(actual).toLowerCase().includes(String(predicate.value).toLowerCase());
14521
+ case "in":
14522
+ return predicate.value.some((item) => canonicalJson(actual ?? null) === canonicalJson(item));
14523
+ case "notIn":
14524
+ return !predicate.value.some((item) => canonicalJson(actual ?? null) === canonicalJson(item));
14525
+ case "contains":
14526
+ if (Array.isArray(actual))
14527
+ return actual.some((item) => canonicalJson(item) === canonicalJson(predicate.value));
14528
+ return typeof actual === "string" && typeof predicate.value === "string" && actual.toLowerCase().includes(predicate.value.toLowerCase());
14529
+ default: {
14530
+ if (actual == null || predicate.value === null)
14531
+ return false;
14532
+ const order = compareQueryValues(actual, predicate.value);
14533
+ if (predicate.op === "gt")
14534
+ return order > 0;
14535
+ if (predicate.op === "gte")
14536
+ return order >= 0;
14537
+ if (predicate.op === "lt")
14538
+ return order < 0;
14539
+ return order <= 0;
14540
+ }
14541
+ }
14542
+ };
14543
+ var encodeQueryCursor = (cursor) => btoa(unescape(encodeURIComponent(JSON.stringify(cursor))));
14544
+ var queryWindow = (query, revision) => {
14545
+ const limit = query.limit ?? 100;
14546
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100)
14547
+ throw new Error("Query limit must be between 1 and 100");
14548
+ const offset = query.offset ?? 0;
14549
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset > 0 && query.cursor)
14550
+ throw new Error("Query offset must be a nonnegative integer without a cursor");
14551
+ if (query.revision !== undefined && query.revision !== revision)
14552
+ throw new Error("Query revision is stale; restart the query");
14553
+ return { limit, offset };
14554
+ };
14555
+ var prepareRecordQuery = async (owner, index, query, revision) => {
14556
+ validatePredicate(index, query.where);
14557
+ const fields = query.fields ?? Object.keys(index.fields);
14558
+ for (const name of fields)
14559
+ queryField(index, name);
14560
+ const { limit, offset } = queryWindow(query, revision);
14561
+ const identity = await fingerprint({
14562
+ owner,
14563
+ index,
14564
+ where: query.where ?? null,
14565
+ fields
14566
+ });
14567
+ let after;
14568
+ if (query.cursor) {
14569
+ try {
14570
+ after = JSON.parse(decodeURIComponent(escape(atob(query.cursor))));
14571
+ } catch {
14572
+ throw new Error("Invalid query cursor");
14573
+ }
14574
+ if (after.identity !== identity || after.revision !== revision)
14575
+ throw new Error("Query cursor is stale; restart the query");
14576
+ if (typeof after.recordId !== "string" || !Array.isArray(after.values) || after.values.length !== (index.orderBy?.length ?? 0))
14577
+ throw new Error("Invalid query cursor");
14578
+ }
14579
+ return { fields, limit, offset, identity, after };
14580
+ };
14581
+
14582
+ // ../pstdio-sync/src/memory-record-queries.ts
14583
+ var definitions = new WeakMap;
14584
+ var indexFor = (document2, name) => {
14585
+ const index = definitions.get(document2)?.get(name);
14586
+ if (!index)
14587
+ throw new Error(`Storage index not installed: ${name}`);
14588
+ return index;
14589
+ };
14590
+ var compareRecords = (index, left, right) => {
14591
+ for (const [position, sort] of (index.orderBy ?? []).entries()) {
14592
+ const a = left.values[position];
14593
+ const b = right.values[position];
14594
+ const order = compareQueryValues(a, b);
14595
+ if (!order)
14596
+ continue;
14597
+ if (a == null || b == null || sort.direction === "asc")
14598
+ return order;
14599
+ return -order;
14600
+ }
14601
+ if (left.recordId === right.recordId)
14602
+ return 0;
14603
+ return compareQueryValues(left.recordId, right.recordId);
14604
+ };
14605
+ var createMemoryRecordQueries = (owner, store) => {
14606
+ const records = (document2) => Promise.all([...document2.getMap("records").keys()].map((id) => readDocumentRecord(document2, id)));
14607
+ const api = {
14608
+ defineIndexes: async (indexes) => {
14609
+ validateIndexes(indexes);
14610
+ await store.transaction(owner, async ({ document: document2 }) => {
14611
+ definitions.set(document2, new Map(indexes.map((index) => [index.name, structuredClone(index)])));
14612
+ });
14613
+ },
14614
+ readMany: (ids) => store.transaction(owner, async ({ document: document2 }) => {
14615
+ if (ids.length > 100)
14616
+ throw new Error("A batch can read at most 100 records");
14617
+ return Promise.all(ids.map((id) => readDocumentRecord(document2, id)));
14618
+ }),
14619
+ query: (query) => store.transaction(owner, async ({ document: document2 }) => {
14620
+ const index = indexFor(document2, query.index);
14621
+ const saved = await records(document2);
14622
+ const revision = await fingerprint(saved);
14623
+ const page = await prepareRecordQuery(owner, index, query, revision);
14624
+ const values = (record) => (index.orderBy ?? []).map((sort) => typedFieldValue(record.value, queryField(index, sort.field)) ?? null);
14625
+ const compare = (left, right) => compareRecords(index, left, right);
14626
+ const selected = saved.filter((record) => !record.deleted && (index.prefix === undefined || record.recordId.startsWith(index.prefix)) && matchesPredicate(index, record.value, query.where)).map((record) => ({ record, recordId: record.recordId, values: values(record) })).filter((record) => !page.after || compare(record, page.after) > 0).sort(compare);
14627
+ const visible = selected.slice(page.offset, page.offset + page.limit);
14628
+ const last = visible.at(-1);
14629
+ return {
14630
+ revision,
14631
+ records: visible.map(({ record }) => ({
14632
+ recordId: record.recordId,
14633
+ revision: record.revision,
14634
+ fields: Object.fromEntries(page.fields.map((name) => [name, typedFieldValue(record.value, queryField(index, name)) ?? null]))
14635
+ })),
14636
+ cursor: last && selected.length > page.offset + page.limit ? encodeQueryCursor({ identity: page.identity, revision, recordId: last.recordId, values: last.values }) : null
14637
+ };
14638
+ }),
14639
+ aggregate: (query) => store.transaction(owner, async ({ document: document2 }) => {
14640
+ const index = indexFor(document2, query.index);
14641
+ validatePredicate(index, query.where);
14642
+ const saved = await records(document2);
14643
+ const selected = saved.filter((record) => !record.deleted && (index.prefix === undefined || record.recordId.startsWith(index.prefix)) && matchesPredicate(index, record.value, query.where));
14644
+ const groups = new Map;
14645
+ if (query.groupBy !== undefined)
14646
+ for (const record of selected) {
14647
+ const value = typedFieldValue(record.value, queryField(index, query.groupBy)) ?? null;
14648
+ const key = JSON.stringify(value);
14649
+ const group = groups.get(key) ?? { value, count: 0 };
14650
+ group.count++;
14651
+ groups.set(key, group);
14652
+ }
14653
+ return {
14654
+ revision: await fingerprint(saved),
14655
+ count: selected.length,
14656
+ groups: [...groups.values()].sort((a, b) => compareQueryValues(a.value, b.value))
14657
+ };
14658
+ })
14659
+ };
14660
+ return api;
14661
+ };
14662
+
14244
14663
  // ../pstdio-sync/src/document-storage.ts
14245
14664
  var outcome = (operationId) => ({
14246
14665
  operationId,
14247
14666
  state: "saved-locally",
14248
14667
  status: "saved-locally"
14249
14668
  });
14250
- var readRecord = async (document2, recordId) => {
14251
- const name = document2.getMap("records").get(recordId);
14252
- const record = name ? document2.getMap(name) : undefined;
14253
- const deleted = !record && document2.getMap("deleted").has(recordId);
14254
- const shared = record?.get("sharedKind");
14255
- const value = record ? readValue(record.get("value"), document2) : null;
14256
- const asset = structuredClone(record?.get("asset") ?? null);
14257
- const sharedValue = shared ? { kind: shared, value: readValue(record?.get("shared"), document2) } : null;
14258
- return {
14259
- recordId,
14260
- exists: !!record || deleted,
14261
- deleted,
14262
- value,
14263
- asset,
14264
- shared: sharedValue,
14265
- revision: await fingerprint({ value, asset, shared: sharedValue, deleted })
14266
- };
14267
- };
14268
14669
  var createDocumentStorage = (input) => {
14269
14670
  const { owner, store } = input;
14270
14671
  const observed = async (document2, id) => {
14271
- const record = await readRecord(document2, id);
14672
+ const record = await readDocumentRecord(document2, id);
14272
14673
  store.observer?.read(owner, record);
14273
14674
  return record;
14274
14675
  };
@@ -14296,6 +14697,11 @@ var createDocumentStorage = (input) => {
14296
14697
  }
14297
14698
  },
14298
14699
  records: {
14700
+ ...store.queries?.(owner) ?? createMemoryRecordQueries(owner, store),
14701
+ transaction: (run) => store.transaction(owner, (state) => run(createDocumentStorage({
14702
+ ...input,
14703
+ store: { transaction: async (_owner, action) => action(state), observer: store.observer }
14704
+ }).records)),
14299
14705
  read: (id, _branch) => store.transaction(owner, async ({ document: document2 }) => observed(document2, id)),
14300
14706
  list: (prefix = "") => store.transaction(owner, async ({ document: document2 }) => Promise.all([...document2.getMap("records").keys()].filter((id) => id.startsWith(prefix)).sort().map((id) => observed(document2, id)))),
14301
14707
  outcome: (id) => store.transaction(owner, async (state) => await state.operation(id) ? outcome(id) : undefined),
@@ -14326,7 +14732,7 @@ var createDocumentStorage = (input) => {
14326
14732
  });
14327
14733
  }
14328
14734
  state.remember(group.operationId, identity);
14329
- return Promise.all(group.edits.map((edit) => readRecord(doc, edit.recordId)));
14735
+ return Promise.all(group.edits.map((edit) => readDocumentRecord(doc, edit.recordId)));
14330
14736
  });
14331
14737
  const result = outcome(group.operationId);
14332
14738
  store.observer?.committed(owner, saved, result);
@@ -14364,12 +14770,9 @@ var legacyNamespaceStorage = (records, namespace) => {
14364
14770
  // ../pstdio-sync/src/legacy.ts
14365
14771
  var legacyJson = (value) => JSON.parse(JSON.stringify(value));
14366
14772
  var createLegacyRecordStorage = (input) => {
14367
- const within = (namespace, action) => input.store.transaction(input.owner, (state) => action(legacyNamespaceStorage(createDocumentStorage({
14368
- ...input,
14369
- store: { transaction: async (_owner, run) => run(state), observer: input.store.observer }
14370
- }).records, namespace)));
14773
+ const within = (namespace, action) => input.records.transaction((records) => action(legacyNamespaceStorage(records, namespace)));
14371
14774
  const namespaceApi = (namespace) => {
14372
- const current = legacyNamespaceStorage(createDocumentStorage(input).records, namespace);
14775
+ const current = legacyNamespaceStorage(input.records, namespace);
14373
14776
  const read = (records, id) => records.read(id);
14374
14777
  const replace = async (records, id, value, deleted = false) => {
14375
14778
  const current = await read(records, id);
@@ -14517,8 +14920,11 @@ var createMemoryDocumentStore = () => {
14517
14920
  var createMemoryRecordOwner = (assets, seed = {}, identity = {}) => {
14518
14921
  const owner = { workbenchId: crypto.randomUUID(), extensionId: "test-extension", ...identity };
14519
14922
  const baseStore = createMemoryDocumentStore();
14520
- const seedStorage = createLegacyRecordStorage({ store: baseStore, owner }).scope("project", owner.workbenchId);
14923
+ const seedStorage = createLegacyRecordStorage({
14924
+ records: createDocumentStorage({ store: baseStore, owner }).records
14925
+ }).scope("project", owner.workbenchId);
14521
14926
  const initialized = Promise.all([
14927
+ createDocumentStorage({ owner, store: baseStore }).records.defineIndexes(seed.indexes ?? []),
14522
14928
  ...Object.entries(seed.kv ?? {}).map(([key, value]) => seedStorage.kv.set(key, value)),
14523
14929
  ...Object.entries(seed.collections ?? {}).flatMap(([name, items]) => Object.entries(items).map(([id, value]) => seedStorage.collection(name).set(id, value)))
14524
14930
  ]);
@@ -14539,7 +14945,7 @@ var createMemoryRecordOwner = (assets, seed = {}, identity = {}) => {
14539
14945
  }
14540
14946
  }
14541
14947
  });
14542
- const legacy = createLegacyRecordStorage({ store, owner });
14948
+ const legacy = createLegacyRecordStorage({ records: createDocumentStorage({ store, owner }).records });
14543
14949
  return {
14544
14950
  workbenchId: owner.workbenchId,
14545
14951
  extensionId: owner.extensionId,
package/dist/testing.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Dc as ResourceRef, Qp as JsonObject, Sc as ResourceAnchorQuery, _s as ExtensionStorageApi, em as JsonValue, pc as ExtensionResourcesApi, xa as CommandContext, ya as ArtifactFile, yc as ResourceAnchor } from "./index-j28tAAxd.js";
1
+ import { Ca as CommandContext, Ko as ResourceAnchorQuery, Lo as ExtensionResourcesApi, Sm as JsonObject, Uf as StorageRecordIndex, Uo as ResourceAnchor, Zo as ResourceRef, io as ExtensionStorageApi, wm as JsonValue, xa as ArtifactFile } from "./index-DWpHZ0Dd.js";
2
2
  type ContextNamespace = "project" | "resources" | "views" | "navigation" | "artifacts" | "projectFiles" | "packageFiles" | "extensionFiles" | "files" | "skills" | "sessions" | "workspaces" | "commands" | "events" | "activity" | "notify" | "automation" | "process" | "net" | "connections" | "logger" | "settings" | "account" | "stream" | "invocation";
3
3
  type CommandContextOverrides = Partial<Omit<CommandContext, ContextNamespace>> & { [K in ContextNamespace]?: Partial<CommandContext[K]>; };
4
4
  interface CommandContextInput<TParams extends Record<string, unknown>> {
@@ -67,6 +67,8 @@ export declare const createMemoryResources: (prefixes: Record<string, string>, s
67
67
  interface MemoryStorageSeed {
68
68
  kv?: Record<string, unknown>;
69
69
  collections?: Record<string, Record<string, unknown>>;
70
+ /** Use the extension's storageIndexes declaration to mirror local host installation. */
71
+ indexes?: StorageRecordIndex[];
70
72
  }
71
73
  interface MemoryStorageOptions extends MemoryStorageSeed {
72
74
  /** Reuse these owner IDs to simulate the same extension and workbench on two devices. */