@mitralab.io/sdk-core 0.1.1 → 0.2.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -20,19 +20,46 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
+ AgentTaskTurnError: () => AgentTaskTurnError,
23
24
  SdkCoreConfigurationError: () => SdkCoreConfigurationError,
24
25
  SdkCoreResponseError: () => SdkCoreResponseError,
26
+ createAgentConnectionsModule: () => createAgentConnectionsModule,
27
+ createAgentCredentialsModule: () => createAgentCredentialsModule,
28
+ createAgentTaskSessionManager: () => createAgentTaskSessionManager,
29
+ createAgentTasksModule: () => createAgentTasksModule,
30
+ createAgentsModule: () => createAgentsModule,
31
+ createAppsModule: () => createAppsModule,
25
32
  createAuthModule: () => createAuthModule,
33
+ createContextModule: () => createContextModule,
34
+ createCustomQueriesModule: () => createCustomQueriesModule,
35
+ createDataSourcesModule: () => createDataSourcesModule,
26
36
  createEntitiesModule: () => createEntitiesModule,
37
+ createFunctionsAdminModule: () => createFunctionsAdminModule,
27
38
  createFunctionsModule: () => createFunctionsModule,
39
+ createImportsModule: () => createImportsModule,
40
+ createIntegrationAdminModule: () => createIntegrationAdminModule,
28
41
  createIntegrationModule: () => createIntegrationModule,
42
+ createIntegrationResourcesModule: () => createIntegrationResourcesModule,
43
+ createIntegrationTemplatesModule: () => createIntegrationTemplatesModule,
44
+ createMembersModule: () => createMembersModule,
45
+ createMessengerModule: () => createMessengerModule,
46
+ createPublicFunctionsModule: () => createPublicFunctionsModule,
29
47
  createQueriesModule: () => createQueriesModule,
48
+ createSchemaModule: () => createSchemaModule,
30
49
  createSdkCore: () => createSdkCore,
50
+ createSqlModule: () => createSqlModule,
51
+ createWorkflowsModule: () => createWorkflowsModule,
31
52
  defaultSdkCoreErrorFactory: () => defaultSdkCoreErrorFactory,
32
53
  encodePathSegment: () => encodePathSegment,
33
54
  expectEmpty: () => expectEmpty,
55
+ expectLegacyPage: () => expectLegacyPage,
56
+ expectNullableObject: () => expectNullableObject,
34
57
  expectObject: () => expectObject,
35
- expectObjectArray: () => expectObjectArray
58
+ expectObjectArray: () => expectObjectArray,
59
+ expectPage: () => expectPage,
60
+ expectStringArray: () => expectStringArray,
61
+ toAgentTimelineItem: () => toAgentTimelineItem,
62
+ withAgentTaskSessions: () => withAgentTaskSessions
36
63
  });
37
64
  module.exports = __toCommonJS(index_exports);
38
65
 
@@ -62,6 +89,23 @@ function invalidResponse(message, errors = defaultSdkCoreErrorFactory) {
62
89
  throw errors.invalidResponse(message);
63
90
  }
64
91
 
92
+ // src/batch.ts
93
+ function requireBatchSize(items, name, maxSize, errors = defaultSdkCoreErrorFactory) {
94
+ if (items.length < 1 || items.length > maxSize) {
95
+ configurationError(`${name} must contain between 1 and ${maxSize} items`, errors);
96
+ }
97
+ }
98
+
99
+ // src/path.ts
100
+ function encodePathSegment(value, name, errors = defaultSdkCoreErrorFactory) {
101
+ const segment = String(value);
102
+ if (!segment.trim()) configurationError(`${name} must not be empty`, errors);
103
+ if (segment === "." || segment === "..") {
104
+ configurationError(`${name} must not be a dot segment`, errors);
105
+ }
106
+ return encodeURIComponent(segment);
107
+ }
108
+
65
109
  // src/response.ts
