@gravity-rail/sdk 0.7.2 → 0.7.4

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.js CHANGED
@@ -95,6 +95,7 @@ import {
95
95
  areDependenciesSatisfied,
96
96
  canPreviewVoice,
97
97
  clearRegistry,
98
+ createWorkspaceClient,
98
99
  decodePermissions,
99
100
  encodePermissions,
100
101
  eventRuleActionParams,
@@ -121,7 +122,7 @@ import {
121
122
  requiresAssistantParticipant,
122
123
  usesBuiltinAssistant,
123
124
  validateFeatureDependencies
124
- } from "./chunk-WXSLDWIA.js";
125
+ } from "./chunk-ANY7WLOD.js";
125
126
  import {
126
127
  AttendeeResponseStatus,
127
128
  AttendeeStatus,
@@ -136,6 +137,1282 @@ import {
136
137
  DataTypeRecordScope,
137
138
  IndexStatus
138
139
  } from "./chunk-QS6ZRQUZ.js";
140
+
141
+ // src/workspace-builder/resource.ts
142
+ function isRecord(value) {
143
+ return !!value && typeof value === "object" && !Array.isArray(value);
144
+ }
145
+ function isPlainRecord(value) {
146
+ if (!isRecord(value)) return false;
147
+ const prototype = Object.getPrototypeOf(value);
148
+ return prototype === Object.prototype || prototype === null;
149
+ }
150
+ function slugify(name) {
151
+ return name.toLowerCase().replaceAll(" ", "_").replaceAll("-", "_");
152
+ }
153
+ var WorkspaceBuilderResource = class {
154
+ _id;
155
+ _uuid;
156
+ _created = false;
157
+ _existed = false;
158
+ matchKey() {
159
+ return void 0;
160
+ }
161
+ adopt(existing) {
162
+ this._id = existing.id;
163
+ this._uuid = existing.uuid;
164
+ this._existed = true;
165
+ }
166
+ };
167
+ function resolveRefs(params) {
168
+ return resolveRefValue(params);
169
+ }
170
+ function resolveRefValue(value) {
171
+ if (value instanceof WorkspaceBuilderResource) return value._uuid;
172
+ if (Array.isArray(value)) return value.map(resolveRefValue);
173
+ if (!isPlainRecord(value)) return value;
174
+ const out = {};
175
+ for (const [key, nestedValue] of Object.entries(value)) {
176
+ out[key] = resolveRefValue(nestedValue);
177
+ }
178
+ return out;
179
+ }
180
+
181
+ // src/workspace-builder/automation.ts
182
+ var MemberFilterBuilder = class extends WorkspaceBuilderResource {
183
+ constructor(name, options = {}) {
184
+ super();
185
+ this.name = name;
186
+ this.description = options.description ?? "";
187
+ }
188
+ description;
189
+ rules = [];
190
+ addRule(objectType, filterType, options = {}) {
191
+ this.rules.push({
192
+ objectType,
193
+ filterType,
194
+ ...options.objectIds ? { objectIds: options.objectIds } : {},
195
+ ...options.query ? { query: options.query } : {}
196
+ });
197
+ return this;
198
+ }
199
+ planLine() {
200
+ return `MemberFilter: ${this.name}${this.rules.length ? ` (${this.rules.length} rules)` : ""}`;
201
+ }
202
+ async apply(client) {
203
+ const payload = {
204
+ name: this.name,
205
+ description: this.description,
206
+ rules: this.rules
207
+ };
208
+ const result = await client.createMemberFilter(payload);
209
+ this._id = result.id;
210
+ this._uuid = result.uuid;
211
+ this._created = true;
212
+ }
213
+ };
214
+ var RoutineBuilder = class extends WorkspaceBuilderResource {
215
+ constructor(name, cronSchedule = "", options = {}) {
216
+ super();
217
+ this.name = name;
218
+ this.cronSchedule = cronSchedule;
219
+ this.active = options.active ?? false;
220
+ this.description = options.description ?? "";
221
+ }
222
+ active;
223
+ description;
224
+ rules = [];
225
+ addRule(actionType, options = {}) {
226
+ this.rules.push({
227
+ actionType,
228
+ workflow: options.workflow,
229
+ memberFilter: options.memberFilter,
230
+ actionParams: options.actionParams ?? {}
231
+ });
232
+ return this;
233
+ }
234
+ planLine() {
235
+ const parts = [
236
+ ...this.cronSchedule ? [`cron=${this.cronSchedule}`] : [],
237
+ ...this.rules.length ? [`${this.rules.length} rules`] : [],
238
+ this.active ? "active" : "inactive"
239
+ ];
240
+ return `Routine: ${this.name} (${parts.join(", ")})`;
241
+ }
242
+ async apply(client) {
243
+ const eventRules = this.rules.map((rule) => {
244
+ const actionParams = { ...rule.actionParams };
245
+ if (rule.workflow?._id !== void 0) actionParams.workflowId = rule.workflow._id;
246
+ if (rule.memberFilter?._id !== void 0)
247
+ actionParams.memberFilterId = rule.memberFilter._id;
248
+ return {
249
+ uuid: crypto.randomUUID(),
250
+ objectType: "routine" /* ROUTINE */,
251
+ eventType: "routine:triggered" /* ROUTINE_TRIGGERED */,
252
+ actionType: rule.actionType,
253
+ actionParams,
254
+ active: true
255
+ };
256
+ });
257
+ const payload = {
258
+ name: this.name,
259
+ cronString: this.cronSchedule,
260
+ scheduleMode: this.cronSchedule ? "CRON" : void 0,
261
+ scheduleEnabled: this.active,
262
+ ...this.description ? { description: this.description } : {},
263
+ ...eventRules.length ? { eventRules } : {}
264
+ };
265
+ const result = await client.createRoutine(payload);
266
+ this._id = result.id;
267
+ this._uuid = result.uuid;
268
+ this._created = true;
269
+ }
270
+ };
271
+ var NotificationRuleBuilder = class extends WorkspaceBuilderResource {
272
+ constructor(name, options = {}) {
273
+ super();
274
+ this.name = name;
275
+ this.noticeType = options.noticeType ?? options.notice_type ?? name;
276
+ this.memberId = options.memberId ?? options.member_id;
277
+ this.workflow = options.workflow;
278
+ this.prompt = options.prompt ?? options.message;
279
+ this.notifySms = Boolean(options.notifySms ?? options.notify_sms);
280
+ this.notifyEmail = Boolean(options.notifyEmail ?? options.notify_email);
281
+ this.notifyVoice = Boolean(options.notifyVoice ?? options.notify_voice);
282
+ }
283
+ noticeType;
284
+ memberId;
285
+ workflow;
286
+ prompt;
287
+ notifySms;
288
+ notifyEmail;
289
+ notifyVoice;
290
+ planLine() {
291
+ const parts = [];
292
+ if (this.memberId !== void 0) parts.push(`memberId=${this.memberId}`);
293
+ if (this.workflow) parts.push(`workflow='${this.workflow.name}'`);
294
+ return `NotificationRule: ${this.name}${parts.length ? ` (${parts.join(", ")})` : ""}`;
295
+ }
296
+ async apply(client) {
297
+ if (this.memberId === void 0) {
298
+ throw new Error(`Notification rule '${this.name}' requires memberId`);
299
+ }
300
+ const payload = {
301
+ noticeType: this.noticeType,
302
+ memberId: this.memberId,
303
+ workflowId: this.workflow?._id,
304
+ prompt: this.prompt ?? null,
305
+ notifySms: this.notifySms,
306
+ notifyEmail: this.notifyEmail,
307
+ notifyVoice: this.notifyVoice
308
+ };
309
+ const result = await client.createNotificationRule(payload);
310
+ this._id = result.id;
311
+ this._created = true;
312
+ }
313
+ };
314
+
315
+ // src/workspace-builder/forms.ts
316
+ function normalizeOptions(options) {
317
+ if (options.length === 0) return [];
318
+ const first = options[0];
319
+ if (isRecord(first)) return options;
320
+ if (Array.isArray(first)) {
321
+ return options.map((entry) => ({ label: String(entry[0]), value: entry[1] }));
322
+ }
323
+ return options.map((option) => ({ label: String(option), value: String(option) }));
324
+ }
325
+ function createFieldDraft(fieldType, name, slug, options = {}) {
326
+ return {
327
+ name,
328
+ slug,
329
+ fieldType,
330
+ required: Boolean(options.required),
331
+ order: options.order ?? 0,
332
+ ...options.description ? { description: options.description } : {},
333
+ ...options.choices ? { options: options.choices } : {},
334
+ ...options.cel ? { celFunction: options.cel } : {}
335
+ };
336
+ }
337
+ var FormBuilder = class extends WorkspaceBuilderResource {
338
+ name;
339
+ slug;
340
+ description;
341
+ prompt;
342
+ collection;
343
+ fields = [];
344
+ eventRules = [];
345
+ constructor(name, slug, options = {}) {
346
+ super();
347
+ this.name = name;
348
+ this.slug = slug ?? slugify(name);
349
+ this.description = options.description ?? "";
350
+ this.prompt = options.prompt ?? "";
351
+ this.collection = options.collection ?? false;
352
+ for (const field of options.fields ?? []) {
353
+ if (!isRecord(field) || !field.name) continue;
354
+ const choices = field.options ? normalizeOptions(field.options) : void 0;
355
+ this.fields.push(
356
+ createFieldDraft(
357
+ field.fieldType ?? field.field_type ?? "text" /* TEXT */,
358
+ field.name,
359
+ field.slug ?? slugify(field.name),
360
+ {
361
+ required: Boolean(field.required ?? field.isRequired),
362
+ order: field.order ?? 0,
363
+ description: field.description,
364
+ choices
365
+ }
366
+ )
367
+ );
368
+ }
369
+ }
370
+ field(fieldType, name, slug, options = {}) {
371
+ this.fields.push(createFieldDraft(fieldType, name, slug, options));
372
+ return this;
373
+ }
374
+ enumField(name, slug, options, settings = {}) {
375
+ return this.field("enum" /* ENUM */, name, slug, {
376
+ ...settings,
377
+ choices: normalizeOptions(options)
378
+ });
379
+ }
380
+ textField(name, slug, settings = {}) {
381
+ return this.field("text" /* TEXT */, name, slug, settings);
382
+ }
383
+ numberField(name, slug, settings = {}) {
384
+ return this.field("number" /* NUMBER */, name, slug, settings);
385
+ }
386
+ dateField(name, slug, settings = {}) {
387
+ return this.field("date" /* DATE */, name, slug, settings);
388
+ }
389
+ booleanField(name, slug, settings = {}) {
390
+ return this.field("boolean" /* BOOLEAN */, name, slug, settings);
391
+ }
392
+ functionField(name, slug, cel, settings = {}) {
393
+ return this.field("function" /* FUNCTION */, name, slug, { ...settings, cel });
394
+ }
395
+ emailField(name, slug, settings = {}) {
396
+ return this.field("email" /* EMAIL */, name, slug, settings);
397
+ }
398
+ phoneField(name, slug, settings = {}) {
399
+ return this.field("phone" /* PHONE */, name, slug, settings);
400
+ }
401
+ longtextField(name, slug, settings = {}) {
402
+ return this.field("longtext" /* LONGTEXT */, name, slug, settings);
403
+ }
404
+ integerField(name, slug, settings = {}) {
405
+ return this.field("integer" /* INTEGER */, name, slug, settings);
406
+ }
407
+ datetimeField(name, slug, settings = {}) {
408
+ return this.field("datetime" /* DATETIME */, name, slug, settings);
409
+ }
410
+ timeOfDayField(name, slug, settings = {}) {
411
+ return this.field("time_of_day" /* TIME_OF_DAY */, name, slug, settings);
412
+ }
413
+ usZipCodeField(name, slug, settings = {}) {
414
+ return this.field("us_zip_code" /* US_ZIP_CODE */, name, slug, settings);
415
+ }
416
+ arrayField(name, slug, settings = {}) {
417
+ return this.field("array" /* ARRAY */, name, slug, settings);
418
+ }
419
+ objectField(name, slug, settings = {}) {
420
+ return this.field("object" /* OBJECT */, name, slug, settings);
421
+ }
422
+ onRecordCreated(action, params = {}, condition, name) {
423
+ this.eventRules.push({
424
+ eventType: "data_record:created" /* DATA_RECORD_CREATED */,
425
+ actionType: action,
426
+ actionParams: params,
427
+ condition,
428
+ name
429
+ });
430
+ return this;
431
+ }
432
+ onRecordUpdated(action, params = {}, condition, name) {
433
+ this.eventRules.push({
434
+ eventType: "data_record:updated" /* DATA_RECORD_UPDATED */,
435
+ actionType: action,
436
+ actionParams: params,
437
+ condition,
438
+ name
439
+ });
440
+ return this;
441
+ }
442
+ matchKey() {
443
+ return this.slug;
444
+ }
445
+ planLine() {
446
+ return `Form: ${this.name} (slug=${this.slug}, ${this.fields.length} fields)`;
447
+ }
448
+ async apply(client) {
449
+ if (this._existed) return;
450
+ const payload = {
451
+ name: this.name,
452
+ slug: this.slug,
453
+ description: this.description,
454
+ prompt: this.prompt,
455
+ isCollection: this.collection,
456
+ fields: this.fields
457
+ };
458
+ const result = await client.createDataType(payload);
459
+ this._id = result.id;
460
+ this._uuid = result.uuid;
461
+ this._created = true;
462
+ }
463
+ };
464
+ var MemberLabelBuilder = class extends WorkspaceBuilderResource {
465
+ name;
466
+ slug;
467
+ color;
468
+ description;
469
+ constructor(name, slug, color = "8b5cf6", description = "") {
470
+ super();
471
+ this.name = name;
472
+ this.slug = slug ?? slugify(name);
473
+ this.color = color;
474
+ this.description = description;
475
+ }
476
+ matchKey() {
477
+ return this.slug;
478
+ }
479
+ planLine() {
480
+ return `Label: ${this.name} (slug=${this.slug})`;
481
+ }
482
+ async apply(client) {
483
+ if (this._existed) return;
484
+ const payload = {
485
+ name: this.name,
486
+ slug: this.slug,
487
+ color: this.color,
488
+ description: this.description
489
+ };
490
+ const result = await client.createMemberLabel(payload);
491
+ this._id = result.id;
492
+ this._uuid = result.uuid;
493
+ this._created = true;
494
+ }
495
+ };
496
+
497
+ // src/workspace-builder/journeys.ts
498
+ var JourneyStepBuilder = class extends WorkspaceBuilderResource {
499
+ constructor(name, journey, order = 0, workflow, description = "") {
500
+ super();
501
+ this.name = name;
502
+ this.journey = journey;
503
+ this.order = order;
504
+ this.workflow = workflow;
505
+ this.description = description;
506
+ }
507
+ connections = [];
508
+ connectsTo(child, condition, required = false, timeoutSeconds) {
509
+ this.connections.push({ parent: this, child, condition, required, timeoutSeconds });
510
+ return this;
511
+ }
512
+ planLine() {
513
+ return `Step: ${this.name}${this.workflow ? ` -> workflow '${this.workflow.name}'` : ""}`;
514
+ }
515
+ async apply(client) {
516
+ if (this.journey._id === void 0) return;
517
+ const payload = {
518
+ name: this.name,
519
+ description: this.description,
520
+ order: this.order,
521
+ ...this.workflow?._id ? { workflowId: this.workflow._id } : {}
522
+ };
523
+ const result = await client.createStep(this.journey._id, payload);
524
+ this._id = result.id;
525
+ this._uuid = result.uuid;
526
+ this._created = true;
527
+ }
528
+ };
529
+ var JourneyBuilder = class extends WorkspaceBuilderResource {
530
+ constructor(name, options = {}) {
531
+ super();
532
+ this.name = name;
533
+ this.description = options.description ?? "";
534
+ }
535
+ description;
536
+ steps = [];
537
+ goals = [];
538
+ step(name, options = {}) {
539
+ const step = new JourneyStepBuilder(
540
+ name,
541
+ this,
542
+ options.order ?? 0,
543
+ options.workflow,
544
+ options.description ?? ""
545
+ );
546
+ this.steps.push(step);
547
+ return step;
548
+ }
549
+ goal(name, options = {}) {
550
+ this.goals.push({
551
+ name,
552
+ description: options.description ?? "",
553
+ step: options.step,
554
+ completionCel: options.completionCel ?? options.completion_cel,
555
+ value: options.value,
556
+ order: options.order ?? 0
557
+ });
558
+ return this;
559
+ }
560
+ planLine() {
561
+ const parts = [];
562
+ if (this.steps.length) parts.push(`${this.steps.length} steps`);
563
+ if (this.goals.length) parts.push(`${this.goals.length} goals`);
564
+ return `Journey: ${this.name}${parts.length ? ` (${parts.join(", ")})` : ""}`;
565
+ }
566
+ async apply(client) {
567
+ const result = await client.createJourney({
568
+ name: this.name,
569
+ description: this.description
570
+ });
571
+ this._id = result.id;
572
+ this._uuid = result.uuid;
573
+ this._created = true;
574
+ }
575
+ };
576
+ function buildJourneyConnectionPayload(connection) {
577
+ if (!connection.parent._uuid || !connection.child._uuid) return void 0;
578
+ return {
579
+ parentStepUuid: connection.parent._uuid,
580
+ childStepUuid: connection.child._uuid,
581
+ ...connection.condition ? { celCondition: connection.condition } : {},
582
+ ...connection.required ? { required: true } : {},
583
+ ...connection.timeoutSeconds ? { timeoutSeconds: connection.timeoutSeconds } : {}
584
+ };
585
+ }
586
+ function buildJourneyGoalPayload(goal) {
587
+ return {
588
+ name: goal.name,
589
+ description: goal.description,
590
+ order: goal.order,
591
+ ...goal.step?._uuid ? { goalStepUuid: goal.step._uuid } : {},
592
+ ...goal.completionCel ? { completionCel: goal.completionCel } : {},
593
+ ...goal.value !== void 0 ? { value: goal.value } : {}
594
+ };
595
+ }
596
+
597
+ // src/workspace-builder/role-update.ts
598
+ var RoleUpdate = class extends WorkspaceBuilderResource {
599
+ constructor(roleId, workflowIds, dataTypeIds) {
600
+ super();
601
+ this.roleId = roleId;
602
+ this.workflowIds = workflowIds;
603
+ this.dataTypeIds = dataTypeIds;
604
+ }
605
+ planLine() {
606
+ const parts = [];
607
+ if (this.workflowIds) parts.push(`workflows=${JSON.stringify(this.workflowIds)}`);
608
+ if (this.dataTypeIds) parts.push(`dataTypes=${JSON.stringify(this.dataTypeIds)}`);
609
+ return `RoleUpdate: roleId=${this.roleId}${parts.length ? ` (${parts.join(", ")})` : ""}`;
610
+ }
611
+ async apply(client) {
612
+ const payload = {};
613
+ if (this.workflowIds) payload.workflowIds = this.workflowIds;
614
+ if (this.dataTypeIds) payload.dataTypeIds = this.dataTypeIds;
615
+ if (Object.keys(payload).length) await client.updateMemberRole(this.roleId, payload);
616
+ this._id = this.roleId;
617
+ this._created = true;
618
+ }
619
+ };
620
+
621
+ // src/workspace-builder/workflows.ts
622
+ var PERM_KEYS = {
623
+ canRead: "canRead",
624
+ canCreate: "canCreate",
625
+ canEdit: "canEdit",
626
+ can_read: "canRead",
627
+ can_create: "canCreate",
628
+ can_edit: "canEdit"
629
+ };
630
+ var ABILITY_TYPE_MAP = {
631
+ data_access: "integration:data_access",
632
+ file_access: "integration:file_access",
633
+ escalation: "oversight:escalation"
634
+ };
635
+ var AbilityDef = class {
636
+ constructor(abilityType, options = {}) {
637
+ this.abilityType = abilityType;
638
+ this.config = options.config ?? {};
639
+ this.enabled = options.enabled ?? true;
640
+ this.celCondition = options.celCondition ?? options.cel_condition;
641
+ this.form = options.form;
642
+ for (const [inputKey, outputKey] of Object.entries(PERM_KEYS)) {
643
+ if (inputKey in options) this.perms[outputKey] = options[inputKey];
644
+ }
645
+ }
646
+ uuid = crypto.randomUUID();
647
+ config;
648
+ enabled;
649
+ celCondition;
650
+ form;
651
+ perms = {};
652
+ toAbility() {
653
+ const config = { ...this.config };
654
+ if (this.form?._uuid) {
655
+ config.dataTypeUuid = this.form._uuid;
656
+ Object.assign(config, this.perms);
657
+ }
658
+ return {
659
+ uuid: this.uuid,
660
+ abilityType: ABILITY_TYPE_MAP[this.abilityType] ?? this.abilityType,
661
+ config,
662
+ enabled: this.enabled,
663
+ ...this.celCondition ? { celCondition: this.celCondition } : {}
664
+ };
665
+ }
666
+ };
667
+ var TaskBuilder = class extends WorkspaceBuilderResource {
668
+ constructor(name, workflow, prompt = "", start = false, description = "") {
669
+ super();
670
+ this.name = name;
671
+ this.workflow = workflow;
672
+ this.prompt = prompt;
673
+ this.start = start;
674
+ this.description = description;
675
+ }
676
+ transitions = [];
677
+ eventRules = [];
678
+ transitionsTo(child, when, autoNext = false, required = false) {
679
+ if (child === this) {
680
+ throw new Error(`Task '${this.name}' cannot transition to itself`);
681
+ }
682
+ this.transitions.push({ parent: this, child, when, autoNext, required });
683
+ return this;
684
+ }
685
+ onEnter(action, params = {}, name) {
686
+ this.eventRules.push({
687
+ eventType: "task:execute" /* TASK_EXECUTE */,
688
+ actionType: action,
689
+ actionParams: params,
690
+ name
691
+ });
692
+ return this;
693
+ }
694
+ initialMessage(message, suggestions) {
695
+ return this.onEnter("assistant:message", {
696
+ message,
697
+ ...suggestions ? { suggestions } : {}
698
+ });
699
+ }
700
+ planLine() {
701
+ return `Task: ${this.name}${this.start ? " [start]" : ""}`;
702
+ }
703
+ async apply(client) {
704
+ if (this._existed || this.workflow._id === void 0) return;
705
+ const result = await client.createTask({
706
+ workflowId: this.workflow._id,
707
+ name: this.name,
708
+ prompt: this.prompt,
709
+ description: this.description
710
+ });
711
+ this._id = result.id;
712
+ this._uuid = result.uuid;
713
+ this._created = true;
714
+ }
715
+ };
716
+ var WorkflowBuilder = class extends WorkspaceBuilderResource {
717
+ constructor(name, options = {}) {
718
+ super();
719
+ this.name = name;
720
+ this.description = options.description ?? "";
721
+ this.prompt = options.prompt;
722
+ this.agentId = options.agentId ?? options.agent_id;
723
+ }
724
+ description;
725
+ prompt;
726
+ agentId;
727
+ tasks = [];
728
+ abilities = [];
729
+ task(name, options = {}) {
730
+ const task = new TaskBuilder(
731
+ name,
732
+ this,
733
+ options.prompt ?? "",
734
+ options.start ?? false,
735
+ options.description ?? ""
736
+ );
737
+ this.tasks.push(task);
738
+ return task;
739
+ }
740
+ ability(abilityType, options = {}) {
741
+ this.abilities.push(new AbilityDef(abilityType, options));
742
+ return this;
743
+ }
744
+ get startTask() {
745
+ return this.tasks.find((task) => task.start) ?? this.tasks[0];
746
+ }
747
+ matchKey() {
748
+ return this.name;
749
+ }
750
+ adopt(existing) {
751
+ super.adopt(existing);
752
+ const start = this.startTask;
753
+ if (start && existing.startTaskId) {
754
+ start._id = existing.startTaskId;
755
+ start._existed = true;
756
+ }
757
+ }
758
+ planLine() {
759
+ const details = [];
760
+ if (this.tasks.length) details.push(`${this.tasks.length} tasks`);
761
+ if (this.abilities.length) details.push(`${this.abilities.length} abilities`);
762
+ return `Workflow: ${this.name}${details.length ? ` (${details.join(", ")})` : ""}`;
763
+ }
764
+ needsDefaultAgent() {
765
+ return !this._existed && this.agentId === void 0;
766
+ }
767
+ setAgentId(agentId) {
768
+ this.agentId = agentId;
769
+ }
770
+ async apply(client) {
771
+ if (this._existed) return;
772
+ const payload = {
773
+ name: this.name,
774
+ description: this.description,
775
+ createMode: "taskless",
776
+ ...this.prompt ? { prompt: this.prompt } : {},
777
+ ...this.agentId ? { agentId: this.agentId } : {},
778
+ ...this.abilities.length ? { abilities: this.abilities.map((ability) => ability.toAbility()) } : {}
779
+ };
780
+ const result = await client.createWorkflow(payload);
781
+ this._id = result.id;
782
+ this._uuid = result.uuid;
783
+ this._created = true;
784
+ }
785
+ };
786
+ var WORKSPACE_BUILDER_DEFAULT_AGENT_NAME = "Workspace Setup Agent";
787
+ var WORKSPACE_BUILDER_DEFAULT_AGENT_PROMPT = "You help workspace members complete the workflow you are assigned to. Follow the task prompts, collect requested information accurately, and escalate when the workflow asks you to.";
788
+ async function getOrCreateDefaultWorkflowAgent(client) {
789
+ const existingAgents = recordsFromResponse(
790
+ await client.getAgents({ pageSize: 100, includeArchived: false })
791
+ );
792
+ const existing = existingAgents.find((agent) => !agent.isArchived) ?? existingAgents[0];
793
+ if (existing) {
794
+ return {
795
+ id: numberField(existing, "id"),
796
+ name: stringField(existing, "name"),
797
+ created: false
798
+ };
799
+ }
800
+ const roles = recordsFromResponse(await client.getMemberRoles());
801
+ const role = roles.find((candidate) => stringField(candidate, "name").toLowerCase() === "agent") ?? roles[0];
802
+ if (!role) {
803
+ throw new Error("Cannot create default workflow agent: workspace has no member roles");
804
+ }
805
+ const payload = {
806
+ name: WORKSPACE_BUILDER_DEFAULT_AGENT_NAME,
807
+ memberRoleId: numberField(role, "id"),
808
+ chatModelId: DEFAULT_CHAT_MODEL,
809
+ systemPrompt: WORKSPACE_BUILDER_DEFAULT_AGENT_PROMPT
810
+ };
811
+ const created = await client.createAgent(payload);
812
+ return {
813
+ id: created.id,
814
+ name: created.name ?? WORKSPACE_BUILDER_DEFAULT_AGENT_NAME,
815
+ created: true
816
+ };
817
+ }
818
+ function recordsFromResponse(value) {
819
+ if (Array.isArray(value)) return value;
820
+ if (value && typeof value === "object" && Array.isArray(value.items)) {
821
+ return value.items;
822
+ }
823
+ return [];
824
+ }
825
+ function numberField(record, key) {
826
+ const value = record[key];
827
+ if (typeof value !== "number") throw new Error(`Expected numeric ${key}`);
828
+ return value;
829
+ }
830
+ function stringField(record, key) {
831
+ const value = record[key];
832
+ return typeof value === "string" ? value : "";
833
+ }
834
+ var AgentBuilder = class extends WorkspaceBuilderResource {
835
+ constructor(name, options = {}) {
836
+ super();
837
+ this.name = name;
838
+ this.chatModelId = options.chatModelId ?? options.chat_model_id ?? "";
839
+ this.systemPrompt = options.systemPrompt ?? options.system_prompt ?? "";
840
+ this.memberRoleId = options.roleId ?? options.role_id;
841
+ this.tools = options.tools ?? [];
842
+ this.codeInterpreterEnabled = options.codeInterpreterEnabled ?? options.code_interpreter_enabled ?? false;
843
+ }
844
+ chatModelId;
845
+ systemPrompt;
846
+ memberRoleId;
847
+ tools;
848
+ codeInterpreterEnabled;
849
+ planLine() {
850
+ const parts = [];
851
+ if (this.chatModelId) parts.push(`model=${this.chatModelId}`);
852
+ if (this.tools.length) parts.push(`${this.tools.length} tools`);
853
+ return `Agent: ${this.name}${parts.length ? ` (${parts.join(", ")})` : ""}`;
854
+ }
855
+ async apply(client) {
856
+ if (this.memberRoleId === void 0) {
857
+ throw new Error(`Agent '${this.name}' requires memberRoleId`);
858
+ }
859
+ if (!this.chatModelId) {
860
+ throw new Error(`Agent '${this.name}' requires chatModelId`);
861
+ }
862
+ const payload = {
863
+ name: this.name,
864
+ memberRoleId: this.memberRoleId,
865
+ chatModelId: this.chatModelId,
866
+ systemPrompt: this.systemPrompt,
867
+ ...this.tools.length ? { tools: this.tools } : {},
868
+ ...this.codeInterpreterEnabled ? { codeInterpreterEnabled: true } : {}
869
+ };
870
+ const result = await client.createAgent(payload);
871
+ this._id = result.id;
872
+ this._uuid = result.uuid;
873
+ this._created = true;
874
+ }
875
+ };
876
+
877
+ // src/workspace-builder/orchestrator.ts
878
+ var PHASES = /* @__PURE__ */ new Map([
879
+ [FormBuilder, 0],
880
+ [MemberLabelBuilder, 0],
881
+ [AgentBuilder, 1],
882
+ [WorkflowBuilder, 2],
883
+ [TaskBuilder, 3],
884
+ [RoleUpdate, 4],
885
+ [MemberFilterBuilder, 5],
886
+ [RoutineBuilder, 6],
887
+ [NotificationRuleBuilder, 6],
888
+ [JourneyBuilder, 7],
889
+ [JourneyStepBuilder, 8]
890
+ ]);
891
+ var WorkspaceBuilder = class {
892
+ constructor(client) {
893
+ this.client = client;
894
+ }
895
+ resources = [];
896
+ form(name, options = {}) {
897
+ const form = new FormBuilder(name, options.slug, options);
898
+ this.resources.push(form);
899
+ return form;
900
+ }
901
+ workflow(name, options = {}) {
902
+ const workflow = new WorkflowBuilder(name, options);
903
+ this.resources.push(workflow);
904
+ return workflow;
905
+ }
906
+ label(name, options = {}) {
907
+ const label = new MemberLabelBuilder(
908
+ name,
909
+ options.slug,
910
+ options.color,
911
+ options.description ?? ""
912
+ );
913
+ this.resources.push(label);
914
+ return label;
915
+ }
916
+ journey(name, options = {}) {
917
+ const journey = new JourneyBuilder(name, options);
918
+ this.resources.push(journey);
919
+ return journey;
920
+ }
921
+ agent(name, options = {}) {
922
+ const agent = new AgentBuilder(name, options);
923
+ this.resources.push(agent);
924
+ return agent;
925
+ }
926
+ routine(name, cronSchedule = "", options = {}) {
927
+ const routine = new RoutineBuilder(name, cronSchedule, options);
928
+ this.resources.push(routine);
929
+ return routine;
930
+ }
931
+ memberFilter(name, options = {}) {
932
+ const filter = new MemberFilterBuilder(name, options);
933
+ this.resources.push(filter);
934
+ return filter;
935
+ }
936
+ notificationRule(name, options = {}) {
937
+ const rule = new NotificationRuleBuilder(name, options);
938
+ this.resources.push(rule);
939
+ return rule;
940
+ }
941
+ roleUpdate(roleId, workflowIds, dataTypeIds) {
942
+ const update = new RoleUpdate(roleId, workflowIds, dataTypeIds);
943
+ this.resources.push(update);
944
+ return update;
945
+ }
946
+ plan() {
947
+ const resources = this.sortedResources();
948
+ writeLine(`
949
+ ${"=".repeat(50)}`);
950
+ writeLine("Plan");
951
+ writeLine("=".repeat(50));
952
+ for (const resource of resources) {
953
+ writeLine(` + ${resource.planLine()}`);
954
+ }
955
+ const wiring = this.collectWiringSummary(resources);
956
+ if (wiring.length) {
957
+ writeLine("\n Wiring:");
958
+ for (const line of wiring) writeLine(` ${line}`);
959
+ }
960
+ writeLine(`
961
+ Total: ${resources.length} resources, ${wiring.length} connections`);
962
+ writeLine(`${"=".repeat(50)}
963
+ `);
964
+ }
965
+ async preview() {
966
+ const resources = this.sortedResources();
967
+ await this.resolveExisting(resources);
968
+ writeLine(`
969
+ ${"=".repeat(50)}`);
970
+ writeLine("Preview");
971
+ writeLine("=".repeat(50));
972
+ for (const resource of resources) {
973
+ if (resource._existed) {
974
+ writeLine(` = ${resource.planLine()} (exists, id=${resource._id})`);
975
+ } else {
976
+ writeLine(` + ${resource.planLine()}`);
977
+ }
978
+ }
979
+ const wiring = this.collectWiringSummary(resources);
980
+ if (wiring.length) {
981
+ writeLine("\n Wiring:");
982
+ for (const line of wiring) writeLine(` ${line}`);
983
+ }
984
+ const toCreate = resources.filter((resource) => !resource._existed);
985
+ const existing = resources.filter((resource) => resource._existed);
986
+ writeLine(
987
+ `
988
+ Total: ${toCreate.length} to create, ${existing.length} existing, ${wiring.length} connections`
989
+ );
990
+ writeLine(`${"=".repeat(50)}
991
+ `);
992
+ }
993
+ async apply() {
994
+ const resources = this.sortedResources();
995
+ await this.resolveExisting(resources);
996
+ const summary = {};
997
+ writeLine("Applying...");
998
+ await this.ensureWorkflowAgents(resources, summary);
999
+ for (const resource of resources) {
1000
+ try {
1001
+ if (resource._existed) {
1002
+ const key = resourceKey(resource);
1003
+ summary[key] ??= [];
1004
+ summary[key].push(resource._id);
1005
+ writeLine(` Exists ${resource.planLine()} -> id=${resource._id}`);
1006
+ continue;
1007
+ }
1008
+ await resource.apply(this.client);
1009
+ if (resource._created || resource._id !== void 0) {
1010
+ const key = resourceKey(resource);
1011
+ summary[key] ??= [];
1012
+ summary[key].push(resource._id);
1013
+ const startTag = resource instanceof TaskBuilder && resource.start ? " [start]" : "";
1014
+ writeLine(` Created ${resource.planLine()}${startTag} -> id=${resource._id}`);
1015
+ } else {
1016
+ writeLine(` Skipped: ${resource.planLine()}`);
1017
+ }
1018
+ } catch (err) {
1019
+ writeLine(` FAILED: ${resource.planLine()}: ${summarizeError(err)}`);
1020
+ throw new ApplyError(resource, err, summary);
1021
+ }
1022
+ }
1023
+ await this.applyTransitions();
1024
+ await this.applyEventRules(resources);
1025
+ await this.applyJourneyConnections(resources);
1026
+ await this.applyJourneyGoals(resources);
1027
+ const count = Object.values(summary).reduce((total, ids) => total + ids.length, 0);
1028
+ writeLine(`
1029
+ Done! Created ${count} resources.`);
1030
+ return summary;
1031
+ }
1032
+ async resolveExisting(resources) {
1033
+ const formSlugs = new Map(
1034
+ resources.filter((resource) => resource instanceof FormBuilder).map((resource) => [resource.slug, resource])
1035
+ );
1036
+ const labelSlugs = new Map(
1037
+ resources.filter(
1038
+ (resource) => resource instanceof MemberLabelBuilder
1039
+ ).map((resource) => [resource.slug, resource])
1040
+ );
1041
+ const workflowNames = new Map(
1042
+ resources.filter((resource) => resource instanceof WorkflowBuilder).map((resource) => [resource.name, resource])
1043
+ );
1044
+ if (formSlugs.size) {
1045
+ for (const existing of await this.client.getDataTypes()) {
1046
+ if (existing.slug && formSlugs.has(existing.slug)) {
1047
+ formSlugs.get(existing.slug).adopt(existing);
1048
+ }
1049
+ }
1050
+ }
1051
+ if (labelSlugs.size) {
1052
+ for (const existing of await this.client.getMemberLabels()) {
1053
+ if (existing.slug && labelSlugs.has(existing.slug)) {
1054
+ labelSlugs.get(existing.slug).adopt(existing);
1055
+ }
1056
+ }
1057
+ }
1058
+ if (!workflowNames.size) return;
1059
+ for (const existing of await this.client.getWorkflows()) {
1060
+ if (existing.name && workflowNames.has(existing.name)) {
1061
+ workflowNames.get(existing.name).adopt(existing);
1062
+ }
1063
+ }
1064
+ const adoptedWorkflows = resources.filter(
1065
+ (resource) => resource instanceof WorkflowBuilder && resource._existed && resource._id !== void 0
1066
+ );
1067
+ if (!adoptedWorkflows.length) return;
1068
+ const existingTasks = await this.client.getTasks();
1069
+ for (const workflow of adoptedWorkflows) {
1070
+ const workflowTasks = existingTasks.filter((task) => task.workflowId === workflow._id);
1071
+ const taskByName = new Map(workflowTasks.map((task) => [task.name, task]));
1072
+ for (const taskBuilder of workflow.tasks) {
1073
+ const match = taskByName.get(taskBuilder.name);
1074
+ if (match) taskBuilder.adopt(match);
1075
+ }
1076
+ const ids = /* @__PURE__ */ new Map();
1077
+ for (const taskBuilder of workflow.tasks) {
1078
+ if (taskBuilder._id !== void 0) {
1079
+ ids.set(taskBuilder._id, [...ids.get(taskBuilder._id) ?? [], taskBuilder]);
1080
+ }
1081
+ }
1082
+ for (const builders of ids.values()) {
1083
+ if (builders.length <= 1) continue;
1084
+ const nameAdopted = builders.filter((task) => taskByName.has(task.name));
1085
+ for (const task of builders.filter((builder) => !nameAdopted.includes(builder))) {
1086
+ task._id = void 0;
1087
+ task._existed = false;
1088
+ }
1089
+ }
1090
+ }
1091
+ }
1092
+ async ensureWorkflowAgents(resources, summary) {
1093
+ const workflows = resources.filter(
1094
+ (resource) => resource instanceof WorkflowBuilder && resource.needsDefaultAgent()
1095
+ );
1096
+ if (!workflows.length) return;
1097
+ const agent = await getOrCreateDefaultWorkflowAgent(this.client);
1098
+ for (const workflow of workflows) workflow.setAgentId(agent.id);
1099
+ if (agent.created) {
1100
+ summary.agents ??= [];
1101
+ summary.agents.push(agent.id);
1102
+ writeLine(` Created Agent: ${agent.name} -> id=${agent.id}`);
1103
+ } else {
1104
+ writeLine(` Using Agent: ${agent.name || agent.id} -> id=${agent.id}`);
1105
+ }
1106
+ }
1107
+ sortedResources() {
1108
+ const all = [];
1109
+ for (const resource of this.resources) {
1110
+ all.push(resource);
1111
+ if (resource instanceof WorkflowBuilder) {
1112
+ const start = resource.startTask;
1113
+ const tasks = start === void 0 ? resource.tasks : [start, ...resource.tasks.filter((task) => task !== start)];
1114
+ all.push(...tasks);
1115
+ } else if (resource instanceof JourneyBuilder) {
1116
+ all.push(...resource.steps);
1117
+ }
1118
+ }
1119
+ return all.sort(
1120
+ (a, b) => (PHASES.get(a.constructor) ?? 99) - (PHASES.get(b.constructor) ?? 99)
1121
+ );
1122
+ }
1123
+ collectWiringSummary(resources) {
1124
+ const lines = [];
1125
+ for (const resource of resources) {
1126
+ if (resource instanceof TaskBuilder) {
1127
+ for (const transition of resource.transitions) {
1128
+ lines.push(`${transition.parent.name} -> ${transition.child.name}`);
1129
+ }
1130
+ for (const rule of resource.eventRules) {
1131
+ lines.push(`${rule.actionType} on enter '${resource.name}'`);
1132
+ }
1133
+ } else if (resource instanceof FormBuilder) {
1134
+ for (const rule of resource.eventRules) {
1135
+ lines.push(`${rule.actionType} on ${rule.eventType} '${resource.name}'`);
1136
+ }
1137
+ } else if (resource instanceof RoutineBuilder) {
1138
+ for (const rule of resource.rules)
1139
+ lines.push(`${rule.actionType} rule on '${resource.name}'`);
1140
+ } else if (resource instanceof JourneyStepBuilder) {
1141
+ for (const connection of resource.connections) {
1142
+ lines.push(`${connection.parent.name} -> ${connection.child.name}`);
1143
+ }
1144
+ } else if (resource instanceof JourneyBuilder) {
1145
+ for (const goal of resource.goals) lines.push(`Goal: ${goal.name}`);
1146
+ }
1147
+ }
1148
+ return lines;
1149
+ }
1150
+ async applyTransitions() {
1151
+ const parentChildren = /* @__PURE__ */ new Map();
1152
+ for (const resource of this.sortedResources()) {
1153
+ if (!(resource instanceof TaskBuilder)) continue;
1154
+ for (const transition of resource.transitions) {
1155
+ parentChildren.set(transition.parent, [
1156
+ ...parentChildren.get(transition.parent) ?? [],
1157
+ transition
1158
+ ]);
1159
+ }
1160
+ }
1161
+ for (const [parent, transitions] of parentChildren) {
1162
+ if (parent._id === void 0) continue;
1163
+ const childTasks = transitions.flatMap((transition) => {
1164
+ const taskId = transition.child._id;
1165
+ if (taskId === void 0 || taskId === parent._id) return [];
1166
+ return [
1167
+ {
1168
+ taskId,
1169
+ choicePrompt: transition.when,
1170
+ celCondition: null,
1171
+ autoNext: transition.autoNext,
1172
+ required: transition.required
1173
+ }
1174
+ ];
1175
+ });
1176
+ if (!childTasks.length) continue;
1177
+ await this.client.updateTask(parent._id, { childTasks });
1178
+ writeLine(
1179
+ ` Wired: ${parent.name} -> [${transitions.map((tr) => tr.child.name).join(", ")}]`
1180
+ );
1181
+ }
1182
+ }
1183
+ async applyEventRules(resources) {
1184
+ for (const resource of resources) {
1185
+ if (resource instanceof TaskBuilder) {
1186
+ for (const rule of resource.eventRules) {
1187
+ try {
1188
+ const payload = {
1189
+ objectType: "task" /* TASK */,
1190
+ taskId: resource._id,
1191
+ eventType: rule.eventType,
1192
+ actionType: rule.actionType,
1193
+ actionParams: resolveRefs(rule.actionParams),
1194
+ ...rule.name ? { name: rule.name } : {}
1195
+ };
1196
+ await this.applyEventRule(
1197
+ payload,
1198
+ `${rule.actionType} on enter '${resource.name}'`
1199
+ );
1200
+ } catch (err) {
1201
+ handleEventRuleApplyFailure(resource.name, err);
1202
+ }
1203
+ }
1204
+ } else if (resource instanceof FormBuilder) {
1205
+ for (const rule of resource.eventRules) {
1206
+ try {
1207
+ const payload = {
1208
+ objectType: "data_record" /* DATA_RECORD */,
1209
+ dataTypeId: resource._id,
1210
+ eventType: rule.eventType,
1211
+ actionType: rule.actionType,
1212
+ actionParams: resolveRefs(rule.actionParams),
1213
+ ...rule.condition ? { conditions: rule.condition } : {},
1214
+ ...rule.name ? { name: rule.name } : {}
1215
+ };
1216
+ await this.applyEventRule(
1217
+ payload,
1218
+ `${rule.actionType} on ${rule.eventType} '${resource.name}'`
1219
+ );
1220
+ } catch (err) {
1221
+ handleEventRuleApplyFailure(resource.name, err);
1222
+ }
1223
+ }
1224
+ }
1225
+ }
1226
+ }
1227
+ async applyEventRule(payload, label) {
1228
+ const existing = await this.findMatchingEventRule(payload);
1229
+ if (!existing) {
1230
+ await this.client.createEventRule(payload);
1231
+ writeLine(` Wired: ${label}`);
1232
+ return;
1233
+ }
1234
+ const update = eventRuleUpdate(existing, payload);
1235
+ if (Object.keys(update).length) {
1236
+ await this.client.updateEventRule(existing.id, update);
1237
+ writeLine(` Updated: ${label}`);
1238
+ } else {
1239
+ writeLine(` Exists: ${label}`);
1240
+ }
1241
+ }
1242
+ async findMatchingEventRule(payload) {
1243
+ const sourceFilter = eventRuleSourceFilter(payload);
1244
+ const candidates = await this.client.searchEventRules({
1245
+ objectType: payload.objectType,
1246
+ eventType: payload.eventType,
1247
+ actionType: payload.actionType,
1248
+ includeDisabled: true,
1249
+ ...sourceFilter
1250
+ });
1251
+ return candidates.find((candidate) => eventRulesMatch(candidate, payload));
1252
+ }
1253
+ async applyJourneyConnections(resources) {
1254
+ for (const resource of resources) {
1255
+ if (!(resource instanceof JourneyStepBuilder)) continue;
1256
+ for (const connection of resource.connections) {
1257
+ if (resource.journey._id === void 0) continue;
1258
+ const payload = buildJourneyConnectionPayload(connection);
1259
+ if (!payload) continue;
1260
+ await this.client.createConnection(resource.journey._id, payload);
1261
+ writeLine(` Wired: ${connection.parent.name} -> ${connection.child.name}`);
1262
+ }
1263
+ }
1264
+ }
1265
+ async applyJourneyGoals(resources) {
1266
+ for (const resource of resources) {
1267
+ if (!(resource instanceof JourneyBuilder) || resource._id === void 0) continue;
1268
+ for (const goal of resource.goals) {
1269
+ await this.client.createGoal(resource._id, buildJourneyGoalPayload(goal));
1270
+ writeLine(` Created goal: ${goal.name}`);
1271
+ }
1272
+ }
1273
+ }
1274
+ };
1275
+ var ApplyError = class extends Error {
1276
+ constructor(resource, cause, createdSoFar) {
1277
+ super(
1278
+ `Failed creating ${resource.planLine()}: ${summarizeError(cause)}
1279
+ Already created: ${JSON.stringify(
1280
+ createdSoFar
1281
+ )}`
1282
+ );
1283
+ this.resource = resource;
1284
+ this.cause = cause;
1285
+ this.createdSoFar = createdSoFar;
1286
+ }
1287
+ };
1288
+ function resourceKey(resource) {
1289
+ if (resource instanceof RoleUpdate) return "roleUpdates";
1290
+ if (resource instanceof FormBuilder) return "forms";
1291
+ if (resource instanceof MemberLabelBuilder) return "labels";
1292
+ if (resource instanceof WorkflowBuilder) return "workflows";
1293
+ if (resource instanceof TaskBuilder) return "tasks";
1294
+ if (resource instanceof MemberFilterBuilder) return "memberFilters";
1295
+ if (resource instanceof RoutineBuilder) return "routines";
1296
+ if (resource instanceof NotificationRuleBuilder) return "notificationRules";
1297
+ if (resource instanceof JourneyBuilder) return "journeys";
1298
+ if (resource instanceof JourneyStepBuilder) return "journeySteps";
1299
+ if (resource instanceof AgentBuilder) return "agents";
1300
+ return "resources";
1301
+ }
1302
+ var SEARCHABLE_EVENT_RULE_SOURCE_FIELDS = [
1303
+ "taskId",
1304
+ "dataTypeId",
1305
+ "routineId",
1306
+ "workflowId",
1307
+ "journeyStepId"
1308
+ ];
1309
+ var EVENT_RULE_SOURCE_FIELDS = [
1310
+ ...SEARCHABLE_EVENT_RULE_SOURCE_FIELDS,
1311
+ "calendarId",
1312
+ "calendarEventTypeId"
1313
+ ];
1314
+ function eventRuleSourceFilter(payload) {
1315
+ const filter = {};
1316
+ for (const field of SEARCHABLE_EVENT_RULE_SOURCE_FIELDS) {
1317
+ const value = payload[field];
1318
+ if (value !== void 0 && value !== null) {
1319
+ filter[field] = value;
1320
+ }
1321
+ }
1322
+ return filter;
1323
+ }
1324
+ function eventRulesMatch(existing, payload) {
1325
+ if (normalizeString(existing.name) !== normalizeString(payload.name)) return false;
1326
+ if (existing.objectType !== payload.objectType) return false;
1327
+ if (existing.eventType !== payload.eventType) return false;
1328
+ if (existing.actionType !== payload.actionType) return false;
1329
+ for (const field of EVENT_RULE_SOURCE_FIELDS) {
1330
+ if ((existing[field] ?? null) !== (payload[field] ?? null)) return false;
1331
+ }
1332
+ if (normalizeString(payload.name)) return true;
1333
+ if (normalizeString(existing.conditions) !== normalizeString(payload.conditions)) return false;
1334
+ if (!eventRuleValueEqual(existing.actionParams, payload.actionParams ?? null)) return false;
1335
+ if (!eventRuleValueEqual(existing.triggerParams, payload.triggerParams ?? null)) return false;
1336
+ return true;
1337
+ }
1338
+ function eventRuleUpdate(existing, payload) {
1339
+ const update = {};
1340
+ const conditions = payload.conditions ?? null;
1341
+ if (normalizeString(existing.conditions) !== normalizeString(conditions)) {
1342
+ update.conditions = conditions;
1343
+ }
1344
+ const actionParams = payload.actionParams ?? null;
1345
+ if (!eventRuleValueEqual(existing.actionParams, actionParams)) {
1346
+ update.actionParams = payload.actionParams;
1347
+ }
1348
+ const triggerParams = payload.triggerParams ?? null;
1349
+ if (!eventRuleValueEqual(existing.triggerParams, triggerParams)) {
1350
+ update.triggerParams = payload.triggerParams;
1351
+ }
1352
+ const active = payload.active ?? true;
1353
+ if (existing.active !== active) {
1354
+ update.active = active;
1355
+ }
1356
+ const delay = payload.delay ?? 0;
1357
+ if (existing.delay !== delay) {
1358
+ update.delay = delay;
1359
+ }
1360
+ const order = payload.order ?? 0;
1361
+ if (existing.order !== order) {
1362
+ update.order = order;
1363
+ }
1364
+ return update;
1365
+ }
1366
+ function normalizeString(value) {
1367
+ return value ?? "";
1368
+ }
1369
+ function eventRuleValueEqual(left, right) {
1370
+ return JSON.stringify(stableValue(left)) === JSON.stringify(stableValue(right));
1371
+ }
1372
+ function stableValue(value) {
1373
+ if (Array.isArray(value)) return value.map(stableValue);
1374
+ if (!value || typeof value !== "object") return value;
1375
+ const prototype = Object.getPrototypeOf(value);
1376
+ if (prototype !== Object.prototype && prototype !== null) return value;
1377
+ return Object.fromEntries(
1378
+ Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, nested]) => [key, stableValue(nested)])
1379
+ );
1380
+ }
1381
+ function writeLine(message = "") {
1382
+ process.stdout.write(`${message}
1383
+ `);
1384
+ }
1385
+ function handleEventRuleApplyFailure(resourceName, err) {
1386
+ if (hasStatus(err, 403)) {
1387
+ writeLine(
1388
+ ` WARNING: Event rule on '${resourceName}' failed (retry exec() with scopes=['automations:admin'])`
1389
+ );
1390
+ return;
1391
+ }
1392
+ const summary = summarizeError(err);
1393
+ writeLine(` FAILED: Event rule on '${resourceName}': ${summary}`);
1394
+ throw new Error(`Failed wiring event rule on '${resourceName}': ${summary}`);
1395
+ }
1396
+ function summarizeError(err) {
1397
+ if (err instanceof Error) return err.name || "Error";
1398
+ return typeof err;
1399
+ }
1400
+ function hasStatus(err, status) {
1401
+ if (typeof err === "object" && err !== null) {
1402
+ const candidate = err;
1403
+ if (candidate.status === status || candidate.statusCode === status) return true;
1404
+ }
1405
+ const message = err instanceof Error ? err.message : typeof err === "string" ? err : "";
1406
+ return message.includes(String(status));
1407
+ }
1408
+ async function runWorkspaceScript(client, build, mode = "plan") {
1409
+ const workspace = new WorkspaceBuilder(client);
1410
+ await build(workspace);
1411
+ if (mode === "plan") return workspace.plan();
1412
+ if (mode === "preview") return workspace.preview();
1413
+ if (mode === "apply") return workspace.apply();
1414
+ throw new Error(`Unknown mode '${mode}'. Use plan, preview, or apply.`);
1415
+ }
139
1416
  export {
140
1417
  AbilityConfigIssueCode,
141
1418
  AbilityConfigIssueSeverity,
@@ -144,7 +1421,9 @@ export {
144
1421
  AccessGrantStatus,
145
1422
  AccessGrantTrigger,
146
1423
  AccessLevel,
1424
+ AgentBuilder,
147
1425
  ApiError,
1426
+ ApplyError,
148
1427
  AppsApi,
149
1428
  AttendeeResponseStatus,
150
1429
  AttendeeStatus,
@@ -181,19 +1460,25 @@ export {
181
1460
  FhirClientType,
182
1461
  FhirConnectionState,
183
1462
  FhirVendor,
1463
+ FormBuilder,
184
1464
  GravityRailClient,
185
1465
  IndexStatus,
186
1466
  InvitationStatus,
187
1467
  JobPosition,
1468
+ JourneyBuilder,
1469
+ JourneyStepBuilder,
188
1470
  MASKED_SECRET_SENTINEL,
189
1471
  McpServerState,
190
1472
  MemberFeature,
1473
+ MemberFilterBuilder,
1474
+ MemberLabelBuilder,
191
1475
  MemberType,
192
1476
  MenuItemResponseItemType,
193
1477
  MenuItemResponseItemType as MenuItemType,
194
1478
  ModelProvider,
195
1479
  ModelType,
196
1480
  NO_ASSISTANT_PARTICIPANT_CHAT_TYPES,
1481
+ NotificationRuleBuilder,
197
1482
  OIDCAdminConfigViewProviderType,
198
1483
  ORG_ONLY_RESOURCES,
199
1484
  OrgApi,
@@ -219,6 +1504,8 @@ export {
219
1504
  Region,
220
1505
  RegistrationIdentifier,
221
1506
  Resource,
1507
+ RoleUpdate,
1508
+ RoutineBuilder,
222
1509
  SCOPES,
223
1510
  SCOPE_PRESETS,
224
1511
  SMS_DELIVERY_FAILURE_STATUSES,
@@ -238,15 +1525,19 @@ export {
238
1525
  TTS_MODEL_ELEVENLABS_TURBO,
239
1526
  TTS_MODEL_POCKET,
240
1527
  TTS_PREVIEW_PROVIDERS,
1528
+ TaskBuilder,
241
1529
  TemplatesApi,
242
1530
  ToolkitState,
243
1531
  WorkflowAccessWarningResourceType,
1532
+ WorkflowBuilder,
244
1533
  WorkflowAccessWarningResourceType as WorkflowResourceType,
1534
+ WorkspaceBuilder,
245
1535
  WorkspaceFeature,
246
1536
  WorkspaceProvisionStatus,
247
1537
  areDependenciesSatisfied,
248
1538
  canPreviewVoice,
249
1539
  clearRegistry,
1540
+ createWorkspaceClient,
250
1541
  decodePermissions,
251
1542
  encodePermissions,
252
1543
  eventRuleActionParams,
@@ -271,6 +1562,7 @@ export {
271
1562
  isRegistryInitialized,
272
1563
  isSMSDeliveryFailureStatus,
273
1564
  requiresAssistantParticipant,
1565
+ runWorkspaceScript,
274
1566
  usesBuiltinAssistant,
275
1567
  validateFeatureDependencies
276
1568
  };