@meshagent/meshagent-ts-auth 0.36.2 → 0.37.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.
@@ -3047,7 +3047,8 @@ meshagent.auth = (() => {
3047
3047
  "../meshagent-ts/dist/browser/agent.js"(exports) {
3048
3048
  "use strict";
3049
3049
  Object.defineProperty(exports, "__esModule", { value: true });
3050
- exports.RemoteTaskRunner = exports.RemoteToolkit = exports.Toolkit = exports.Tool = void 0;
3050
+ exports.RemoteTaskRunner = exports.HostedToolkit = exports.Toolkit = exports.Tool = void 0;
3051
+ exports.startHostedToolkit = startHostedToolkit;
3051
3052
  var response_1 = require_response();
3052
3053
  var tool_content_type_1 = require_tool_content_type();
3053
3054
  var utils_1 = require_utils();
@@ -3097,7 +3098,11 @@ meshagent.auth = (() => {
3097
3098
  };
3098
3099
  exports.Tool = Tool;
3099
3100
  var Toolkit = class {
3100
- constructor({ tools, rules = [] }) {
3101
+ constructor({ name, title = name, description = "", thumbnailUrl, tools, rules = [] }) {
3102
+ this.name = name;
3103
+ this.title = title;
3104
+ this.description = description;
3105
+ this.thumbnailUrl = thumbnailUrl;
3101
3106
  this.tools = tools;
3102
3107
  this.rules = rules;
3103
3108
  }
@@ -3126,30 +3131,38 @@ meshagent.auth = (() => {
3126
3131
  }
3127
3132
  };
3128
3133
  exports.Toolkit = Toolkit;
3129
- var RemoteToolkit = class extends Toolkit {
3130
- constructor({ name, title, description, room, tools, rules = [] }) {
3131
- super({ tools, rules });
3134
+ var HostedToolkit = class {
3135
+ constructor({ toolkit, stopHostedToolkit }) {
3136
+ this.toolkit = toolkit;
3137
+ this._stopHostedToolkit = stopHostedToolkit;
3138
+ }
3139
+ async stop() {
3140
+ await this._stopHostedToolkit();
3141
+ }
3142
+ };
3143
+ exports.HostedToolkit = HostedToolkit;
3144
+ var _RemoteToolkitWrapper = class {
3145
+ constructor({ toolkit, room }) {
3146
+ this.toolkit = toolkit;
3132
3147
  this.client = room;
3133
- this.name = name;
3134
- this.title = title;
3135
- this.description = description;
3136
3148
  }
3137
3149
  async start({ public_: isPublic = false } = {}) {
3138
3150
  const handler = this._toolCall.bind(this);
3139
- this.client.protocol.addHandler(`room.tool_call.${this.name}`, handler);
3151
+ this.client.protocol.addHandler(`room.tool_call.${this.toolkit.name}`, handler);
3140
3152
  await this._register(isPublic);
3141
3153
  }
3142
3154
  async stop() {
3143
3155
  await this._unregister();
3144
- this.client.protocol.removeHandler(`room.tool_call.${this.name}`);
3156
+ this.client.protocol.removeHandler(`room.tool_call.${this.toolkit.name}`);
3145
3157
  }
3146
3158
  async _register(public_) {
3147
3159
  const response = await this.client.sendRequest("room.register_toolkit", {
3148
- name: this.name,
3149
- title: this.title,
3150
- description: this.description,
3151
- tools: this.getTools(),
3152
- public: public_
3160
+ name: this.toolkit.name,
3161
+ title: this.toolkit.title,
3162
+ description: this.toolkit.description,
3163
+ tools: this.toolkit.getTools(),
3164
+ public: public_,
3165
+ thumbnail_url: this.toolkit.thumbnailUrl
3153
3166
  });
3154
3167
  const json = response.json;
3155
3168
  this._registrationId = json["id"];
@@ -3180,7 +3193,7 @@ meshagent.auth = (() => {
3180
3193
  } else {
3181
3194
  args = rawArguments ?? {};
3182
3195
  }
3183
- const response = await this.execute(toolName, args);
3196
+ const response = await this.toolkit.execute(toolName, args);
3184
3197
  await this.client.protocol.send("room.tool_call_response", response.pack(), messageId);
3185
3198
  } catch (e) {
3186
3199
  const err = new response_1.ErrorContent({ text: String(e) });
@@ -3188,7 +3201,14 @@ meshagent.auth = (() => {
3188
3201
  }
3189
3202
  }
3190
3203
  };
3191
- exports.RemoteToolkit = RemoteToolkit;
3204
+ async function startHostedToolkit({ room, toolkit, public_: isPublic = false }) {
3205
+ const wrapper = new _RemoteToolkitWrapper({ toolkit, room });
3206
+ await wrapper.start({ public_: isPublic });
3207
+ return new HostedToolkit({
3208
+ toolkit,
3209
+ stopHostedToolkit: () => wrapper.stop()
3210
+ });
3211
+ }
3192
3212
  var RemoteTaskRunner = class {
3193
3213
  constructor({ name, description, client, inputSchema, outputSchema, supportsTools = false, required = [] }) {
3194
3214
  this.client = client;
@@ -3214,10 +3234,10 @@ meshagent.auth = (() => {
3214
3234
  "../meshagent-ts/dist/browser/agent-client.js"(exports) {
3215
3235
  "use strict";
3216
3236
  Object.defineProperty(exports, "__esModule", { value: true });
3217
- exports.AgentsClient = exports.ToolkitConfiguration = exports.ToolkitDescription = exports.ToolDescription = void 0;
3237
+ exports.AgentsClient = exports.ToolkitDescription = exports.ToolDescription = void 0;
3218
3238
  var tool_content_type_1 = require_tool_content_type();
3219
3239
  var ToolDescription = class {
3220
- constructor({ title, name, description, inputSchema, inputSpec, outputSpec, outputSchema, thumbnailUrl, defs, pricing, supportsContext }) {
3240
+ constructor({ title, name, description, inputSchema, inputSpec, outputSpec, outputSchema, thumbnailUrl, defs, pricing }) {
3221
3241
  this.title = title;
3222
3242
  this.name = name;
3223
3243
  this.description = description;
@@ -3254,7 +3274,6 @@ meshagent.auth = (() => {
3254
3274
  this.thumbnailUrl = thumbnailUrl;
3255
3275
  this.defs = defs;
3256
3276
  this.pricing = pricing;
3257
- this.supportsContext = supportsContext ?? false;
3258
3277
  }
3259
3278
  get inputSchema() {
3260
3279
  return this.inputSpec?.schema;
@@ -3294,8 +3313,7 @@ meshagent.auth = (() => {
3294
3313
  output_spec: tool.outputSpec?.toJson(),
3295
3314
  thumbnail_url: tool.thumbnailUrl,
3296
3315
  defs: tool.defs,
3297
- pricing: tool.pricing,
3298
- supports_context: tool.supportsContext
3316
+ pricing: tool.pricing
3299
3317
  }))
3300
3318
  };
3301
3319
  }
@@ -3319,8 +3337,7 @@ meshagent.auth = (() => {
3319
3337
  outputSpec: tool_content_type_1.ToolContentSpec.fromJson(tool["output_spec"]),
3320
3338
  thumbnailUrl: tool["thumbnail_url"],
3321
3339
  defs: tool["defs"],
3322
- pricing: tool["pricing"],
3323
- supportsContext: tool["supports_context"] ?? tool["supportsContext"]
3340
+ pricing: tool["pricing"]
3324
3341
  }));
3325
3342
  }
3326
3343
  } else if (typeof json["tools"] === "object" && json["tools"] !== null) {
@@ -3337,8 +3354,7 @@ meshagent.auth = (() => {
3337
3354
  outputSpec: tool_content_type_1.ToolContentSpec.fromJson(tool["output_spec"]),
3338
3355
  thumbnailUrl: tool["thumbnail_url"],
3339
3356
  defs: tool["defs"],
3340
- pricing: tool["pricing"],
3341
- supportsContext: tool["supports_context"] ?? tool["supportsContext"]
3357
+ pricing: tool["pricing"]
3342
3358
  }));
3343
3359
  }
3344
3360
  }
@@ -3353,29 +3369,6 @@ meshagent.auth = (() => {
3353
3369
  }
3354
3370
  };
3355
3371
  exports.ToolkitDescription = ToolkitDescription;
3356
- var ToolkitConfiguration = class {
3357
- constructor(name, use) {
3358
- this.name = name;
3359
- this.use = use;
3360
- }
3361
- toJson() {
3362
- if (!this.use) {
3363
- return {
3364
- [this.name]: {}
3365
- };
3366
- } else {
3367
- return {
3368
- [this.name]: {
3369
- use: this.use.reduce((acc, tool) => {
3370
- acc[tool] = {};
3371
- return acc;
3372
- }, {})
3373
- }
3374
- };
3375
- }
3376
- }
3377
- };
3378
- exports.ToolkitConfiguration = ToolkitConfiguration;
3379
3372
  var AgentsClient = class {
3380
3373
  constructor({ room }) {
3381
3374
  this.client = room;
@@ -6148,7 +6141,7 @@ meshagent.auth = (() => {
6148
6141
  } catch (e) {
6149
6142
  }
6150
6143
  var varStorage = _localStorage;
6151
- var EqualityTraitSymbol = Symbol("Equality");
6144
+ var EqualityTraitSymbol = /* @__PURE__ */ Symbol("Equality");
6152
6145
  var equals = (a, b) => a === b || !!a?.[EqualityTraitSymbol]?.(b) || false;
6153
6146
  var isObject2 = (o) => typeof o === "object";
6154
6147
  var assign = Object.assign;
@@ -6354,7 +6347,7 @@ meshagent.auth = (() => {
6354
6347
  return str;
6355
6348
  };
6356
6349
  var oneOf = (gen, array) => array[int31(gen, 0, array.length - 1)];
6357
- var schemaSymbol = Symbol("0schema");
6350
+ var schemaSymbol = /* @__PURE__ */ Symbol("0schema");
6358
6351
  var ValidationError = class {
6359
6352
  constructor() {
6360
6353
  this._rerrs = [];
@@ -6632,7 +6625,7 @@ meshagent.auth = (() => {
6632
6625
  }
6633
6626
  };
6634
6627
  var $$stringTemplate = $constructedBy($StringTemplate);
6635
- var isOptionalSymbol = Symbol("optional");
6628
+ var isOptionalSymbol = /* @__PURE__ */ Symbol("optional");
6636
6629
  var $Optional = class extends Schema {
6637
6630
  /**
6638
6631
  * @param {S} shape
@@ -14947,19 +14940,28 @@ ${err.toString()}`);
14947
14940
  exitCode: readOptionalIntegerField(data, "exit_code", operation)
14948
14941
  };
14949
14942
  }
14950
- function buildRequestPayload(params) {
14951
- return {
14952
- tag: params.tag,
14953
- mounts: toMountList(params.mounts),
14954
- context_path: params.contextPath,
14955
- dockerfile_path: params.dockerfilePath ?? null,
14956
- private: params.private ?? false,
14957
- credentials: toCredentials(params.credentials ?? []),
14958
- context_archive_path: params.contextArchivePath ?? null,
14959
- context_archive_ref: params.contextArchiveRef ?? null,
14960
- context_archive_mount_path: params.contextArchiveMountPath ?? null,
14961
- context_archive_arch: params.contextArchiveArch ?? null
14962
- };
14943
+ async function* buildInputStream(params) {
14944
+ yield new response_1.BinaryContent({
14945
+ data: new Uint8Array(0),
14946
+ headers: {
14947
+ kind: "start",
14948
+ tag: params.tag,
14949
+ mount_path: params.mountPath,
14950
+ context_path: params.contextPath,
14951
+ dockerfile_path: params.dockerfilePath ?? null,
14952
+ optimize_image: params.optimizeImage ?? true,
14953
+ private: params.private ?? false,
14954
+ credentials: toCredentials(params.credentials ?? []),
14955
+ builder_name: params.builderName ?? null,
14956
+ size: params.size ?? null
14957
+ }
14958
+ });
14959
+ for await (const chunk of params.chunks) {
14960
+ yield new response_1.BinaryContent({
14961
+ data: new Uint8Array(chunk),
14962
+ headers: { kind: "data" }
14963
+ });
14964
+ }
14963
14965
  }
14964
14966
  var ExecSession = class {
14965
14967
  constructor(params) {
@@ -15200,15 +15202,12 @@ ${err.toString()}`);
15200
15202
  }
15201
15203
  return readStringField(output.json, "container_id", "run");
15202
15204
  }
15203
- async startBuild(params) {
15204
- const output = await this.invoke("start_build", buildRequestPayload(params));
15205
- if (!(output instanceof response_1.JsonContent) || !isRecord(output.json)) {
15206
- throw this.unexpectedResponseError("start_build");
15207
- }
15208
- return readStringField(output.json, "build_id", "start_build");
15209
- }
15210
15205
  async build(params) {
15211
- const output = await this.invoke("build", buildRequestPayload(params));
15206
+ const output = await this.room.invokeWithStreamInput({
15207
+ toolkit: "containers",
15208
+ tool: "build",
15209
+ input: buildInputStream(params)
15210
+ });
15212
15211
  if (!(output instanceof response_1.JsonContent) || !isRecord(output.json)) {
15213
15212
  throw this.unexpectedResponseError("build");
15214
15213
  }
@@ -15585,7 +15584,7 @@ ${err.toString()}`);
15585
15584
  "../meshagent-ts/dist/browser/data-types.js"(exports) {
15586
15585
  "use strict";
15587
15586
  Object.defineProperty(exports, "__esModule", { value: true });
15588
- exports.BinaryDataType = exports.TextDataType = exports.VectorDataType = exports.FloatDataType = exports.DateDataType = exports.IntDataType = exports.BoolDataType = exports.DataType = exports._dataTypes = void 0;
15587
+ exports.BinaryDataType = exports.UuidDataType = exports.JsonDataType = exports.TextDataType = exports.VectorDataType = exports.FloatDataType = exports.DateDataType = exports.IntDataType = exports.BoolDataType = exports.DataType = exports._dataTypes = void 0;
15589
15588
  exports._dataTypes = {};
15590
15589
  var DataType = class {
15591
15590
  constructor(_) {
@@ -15612,6 +15611,12 @@ ${err.toString()}`);
15612
15611
  static text() {
15613
15612
  return new TextDataType();
15614
15613
  }
15614
+ static json() {
15615
+ return new JsonDataType();
15616
+ }
15617
+ static uuid() {
15618
+ return new UuidDataType();
15619
+ }
15615
15620
  static binary() {
15616
15621
  return new BinaryDataType();
15617
15622
  }
@@ -15722,6 +15727,38 @@ ${err.toString()}`);
15722
15727
  };
15723
15728
  exports.TextDataType = TextDataType;
15724
15729
  exports._dataTypes["text"] = TextDataType;
15730
+ var JsonDataType = class _JsonDataType extends DataType {
15731
+ constructor() {
15732
+ super();
15733
+ }
15734
+ static fromJson(data) {
15735
+ if (data.type !== "json") {
15736
+ throw new Error(`Expected type 'json', got '${data.type}'`);
15737
+ }
15738
+ return new _JsonDataType();
15739
+ }
15740
+ toJson() {
15741
+ return { type: "json" };
15742
+ }
15743
+ };
15744
+ exports.JsonDataType = JsonDataType;
15745
+ exports._dataTypes["json"] = JsonDataType;
15746
+ var UuidDataType = class _UuidDataType extends DataType {
15747
+ constructor() {
15748
+ super();
15749
+ }
15750
+ static fromJson(data) {
15751
+ if (data.type !== "uuid") {
15752
+ throw new Error(`Expected type 'uuid', got '${data.type}'`);
15753
+ }
15754
+ return new _UuidDataType();
15755
+ }
15756
+ toJson() {
15757
+ return { type: "uuid" };
15758
+ }
15759
+ };
15760
+ exports.UuidDataType = UuidDataType;
15761
+ exports._dataTypes["uuid"] = UuidDataType;
15725
15762
  var BinaryDataType = class _BinaryDataType extends DataType {
15726
15763
  constructor() {
15727
15764
  super();
@@ -15746,11 +15783,109 @@ ${err.toString()}`);
15746
15783
  "../meshagent-ts/dist/browser/database-client.js"(exports) {
15747
15784
  "use strict";
15748
15785
  Object.defineProperty(exports, "__esModule", { value: true });
15749
- exports.DatabaseClient = void 0;
15786
+ exports.DatabaseClient = exports.DatabaseUuid = exports.DatabaseJson = exports.DatabaseStruct = exports.DatabaseDate = exports.DatabaseExpression = exports.DatabaseValueEncoder = void 0;
15750
15787
  var data_types_1 = require_data_types();
15751
15788
  var room_server_client_1 = require_room_server_client();
15752
15789
  var response_1 = require_response();
15790
+ var DatabaseValueEncoder = class {
15791
+ };
15792
+ exports.DatabaseValueEncoder = DatabaseValueEncoder;
15793
+ var DatabaseExpression = class extends DatabaseValueEncoder {
15794
+ constructor(expression) {
15795
+ super();
15796
+ const normalized = expression.trim();
15797
+ if (normalized === "") {
15798
+ throw new TypeError("database expression must not be empty");
15799
+ }
15800
+ this.expression = normalized;
15801
+ }
15802
+ encodeDatabaseValue() {
15803
+ return {
15804
+ expression: this.expression
15805
+ };
15806
+ }
15807
+ toString() {
15808
+ return this.expression;
15809
+ }
15810
+ };
15811
+ exports.DatabaseExpression = DatabaseExpression;
15812
+ var DatabaseDate = class extends DatabaseValueEncoder {
15813
+ constructor(value) {
15814
+ super();
15815
+ const normalized = value.trim();
15816
+ const parsed = /* @__PURE__ */ new Date(`${normalized}T00:00:00Z`);
15817
+ if (!ISO_DATE_REGEX.test(normalized) || Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== normalized) {
15818
+ throw new TypeError("invalid database date format");
15819
+ }
15820
+ this.value = normalized;
15821
+ }
15822
+ encodeDatabaseValue() {
15823
+ return {
15824
+ date: this.value
15825
+ };
15826
+ }
15827
+ toString() {
15828
+ return this.value;
15829
+ }
15830
+ };
15831
+ exports.DatabaseDate = DatabaseDate;
15832
+ var DatabaseStruct = class extends DatabaseValueEncoder {
15833
+ constructor(fields) {
15834
+ super();
15835
+ this.fields = Object.fromEntries(Object.entries(fields).map(([key, value]) => {
15836
+ if (typeof key !== "string") {
15837
+ throw new TypeError("database struct keys must be strings");
15838
+ }
15839
+ return [key, value];
15840
+ }));
15841
+ }
15842
+ toJson() {
15843
+ return Object.fromEntries(Object.entries(this.fields).map(([key, value]) => [key, encodeRecordValue(value)]));
15844
+ }
15845
+ encodeDatabaseValue() {
15846
+ return {
15847
+ struct: this.toJson()
15848
+ };
15849
+ }
15850
+ };
15851
+ exports.DatabaseStruct = DatabaseStruct;
15852
+ var DatabaseJson = class extends DatabaseValueEncoder {
15853
+ constructor(value) {
15854
+ super();
15855
+ this.value = normalizeDatabaseJsonValue(value);
15856
+ }
15857
+ toJson() {
15858
+ return this.value;
15859
+ }
15860
+ encodeDatabaseValue() {
15861
+ return {
15862
+ json: this.value
15863
+ };
15864
+ }
15865
+ };
15866
+ exports.DatabaseJson = DatabaseJson;
15753
15867
  var globalScope = globalThis;
15868
+ var UUID_HEX_REGEX = /^[0-9a-f]{32}$/;
15869
+ var ISO_DATE_REGEX = /^\d{4}-\d{2}-\d{2}$/;
15870
+ function normalizeUuidHex(value) {
15871
+ const normalized = value.trim().toLowerCase().replace(/-/g, "");
15872
+ if (!UUID_HEX_REGEX.test(normalized)) {
15873
+ throw new room_server_client_1.RoomServerException("invalid uuid format");
15874
+ }
15875
+ return normalized;
15876
+ }
15877
+ function formatUuidHex(value) {
15878
+ return `${value.substring(0, 8)}-${value.substring(8, 12)}-${value.substring(12, 16)}-${value.substring(16, 20)}-${value.substring(20)}`;
15879
+ }
15880
+ var DatabaseUuid = class {
15881
+ constructor(value) {
15882
+ this.value = formatUuidHex(normalizeUuidHex(value));
15883
+ }
15884
+ toString() {
15885
+ return this.value;
15886
+ }
15887
+ };
15888
+ exports.DatabaseUuid = DatabaseUuid;
15754
15889
  function bytesToBase64(bytes) {
15755
15890
  if (globalScope.Buffer) {
15756
15891
  return globalScope.Buffer.from(bytes).toString("base64");
@@ -15781,13 +15916,28 @@ ${err.toString()}`);
15781
15916
  function isRecord(value) {
15782
15917
  return typeof value === "object" && value !== null && !Array.isArray(value);
15783
15918
  }
15919
+ function isPlainRecord(value) {
15920
+ return isRecord(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
15921
+ }
15922
+ function normalizeDatabaseJsonValue(value) {
15923
+ if (value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string") {
15924
+ return value;
15925
+ }
15926
+ if (Array.isArray(value)) {
15927
+ return value.map((item) => normalizeDatabaseJsonValue(item));
15928
+ }
15929
+ if (isPlainRecord(value)) {
15930
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, normalizeDatabaseJsonValue(item)]));
15931
+ }
15932
+ throw new TypeError("database json values must be valid JSON");
15933
+ }
15784
15934
  function metadataEntries(metadata) {
15785
15935
  if (metadata == null) {
15786
15936
  return null;
15787
15937
  }
15788
15938
  return Object.entries(metadata).map(([key, value]) => ({
15789
15939
  key,
15790
- value: typeof value === "string" ? value : JSON.stringify(encodeLegacyValue(value))
15940
+ value: typeof value === "string" ? value : JSON.stringify(value)
15791
15941
  }));
15792
15942
  }
15793
15943
  function toolkitDataTypeJson(dataType) {
@@ -15874,125 +16024,124 @@ ${err.toString()}`);
15874
16024
  }
15875
16025
  return payload;
15876
16026
  }
15877
- function encodeLegacyValue(value) {
16027
+ function encodeRecordValue(value) {
16028
+ if (value instanceof DatabaseValueEncoder) {
16029
+ return value.encodeDatabaseValue();
16030
+ }
16031
+ if (value instanceof DatabaseUuid) {
16032
+ return {
16033
+ uuid: value.toString()
16034
+ };
16035
+ }
15878
16036
  if (value instanceof Uint8Array) {
15879
16037
  return {
15880
- encoding: "base64",
15881
- data: bytesToBase64(value)
16038
+ binary: bytesToBase64(value)
15882
16039
  };
15883
16040
  }
15884
16041
  if (value instanceof Date) {
15885
- return value.toISOString().replace("+00:00", "Z");
16042
+ return {
16043
+ timestamp: value.toISOString().replace("+00:00", "Z")
16044
+ };
15886
16045
  }
15887
16046
  if (Array.isArray(value)) {
15888
- return value.map((item) => encodeLegacyValue(item));
16047
+ return {
16048
+ list: value.map((item) => encodeRecordValue(item))
16049
+ };
15889
16050
  }
15890
16051
  if (isRecord(value)) {
15891
- return Object.fromEntries(Object.entries(value).map(([key, entryValue]) => [key, encodeLegacyValue(entryValue)]));
16052
+ throw new room_server_client_1.RoomServerException("database object values must use DatabaseStruct or DatabaseJson");
15892
16053
  }
15893
16054
  return value;
15894
16055
  }
15895
- function encodeStreamValue(value) {
15896
- if (value == null) {
15897
- return { type: "null" };
16056
+ function databaseSqlLiteral(value) {
16057
+ if (value instanceof DatabaseUuid) {
16058
+ return `X'${normalizeUuidHex(value.toString())}'`;
15898
16059
  }
15899
- if (typeof value === "boolean") {
15900
- return { type: "bool", value };
15901
- }
15902
- if (typeof value === "number") {
15903
- if (Number.isInteger(value)) {
15904
- return { type: "int", value };
15905
- }
15906
- return { type: "float", value };
16060
+ if (value instanceof DatabaseDate) {
16061
+ return JSON.stringify(value.toString());
15907
16062
  }
15908
- if (typeof value === "string") {
15909
- return { type: "text", value };
16063
+ if (value instanceof Date) {
16064
+ return JSON.stringify(value.toISOString().replace("+00:00", "Z"));
15910
16065
  }
15911
- if (value instanceof Uint8Array) {
15912
- return {
15913
- type: "binary",
15914
- data: bytesToBase64(value)
15915
- };
16066
+ if (value instanceof DatabaseJson) {
16067
+ return JSON.stringify(JSON.stringify(value.toJson()));
15916
16068
  }
15917
- if (value instanceof Date) {
15918
- return {
15919
- type: "timestamp",
15920
- value: value.toISOString().replace("+00:00", "Z")
15921
- };
16069
+ if (value instanceof DatabaseStruct) {
16070
+ const fields = Object.entries(value.fields).map(([key, fieldValue]) => `${JSON.stringify(key)}, ${databaseSqlLiteral(fieldValue)}`);
16071
+ return `named_struct(${fields.join(", ")})`;
15922
16072
  }
16073
+ return JSON.stringify(encodeRecordValue(value));
16074
+ }
16075
+ function decodeRecordValue(value) {
15923
16076
  if (Array.isArray(value)) {
15924
- return {
15925
- type: "list",
15926
- items: value.map((item) => encodeStreamValue(item))
15927
- };
16077
+ throw new room_server_client_1.RoomServerException("database list values must use a {'list': [...]} wrapper");
15928
16078
  }
15929
- if (isRecord(value)) {
15930
- return {
15931
- type: "struct",
15932
- fields: Object.entries(value).map(([name, fieldValue]) => ({
15933
- name,
15934
- value: encodeStreamValue(fieldValue)
15935
- }))
15936
- };
16079
+ if (!isRecord(value)) {
16080
+ return value;
15937
16081
  }
15938
- throw new room_server_client_1.RoomServerException(`database stream does not support value type ${typeof value}`);
15939
- }
15940
- function decodeStreamValue(value, operation) {
15941
- if (!isRecord(value) || typeof value.type !== "string") {
15942
- throw new room_server_client_1.RoomServerException(`unexpected return type from database.${operation}`);
16082
+ const entries = Object.entries(value);
16083
+ if (entries.length !== 1) {
16084
+ throw new room_server_client_1.RoomServerException("database object values must use a single-key type wrapper");
15943
16085
  }
15944
- switch (value.type) {
15945
- case "null":
15946
- return null;
15947
- case "bool":
15948
- if (typeof value.value !== "boolean") {
15949
- throw new room_server_client_1.RoomServerException(`unexpected return type from database.${operation}`);
16086
+ const [wrapper, payload] = entries[0];
16087
+ switch (wrapper) {
16088
+ case "binary":
16089
+ if (typeof payload !== "string") {
16090
+ throw new room_server_client_1.RoomServerException("database binary values must be base64 strings");
15950
16091
  }
15951
- return value.value;
15952
- case "int":
15953
- case "float":
15954
- if (typeof value.value !== "number") {
15955
- throw new room_server_client_1.RoomServerException(`unexpected return type from database.${operation}`);
16092
+ return base64ToBytes(payload);
16093
+ case "uuid":
16094
+ if (typeof payload !== "string") {
16095
+ throw new room_server_client_1.RoomServerException("database uuid values must be strings");
15956
16096
  }
15957
- return value.value;
15958
- case "text":
16097
+ return new DatabaseUuid(payload);
16098
+ case "expression":
16099
+ if (typeof payload !== "string") {
16100
+ throw new room_server_client_1.RoomServerException("database expression values must be strings");
16101
+ }
16102
+ return new DatabaseExpression(payload);
15959
16103
  case "date":
16104
+ if (typeof payload !== "string") {
16105
+ throw new room_server_client_1.RoomServerException("database date values must be strings");
16106
+ }
16107
+ return new DatabaseDate(payload);
15960
16108
  case "timestamp":
15961
- if (typeof value.value !== "string") {
15962
- throw new room_server_client_1.RoomServerException(`unexpected return type from database.${operation}`);
16109
+ if (typeof payload !== "string") {
16110
+ throw new room_server_client_1.RoomServerException("database timestamp values must be strings");
15963
16111
  }
15964
- return value.value;
15965
- case "binary":
15966
- if (typeof value.data !== "string") {
15967
- throw new room_server_client_1.RoomServerException(`unexpected return type from database.${operation}`);
16112
+ {
16113
+ const parsed = new Date(payload);
16114
+ if (Number.isNaN(parsed.getTime())) {
16115
+ throw new room_server_client_1.RoomServerException("database timestamp value is not valid");
16116
+ }
16117
+ return parsed;
15968
16118
  }
15969
- return base64ToBytes(value.data);
15970
16119
  case "list":
15971
- if (!Array.isArray(value.items)) {
15972
- throw new room_server_client_1.RoomServerException(`unexpected return type from database.${operation}`);
16120
+ if (!Array.isArray(payload)) {
16121
+ throw new room_server_client_1.RoomServerException("database list values must be arrays");
15973
16122
  }
15974
- return value.items.map((item) => decodeStreamValue(item, operation));
16123
+ return payload.map((item) => decodeRecordValue(item));
15975
16124
  case "struct":
15976
- if (!Array.isArray(value.fields)) {
15977
- throw new room_server_client_1.RoomServerException(`unexpected return type from database.${operation}`);
16125
+ if (!isRecord(payload)) {
16126
+ throw new room_server_client_1.RoomServerException("database struct values must be objects");
15978
16127
  }
15979
- return Object.fromEntries(value.fields.map((field) => {
15980
- if (!isRecord(field) || typeof field.name !== "string") {
15981
- throw new room_server_client_1.RoomServerException(`unexpected return type from database.${operation}`);
15982
- }
15983
- return [field.name, decodeStreamValue(field.value, operation)];
15984
- }));
16128
+ return new DatabaseStruct(Object.fromEntries(Object.entries(payload).map(([key, item]) => [key, decodeRecordValue(item)])));
16129
+ case "json":
16130
+ return new DatabaseJson(normalizeDatabaseJsonValue(payload));
15985
16131
  default:
15986
- throw new room_server_client_1.RoomServerException(`unexpected return type from database.${operation}`);
16132
+ throw new room_server_client_1.RoomServerException(`unsupported database value wrapper '${wrapper}'`);
15987
16133
  }
15988
16134
  }
16135
+ function encodeDatabaseRecord(record) {
16136
+ return Object.fromEntries(Object.entries(record).map(([key, value]) => [key, encodeRecordValue(value)]));
16137
+ }
15989
16138
  function rowsChunk(records) {
15990
16139
  return {
15991
16140
  kind: "rows",
15992
16141
  rows: records.map((record) => ({
15993
16142
  columns: Object.entries(record).map(([name, value]) => ({
15994
16143
  name,
15995
- value: encodeStreamValue(value)
16144
+ value: encodeRecordValue(value)
15996
16145
  }))
15997
16146
  }))
15998
16147
  };
@@ -16009,7 +16158,11 @@ ${err.toString()}`);
16009
16158
  if (!isRecord(column) || typeof column.name !== "string") {
16010
16159
  throw new room_server_client_1.RoomServerException(`unexpected return type from database.${operation}`);
16011
16160
  }
16012
- return [column.name, decodeStreamValue(column.value, operation)];
16161
+ try {
16162
+ return [column.name, decodeRecordValue(column.value)];
16163
+ } catch {
16164
+ throw new room_server_client_1.RoomServerException(`unexpected return type from database.${operation}`);
16165
+ }
16013
16166
  }));
16014
16167
  });
16015
16168
  }
@@ -16036,7 +16189,7 @@ ${err.toString()}`);
16036
16189
  }
16037
16190
  function buildWhereClause(where) {
16038
16191
  if (where != null && typeof where === "object" && !Array.isArray(where)) {
16039
- return Object.entries(where).map(([key, value]) => `${key} = ${JSON.stringify(encodeLegacyValue(value))}`).join(" AND ");
16192
+ return Object.entries(where).map(([key, value]) => `${key} = ${databaseSqlLiteral(value)}`).join(" AND ");
16040
16193
  }
16041
16194
  if (typeof where === "string") {
16042
16195
  return where;
@@ -16084,6 +16237,37 @@ ${err.toString()}`);
16084
16237
  metadata
16085
16238
  };
16086
16239
  }
16240
+ function tableBranchFromJson(value) {
16241
+ if (!isRecord(value) || typeof value.name !== "string") {
16242
+ throw new room_server_client_1.RoomServerException("unexpected return type from database.list_branches");
16243
+ }
16244
+ if (value.parent_branch != null && typeof value.parent_branch !== "string") {
16245
+ throw new room_server_client_1.RoomServerException("unexpected return type from database.list_branches");
16246
+ }
16247
+ if (value.parent_version != null && (typeof value.parent_version !== "number" || !Number.isInteger(value.parent_version))) {
16248
+ throw new room_server_client_1.RoomServerException("unexpected return type from database.list_branches");
16249
+ }
16250
+ if (value.manifest_size != null && (typeof value.manifest_size !== "number" || !Number.isInteger(value.manifest_size))) {
16251
+ throw new room_server_client_1.RoomServerException("unexpected return type from database.list_branches");
16252
+ }
16253
+ let createdAt = null;
16254
+ if (value.created_at != null) {
16255
+ if (typeof value.created_at !== "string") {
16256
+ throw new room_server_client_1.RoomServerException("unexpected return type from database.list_branches");
16257
+ }
16258
+ createdAt = new Date(value.created_at);
16259
+ if (Number.isNaN(createdAt.getTime())) {
16260
+ throw new room_server_client_1.RoomServerException("unexpected return type from database.list_branches");
16261
+ }
16262
+ }
16263
+ return {
16264
+ name: value.name,
16265
+ parentBranch: value.parent_branch ?? null,
16266
+ parentVersion: value.parent_version ?? null,
16267
+ createdAt,
16268
+ manifestSize: value.manifest_size ?? null
16269
+ };
16270
+ }
16087
16271
  var DatabaseWriteInputStream = class {
16088
16272
  constructor(start, chunks) {
16089
16273
  this.start = start;
@@ -16262,118 +16446,132 @@ ${err.toString()}`);
16262
16446
  input.close();
16263
16447
  }
16264
16448
  }
16265
- async listTables({ namespace } = {}) {
16266
- const response = await this.invoke("list_tables", { namespace: namespace ?? null });
16449
+ async listTables({ namespace, branch } = {}) {
16450
+ const response = await this.invoke("list_tables", {
16451
+ namespace: namespace ?? null,
16452
+ branch: branch ?? null
16453
+ });
16267
16454
  if (!(response instanceof response_1.JsonContent)) {
16268
16455
  throw this._unexpectedResponseError("list_tables");
16269
16456
  }
16270
16457
  return Array.isArray(response.json.tables) ? response.json.tables : [];
16271
16458
  }
16272
- async createTable({ name, data, schema, mode = "create", namespace, metadata }) {
16459
+ async createTable({ name, data, schema, mode = "create", namespace, branch, metadata }) {
16273
16460
  const input = new DatabaseWriteInputStream({
16274
16461
  kind: "start",
16275
16462
  name,
16276
16463
  fields: schemaEntries(schema),
16277
16464
  mode,
16278
16465
  namespace: namespace ?? null,
16466
+ branch: branch ?? null,
16279
16467
  metadata: metadataEntries(metadata)
16280
16468
  }, data ?? []);
16281
16469
  await this.drainWriteStream("create_table", input);
16282
16470
  }
16283
- async createTableWithSchema({ name, schema, data, mode = "create", namespace, metadata }) {
16471
+ async createTableWithSchema({ name, schema, data, mode = "create", namespace, branch, metadata }) {
16284
16472
  return this.createTable({
16285
16473
  name,
16286
16474
  schema,
16287
16475
  data: data == null ? void 0 : rowChunkList(data),
16288
16476
  mode,
16289
16477
  namespace,
16478
+ branch,
16290
16479
  metadata
16291
16480
  });
16292
16481
  }
16293
- async createTableFromData({ name, data, mode = "create", namespace, metadata }) {
16482
+ async createTableFromData({ name, data, mode = "create", namespace, branch, metadata }) {
16294
16483
  return this.createTable({
16295
16484
  name,
16296
16485
  data: data == null ? void 0 : rowChunkList(data),
16297
16486
  mode,
16298
16487
  namespace,
16488
+ branch,
16299
16489
  metadata
16300
16490
  });
16301
16491
  }
16302
- async createTableFromDataStream({ name, chunks, schema, mode = "create", namespace, metadata }) {
16303
- return this.createTable({ name, data: chunks, schema, mode, namespace, metadata });
16492
+ async createTableFromDataStream({ name, chunks, schema, mode = "create", namespace, branch, metadata }) {
16493
+ return this.createTable({ name, data: chunks, schema, mode, namespace, branch, metadata });
16304
16494
  }
16305
- async dropTable({ name, ignoreMissing = false, namespace }) {
16495
+ async dropTable({ name, ignoreMissing = false, namespace, branch }) {
16306
16496
  await this.room.invoke({
16307
16497
  toolkit: "database",
16308
16498
  tool: "drop_table",
16309
- input: { name, ignore_missing: ignoreMissing, namespace: namespace ?? null }
16499
+ input: {
16500
+ name,
16501
+ ignore_missing: ignoreMissing,
16502
+ namespace: namespace ?? null,
16503
+ branch: branch ?? null
16504
+ }
16310
16505
  });
16311
16506
  }
16312
- async dropIndex({ table, name, namespace }) {
16507
+ async dropIndex({ table, name, namespace, branch }) {
16313
16508
  await this.room.invoke({
16314
16509
  toolkit: "database",
16315
16510
  tool: "drop_index",
16316
- input: { table, name, namespace: namespace ?? null }
16511
+ input: { table, name, namespace: namespace ?? null, branch: branch ?? null }
16317
16512
  });
16318
16513
  }
16319
- async addColumns({ table, newColumns, namespace }) {
16514
+ async addColumns({ table, newColumns, namespace, branch }) {
16320
16515
  await this.room.invoke({
16321
16516
  toolkit: "database",
16322
16517
  tool: "add_columns",
16323
16518
  input: {
16324
16519
  table,
16325
16520
  columns: Object.entries(newColumns).map(([name, value]) => value instanceof data_types_1.DataType ? { name, value_sql: null, data_type: toolkitDataTypeJson(value) } : { name, value_sql: value, data_type: null }),
16326
- namespace: namespace ?? null
16521
+ namespace: namespace ?? null,
16522
+ branch: branch ?? null
16327
16523
  }
16328
16524
  });
16329
16525
  }
16330
- async dropColumns({ table, columns, namespace }) {
16526
+ async dropColumns({ table, columns, namespace, branch }) {
16331
16527
  await this.room.invoke({
16332
16528
  toolkit: "database",
16333
16529
  tool: "drop_columns",
16334
- input: { table, columns, namespace: namespace ?? null }
16530
+ input: { table, columns, namespace: namespace ?? null, branch: branch ?? null }
16335
16531
  });
16336
16532
  }
16337
- async insert({ table, records, namespace }) {
16338
- await this.insertStream({ table, chunks: rowChunkList(records), namespace });
16533
+ async insert({ table, records, namespace, branch }) {
16534
+ await this.insertStream({ table, chunks: rowChunkList(records), namespace, branch });
16339
16535
  }
16340
- async insertStream({ table, chunks, namespace }) {
16536
+ async insertStream({ table, chunks, namespace, branch }) {
16341
16537
  const input = new DatabaseWriteInputStream({
16342
16538
  kind: "start",
16343
16539
  table,
16344
- namespace: namespace ?? null
16540
+ namespace: namespace ?? null,
16541
+ branch: branch ?? null
16345
16542
  }, chunks);
16346
16543
  await this.drainWriteStream("insert", input);
16347
16544
  }
16348
- async update({ table, where, values, valuesSql, namespace }) {
16545
+ async update({ table, where, values, namespace, branch }) {
16349
16546
  await this.room.invoke({
16350
16547
  toolkit: "database",
16351
16548
  tool: "update",
16352
16549
  input: {
16353
16550
  table,
16354
16551
  where,
16355
- values: values == null ? null : Object.entries(values).map(([column, value]) => ({ column, value_json: JSON.stringify(encodeLegacyValue(value)) })),
16356
- values_sql: valuesSql == null ? null : Object.entries(valuesSql).map(([column, expression]) => ({ column, expression })),
16357
- namespace: namespace ?? null
16552
+ values: Object.entries(values).map(([column, value]) => ({ column, value_json: JSON.stringify(encodeRecordValue(value)) })),
16553
+ namespace: namespace ?? null,
16554
+ branch: branch ?? null
16358
16555
  }
16359
16556
  });
16360
16557
  }
16361
- async delete({ table, where, namespace }) {
16558
+ async delete({ table, where, namespace, branch }) {
16362
16559
  await this.room.invoke({
16363
16560
  toolkit: "database",
16364
16561
  tool: "delete",
16365
- input: { table, where, namespace: namespace ?? null }
16562
+ input: { table, where, namespace: namespace ?? null, branch: branch ?? null }
16366
16563
  });
16367
16564
  }
16368
- async merge({ table, on, records, namespace }) {
16369
- await this.mergeStream({ table, on, chunks: rowChunkList(records), namespace });
16565
+ async merge({ table, on, records, namespace, branch }) {
16566
+ await this.mergeStream({ table, on, chunks: rowChunkList(records), namespace, branch });
16370
16567
  }
16371
- async mergeStream({ table, on, chunks, namespace }) {
16568
+ async mergeStream({ table, on, chunks, namespace, branch }) {
16372
16569
  const input = new DatabaseWriteInputStream({
16373
16570
  kind: "start",
16374
16571
  table,
16375
16572
  on,
16376
- namespace: namespace ?? null
16573
+ namespace: namespace ?? null,
16574
+ branch: branch ?? null
16377
16575
  }, chunks);
16378
16576
  await this.drainWriteStream("merge", input);
16379
16577
  }
@@ -16389,17 +16587,28 @@ ${err.toString()}`);
16389
16587
  kind: "start",
16390
16588
  query,
16391
16589
  tables: normalizeTableRefs(tables),
16392
- params_json: params == null ? null : JSON.stringify(encodeLegacyValue(params))
16590
+ params_json: params == null ? null : JSON.stringify(encodeDatabaseRecord(params))
16393
16591
  });
16394
16592
  }
16395
- async search({ table, text, vector, where, offset, limit, select, namespace }) {
16593
+ async search({ table, text, vector, where, offset, limit, select, namespace, branch, version }) {
16396
16594
  const rows = [];
16397
- for await (const chunk of this.searchStream({ table, text, vector, where, offset, limit, select, namespace })) {
16595
+ for await (const chunk of this.searchStream({
16596
+ table,
16597
+ text,
16598
+ vector,
16599
+ where,
16600
+ offset,
16601
+ limit,
16602
+ select,
16603
+ namespace,
16604
+ branch,
16605
+ version
16606
+ })) {
16398
16607
  rows.push(...chunk);
16399
16608
  }
16400
16609
  return rows;
16401
16610
  }
16402
- async *searchStream({ table, text, vector, where, offset, limit, select, namespace }) {
16611
+ async *searchStream({ table, text, vector, where, offset, limit, select, namespace, branch, version }) {
16403
16612
  yield* this.streamRows("search", {
16404
16613
  kind: "start",
16405
16614
  table,
@@ -16410,25 +16619,34 @@ ${err.toString()}`);
16410
16619
  offset: offset ?? null,
16411
16620
  limit: limit ?? null,
16412
16621
  select: select ?? null,
16413
- namespace: namespace ?? null
16622
+ namespace: namespace ?? null,
16623
+ branch: branch ?? null,
16624
+ version: version ?? null
16414
16625
  });
16415
16626
  }
16416
- async count({ table, text, vector, where, namespace }) {
16627
+ async count({ table, text, vector, where, namespace, branch, version }) {
16417
16628
  const response = await this.invoke("count", {
16418
16629
  table,
16419
16630
  text: text ?? null,
16420
16631
  vector: vector ?? null,
16421
16632
  text_columns: null,
16422
16633
  where: buildWhereClause(where),
16423
- namespace: namespace ?? null
16634
+ namespace: namespace ?? null,
16635
+ branch: branch ?? null,
16636
+ version: version ?? null
16424
16637
  });
16425
16638
  if (!(response instanceof response_1.JsonContent) || typeof response.json.count !== "number" || !Number.isInteger(response.json.count)) {
16426
16639
  throw this._unexpectedResponseError("count");
16427
16640
  }
16428
16641
  return response.json.count;
16429
16642
  }
16430
- async inspect({ table, namespace }) {
16431
- const response = await this.invoke("inspect", { table, namespace: namespace ?? null });
16643
+ async inspect({ table, namespace, branch, version }) {
16644
+ const response = await this.invoke("inspect", {
16645
+ table,
16646
+ namespace: namespace ?? null,
16647
+ branch: branch ?? null,
16648
+ version: version ?? null
16649
+ });
16432
16650
  if (!(response instanceof response_1.JsonContent) || !Array.isArray(response.json.fields)) {
16433
16651
  throw this._unexpectedResponseError("inspect");
16434
16652
  }
@@ -16442,57 +16660,91 @@ ${err.toString()}`);
16442
16660
  async optimize(tableOrParams) {
16443
16661
  const table = typeof tableOrParams === "string" ? tableOrParams : tableOrParams.table;
16444
16662
  const namespace = typeof tableOrParams === "string" ? void 0 : tableOrParams.namespace;
16445
- await this.room.invoke({ toolkit: "database", tool: "optimize", input: { table, namespace: namespace ?? null } });
16446
- }
16447
- async restore({ table, version, namespace }) {
16663
+ const branch = typeof tableOrParams === "string" ? void 0 : tableOrParams.branch;
16448
16664
  await this.room.invoke({
16449
16665
  toolkit: "database",
16450
- tool: "restore",
16451
- input: { table, version, namespace: namespace ?? null }
16666
+ tool: "optimize",
16667
+ input: { table, namespace: namespace ?? null, branch: branch ?? null }
16452
16668
  });
16453
16669
  }
16454
- async checkout({ table, version, namespace }) {
16670
+ async restore({ table, version, namespace, branch }) {
16455
16671
  await this.room.invoke({
16456
16672
  toolkit: "database",
16457
- tool: "checkout",
16458
- input: { table, version, namespace: namespace ?? null }
16673
+ tool: "restore",
16674
+ input: { table, version, namespace: namespace ?? null, branch: branch ?? null }
16459
16675
  });
16460
16676
  }
16461
- async listVersions({ table, namespace }) {
16462
- const response = await this.invoke("list_versions", { table, namespace: namespace ?? null });
16677
+ async listVersions({ table, namespace, branch }) {
16678
+ const response = await this.invoke("list_versions", {
16679
+ table,
16680
+ namespace: namespace ?? null,
16681
+ branch: branch ?? null
16682
+ });
16463
16683
  if (!(response instanceof response_1.JsonContent) || !Array.isArray(response.json.versions)) {
16464
16684
  throw this._unexpectedResponseError("list_versions");
16465
16685
  }
16466
16686
  return response.json.versions.map((version) => tableVersionFromJson(version));
16467
16687
  }
16468
- async createVectorIndex({ table, column, replace = false, namespace }) {
16688
+ async createVectorIndex({ table, column, replace = false, namespace, branch }) {
16469
16689
  await this.room.invoke({
16470
16690
  toolkit: "database",
16471
16691
  tool: "create_vector_index",
16472
- input: { table, column, replace, namespace: namespace ?? null }
16692
+ input: { table, column, replace, namespace: namespace ?? null, branch: branch ?? null }
16473
16693
  });
16474
16694
  }
16475
- async createScalarIndex({ table, column, replace = false, namespace }) {
16695
+ async createScalarIndex({ table, column, replace = false, namespace, branch }) {
16476
16696
  await this.room.invoke({
16477
16697
  toolkit: "database",
16478
16698
  tool: "create_scalar_index",
16479
- input: { table, column, replace, namespace: namespace ?? null }
16699
+ input: { table, column, replace, namespace: namespace ?? null, branch: branch ?? null }
16480
16700
  });
16481
16701
  }
16482
- async createFullTextSearchIndex({ table, column, replace = false, namespace }) {
16702
+ async createFullTextSearchIndex({ table, column, replace = false, namespace, branch }) {
16483
16703
  await this.room.invoke({
16484
16704
  toolkit: "database",
16485
16705
  tool: "create_full_text_search_index",
16486
- input: { table, column, replace, namespace: namespace ?? null }
16706
+ input: { table, column, replace, namespace: namespace ?? null, branch: branch ?? null }
16487
16707
  });
16488
16708
  }
16489
- async listIndexes({ table, namespace }) {
16490
- const response = await this.invoke("list_indexes", { table, namespace: namespace ?? null });
16709
+ async listIndexes({ table, namespace, branch, version }) {
16710
+ const response = await this.invoke("list_indexes", {
16711
+ table,
16712
+ namespace: namespace ?? null,
16713
+ branch: branch ?? null,
16714
+ version: version ?? null
16715
+ });
16491
16716
  if (!(response instanceof response_1.JsonContent) || !Array.isArray(response.json.indexes)) {
16492
16717
  throw this._unexpectedResponseError("list_indexes");
16493
16718
  }
16494
16719
  return response.json.indexes.map((index) => tableIndexFromJson(index));
16495
16720
  }
16721
+ async listBranches({ namespace } = {}) {
16722
+ const response = await this.invoke("list_branches", {
16723
+ namespace: namespace ?? null
16724
+ });
16725
+ if (!(response instanceof response_1.JsonContent) || !Array.isArray(response.json.branches)) {
16726
+ throw this._unexpectedResponseError("list_branches");
16727
+ }
16728
+ return response.json.branches.map((branch) => tableBranchFromJson(branch));
16729
+ }
16730
+ async createBranch({ branch, fromBranch, namespace }) {
16731
+ await this.room.invoke({
16732
+ toolkit: "database",
16733
+ tool: "create_branch",
16734
+ input: {
16735
+ branch,
16736
+ from_branch: fromBranch ?? null,
16737
+ namespace: namespace ?? null
16738
+ }
16739
+ });
16740
+ }
16741
+ async deleteBranch({ branch, namespace }) {
16742
+ await this.room.invoke({
16743
+ toolkit: "database",
16744
+ tool: "delete_branch",
16745
+ input: { branch, namespace: namespace ?? null }
16746
+ });
16747
+ }
16496
16748
  };
16497
16749
  exports.DatabaseClient = DatabaseClient;
16498
16750
  }
@@ -16503,7 +16755,7 @@ ${err.toString()}`);
16503
16755
  "../meshagent-ts/dist/browser/room-event.js"(exports) {
16504
16756
  "use strict";
16505
16757
  Object.defineProperty(exports, "__esModule", { value: true });
16506
- exports.RoomLogEvent = exports.FileUpdatedEvent = exports.FileDeletedEvent = exports.FileCreatedEvent = exports.RoomMessageEvent = exports.RoomMessage = exports.RoomEvent = void 0;
16758
+ exports.RoomLogEvent = exports.FileMovedEvent = exports.FileUpdatedEvent = exports.FileDeletedEvent = exports.FileCreatedEvent = exports.RoomMessageEvent = exports.RoomMessage = exports.RoomEvent = void 0;
16507
16759
  var RoomEvent = class {
16508
16760
  };
16509
16761
  exports.RoomEvent = RoomEvent;
@@ -16571,17 +16823,32 @@ ${err.toString()}`);
16571
16823
  }
16572
16824
  };
16573
16825
  exports.FileUpdatedEvent = FileUpdatedEvent;
16574
- var RoomLogEvent = class extends RoomEvent {
16575
- constructor({ type, data }) {
16826
+ var FileMovedEvent = class extends RoomEvent {
16827
+ constructor({ sourcePath, destinationPath, participantId }) {
16576
16828
  super();
16577
- this.type = type;
16578
- this.data = data;
16829
+ this.sourcePath = sourcePath;
16830
+ this.destinationPath = destinationPath;
16831
+ this.participantId = participantId;
16579
16832
  }
16580
16833
  get name() {
16581
- return this.type;
16834
+ return "file moved";
16582
16835
  }
16583
16836
  get description() {
16584
- return JSON.stringify(this.data);
16837
+ return `a file was moved from ${this.sourcePath} to ${this.destinationPath}`;
16838
+ }
16839
+ };
16840
+ exports.FileMovedEvent = FileMovedEvent;
16841
+ var RoomLogEvent = class extends RoomEvent {
16842
+ constructor({ type, data }) {
16843
+ super();
16844
+ this.type = type;
16845
+ this.data = data;
16846
+ }
16847
+ get name() {
16848
+ return this.type;
16849
+ }
16850
+ get description() {
16851
+ return JSON.stringify(this.data);
16585
16852
  }
16586
16853
  };
16587
16854
  exports.RoomLogEvent = RoomLogEvent;
@@ -17703,7 +17970,7 @@ ${err.toString()}`);
17703
17970
  var init_helpers = __esm({
17704
17971
  "../node_modules/jose/dist/webapi/lib/helpers.js"() {
17705
17972
  init_base64url();
17706
- unprotected = Symbol();
17973
+ unprotected = /* @__PURE__ */ Symbol();
17707
17974
  }
17708
17975
  });
17709
17976
 
@@ -20828,8 +21095,8 @@ ${newlined}
20828
21095
  const VERSION = "v6.2.2";
20829
21096
  USER_AGENT = `${NAME}/${VERSION}`;
20830
21097
  }
20831
- customFetch = Symbol();
20832
- jwksCache = Symbol();
21098
+ customFetch = /* @__PURE__ */ Symbol();
21099
+ jwksCache = /* @__PURE__ */ Symbol();
20833
21100
  RemoteJWKSet = class {
20834
21101
  constructor(url, options) {
20835
21102
  __privateAdd(this, _url);
@@ -21581,246 +21848,1050 @@ ${newlined}
21581
21848
  }
21582
21849
  });
21583
21850
 
21851
+ // ../meshagent-ts/dist/browser/version.js
21852
+ var require_version2 = __commonJS({
21853
+ "../meshagent-ts/dist/browser/version.js"(exports) {
21854
+ "use strict";
21855
+ Object.defineProperty(exports, "__esModule", { value: true });
21856
+ exports.__version__ = void 0;
21857
+ exports.__version__ = "0.36.3";
21858
+ }
21859
+ });
21860
+
21584
21861
  // ../meshagent-ts/dist/browser/participant-token.js
21585
21862
  var require_participant_token = __commonJS({
21586
21863
  "../meshagent-ts/dist/browser/participant-token.js"(exports) {
21587
21864
  "use strict";
21588
21865
  Object.defineProperty(exports, "__esModule", { value: true });
21589
- exports.ParticipantToken = exports.ParticipantGrant = exports.ApiScope = exports.SecretsGrant = exports.AdminGrant = exports.DeveloperGrant = exports.ContainersGrant = exports.StorageGrant = exports.StoragePathGrant = exports.SyncGrant = exports.SyncPathGrant = exports.DatabaseGrant = exports.TableGrant = exports.MessagingGrant = exports.QueuesGrant = exports.LivekitGrant = exports.AgentsGrant = void 0;
21866
+ exports.ParticipantToken = exports.ParticipantGrant = exports.ApiScope = exports.LLMGrant = exports.ServicesGrant = exports.TunnelsGrant = exports.SecretsGrant = exports.OAuthEndpoint = exports.AdminGrant = exports.DeveloperGrant = exports.ContainersGrant = exports.ContainerRegistryGrant = exports.StorageGrant = exports.StoragePathGrant = exports.SyncGrant = exports.SyncPathGrant = exports.MemoryGrant = exports.MemoryEntryGrant = exports.MemoryPermissions = exports.DatabaseGrant = exports.TableGrant = exports.MessagingGrant = exports.QueuesGrant = exports.LivekitGrant = exports.AgentsGrant = void 0;
21590
21867
  var jose_1 = (init_webapi(), __toCommonJS(webapi_exports));
21591
21868
  var api_keys_1 = require_api_keys();
21869
+ var version_1 = require_version2();
21870
+ function matchesGrantPattern(patterns, value, allowIfUnset) {
21871
+ if (!patterns) {
21872
+ return allowIfUnset;
21873
+ }
21874
+ return patterns.some((pattern) => value === pattern || pattern.endsWith("*") && value.startsWith(pattern.slice(0, -1)));
21875
+ }
21592
21876
  function getEnvValue(name) {
21593
21877
  if (typeof process === "undefined") {
21594
21878
  return void 0;
21595
21879
  }
21596
21880
  return process.env?.[name];
21597
21881
  }
21598
- var AgentsGrant = class {
21599
- constructor({ registerAgent, registerPublicToolkit, registerPrivateToolkit, call, useAgents, useTools } = {}) {
21882
+ function normalizeNamespace(namespace) {
21883
+ return namespace ?? [];
21884
+ }
21885
+ function namespacesEqual(left, right) {
21886
+ const normalizedLeft = normalizeNamespace(left);
21887
+ const normalizedRight = normalizeNamespace(right);
21888
+ if (normalizedLeft.length !== normalizedRight.length) {
21889
+ return false;
21890
+ }
21891
+ return normalizedLeft.every((value, index) => value === normalizedRight[index]);
21892
+ }
21893
+ function isRecord(value) {
21894
+ return typeof value === "object" && value !== null;
21895
+ }
21896
+ function asStringList(value) {
21897
+ return Array.isArray(value) && value.every((item) => typeof item === "string") ? value : void 0;
21898
+ }
21899
+ var AgentsGrant = class _AgentsGrant {
21900
+ constructor({ registerAgent, registerPublicToolkit, registerPrivateToolkit, call, useAgents, useTools, allowedToolkits } = {}) {
21600
21901
  this.registerAgent = registerAgent ?? true;
21601
21902
  this.registerPublicToolkit = registerPublicToolkit ?? true;
21602
21903
  this.registerPrivateToolkit = registerPrivateToolkit ?? true;
21603
21904
  this.call = call ?? true;
21604
21905
  this.useAgents = useAgents ?? true;
21605
21906
  this.useTools = useTools ?? true;
21907
+ this.allowedToolkits = allowedToolkits;
21908
+ }
21909
+ toJSON() {
21910
+ const json = {};
21911
+ if (this.registerAgent !== true) {
21912
+ json["register_agent"] = this.registerAgent;
21913
+ }
21914
+ if (this.registerPublicToolkit !== true) {
21915
+ json["register_public_toolkit"] = this.registerPublicToolkit;
21916
+ }
21917
+ if (this.registerPrivateToolkit !== true) {
21918
+ json["register_private_toolkit"] = this.registerPrivateToolkit;
21919
+ }
21920
+ if (this.call !== true) {
21921
+ json["call"] = this.call;
21922
+ }
21923
+ if (this.useAgents !== true) {
21924
+ json["use_agents"] = this.useAgents;
21925
+ }
21926
+ if (this.useTools !== true) {
21927
+ json["use_tools"] = this.useTools;
21928
+ }
21929
+ if (this.allowedToolkits !== void 0) {
21930
+ json["allowed_toolkits"] = this.allowedToolkits;
21931
+ }
21932
+ return json;
21933
+ }
21934
+ static fromJSON(obj) {
21935
+ if (!isRecord(obj)) {
21936
+ return new _AgentsGrant();
21937
+ }
21938
+ return new _AgentsGrant({
21939
+ registerAgent: obj.register_agent ?? obj.registerAgent,
21940
+ registerPublicToolkit: obj.register_public_toolkit ?? obj.registerPublicToolkit,
21941
+ registerPrivateToolkit: obj.register_private_toolkit ?? obj.registerPrivateToolkit,
21942
+ call: obj.call,
21943
+ useAgents: obj.use_agents ?? obj.useAgents,
21944
+ useTools: obj.use_tools ?? obj.useTools,
21945
+ allowedToolkits: asStringList(obj.allowed_toolkits ?? obj.allowedToolkits)
21946
+ });
21606
21947
  }
21607
21948
  };
21608
21949
  exports.AgentsGrant = AgentsGrant;
21609
- var LivekitGrant = class {
21950
+ var LivekitGrant = class _LivekitGrant {
21610
21951
  constructor({ breakoutRooms } = {}) {
21611
21952
  this.breakoutRooms = breakoutRooms;
21612
21953
  }
21613
21954
  canJoinBreakoutRoom(name) {
21614
21955
  return !this.breakoutRooms || this.breakoutRooms.includes(name);
21615
21956
  }
21957
+ toJSON() {
21958
+ const json = {};
21959
+ if (this.breakoutRooms !== void 0) {
21960
+ json["breakout_rooms"] = this.breakoutRooms;
21961
+ }
21962
+ return json;
21963
+ }
21964
+ static fromJSON(obj) {
21965
+ if (!isRecord(obj)) {
21966
+ return new _LivekitGrant();
21967
+ }
21968
+ return new _LivekitGrant({
21969
+ breakoutRooms: asStringList(obj.breakout_rooms ?? obj.breakoutRooms)
21970
+ });
21971
+ }
21616
21972
  };
21617
21973
  exports.LivekitGrant = LivekitGrant;
21618
- var QueuesGrant = class {
21974
+ var QueuesGrant = class _QueuesGrant {
21619
21975
  constructor({ send, receive, list } = {}) {
21620
- this.list = true;
21621
21976
  this.send = send;
21622
21977
  this.receive = receive;
21623
21978
  this.list = list ?? true;
21624
21979
  }
21625
- canSend(q) {
21626
- return !this.send || this.send.includes(q);
21980
+ canSend(queue) {
21981
+ return !this.send || this.send.includes(queue);
21627
21982
  }
21628
- canReceive(q) {
21629
- return !this.receive || this.receive.includes(q);
21983
+ canReceive(queue) {
21984
+ return !this.receive || this.receive.includes(queue);
21985
+ }
21986
+ toJSON() {
21987
+ const json = {};
21988
+ if (this.send !== void 0) {
21989
+ json["send"] = this.send;
21990
+ }
21991
+ if (this.receive !== void 0) {
21992
+ json["receive"] = this.receive;
21993
+ }
21994
+ if (this.list !== true) {
21995
+ json["list"] = this.list;
21996
+ }
21997
+ return json;
21998
+ }
21999
+ static fromJSON(obj) {
22000
+ if (!isRecord(obj)) {
22001
+ return new _QueuesGrant();
22002
+ }
22003
+ return new _QueuesGrant({
22004
+ send: asStringList(obj.send),
22005
+ receive: asStringList(obj.receive),
22006
+ list: obj.list
22007
+ });
21630
22008
  }
21631
22009
  };
21632
22010
  exports.QueuesGrant = QueuesGrant;
21633
- var MessagingGrant = class {
22011
+ var MessagingGrant = class _MessagingGrant {
21634
22012
  constructor({ broadcast, list, send } = {}) {
21635
22013
  this.broadcast = broadcast ?? true;
21636
22014
  this.list = list ?? true;
21637
22015
  this.send = send ?? true;
21638
22016
  }
22017
+ toJSON() {
22018
+ const json = {};
22019
+ if (this.broadcast !== true) {
22020
+ json["broadcast"] = this.broadcast;
22021
+ }
22022
+ if (this.list !== true) {
22023
+ json["list"] = this.list;
22024
+ }
22025
+ if (this.send !== true) {
22026
+ json["send"] = this.send;
22027
+ }
22028
+ return json;
22029
+ }
22030
+ static fromJSON(obj) {
22031
+ if (!isRecord(obj)) {
22032
+ return new _MessagingGrant();
22033
+ }
22034
+ return new _MessagingGrant({
22035
+ broadcast: obj.broadcast,
22036
+ list: obj.list,
22037
+ send: obj.send
22038
+ });
22039
+ }
21639
22040
  };
21640
22041
  exports.MessagingGrant = MessagingGrant;
21641
- var TableGrant = class {
21642
- constructor({ name, write, read, alter }) {
21643
- this.write = false;
21644
- this.read = true;
21645
- this.alter = false;
22042
+ var TableGrant = class _TableGrant {
22043
+ constructor({ name, namespace, write, read, alter }) {
21646
22044
  this.name = name;
22045
+ this.namespace = namespace;
21647
22046
  this.write = write ?? false;
21648
22047
  this.read = read ?? true;
21649
22048
  this.alter = alter ?? false;
21650
22049
  }
22050
+ toJSON() {
22051
+ const json = {
22052
+ name: this.name
22053
+ };
22054
+ if (this.namespace !== void 0) {
22055
+ json["namespace"] = this.namespace;
22056
+ }
22057
+ if (this.write !== false) {
22058
+ json["write"] = this.write;
22059
+ }
22060
+ if (this.read !== true) {
22061
+ json["read"] = this.read;
22062
+ }
22063
+ if (this.alter !== false) {
22064
+ json["alter"] = this.alter;
22065
+ }
22066
+ return json;
22067
+ }
22068
+ static fromJSON(obj) {
22069
+ if (!isRecord(obj) || typeof obj.name !== "string") {
22070
+ throw new Error("TableGrant requires a name");
22071
+ }
22072
+ return new _TableGrant({
22073
+ name: obj.name,
22074
+ namespace: asStringList(obj.namespace),
22075
+ write: obj.write,
22076
+ read: obj.read,
22077
+ alter: obj.alter
22078
+ });
22079
+ }
21651
22080
  };
21652
22081
  exports.TableGrant = TableGrant;
21653
- var DatabaseGrant = class {
22082
+ var DatabaseGrant = class _DatabaseGrant {
21654
22083
  constructor({ tables, listTables } = {}) {
21655
- this.listTables = true;
21656
22084
  this.tables = tables;
21657
22085
  this.listTables = listTables ?? true;
21658
22086
  }
21659
- _match(table) {
21660
- if (!this.tables)
21661
- return void 0;
21662
- return this.tables.find((t) => t.name === table);
22087
+ matchingTables(table, namespace) {
22088
+ if (this.tables === void 0) {
22089
+ return [];
22090
+ }
22091
+ return this.tables.filter((tableGrant) => {
22092
+ if (tableGrant.name !== table) {
22093
+ return false;
22094
+ }
22095
+ if (tableGrant.namespace === void 0) {
22096
+ return true;
22097
+ }
22098
+ return namespacesEqual(tableGrant.namespace, namespace);
22099
+ });
22100
+ }
22101
+ canWrite(table, namespace) {
22102
+ if (this.tables === void 0) {
22103
+ return true;
22104
+ }
22105
+ const matches = this.matchingTables(table, namespace);
22106
+ if (matches.length === 0) {
22107
+ return false;
22108
+ }
22109
+ return matches.some((tableGrant) => tableGrant.write);
21663
22110
  }
21664
- canWrite(table) {
21665
- const t = this._match(table);
21666
- return t ? t.write : this.tables === void 0;
22111
+ canRead(table, namespace) {
22112
+ if (this.tables === void 0) {
22113
+ return true;
22114
+ }
22115
+ const matches = this.matchingTables(table, namespace);
22116
+ if (matches.length === 0) {
22117
+ return false;
22118
+ }
22119
+ return matches.some((tableGrant) => tableGrant.read);
21667
22120
  }
21668
- canRead(table) {
21669
- const t = this._match(table);
21670
- return t ? t.read : this.tables === void 0;
22121
+ canAlter(table, namespace) {
22122
+ if (this.tables === void 0) {
22123
+ return true;
22124
+ }
22125
+ const matches = this.matchingTables(table, namespace);
22126
+ if (matches.length === 0) {
22127
+ return false;
22128
+ }
22129
+ return matches.some((tableGrant) => tableGrant.alter);
21671
22130
  }
21672
- canAlter(table) {
21673
- const t = this._match(table);
21674
- return t ? t.alter : this.tables === void 0;
22131
+ canAccess(table, namespace) {
22132
+ return this.canRead(table, namespace) || this.canWrite(table, namespace) || this.canAlter(table, namespace);
22133
+ }
22134
+ toJSON() {
22135
+ const json = {};
22136
+ if (this.tables !== void 0) {
22137
+ json["tables"] = this.tables.map((tableGrant) => tableGrant.toJSON());
22138
+ }
22139
+ if (this.listTables !== true) {
22140
+ json["list_tables"] = this.listTables;
22141
+ }
22142
+ return json;
22143
+ }
22144
+ static fromJSON(obj) {
22145
+ if (!isRecord(obj)) {
22146
+ return new _DatabaseGrant();
22147
+ }
22148
+ return new _DatabaseGrant({
22149
+ tables: Array.isArray(obj.tables) ? obj.tables.map((tableGrant) => TableGrant.fromJSON(tableGrant)) : void 0,
22150
+ listTables: obj.list_tables ?? obj.listTables
22151
+ });
21675
22152
  }
21676
22153
  };
21677
22154
  exports.DatabaseGrant = DatabaseGrant;
21678
- var SyncPathGrant = class {
22155
+ var MemoryPermissions = class _MemoryPermissions {
22156
+ constructor({ create, drop, inspect, query, upsert, ingest, recall, optimize } = {}) {
22157
+ this.create = create ?? true;
22158
+ this.drop = drop ?? true;
22159
+ this.inspect = inspect ?? true;
22160
+ this.query = query ?? true;
22161
+ this.upsert = upsert ?? true;
22162
+ this.ingest = ingest ?? true;
22163
+ this.recall = recall ?? true;
22164
+ this.optimize = optimize ?? true;
22165
+ }
22166
+ toJSON() {
22167
+ const json = {};
22168
+ if (this.create !== true) {
22169
+ json["create"] = this.create;
22170
+ }
22171
+ if (this.drop !== true) {
22172
+ json["drop"] = this.drop;
22173
+ }
22174
+ if (this.inspect !== true) {
22175
+ json["inspect"] = this.inspect;
22176
+ }
22177
+ if (this.query !== true) {
22178
+ json["query"] = this.query;
22179
+ }
22180
+ if (this.upsert !== true) {
22181
+ json["upsert"] = this.upsert;
22182
+ }
22183
+ if (this.ingest !== true) {
22184
+ json["ingest"] = this.ingest;
22185
+ }
22186
+ if (this.recall !== true) {
22187
+ json["recall"] = this.recall;
22188
+ }
22189
+ if (this.optimize !== true) {
22190
+ json["optimize"] = this.optimize;
22191
+ }
22192
+ return json;
22193
+ }
22194
+ static fromJSON(obj) {
22195
+ if (!isRecord(obj)) {
22196
+ return new _MemoryPermissions();
22197
+ }
22198
+ return new _MemoryPermissions({
22199
+ create: obj.create,
22200
+ drop: obj.drop,
22201
+ inspect: obj.inspect,
22202
+ query: obj.query,
22203
+ upsert: obj.upsert,
22204
+ ingest: obj.ingest,
22205
+ recall: obj.recall,
22206
+ optimize: obj.optimize
22207
+ });
22208
+ }
22209
+ };
22210
+ exports.MemoryPermissions = MemoryPermissions;
22211
+ var MemoryEntryGrant = class _MemoryEntryGrant {
22212
+ constructor({ name, namespace, permissions }) {
22213
+ this.name = name;
22214
+ this.namespace = namespace;
22215
+ this.permissions = permissions ?? new MemoryPermissions();
22216
+ }
22217
+ toJSON() {
22218
+ const json = {
22219
+ name: this.name
22220
+ };
22221
+ if (this.namespace !== void 0) {
22222
+ json["namespace"] = this.namespace;
22223
+ }
22224
+ json["permissions"] = this.permissions.toJSON();
22225
+ return json;
22226
+ }
22227
+ static fromJSON(obj) {
22228
+ if (!isRecord(obj) || typeof obj.name !== "string") {
22229
+ throw new Error("MemoryEntryGrant requires a name");
22230
+ }
22231
+ return new _MemoryEntryGrant({
22232
+ name: obj.name,
22233
+ namespace: asStringList(obj.namespace),
22234
+ permissions: MemoryPermissions.fromJSON(obj.permissions)
22235
+ });
22236
+ }
22237
+ };
22238
+ exports.MemoryEntryGrant = MemoryEntryGrant;
22239
+ var MemoryGrant = class _MemoryGrant {
22240
+ constructor({ list, memories } = {}) {
22241
+ this.list = list ?? true;
22242
+ this.memories = memories;
22243
+ }
22244
+ matchingMemories(name, namespace) {
22245
+ if (this.memories === void 0) {
22246
+ return [];
22247
+ }
22248
+ return this.memories.filter((memoryGrant) => {
22249
+ if (memoryGrant.name !== name) {
22250
+ return false;
22251
+ }
22252
+ if (memoryGrant.namespace === void 0) {
22253
+ return true;
22254
+ }
22255
+ return namespacesEqual(memoryGrant.namespace, namespace);
22256
+ });
22257
+ }
22258
+ can(name, namespace, permission) {
22259
+ if (this.memories === void 0) {
22260
+ return true;
22261
+ }
22262
+ const matches = this.matchingMemories(name, namespace);
22263
+ if (matches.length === 0) {
22264
+ return false;
22265
+ }
22266
+ return matches.some((memoryGrant) => memoryGrant.permissions[permission]);
22267
+ }
22268
+ canCreate(name, namespace) {
22269
+ return this.can(name, namespace, "create");
22270
+ }
22271
+ canDrop(name, namespace) {
22272
+ return this.can(name, namespace, "drop");
22273
+ }
22274
+ canInspect(name, namespace) {
22275
+ return this.can(name, namespace, "inspect");
22276
+ }
22277
+ canQuery(name, namespace) {
22278
+ return this.can(name, namespace, "query");
22279
+ }
22280
+ canUpsert(name, namespace) {
22281
+ return this.can(name, namespace, "upsert");
22282
+ }
22283
+ canIngest(name, namespace) {
22284
+ return this.can(name, namespace, "ingest");
22285
+ }
22286
+ canRecall(name, namespace) {
22287
+ return this.can(name, namespace, "recall");
22288
+ }
22289
+ canOptimize(name, namespace) {
22290
+ return this.can(name, namespace, "optimize");
22291
+ }
22292
+ canAccessExisting(name, namespace) {
22293
+ return this.canDrop(name, namespace) || this.canInspect(name, namespace) || this.canQuery(name, namespace) || this.canUpsert(name, namespace) || this.canIngest(name, namespace) || this.canRecall(name, namespace) || this.canOptimize(name, namespace);
22294
+ }
22295
+ toJSON() {
22296
+ const json = {};
22297
+ if (this.list !== true) {
22298
+ json["list"] = this.list;
22299
+ }
22300
+ if (this.memories !== void 0) {
22301
+ json["memories"] = this.memories.map((memoryGrant) => memoryGrant.toJSON());
22302
+ }
22303
+ return json;
22304
+ }
22305
+ static fromJSON(obj) {
22306
+ if (!isRecord(obj)) {
22307
+ return new _MemoryGrant();
22308
+ }
22309
+ return new _MemoryGrant({
22310
+ list: obj.list,
22311
+ memories: Array.isArray(obj.memories) ? obj.memories.map((memoryGrant) => MemoryEntryGrant.fromJSON(memoryGrant)) : void 0
22312
+ });
22313
+ }
22314
+ };
22315
+ exports.MemoryGrant = MemoryGrant;
22316
+ var SyncPathGrant = class _SyncPathGrant {
21679
22317
  constructor({ path, readOnly }) {
21680
22318
  this.path = path;
21681
22319
  this.readOnly = readOnly ?? false;
21682
22320
  }
22321
+ toJSON() {
22322
+ const json = {
22323
+ path: this.path
22324
+ };
22325
+ if (this.readOnly !== false) {
22326
+ json["read_only"] = this.readOnly;
22327
+ }
22328
+ return json;
22329
+ }
22330
+ static fromJSON(obj) {
22331
+ if (!isRecord(obj) || typeof obj.path !== "string") {
22332
+ throw new Error("SyncPathGrant requires a path");
22333
+ }
22334
+ return new _SyncPathGrant({
22335
+ path: obj.path,
22336
+ readOnly: obj.read_only ?? obj.readOnly
22337
+ });
22338
+ }
21683
22339
  };
21684
22340
  exports.SyncPathGrant = SyncPathGrant;
21685
- var SyncGrant = class {
22341
+ var SyncGrant = class _SyncGrant {
21686
22342
  constructor({ paths } = {}) {
21687
22343
  this.paths = paths;
21688
22344
  }
21689
- matches(p, path) {
21690
- return p.path === path || p.path.endsWith("*") && path.startsWith(p.path.slice(0, -1));
22345
+ matches(pathGrant, path) {
22346
+ return pathGrant.path === path || pathGrant.path.endsWith("*") && path.startsWith(pathGrant.path.slice(0, -1));
21691
22347
  }
21692
22348
  canRead(path) {
21693
- if (this.paths) {
21694
- return this.paths.some((p) => this.matches(p, path));
22349
+ if (this.paths === void 0) {
22350
+ return true;
21695
22351
  }
21696
- return true;
22352
+ return this.paths.some((pathGrant) => this.matches(pathGrant, path));
21697
22353
  }
21698
22354
  canWrite(path) {
21699
- if (this.paths) {
21700
- const p = this.paths.find((pp) => this.matches(pp, path));
21701
- return p ? !p.readOnly : false;
22355
+ if (this.paths === void 0) {
22356
+ return true;
21702
22357
  }
21703
- return true;
22358
+ for (const pathGrant of this.paths) {
22359
+ if (this.matches(pathGrant, path)) {
22360
+ return !pathGrant.readOnly;
22361
+ }
22362
+ }
22363
+ return false;
22364
+ }
22365
+ toJSON() {
22366
+ const json = {};
22367
+ if (this.paths !== void 0) {
22368
+ json["paths"] = this.paths.map((pathGrant) => pathGrant.toJSON());
22369
+ }
22370
+ return json;
22371
+ }
22372
+ static fromJSON(obj) {
22373
+ if (!isRecord(obj)) {
22374
+ return new _SyncGrant();
22375
+ }
22376
+ return new _SyncGrant({
22377
+ paths: Array.isArray(obj.paths) ? obj.paths.map((pathGrant) => SyncPathGrant.fromJSON(pathGrant)) : void 0
22378
+ });
21704
22379
  }
21705
22380
  };
21706
22381
  exports.SyncGrant = SyncGrant;
21707
- var StoragePathGrant = class {
22382
+ var StoragePathGrant = class _StoragePathGrant {
21708
22383
  constructor({ path, readOnly }) {
21709
22384
  this.path = path;
21710
22385
  this.readOnly = readOnly ?? false;
21711
22386
  }
22387
+ toJSON() {
22388
+ const json = {
22389
+ path: this.path
22390
+ };
22391
+ if (this.readOnly !== false) {
22392
+ json["read_only"] = this.readOnly;
22393
+ }
22394
+ return json;
22395
+ }
22396
+ static fromJSON(obj) {
22397
+ if (!isRecord(obj) || typeof obj.path !== "string") {
22398
+ throw new Error("StoragePathGrant requires a path");
22399
+ }
22400
+ return new _StoragePathGrant({
22401
+ path: obj.path,
22402
+ readOnly: obj.read_only ?? obj.readOnly
22403
+ });
22404
+ }
21712
22405
  };
21713
22406
  exports.StoragePathGrant = StoragePathGrant;
21714
- var StorageGrant = class {
22407
+ var StorageGrant = class _StorageGrant {
21715
22408
  constructor({ paths } = {}) {
21716
22409
  this.paths = paths;
21717
22410
  }
21718
- matches(p, path) {
21719
- return path.startsWith(p.path);
21720
- }
21721
22411
  canRead(path) {
21722
- if (!this.paths)
22412
+ if (this.paths === void 0) {
21723
22413
  return true;
21724
- return this.paths.some((p) => this.matches(p, path));
22414
+ }
22415
+ return this.paths.some((pathGrant) => path.startsWith(pathGrant.path));
21725
22416
  }
21726
22417
  canWrite(path) {
21727
- if (!this.paths)
22418
+ if (this.paths === void 0) {
21728
22419
  return true;
21729
- const p = this.paths.find((pp) => this.matches(pp, path));
21730
- return p ? !p.readOnly : false;
22420
+ }
22421
+ for (const pathGrant of this.paths) {
22422
+ if (path.startsWith(pathGrant.path)) {
22423
+ return !pathGrant.readOnly;
22424
+ }
22425
+ }
22426
+ return false;
22427
+ }
22428
+ toJSON() {
22429
+ const json = {};
22430
+ if (this.paths !== void 0) {
22431
+ json["paths"] = this.paths.map((pathGrant) => pathGrant.toJSON());
22432
+ }
22433
+ return json;
22434
+ }
22435
+ static fromJSON(obj) {
22436
+ if (!isRecord(obj)) {
22437
+ return new _StorageGrant();
22438
+ }
22439
+ return new _StorageGrant({
22440
+ paths: Array.isArray(obj.paths) ? obj.paths.map((pathGrant) => StoragePathGrant.fromJSON(pathGrant)) : void 0
22441
+ });
21731
22442
  }
21732
22443
  };
21733
22444
  exports.StorageGrant = StorageGrant;
21734
- var ContainersGrant = class {
21735
- constructor({ logs, pull, run, useContainers } = {}) {
21736
- this.logs = logs ?? true;
22445
+ var ContainerRegistryGrant = class _ContainerRegistryGrant {
22446
+ constructor({ list, pull, run, write } = {}) {
22447
+ this.list = list;
21737
22448
  this.pull = pull;
21738
22449
  this.run = run;
21739
- this.useContainers = useContainers ?? true;
22450
+ this.write = write;
21740
22451
  }
21741
- match(list, tag2) {
21742
- if (!list) {
22452
+ canList(repository) {
22453
+ if (this.list !== void 0) {
22454
+ return matchesGrantPattern(this.list, repository, false);
22455
+ }
22456
+ if (this.pull === void 0 && this.run === void 0 && this.write === void 0) {
21743
22457
  return true;
21744
22458
  }
21745
- return list.some((t) => tag2 === t || tag2.startsWith(t.endsWith("*") ? t.slice(0, -1) : t));
22459
+ return [this.pull, this.run, this.write].filter((patterns) => patterns !== void 0).some((patterns) => matchesGrantPattern(patterns, repository, false));
22460
+ }
22461
+ canPull(repository) {
22462
+ return matchesGrantPattern(this.pull, repository, true);
22463
+ }
22464
+ canRun(repository) {
22465
+ return matchesGrantPattern(this.run, repository, true);
22466
+ }
22467
+ canWrite(repository) {
22468
+ return matchesGrantPattern(this.write, repository, true);
22469
+ }
22470
+ toJSON() {
22471
+ const json = {};
22472
+ if (this.list !== void 0) {
22473
+ json["list"] = this.list;
22474
+ }
22475
+ if (this.pull !== void 0) {
22476
+ json["pull"] = this.pull;
22477
+ }
22478
+ if (this.run !== void 0) {
22479
+ json["run"] = this.run;
22480
+ }
22481
+ if (this.write !== void 0) {
22482
+ json["write"] = this.write;
22483
+ }
22484
+ return json;
22485
+ }
22486
+ static fromJSON(obj) {
22487
+ if (!isRecord(obj)) {
22488
+ return new _ContainerRegistryGrant();
22489
+ }
22490
+ return new _ContainerRegistryGrant({
22491
+ list: asStringList(obj.list),
22492
+ pull: asStringList(obj.pull),
22493
+ run: asStringList(obj.run),
22494
+ write: asStringList(obj.write)
22495
+ });
22496
+ }
22497
+ };
22498
+ exports.ContainerRegistryGrant = ContainerRegistryGrant;
22499
+ var ContainersGrant = class _ContainersGrant {
22500
+ constructor({ logs, pull, run, registry, useContainers } = {}) {
22501
+ this.logs = logs ?? true;
22502
+ this.pull = pull;
22503
+ this.run = run;
22504
+ this.registry = registry;
22505
+ this.useContainers = useContainers ?? true;
21746
22506
  }
21747
22507
  canPull(tag2) {
21748
- return this.match(this.pull, tag2);
22508
+ return matchesGrantPattern(this.pull, tag2, true);
21749
22509
  }
21750
22510
  canRun(tag2) {
21751
- return this.match(this.run, tag2);
22511
+ return matchesGrantPattern(this.run, tag2, true);
22512
+ }
22513
+ canRegistryList(repository) {
22514
+ if (this.registry === void 0) {
22515
+ return true;
22516
+ }
22517
+ return this.registry.canList(repository);
22518
+ }
22519
+ canRegistryPull(repository) {
22520
+ if (this.registry === void 0) {
22521
+ return true;
22522
+ }
22523
+ return this.registry.canPull(repository);
22524
+ }
22525
+ canRegistryRun(repository) {
22526
+ if (this.registry === void 0) {
22527
+ return true;
22528
+ }
22529
+ return this.registry.canRun(repository);
22530
+ }
22531
+ canRegistryWrite(repository) {
22532
+ if (this.registry === void 0) {
22533
+ return true;
22534
+ }
22535
+ return this.registry.canWrite(repository);
22536
+ }
22537
+ toJSON() {
22538
+ const json = {};
22539
+ if (this.logs !== true) {
22540
+ json["logs"] = this.logs;
22541
+ }
22542
+ if (this.pull !== void 0) {
22543
+ json["pull"] = this.pull;
22544
+ }
22545
+ if (this.run !== void 0) {
22546
+ json["run"] = this.run;
22547
+ }
22548
+ if (this.registry !== void 0) {
22549
+ json["registry"] = this.registry.toJSON();
22550
+ }
22551
+ if (this.useContainers !== true) {
22552
+ json["use_containers"] = this.useContainers;
22553
+ }
22554
+ return json;
22555
+ }
22556
+ static fromJSON(obj) {
22557
+ if (!isRecord(obj)) {
22558
+ return new _ContainersGrant();
22559
+ }
22560
+ return new _ContainersGrant({
22561
+ logs: obj.logs,
22562
+ pull: asStringList(obj.pull),
22563
+ run: asStringList(obj.run),
22564
+ registry: obj.registry ? ContainerRegistryGrant.fromJSON(obj.registry) : void 0,
22565
+ useContainers: obj.use_containers ?? obj.useContainers
22566
+ });
21752
22567
  }
21753
22568
  };
21754
22569
  exports.ContainersGrant = ContainersGrant;
21755
- var DeveloperGrant = class {
22570
+ var DeveloperGrant = class _DeveloperGrant {
21756
22571
  constructor({ logs } = {}) {
21757
22572
  this.logs = logs ?? true;
21758
22573
  }
22574
+ toJSON() {
22575
+ const json = {};
22576
+ if (this.logs !== true) {
22577
+ json["logs"] = this.logs;
22578
+ }
22579
+ return json;
22580
+ }
22581
+ static fromJSON(obj) {
22582
+ if (!isRecord(obj)) {
22583
+ return new _DeveloperGrant();
22584
+ }
22585
+ return new _DeveloperGrant({
22586
+ logs: obj.logs
22587
+ });
22588
+ }
21759
22589
  };
21760
22590
  exports.DeveloperGrant = DeveloperGrant;
21761
- var AdminGrant = class {
22591
+ var AdminGrant = class _AdminGrant {
22592
+ constructor({ config } = {}) {
22593
+ this.config = config ?? true;
22594
+ }
22595
+ toJSON() {
22596
+ const json = {};
22597
+ if (this.config !== true) {
22598
+ json["config"] = this.config;
22599
+ }
22600
+ return json;
22601
+ }
22602
+ static fromJSON(obj) {
22603
+ if (!isRecord(obj)) {
22604
+ return new _AdminGrant();
22605
+ }
22606
+ return new _AdminGrant({
22607
+ config: obj.config
22608
+ });
22609
+ }
21762
22610
  };
21763
22611
  exports.AdminGrant = AdminGrant;
21764
- var SecretsGrant = class {
21765
- canRequestOauthToken(authorizationEndpoint) {
21766
- if (!this.requestOauthToken) {
22612
+ var OAuthEndpoint = class _OAuthEndpoint {
22613
+ constructor({ endpoint, clientId }) {
22614
+ this.endpoint = endpoint;
22615
+ this.clientId = clientId;
22616
+ }
22617
+ toJSON() {
22618
+ return {
22619
+ endpoint: this.endpoint,
22620
+ client_id: this.clientId
22621
+ };
22622
+ }
22623
+ static fromJSON(obj) {
22624
+ if (!isRecord(obj) || typeof obj.endpoint !== "string") {
22625
+ throw new Error("OAuthEndpoint requires an endpoint");
22626
+ }
22627
+ const clientId = obj.client_id ?? obj.clientId;
22628
+ if (typeof clientId !== "string") {
22629
+ throw new Error("OAuthEndpoint requires a client_id");
22630
+ }
22631
+ return new _OAuthEndpoint({
22632
+ endpoint: obj.endpoint,
22633
+ clientId
22634
+ });
22635
+ }
22636
+ };
22637
+ exports.OAuthEndpoint = OAuthEndpoint;
22638
+ var SecretsGrant = class _SecretsGrant {
22639
+ constructor({ requestOauthToken } = {}) {
22640
+ this.requestOauthToken = requestOauthToken;
22641
+ }
22642
+ canRequestOauthToken({ connector, oauth } = {}) {
22643
+ void connector;
22644
+ if (this.requestOauthToken === void 0) {
21767
22645
  return true;
21768
22646
  }
21769
- return this.requestOauthToken.some((t) => t === authorizationEndpoint || t.endsWith("*") && authorizationEndpoint.startsWith(t.slice(0, -1)));
22647
+ const authorizationEndpoint = typeof oauth?.authorization_endpoint === "string" ? oauth.authorization_endpoint.trim() : "";
22648
+ const clientId = typeof oauth?.client_id === "string" ? oauth.client_id.trim() : "";
22649
+ if (authorizationEndpoint === "" || clientId === "") {
22650
+ return false;
22651
+ }
22652
+ return this.requestOauthToken.some((endpointGrant) => (endpointGrant.endpoint === authorizationEndpoint || endpointGrant.endpoint.endsWith("*") && authorizationEndpoint.startsWith(endpointGrant.endpoint.slice(0, -1))) && endpointGrant.clientId === clientId);
22653
+ }
22654
+ toJSON() {
22655
+ const json = {};
22656
+ if (this.requestOauthToken !== void 0) {
22657
+ json["request_oauth_token"] = this.requestOauthToken.map((endpointGrant) => endpointGrant.toJSON());
22658
+ }
22659
+ return json;
22660
+ }
22661
+ static fromJSON(obj) {
22662
+ if (!isRecord(obj)) {
22663
+ return new _SecretsGrant();
22664
+ }
22665
+ const requestOauthToken = obj.request_oauth_token ?? obj.requestOauthToken;
22666
+ return new _SecretsGrant({
22667
+ requestOauthToken: Array.isArray(requestOauthToken) ? requestOauthToken.map((endpointGrant) => OAuthEndpoint.fromJSON(endpointGrant)) : void 0
22668
+ });
21770
22669
  }
21771
22670
  };
21772
22671
  exports.SecretsGrant = SecretsGrant;
22672
+ var TunnelsGrant = class _TunnelsGrant {
22673
+ constructor({ ports } = {}) {
22674
+ this.ports = ports;
22675
+ }
22676
+ toJSON() {
22677
+ const json = {};
22678
+ if (this.ports !== void 0) {
22679
+ json["ports"] = this.ports;
22680
+ }
22681
+ return json;
22682
+ }
22683
+ static fromJSON(obj) {
22684
+ if (!isRecord(obj)) {
22685
+ return new _TunnelsGrant();
22686
+ }
22687
+ return new _TunnelsGrant({
22688
+ ports: asStringList(obj.ports)
22689
+ });
22690
+ }
22691
+ };
22692
+ exports.TunnelsGrant = TunnelsGrant;
22693
+ var ServicesGrant = class _ServicesGrant {
22694
+ constructor({ list } = {}) {
22695
+ this.list = list ?? true;
22696
+ }
22697
+ toJSON() {
22698
+ const json = {};
22699
+ if (this.list !== true) {
22700
+ json["list"] = this.list;
22701
+ }
22702
+ return json;
22703
+ }
22704
+ static fromJSON(obj) {
22705
+ if (!isRecord(obj)) {
22706
+ return new _ServicesGrant();
22707
+ }
22708
+ return new _ServicesGrant({
22709
+ list: obj.list
22710
+ });
22711
+ }
22712
+ };
22713
+ exports.ServicesGrant = ServicesGrant;
22714
+ var LLMGrant = class _LLMGrant {
22715
+ constructor({ models } = {}) {
22716
+ this.models = models;
22717
+ }
22718
+ canUseProvider(provider) {
22719
+ const normalizedProvider = provider.trim();
22720
+ if (normalizedProvider === "") {
22721
+ return false;
22722
+ }
22723
+ if (!this.models) {
22724
+ return true;
22725
+ }
22726
+ const prefix = `${normalizedProvider}/`;
22727
+ return this.models.some((pattern) => pattern.trim().startsWith(prefix));
22728
+ }
22729
+ canUseModel(provider, model) {
22730
+ const normalizedProvider = provider.trim();
22731
+ const normalizedModel = model.trim();
22732
+ if (normalizedProvider === "" || normalizedModel === "") {
22733
+ return false;
22734
+ }
22735
+ return matchesGrantPattern(this.models, `${normalizedProvider}/${normalizedModel}`, true);
22736
+ }
22737
+ toJSON() {
22738
+ const json = {};
22739
+ if (this.models !== void 0) {
22740
+ json["models"] = this.models;
22741
+ }
22742
+ return json;
22743
+ }
22744
+ static fromJSON(obj) {
22745
+ if (!isRecord(obj)) {
22746
+ return new _LLMGrant();
22747
+ }
22748
+ return new _LLMGrant({
22749
+ models: asStringList(obj.models)
22750
+ });
22751
+ }
22752
+ };
22753
+ exports.LLMGrant = LLMGrant;
21773
22754
  var ApiScope = class _ApiScope {
21774
- constructor({ livekit, queues, messaging, database, sync, storage, containers, developer, agents, admin, secrets } = {}) {
22755
+ constructor({ livekit, queues, messaging, database, memory, sync, storage, containers, developer, agents, llm, admin, secrets, tunnels, services } = {}) {
21775
22756
  this.livekit = livekit;
21776
22757
  this.queues = queues;
21777
22758
  this.messaging = messaging;
21778
22759
  this.database = database;
22760
+ this.memory = memory;
21779
22761
  this.sync = sync;
21780
22762
  this.storage = storage;
21781
22763
  this.containers = containers;
21782
22764
  this.developer = developer;
21783
22765
  this.agents = agents;
22766
+ this.llm = llm;
21784
22767
  this.admin = admin;
21785
22768
  this.secrets = secrets;
21786
- }
21787
- static agentDefault() {
21788
- const s = new _ApiScope();
21789
- s.livekit = new LivekitGrant();
21790
- s.queues = new QueuesGrant();
21791
- s.messaging = new MessagingGrant();
21792
- s.database = new DatabaseGrant();
21793
- s.sync = new SyncGrant();
21794
- s.storage = new StorageGrant();
21795
- s.containers = new ContainersGrant();
21796
- s.developer = new DeveloperGrant();
21797
- s.agents = new AgentsGrant();
21798
- return s;
22769
+ this.tunnels = tunnels;
22770
+ this.services = services;
22771
+ }
22772
+ static agentDefault({ tunnels = false } = {}) {
22773
+ return new _ApiScope({
22774
+ livekit: new LivekitGrant(),
22775
+ queues: new QueuesGrant(),
22776
+ messaging: new MessagingGrant(),
22777
+ database: new DatabaseGrant(),
22778
+ memory: new MemoryGrant(),
22779
+ sync: new SyncGrant(),
22780
+ storage: new StorageGrant(),
22781
+ containers: new ContainersGrant(),
22782
+ developer: new DeveloperGrant(),
22783
+ agents: new AgentsGrant(),
22784
+ llm: new LLMGrant(),
22785
+ secrets: new SecretsGrant(),
22786
+ services: new ServicesGrant(),
22787
+ tunnels: tunnels ? new TunnelsGrant() : void 0
22788
+ });
21799
22789
  }
21800
22790
  static userDefault() {
21801
- const s = new _ApiScope();
21802
- s.livekit = new LivekitGrant();
21803
- s.queues = new QueuesGrant();
21804
- s.messaging = new MessagingGrant();
21805
- s.database = new DatabaseGrant();
21806
- s.sync = new SyncGrant();
21807
- s.storage = new StorageGrant();
21808
- s.containers = new ContainersGrant();
21809
- s.developer = new DeveloperGrant();
21810
- s.agents = new AgentsGrant();
21811
- s.secrets = new SecretsGrant();
21812
- return s;
22791
+ return new _ApiScope({
22792
+ livekit: new LivekitGrant(),
22793
+ queues: new QueuesGrant(),
22794
+ messaging: new MessagingGrant(),
22795
+ database: new DatabaseGrant(),
22796
+ memory: new MemoryGrant(),
22797
+ sync: new SyncGrant(),
22798
+ storage: new StorageGrant(),
22799
+ containers: new ContainersGrant(),
22800
+ developer: new DeveloperGrant(),
22801
+ agents: new AgentsGrant(),
22802
+ secrets: new SecretsGrant(),
22803
+ services: new ServicesGrant()
22804
+ });
21813
22805
  }
21814
22806
  static full() {
21815
- const s = _ApiScope.agentDefault();
21816
- s.admin = new AdminGrant();
21817
- return s;
22807
+ return new _ApiScope({
22808
+ livekit: new LivekitGrant(),
22809
+ queues: new QueuesGrant(),
22810
+ messaging: new MessagingGrant(),
22811
+ database: new DatabaseGrant(),
22812
+ memory: new MemoryGrant(),
22813
+ sync: new SyncGrant(),
22814
+ storage: new StorageGrant(),
22815
+ containers: new ContainersGrant(),
22816
+ developer: new DeveloperGrant(),
22817
+ agents: new AgentsGrant(),
22818
+ llm: new LLMGrant(),
22819
+ admin: new AdminGrant(),
22820
+ secrets: new SecretsGrant(),
22821
+ tunnels: new TunnelsGrant(),
22822
+ services: new ServicesGrant()
22823
+ });
21818
22824
  }
21819
22825
  toJSON() {
21820
- return { ...this };
22826
+ const json = {};
22827
+ if (this.livekit !== void 0) {
22828
+ json["livekit"] = this.livekit.toJSON();
22829
+ }
22830
+ if (this.queues !== void 0) {
22831
+ json["queues"] = this.queues.toJSON();
22832
+ }
22833
+ if (this.messaging !== void 0) {
22834
+ json["messaging"] = this.messaging.toJSON();
22835
+ }
22836
+ if (this.database !== void 0) {
22837
+ json["database"] = this.database.toJSON();
22838
+ }
22839
+ if (this.memory !== void 0) {
22840
+ json["memory"] = this.memory.toJSON();
22841
+ }
22842
+ if (this.sync !== void 0) {
22843
+ json["sync"] = this.sync.toJSON();
22844
+ }
22845
+ if (this.storage !== void 0) {
22846
+ json["storage"] = this.storage.toJSON();
22847
+ }
22848
+ if (this.containers !== void 0) {
22849
+ json["containers"] = this.containers.toJSON();
22850
+ }
22851
+ if (this.developer !== void 0) {
22852
+ json["developer"] = this.developer.toJSON();
22853
+ }
22854
+ if (this.agents !== void 0) {
22855
+ json["agents"] = this.agents.toJSON();
22856
+ }
22857
+ if (this.llm !== void 0) {
22858
+ json["llm"] = this.llm.toJSON();
22859
+ }
22860
+ if (this.admin !== void 0) {
22861
+ json["admin"] = this.admin.toJSON();
22862
+ }
22863
+ if (this.secrets !== void 0) {
22864
+ json["secrets"] = this.secrets.toJSON();
22865
+ }
22866
+ if (this.tunnels !== void 0) {
22867
+ json["tunnels"] = this.tunnels.toJSON();
22868
+ }
22869
+ if (this.services !== void 0) {
22870
+ json["services"] = this.services.toJSON();
22871
+ }
22872
+ return json;
21821
22873
  }
21822
22874
  static fromJSON(obj) {
21823
- return Object.assign(new _ApiScope(), obj);
22875
+ if (!isRecord(obj)) {
22876
+ return new _ApiScope();
22877
+ }
22878
+ return new _ApiScope({
22879
+ livekit: obj.livekit ? LivekitGrant.fromJSON(obj.livekit) : void 0,
22880
+ queues: obj.queues ? QueuesGrant.fromJSON(obj.queues) : void 0,
22881
+ messaging: obj.messaging ? MessagingGrant.fromJSON(obj.messaging) : void 0,
22882
+ database: obj.database ? DatabaseGrant.fromJSON(obj.database) : void 0,
22883
+ memory: obj.memory ? MemoryGrant.fromJSON(obj.memory) : void 0,
22884
+ sync: obj.sync ? SyncGrant.fromJSON(obj.sync) : void 0,
22885
+ storage: obj.storage ? StorageGrant.fromJSON(obj.storage) : void 0,
22886
+ containers: obj.containers ? ContainersGrant.fromJSON(obj.containers) : void 0,
22887
+ developer: obj.developer ? DeveloperGrant.fromJSON(obj.developer) : void 0,
22888
+ agents: obj.agents ? AgentsGrant.fromJSON(obj.agents) : void 0,
22889
+ llm: obj.llm ? LLMGrant.fromJSON(obj.llm) : void 0,
22890
+ admin: obj.admin ? AdminGrant.fromJSON(obj.admin) : void 0,
22891
+ secrets: obj.secrets ? SecretsGrant.fromJSON(obj.secrets) : void 0,
22892
+ tunnels: obj.tunnels ? TunnelsGrant.fromJSON(obj.tunnels) : void 0,
22893
+ services: obj.services ? ServicesGrant.fromJSON(obj.services) : void 0
22894
+ });
21824
22895
  }
21825
22896
  };
21826
22897
  exports.ApiScope = ApiScope;
@@ -21855,12 +22926,14 @@ ${newlined}
21855
22926
  };
21856
22927
  exports.ParticipantGrant = ParticipantGrant;
21857
22928
  function compareSemver(a, b) {
21858
- const pa = a.split(".").map((n) => parseInt(n, 10));
21859
- const pb = b.split(".").map((n) => parseInt(n, 10));
21860
- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
21861
- const x = pa[i] || 0, y = pb[i] || 0;
21862
- if (x !== y)
21863
- return x - y;
22929
+ const pa = a.split(".").map((value) => parseInt(value, 10));
22930
+ const pb = b.split(".").map((value) => parseInt(value, 10));
22931
+ for (let index = 0; index < Math.max(pa.length, pb.length); index += 1) {
22932
+ const left = pa[index] || 0;
22933
+ const right = pb[index] || 0;
22934
+ if (left !== right) {
22935
+ return left - right;
22936
+ }
21864
22937
  }
21865
22938
  return 0;
21866
22939
  }
@@ -21869,14 +22942,14 @@ ${newlined}
21869
22942
  this.name = name;
21870
22943
  this.projectId = projectId;
21871
22944
  this.apiKeyId = apiKeyId;
21872
- this.version = version;
22945
+ this.version = version ?? version_1.__version__;
21873
22946
  this.extra = extra ?? {};
21874
22947
  this.grants = grants ?? [];
21875
22948
  }
21876
22949
  get role() {
21877
- for (const g of this.grants) {
21878
- if (g.name === "role" && g.scope !== "user") {
21879
- return String(g.scope);
22950
+ for (const grant of this.grants) {
22951
+ if (grant.name === "role" && grant.scope !== "user") {
22952
+ return String(grant.scope);
21880
22953
  }
21881
22954
  }
21882
22955
  return "user";
@@ -21898,8 +22971,10 @@ ${newlined}
21898
22971
  return true;
21899
22972
  }
21900
22973
  addTunnelGrant(ports) {
21901
- const portsStr = ports.join(",");
21902
- this.grants.push(new ParticipantGrant({ name: "tunnel_ports", scope: portsStr }));
22974
+ this.grants.push(new ParticipantGrant({
22975
+ name: "tunnel_ports",
22976
+ scope: ports.join(",")
22977
+ }));
21903
22978
  }
21904
22979
  addRoleGrant(role) {
21905
22980
  this.grants.push(new ParticipantGrant({ name: "role", scope: role }));
@@ -21908,125 +22983,109 @@ ${newlined}
21908
22983
  this.grants.push(new ParticipantGrant({ name: "room", scope: roomName }));
21909
22984
  }
21910
22985
  addApiGrant(grant) {
22986
+ for (const existingGrant of this.grants) {
22987
+ if (existingGrant.name === "api") {
22988
+ throw new Error("can only have a single api grant");
22989
+ }
22990
+ }
21911
22991
  this.grants.push(new ParticipantGrant({ name: "api", scope: grant }));
21912
22992
  }
21913
22993
  grantScope(name) {
21914
- return this.grants.find((g) => g.name === name)?.scope;
22994
+ return this.grants.find((grant) => grant.name === name)?.scope;
21915
22995
  }
21916
22996
  getApiGrant() {
21917
- const api = this.grantScope("api");
21918
- if (api && typeof api !== "string") {
21919
- return api;
21920
- }
21921
- if (this.version && compareSemver(this.version, "0.6.0") < 0 && !api) {
21922
- return new ApiScope({
21923
- livekit: new LivekitGrant(),
21924
- queues: new QueuesGrant(),
21925
- messaging: new MessagingGrant(),
21926
- database: new DatabaseGrant(),
21927
- sync: new SyncGrant(),
21928
- storage: new StorageGrant(),
21929
- agents: new AgentsGrant(),
21930
- developer: new DeveloperGrant()
21931
- });
22997
+ const apiGrant = this.grantScope("api");
22998
+ if (apiGrant && typeof apiGrant !== "string") {
22999
+ return apiGrant;
21932
23000
  }
21933
- return api;
23001
+ return void 0;
21934
23002
  }
21935
23003
  toJson() {
21936
- const base = {
23004
+ const json = {
23005
+ ...this.extra ?? {},
21937
23006
  name: this.name,
21938
- grants: this.grants.map((g) => g.toJson())
23007
+ grants: this.grants.map((grant) => grant.toJson())
21939
23008
  };
21940
- if (this.projectId) {
21941
- base["sub"] = this.projectId;
23009
+ if (this.projectId !== void 0) {
23010
+ json["sub"] = this.projectId;
21942
23011
  }
21943
- if (this.apiKeyId) {
21944
- base["kid"] = this.apiKeyId;
23012
+ if (this.apiKeyId !== void 0) {
23013
+ json["kid"] = this.apiKeyId;
21945
23014
  }
21946
- if (this.version) {
21947
- base["version"] = this.version;
23015
+ if (this.version !== void 0) {
23016
+ json["version"] = this.version;
21948
23017
  }
21949
- return base;
23018
+ return json;
21950
23019
  }
21951
23020
  async toJwt({ token, expiration, apiKey } = {}) {
21952
- let apiGrant = null;
21953
- for (const g of this.grants) {
21954
- if (g.name === "api") {
21955
- apiGrant = g;
21956
- break;
21957
- }
21958
- }
21959
- if (!apiGrant && this.version && compareSemver(this.version, "0.5.3") >= 0) {
21960
- console.error("ParticipantToken.toJwt: No API grant found, but version is >= 0.5.3. This may cause issues with older clients that expect an API grant.");
23021
+ const apiGrant = this.grants.find((grant) => grant.name === "api");
23022
+ if (!apiGrant && compareSemver(this.version, "0.3.5") > 0) {
23023
+ console.warn("there is no ApiScope in the participant token, this participant will not be able to make calls to the the room API. Use addApiGrant to add an ApiScope to this token.");
21961
23024
  }
23025
+ const payload = this.toJson();
23026
+ const resolvedApiKey = apiKey ?? getEnvValue("MESHAGENT_API_KEY");
21962
23027
  let resolvedSecret = token;
21963
- let resolvedKid = this.apiKeyId;
21964
- let resolvedSub = this.projectId;
21965
- const apiKeyValue = apiKey ?? getEnvValue("MESHAGENT_API_KEY");
21966
- if (apiKeyValue) {
21967
- const parsed = (0, api_keys_1.parseApiKey)(apiKeyValue);
21968
- resolvedSecret ?? (resolvedSecret = parsed.secret);
21969
- resolvedKid = parsed.id;
21970
- resolvedSub = parsed.projectId;
21971
- }
21972
- let usingDefaultSecret = false;
21973
- if (!resolvedSecret) {
21974
- const envSecret = getEnvValue("MESHAGENT_SECRET");
21975
- if (!envSecret) {
21976
- throw new Error("ParticipantToken.toJwt: No secret provided. Pass `token`, `apiKey`, or set MESHAGENT_SECRET / MESHAGENT_API_KEY.");
21977
- }
21978
- resolvedSecret = envSecret;
21979
- usingDefaultSecret = true;
23028
+ if (resolvedApiKey !== void 0) {
23029
+ const parsed = (0, api_keys_1.parseApiKey)(resolvedApiKey);
23030
+ resolvedSecret = parsed.secret;
23031
+ payload["kid"] = parsed.id;
23032
+ payload["sub"] = parsed.projectId;
23033
+ } else if (resolvedSecret === void 0) {
23034
+ delete payload["kid"];
21980
23035
  }
21981
- const secretKey = new TextEncoder().encode(resolvedSecret);
21982
- const payload = this.toJson();
21983
- if (resolvedSub) {
21984
- payload["sub"] = resolvedSub;
21985
- } else {
21986
- delete payload["sub"];
23036
+ if (resolvedSecret === void 0) {
23037
+ resolvedSecret = getEnvValue("MESHAGENT_SECRET");
21987
23038
  }
21988
- if (usingDefaultSecret) {
21989
- delete payload["kid"];
21990
- } else if (resolvedKid) {
21991
- payload["kid"] = resolvedKid;
21992
- } else {
21993
- delete payload["kid"];
23039
+ if (resolvedSecret === void 0) {
23040
+ throw new Error("ParticipantToken.toJwt: No secret provided. Pass `token`, `apiKey`, or set MESHAGENT_SECRET / MESHAGENT_API_KEY.");
21994
23041
  }
21995
- if (expiration) {
23042
+ if (expiration !== void 0) {
21996
23043
  payload.exp = Math.floor(expiration.getTime() / 1e3);
21997
23044
  }
21998
- const jwt = new jose_1.SignJWT(payload).setProtectedHeader({ alg: "HS256", typ: "JWT" });
21999
- const jwtToken = await jwt.sign(secretKey);
22000
- return jwtToken;
23045
+ const secretKey = new TextEncoder().encode(resolvedSecret);
23046
+ return await new jose_1.SignJWT(payload).setProtectedHeader({ alg: "HS256", typ: "JWT" }).sign(secretKey);
22001
23047
  }
22002
23048
  static fromJson(json) {
22003
- const { name, sub, grants, kid, version, ...rest } = json;
22004
- const extra = { ...rest };
22005
- const v = version ? version : "0.5.3";
23049
+ const data = { ...json };
23050
+ if (typeof data.name !== "string") {
23051
+ throw new Error(`Participant token does not have a name ${JSON.stringify(json)}`);
23052
+ }
23053
+ const name = data.name;
23054
+ delete data.name;
23055
+ const grantsRaw = Array.isArray(data.grants) ? data.grants : [];
23056
+ delete data.grants;
23057
+ const projectId = typeof data.sub === "string" ? data.sub : void 0;
23058
+ delete data.sub;
23059
+ const apiKeyId = typeof data.kid === "string" ? data.kid : void 0;
23060
+ delete data.kid;
23061
+ const version = typeof data.version === "string" ? data.version : version_1.__version__;
23062
+ delete data.version;
22006
23063
  return new _ParticipantToken({
22007
23064
  name,
22008
- projectId: sub,
22009
- apiKeyId: kid,
22010
- version: v,
22011
- grants: grants?.map((g) => ParticipantGrant.fromJson(g)),
22012
- extra
23065
+ projectId,
23066
+ apiKeyId,
23067
+ grants: grantsRaw.map((grant) => ParticipantGrant.fromJson(grant)),
23068
+ extra: data,
23069
+ version
22013
23070
  });
22014
23071
  }
22015
23072
  static async fromJwt(jwtStr, options = {}) {
22016
- const { token, verify: verify2 = true } = options ?? {};
23073
+ const { token, verify: verify2 = true } = options;
22017
23074
  if (verify2) {
22018
- const secretKey = new TextEncoder().encode(token);
23075
+ const verificationToken = token ?? getEnvValue("MESHAGENT_SECRET");
23076
+ if (verificationToken === void 0) {
23077
+ throw new Error("Failed to verify JWT: no token provided");
23078
+ }
23079
+ const secretKey = new TextEncoder().encode(verificationToken);
22019
23080
  const { payload } = await (0, jose_1.jwtVerify)(jwtStr, secretKey, {
22020
23081
  algorithms: ["HS256"]
22021
23082
  });
22022
23083
  return _ParticipantToken.fromJson(payload);
22023
- } else {
22024
- try {
22025
- const payload = (0, jose_1.decodeJwt)(jwtStr);
22026
- return _ParticipantToken.fromJson(payload);
22027
- } catch (err) {
22028
- throw new Error("Failed to decode JWT");
22029
- }
23084
+ }
23085
+ try {
23086
+ return _ParticipantToken.fromJson((0, jose_1.decodeJwt)(jwtStr));
23087
+ } catch {
23088
+ throw new Error("Failed to decode JWT");
22030
23089
  }
22031
23090
  }
22032
23091
  };
@@ -22559,6 +23618,17 @@ ${newlined}
22559
23618
  }
22560
23619
  return bytes;
22561
23620
  }
23621
+ function toFetchBody(body) {
23622
+ if (body == null) {
23623
+ return void 0;
23624
+ }
23625
+ if (typeof body === "string" || body instanceof ArrayBuffer) {
23626
+ return body;
23627
+ }
23628
+ const copy = new Uint8Array(body.byteLength);
23629
+ copy.set(body);
23630
+ return copy.buffer;
23631
+ }
22562
23632
  function normalizeBinary(data) {
22563
23633
  if (data instanceof Uint8Array) {
22564
23634
  return data;
@@ -22610,7 +23680,7 @@ ${newlined}
22610
23680
  const response = await fetch(url, {
22611
23681
  method,
22612
23682
  headers: finalHeaders,
22613
- body: requestBody ?? void 0
23683
+ body: toFetchBody(requestBody)
22614
23684
  });
22615
23685
  if (!response.ok) {
22616
23686
  let message2;
@@ -23066,15 +24136,15 @@ ${newlined}
23066
24136
  });
23067
24137
  }
23068
24138
  async addUserToProject(projectId, userId, options = {}) {
23069
- const { isAdmin = false, isDeveloper = false, canCreateRooms = false } = options;
24139
+ const { isAdmin, isDeveloper, canCreateRooms } = options;
23070
24140
  return await this.request(`/accounts/projects/${projectId}/users`, {
23071
24141
  method: "POST",
23072
24142
  json: {
23073
24143
  project_id: projectId,
23074
24144
  user_id: userId,
23075
- is_admin: isAdmin,
23076
- is_developer: isDeveloper,
23077
- can_create_rooms: canCreateRooms
24145
+ ...isAdmin !== void 0 ? { is_admin: isAdmin } : {},
24146
+ ...isDeveloper !== void 0 ? { is_developer: isDeveloper } : {},
24147
+ ...canCreateRooms !== void 0 ? { can_create_rooms: canCreateRooms } : {}
23078
24148
  },
23079
24149
  action: "add user to project"
23080
24150
  });
@@ -25027,7 +26097,7 @@ ${newlined}
25027
26097
  await this._task;
25028
26098
  }
25029
26099
  };
25030
- SyncOpenStreamState.INPUT_STREAM_CLOSE = Symbol("sync-open-input-close");
26100
+ SyncOpenStreamState.INPUT_STREAM_CLOSE = /* @__PURE__ */ Symbol("sync-open-input-close");
25031
26101
  var SyncClient = class extends event_emitter_1.EventEmitter {
25032
26102
  constructor({ room }) {
25033
26103
  super();
@@ -25326,6 +26396,7 @@ ${newlined}
25326
26396
  super();
25327
26397
  this.client = room;
25328
26398
  this.client.protocol.addHandler("storage.file.deleted", this._handleFileDeleted.bind(this));
26399
+ this.client.protocol.addHandler("storage.file.moved", this._handleFileMoved.bind(this));
25329
26400
  this.client.protocol.addHandler("storage.file.updated", this._handleFileUpdated.bind(this));
25330
26401
  }
25331
26402
  async _handleFileUpdated(protocol, messageId, type, bytes) {
@@ -25340,6 +26411,16 @@ ${newlined}
25340
26411
  this.client.emit(event);
25341
26412
  this.emit("file.deleted", event);
25342
26413
  }
26414
+ async _handleFileMoved(protocol, messageId, type, bytes) {
26415
+ const [data, _] = (0, utils_1.unpackMessage)(bytes || new Uint8Array());
26416
+ const event = new room_event_1.FileMovedEvent({
26417
+ sourcePath: data["source_path"],
26418
+ destinationPath: data["destination_path"],
26419
+ participantId: data["participant_id"]
26420
+ });
26421
+ this.client.emit(event);
26422
+ this.emit("file.moved", event);
26423
+ }
25343
26424
  _unexpectedResponseError(operation) {
25344
26425
  return _unexpectedStorageResponseError(operation);
25345
26426
  }
@@ -25386,6 +26467,13 @@ ${newlined}
25386
26467
  async delete(path, { recursive = null } = {}) {
25387
26468
  await this._invoke("delete", { path, recursive });
25388
26469
  }
26470
+ async move(sourcePath, destinationPath, { overwrite = false } = {}) {
26471
+ await this._invoke("move", {
26472
+ source_path: sourcePath,
26473
+ destination_path: destinationPath,
26474
+ overwrite
26475
+ });
26476
+ }
25389
26477
  async exists(path) {
25390
26478
  const result = await this._invoke("exists", { path });
25391
26479
  if (!(result instanceof response_1.JsonContent)) {
@@ -25981,6 +27069,17 @@ ${newlined}
25981
27069
  }
25982
27070
  return secrets.map((item) => this.parseSecretInfo(item));
25983
27071
  }
27072
+ async exists({ secretId, delegatedTo, forIdentity }) {
27073
+ const response = await this.invoke("exists", {
27074
+ secret_id: secretId,
27075
+ delegated_to: delegatedTo ?? null,
27076
+ for_identity: forIdentity ?? null
27077
+ });
27078
+ if (!(response instanceof response_1.JsonContent) || typeof response.json["exists"] !== "boolean") {
27079
+ throw this.unexpectedResponse("exists");
27080
+ }
27081
+ return response.json["exists"];
27082
+ }
25984
27083
  async deleteSecret({ secretId, delegatedTo }) {
25985
27084
  const response = await this.invoke("delete_secret", {
25986
27085
  id: secretId,
@@ -26523,6 +27622,7 @@ ${newlined}
26523
27622
  __exportStar(require_helpers(), exports);
26524
27623
  __exportStar(require_tool_content_type(), exports);
26525
27624
  __exportStar(require_utils(), exports);
27625
+ __exportStar(require_version2(), exports);
26526
27626
  }
26527
27627
  });
26528
27628