66
110
  function isObject(value) {
67
111
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -69,6 +113,9 @@ function isObject(value) {
69
113
  function isNullableString(value) {
70
114
  return value === null || typeof value === "string";
71
115
  }
116
+ function isNullableBoolean(value) {
117
+ return value === null || typeof value === "boolean";
118
+ }
72
119
  function isInteger(value) {
73
120
  return typeof value === "number" && Number.isInteger(value);
74
121
  }
@@ -78,6 +125,21 @@ function isNullableInteger(value) {
78
125
  function isStringRecord(value) {
79
126
  return isObject(value) && Object.values(value).every((item) => typeof item === "string");
80
127
  }
128
+ function isStringArray(value) {
129
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
130
+ }
131
+ function isJsonValue(value) {
132
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
133
+ if (typeof value === "number") return Number.isFinite(value);
134
+ if (Array.isArray(value)) return value.every(isJsonValue);
135
+ return isObject(value) && Object.values(value).every(isJsonValue);
136
+ }
137
+ function isJsonRecord(value) {
138
+ return isObject(value) && Object.values(value).every(isJsonValue);
139
+ }
140
+ function isOneOf(value, allowed) {
141
+ return typeof value === "string" && allowed.includes(value);
142
+ }
81
143
  function hasOwn(value, property) {
82
144
  return Object.hasOwn(value, property);
83
145
  }
@@ -90,21 +152,67 @@ function expectObject(value, context, errors = defaultSdkCoreErrorFactory) {
90
152
  }
91
153
  return value;
92
154
  }
93
- function expectObjectArray(value, context, errors = defaultSdkCoreErrorFactory) {
155
+ function expectObjectArray(value, context, errors = defaultSdkCoreErrorFactory, validateItem) {
94
156
  if (!Array.isArray(value) || value.some((item) => !isObject(item))) {
95
157
  return invalidResponse(`${context} must be a JSON array of objects`, errors);
96
158
  }
159
+ if (validateItem) {
160
+ value.forEach((item, position) => validateItem(item, `${context} item ${position}`, errors));
161
+ }
162
+ return value;
163
+ }
164
+ function expectNullableObject(value, context, errors = defaultSdkCoreErrorFactory) {
165
+ return value === null ? null : expectObject(value, context, errors);
166
+ }
167
+ function expectStringArray(value, context, errors = defaultSdkCoreErrorFactory) {
168
+ if (!isStringArray(value)) {
169
+ return invalidResponse(`${context} must be a JSON array of strings`, errors);
170
+ }
97
171
  return value;
98
172
  }
173
+ function expectPage(value, context, errors = defaultSdkCoreErrorFactory, validateItem) {
174
+ const page = expectObject(value, context, errors);
175
+ if (!Array.isArray(page.content) || page.content.some((item) => !isObject(item))) {
176
+ invalidField(context, "content", errors);
177
+ }
178
+ const metadata = expectObject(page.page, `${context} page`, errors);
179
+ for (const field of ["size", "totalElements", "totalPages", "number"]) {
180
+ if (!isInteger(metadata[field])) invalidField(`${context} page`, field, errors);
181
+ }
182
+ if (metadata.totalElements < page.content.length) {
183
+ invalidField(`${context} page`, "totalElements", errors);
184
+ }
185
+ if (validateItem) {
186
+ page.content.forEach(
187
+ (item, position) => validateItem(item, `${context} item ${position}`, errors)
188
+ );
189
+ }
190
+ return page;
191
+ }
192
+ function expectLegacyPage(value, context, errors = defaultSdkCoreErrorFactory, validateItem) {
193
+ const page = expectObject(value, context, errors);
194
+ if (!Array.isArray(page.content) || page.content.some((item) => !isObject(item))) {
195
+ invalidField(context, "content", errors);
196
+ }
197
+ if (!isInteger(page.totalElements) || page.totalElements < page.content.length) {
198
+ invalidField(context, "totalElements", errors);
199
+ }
200
+ if (validateItem) {
201
+ page.content.forEach(
202
+ (item, position) => validateItem(item, `${context} item ${position}`, errors)
203
+ );
204
+ }
205
+ return page;
206
+ }
99
207
  function expectTenant(value, context, errors = defaultSdkCoreErrorFactory) {
100
208
  const tenant = expectObject(value, context, errors);
101
209
  if (typeof tenant.id !== "string") invalidField(context, "id", errors);
102
210
  if (typeof tenant.shortId !== "string") invalidField(context, "shortId", errors);
103
211
  if (!isNullableInteger(tenant.legacyId)) invalidField(context, "legacyId", errors);
104
212
  if (typeof tenant.slug !== "string") invalidField(context, "slug", errors);
105
- if (!isObject(tenant.plan)) invalidField(context, "plan", errors);
106
- if (typeof tenant.plan.id !== "string") invalidField(`${context} plan`, "id", errors);
107
- if (typeof tenant.plan.name !== "string") invalidField(`${context} plan`, "name", errors);
213
+ if (!isOneOf(tenant.clusterType, ["SHARED", "DEDICATED"])) {
214
+ invalidField(context, "clusterType", errors);
215
+ }
108
216
  if (typeof tenant.name !== "string") invalidField(context, "name", errors);
109
217
  if (!isNullableString(tenant.description)) invalidField(context, "description", errors);
110
218
  if (!isNullableString(tenant.hexColor)) invalidField(context, "hexColor", errors);
@@ -120,11 +228,29 @@ function expectUser(value, context, errors = defaultSdkCoreErrorFactory) {
120
228
  if (typeof user.name !== "string") invalidField(context, "name", errors);
121
229
  if (typeof user.email !== "string") invalidField(context, "email", errors);
122
230
  if (!isNullableString(user.imageUrl)) invalidField(context, "imageUrl", errors);
231
+ if (typeof user.planId !== "string") invalidField(context, "planId", errors);
123
232
  if (typeof user.onboardingCompleted !== "boolean") {
124
233
  invalidField(context, "onboardingCompleted", errors);
125
234
  }
235
+ if (typeof user.language !== "string") invalidField(context, "language", errors);
126
236
  return user;
127
237
  }
238
+ function expectUserPlan(value, context, errors = defaultSdkCoreErrorFactory) {
239
+ const plan = expectObject(value, context, errors);
240
+ if (typeof plan.id !== "string") invalidField(context, "id", errors);
241
+ if (typeof plan.code !== "string") invalidField(context, "code", errors);
242
+ if (typeof plan.name !== "string") invalidField(context, "name", errors);
243
+ if (!isInteger(plan.maxUsers)) invalidField(context, "maxUsers", errors);
244
+ expectObjectArray(plan.prices, `${context} prices`, errors).forEach(
245
+ (price, position) => {
246
+ const priceContext = `${context} price ${position}`;
247
+ if (typeof price.currency !== "string") invalidField(priceContext, "currency", errors);
248
+ if (!isInteger(price.amountMinorUnits)) invalidField(priceContext, "amountMinorUnits", errors);
249
+ if (typeof price.interval !== "string") invalidField(priceContext, "interval", errors);
250
+ }
251
+ );
252
+ return plan;
253
+ }
128
254
  function expectQueryResult(value, context, errors = defaultSdkCoreErrorFactory) {
129
255
  const result = expectObject(value, context, errors);
130
256
  if (!Array.isArray(result.rows) || result.rows.some((row) => !isObject(row))) {
@@ -159,7 +285,7 @@ function expectFunctionExecution(value, context, errors = defaultSdkCoreErrorFac
159
285
  if (!isNullableInteger(execution.durationMs)) invalidField(context, "durationMs", errors);
160
286
  if (!isNullableString(execution.startedAt)) invalidField(context, "startedAt", errors);
161
287
  if (!isNullableString(execution.finishedAt)) invalidField(context, "finishedAt", errors);
162
- if (typeof execution.createdAt !== "string") invalidField(context, "createdAt", errors);
288
+ if (!isNullableString(execution.createdAt)) invalidField(context, "createdAt", errors);
163
289
  return execution;
164
290
  }
165
291
  function expectProxyResult(value, context, errors = defaultSdkCoreErrorFactory) {
@@ -175,194 +301,2083 @@ function expectProxyResult(value, context, errors = defaultSdkCoreErrorFactory)
175
301
  if (typeof result.executionId !== "string") invalidField(context, "executionId", errors);
176
302
  return result;
177
303
  }
178
- function expectEmpty(value, context, errors = defaultSdkCoreErrorFactory) {
179
- if (value !== void 0) invalidResponse(`${context} must be empty`, errors);
304
+ function expectBatchExecution(value, context, errors = defaultSdkCoreErrorFactory) {
305
+ const execution = expectObject(value, context, errors);
306
+ expectObjectArray(execution.results, `${context} results`, errors).forEach(
307
+ (item, position) => {
308
+ const itemContext = `${context} result ${position}`;
309
+ if (!isInteger(item.index)) invalidField(itemContext, "index", errors);
310
+ if (hasOwn(item, "affectedRows") && !isInteger(item.affectedRows)) {
311
+ invalidField(itemContext, "affectedRows", errors);
312
+ }
313
+ if (!isInteger(item.durationMs)) invalidField(itemContext, "durationMs", errors);
314
+ }
315
+ );
316
+ if (!isInteger(execution.executedCount)) invalidField(context, "executedCount", errors);
317
+ if (!isInteger(execution.totalDurationMs)) invalidField(context, "totalDurationMs", errors);
318
+ return execution;
180
319
  }
181
-
182
- // src/modules/auth.ts
183
- function createAuthModule(transport, errors = defaultSdkCoreErrorFactory) {
184
- return {
185
- async me() {
186
- return expectUser(
187
- await transport.request("/api/v1/auth/me", { method: "GET" }),
188
- "Current user response",
189
- errors
190
- );
320
+ function expectSchemaTables(value, context, errors = defaultSdkCoreErrorFactory) {
321
+ const groups = expectObjectArray(value, context, errors);
322
+ groups.forEach((group, position) => {
323
+ const groupContext = `${context} group ${position}`;
324
+ if (typeof group.schema !== "string") invalidField(groupContext, "schema", errors);
325
+ expectObjectArray(group.tables, `${groupContext} tables`, errors).forEach(
326
+ (table, tablePosition) => {
327
+ const tableContext = `${groupContext} table ${tablePosition}`;
328
+ if (typeof table.tableName !== "string") invalidField(tableContext, "tableName", errors);
329
+ expectObjectArray(table.columns, `${tableContext} columns`, errors).forEach(
330
+ (column, columnPosition) => {
331
+ const columnContext = `${tableContext} column ${columnPosition}`;
332
+ if (typeof column.name !== "string") invalidField(columnContext, "name", errors);
333
+ if (typeof column.type !== "string") invalidField(columnContext, "type", errors);
334
+ if (typeof column.primaryKey !== "boolean") {
335
+ invalidField(columnContext, "primaryKey", errors);
336
+ }
337
+ if (typeof column.nullable !== "boolean") {
338
+ invalidField(columnContext, "nullable", errors);
339
+ }
340
+ if (!isNullableString(column.defaultValue)) {
341
+ invalidField(columnContext, "defaultValue", errors);
342
+ }
343
+ }
344
+ );
345
+ expectObjectArray(
346
+ table.foreignKeys,
347
+ `${tableContext} foreignKeys`,
348
+ errors
349
+ ).forEach((foreignKey, foreignKeyPosition) => {
350
+ const foreignKeyContext = `${tableContext} foreign key ${foreignKeyPosition}`;
351
+ if (!isStringArray(foreignKey.columns)) {
352
+ invalidField(foreignKeyContext, "columns", errors);
353
+ }
354
+ if (typeof foreignKey.referencedTable !== "string") {
355
+ invalidField(foreignKeyContext, "referencedTable", errors);
356
+ }
357
+ if (!isStringArray(foreignKey.referencedColumns)) {
358
+ invalidField(foreignKeyContext, "referencedColumns", errors);
359
+ }
360
+ });
361
+ }
362
+ );
363
+ });
364
+ return groups;
365
+ }
366
+ function expectBulkResult(value, context, idField, errors) {
367
+ const result = expectObject(value, context, errors);
368
+ expectObjectArray(result.results, `${context} results`, errors).forEach(
369
+ (item, position) => {
370
+ const itemContext = `${context} result ${position}`;
371
+ if (!isInteger(item.index)) invalidField(itemContext, "index", errors);
372
+ if (typeof item.success !== "boolean") invalidField(itemContext, "success", errors);
373
+ if (hasOwn(item, idField) && !isNullableString(item[idField])) {
374
+ invalidField(itemContext, idField, errors);
375
+ }
376
+ if (hasOwn(item, "errorCode") && !isNullableString(item.errorCode)) {
377
+ invalidField(itemContext, "errorCode", errors);
378
+ }
379
+ if (hasOwn(item, "message") && !isNullableString(item.message)) {
380
+ invalidField(itemContext, "message", errors);
381
+ }
191
382
  }
192
- };
383
+ );
384
+ if (!isInteger(result.processedCount)) invalidField(context, "processedCount", errors);
385
+ if (!isInteger(result.succeededCount)) invalidField(context, "succeededCount", errors);
386
+ if (!isInteger(result.failedCount)) invalidField(context, "failedCount", errors);
387
+ return result;
193
388
  }
194
-
195
- // src/path.ts
196
- function encodePathSegment(value, name, errors = defaultSdkCoreErrorFactory) {
197
- const segment = String(value);
198
- if (!segment.trim()) configurationError(`${name} must not be empty`, errors);
199
- if (segment === "." || segment === "..") {
200
- configurationError(`${name} must not be a dot segment`, errors);
389
+ function expectTemplateConfigBulkResult(value, context, errors = defaultSdkCoreErrorFactory) {
390
+ return expectBulkResult(value, context, "configId", errors);
391
+ }
392
+ function expectFunctionVersion(value, context, errors) {
393
+ const version = expectObject(value, context, errors);
394
+ if (typeof version.id !== "string") invalidField(context, "id", errors);
395
+ if (typeof version.functionId !== "string") invalidField(context, "functionId", errors);
396
+ if (typeof version.status !== "string") invalidField(context, "status", errors);
397
+ if (typeof version.code !== "string") invalidField(context, "code", errors);
398
+ if (version.inputSchema !== null && !isObject(version.inputSchema)) {
399
+ invalidField(context, "inputSchema", errors);
201
400
  }
202
- return encodeURIComponent(segment);
401
+ if (version.outputSchema !== null && !isObject(version.outputSchema)) {
402
+ invalidField(context, "outputSchema", errors);
403
+ }
404
+ if (version.secrets !== null && !isStringArray(version.secrets)) {
405
+ invalidField(context, "secrets", errors);
406
+ }
407
+ if (typeof version.createdAt !== "string") invalidField(context, "createdAt", errors);
203
408
  }
204
-
205
- // src/modules/entities.ts
206
- var DefaultEntitiesModule = class {
207
- constructor(transport, errors) {
208
- this.transport = transport;
209
- this.errors = errors;
409
+ function expectFunctionDefinition(value, context, errors = defaultSdkCoreErrorFactory) {
410
+ const definition = expectObject(value, context, errors);
411
+ if (typeof definition.id !== "string") invalidField(context, "id", errors);
412
+ if (typeof definition.tenantId !== "string") invalidField(context, "tenantId", errors);
413
+ if (!isNullableString(definition.appId)) invalidField(context, "appId", errors);
414
+ if (!isNullableInteger(definition.legacyId)) invalidField(context, "legacyId", errors);
415
+ if (typeof definition.name !== "string") invalidField(context, "name", errors);
416
+ if (!isNullableString(definition.description)) invalidField(context, "description", errors);
417
+ if (typeof definition.runtime !== "string") invalidField(context, "runtime", errors);
418
+ if (!isNullableString(definition.dataSourceId)) invalidField(context, "dataSourceId", errors);
419
+ if (typeof definition.visibility !== "string") invalidField(context, "visibility", errors);
420
+ if (definition.currentVersion !== null) {
421
+ expectFunctionVersion(definition.currentVersion, `${context} current version`, errors);
210
422
  }
211
- tables = /* @__PURE__ */ new Map();
212
- getTable(tableName) {
213
- if (!this.tables.has(tableName)) {
214
- this.tables.set(tableName, this.createTable(tableName));
423
+ if (!isNullableString(definition.cronExpression)) {
424
+ invalidField(context, "cronExpression", errors);
425
+ }
426
+ if (definition.cronInputJson !== null && !isJsonRecord(definition.cronInputJson)) {
427
+ invalidField(context, "cronInputJson", errors);
428
+ }
429
+ if (!isNullableBoolean(definition.cronEnabled)) invalidField(context, "cronEnabled", errors);
430
+ if (!isNullableString(definition.createdAt)) invalidField(context, "createdAt", errors);
431
+ if (typeof definition.updatedAt !== "string") invalidField(context, "updatedAt", errors);
432
+ return definition;
433
+ }
434
+ function expectFunctionDefinitions(value, context, errors = defaultSdkCoreErrorFactory) {
435
+ return expectObjectArray(value, context, errors).map(
436
+ (item, position) => expectFunctionDefinition(item, `${context} item ${position}`, errors)
437
+ );
438
+ }
439
+ function expectFunctionBulkDeleteResult(value, context, errors = defaultSdkCoreErrorFactory) {
440
+ const result = expectObject(value, context, errors);
441
+ if (!isStringArray(result.deleted)) invalidField(context, "deleted", errors);
442
+ if (!isStringArray(result.notFound)) invalidField(context, "notFound", errors);
443
+ if (!isInteger(result.deletedCount)) invalidField(context, "deletedCount", errors);
444
+ return result;
445
+ }
446
+ function expectTemplateConfigPage(value, context, errors = defaultSdkCoreErrorFactory) {
447
+ return expectLegacyPage(value, context, errors, expectTemplateConfigSummary);
448
+ }
449
+ function expectConnectionTestResult(value, context, errors = defaultSdkCoreErrorFactory) {
450
+ const result = expectObject(value, context, errors);
451
+ if (!isOneOf(result.status, ["unchecked", "connected", "error"])) {
452
+ invalidField(context, "status", errors);
453
+ }
454
+ if (!isInteger(result.durationMs)) invalidField(context, "durationMs", errors);
455
+ if (typeof result.checkedAt !== "string") invalidField(context, "checkedAt", errors);
456
+ if (!isNullableString(result.message)) invalidField(context, "message", errors);
457
+ return result;
458
+ }
459
+ function expectAppMembers(value, context, errors = defaultSdkCoreErrorFactory) {
460
+ const members = expectObjectArray(value, context, errors);
461
+ members.forEach((member, position) => {
462
+ const memberContext = `${context} member ${position}`;
463
+ if (typeof member.userId !== "string") invalidField(memberContext, "userId", errors);
464
+ if (typeof member.name !== "string") invalidField(memberContext, "name", errors);
465
+ if (typeof member.email !== "string") invalidField(memberContext, "email", errors);
466
+ if (typeof member.accessLevel !== "string") invalidField(memberContext, "accessLevel", errors);
467
+ if (typeof member.accessSource !== "string") {
468
+ invalidField(memberContext, "accessSource", errors);
215
469
  }
216
- return this.tables.get(tableName);
470
+ });
471
+ return members;
472
+ }
473
+ function expectBulkUnsubscribeResult(value, context, errors = defaultSdkCoreErrorFactory) {
474
+ const result = expectObject(value, context, errors);
475
+ if (!isStringArray(result.revoked)) invalidField(context, "revoked", errors);
476
+ if (!isStringArray(result.notFound)) invalidField(context, "notFound", errors);
477
+ if (!isInteger(result.revokedCount)) invalidField(context, "revokedCount", errors);
478
+ return result;
479
+ }
480
+ function expectAppDefinition(value, context, errors = defaultSdkCoreErrorFactory) {
481
+ const app = expectObject(value, context, errors);
482
+ expectAppFields(app, context, errors);
483
+ if (!isNullableString(app.dataSourceId)) invalidField(context, "dataSourceId", errors);
484
+ return app;
485
+ }
486
+ function expectAppSummary(value, context, errors = defaultSdkCoreErrorFactory) {
487
+ const app = expectObject(value, context, errors);
488
+ expectAppFields(app, context, errors);
489
+ if (typeof app.tenantId !== "string") invalidField(context, "tenantId", errors);
490
+ return app;
491
+ }
492
+ function expectAppFields(app, context, errors) {
493
+ for (const field of ["id", "shortId", "subdomain", "brand", "name", "planId"]) {
494
+ if (typeof app[field] !== "string") invalidField(context, field, errors);
217
495
  }
218
- createTable(tableName) {
219
- const basePath = `/api/v1/tables/${encodePathSegment(tableName, "tableName", this.errors)}/records`;
220
- return {
221
- list: async (sortOrOptions, limit, skip, fields) => {
222
- const options = typeof sortOrOptions === "object" ? sortOrOptions : void 0;
223
- const params = {
224
- sort: options?.sort ?? (typeof sortOrOptions === "string" ? sortOrOptions : void 0),
225
- limit: options?.limit ?? limit,
226
- skip: options?.skip ?? skip,
227
- fields: (options?.fields ?? fields)?.join(",")
228
- };
229
- const response = expectObject(
230
- await this.transport.request(basePath, { method: "GET", params }),
231
- "Entity list response",
232
- this.errors
233
- );
234
- return expectObjectArray(response.data, "Entity list data", this.errors);
235
- },
236
- filter: async (query, sort, limit, skip, fields) => {
237
- const response = expectObject(
238
- await this.transport.request(basePath, {
239
- method: "GET",
240
- params: {
241
- q: JSON.stringify(query),
242
- sort,
243
- limit,
244
- skip,
245
- fields: fields?.join(",")
246
- }
247
- }),
248
- "Entity list response",
249
- this.errors
250
- );
251
- return expectObjectArray(response.data, "Entity list data", this.errors);
252
- },
253
- get: async (id) => expectObject(
254
- await this.transport.request(
255
- `${basePath}/${encodePathSegment(id, "id", this.errors)}`,
256
- { method: "GET" }
257
- ),
258
- "Entity response",
259
- this.errors
260
- ),
261
- create: async (data) => expectObject(
262
- await this.transport.request(basePath, { method: "POST", body: data }),
263
- "Created entity response",
264
- this.errors
265
- ),
266
- bulkCreate: async (data) => expectObjectArray(
267
- await this.transport.request(`${basePath}/bulk`, {
268
- method: "POST",
269
- body: data
270
- }),
271
- "Bulk create response",
272
- this.errors
273
- ),
274
- update: async (id, data) => expectObject(
275
- await this.transport.request(
276
- `${basePath}/${encodePathSegment(id, "id", this.errors)}`,
277
- { method: "PUT", body: data }
278
- ),
279
- "Updated entity response",
280
- this.errors
281
- ),
282
- delete: (id) => this.transport.request(`${basePath}/${encodePathSegment(id, "id", this.errors)}`, {
283
- method: "DELETE"
284
- }).then((response) => expectEmpty(response, "Delete entity response", this.errors)),
285
- deleteMany: async (query) => {
286
- if (Object.keys(query).length === 0) {
287
- configurationError("query must not be empty for deleteMany", this.errors);
288
- }
289
- const response = expectObject(
290
- await this.transport.request(basePath, {
291
- method: "DELETE",
292
- params: { q: JSON.stringify(query) }
293
- }),
294
- "Delete many response",
295
- this.errors
296
- );
297
- if (!Number.isInteger(response.deleted)) {
298
- return invalidResponse(
299
- "Delete many response must include an integer deleted count",
300
- this.errors
301
- );
302
- }
303
- return { deleted: response.deleted };
304
- }
305
- };
496
+ if (!isNullableInteger(app.legacyId)) invalidField(context, "legacyId", errors);
497
+ if (!isNullableString(app.description)) invalidField(context, "description", errors);
498
+ if (!isNullableString(app.icon)) invalidField(context, "icon", errors);
499
+ if (!isNullableString(app.template)) invalidField(context, "template", errors);
500
+ if (typeof app.allowSignup !== "boolean") invalidField(context, "allowSignup", errors);
501
+ if (typeof app.externalAccessEnabled !== "boolean") {
502
+ invalidField(context, "externalAccessEnabled", errors);
306
503
  }
307
- };
308
- function createEntitiesModule(transport, errors = defaultSdkCoreErrorFactory) {
309
- const instance = new DefaultEntitiesModule(transport, errors);
310
- return new Proxy(instance, {
311
- get(target, property, receiver) {
312
- if (typeof property !== "string" || property in target) {
313
- return Reflect.get(target, property, receiver);
504
+ expectAppColor(app.color, `${context} color`, errors);
505
+ expectObjectArray(app.domains, `${context} domains`, errors).forEach(
506
+ (domain, position) => {
507
+ const domainContext = `${context} domain ${position}`;
508
+ if (typeof domain.hostname !== "string") invalidField(domainContext, "hostname", errors);
509
+ if (!isOneOf(domain.kind, ["PLATFORM", "CUSTOM"])) {
510
+ invalidField(domainContext, "kind", errors);
511
+ }
512
+ if (!isOneOf(domain.status, ["ACTIVE", "PENDING", "INACTIVE"])) {
513
+ invalidField(domainContext, "status", errors);
314
514
  }
315
- return target.getTable(property);
316
515
  }
317
- });
516
+ );
517
+ if (app.currentVersion !== null) {
518
+ expectAppVersion(app.currentVersion, `${context} currentVersion`, errors);
519
+ }
520
+ if (typeof app.createdAt !== "string") invalidField(context, "createdAt", errors);
521
+ if (typeof app.updatedAt !== "string") invalidField(context, "updatedAt", errors);
318
522
  }
319
-
320
- // src/modules/functions.ts
321
- var DefaultFunctionsModule = class {
322
- constructor(transport, errors, options) {
323
- this.transport = transport;
324
- this.errors = errors;
325
- this.options = options;
523
+ function expectAppColor(value, context, errors) {
524
+ const color = expectObject(value, context, errors);
525
+ if (color.type === "SOLID") {
526
+ if (typeof color.hex !== "string") invalidField(context, "hex", errors);
527
+ return;
326
528
  }
327
- execute(id, input) {
328
- return this.executeWithType(id, this.options.executeInvocationType, input);
529
+ if (color.type === "GRADIENT") {
530
+ if (typeof color.startHex !== "string") invalidField(context, "startHex", errors);
531
+ if (typeof color.endHex !== "string") invalidField(context, "endHex", errors);
532
+ return;
329
533
  }
330
- executeAsync(id, input) {
331
- return this.executeWithType(id, "async", input);
534
+ invalidField(context, "type", errors);
535
+ }
536
+ function expectAppDeploy(value, context, errors = defaultSdkCoreErrorFactory) {
537
+ const deploy = expectObject(value, context, errors);
538
+ if (typeof deploy.id !== "string") invalidField(context, "id", errors);
539
+ if (typeof deploy.appId !== "string") invalidField(context, "appId", errors);
540
+ if (typeof deploy.appVersionId !== "string") invalidField(context, "appVersionId", errors);
541
+ if (!isOneOf(deploy.status, ["PENDING", "BUILDING", "DEPLOYED", "FAILED", "CANCELLED"])) {
542
+ invalidField(context, "status", errors);
332
543
  }
333
- getExecution(id) {
334
- return this.transport.request(
335
- `/api/v1/executions/${encodePathSegment(id, "execution id", this.errors)}`,
336
- { method: "GET" }
337
- ).then(
338
- (response) => expectFunctionExecution(response, "Function execution response", this.errors)
339
- );
544
+ for (const field of ["deployUrl", "errorMessage", "logs", "startedAt", "finishedAt"]) {
545
+ if (!isNullableString(deploy[field])) invalidField(context, field, errors);
340
546
  }
341
- cancelExecution(id) {
342
- return this.transport.request(
343
- `/api/v1/executions/${encodePathSegment(id, "execution id", this.errors)}/cancel`,
344
- { method: "POST" }
345
- ).then((response) => expectEmpty(response, "Cancel execution response", this.errors));
547
+ if (!isNullableInteger(deploy.durationMs)) invalidField(context, "durationMs", errors);
548
+ if (typeof deploy.createdAt !== "string") invalidField(context, "createdAt", errors);
549
+ return deploy;
550
+ }
551
+ function expectAppVersion(value, context, errors = defaultSdkCoreErrorFactory) {
552
+ const version = expectObject(value, context, errors);
553
+ if (typeof version.id !== "string") invalidField(context, "id", errors);
554
+ if (typeof version.appId !== "string") invalidField(context, "appId", errors);
555
+ if (!isOneOf(version.status, ["DRAFT", "PUBLISHED"])) {
556
+ invalidField(context, "status", errors);
346
557
  }
347
- executeWithType(id, invocationType, input) {
348
- const request = {
349
- method: "POST",
350
- ...input !== void 0 || this.options.emptyInput !== "omit-body" ? { body: { input: input ?? {} } } : {},
351
- ...invocationType === void 0 ? {} : { headers: { "X-Invocation-Type": invocationType } }
352
- };
353
- return this.transport.request(
354
- `/api/v1/functions/${encodePathSegment(id, "function id", this.errors)}/execute`,
355
- request
356
- ).then(
357
- (response) => expectFunctionExecution(response, "Function execution response", this.errors)
358
- );
558
+ if (version.currentDeploy !== null) {
559
+ expectAppDeploy(version.currentDeploy, `${context} currentDeploy`, errors);
359
560
  }
360
- };
361
- function createFunctionsModule(transport, options = {}, errors = defaultSdkCoreErrorFactory) {
362
- return new DefaultFunctionsModule(transport, errors, options);
561
+ if (typeof version.createdAt !== "string") invalidField(context, "createdAt", errors);
562
+ return version;
363
563
  }
364
-
365
- // src/modules/integration.ts
564
+ function expectCustomQueryDefinition(value, context, errors = defaultSdkCoreErrorFactory) {
565
+ const query = expectCustomQuerySummary(value, context, errors);
566
+ if (typeof query.sql !== "string") invalidField(context, "sql", errors);
567
+ return query;
568
+ }
569
+ function expectCustomQuerySummary(value, context, errors = defaultSdkCoreErrorFactory) {
570
+ const query = expectObject(value, context, errors);
571
+ if (typeof query.id !== "string") invalidField(context, "id", errors);
572
+ if (typeof query.name !== "string") invalidField(context, "name", errors);
573
+ if (typeof query.isVirtualTable !== "boolean") invalidField(context, "isVirtualTable", errors);
574
+ if (!isNullableString(query.connectionId)) invalidField(context, "connectionId", errors);
575
+ if (!isNullableString(query.createdAt)) invalidField(context, "createdAt", errors);
576
+ if (typeof query.updatedAt !== "string") invalidField(context, "updatedAt", errors);
577
+ return query;
578
+ }
579
+ function expectConnectionConfig(value, context, errors) {
580
+ const config = expectObject(value, context, errors);
581
+ for (const field of ["host", "schema", "databaseName", "username"]) {
582
+ if (!isNullableString(config[field])) invalidField(context, field, errors);
583
+ }
584
+ if (!isNullableInteger(config.port)) invalidField(context, "port", errors);
585
+ for (const field of [
586
+ "maxPoolSize",
587
+ "connectionTimeoutMs",
588
+ "idleTimeoutMs",
589
+ "minimumIdle",
590
+ "maxLifetimeMs"
591
+ ]) {
592
+ if (!isNullableInteger(config[field])) invalidField(context, field, errors);
593
+ }
594
+ if (config.additionalParams !== null && !isStringRecord(config.additionalParams)) {
595
+ invalidField(context, "additionalParams", errors);
596
+ }
597
+ if (config.credential !== null) invalidField(context, "credential", errors);
598
+ }
599
+ function expectDataSourceDefinition(value, context, errors = defaultSdkCoreErrorFactory) {
600
+ const dataSource = expectObject(value, context, errors);
601
+ if (typeof dataSource.id !== "string") invalidField(context, "id", errors);
602
+ if (!isNullableInteger(dataSource.legacyId)) invalidField(context, "legacyId", errors);
603
+ if (!isNullableString(dataSource.appId)) invalidField(context, "appId", errors);
604
+ if (typeof dataSource.name !== "string") invalidField(context, "name", errors);
605
+ if (!isOneOf(dataSource.instanceType, ["MITRA_SHARED", "MITRA_DEDICATED", "EXTERNAL"])) {
606
+ invalidField(context, "instanceType", errors);
607
+ }
608
+ if (!isOneOf(dataSource.dbType, ["POSTGRES", "MYSQL", "SQLSERVER", "ORACLE"])) {
609
+ invalidField(context, "dbType", errors);
610
+ }
611
+ expectConnectionConfig(
612
+ dataSource.writeConnectionConfig,
613
+ `${context} writeConnectionConfig`,
614
+ errors
615
+ );
616
+ if (dataSource.readConnectionConfig !== null) {
617
+ expectConnectionConfig(
618
+ dataSource.readConnectionConfig,
619
+ `${context} readConnectionConfig`,
620
+ errors
621
+ );
622
+ }
623
+ if (dataSource.connectionStatus !== null && !isOneOf(dataSource.connectionStatus, ["CONNECTED", "ERROR"])) {
624
+ invalidField(context, "connectionStatus", errors);
625
+ }
626
+ if (!isNullableString(dataSource.lastCheckedAt)) invalidField(context, "lastCheckedAt", errors);
627
+ if (dataSource.storageQuota !== null) {
628
+ const quota = expectObject(
629
+ dataSource.storageQuota,
630
+ `${context} storageQuota`,
631
+ errors
632
+ );
633
+ if (quota.status !== null && !isOneOf(quota.status, ["NORMAL", "WATCH", "BLOCKED"])) {
634
+ invalidField(`${context} storageQuota`, "status", errors);
635
+ }
636
+ for (const field of ["usedBytes", "limitBytes", "measurementVersion"]) {
637
+ if (!isNullableInteger(quota[field])) invalidField(`${context} storageQuota`, field, errors);
638
+ }
639
+ if (!isNullableString(quota.measuredAt)) {
640
+ invalidField(`${context} storageQuota`, "measuredAt", errors);
641
+ }
642
+ }
643
+ return dataSource;
644
+ }
645
+ function expectImportSource(value, context, errors) {
646
+ const source = expectObject(value, context, errors);
647
+ if (source.type === "SQL") {
648
+ if (typeof source.query !== "string") invalidField(context, "query", errors);
649
+ return;
650
+ }
651
+ if (source.type === "CSV") {
652
+ if (typeof source.fileKey !== "string") invalidField(context, "fileKey", errors);
653
+ if (typeof source.separator !== "string") invalidField(context, "separator", errors);
654
+ return;
655
+ }
656
+ invalidField(context, "type", errors);
657
+ }
658
+ function expectImportDefinition(value, context, errors = defaultSdkCoreErrorFactory) {
659
+ const definition = expectObject(value, context, errors);
660
+ if (typeof definition.id !== "string") invalidField(context, "id", errors);
661
+ if (!isNullableInteger(definition.legacyId)) invalidField(context, "legacyId", errors);
662
+ if (typeof definition.name !== "string") invalidField(context, "name", errors);
663
+ expectImportSource(definition.source, `${context} source`, errors);
664
+ const target = expectObject(definition.target, `${context} target`, errors);
665
+ if (typeof target.tableName !== "string") invalidField(`${context} target`, "tableName", errors);
666
+ if (!isOneOf(target.mode, ["REPLACE", "APPEND", "UPSERT"])) {
667
+ invalidField(`${context} target`, "mode", errors);
668
+ }
669
+ if (target.upsertKeyColumns !== null && !isStringArray(target.upsertKeyColumns)) {
670
+ invalidField(`${context} target`, "upsertKeyColumns", errors);
671
+ }
672
+ const processing = expectObject(
673
+ definition.processing,
674
+ `${context} processing`,
675
+ errors
676
+ );
677
+ if (!isOneOf(processing.mode, ["CHUNKED", "STREAMING"])) {
678
+ invalidField(`${context} processing`, "mode", errors);
679
+ }
680
+ if (!isNullableString(processing.orderColumn)) {
681
+ invalidField(`${context} processing`, "orderColumn", errors);
682
+ }
683
+ if (!isInteger(processing.chunkSize)) invalidField(`${context} processing`, "chunkSize", errors);
684
+ const schedule = expectObject(definition.schedule, `${context} schedule`, errors);
685
+ if (!isNullableString(schedule.cron)) invalidField(`${context} schedule`, "cron", errors);
686
+ if (typeof schedule.enabled !== "boolean") invalidField(`${context} schedule`, "enabled", errors);
687
+ if (definition.columnMappings !== null) {
688
+ expectObjectArray(
689
+ definition.columnMappings,
690
+ `${context} columnMappings`,
691
+ errors
692
+ ).forEach((mapping, position) => {
693
+ const mappingContext = `${context} columnMapping ${position}`;
694
+ if (typeof mapping.source !== "string") invalidField(mappingContext, "source", errors);
695
+ if (typeof mapping.target !== "string") invalidField(mappingContext, "target", errors);
696
+ if (hasOwn(mapping, "type") && !isNullableString(mapping.type)) {
697
+ invalidField(mappingContext, "type", errors);
698
+ }
699
+ });
700
+ }
701
+ if (typeof definition.createdAt !== "string") invalidField(context, "createdAt", errors);
702
+ if (typeof definition.updatedAt !== "string") invalidField(context, "updatedAt", errors);
703
+ return definition;
704
+ }
705
+ function expectImportExecution(value, context, errors = defaultSdkCoreErrorFactory) {
706
+ const execution = expectObject(value, context, errors);
707
+ if (typeof execution.id !== "string") invalidField(context, "id", errors);
708
+ if (typeof execution.importDefinitionId !== "string") {
709
+ invalidField(context, "importDefinitionId", errors);
710
+ }
711
+ if (!isNullableString(execution.importName)) invalidField(context, "importName", errors);
712
+ if (!isOneOf(execution.status, [
713
+ "PENDING",
714
+ "PREPARING",
715
+ "RUNNING",
716
+ "COMPLETED",
717
+ "PARTIALLY_COMPLETED",
718
+ "FAILED",
719
+ "CANCELLED"
720
+ ])) {
721
+ invalidField(context, "status", errors);
722
+ }
723
+ if (!isOneOf(execution.triggerType, ["MANUAL", "SCHEDULED", "API"])) {
724
+ invalidField(context, "triggerType", errors);
725
+ }
726
+ for (const field of ["totalChunks", "progressPercent", "rowsTotal", "durationSeconds"]) {
727
+ if (!isNullableInteger(execution[field])) invalidField(context, field, errors);
728
+ }
729
+ for (const field of ["completedChunks", "failedChunks", "rowsProcessed"]) {
730
+ if (!isInteger(execution[field])) invalidField(context, field, errors);
731
+ }
732
+ if (typeof execution.queuedAt !== "string") invalidField(context, "queuedAt", errors);
733
+ if (!isNullableString(execution.startedAt)) invalidField(context, "startedAt", errors);
734
+ if (!isNullableString(execution.completedAt)) invalidField(context, "completedAt", errors);
735
+ if (!isNullableString(execution.errorMessage)) invalidField(context, "errorMessage", errors);
736
+ return execution;
737
+ }
738
+ function expectMessageAccepted(value, context, errors = defaultSdkCoreErrorFactory) {
739
+ const response = expectObject(value, context, errors);
740
+ if (typeof response.messageId !== "string") invalidField(context, "messageId", errors);
741
+ return response;
742
+ }
743
+ function expectAgentDefinition(value, context, errors = defaultSdkCoreErrorFactory) {
744
+ const agent = expectObject(value, context, errors);
745
+ if (typeof agent.id !== "string") invalidField(context, "id", errors);
746
+ if (typeof agent.name !== "string") invalidField(context, "name", errors);
747
+ if (!isStringArray(agent.functionIds)) invalidField(context, "functionIds", errors);
748
+ if (typeof agent.autonomous !== "boolean") invalidField(context, "autonomous", errors);
749
+ if (typeof agent.createdAt !== "string") invalidField(context, "createdAt", errors);
750
+ if (typeof agent.updatedAt !== "string") invalidField(context, "updatedAt", errors);
751
+ return agent;
752
+ }
753
+ function expectAgentBulkDeleteResult(value, context, errors = defaultSdkCoreErrorFactory) {
754
+ const result = expectObject(value, context, errors);
755
+ if (!isStringArray(result.deleted)) invalidField(context, "deleted", errors);
756
+ if (!isStringArray(result.notFound)) invalidField(context, "notFound", errors);
757
+ if (!isInteger(result.deletedCount)) invalidField(context, "deletedCount", errors);
758
+ return result;
759
+ }
760
+ function expectWorkflowDefinition(value, context, errors = defaultSdkCoreErrorFactory) {
761
+ const workflow = expectWorkflowSummary(value, context, errors);
762
+ if (!isObject(workflow.definition)) invalidField(context, "definition", errors);
763
+ return workflow;
764
+ }
765
+ function expectWorkflowSummary(value, context, errors = defaultSdkCoreErrorFactory) {
766
+ const workflow = expectObject(value, context, errors);
767
+ if (typeof workflow.id !== "string") invalidField(context, "id", errors);
768
+ if (typeof workflow.tenantId !== "string") invalidField(context, "tenantId", errors);
769
+ if (!isNullableString(workflow.appId)) invalidField(context, "appId", errors);
770
+ if (typeof workflow.name !== "string") invalidField(context, "name", errors);
771
+ if (typeof workflow.createdAt !== "string") invalidField(context, "createdAt", errors);
772
+ if (typeof workflow.updatedAt !== "string") invalidField(context, "updatedAt", errors);
773
+ return workflow;
774
+ }
775
+ function expectWorkflowExecution(value, context, errors = defaultSdkCoreErrorFactory) {
776
+ const execution = expectObject(value, context, errors);
777
+ if (typeof execution.id !== "string") invalidField(context, "id", errors);
778
+ if (typeof execution.tenantId !== "string") invalidField(context, "tenantId", errors);
779
+ if (!isNullableString(execution.appId)) invalidField(context, "appId", errors);
780
+ if (typeof execution.workflowId !== "string") invalidField(context, "workflowId", errors);
781
+ if (!isOneOf(execution.triggerType, ["MANUAL", "SCHEDULED"])) {
782
+ invalidField(context, "triggerType", errors);
783
+ }
784
+ if (!isNullableString(execution.triggeredBy)) invalidField(context, "triggeredBy", errors);
785
+ if (!isOneOf(execution.status, ["PENDING", "RUNNING", "SUCCESS", "FAILED", "CANCELLED"])) {
786
+ invalidField(context, "status", errors);
787
+ }
788
+ if (!isNullableString(execution.currentStepId)) invalidField(context, "currentStepId", errors);
789
+ if (execution.context !== null && !isJsonRecord(execution.context)) {
790
+ invalidField(context, "context", errors);
791
+ }
792
+ if (!isNullableString(execution.errorMessage)) invalidField(context, "errorMessage", errors);
793
+ if (!isNullableString(execution.startedAt)) invalidField(context, "startedAt", errors);
794
+ if (!isNullableString(execution.finishedAt)) invalidField(context, "finishedAt", errors);
795
+ if (typeof execution.createdAt !== "string") invalidField(context, "createdAt", errors);
796
+ return execution;
797
+ }
798
+ function expectIntegrationResource(value, context, errors = defaultSdkCoreErrorFactory) {
799
+ const resource = expectObject(value, context, errors);
800
+ if (typeof resource.id !== "string") invalidField(context, "id", errors);
801
+ if (typeof resource.tenantId !== "string") invalidField(context, "tenantId", errors);
802
+ if (typeof resource.templateConfigId !== "string")
803
+ invalidField(context, "templateConfigId", errors);
804
+ if (typeof resource.name !== "string") invalidField(context, "name", errors);
805
+ if (typeof resource.method !== "string") invalidField(context, "method", errors);
806
+ if (typeof resource.endpoint !== "string") invalidField(context, "endpoint", errors);
807
+ if (resource.body !== null && !isJsonRecord(resource.body)) {
808
+ invalidField(context, "body", errors);
809
+ }
810
+ const params = expectObject(resource.params, `${context} params`, errors);
811
+ Object.entries(params).forEach(([name, value2]) => {
812
+ const paramContext = `${context} param ${name}`;
813
+ const param = expectObject(value2, paramContext, errors);
814
+ if (typeof param.type !== "string") invalidField(paramContext, "type", errors);
815
+ if (typeof param.required !== "boolean") invalidField(paramContext, "required", errors);
816
+ if (!isJsonValue(param.defaultValue)) invalidField(paramContext, "defaultValue", errors);
817
+ if (!isNullableString(param.description)) invalidField(paramContext, "description", errors);
818
+ });
819
+ if (typeof resource.createdAt !== "string") invalidField(context, "createdAt", errors);
820
+ if (typeof resource.updatedAt !== "string") invalidField(context, "updatedAt", errors);
821
+ return resource;
822
+ }
823
+ function expectIntegrationResourceSummary(value, context, errors = defaultSdkCoreErrorFactory) {
824
+ const resource = expectObject(value, context, errors);
825
+ if (typeof resource.id !== "string") invalidField(context, "id", errors);
826
+ if (typeof resource.name !== "string") invalidField(context, "name", errors);
827
+ if (typeof resource.method !== "string") invalidField(context, "method", errors);
828
+ if (typeof resource.endpoint !== "string") invalidField(context, "endpoint", errors);
829
+ return resource;
830
+ }
831
+ function expectIntegrationTemplateSummary(value, context, errors = defaultSdkCoreErrorFactory) {
832
+ const template = expectObject(value, context, errors);
833
+ if (typeof template.id !== "string") invalidField(context, "id", errors);
834
+ if (typeof template.name !== "string") invalidField(context, "name", errors);
835
+ if (!isNullableString(template.baseUrl)) invalidField(context, "baseUrl", errors);
836
+ if (!isOneOf(template.proxyMode, ["OPEN", "RESOURCE_ONLY"])) {
837
+ invalidField(context, "proxyMode", errors);
838
+ }
839
+ if (!isNullableString(template.logoUrl)) invalidField(context, "logoUrl", errors);
840
+ if (!isOneOf(template.templateType, ["GENERIC_AUTH", "PROVIDER"])) {
841
+ invalidField(context, "templateType", errors);
842
+ }
843
+ return template;
844
+ }
845
+ function expectIntegrationTemplate(value, context, errors = defaultSdkCoreErrorFactory) {
846
+ const template = expectIntegrationTemplateSummary(value, context, errors);
847
+ if (template.loginConfig !== null) {
848
+ expectIntegrationLoginConfig(template.loginConfig, `${context} loginConfig`, errors);
849
+ }
850
+ expectIntegrationRequestConfig(template.requestConfig, `${context} requestConfig`, errors);
851
+ expectIntegrationFieldsSchema(template.fieldsSchema, `${context} fieldsSchema`, errors);
852
+ if (!isNullableString(template.documentationUrl)) {
853
+ invalidField(context, "documentationUrl", errors);
854
+ }
855
+ return template;
856
+ }
857
+ function expectIntegrationFieldsSchema(value, context, errors) {
858
+ expectObjectArray(value, context, errors).forEach((field, position) => {
859
+ const fieldContext = `${context} field ${position}`;
860
+ if (typeof field.key !== "string") invalidField(fieldContext, "key", errors);
861
+ if (typeof field.label !== "string") invalidField(fieldContext, "label", errors);
862
+ if (!isOneOf(field.type, ["url", "text", "secret"])) {
863
+ invalidField(fieldContext, "type", errors);
864
+ }
865
+ if (typeof field.required !== "boolean") invalidField(fieldContext, "required", errors);
866
+ if (!isNullableString(field.placeholder)) invalidField(fieldContext, "placeholder", errors);
867
+ if (!isNullableString(field.default)) invalidField(fieldContext, "default", errors);
868
+ });
869
+ }
870
+ function expectIntegrationLoginConfig(value, context, errors) {
871
+ const config = expectObject(value, context, errors);
872
+ if (!isNullableString(config.url)) invalidField(context, "url", errors);
873
+ if (!isNullableString(config.method)) invalidField(context, "method", errors);
874
+ for (const field of ["headers", "query_params", "body_form", "body"]) {
875
+ if (config[field] !== null && !isJsonRecord(config[field])) {
876
+ invalidField(context, field, errors);
877
+ }
878
+ }
879
+ if (config.token_extraction !== null) {
880
+ const extraction = expectObject(
881
+ config.token_extraction,
882
+ `${context} token_extraction`,
883
+ errors
884
+ );
885
+ for (const field of ["source", "path", "name"]) {
886
+ if (!isNullableString(extraction[field])) {
887
+ invalidField(`${context} token_extraction`, field, errors);
888
+ }
889
+ }
890
+ }
891
+ if (!isNullableInteger(config.token_ttl_seconds)) {
892
+ invalidField(context, "token_ttl_seconds", errors);
893
+ }
894
+ }
895
+ function expectIntegrationRequestConfig(value, context, errors) {
896
+ const config = expectObject(value, context, errors);
897
+ if (config.headers !== null && !isJsonRecord(config.headers)) {
898
+ invalidField(context, "headers", errors);
899
+ }
900
+ if (config.credential_rules !== null) {
901
+ expectObjectArray(
902
+ config.credential_rules,
903
+ `${context} credential_rules`,
904
+ errors
905
+ ).forEach((rule, position) => {
906
+ const ruleContext = `${context} credential rule ${position}`;
907
+ if (rule.placement !== null && !isOneOf(rule.placement, ["HEADER", "QUERY", "COOKIE", "BODY", "BASIC"])) {
908
+ invalidField(ruleContext, "placement", errors);
909
+ }
910
+ for (const field of ["name", "path", "value"]) {
911
+ if (!isNullableString(rule[field])) invalidField(ruleContext, field, errors);
912
+ }
913
+ });
914
+ }
915
+ }
916
+ function expectInlineDefinition(config, context, errors) {
917
+ if (hasOwn(config, "fieldsSchemaInline") && config.fieldsSchemaInline !== null) {
918
+ expectIntegrationFieldsSchema(
919
+ config.fieldsSchemaInline,
920
+ `${context} fieldsSchemaInline`,
921
+ errors
922
+ );
923
+ }
924
+ if (hasOwn(config, "requestConfigInline") && config.requestConfigInline !== null) {
925
+ expectIntegrationRequestConfig(
926
+ config.requestConfigInline,
927
+ `${context} requestConfigInline`,
928
+ errors
929
+ );
930
+ }
931
+ if (hasOwn(config, "loginConfigInline") && config.loginConfigInline !== null) {
932
+ expectIntegrationLoginConfig(config.loginConfigInline, `${context} loginConfigInline`, errors);
933
+ }
934
+ }
935
+ function expectTemplateConfigSummary(value, context, errors = defaultSdkCoreErrorFactory) {
936
+ const config = expectObject(value, context, errors);
937
+ if (typeof config.id !== "string") invalidField(context, "id", errors);
938
+ if (!isNullableString(config.appId)) invalidField(context, "appId", errors);
939
+ if (!isNullableInteger(config.legacyId)) invalidField(context, "legacyId", errors);
940
+ if (!isNullableString(config.templateId)) invalidField(context, "templateId", errors);
941
+ if (typeof config.alias !== "string") invalidField(context, "alias", errors);
942
+ expectInlineDefinition(config, context, errors);
943
+ if (config.status !== null && !isOneOf(config.status, ["unchecked", "connected", "error"])) {
944
+ invalidField(context, "status", errors);
945
+ }
946
+ if (!isNullableString(config.lastCheckedAt)) invalidField(context, "lastCheckedAt", errors);
947
+ return config;
948
+ }
949
+ function expectTemplateConfig(value, context, errors = defaultSdkCoreErrorFactory) {
950
+ const config = expectTemplateConfigSummary(value, context, errors);
951
+ if (typeof config.tenantId !== "string") invalidField(context, "tenantId", errors);
952
+ if (!isJsonRecord(config.config)) invalidField(context, "config", errors);
953
+ if (!isNullableString(config.lastCheckMessage)) {
954
+ invalidField(context, "lastCheckMessage", errors);
955
+ }
956
+ if (typeof config.createdAt !== "string") invalidField(context, "createdAt", errors);
957
+ if (typeof config.updatedAt !== "string") invalidField(context, "updatedAt", errors);
958
+ return config;
959
+ }
960
+ function expectIntegrationExecution(value, context, errors = defaultSdkCoreErrorFactory) {
961
+ const execution = expectObject(value, context, errors);
962
+ if (typeof execution.id !== "string") invalidField(context, "id", errors);
963
+ if (typeof execution.templateConfigId !== "string") {
964
+ invalidField(context, "templateConfigId", errors);
965
+ }
966
+ if (!isNullableString(execution.appId)) invalidField(context, "appId", errors);
967
+ if (typeof execution.method !== "string") invalidField(context, "method", errors);
968
+ if (typeof execution.endpoint !== "string") invalidField(context, "endpoint", errors);
969
+ if (!hasOwn(execution, "requestBody") || !isJsonValue(execution.requestBody)) {
970
+ invalidField(context, "requestBody", errors);
971
+ }
972
+ if (!isNullableInteger(execution.responseStatus)) {
973
+ invalidField(context, "responseStatus", errors);
974
+ }
975
+ if (!hasOwn(execution, "responseBody") || !isJsonValue(execution.responseBody)) {
976
+ invalidField(context, "responseBody", errors);
977
+ }
978
+ if (!isNullableInteger(execution.durationMs)) invalidField(context, "durationMs", errors);
979
+ if (typeof execution.success !== "boolean") invalidField(context, "success", errors);
980
+ if (!isNullableString(execution.errorMessage)) invalidField(context, "errorMessage", errors);
981
+ if (!isNullableString(execution.source)) invalidField(context, "source", errors);
982
+ if (typeof execution.createdAt !== "string") invalidField(context, "createdAt", errors);
983
+ return execution;
984
+ }
985
+ function expectAgentTask(value, context, errors = defaultSdkCoreErrorFactory) {
986
+ const task = expectObject(value, context, errors);
987
+ if (typeof task.id !== "string") invalidField(context, "id", errors);
988
+ for (const field of ["appId", "agentId", "userId", "title", "reasoningEffort"]) {
989
+ if (!isNullableString(task[field])) invalidField(context, field, errors);
990
+ }
991
+ if (typeof task.agentType !== "string") invalidField(context, "agentType", errors);
992
+ if (typeof task.archived !== "boolean") invalidField(context, "archived", errors);
993
+ if (!isNullableString(task.createdAt)) invalidField(context, "createdAt", errors);
994
+ if (typeof task.updatedAt !== "string") invalidField(context, "updatedAt", errors);
995
+ return task;
996
+ }
997
+ function expectAgentMessage(value, context, errors = defaultSdkCoreErrorFactory) {
998
+ const message = expectObject(value, context, errors);
999
+ for (const field of ["id", "sender", "type", "content", "createdAt"]) {
1000
+ if (typeof message[field] !== "string") invalidField(context, field, errors);
1001
+ }
1002
+ return message;
1003
+ }
1004
+ function expectAgentModel(value, context, errors = defaultSdkCoreErrorFactory) {
1005
+ const model = expectObject(value, context, errors);
1006
+ for (const field of ["model", "name", "provider", "agentType"]) {
1007
+ if (typeof model[field] !== "string") invalidField(context, field, errors);
1008
+ }
1009
+ if (!isStringArray(model.reasoningOptions)) invalidField(context, "reasoningOptions", errors);
1010
+ return model;
1011
+ }
1012
+ function expectCredentialStatus(value, context, errors = defaultSdkCoreErrorFactory) {
1013
+ const status = expectObject(value, context, errors);
1014
+ if (typeof status.provider !== "string") invalidField(context, "provider", errors);
1015
+ if (typeof status.connected !== "boolean") invalidField(context, "connected", errors);
1016
+ for (const field of ["credentialType", "accountEmail", "maskedApiKey"]) {
1017
+ if (!isNullableString(status[field])) invalidField(context, field, errors);
1018
+ }
1019
+ return status;
1020
+ }
1021
+ function expectOAuthStartResult(value, context, errors = defaultSdkCoreErrorFactory) {
1022
+ const result = expectObject(value, context, errors);
1023
+ if (typeof result.authUrl !== "string") invalidField(context, "authUrl", errors);
1024
+ if (typeof result.state !== "string") invalidField(context, "state", errors);
1025
+ return result;
1026
+ }
1027
+ function expectAuthenticationResult(value, context, errors = defaultSdkCoreErrorFactory) {
1028
+ const result = expectObject(value, context, errors);
1029
+ if (typeof result.connected !== "boolean") invalidField(context, "connected", errors);
1030
+ if (!isNullableString(result.email)) invalidField(context, "email", errors);
1031
+ return result;
1032
+ }
1033
+ function expectDeviceAuthorization(value, context, errors = defaultSdkCoreErrorFactory) {
1034
+ const result = expectObject(value, context, errors);
1035
+ for (const field of ["deviceAuthId", "userCode", "verificationUri"]) {
1036
+ if (typeof result[field] !== "string") invalidField(context, field, errors);
1037
+ }
1038
+ if (!isInteger(result.intervalSeconds)) invalidField(context, "intervalSeconds", errors);
1039
+ return result;
1040
+ }
1041
+ function expectProviderCredentialStatus(value, context, errors) {
1042
+ const status = expectObject(value, context, errors);
1043
+ if (typeof status.provider !== "string") invalidField(context, "provider", errors);
1044
+ if (typeof status.connected !== "boolean") invalidField(context, "connected", errors);
1045
+ if (!isNullableString(status.credentialType)) invalidField(context, "credentialType", errors);
1046
+ if (!isNullableString(status.accountEmail)) invalidField(context, "accountEmail", errors);
1047
+ return status;
1048
+ }
1049
+ function expectAgentConnection(value, context, errors = defaultSdkCoreErrorFactory) {
1050
+ const connection = expectObject(value, context, errors);
1051
+ if (typeof connection.id !== "string") invalidField(context, "id", errors);
1052
+ if (typeof connection.name !== "string") invalidField(context, "name", errors);
1053
+ if (typeof connection.createdAt !== "string") invalidField(context, "createdAt", errors);
1054
+ if (typeof connection.updatedAt !== "string") invalidField(context, "updatedAt", errors);
1055
+ expectObjectArray(
1056
+ connection.credentials,
1057
+ `${context} credentials`,
1058
+ errors,
1059
+ expectProviderCredentialStatus
1060
+ );
1061
+ return connection;
1062
+ }
1063
+ function expectTableDefinition(value, context, errors = defaultSdkCoreErrorFactory) {
1064
+ const wrapped = expectSchemaTables([{ schema: "validation", tables: [value] }], context, errors);
1065
+ return wrapped[0].tables[0];
1066
+ }
1067
+ function expectFunctionSummary(value, context, errors = defaultSdkCoreErrorFactory) {
1068
+ const summary = expectObject(value, context, errors);
1069
+ if (typeof summary.id !== "string") invalidField(context, "id", errors);
1070
+ if (typeof summary.tenantId !== "string") invalidField(context, "tenantId", errors);
1071
+ if (!isNullableString(summary.appId)) invalidField(context, "appId", errors);
1072
+ if (!isNullableInteger(summary.legacyId)) invalidField(context, "legacyId", errors);
1073
+ if (typeof summary.name !== "string") invalidField(context, "name", errors);
1074
+ if (!isNullableString(summary.description)) invalidField(context, "description", errors);
1075
+ if (typeof summary.runtime !== "string") invalidField(context, "runtime", errors);
1076
+ if (!isNullableString(summary.dataSourceId)) invalidField(context, "dataSourceId", errors);
1077
+ if (typeof summary.visibility !== "string") invalidField(context, "visibility", errors);
1078
+ if (!isNullableString(summary.cronExpression)) invalidField(context, "cronExpression", errors);
1079
+ if (summary.cronInputJson !== null && !isJsonRecord(summary.cronInputJson)) {
1080
+ invalidField(context, "cronInputJson", errors);
1081
+ }
1082
+ if (!isNullableBoolean(summary.cronEnabled)) invalidField(context, "cronEnabled", errors);
1083
+ if (typeof summary.createdAt !== "string") invalidField(context, "createdAt", errors);
1084
+ if (typeof summary.updatedAt !== "string") invalidField(context, "updatedAt", errors);
1085
+ return summary;
1086
+ }
1087
+ function expectFunctionVersionResponse(value, context, errors = defaultSdkCoreErrorFactory) {
1088
+ expectFunctionVersion(value, context, errors);
1089
+ return value;
1090
+ }
1091
+ function expectFunctionSecrets(value, context, errors = defaultSdkCoreErrorFactory) {
1092
+ const result = expectObject(value, context, errors);
1093
+ if (!isStringArray(result.secrets)) invalidField(context, "secrets", errors);
1094
+ return result;
1095
+ }
1096
+ function expectPublicFunctionResult(value, context, errors = defaultSdkCoreErrorFactory) {
1097
+ const result = expectObject(value, context, errors);
1098
+ if (typeof result.success !== "boolean") invalidField(context, "success", errors);
1099
+ if (result.output !== null && !isObject(result.output)) invalidField(context, "output", errors);
1100
+ if (!isNullableString(result.error)) invalidField(context, "error", errors);
1101
+ return result;
1102
+ }
1103
+ function expectPublicFunctionAsyncResult(value, context, errors = defaultSdkCoreErrorFactory) {
1104
+ const result = expectObject(value, context, errors);
1105
+ if (typeof result.id !== "string") invalidField(context, "id", errors);
1106
+ if (typeof result.status !== "string") invalidField(context, "status", errors);
1107
+ return result;
1108
+ }
1109
+ function expectEmpty(value, context, errors = defaultSdkCoreErrorFactory) {
1110
+ if (value !== void 0) invalidResponse(`${context} must be empty`, errors);
1111
+ }
1112
+
1113
+ // src/modules/agentConnections.ts
1114
+ var MAX_CONNECTIONS = 100;
1115
+ function createAgentConnectionsModule(transport, errors = defaultSdkCoreErrorFactory) {
1116
+ const path = (id) => `/api/v1/connections/${encodePathSegment(id, "connection id", errors)}`;
1117
+ const providerPath = (id, provider) => `${path(id)}/providers/${encodePathSegment(provider, "provider", errors)}`;
1118
+ return {
1119
+ async list() {
1120
+ return expectObjectArray(
1121
+ await transport.request("/api/v1/connections", { method: "GET" }),
1122
+ "Connection response",
1123
+ errors,
1124
+ expectAgentConnection
1125
+ );
1126
+ },
1127
+ async get(id) {
1128
+ return expectAgentConnection(
1129
+ await transport.request(path(id), { method: "GET" }),
1130
+ "Connection response",
1131
+ errors
1132
+ );
1133
+ },
1134
+ async create(name) {
1135
+ return expectAgentConnection(
1136
+ await transport.request("/api/v1/connections", {
1137
+ method: "POST",
1138
+ body: { name }
1139
+ }),
1140
+ "Create connection response",
1141
+ errors
1142
+ );
1143
+ },
1144
+ async bulkCreate(inputs) {
1145
+ requireBatchSize(inputs, "connections", MAX_CONNECTIONS, errors);
1146
+ return expectObjectArray(
1147
+ await transport.request("/api/v1/connections/bulk", {
1148
+ method: "POST",
1149
+ body: { connections: inputs }
1150
+ }),
1151
+ "Bulk create connections response",
1152
+ errors,
1153
+ expectAgentConnection
1154
+ );
1155
+ },
1156
+ async delete(id) {
1157
+ expectEmpty(
1158
+ await transport.request(path(id), { method: "DELETE" }),
1159
+ "Delete connection response",
1160
+ errors
1161
+ );
1162
+ },
1163
+ async saveApiKey(id, provider, apiKey) {
1164
+ expectEmpty(
1165
+ await transport.request(`${providerPath(id, provider)}/api-key`, {
1166
+ method: "PUT",
1167
+ body: { apiKey }
1168
+ }),
1169
+ "Save connection API key response",
1170
+ errors
1171
+ );
1172
+ },
1173
+ async disconnectProvider(id, provider) {
1174
+ expectEmpty(
1175
+ await transport.request(providerPath(id, provider), { method: "DELETE" }),
1176
+ "Disconnect connection provider response",
1177
+ errors
1178
+ );
1179
+ },
1180
+ async startOAuth(id, provider) {
1181
+ return expectOAuthStartResult(
1182
+ await transport.request(`${providerPath(id, provider)}/oauth/start`, {
1183
+ method: "POST"
1184
+ }),
1185
+ "Connection OAuth start response",
1186
+ errors
1187
+ );
1188
+ },
1189
+ async exchangeOAuth(id, provider, input) {
1190
+ return expectAuthenticationResult(
1191
+ await transport.request(`${providerPath(id, provider)}/oauth/exchange`, {
1192
+ method: "POST",
1193
+ body: input
1194
+ }),
1195
+ "Connection OAuth exchange response",
1196
+ errors
1197
+ );
1198
+ },
1199
+ async startDeviceAuthorization(id, provider) {
1200
+ return expectDeviceAuthorization(
1201
+ await transport.request(`${providerPath(id, provider)}/device-authorizations`, {
1202
+ method: "POST"
1203
+ }),
1204
+ "Connection device authorization response",
1205
+ errors
1206
+ );
1207
+ },
1208
+ async pollDeviceAuthorization(id, provider, deviceAuthId) {
1209
+ return expectAuthenticationResult(
1210
+ await transport.request(
1211
+ `${providerPath(id, provider)}/device-authorizations/${encodePathSegment(
1212
+ deviceAuthId,
1213
+ "device authorization id",
1214
+ errors
1215
+ )}/poll`,
1216
+ { method: "POST" }
1217
+ ),
1218
+ "Connection device authorization poll response",
1219
+ errors
1220
+ );
1221
+ }
1222
+ };
1223
+ }
1224
+
1225
+ // src/modules/agentCredentials.ts
1226
+ function createAgentCredentialsModule(transport, errors = defaultSdkCoreErrorFactory) {
1227
+ const providerSegment = (provider) => encodePathSegment(provider, "provider", errors);
1228
+ return {
1229
+ async list() {
1230
+ return expectObjectArray(
1231
+ await transport.request("/api/v1/credentials", { method: "GET" }),
1232
+ "Credential status response",
1233
+ errors,
1234
+ expectCredentialStatus
1235
+ );
1236
+ },
1237
+ async listModels(agentId) {
1238
+ return expectObjectArray(
1239
+ await transport.request("/api/v1/models", {
1240
+ method: "GET",
1241
+ params: { agentId }
1242
+ }),
1243
+ "Agent model response",
1244
+ errors,
1245
+ expectAgentModel
1246
+ );
1247
+ },
1248
+ async saveApiKey(provider, apiKey) {
1249
+ expectEmpty(
1250
+ await transport.request(
1251
+ `/api/v1/credentials/${providerSegment(provider)}/api-key`,
1252
+ { method: "PUT", body: { apiKey } }
1253
+ ),
1254
+ "Save API key response",
1255
+ errors
1256
+ );
1257
+ },
1258
+ async remove(provider) {
1259
+ expectEmpty(
1260
+ await transport.request(`/api/v1/credentials/${providerSegment(provider)}`, {
1261
+ method: "DELETE"
1262
+ }),
1263
+ "Remove credential response",
1264
+ errors
1265
+ );
1266
+ },
1267
+ async startOAuth(provider) {
1268
+ return expectOAuthStartResult(
1269
+ await transport.request("/api/v1/oauth/start", {
1270
+ method: "POST",
1271
+ body: { provider }
1272
+ }),
1273
+ "OAuth start response",
1274
+ errors
1275
+ );
1276
+ },
1277
+ async exchangeOAuth(provider, input) {
1278
+ return expectAuthenticationResult(
1279
+ await transport.request("/api/v1/oauth/exchange", {
1280
+ method: "POST",
1281
+ body: { provider, ...input }
1282
+ }),
1283
+ "OAuth exchange response",
1284
+ errors
1285
+ );
1286
+ },
1287
+ async startDeviceAuthorization(provider) {
1288
+ return expectDeviceAuthorization(
1289
+ await transport.request(
1290
+ `/api/v1/credentials/${providerSegment(provider)}/device-authorizations`,
1291
+ { method: "POST" }
1292
+ ),
1293
+ "Device authorization response",
1294
+ errors
1295
+ );
1296
+ },
1297
+ async pollDeviceAuthorization(provider, deviceAuthId) {
1298
+ return expectAuthenticationResult(
1299
+ await transport.request(
1300
+ `/api/v1/credentials/${providerSegment(provider)}/device-authorizations/${encodePathSegment(
1301
+ deviceAuthId,
1302
+ "device authorization id",
1303
+ errors
1304
+ )}/poll`,
1305
+ { method: "POST" }
1306
+ ),
1307
+ "Device authorization poll response",
1308
+ errors
1309
+ );
1310
+ }
1311
+ };
1312
+ }
1313
+
1314
+ // src/modules/agents.ts
1315
+ var MAX_AGENTS = 100;
1316
+ function createAgentsModule(functionsTransport, copilotTransport, errors = defaultSdkCoreErrorFactory) {
1317
+ const path = (id) => `/api/v1/agents/${encodePathSegment(id, "agent id", errors)}`;
1318
+ return {
1319
+ async list(options = {}) {
1320
+ const params = {
1321
+ page: options.page,
1322
+ size: options.size,
1323
+ sort: options.sort
1324
+ };
1325
+ return expectPage(
1326
+ await functionsTransport.request("/api/v1/agents", { method: "GET", params }),
1327
+ "Agent page response",
1328
+ errors,
1329
+ expectAgentDefinition
1330
+ );
1331
+ },
1332
+ async get(id) {
1333
+ return expectAgentDefinition(
1334
+ await functionsTransport.request(path(id), { method: "GET" }),
1335
+ "Agent response",
1336
+ errors
1337
+ );
1338
+ },
1339
+ async create(input) {
1340
+ return expectAgentDefinition(
1341
+ await functionsTransport.request("/api/v1/agents", {
1342
+ method: "POST",
1343
+ body: input
1344
+ }),
1345
+ "Create agent response",
1346
+ errors
1347
+ );
1348
+ },
1349
+ async update(id, input) {
1350
+ return expectAgentDefinition(
1351
+ await functionsTransport.request(path(id), { method: "PUT", body: input }),
1352
+ "Update agent response",
1353
+ errors
1354
+ );
1355
+ },
1356
+ async delete(id) {
1357
+ expectEmpty(
1358
+ await functionsTransport.request(path(id), { method: "DELETE" }),
1359
+ "Delete agent response",
1360
+ errors
1361
+ );
1362
+ },
1363
+ async bulkCreate(inputs) {
1364
+ requireBatchSize(inputs, "agents", MAX_AGENTS, errors);
1365
+ return expectObjectArray(
1366
+ await functionsTransport.request("/api/v1/agents/bulk", {
1367
+ method: "POST",
1368
+ body: { agents: inputs }
1369
+ }),
1370
+ "Bulk create agents response",
1371
+ errors,
1372
+ expectAgentDefinition
1373
+ );
1374
+ },
1375
+ async bulkUpdate(items) {
1376
+ requireBatchSize(items, "agents", MAX_AGENTS, errors);
1377
+ return expectObjectArray(
1378
+ await functionsTransport.request("/api/v1/agents/bulk", {
1379
+ method: "PUT",
1380
+ body: { agents: items }
1381
+ }),
1382
+ "Bulk update agents response",
1383
+ errors,
1384
+ expectAgentDefinition
1385
+ );
1386
+ },
1387
+ async bulkDelete(ids) {
1388
+ requireBatchSize(ids, "ids", MAX_AGENTS, errors);
1389
+ return expectAgentBulkDeleteResult(
1390
+ await functionsTransport.request("/api/v1/agents/bulk-delete", {
1391
+ method: "POST",
1392
+ body: { ids }
1393
+ }),
1394
+ "Bulk delete agents response",
1395
+ errors
1396
+ );
1397
+ },
1398
+ async listModels(agentId) {
1399
+ return expectObjectArray(
1400
+ await copilotTransport.request("/api/v1/models", {
1401
+ method: "GET",
1402
+ params: { agentId }
1403
+ }),
1404
+ "Agent model response",
1405
+ errors,
1406
+ expectAgentModel
1407
+ );
1408
+ }
1409
+ };
1410
+ }
1411
+
1412
+ // src/modules/agentTasks.ts
1413
+ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory) {
1414
+ const path = (id) => `/api/v1/tasks/${encodePathSegment(id, "task id", errors)}`;
1415
+ return {
1416
+ async list(options = {}) {
1417
+ const params = {
1418
+ page: options.page,
1419
+ size: options.size,
1420
+ sort: options.sort,
1421
+ archived: options.archived,
1422
+ agentId: options.agentId,
1423
+ search: options.search,
1424
+ userId: options.userId
1425
+ };
1426
+ return expectPage(
1427
+ await transport.request("/api/v1/tasks", { method: "GET", params }),
1428
+ "Agent task page response",
1429
+ errors,
1430
+ expectAgentTask
1431
+ );
1432
+ },
1433
+ async get(id) {
1434
+ return expectAgentTask(
1435
+ await transport.request(path(id), { method: "GET" }),
1436
+ "Agent task response",
1437
+ errors
1438
+ );
1439
+ },
1440
+ async create(input) {
1441
+ return expectAgentTask(
1442
+ await transport.request("/api/v1/tasks", { method: "POST", body: input }),
1443
+ "Create agent task response",
1444
+ errors
1445
+ );
1446
+ },
1447
+ async rename(id, title) {
1448
+ return expectAgentTask(
1449
+ await transport.request(path(id), { method: "PATCH", body: { title } }),
1450
+ "Rename agent task response",
1451
+ errors
1452
+ );
1453
+ },
1454
+ async archive(id) {
1455
+ expectEmpty(
1456
+ await transport.request(`${path(id)}/archive`, { method: "PATCH" }),
1457
+ "Archive agent task response",
1458
+ errors
1459
+ );
1460
+ },
1461
+ async sendInput(id, input) {
1462
+ expectEmpty(
1463
+ await transport.request(`${path(id)}/inputs`, { method: "POST", body: input }),
1464
+ "Agent task input response",
1465
+ errors
1466
+ );
1467
+ },
1468
+ async listMessages(id, options = {}) {
1469
+ return expectPage(
1470
+ await transport.request(`${path(id)}/messages`, {
1471
+ method: "GET",
1472
+ params: { page: options.page, size: options.size, sort: options.sort }
1473
+ }),
1474
+ "Agent message page response",
1475
+ errors,
1476
+ expectAgentMessage
1477
+ );
1478
+ }
1479
+ };
1480
+ }
1481
+
1482
+ // src/modules/apps.ts
1483
+ function createAppsModule(transport, errors = defaultSdkCoreErrorFactory) {
1484
+ const appPath = (appId) => `/api/v1/apps/${encodePathSegment(appId, "app id", errors)}`;
1485
+ const params = (options = {}, defaultSort) => ({
1486
+ page: options.page,
1487
+ size: options.size,
1488
+ sort: options.sort ?? defaultSort
1489
+ });
1490
+ return {
1491
+ async list(options = {}) {
1492
+ return expectPage(
1493
+ await transport.request("/api/v1/apps", {
1494
+ method: "GET",
1495
+ params: {
1496
+ ...params(options, "createdAt,desc"),
1497
+ search: options.search,
1498
+ version: options.version,
1499
+ brand: options.brand
1500
+ }
1501
+ }),
1502
+ "App page response",
1503
+ errors,
1504
+ expectAppSummary
1505
+ );
1506
+ },
1507
+ async get(appId, options = {}) {
1508
+ return expectAppDefinition(
1509
+ await transport.request(appPath(appId), {
1510
+ method: "GET",
1511
+ params: { version: options.version }
1512
+ }),
1513
+ "App response",
1514
+ errors
1515
+ );
1516
+ },
1517
+ async create(input) {
1518
+ return expectAppDefinition(
1519
+ await transport.request("/api/v1/apps", { method: "POST", body: input }),
1520
+ "Create app response",
1521
+ errors
1522
+ );
1523
+ },
1524
+ async delete(appId) {
1525
+ expectEmpty(
1526
+ await transport.request(appPath(appId), { method: "DELETE" }),
1527
+ "Delete app response",
1528
+ errors
1529
+ );
1530
+ },
1531
+ async update(appId, input) {
1532
+ return expectAppDefinition(
1533
+ await transport.request(appPath(appId), { method: "PATCH", body: input }),
1534
+ "Update app response",
1535
+ errors
1536
+ );
1537
+ },
1538
+ async getFiles(appId) {
1539
+ return expectFiles(
1540
+ await transport.request(`${appPath(appId)}/files`, { method: "GET" }),
1541
+ errors
1542
+ );
1543
+ },
1544
+ async replaceFiles(appId, files) {
1545
+ return expectFiles(
1546
+ await transport.request(`${appPath(appId)}/files`, {
1547
+ method: "PUT",
1548
+ body: { files }
1549
+ }),
1550
+ errors
1551
+ );
1552
+ },
1553
+ async mergeFiles(appId, files) {
1554
+ return expectFiles(
1555
+ await transport.request(`${appPath(appId)}/files`, {
1556
+ method: "PATCH",
1557
+ body: { files }
1558
+ }),
1559
+ errors
1560
+ );
1561
+ },
1562
+ async build(appId) {
1563
+ return expectAppDeploy(
1564
+ await transport.request(`${appPath(appId)}/build`, { method: "POST" }),
1565
+ "Build app deploy response",
1566
+ errors
1567
+ );
1568
+ },
1569
+ async publish(appId, options = {}) {
1570
+ return expectAppDefinition(
1571
+ await transport.request(`${appPath(appId)}/publish`, {
1572
+ method: "POST",
1573
+ body: options.externalAccess === void 0 ? void 0 : options
1574
+ }),
1575
+ "Publish app response",
1576
+ errors
1577
+ );
1578
+ },
1579
+ async getDeploy(appId, deployId) {
1580
+ return expectAppDeploy(
1581
+ await transport.request(
1582
+ `${appPath(appId)}/deploys/${encodePathSegment(deployId, "deploy id", errors)}`,
1583
+ { method: "GET" }
1584
+ ),
1585
+ "App deploy response",
1586
+ errors
1587
+ );
1588
+ },
1589
+ async getCurrentDeploy(appId) {
1590
+ const response = await transport.request(`${appPath(appId)}/deploys/current`, {
1591
+ method: "GET"
1592
+ });
1593
+ return response === null || response === void 0 ? null : expectAppDeploy(response, "Current app deploy response", errors);
1594
+ },
1595
+ async cancelBuild(appId, deployId) {
1596
+ return expectAppDeploy(
1597
+ await transport.request(
1598
+ `${appPath(appId)}/deploys/${encodePathSegment(deployId, "deploy id", errors)}/cancel`,
1599
+ { method: "POST" }
1600
+ ),
1601
+ "Cancel app build response",
1602
+ errors
1603
+ );
1604
+ },
1605
+ async rollback(appId, targetVersionId) {
1606
+ return expectAppDefinition(
1607
+ await transport.request(`${appPath(appId)}/rollback`, {
1608
+ method: "POST",
1609
+ body: { targetVersionId }
1610
+ }),
1611
+ "Rollback app response",
1612
+ errors
1613
+ );
1614
+ },
1615
+ async listDeploys(appId, options = {}) {
1616
+ return expectPage(
1617
+ await transport.request(`${appPath(appId)}/deploys`, {
1618
+ method: "GET",
1619
+ params: params(options, "createdAt,desc")
1620
+ }),
1621
+ "App deploy page response",
1622
+ errors,
1623
+ expectAppDeploy
1624
+ );
1625
+ },
1626
+ async listVersions(appId, options = {}) {
1627
+ return expectPage(
1628
+ await transport.request(`${appPath(appId)}/versions`, {
1629
+ method: "GET",
1630
+ params: params(options, "createdAt,desc")
1631
+ }),
1632
+ "App version page response",
1633
+ errors,
1634
+ expectAppVersion
1635
+ );
1636
+ }
1637
+ };
1638
+ }
1639
+ function expectFiles(value, errors) {
1640
+ const response = expectObject(value, "App files response", errors);
1641
+ if (response.files === null || typeof response.files !== "object" || Array.isArray(response.files) || Object.values(response.files).some((content) => typeof content !== "string")) {
1642
+ throw errors.invalidResponse("App files response has an invalid files field");
1643
+ }
1644
+ return response;
1645
+ }
1646
+
1647
+ // src/modules/auth.ts
1648
+ function createAuthModule(transport, errors = defaultSdkCoreErrorFactory) {
1649
+ return {
1650
+ async me() {
1651
+ return expectUser(
1652
+ await transport.request("/api/v1/auth/me", { method: "GET" }),
1653
+ "Current user response",
1654
+ errors
1655
+ );
1656
+ },
1657
+ async listUserPlans() {
1658
+ return expectObjectArray(
1659
+ await transport.request("/api/v1/user-plans", { method: "GET" }),
1660
+ "User plan response",
1661
+ errors,
1662
+ expectUserPlan
1663
+ );
1664
+ }
1665
+ };
1666
+ }
1667
+
1668
+ // src/modules/context.ts
1669
+ var SUMMARY_PAGE_SIZE = 2e3;
1670
+ function createContextModule(dependencies, errors = defaultSdkCoreErrorFactory) {
1671
+ return {
1672
+ async getAppContext() {
1673
+ const appId = dependencies.getAppId?.();
1674
+ if (!appId) {
1675
+ configurationError("An appId is required for app context", errors);
1676
+ }
1677
+ const app = await dependencies.apps.get(appId);
1678
+ const tables = await dependencies.schema.listTables({ scope: "APP", includeColumns: true });
1679
+ const functionsPage = await dependencies.functionsAdmin.list({
1680
+ page: 0,
1681
+ size: SUMMARY_PAGE_SIZE,
1682
+ sort: "name"
1683
+ });
1684
+ const agentsPage = await dependencies.agents.list({
1685
+ page: 0,
1686
+ size: SUMMARY_PAGE_SIZE,
1687
+ sort: "name"
1688
+ });
1689
+ const fileResponse = await dependencies.apps.getFiles(appId);
1690
+ const integrationsPage = await dependencies.integrationAdmin.list({
1691
+ page: 0,
1692
+ size: SUMMARY_PAGE_SIZE,
1693
+ sort: "alias"
1694
+ });
1695
+ const connections = await dependencies.agentConnections.list();
1696
+ return {
1697
+ appId,
1698
+ app,
1699
+ tables,
1700
+ functions: functionsPage.content,
1701
+ functionsTotal: functionsPage.page.totalElements,
1702
+ functionsTruncated: functionsPage.content.length < functionsPage.page.totalElements,
1703
+ agents: agentsPage.content,
1704
+ agentsTotal: agentsPage.page.totalElements,
1705
+ agentsTruncated: agentsPage.content.length < agentsPage.page.totalElements,
1706
+ files: Object.keys(fileResponse.files).sort(),
1707
+ integrations: integrationsPage.content,
1708
+ integrationsTotal: integrationsPage.totalElements,
1709
+ integrationsTruncated: integrationsPage.content.length < integrationsPage.totalElements,
1710
+ connections
1711
+ };
1712
+ }
1713
+ };
1714
+ }
1715
+
1716
+ // src/modules/customQueries.ts
1717
+ function createCustomQueriesModule(transport, errors = defaultSdkCoreErrorFactory) {
1718
+ const path = (id) => `/api/v1/custom-queries/${encodePathSegment(id, "query id", errors)}`;
1719
+ return {
1720
+ async list(options = {}) {
1721
+ const params = {
1722
+ page: options.page,
1723
+ size: options.size ?? 20,
1724
+ sort: options.sort ?? "name"
1725
+ };
1726
+ return expectPage(
1727
+ await transport.request("/api/v1/custom-queries", { method: "GET", params }),
1728
+ "Custom query page response",
1729
+ errors,
1730
+ expectCustomQuerySummary
1731
+ );
1732
+ },
1733
+ async get(id) {
1734
+ return expectCustomQueryDefinition(
1735
+ await transport.request(path(id), { method: "GET" }),
1736
+ "Custom query response",
1737
+ errors
1738
+ );
1739
+ },
1740
+ async create(input) {
1741
+ return expectCustomQueryDefinition(
1742
+ await transport.request("/api/v1/custom-queries", { method: "POST", body: input }),
1743
+ "Create custom query response",
1744
+ errors
1745
+ );
1746
+ },
1747
+ async update(id, input) {
1748
+ return expectCustomQueryDefinition(
1749
+ await transport.request(path(id), { method: "PUT", body: input }),
1750
+ "Update custom query response",
1751
+ errors
1752
+ );
1753
+ },
1754
+ async delete(id) {
1755
+ expectEmpty(
1756
+ await transport.request(path(id), { method: "DELETE" }),
1757
+ "Delete custom query response",
1758
+ errors
1759
+ );
1760
+ },
1761
+ async execute(id, parameters = {}) {
1762
+ return expectQueryResult(
1763
+ await transport.request(`${path(id)}/execute`, {
1764
+ method: "POST",
1765
+ body: { parameters }
1766
+ }),
1767
+ "Custom query execution response",
1768
+ errors
1769
+ );
1770
+ }
1771
+ };
1772
+ }
1773
+
1774
+ // src/modules/dataSources.ts
1775
+ var MAX_DATA_SOURCES = 100;
1776
+ function bulkFailure(index, dataSourceId, error) {
1777
+ const errorCode2 = typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : null;
1778
+ return {
1779
+ index,
1780
+ success: false,
1781
+ dataSourceId,
1782
+ errorCode: errorCode2,
1783
+ message: error instanceof Error ? error.message : "Data Source operation failed"
1784
+ };
1785
+ }
1786
+ function bulkResult(results) {
1787
+ const succeededCount = results.filter(({ success }) => success).length;
1788
+ return {
1789
+ results,
1790
+ processedCount: results.length,
1791
+ succeededCount,
1792
+ failedCount: results.length - succeededCount
1793
+ };
1794
+ }
1795
+ function createDataSourcesModule(transport, errors = defaultSdkCoreErrorFactory) {
1796
+ const path = (id) => `/api/v1/data-sources/${encodePathSegment(id, "data source id", errors)}`;
1797
+ const createOne = async (input) => expectDataSourceDefinition(
1798
+ await transport.request("/api/v1/data-sources", { method: "POST", body: input }),
1799
+ "Create Data Source response",
1800
+ errors
1801
+ );
1802
+ const updateOne = async (id, input) => expectDataSourceDefinition(
1803
+ await transport.request(path(id), { method: "PUT", body: input }),
1804
+ "Update Data Source response",
1805
+ errors
1806
+ );
1807
+ const deleteOne = async (id) => {
1808
+ expectEmpty(
1809
+ await transport.request(path(id), { method: "DELETE" }),
1810
+ "Delete Data Source response",
1811
+ errors
1812
+ );
1813
+ };
1814
+ return {
1815
+ async list(options = {}) {
1816
+ const params = {
1817
+ page: options.page,
1818
+ size: options.size,
1819
+ sort: options.sort
1820
+ };
1821
+ return expectPage(
1822
+ await transport.request("/api/v1/data-sources", { method: "GET", params }),
1823
+ "Data Source page response",
1824
+ errors,
1825
+ expectDataSourceDefinition
1826
+ );
1827
+ },
1828
+ async get(id) {
1829
+ return expectDataSourceDefinition(
1830
+ await transport.request(path(id), { method: "GET" }),
1831
+ "Data Source response",
1832
+ errors
1833
+ );
1834
+ },
1835
+ async create(input) {
1836
+ return createOne(input);
1837
+ },
1838
+ async update(id, input) {
1839
+ return updateOne(id, input);
1840
+ },
1841
+ async delete(id) {
1842
+ return deleteOne(id);
1843
+ },
1844
+ async bulkCreate(dataSources) {
1845
+ requireBatchSize(dataSources, "dataSources", MAX_DATA_SOURCES, errors);
1846
+ const results = [];
1847
+ for (const [index, input] of dataSources.entries()) {
1848
+ try {
1849
+ const created = await createOne(input);
1850
+ results.push({
1851
+ index,
1852
+ success: true,
1853
+ dataSourceId: created.id,
1854
+ errorCode: null,
1855
+ message: null
1856
+ });
1857
+ } catch (error) {
1858
+ results.push(bulkFailure(index, null, error));
1859
+ }
1860
+ }
1861
+ return bulkResult(results);
1862
+ },
1863
+ async bulkUpdate(dataSources) {
1864
+ requireBatchSize(dataSources, "dataSources", MAX_DATA_SOURCES, errors);
1865
+ const paths = dataSources.map(({ dataSourceId }) => path(dataSourceId));
1866
+ const results = [];
1867
+ for (const [index, { dataSourceId, ...input }] of dataSources.entries()) {
1868
+ try {
1869
+ const updated = expectDataSourceDefinition(
1870
+ await transport.request(paths[index], { method: "PUT", body: input }),
1871
+ "Update Data Source response",
1872
+ errors
1873
+ );
1874
+ results.push({
1875
+ index,
1876
+ success: true,
1877
+ dataSourceId: updated.id,
1878
+ errorCode: null,
1879
+ message: null
1880
+ });
1881
+ } catch (error) {
1882
+ results.push(bulkFailure(index, dataSourceId, error));
1883
+ }
1884
+ }
1885
+ return bulkResult(results);
1886
+ },
1887
+ async bulkDelete(dataSourceIds) {
1888
+ requireBatchSize(dataSourceIds, "dataSourceIds", MAX_DATA_SOURCES, errors);
1889
+ const paths = dataSourceIds.map((id) => path(id));
1890
+ const results = [];
1891
+ for (const [index, dataSourceId] of dataSourceIds.entries()) {
1892
+ try {
1893
+ expectEmpty(
1894
+ await transport.request(paths[index], { method: "DELETE" }),
1895
+ "Delete Data Source response",
1896
+ errors
1897
+ );
1898
+ results.push({ index, success: true, dataSourceId, errorCode: null, message: null });
1899
+ } catch (error) {
1900
+ results.push(bulkFailure(index, dataSourceId, error));
1901
+ }
1902
+ }
1903
+ return bulkResult(results);
1904
+ }
1905
+ };
1906
+ }
1907
+
1908
+ // src/modules/entities.ts
1909
+ var DefaultEntitiesModule = class {
1910
+ constructor(transport, errors) {
1911
+ this.transport = transport;
1912
+ this.errors = errors;
1913
+ }
1914
+ tables = /* @__PURE__ */ new Map();
1915
+ getTable(tableName) {
1916
+ if (!this.tables.has(tableName)) {
1917
+ this.tables.set(tableName, this.createTable(tableName));
1918
+ }
1919
+ return this.tables.get(tableName);
1920
+ }
1921
+ createTable(tableName) {
1922
+ const basePath = `/api/v1/tables/${encodePathSegment(tableName, "tableName", this.errors)}/records`;
1923
+ return {
1924
+ list: async (sortOrOptions, limit, skip, fields) => {
1925
+ const options = typeof sortOrOptions === "object" ? sortOrOptions : void 0;
1926
+ const params = {
1927
+ sort: options?.sort ?? (typeof sortOrOptions === "string" ? sortOrOptions : void 0),
1928
+ limit: options?.limit ?? limit,
1929
+ skip: options?.skip ?? skip,
1930
+ fields: (options?.fields ?? fields)?.join(",")
1931
+ };
1932
+ return expectEntityListResponse(
1933
+ await this.transport.request(basePath, { method: "GET", params }),
1934
+ "Entity list response",
1935
+ this.errors
1936
+ );
1937
+ },
1938
+ filter: async (query, sort, limit, skip, fields) => {
1939
+ return expectEntityListResponse(
1940
+ await this.transport.request(basePath, {
1941
+ method: "GET",
1942
+ params: {
1943
+ q: JSON.stringify(query),
1944
+ sort,
1945
+ limit,
1946
+ skip,
1947
+ fields: fields?.join(",")
1948
+ }
1949
+ }),
1950
+ "Entity list response",
1951
+ this.errors
1952
+ );
1953
+ },
1954
+ get: async (id) => expectObject(
1955
+ await this.transport.request(
1956
+ `${basePath}/${encodePathSegment(id, "id", this.errors)}`,
1957
+ { method: "GET" }
1958
+ ),
1959
+ "Entity response",
1960
+ this.errors
1961
+ ),
1962
+ create: async (data) => expectObject(
1963
+ await this.transport.request(basePath, { method: "POST", body: data }),
1964
+ "Created entity response",
1965
+ this.errors
1966
+ ),
1967
+ bulkCreate: async (data) => expectObjectArray(
1968
+ await this.transport.request(`${basePath}/bulk`, {
1969
+ method: "POST",
1970
+ body: data
1971
+ }),
1972
+ "Bulk create response",
1973
+ this.errors
1974
+ ),
1975
+ update: async (id, data) => expectObject(
1976
+ await this.transport.request(
1977
+ `${basePath}/${encodePathSegment(id, "id", this.errors)}`,
1978
+ { method: "PUT", body: data }
1979
+ ),
1980
+ "Updated entity response",
1981
+ this.errors
1982
+ ),
1983
+ delete: (id) => this.transport.request(`${basePath}/${encodePathSegment(id, "id", this.errors)}`, {
1984
+ method: "DELETE"
1985
+ }).then((response) => expectEmpty(response, "Delete entity response", this.errors)),
1986
+ deleteMany: async (query) => {
1987
+ if (Object.keys(query).length === 0) {
1988
+ configurationError("query must not be empty for deleteMany", this.errors);
1989
+ }
1990
+ const response = expectObject(
1991
+ await this.transport.request(basePath, {
1992
+ method: "DELETE",
1993
+ params: { q: JSON.stringify(query) }
1994
+ }),
1995
+ "Delete many response",
1996
+ this.errors
1997
+ );
1998
+ if (!Number.isInteger(response.deleted)) {
1999
+ return invalidResponse(
2000
+ "Delete many response must include an integer deleted count",
2001
+ this.errors
2002
+ );
2003
+ }
2004
+ return { deleted: response.deleted };
2005
+ }
2006
+ };
2007
+ }
2008
+ };
2009
+ function expectEntityListResponse(value, context, errors) {
2010
+ const response = expectObject(value, context, errors);
2011
+ expectObjectArray(response.data, `${context} data`, errors);
2012
+ if (!Number.isInteger(response.limit))
2013
+ invalidResponse(`${context} has an invalid limit field`, errors);
2014
+ if (!Number.isInteger(response.skip))
2015
+ invalidResponse(`${context} has an invalid skip field`, errors);
2016
+ if (!Number.isInteger(response.total))
2017
+ invalidResponse(`${context} has an invalid total field`, errors);
2018
+ if (typeof response.hasMore !== "boolean") {
2019
+ invalidResponse(`${context} has an invalid hasMore field`, errors);
2020
+ }
2021
+ return response;
2022
+ }
2023
+ function createEntitiesModule(transport, errors = defaultSdkCoreErrorFactory) {
2024
+ const instance = new DefaultEntitiesModule(transport, errors);
2025
+ return new Proxy(instance, {
2026
+ get(target, property, receiver) {
2027
+ if (typeof property !== "string" || property in target) {
2028
+ return Reflect.get(target, property, receiver);
2029
+ }
2030
+ return target.getTable(property);
2031
+ }
2032
+ });
2033
+ }
2034
+
2035
+ // src/modules/functions.ts
2036
+ var DefaultFunctionsModule = class {
2037
+ constructor(transport, errors, options) {
2038
+ this.transport = transport;
2039
+ this.errors = errors;
2040
+ this.options = options;
2041
+ }
2042
+ execute(id, input) {
2043
+ return this.executeWithType(id, this.options.executeInvocationType, input);
2044
+ }
2045
+ executeAsync(id, input) {
2046
+ return this.executeWithType(id, "async", input);
2047
+ }
2048
+ getExecution(id) {
2049
+ return this.transport.request(
2050
+ `/api/v1/executions/${encodePathSegment(id, "execution id", this.errors)}`,
2051
+ { method: "GET" }
2052
+ ).then(
2053
+ (response) => expectFunctionExecution(response, "Function execution response", this.errors)
2054
+ );
2055
+ }
2056
+ cancelExecution(id) {
2057
+ return this.transport.request(
2058
+ `/api/v1/executions/${encodePathSegment(id, "execution id", this.errors)}/cancel`,
2059
+ { method: "POST" }
2060
+ ).then((response) => expectEmpty(response, "Cancel execution response", this.errors));
2061
+ }
2062
+ executeWithType(id, invocationType, input) {
2063
+ const request = {
2064
+ method: "POST",
2065
+ ...input !== void 0 || this.options.emptyInput !== "omit-body" ? { body: { input: input ?? {} } } : {},
2066
+ ...invocationType === void 0 ? {} : { headers: { "X-Invocation-Type": invocationType } }
2067
+ };
2068
+ return this.transport.request(
2069
+ `/api/v1/functions/${encodePathSegment(id, "function id", this.errors)}/execute`,
2070
+ request
2071
+ ).then(
2072
+ (response) => expectFunctionExecution(response, "Function execution response", this.errors)
2073
+ );
2074
+ }
2075
+ };
2076
+ function createFunctionsModule(transport, options = {}, errors = defaultSdkCoreErrorFactory) {
2077
+ return new DefaultFunctionsModule(transport, errors, options);
2078
+ }
2079
+
2080
+ // src/modules/functionsAdmin.ts
2081
+ var MAX_FUNCTIONS = 100;
2082
+ var COMPOSED_SCHEDULE_FIELDS = ["cronExpression", "cronInputJson", "cronEnabled"];
2083
+ function rejectBulkScheduleFields(value, operation, errors) {
2084
+ if (typeof value !== "object" || value === null) return;
2085
+ const field = COMPOSED_SCHEDULE_FIELDS.find((candidate) => Object.hasOwn(value, candidate));
2086
+ if (field) {
2087
+ configurationError(
2088
+ `functionsAdmin.${operation} does not support ${field}; composed scheduling is supported only by single-Function create and patch`,
2089
+ errors
2090
+ );
2091
+ }
2092
+ }
2093
+ function bulkPatchUpdate(value) {
2094
+ return typeof value === "object" && value !== null && Object.hasOwn(value, "update") ? value.update : void 0;
2095
+ }
2096
+ function createFunctionsAdminModule(transport, errors = defaultSdkCoreErrorFactory) {
2097
+ const functionPath = (id) => `/api/v1/functions/${encodePathSegment(id, "function id", errors)}`;
2098
+ const pageParams = (options = {}) => ({
2099
+ page: options.page,
2100
+ size: options.size,
2101
+ sort: options.sort
2102
+ });
2103
+ return {
2104
+ async list(options = {}) {
2105
+ return expectPage(
2106
+ await transport.request("/api/v1/functions", {
2107
+ method: "GET",
2108
+ params: { ...pageParams(options), search: options.search }
2109
+ }),
2110
+ "Function page response",
2111
+ errors,
2112
+ expectFunctionSummary
2113
+ );
2114
+ },
2115
+ async get(id) {
2116
+ return expectFunctionDefinition(
2117
+ await transport.request(functionPath(id), { method: "GET" }),
2118
+ "Function response",
2119
+ errors
2120
+ );
2121
+ },
2122
+ async create(input) {
2123
+ return expectFunctionDefinition(
2124
+ await transport.request("/api/v1/functions", { method: "POST", body: input }),
2125
+ "Create Function response",
2126
+ errors
2127
+ );
2128
+ },
2129
+ async patch(id, input) {
2130
+ return expectFunctionDefinition(
2131
+ await transport.request(functionPath(id), { method: "PATCH", body: input }),
2132
+ "Patch Function response",
2133
+ errors
2134
+ );
2135
+ },
2136
+ async delete(id) {
2137
+ expectEmpty(
2138
+ await transport.request(functionPath(id), { method: "DELETE" }),
2139
+ "Delete Function response",
2140
+ errors
2141
+ );
2142
+ },
2143
+ async bulkCreate(functions) {
2144
+ requireBatchSize(functions, "functions", MAX_FUNCTIONS, errors);
2145
+ functions.forEach((input) => rejectBulkScheduleFields(input, "bulkCreate", errors));
2146
+ return expectFunctionDefinitions(
2147
+ await transport.request("/api/v1/functions/bulk", {
2148
+ method: "POST",
2149
+ body: { functions }
2150
+ }),
2151
+ "Function bulk create response",
2152
+ errors
2153
+ );
2154
+ },
2155
+ async bulkUpdate(functions) {
2156
+ requireBatchSize(functions, "functions", MAX_FUNCTIONS, errors);
2157
+ return expectFunctionDefinitions(
2158
+ await transport.request("/api/v1/functions/bulk", {
2159
+ method: "PUT",
2160
+ body: { functions }
2161
+ }),
2162
+ "Function bulk update response",
2163
+ errors
2164
+ );
2165
+ },
2166
+ async bulkPatch(functions) {
2167
+ requireBatchSize(functions, "functions", MAX_FUNCTIONS, errors);
2168
+ functions.forEach(
2169
+ (item) => rejectBulkScheduleFields(bulkPatchUpdate(item), "bulkPatch", errors)
2170
+ );
2171
+ return expectFunctionDefinitions(
2172
+ await transport.request("/api/v1/functions/bulk", {
2173
+ method: "PATCH",
2174
+ body: { functions }
2175
+ }),
2176
+ "Function bulk patch response",
2177
+ errors
2178
+ );
2179
+ },
2180
+ // POST, not DELETE: the selector travels in a body, and some proxies drop a DELETE body.
2181
+ async bulkDelete(selector) {
2182
+ const body = selectorBody(selector, errors);
2183
+ return expectFunctionBulkDeleteResult(
2184
+ await transport.request("/api/v1/functions/bulk-delete", {
2185
+ method: "POST",
2186
+ body
2187
+ }),
2188
+ "Function bulk delete response",
2189
+ errors
2190
+ );
2191
+ },
2192
+ async publish(id) {
2193
+ return expectFunctionDefinition(
2194
+ await transport.request(`${functionPath(id)}/publish`, { method: "POST" }),
2195
+ "Publish Function response",
2196
+ errors
2197
+ );
2198
+ },
2199
+ async rollback(id, versionId) {
2200
+ return expectFunctionDefinition(
2201
+ await transport.request(`${functionPath(id)}/rollback`, {
2202
+ method: "POST",
2203
+ body: { targetVersionId: versionId }
2204
+ }),
2205
+ "Rollback Function response",
2206
+ errors
2207
+ );
2208
+ },
2209
+ async listVersions(id, options = {}) {
2210
+ return expectPage(
2211
+ await transport.request(`${functionPath(id)}/versions`, {
2212
+ method: "GET",
2213
+ params: pageParams(options)
2214
+ }),
2215
+ "Function version page response",
2216
+ errors,
2217
+ expectFunctionVersionResponse
2218
+ );
2219
+ },
2220
+ async setVisibility(id, visibility) {
2221
+ return expectFunctionDefinition(
2222
+ await transport.request(`${functionPath(id)}/visibility`, {
2223
+ method: "PATCH",
2224
+ body: { visibility }
2225
+ }),
2226
+ "Function visibility response",
2227
+ errors
2228
+ );
2229
+ },
2230
+ async listExecutions(id, options = {}) {
2231
+ return expectPage(
2232
+ await transport.request(`${functionPath(id)}/executions`, {
2233
+ method: "GET",
2234
+ params: pageParams(options)
2235
+ }),
2236
+ "Function execution page response",
2237
+ errors,
2238
+ expectFunctionExecution
2239
+ );
2240
+ },
2241
+ async getExecution(functionId, executionId) {
2242
+ return expectFunctionExecution(
2243
+ await transport.request(
2244
+ `${functionPath(functionId)}/executions/${encodePathSegment(
2245
+ executionId,
2246
+ "execution id",
2247
+ errors
2248
+ )}`,
2249
+ { method: "GET" }
2250
+ ),
2251
+ "Function execution response",
2252
+ errors
2253
+ );
2254
+ },
2255
+ async listSecrets(id) {
2256
+ return expectFunctionSecrets(
2257
+ await transport.request(`${functionPath(id)}/secrets`, { method: "GET" }),
2258
+ "Function secrets response",
2259
+ errors
2260
+ );
2261
+ },
2262
+ async createSecret(id, name, value) {
2263
+ expectEmpty(
2264
+ await transport.request(`${functionPath(id)}/secrets`, {
2265
+ method: "POST",
2266
+ body: { name, value }
2267
+ }),
2268
+ "Create Function secret response",
2269
+ errors
2270
+ );
2271
+ },
2272
+ async deleteSecret(id, name) {
2273
+ expectEmpty(
2274
+ await transport.request(
2275
+ `${functionPath(id)}/secrets/${encodePathSegment(name, "secret name", errors)}`,
2276
+ { method: "DELETE" }
2277
+ ),
2278
+ "Delete Function secret response",
2279
+ errors
2280
+ );
2281
+ }
2282
+ };
2283
+ }
2284
+ function selectorBody(selector, errors) {
2285
+ const hasIds = selector.ids !== void 0;
2286
+ if (hasIds === (selector.allInApp === true)) {
2287
+ configurationError("Provide either ids or allInApp, not both", errors);
2288
+ }
2289
+ if (selector.ids !== void 0) {
2290
+ requireBatchSize(selector.ids, "ids", MAX_FUNCTIONS, errors);
2291
+ return { ids: selector.ids };
2292
+ }
2293
+ return { allInApp: true };
2294
+ }
2295
+
2296
+ // src/modules/imports.ts
2297
+ function createImportsModule(transport, errors = defaultSdkCoreErrorFactory) {
2298
+ const path = (id) => `/api/v1/data-imports/${encodePathSegment(id, "import id", errors)}`;
2299
+ const pageParams = (options = {}) => ({
2300
+ page: options.page,
2301
+ size: options.size,
2302
+ sort: options.sort
2303
+ });
2304
+ return {
2305
+ async list(options = {}) {
2306
+ return expectPage(
2307
+ await transport.request("/api/v1/data-imports", {
2308
+ method: "GET",
2309
+ params: pageParams(options)
2310
+ }),
2311
+ "Import page response",
2312
+ errors,
2313
+ expectImportDefinition
2314
+ );
2315
+ },
2316
+ async get(id) {
2317
+ return expectImportDefinition(
2318
+ await transport.request(path(id), { method: "GET" }),
2319
+ "Import response",
2320
+ errors
2321
+ );
2322
+ },
2323
+ async create(input) {
2324
+ return expectImportDefinition(
2325
+ await transport.request("/api/v1/data-imports", { method: "POST", body: input }),
2326
+ "Create import response",
2327
+ errors
2328
+ );
2329
+ },
2330
+ async update(id, input) {
2331
+ return expectImportDefinition(
2332
+ await transport.request(path(id), { method: "PUT", body: input }),
2333
+ "Update import response",
2334
+ errors
2335
+ );
2336
+ },
2337
+ async delete(id) {
2338
+ expectEmpty(
2339
+ await transport.request(path(id), { method: "DELETE" }),
2340
+ "Delete import response",
2341
+ errors
2342
+ );
2343
+ },
2344
+ async execute(id) {
2345
+ return expectImportExecution(
2346
+ await transport.request(`${path(id)}/execute`, { method: "POST" }),
2347
+ "Import execution response",
2348
+ errors
2349
+ );
2350
+ },
2351
+ async listExecutions(options) {
2352
+ return expectPage(
2353
+ await transport.request("/api/v1/data-imports/executions", {
2354
+ method: "GET",
2355
+ params: {
2356
+ definitionId: options.definitionId,
2357
+ page: options.page,
2358
+ size: options.size,
2359
+ sort: options.sort ?? "queuedAt,desc"
2360
+ }
2361
+ }),
2362
+ "Import execution page response",
2363
+ errors,
2364
+ expectImportExecution
2365
+ );
2366
+ },
2367
+ async cancelExecution(executionId) {
2368
+ return expectImportExecution(
2369
+ await transport.request(
2370
+ `/api/v1/data-imports/executions/${encodePathSegment(executionId, "execution id", errors)}/cancel`,
2371
+ { method: "POST" }
2372
+ ),
2373
+ "Cancel import execution response",
2374
+ errors
2375
+ );
2376
+ }
2377
+ };
2378
+ }
2379
+
2380
+ // src/modules/integration.ts
366
2381
  function createIntegrationModule(transport, errors = defaultSdkCoreErrorFactory) {
367
2382
  return {
368
2383
  async executeResource(resourceId, params = {}) {
@@ -375,13 +2390,356 @@ function createIntegrationModule(transport, errors = defaultSdkCoreErrorFactory)
375
2390
  errors
376
2391
  );
377
2392
  },
378
- async execute(configId, request) {
379
- return expectProxyResult(
2393
+ async execute(configId, request) {
2394
+ return expectProxyResult(
2395
+ await transport.request(
2396
+ `/api/v1/proxy/template-configs/${encodePathSegment(configId, "config id", errors)}/execute`,
2397
+ { method: "POST", body: { ...request, source: "SDK" } }
2398
+ ),
2399
+ "Integration proxy response",
2400
+ errors
2401
+ );
2402
+ },
2403
+ async executeByAlias(alias, request) {
2404
+ return expectProxyResult(
2405
+ await transport.request(
2406
+ `/api/v1/proxy/template-configs/by-alias/${encodePathSegment(alias, "alias", errors)}/execute`,
2407
+ { method: "POST", body: { ...request, source: "SDK" } }
2408
+ ),
2409
+ "Integration proxy response",
2410
+ errors
2411
+ );
2412
+ }
2413
+ };
2414
+ }
2415
+
2416
+ // src/modules/integrationAdmin.ts
2417
+ var MAX_CONFIGS = 100;
2418
+ function createIntegrationAdminModule(transport, errors = defaultSdkCoreErrorFactory) {
2419
+ const path = (id) => `/api/v1/template-configs/${encodePathSegment(id, "config id", errors)}`;
2420
+ return {
2421
+ async create(input) {
2422
+ return expectTemplateConfig(
2423
+ await transport.request("/api/v1/template-configs", {
2424
+ method: "POST",
2425
+ body: input
2426
+ }),
2427
+ "Create integration config response",
2428
+ errors
2429
+ );
2430
+ },
2431
+ async update(id, input) {
2432
+ return expectTemplateConfig(
2433
+ await transport.request(path(id), { method: "PUT", body: input }),
2434
+ "Update integration config response",
2435
+ errors
2436
+ );
2437
+ },
2438
+ async delete(id) {
2439
+ expectEmpty(
2440
+ await transport.request(path(id), { method: "DELETE" }),
2441
+ "Delete integration config response",
2442
+ errors
2443
+ );
2444
+ },
2445
+ async bulkCreate(configs) {
2446
+ requireBatchSize(configs, "configs", MAX_CONFIGS, errors);
2447
+ return expectTemplateConfigBulkResult(
2448
+ await transport.request("/api/v1/template-configs/bulk", {
2449
+ method: "POST",
2450
+ body: { configs }
2451
+ }),
2452
+ "Template config bulk create response",
2453
+ errors
2454
+ );
2455
+ },
2456
+ async bulkUpdate(configs) {
2457
+ requireBatchSize(configs, "configs", MAX_CONFIGS, errors);
2458
+ return expectTemplateConfigBulkResult(
2459
+ await transport.request("/api/v1/template-configs/bulk", {
2460
+ method: "PUT",
2461
+ body: { configs }
2462
+ }),
2463
+ "Template config bulk update response",
2464
+ errors
2465
+ );
2466
+ },
2467
+ // POST, not DELETE: the id list travels in a body, and some proxies drop a DELETE body.
2468
+ async bulkDelete(configIds) {
2469
+ requireBatchSize(configIds, "configIds", MAX_CONFIGS, errors);
2470
+ return expectTemplateConfigBulkResult(
2471
+ await transport.request("/api/v1/template-configs/bulk-delete", {
2472
+ method: "POST",
2473
+ body: { configIds }
2474
+ }),
2475
+ "Template config bulk delete response",
2476
+ errors
2477
+ );
2478
+ },
2479
+ async testCredentials(request) {
2480
+ return expectConnectionTestResult(
2481
+ await transport.request("/api/v1/template-configs/test", {
2482
+ method: "POST",
2483
+ body: request
2484
+ }),
2485
+ "Integration credentials test response",
2486
+ errors
2487
+ );
2488
+ },
2489
+ async testConfig(configId) {
2490
+ return expectConnectionTestResult(
2491
+ await transport.request(`${path(configId)}/test`, { method: "POST" }),
2492
+ "Integration config test response",
2493
+ errors
2494
+ );
2495
+ },
2496
+ async list(options = {}) {
2497
+ const params = {
2498
+ page: options.page,
2499
+ size: options.size,
2500
+ sort: options.sort
2501
+ };
2502
+ return expectTemplateConfigPage(
2503
+ await transport.request("/api/v1/template-configs", { method: "GET", params }),
2504
+ "Template config page response",
2505
+ errors
2506
+ );
2507
+ },
2508
+ async listExecutions(configId, options = {}) {
2509
+ return expectLegacyPage(
2510
+ await transport.request(`${path(configId)}/executions`, {
2511
+ method: "GET",
2512
+ params: {
2513
+ page: options.page,
2514
+ size: options.size,
2515
+ sort: options.sort ?? "createdAt,desc"
2516
+ }
2517
+ }),
2518
+ "Integration execution page response",
2519
+ errors,
2520
+ expectIntegrationExecution
2521
+ );
2522
+ },
2523
+ async getExecution(configId, executionId) {
2524
+ return expectIntegrationExecution(
2525
+ await transport.request(
2526
+ `${path(configId)}/executions/${encodePathSegment(executionId, "execution id", errors)}`,
2527
+ { method: "GET" }
2528
+ ),
2529
+ "Integration execution response",
2530
+ errors
2531
+ );
2532
+ }
2533
+ };
2534
+ }
2535
+
2536
+ // src/modules/integrationResources.ts
2537
+ function createIntegrationResourcesModule(transport, errors = defaultSdkCoreErrorFactory) {
2538
+ const path = (id) => `/api/v1/integration-resources/${encodePathSegment(id, "resource id", errors)}`;
2539
+ return {
2540
+ async list(options = {}) {
2541
+ const params = {
2542
+ page: options.page,
2543
+ size: options.size,
2544
+ sort: options.sort
2545
+ };
2546
+ return expectLegacyPage(
2547
+ await transport.request("/api/v1/integration-resources", {
2548
+ method: "GET",
2549
+ params
2550
+ }),
2551
+ "Integration resource page response",
2552
+ errors,
2553
+ expectIntegrationResourceSummary
2554
+ );
2555
+ },
2556
+ async get(id) {
2557
+ return expectIntegrationResource(
2558
+ await transport.request(path(id), { method: "GET" }),
2559
+ "Integration resource response",
2560
+ errors
2561
+ );
2562
+ },
2563
+ async create(input) {
2564
+ return expectIntegrationResource(
2565
+ await transport.request("/api/v1/integration-resources", {
2566
+ method: "POST",
2567
+ body: input
2568
+ }),
2569
+ "Create integration resource response",
2570
+ errors
2571
+ );
2572
+ },
2573
+ async update(id, input) {
2574
+ return expectIntegrationResource(
2575
+ await transport.request(path(id), { method: "PUT", body: input }),
2576
+ "Update integration resource response",
2577
+ errors
2578
+ );
2579
+ },
2580
+ async delete(id) {
2581
+ expectEmpty(
2582
+ await transport.request(path(id), { method: "DELETE" }),
2583
+ "Delete integration resource response",
2584
+ errors
2585
+ );
2586
+ }
2587
+ };
2588
+ }
2589
+
2590
+ // src/modules/integrationTemplates.ts
2591
+ function createIntegrationTemplatesModule(transport, errors = defaultSdkCoreErrorFactory) {
2592
+ const params = (options = {}, sort) => ({
2593
+ page: options.page,
2594
+ size: options.size ?? 20,
2595
+ sort: options.sort ?? sort
2596
+ });
2597
+ return {
2598
+ async list(options = {}) {
2599
+ return expectLegacyPage(
2600
+ await transport.request("/api/v1/templates", {
2601
+ method: "GET",
2602
+ params: params(options, "name")
2603
+ }),
2604
+ "Integration template page response",
2605
+ errors,
2606
+ expectIntegrationTemplateSummary
2607
+ );
2608
+ },
2609
+ async get(id) {
2610
+ return expectIntegrationTemplate(
2611
+ await transport.request(
2612
+ `/api/v1/templates/${encodePathSegment(id, "template id", errors)}`,
2613
+ { method: "GET" }
2614
+ ),
2615
+ "Integration template response",
2616
+ errors
2617
+ );
2618
+ },
2619
+ async listConfigs(options = {}) {
2620
+ return expectLegacyPage(
2621
+ await transport.request("/api/v1/template-configs", {
2622
+ method: "GET",
2623
+ params: params(options, "alias")
2624
+ }),
2625
+ "Integration config page response",
2626
+ errors,
2627
+ expectTemplateConfigSummary
2628
+ );
2629
+ },
2630
+ async getConfig(id) {
2631
+ return expectTemplateConfig(
2632
+ await transport.request(
2633
+ `/api/v1/template-configs/${encodePathSegment(id, "config id", errors)}`,
2634
+ { method: "GET" }
2635
+ ),
2636
+ "Integration config response",
2637
+ errors
2638
+ );
2639
+ }
2640
+ };
2641
+ }
2642
+
2643
+ // src/modules/members.ts
2644
+ var MAX_APP_USERS = 100;
2645
+ function createMembersModule(transport, errors = defaultSdkCoreErrorFactory) {
2646
+ const path = (appId) => `/api/v1/apps/${encodePathSegment(appId, "app id", errors)}/users`;
2647
+ return {
2648
+ async list() {
2649
+ return expectAppMembers(
2650
+ await transport.request("/api/v1/members/current-app", { method: "GET" }),
2651
+ "App members response",
2652
+ errors
2653
+ );
2654
+ },
2655
+ async invite(appId, input) {
2656
+ expectEmpty(
2657
+ await transport.request(path(appId), { method: "POST", body: input }),
2658
+ "Invite app user response",
2659
+ errors
2660
+ );
2661
+ },
2662
+ async unsubscribe(appId, userId) {
2663
+ expectEmpty(
380
2664
  await transport.request(
381
- `/api/v1/proxy/template-configs/${encodePathSegment(configId, "config id", errors)}/execute`,
382
- { method: "POST", body: { ...request, source: "SDK" } }
2665
+ `${path(appId)}/${encodePathSegment(userId, "user id", errors)}`,
2666
+ { method: "DELETE" }
383
2667
  ),
384
- "Integration proxy response",
2668
+ "Unsubscribe app user response",
2669
+ errors
2670
+ );
2671
+ },
2672
+ async bulkInvite(appId, users) {
2673
+ requireBatchSize(users, "users", MAX_APP_USERS, errors);
2674
+ expectEmpty(
2675
+ await transport.request(`${path(appId)}/bulk`, {
2676
+ method: "POST",
2677
+ body: { users }
2678
+ }),
2679
+ "Bulk invite app users response",
2680
+ errors
2681
+ );
2682
+ },
2683
+ async bulkUnsubscribe(appId, userIds) {
2684
+ requireBatchSize(userIds, "userIds", MAX_APP_USERS, errors);
2685
+ return expectBulkUnsubscribeResult(
2686
+ await transport.request(`${path(appId)}/bulk-unsubscribe`, {
2687
+ method: "POST",
2688
+ body: { userIds }
2689
+ }),
2690
+ "Bulk unsubscribe app users response",
2691
+ errors
2692
+ );
2693
+ }
2694
+ };
2695
+ }
2696
+
2697
+ // src/modules/messenger.ts
2698
+ function createMessengerModule(transport, errors = defaultSdkCoreErrorFactory) {
2699
+ return {
2700
+ async notify(content) {
2701
+ return expectMessageAccepted(
2702
+ await transport.request("/api/v1/messages/notify", {
2703
+ method: "POST",
2704
+ body: { content }
2705
+ }),
2706
+ "Notify user response",
2707
+ errors
2708
+ );
2709
+ }
2710
+ };
2711
+ }
2712
+
2713
+ // src/modules/publicFunctions.ts
2714
+ function createPublicFunctionsModule(transport, errors = defaultSdkCoreErrorFactory) {
2715
+ const execute = async (id, input, mode) => {
2716
+ if (!transport) {
2717
+ configurationError(
2718
+ "A separate publicFunctions transport is required so anonymous requests do not inherit authorization headers",
2719
+ errors
2720
+ );
2721
+ }
2722
+ return transport.request(
2723
+ `/public/v1/functions/${encodePathSegment(id, "function id", errors)}/execute`,
2724
+ {
2725
+ method: "POST",
2726
+ headers: { "X-Invocation-Type": mode },
2727
+ body: { input: input ?? {} }
2728
+ }
2729
+ );
2730
+ };
2731
+ return {
2732
+ async execute(id, input) {
2733
+ return expectPublicFunctionResult(
2734
+ await execute(id, input, "sync"),
2735
+ "Public Function execution response",
2736
+ errors
2737
+ );
2738
+ },
2739
+ async executeAsync(id, input) {
2740
+ return expectPublicFunctionAsyncResult(
2741
+ await execute(id, input, "async"),
2742
+ "Public async Function execution response",
385
2743
  errors
386
2744
  );
387
2745
  }
@@ -389,22 +2747,15 @@ function createIntegrationModule(transport, errors = defaultSdkCoreErrorFactory)
389
2747
  }
390
2748
 
391
2749
  // src/modules/queries.ts
392
- function createQueriesModule(transport, getDataSourceId, errors = defaultSdkCoreErrorFactory) {
2750
+ function createQueriesModule(transport, errors = defaultSdkCoreErrorFactory) {
393
2751
  return {
394
2752
  async execute(id, parameters = {}) {
395
- const dataSourceId = getDataSourceId();
396
- if (!dataSourceId) {
397
- configurationError(
398
- "A dataSourceId is required for queries. Call client.init() first or configure dataSourceId.",
399
- errors
400
- );
401
- }
402
2753
  return expectQueryResult(
403
2754
  await transport.request(
404
2755
  `/api/v1/custom-queries/${encodePathSegment(id, "query id", errors)}/execute`,
405
2756
  {
406
2757
  method: "POST",
407
- body: { dataSourceId, parameters }
2758
+ body: { parameters }
408
2759
  }
409
2760
  ),
410
2761
  "Query execution response",
@@ -414,30 +2765,975 @@ function createQueriesModule(transport, getDataSourceId, errors = defaultSdkCore
414
2765
  };
415
2766
  }
416
2767
 
2768
+ // src/modules/schema.ts
2769
+ function createSchemaModule(transport, errors = defaultSdkCoreErrorFactory) {
2770
+ const tablePath = (name) => `/api/v1/tables/${encodePathSegment(name, "table name", errors)}`;
2771
+ const list = async (options = {}) => {
2772
+ const params = {
2773
+ scope: options.scope,
2774
+ includeColumns: options.includeColumns
2775
+ };
2776
+ return expectSchemaTables(
2777
+ await transport.request("/api/v1/tables", { method: "GET", params }),
2778
+ "Schema tables response",
2779
+ errors
2780
+ );
2781
+ };
2782
+ return {
2783
+ async createTable(tableName, columns) {
2784
+ expectEmpty(
2785
+ await transport.request("/api/v1/tables", {
2786
+ method: "POST",
2787
+ body: { tableName, columns }
2788
+ }),
2789
+ "Create table response",
2790
+ errors
2791
+ );
2792
+ },
2793
+ listTables: list,
2794
+ listAppTables(options = {}) {
2795
+ return list({
2796
+ scope: "APP",
2797
+ ...options.includeColumns === void 0 ? {} : { includeColumns: options.includeColumns }
2798
+ });
2799
+ },
2800
+ async getTable(tableName) {
2801
+ return expectTableDefinition(
2802
+ await transport.request(tablePath(tableName), { method: "GET" }),
2803
+ "Table details response",
2804
+ errors
2805
+ );
2806
+ },
2807
+ async dropTable(tableName) {
2808
+ expectEmpty(
2809
+ await transport.request(tablePath(tableName), { method: "DELETE" }),
2810
+ "Drop table response",
2811
+ errors
2812
+ );
2813
+ },
2814
+ async truncateTable(tableName) {
2815
+ expectEmpty(
2816
+ await transport.request(`${tablePath(tableName)}/truncate`, { method: "POST" }),
2817
+ "Truncate table response",
2818
+ errors
2819
+ );
2820
+ },
2821
+ async addColumn(tableName, column) {
2822
+ expectEmpty(
2823
+ await transport.request(`${tablePath(tableName)}/columns`, {
2824
+ method: "POST",
2825
+ body: column
2826
+ }),
2827
+ "Add column response",
2828
+ errors
2829
+ );
2830
+ },
2831
+ async dropColumn(tableName, columnName) {
2832
+ expectEmpty(
2833
+ await transport.request(
2834
+ `${tablePath(tableName)}/columns/${encodePathSegment(columnName, "column name", errors)}`,
2835
+ { method: "DELETE" }
2836
+ ),
2837
+ "Drop column response",
2838
+ errors
2839
+ );
2840
+ }
2841
+ };
2842
+ }
2843
+
2844
+ // src/modules/sql.ts
2845
+ var MAX_STATEMENTS = 20;
2846
+ function createSqlModule(transport, errors = defaultSdkCoreErrorFactory) {
2847
+ return {
2848
+ async executeQuery(sql, parameters = {}) {
2849
+ return expectQueryResult(
2850
+ await transport.request("/api/v1/sql/execute", {
2851
+ method: "POST",
2852
+ body: { sql, parameters }
2853
+ }),
2854
+ "SQL execution response",
2855
+ errors
2856
+ );
2857
+ },
2858
+ async executeDdl(statements) {
2859
+ requireBatchSize(statements, "statements", MAX_STATEMENTS, errors);
2860
+ return expectBatchExecution(
2861
+ await transport.request("/api/v1/sql/ddl/execute", {
2862
+ method: "POST",
2863
+ body: { statements }
2864
+ }),
2865
+ "DDL batch response",
2866
+ errors
2867
+ );
2868
+ },
2869
+ async executeDml(statements) {
2870
+ requireBatchSize(statements, "statements", MAX_STATEMENTS, errors);
2871
+ return expectBatchExecution(
2872
+ await transport.request("/api/v1/sql/dml/execute", {
2873
+ method: "POST",
2874
+ body: { statements }
2875
+ }),
2876
+ "DML batch response",
2877
+ errors
2878
+ );
2879
+ },
2880
+ async listTables(options = {}) {
2881
+ const params = {
2882
+ scope: options.scope,
2883
+ includeColumns: options.includeColumns
2884
+ };
2885
+ return expectSchemaTables(
2886
+ await transport.request("/api/v1/tables", { method: "GET", params }),
2887
+ "Schema tables response",
2888
+ errors
2889
+ );
2890
+ }
2891
+ };
2892
+ }
2893
+
2894
+ // src/modules/workflows.ts
2895
+ function createWorkflowsModule(transport, errors = defaultSdkCoreErrorFactory) {
2896
+ const path = (id) => `/api/v1/workflows/${encodePathSegment(id, "workflow id", errors)}`;
2897
+ const params = (options = {}) => ({
2898
+ page: options.page,
2899
+ size: options.size,
2900
+ sort: options.sort
2901
+ });
2902
+ const executionPath = (workflowId, executionId) => `${path(workflowId)}/executions${executionId === void 0 ? "" : `/${encodePathSegment(executionId, "workflow execution id", errors)}`}`;
2903
+ return {
2904
+ async list(options = {}) {
2905
+ return expectPage(
2906
+ await transport.request("/api/v1/workflows", {
2907
+ method: "GET",
2908
+ params: params(options)
2909
+ }),
2910
+ "Workflow page response",
2911
+ errors,
2912
+ expectWorkflowSummary
2913
+ );
2914
+ },
2915
+ async get(id) {
2916
+ return expectWorkflowDefinition(
2917
+ await transport.request(path(id), { method: "GET" }),
2918
+ "Workflow response",
2919
+ errors
2920
+ );
2921
+ },
2922
+ async create(input) {
2923
+ return expectWorkflowDefinition(
2924
+ await transport.request("/api/v1/workflows", {
2925
+ method: "POST",
2926
+ body: input
2927
+ }),
2928
+ "Create workflow response",
2929
+ errors
2930
+ );
2931
+ },
2932
+ async update(id, input) {
2933
+ return expectWorkflowDefinition(
2934
+ await transport.request(path(id), { method: "PUT", body: input }),
2935
+ "Update workflow response",
2936
+ errors
2937
+ );
2938
+ },
2939
+ async delete(id) {
2940
+ expectEmpty(
2941
+ await transport.request(path(id), { method: "DELETE" }),
2942
+ "Delete workflow response",
2943
+ errors
2944
+ );
2945
+ },
2946
+ async execute(id, input = {}) {
2947
+ return expectWorkflowExecution(
2948
+ await transport.request(`${path(id)}/execute`, {
2949
+ method: "POST",
2950
+ body: { input }
2951
+ }),
2952
+ "Workflow execution response",
2953
+ errors
2954
+ );
2955
+ },
2956
+ async listExecutions(workflowId, options = {}) {
2957
+ return expectPage(
2958
+ await transport.request(executionPath(workflowId), {
2959
+ method: "GET",
2960
+ params: params(options)
2961
+ }),
2962
+ "Workflow execution page response",
2963
+ errors,
2964
+ expectWorkflowExecution
2965
+ );
2966
+ },
2967
+ async getExecution(workflowId, executionId) {
2968
+ return expectWorkflowExecution(
2969
+ await transport.request(executionPath(workflowId, executionId), { method: "GET" }),
2970
+ "Workflow execution response",
2971
+ errors
2972
+ );
2973
+ },
2974
+ async cancelExecution(workflowId, executionId) {
2975
+ expectEmpty(
2976
+ await transport.request(`${executionPath(workflowId, executionId)}/cancel`, {
2977
+ method: "POST"
2978
+ }),
2979
+ "Cancel workflow execution response",
2980
+ errors
2981
+ );
2982
+ }
2983
+ };
2984
+ }
2985
+
417
2986
  // src/core.ts
418
2987
  function createSdkCore(options) {
419
2988
  const errors = options.errors ?? defaultSdkCoreErrorFactory;
2989
+ const codeStudio = options.transports.codeStudio ?? unavailableTransport("codeStudio", errors);
2990
+ const copilot = options.transports.copilot ?? unavailableTransport("copilot", errors);
2991
+ const messengerTransport = options.transports.messenger ?? unavailableTransport("messenger", errors);
2992
+ const apps = createAppsModule(codeStudio, errors);
2993
+ const schema = createSchemaModule(options.transports.dataManager, errors);
2994
+ const functionsAdmin = createFunctionsAdminModule(options.transports.functions, errors);
2995
+ const agents = createAgentsModule(options.transports.functions, copilot, errors);
2996
+ const integrationAdmin = createIntegrationAdminModule(options.transports.integration, errors);
2997
+ const agentConnections = createAgentConnectionsModule(copilot, errors);
2998
+ const members = createMembersModule(options.transports.auth, errors);
420
2999
  return {
3000
+ agentConnections,
3001
+ agentCredentials: createAgentCredentialsModule(copilot, errors),
3002
+ agents,
3003
+ agentTasks: createAgentTasksModule(copilot, errors),
3004
+ apps,
421
3005
  auth: createAuthModule(options.transports.auth, errors),
3006
+ context: createContextModule(
3007
+ {
3008
+ apps,
3009
+ schema,
3010
+ functionsAdmin,
3011
+ agents,
3012
+ integrationAdmin,
3013
+ agentConnections,
3014
+ getAppId: options.getAppId
3015
+ },
3016
+ errors
3017
+ ),
3018
+ customQueries: createCustomQueriesModule(options.transports.dataManager, errors),
3019
+ dataSources: createDataSourcesModule(options.transports.dataManager, errors),
422
3020
  entities: createEntitiesModule(options.transports.dataManager, errors),
423
3021
  functions: createFunctionsModule(options.transports.functions, options.functions, errors),
3022
+ functionsAdmin,
3023
+ imports: createImportsModule(options.transports.dataManager, errors),
424
3024
  integration: createIntegrationModule(options.transports.integration, errors),
425
- queries: createQueriesModule(options.transports.dataManager, options.getDataSourceId, errors)
3025
+ integrationAdmin,
3026
+ integrationResources: createIntegrationResourcesModule(options.transports.integration, errors),
3027
+ integrationTemplates: createIntegrationTemplatesModule(options.transports.integration, errors),
3028
+ members,
3029
+ messenger: createMessengerModule(messengerTransport, errors),
3030
+ publicFunctions: createPublicFunctionsModule(options.transports.publicFunctions, errors),
3031
+ queries: createQueriesModule(options.transports.dataManager, errors),
3032
+ sql: createSqlModule(options.transports.dataManager, errors),
3033
+ schema,
3034
+ workflows: createWorkflowsModule(options.transports.functions, errors)
3035
+ };
3036
+ }
3037
+ function unavailableTransport(name, errors) {
3038
+ return {
3039
+ request() {
3040
+ return Promise.reject(errors.configuration(`The ${name} transport is not configured`));
3041
+ }
3042
+ };
3043
+ }
3044
+
3045
+ // src/agentSession.ts
3046
+ var AGENT_QUEUE_LIMIT = 10;
3047
+ var CANCEL_SAFETY_MS = 1e4;
3048
+ var RECONCILE_DELAY_MS = 1e3;
3049
+ var AgentTaskTurnError = class extends Error {
3050
+ code;
3051
+ constructor(message, code) {
3052
+ super(message);
3053
+ this.name = "AgentTaskTurnError";
3054
+ this.code = code;
3055
+ }
3056
+ };
3057
+ function asObject(value) {
3058
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
3059
+ }
3060
+ function errorMessage(error) {
3061
+ if (error instanceof Error) return error.message;
3062
+ if (error && typeof error === "object" && "message" in error) {
3063
+ return String(error.message);
3064
+ }
3065
+ return String(error);
3066
+ }
3067
+ function errorCode(error) {
3068
+ if (!error || typeof error !== "object") return void 0;
3069
+ const candidate = error;
3070
+ const code = candidate.code ?? candidate.details?.code ?? candidate.details?.error_code;
3071
+ return typeof code === "string" ? code : void 0;
3072
+ }
3073
+ function delay(milliseconds) {
3074
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
3075
+ }
3076
+ function toAgentTimelineItem(message) {
3077
+ if (message.type === "TOOL_USE") {
3078
+ try {
3079
+ const payload = JSON.parse(message.content);
3080
+ if (payload && typeof payload === "object") {
3081
+ return {
3082
+ id: message.id,
3083
+ kind: "tool",
3084
+ tool: {
3085
+ tool: typeof payload.name === "string" ? payload.name : "",
3086
+ ...typeof payload.toolId === "string" ? { toolId: payload.toolId } : {},
3087
+ ...payload.input !== void 0 ? { input: payload.input } : {},
3088
+ ...payload.content !== void 0 ? { content: payload.content } : payload.output !== void 0 ? { content: payload.output } : {},
3089
+ phase: payload.output !== void 0 || payload.content !== void 0 ? "result" : "call"
3090
+ },
3091
+ at: message.createdAt
3092
+ };
3093
+ }
3094
+ } catch {
3095
+ }
3096
+ }
3097
+ return {
3098
+ id: message.id,
3099
+ kind: message.sender === "USER" ? "user" : "agent",
3100
+ text: message.content,
3101
+ at: message.createdAt
3102
+ };
3103
+ }
3104
+ function createAgentTaskSessionManager(options) {
3105
+ const sessions = /* @__PURE__ */ new Map();
3106
+ return {
3107
+ session(sessionOptions) {
3108
+ if ("taskId" in sessionOptions) {
3109
+ const current = sessions.get(sessionOptions.taskId);
3110
+ if (current && current.status !== "closed") return current;
3111
+ }
3112
+ const session = new CoreAgentTaskSession(sessionOptions, {
3113
+ ...options,
3114
+ onTaskId: (taskId, value) => sessions.set(taskId, value),
3115
+ onClose: (taskId, value) => {
3116
+ if (sessions.get(taskId) === value) sessions.delete(taskId);
3117
+ }
3118
+ });
3119
+ if ("taskId" in sessionOptions) sessions.set(sessionOptions.taskId, session);
3120
+ return session;
3121
+ }
426
3122
  };
427
3123
  }
3124
+ function withAgentTaskSessions(tasks, manager) {
3125
+ return { ...tasks, session: (options) => manager.session(options) };
3126
+ }
3127
+ var CoreAgentTaskSession = class {
3128
+ constructor(options, dependencies) {
3129
+ this.options = options;
3130
+ this.dependencies = dependencies;
3131
+ this.isNewSession = "create" in options;
3132
+ if ("taskId" in options) {
3133
+ this._taskId = options.taskId;
3134
+ this.openingPromise = this.openExisting();
3135
+ } else {
3136
+ this._status = "idle";
3137
+ }
3138
+ }
3139
+ _taskId = null;
3140
+ _task = null;
3141
+ _status = "opening";
3142
+ _history = [];
3143
+ _content = "";
3144
+ _queue = [];
3145
+ isNewSession;
3146
+ listeners = /* @__PURE__ */ new Map();
3147
+ connection = null;
3148
+ connectionAbort = null;
3149
+ connectionPromise = null;
3150
+ openingPromise = null;
3151
+ createPromise = null;
3152
+ dispatching = false;
3153
+ recoveryUsed = false;
3154
+ recoveryPromise = null;
3155
+ recoveryGeneration = 0;
3156
+ recoveredTerminalReason;
3157
+ cancelTimer = null;
3158
+ queueSequence = 0;
3159
+ activeWaiter;
3160
+ turnBaselineIds = /* @__PURE__ */ new Set();
3161
+ get taskId() {
3162
+ return this._taskId;
3163
+ }
3164
+ get task() {
3165
+ return this._task;
3166
+ }
3167
+ get isNew() {
3168
+ return this.isNewSession;
3169
+ }
3170
+ get status() {
3171
+ return this._status;
3172
+ }
3173
+ get history() {
3174
+ return [...this._history];
3175
+ }
3176
+ get content() {
3177
+ return this._content;
3178
+ }
3179
+ get queue() {
3180
+ return this._queue.map((item) => ({
3181
+ id: item.id,
3182
+ text: item.text,
3183
+ createdAt: item.createdAt,
3184
+ ...item.agentType ? { agentType: item.agentType } : {},
3185
+ ...item.reasoningEffort ? { reasoningEffort: item.reasoningEffort } : {}
3186
+ }));
3187
+ }
3188
+ send(prompt, options = {}) {
3189
+ this.requireOpen();
3190
+ if (!prompt.trim()) return;
3191
+ if (this.isBusy()) {
3192
+ this.enqueue(prompt, options);
3193
+ return;
3194
+ }
3195
+ this.startDispatch(prompt, options);
3196
+ }
3197
+ sendAndWait(prompt, options = {}) {
3198
+ this.requireOpen();
3199
+ if (!prompt.trim()) return Promise.reject(new Error("Agent prompt must not be blank."));
3200
+ const waiter = this.createWaiter(options);
3201
+ if (waiter.settled) return waiter.promise;
3202
+ const sendOptions = {
3203
+ ...options.agentType ? { agentType: options.agentType } : {},
3204
+ ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {}
3205
+ };
3206
+ if (this.isBusy()) {
3207
+ const queueId = this.enqueue(prompt, sendOptions, waiter);
3208
+ if (queueId) waiter.queueId = queueId;
3209
+ return waiter.promise;
3210
+ }
3211
+ this.startDispatch(prompt, sendOptions, waiter);
3212
+ return waiter.promise;
3213
+ }
3214
+ async cancel() {
3215
+ if (this._status !== "streaming" && this._status !== "cancelled") return;
3216
+ try {
3217
+ await this.sendInput({ type: "interrupt" });
3218
+ this.setStatus("cancelled");
3219
+ this.emit("cancelled", {});
3220
+ if (this.cancelTimer) clearTimeout(this.cancelTimer);
3221
+ this.cancelTimer = setTimeout(() => {
3222
+ this.cancelTimer = null;
3223
+ if (this._status === "cancelled") {
3224
+ const error = new AgentTaskTurnError(
3225
+ "Agent turn cancellation was not acknowledged before the safety timeout."
3226
+ );
3227
+ this.emit("error", { error: error.message });
3228
+ this.failTurn(error);
3229
+ }
3230
+ }, CANCEL_SAFETY_MS);
3231
+ } catch (error) {
3232
+ this.emitError("Failed to cancel Agent task", error);
3233
+ throw error;
3234
+ }
3235
+ }
3236
+ respondApproval(approved) {
3237
+ void this.sendInput({ type: "approval_response", approved }).catch((error) => {
3238
+ this.emitError("Failed to answer Agent approval", error);
3239
+ });
3240
+ }
3241
+ async loadHistory(options = {}) {
3242
+ if (!this._taskId) return [];
3243
+ const page = await this.dependencies.tasks.listMessages(this._taskId, {
3244
+ ...options.limit !== void 0 ? { size: options.limit } : {},
3245
+ sort: "createdAt,desc"
3246
+ });
3247
+ this._history = [...page.content].reverse().map(toAgentTimelineItem);
3248
+ const history = this.history;
3249
+ this.emit("historyLoaded", { history });
3250
+ return history;
3251
+ }
3252
+ editQueueItem(id, text) {
3253
+ if (!text.trim()) {
3254
+ this.removeQueueItem(id);
3255
+ return;
3256
+ }
3257
+ this._queue = this._queue.map((item) => item.id === id ? { ...item, text } : item);
3258
+ this.emitQueue();
3259
+ }
3260
+ removeQueueItem(id) {
3261
+ const removed = this._queue.find((item) => item.id === id);
3262
+ this._queue = this._queue.filter((item) => item.id !== id);
3263
+ removed?.waiter?.reject(new Error("Queued Agent prompt was removed."));
3264
+ this.emitQueue();
3265
+ }
3266
+ clearQueue() {
3267
+ if (!this._queue.length) return;
3268
+ const removed = this._queue;
3269
+ this._queue = [];
3270
+ for (const item of removed) item.waiter?.reject(new Error("Agent prompt queue was cleared."));
3271
+ this.emitQueue();
3272
+ }
3273
+ on(event, handler) {
3274
+ let listeners = this.listeners.get(event);
3275
+ if (!listeners) {
3276
+ listeners = /* @__PURE__ */ new Set();
3277
+ this.listeners.set(event, listeners);
3278
+ }
3279
+ const callback = handler;
3280
+ listeners.add(callback);
3281
+ return () => listeners?.delete(callback);
3282
+ }
3283
+ close() {
3284
+ if (this._status === "closed") return;
3285
+ this.setStatus("closed");
3286
+ if (this.cancelTimer) clearTimeout(this.cancelTimer);
3287
+ this.cancelTimer = null;
3288
+ this.connectionAbort?.abort();
3289
+ this.connectionAbort = null;
3290
+ this.connection?.close();
3291
+ this.connection = null;
3292
+ this.recoveryGeneration += 1;
3293
+ const closedError = new Error("Agent task session is closed.");
3294
+ this.activeWaiter?.reject(closedError);
3295
+ this.activeWaiter = void 0;
3296
+ for (const item of this._queue) item.waiter?.reject(closedError);
3297
+ this._queue = [];
3298
+ if (this._taskId) this.dependencies.onClose(this._taskId, this);
3299
+ for (const listeners of this.listeners.values()) listeners.clear();
3300
+ }
3301
+ async openExisting() {
3302
+ try {
3303
+ this._task = await this.dependencies.tasks.get(this._taskId);
3304
+ if (this.isClosed()) return false;
3305
+ await this.loadHistory();
3306
+ if (this.isClosed()) return false;
3307
+ await this.ensureChannel();
3308
+ if (this.isClosed()) return false;
3309
+ this.setStatus("idle");
3310
+ return true;
3311
+ } catch (error) {
3312
+ if (this.isClosed()) return false;
3313
+ this.emitError("Failed to open Agent task", error);
3314
+ this.setStatus("error");
3315
+ return false;
3316
+ }
3317
+ }
3318
+ startDispatch(prompt, options, waiter) {
3319
+ this.dispatching = true;
3320
+ void this.dispatchSend(prompt, options, waiter).catch((error) => {
3321
+ waiter?.reject(error);
3322
+ this.emitError("Failed to send Agent prompt", error);
3323
+ if (this._status === "streaming") this.setStatus("idle");
3324
+ this.flushQueue();
3325
+ }).finally(() => {
3326
+ this.dispatching = false;
3327
+ if (this._status === "idle") this.flushQueue();
3328
+ });
3329
+ }
3330
+ async dispatchSend(prompt, options, waiter) {
3331
+ if (this.openingPromise && !await this.openingPromise) {
3332
+ throw new Error("Agent task session could not be opened.");
3333
+ }
3334
+ if (this.isClosed() || waiter?.settled) return;
3335
+ await this.ensureTask();
3336
+ if (this.isClosed() || waiter?.settled) return;
3337
+ await this.ensureChannel();
3338
+ if (this.isClosed() || waiter?.settled) return;
3339
+ await this.captureTurnBaseline();
3340
+ this._content = "";
3341
+ this.recoveryUsed = false;
3342
+ this.recoveredTerminalReason = void 0;
3343
+ this.recoveryGeneration += 1;
3344
+ this.activeWaiter = waiter;
3345
+ this.setStatus("streaming");
3346
+ this.emit("turnStart", {});
3347
+ await this.sendInput({
3348
+ type: "message",
3349
+ content: prompt,
3350
+ ...options.agentType ? { agentType: options.agentType } : {},
3351
+ ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {}
3352
+ });
3353
+ }
3354
+ async ensureTask() {
3355
+ if (this._taskId) return;
3356
+ if (!("create" in this.options)) throw new Error("Agent task session has no task.");
3357
+ const createOptions = this.options;
3358
+ if (this.createPromise) return this.createPromise;
3359
+ this.createPromise = (async () => {
3360
+ const task = await this.dependencies.tasks.create({
3361
+ agentType: createOptions.agentType,
3362
+ ...createOptions.title ? { title: createOptions.title } : {},
3363
+ ...createOptions.agentId ? { agentId: createOptions.agentId } : {},
3364
+ ...createOptions.reasoningEffort ? { reasoningEffort: createOptions.reasoningEffort } : {},
3365
+ ...createOptions.userId ? { userId: createOptions.userId } : {}
3366
+ });
3367
+ this._task = task;
3368
+ this._taskId = task.id;
3369
+ this.dependencies.onTaskId(task.id, this);
3370
+ this.emit("taskCreated", { task });
3371
+ })().finally(() => {
3372
+ this.createPromise = null;
3373
+ });
3374
+ return this.createPromise;
3375
+ }
3376
+ ensureChannel() {
3377
+ if (this.connection) return Promise.resolve();
3378
+ if (this.connectionPromise) return this.connectionPromise;
3379
+ if (!this._taskId) return Promise.reject(new Error("Agent task has not been created."));
3380
+ const abort = new AbortController();
3381
+ this.connectionAbort = abort;
3382
+ this.connectionPromise = this.dependencies.eventSource.open(
3383
+ this._taskId,
3384
+ {
3385
+ onEvent: (event) => this.handleEvent(event),
3386
+ onDisconnect: (error) => this.handleDisconnect(error)
3387
+ },
3388
+ abort.signal,
3389
+ this.options.transport
3390
+ ).then((connection) => {
3391
+ if (this.isClosed() || this._status === "error") {
3392
+ connection.close();
3393
+ return;
3394
+ }
3395
+ this.connection = connection;
3396
+ }).finally(() => {
3397
+ this.connectionPromise = null;
3398
+ });
3399
+ return this.connectionPromise;
3400
+ }
3401
+ handleDisconnect(error) {
3402
+ this.connection = null;
3403
+ this.connectionAbort = null;
3404
+ if (this.isClosed()) return;
3405
+ if (this._status !== "streaming" && this._status !== "cancelled") return;
3406
+ if (this.recoveryUsed) {
3407
+ const disconnectError = new Error("Agent live channel disconnected after one recovery.");
3408
+ this.failLiveChannel(error ?? disconnectError, disconnectError);
3409
+ return;
3410
+ }
3411
+ this.recoveryUsed = true;
3412
+ const generation = ++this.recoveryGeneration;
3413
+ this.recoveryPromise = this.recoverTurn(generation).finally(() => {
3414
+ this.recoveryPromise = null;
3415
+ });
3416
+ }
3417
+ async recoverTurn(generation) {
3418
+ try {
3419
+ await this.ensureChannel();
3420
+ while (generation === this.recoveryGeneration && !this.isClosed() && (this._status === "streaming" || this._status === "cancelled")) {
3421
+ if (await this.reconcilePersistedTurn(this.recoveredTerminalReason ?? "reconciled")) {
3422
+ return;
3423
+ }
3424
+ if (this.activeWaiter?.settled) return;
3425
+ await delay(RECONCILE_DELAY_MS);
3426
+ }
3427
+ } catch (error) {
3428
+ if (this.isClosed()) return;
3429
+ const recoveryError = error instanceof Error ? error : new Error(errorMessage(error));
3430
+ this.failLiveChannel(error, recoveryError);
3431
+ }
3432
+ }
3433
+ async captureTurnBaseline() {
3434
+ if (!this._taskId) return;
3435
+ const page = await this.dependencies.tasks.listMessages(this._taskId, {
3436
+ size: 100,
3437
+ sort: "createdAt,desc"
3438
+ });
3439
+ this.turnBaselineIds = new Set(page.content.map((message) => message.id));
3440
+ }
3441
+ async reconcilePersistedTurn(reason) {
3442
+ if (!this._taskId) return false;
3443
+ const page = await this.dependencies.tasks.listMessages(this._taskId, {
3444
+ size: 100,
3445
+ sort: "createdAt,desc"
3446
+ });
3447
+ this._history = [...page.content].reverse().map(toAgentTimelineItem);
3448
+ this.emit("historyLoaded", { history: this.history });
3449
+ const recovered = page.content.find(
3450
+ (message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE"
3451
+ );
3452
+ if (!recovered) return false;
3453
+ if (recovered.type === "ERROR") {
3454
+ const error = new AgentTaskTurnError(recovered.content);
3455
+ this.emit("error", { error: error.message });
3456
+ this.failTurn(error);
3457
+ return true;
3458
+ }
3459
+ this._content = recovered.content;
3460
+ this.finishTurn(reason);
3461
+ return true;
3462
+ }
3463
+ sendInput(input) {
3464
+ if (!this._taskId) return Promise.reject(new Error("Agent task has not been created."));
3465
+ return this.dependencies.tasks.sendInput(this._taskId, input);
3466
+ }
3467
+ handleEvent(event) {
3468
+ this.emit("raw", event);
3469
+ const payload = asObject(event.payload);
3470
+ switch (event.type) {
3471
+ case "textDelta":
3472
+ this.consumeDelta(payload, "text");
3473
+ break;
3474
+ case "thinking":
3475
+ this.consumeDelta(payload, "thinking");
3476
+ break;
3477
+ case "toolCall":
3478
+ this.emitTool(payload, "call", event.timestamp);
3479
+ break;
3480
+ case "toolResult":
3481
+ this.emitTool(payload, "result", event.timestamp);
3482
+ break;
3483
+ case "workspace":
3484
+ this.emit("workspace", { payload: event.payload, timestamp: event.timestamp });
3485
+ break;
3486
+ case "stepFinish": {
3487
+ const reason = typeof payload?.reason === "string" ? payload.reason : "unknown";
3488
+ if (reason === "stop" || reason === "endTurn") {
3489
+ if (this.recoveryUsed) {
3490
+ this.recoveredTerminalReason = reason;
3491
+ if (!this.recoveryPromise) {
3492
+ const generation = this.recoveryGeneration;
3493
+ this.recoveryPromise = this.recoverTurn(generation).finally(() => {
3494
+ this.recoveryPromise = null;
3495
+ });
3496
+ }
3497
+ } else {
3498
+ this.finishTurn(reason);
3499
+ }
3500
+ }
3501
+ break;
3502
+ }
3503
+ case "error": {
3504
+ const code = typeof payload?.code === "string" ? payload.code : void 0;
3505
+ const message = typeof payload?.message === "string" ? payload.message : "Agent returned an error.";
3506
+ this.emit("error", { ...code ? { code } : {}, error: message });
3507
+ if (this._status === "streaming" || this._status === "cancelled") {
3508
+ this.failTurn(new AgentTaskTurnError(message, code));
3509
+ }
3510
+ break;
3511
+ }
3512
+ default:
3513
+ break;
3514
+ }
3515
+ }
3516
+ consumeDelta(payload, kind) {
3517
+ const text = typeof payload?.text === "string" ? payload.text : "";
3518
+ if (this._status !== "streaming" && this._status !== "cancelled") {
3519
+ this.setStatus("streaming");
3520
+ this.emit("turnStart", {});
3521
+ }
3522
+ if (kind === "text") this._content += text;
3523
+ this.emit("delta", { delta: text, kind });
3524
+ }
3525
+ emitTool(payload, phase, timestamp) {
3526
+ this.emit("tool", {
3527
+ tool: typeof payload?.name === "string" ? payload.name : "",
3528
+ phase,
3529
+ timestamp,
3530
+ ...typeof payload?.toolId === "string" ? { toolId: payload.toolId } : {},
3531
+ ...phase === "call" && payload?.input !== void 0 ? { input: payload.input } : {},
3532
+ ...phase === "result" ? { content: payload?.content ?? payload?.output } : {}
3533
+ });
3534
+ }
3535
+ finishTurn(reason) {
3536
+ if (this._status !== "streaming" && this._status !== "cancelled") return;
3537
+ if (this.cancelTimer) clearTimeout(this.cancelTimer);
3538
+ this.cancelTimer = null;
3539
+ this.recoveryGeneration += 1;
3540
+ const task = this._task;
3541
+ if (!task) {
3542
+ const error = new Error("Agent turn ended before task metadata was available.");
3543
+ this.activeWaiter?.reject(error);
3544
+ this.activeWaiter = void 0;
3545
+ this.emitError("Failed to finish Agent turn", error);
3546
+ this.setStatus("error");
3547
+ return;
3548
+ }
3549
+ const result = { task, content: this._content, reason };
3550
+ this.emit("turnEnd", result);
3551
+ this.activeWaiter?.resolve(result);
3552
+ this.activeWaiter = void 0;
3553
+ this.setStatus("idle");
3554
+ this.flushQueue();
3555
+ }
3556
+ failTurn(error) {
3557
+ if (this.cancelTimer) clearTimeout(this.cancelTimer);
3558
+ this.cancelTimer = null;
3559
+ this.recoveryGeneration += 1;
3560
+ this.activeWaiter?.reject(error);
3561
+ this.activeWaiter = void 0;
3562
+ this.setStatus("idle");
3563
+ this.flushQueue();
3564
+ }
3565
+ failLiveChannel(observed, waiterError) {
3566
+ this.recoveryGeneration += 1;
3567
+ this.emitError("Agent live channel failed", observed);
3568
+ this.activeWaiter?.reject(waiterError);
3569
+ this.activeWaiter = void 0;
3570
+ for (const item of this._queue) item.waiter?.reject(waiterError);
3571
+ this._queue = [];
3572
+ this.emitQueue();
3573
+ this.setStatus("error");
3574
+ }
3575
+ enqueue(text, options, waiter) {
3576
+ if (this._queue.length >= AGENT_QUEUE_LIMIT) {
3577
+ const error = new Error(`Agent message queue is full (maximum ${AGENT_QUEUE_LIMIT}).`);
3578
+ waiter?.reject(error);
3579
+ this.emit("error", { error: error.message });
3580
+ return void 0;
3581
+ }
3582
+ const id = `q-${++this.queueSequence}`;
3583
+ this._queue = [
3584
+ ...this._queue,
3585
+ { id, text, createdAt: Date.now(), ...options, ...waiter ? { waiter } : {} }
3586
+ ];
3587
+ this.emitQueue();
3588
+ return id;
3589
+ }
3590
+ flushQueue() {
3591
+ if (this.isBusy()) return;
3592
+ let next = this._queue[0];
3593
+ while (next?.waiter?.settled) {
3594
+ this._queue = this._queue.slice(1);
3595
+ next = this._queue[0];
3596
+ }
3597
+ if (!next) {
3598
+ this.emitQueue();
3599
+ return;
3600
+ }
3601
+ this._queue = this._queue.slice(1);
3602
+ this.emitQueue();
3603
+ this.startDispatch(
3604
+ next.text,
3605
+ {
3606
+ ...next.agentType ? { agentType: next.agentType } : {},
3607
+ ...next.reasoningEffort ? { reasoningEffort: next.reasoningEffort } : {}
3608
+ },
3609
+ next.waiter
3610
+ );
3611
+ }
3612
+ createWaiter(options) {
3613
+ let resolvePromise;
3614
+ let rejectPromise;
3615
+ let timer;
3616
+ let abortListener;
3617
+ const waiter = {
3618
+ promise: new Promise((resolve, reject) => {
3619
+ resolvePromise = resolve;
3620
+ rejectPromise = reject;
3621
+ }),
3622
+ settled: false,
3623
+ resolve: (result) => {
3624
+ if (waiter.settled) return;
3625
+ waiter.settled = true;
3626
+ waiter.cleanup();
3627
+ resolvePromise(result);
3628
+ },
3629
+ reject: (error) => {
3630
+ if (waiter.settled) return;
3631
+ waiter.settled = true;
3632
+ waiter.cleanup();
3633
+ if (waiter.queueId) this.removeQueuedWaiter(waiter.queueId);
3634
+ rejectPromise(error);
3635
+ },
3636
+ cleanup: () => {
3637
+ if (timer) clearTimeout(timer);
3638
+ if (abortListener) options.signal?.removeEventListener("abort", abortListener);
3639
+ }
3640
+ };
3641
+ if (options.timeoutMs !== void 0) {
3642
+ if (!Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0) {
3643
+ waiter.reject(new Error("Agent turn timeoutMs must be a positive number."));
3644
+ return waiter;
3645
+ }
3646
+ timer = setTimeout(
3647
+ () => waiter.reject(new Error(`Agent turn timed out after ${options.timeoutMs} ms.`)),
3648
+ options.timeoutMs
3649
+ );
3650
+ }
3651
+ if (options.signal) {
3652
+ abortListener = () => waiter.reject(options.signal?.reason ?? new Error("Agent turn aborted."));
3653
+ if (options.signal.aborted) abortListener();
3654
+ else options.signal.addEventListener("abort", abortListener, { once: true });
3655
+ }
3656
+ return waiter;
3657
+ }
3658
+ removeQueuedWaiter(id) {
3659
+ const size = this._queue.length;
3660
+ this._queue = this._queue.filter((item) => item.id !== id);
3661
+ if (this._queue.length !== size) this.emitQueue();
3662
+ }
3663
+ emitQueue() {
3664
+ this.emit("queueChange", { queue: this.queue });
3665
+ }
3666
+ emitError(prefix, error) {
3667
+ const code = errorCode(error);
3668
+ this.emit("error", {
3669
+ ...code ? { code } : {},
3670
+ error: `${prefix}: ${errorMessage(error)}`
3671
+ });
3672
+ }
3673
+ setStatus(status) {
3674
+ if (this._status === status) return;
3675
+ this._status = status;
3676
+ this.emit("statusChange", { status });
3677
+ }
3678
+ requireOpen() {
3679
+ if (this.isClosed()) throw new Error("Agent task session is closed.");
3680
+ }
3681
+ isClosed() {
3682
+ return this._status === "closed";
3683
+ }
3684
+ isBusy() {
3685
+ return this.dispatching || this._status === "streaming" || this._status === "cancelled";
3686
+ }
3687
+ emit(event, payload) {
3688
+ const listeners = this.listeners.get(event);
3689
+ for (const listener of listeners ?? []) {
3690
+ try {
3691
+ listener(payload);
3692
+ } catch {
3693
+ }
3694
+ }
3695
+ }
3696
+ };
428
3697
  // Annotate the CommonJS export names for ESM import in node:
429
3698
  0 && (module.exports = {
3699
+ AgentTaskTurnError,
430
3700
  SdkCoreConfigurationError,
431
3701
  SdkCoreResponseError,
3702
+ createAgentConnectionsModule,
3703
+ createAgentCredentialsModule,
3704
+ createAgentTaskSessionManager,
3705
+ createAgentTasksModule,
3706
+ createAgentsModule,
3707
+ createAppsModule,
432
3708
  createAuthModule,
3709
+ createContextModule,
3710
+ createCustomQueriesModule,
3711
+ createDataSourcesModule,
433
3712
  createEntitiesModule,
3713
+ createFunctionsAdminModule,
434
3714
  createFunctionsModule,
3715
+ createImportsModule,
3716
+ createIntegrationAdminModule,
435
3717
  createIntegrationModule,
3718
+ createIntegrationResourcesModule,
3719
+ createIntegrationTemplatesModule,
3720
+ createMembersModule,
3721
+ createMessengerModule,
3722
+ createPublicFunctionsModule,
436
3723
  createQueriesModule,
3724
+ createSchemaModule,
437
3725
  createSdkCore,
3726
+ createSqlModule,
3727
+ createWorkflowsModule,
438
3728
  defaultSdkCoreErrorFactory,
439
3729
  encodePathSegment,
440
3730
  expectEmpty,
3731
+ expectLegacyPage,
3732
+ expectNullableObject,
441
3733
  expectObject,
442
- expectObjectArray
3734
+ expectObjectArray,
3735
+ expectPage,
3736
+ expectStringArray,
3737
+ toAgentTimelineItem,
3738
+ withAgentTaskSessions
443
3739
  });