@gravity-rail/sdk 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/workspace-builder/resource.ts","../src/workspace-builder/automation.ts","../src/workspace-builder/forms.ts","../src/workspace-builder/journeys.ts","../src/workspace-builder/role-update.ts","../src/workspace-builder/workflows.ts","../src/workspace-builder/orchestrator.ts"],"sourcesContent":["import type { GravityRailWorkspaceClient } from '../client/workspace-client';\n\nexport type AnyRecord = Record<string, any>;\nexport type ResourceSummary = Record<string, Array<number | undefined>>;\n\nexport function isRecord(value: unknown): value is AnyRecord {\n return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isPlainRecord(value: unknown): value is AnyRecord {\n if (!isRecord(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nexport function slugify(name: string): string {\n return name.toLowerCase().replaceAll(' ', '_').replaceAll('-', '_');\n}\n\nexport abstract class WorkspaceBuilderResource {\n _id?: number;\n _uuid?: string;\n _created = false;\n _existed = false;\n\n /** Server-assigned numeric id — available after apply() or adopt(). */\n get id(): number {\n if (this._id === undefined) {\n throw new Error(\n `${this.constructor.name} has no id yet — ids are assigned during apply(). ` +\n 'Pass the builder object itself where a reference is needed; refs resolve at apply time.'\n );\n }\n return this._id;\n }\n\n /** Server-assigned uuid — available after apply() or adopt(). */\n get uuid(): string {\n if (this._uuid === undefined) {\n throw new Error(\n `${this.constructor.name} has no uuid yet — uuids are assigned during apply(). ` +\n 'Pass the builder object itself where a reference is needed; refs resolve at apply time.'\n );\n }\n return this._uuid;\n }\n\n abstract planLine(): string;\n abstract apply(client: GravityRailWorkspaceClient): Promise<void>;\n\n matchKey(): string | undefined {\n return undefined;\n }\n\n adopt(existing: AnyRecord): void {\n this._id = existing.id;\n this._uuid = existing.uuid;\n this._existed = true;\n }\n}\n\nexport function resolveRefs(params: AnyRecord): AnyRecord {\n return resolveRefValue(params) as AnyRecord;\n}\n\nfunction resolveRefValue(value: unknown): unknown {\n if (value instanceof WorkspaceBuilderResource) return value._uuid;\n if (Array.isArray(value)) return value.map(resolveRefValue);\n if (!isPlainRecord(value)) return value;\n\n const out: AnyRecord = {};\n for (const [key, nestedValue] of Object.entries(value)) {\n out[key] = resolveRefValue(nestedValue);\n }\n return out;\n}\n","import {\n EventRuleEventType,\n EventRuleObjectType,\n type CreateRoutineRequest,\n type EventRuleActionType,\n type MemberFilterFormData,\n type NotificationRuleCreate,\n} from '../types';\nimport type { QueryPredicate } from '../types/query-engine-types';\nimport type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport type { AnyRecord } from './resource';\nimport { WorkspaceBuilderResource } from './resource';\nimport type { WorkflowBuilder } from './workflows';\n\nexport class MemberFilterBuilder extends WorkspaceBuilderResource {\n readonly description: string;\n /** Query-engine predicate (JSON IR) authored on MemberFilter.query. */\n query: QueryPredicate | null = null;\n\n constructor(\n readonly name: string,\n options: AnyRecord = {}\n ) {\n super();\n this.description = options.description ?? '';\n this.query = options.query ?? null;\n }\n\n /** Set the filter's query-engine predicate (JSON IR). */\n setQuery(query: QueryPredicate): MemberFilterBuilder {\n this.query = query;\n return this;\n }\n\n planLine(): string {\n return `MemberFilter: ${this.name}${this.query ? ' (query)' : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n const payload: MemberFilterFormData = {\n name: this.name,\n description: this.description,\n query: this.query,\n };\n const result = await client.createMemberFilter(payload);\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n\ninterface RoutineRuleDraft {\n actionType: EventRuleActionType | string;\n workflow?: WorkflowBuilder;\n memberFilter?: MemberFilterBuilder;\n actionParams: AnyRecord;\n}\n\nexport class RoutineBuilder extends WorkspaceBuilderResource {\n readonly active: boolean;\n readonly description: string;\n readonly rules: RoutineRuleDraft[] = [];\n\n constructor(\n readonly name: string,\n readonly cronSchedule = '',\n options: AnyRecord = {}\n ) {\n super();\n this.active = options.active ?? false;\n this.description = options.description ?? '';\n }\n\n addRule(\n actionType: string,\n options: {\n workflow?: WorkflowBuilder;\n memberFilter?: MemberFilterBuilder;\n actionParams?: AnyRecord;\n } = {}\n ): RoutineBuilder {\n this.rules.push({\n actionType,\n workflow: options.workflow,\n memberFilter: options.memberFilter,\n actionParams: options.actionParams ?? {},\n });\n return this;\n }\n\n planLine(): string {\n const parts = [\n ...(this.cronSchedule ? [`cron=${this.cronSchedule}`] : []),\n ...(this.rules.length ? [`${this.rules.length} rules`] : []),\n this.active ? 'active' : 'inactive',\n ];\n return `Routine: ${this.name} (${parts.join(', ')})`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n const eventRules = this.rules.map((rule) => {\n const actionParams = { ...rule.actionParams };\n if (rule.workflow?._id !== undefined) actionParams.workflowId = rule.workflow._id;\n if (rule.memberFilter?._id !== undefined)\n actionParams.memberFilterId = rule.memberFilter._id;\n return {\n uuid: crypto.randomUUID(),\n objectType: EventRuleObjectType.ROUTINE,\n eventType: EventRuleEventType.ROUTINE_TRIGGERED,\n actionType: rule.actionType as EventRuleActionType,\n actionParams,\n active: true,\n };\n });\n const payload: CreateRoutineRequest = {\n name: this.name,\n cronString: this.cronSchedule,\n scheduleMode: this.cronSchedule ? 'CRON' : undefined,\n scheduleEnabled: this.active,\n ...(this.description ? { description: this.description } : {}),\n ...(eventRules.length ? { eventRules } : {}),\n };\n const result = await client.createRoutine(payload);\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n\nexport class NotificationRuleBuilder extends WorkspaceBuilderResource {\n readonly noticeType: string;\n readonly memberId: number;\n readonly workflow?: WorkflowBuilder;\n readonly prompt?: string;\n readonly notifySms: boolean;\n readonly notifyEmail: boolean;\n readonly notifyVoice: boolean;\n\n constructor(\n readonly name: string,\n options: AnyRecord = {}\n ) {\n super();\n this.noticeType = options.noticeType ?? options.notice_type ?? name;\n this.memberId = options.memberId ?? options.member_id;\n this.workflow = options.workflow;\n this.prompt = options.prompt ?? options.message;\n this.notifySms = Boolean(options.notifySms ?? options.notify_sms);\n this.notifyEmail = Boolean(options.notifyEmail ?? options.notify_email);\n this.notifyVoice = Boolean(options.notifyVoice ?? options.notify_voice);\n }\n\n planLine(): string {\n const parts: string[] = [];\n if (this.memberId !== undefined) parts.push(`memberId=${this.memberId}`);\n if (this.workflow) parts.push(`workflow='${this.workflow.name}'`);\n return `NotificationRule: ${this.name}${parts.length ? ` (${parts.join(', ')})` : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this.memberId === undefined) {\n throw new Error(`Notification rule '${this.name}' requires memberId`);\n }\n const payload: NotificationRuleCreate = {\n noticeType: this.noticeType,\n memberId: this.memberId,\n workflowId: this.workflow?._id,\n prompt: this.prompt ?? null,\n notifySms: this.notifySms,\n notifyEmail: this.notifyEmail,\n notifyVoice: this.notifyVoice,\n };\n const result = await client.createNotificationRule(payload);\n this._id = result.id;\n this._created = true;\n }\n}\n","import {\n DataFieldType,\n EventRuleEventType,\n type DataTypeFormData,\n type EnumOption,\n type EventRuleActionType,\n type MemberLabelFormData,\n type SchemaField,\n} from '../types';\nimport type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport type { WorkspaceBuilderEventRule } from './event-rules';\nimport { type AnyRecord, isRecord, slugify, WorkspaceBuilderResource } from './resource';\n\n// The client DataFieldType enum and the generated SchemaField fieldType\n// literal union share the same string values, but TS string enums are\n// nominal — convert once at draft construction.\ntype WorkspaceFieldDraft = SchemaField;\n\nfunction normalizeOptions(options: any[]): EnumOption[] {\n if (options.length === 0) return [];\n const first = options[0];\n if (isRecord(first)) return options as EnumOption[];\n if (Array.isArray(first)) {\n return options.map((entry) => ({ label: String(entry[0]), value: entry[1] }));\n }\n return options.map((option) => ({ label: String(option), value: String(option) }));\n}\n\nfunction createFieldDraft(\n fieldType: DataFieldType,\n name: string,\n slug: string,\n options: {\n required?: boolean;\n order?: number;\n description?: string;\n choices?: EnumOption[];\n cel?: string;\n } = {}\n): WorkspaceFieldDraft {\n return {\n name,\n slug,\n fieldType: fieldType as SchemaField['fieldType'],\n required: Boolean(options.required),\n order: options.order ?? 0,\n ...(options.description ? { description: options.description } : {}),\n ...(options.choices ? { options: options.choices } : {}),\n ...(options.cel ? { celFunction: options.cel } : {}),\n };\n}\n\nexport class FormBuilder extends WorkspaceBuilderResource {\n readonly name: string;\n readonly slug: string;\n readonly description: string;\n readonly prompt: string;\n readonly collection: boolean;\n readonly fields: WorkspaceFieldDraft[] = [];\n readonly eventRules: WorkspaceBuilderEventRule[] = [];\n\n constructor(name: string, slug?: string, options: AnyRecord = {}) {\n super();\n this.name = name;\n this.slug = slug ?? slugify(name);\n this.description = options.description ?? '';\n this.prompt = options.prompt ?? '';\n this.collection = options.collection ?? false;\n\n for (const field of options.fields ?? []) {\n if (!isRecord(field) || !field.name) continue;\n const choices = field.options ? normalizeOptions(field.options) : undefined;\n this.fields.push(\n createFieldDraft(\n (field.fieldType ?? field.field_type ?? DataFieldType.TEXT) as DataFieldType,\n field.name,\n field.slug ?? slugify(field.name),\n {\n required: Boolean(field.required ?? field.isRequired),\n order: field.order ?? 0,\n description: field.description,\n choices,\n }\n )\n );\n }\n }\n\n field(\n fieldType: DataFieldType,\n name: string,\n slug: string,\n options: {\n required?: boolean;\n order?: number;\n description?: string;\n choices?: any[];\n cel?: string;\n } = {}\n ): FormBuilder {\n this.fields.push(createFieldDraft(fieldType, name, slug, options));\n return this;\n }\n\n enumField(name: string, slug: string, options: any[], settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.ENUM, name, slug, {\n ...settings,\n choices: normalizeOptions(options),\n });\n }\n\n textField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.TEXT, name, slug, settings);\n }\n\n numberField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.NUMBER, name, slug, settings);\n }\n\n dateField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.DATE, name, slug, settings);\n }\n\n booleanField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.BOOLEAN, name, slug, settings);\n }\n\n functionField(name: string, slug: string, cel: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.FUNCTION, name, slug, { ...settings, cel });\n }\n\n emailField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.EMAIL, name, slug, settings);\n }\n\n phoneField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.PHONE, name, slug, settings);\n }\n\n longtextField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.LONGTEXT, name, slug, settings);\n }\n\n integerField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.INTEGER, name, slug, settings);\n }\n\n datetimeField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.DATETIME, name, slug, settings);\n }\n\n timeOfDayField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.TIME_OF_DAY, name, slug, settings);\n }\n\n usZipCodeField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.US_ZIP_CODE, name, slug, settings);\n }\n\n arrayField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.ARRAY, name, slug, settings);\n }\n\n objectField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.OBJECT, name, slug, settings);\n }\n\n onRecordCreated(\n action: string,\n params: AnyRecord = {},\n condition?: string,\n name?: string\n ): FormBuilder {\n this.eventRules.push({\n eventType: EventRuleEventType.DATA_RECORD_CREATED,\n actionType: action as EventRuleActionType,\n actionParams: params,\n condition,\n name,\n });\n return this;\n }\n\n onRecordUpdated(\n action: string,\n params: AnyRecord = {},\n condition?: string,\n name?: string\n ): FormBuilder {\n this.eventRules.push({\n eventType: EventRuleEventType.DATA_RECORD_UPDATED,\n actionType: action as EventRuleActionType,\n actionParams: params,\n condition,\n name,\n });\n return this;\n }\n\n matchKey(): string {\n return this.slug;\n }\n\n planLine(): string {\n return `Form: ${this.name} (slug=${this.slug}, ${this.fields.length} fields)`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed) return;\n const payload: DataTypeFormData = {\n name: this.name,\n slug: this.slug,\n description: this.description,\n prompt: this.prompt,\n isCollection: this.collection,\n fields: this.fields,\n };\n const result = await client.createDataType(payload);\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n\nexport class MemberLabelBuilder extends WorkspaceBuilderResource {\n readonly name: string;\n readonly slug: string;\n readonly color: string;\n readonly description: string;\n\n constructor(name: string, slug?: string, color = '8b5cf6', description = '') {\n super();\n this.name = name;\n this.slug = slug ?? slugify(name);\n this.color = color;\n this.description = description;\n }\n\n matchKey(): string {\n return this.slug;\n }\n\n planLine(): string {\n return `Label: ${this.name} (slug=${this.slug})`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed) return;\n const payload: MemberLabelFormData = {\n name: this.name,\n slug: this.slug,\n color: this.color,\n description: this.description,\n };\n const result = await client.createMemberLabel(payload);\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n","import type {\n JourneyGoalFormData,\n JourneyStepConnectionFormData,\n JourneyStepFormData,\n} from '../types';\nimport type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport type { AnyRecord } from './resource';\nimport { WorkspaceBuilderResource } from './resource';\n\nexport interface StepConnectionDraft {\n parent: JourneyStepBuilder;\n child: JourneyStepBuilder;\n condition?: string;\n required: boolean;\n timeoutSeconds?: number;\n}\n\nexport interface JourneyGoalDraft {\n name: string;\n description: string;\n step?: JourneyStepBuilder;\n completionCel?: string;\n value?: number;\n order: number;\n}\n\nexport class JourneyStepBuilder extends WorkspaceBuilderResource {\n readonly connections: StepConnectionDraft[] = [];\n\n // journey-decoupling Phase 7: a Journey step no longer links to a Workflow.\n // A step nudges via EventRule actions instead of running a Workflow, so the\n // builder no longer accepts or emits a workflow reference.\n constructor(\n readonly name: string,\n readonly journey: JourneyBuilder,\n readonly order = 0,\n readonly description = ''\n ) {\n super();\n }\n\n connectsTo(\n child: JourneyStepBuilder,\n condition?: string,\n required = false,\n timeoutSeconds?: number\n ): JourneyStepBuilder {\n this.connections.push({ parent: this, child, condition, required, timeoutSeconds });\n return this;\n }\n\n planLine(): string {\n return `Step: ${this.name}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this.journey._id === undefined) return;\n const payload: JourneyStepFormData = {\n name: this.name,\n description: this.description,\n order: this.order,\n };\n const result = await client.createStep(this.journey._id, payload);\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n\nexport class JourneyBuilder extends WorkspaceBuilderResource {\n readonly description: string;\n readonly steps: JourneyStepBuilder[] = [];\n readonly goals: JourneyGoalDraft[] = [];\n\n constructor(\n readonly name: string,\n options: AnyRecord = {}\n ) {\n super();\n this.description = options.description ?? '';\n }\n\n step(name: string, options: AnyRecord = {}): JourneyStepBuilder {\n const step = new JourneyStepBuilder(\n name,\n this,\n options.order ?? 0,\n options.description ?? ''\n );\n this.steps.push(step);\n return step;\n }\n\n goal(name: string, options: AnyRecord = {}): JourneyBuilder {\n this.goals.push({\n name,\n description: options.description ?? '',\n step: options.step,\n completionCel: options.completionCel ?? options.completion_cel,\n value: options.value,\n order: options.order ?? 0,\n });\n return this;\n }\n\n planLine(): string {\n const parts: string[] = [];\n if (this.steps.length) parts.push(`${this.steps.length} steps`);\n if (this.goals.length) parts.push(`${this.goals.length} goals`);\n return `Journey: ${this.name}${parts.length ? ` (${parts.join(', ')})` : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n const result = await client.createJourney({\n name: this.name,\n description: this.description,\n });\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n\nexport function buildJourneyConnectionPayload(\n connection: StepConnectionDraft\n): JourneyStepConnectionFormData | undefined {\n if (!connection.parent._uuid || !connection.child._uuid) return undefined;\n return {\n parentStepUuid: connection.parent._uuid,\n childStepUuid: connection.child._uuid,\n ...(connection.condition ? { celCondition: connection.condition } : {}),\n ...(connection.required ? { required: true } : {}),\n ...(connection.timeoutSeconds ? { timeoutSeconds: connection.timeoutSeconds } : {}),\n };\n}\n\nexport function buildJourneyGoalPayload(goal: JourneyGoalDraft): JourneyGoalFormData {\n return {\n name: goal.name,\n description: goal.description,\n order: goal.order,\n ...(goal.step?._uuid ? { goalStepUuid: goal.step._uuid } : {}),\n ...(goal.completionCel ? { completionCel: goal.completionCel } : {}),\n ...(goal.value !== undefined ? { value: goal.value } : {}),\n };\n}\n","import type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport type { AnyRecord } from './resource';\nimport { WorkspaceBuilderResource } from './resource';\n\nexport class RoleUpdate extends WorkspaceBuilderResource {\n constructor(\n readonly roleId: number,\n readonly workflowIds?: number[],\n readonly dataTypeIds?: number[]\n ) {\n super();\n }\n\n planLine(): string {\n const parts: string[] = [];\n if (this.workflowIds) parts.push(`workflows=${JSON.stringify(this.workflowIds)}`);\n if (this.dataTypeIds) parts.push(`dataTypes=${JSON.stringify(this.dataTypeIds)}`);\n return `RoleUpdate: roleId=${this.roleId}${parts.length ? ` (${parts.join(', ')})` : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n const payload: AnyRecord = {};\n if (this.workflowIds) payload.workflowIds = this.workflowIds;\n if (this.dataTypeIds) payload.dataTypeIds = this.dataTypeIds;\n if (Object.keys(payload).length) await client.updateMemberRole(this.roleId, payload);\n this._id = this.roleId;\n this._created = true;\n }\n}\n","import {\n EventRuleEventType,\n type CreateAgentRequest,\n type EventRuleActionType,\n type WorkflowFormData,\n} from '../types';\nimport type { Ability } from '../types/ability-types';\nimport type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport type { WorkspaceBuilderEventRule } from './event-rules';\nimport type { FormBuilder } from './forms';\nimport { type AnyRecord, WorkspaceBuilderResource } from './resource';\n\nconst PERM_KEYS: Record<string, string> = {\n canRead: 'canRead',\n canCreate: 'canCreate',\n canEdit: 'canEdit',\n can_read: 'canRead',\n can_create: 'canCreate',\n can_edit: 'canEdit',\n};\n\nconst ABILITY_TYPE_MAP: Record<string, string> = {\n data_access: 'integration:data_access',\n file_access: 'integration:file_access',\n escalation: 'oversight:escalation',\n};\n\nclass AbilityDef {\n readonly uuid = crypto.randomUUID();\n readonly config: AnyRecord;\n readonly enabled: boolean;\n readonly celCondition?: string;\n readonly form?: FormBuilder;\n readonly perms: AnyRecord = {};\n\n constructor(\n readonly abilityType: string,\n options: AnyRecord = {}\n ) {\n this.config = options.config ?? {};\n this.enabled = options.enabled ?? true;\n this.celCondition = options.celCondition ?? options.cel_condition;\n this.form = options.form;\n for (const [inputKey, outputKey] of Object.entries(PERM_KEYS)) {\n if (inputKey in options) this.perms[outputKey] = options[inputKey];\n }\n }\n\n toAbility(): Ability {\n const config = { ...this.config };\n if (this.form?._uuid) {\n config.dataTypeUuid = this.form._uuid;\n Object.assign(config, this.perms);\n }\n return {\n uuid: this.uuid,\n abilityType: ABILITY_TYPE_MAP[this.abilityType] ?? this.abilityType,\n config,\n enabled: this.enabled,\n ...(this.celCondition ? { celCondition: this.celCondition } : {}),\n };\n }\n}\n\nexport interface TaskTransition {\n parent: TaskBuilder;\n child: TaskBuilder;\n when: string;\n autoNext: boolean;\n required: boolean;\n celCondition?: string;\n}\n\nexport interface WorkflowBuilderOptions {\n description?: string;\n prompt?: string;\n copyFromAgentId?: number;\n}\n\nexport class TaskBuilder extends WorkspaceBuilderResource {\n readonly transitions: TaskTransition[] = [];\n readonly eventRules: WorkspaceBuilderEventRule[] = [];\n\n constructor(\n readonly name: string,\n readonly workflow: WorkflowBuilder,\n readonly prompt = '',\n readonly start = false,\n readonly description = ''\n ) {\n super();\n }\n\n transitionsTo(\n child: TaskBuilder,\n when: string,\n autoNext = false,\n required = false,\n celCondition?: string\n ): TaskBuilder {\n if (child === this) {\n throw new Error(`Task '${this.name}' cannot transition to itself`);\n }\n this.transitions.push({\n parent: this,\n child,\n when,\n autoNext,\n required,\n celCondition,\n });\n return this;\n }\n\n onEnter(action: string, params: AnyRecord = {}, name?: string): TaskBuilder {\n this.eventRules.push({\n eventType: EventRuleEventType.TASK_EXECUTE,\n actionType: action as EventRuleActionType,\n actionParams: params,\n name,\n });\n return this;\n }\n\n initialMessage(message: string, suggestions?: string[]): TaskBuilder {\n return this.onEnter('assistant:message', {\n message,\n ...(suggestions ? { suggestions } : {}),\n });\n }\n\n planLine(): string {\n return `Task: ${this.name}${this.start ? ' [start]' : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed || this.workflow._id === undefined) return;\n if (this.workflow._draftRevisionId === undefined) {\n // Root id without a draft revision id means the workflow was\n // created/adopted through a path that skipped revision resolution —\n // creating the task would attach it to whatever revision happens to\n // share the number (cross-workflow corruption). Fail loudly.\n throw new Error(\n `Workflow '${this.workflow.name}' has no draft revision id; ` +\n 'cannot create tasks. Tasks attach to a WorkflowRevision, ' +\n 'not the stable workflow root.'\n );\n }\n // Tasks belong to a revision graph — target the DRAFT revision\n // explicitly (edits always land on the draft; publish makes them live).\n const result = await client.createTask({\n workflowRevisionId: this.workflow._draftRevisionId,\n name: this.name,\n prompt: this.prompt,\n description: this.description,\n });\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n\nexport class WorkflowBuilder extends WorkspaceBuilderResource {\n readonly description: string;\n readonly prompt?: string;\n private copyFromAgentId?: number;\n readonly tasks: TaskBuilder[] = [];\n readonly abilities: AbilityDef[] = [];\n /** The DRAFT revision's id — where tasks and graph edits attach.\n * `_id` is the STABLE workflow root id; the two are different entities\n * and (after any publish) different numbers. */\n _draftRevisionId?: number;\n\n constructor(\n readonly name: string,\n options: WorkflowBuilderOptions = {}\n ) {\n super();\n this.description = options.description ?? '';\n this.prompt = options.prompt;\n this.copyFromAgentId = options.copyFromAgentId;\n }\n\n task(name: string, options: AnyRecord = {}): TaskBuilder {\n const task = new TaskBuilder(\n name,\n this,\n options.prompt ?? '',\n options.start ?? false,\n options.description ?? ''\n );\n this.tasks.push(task);\n return task;\n }\n\n ability(abilityType: string, options: AnyRecord = {}): WorkflowBuilder {\n this.abilities.push(new AbilityDef(abilityType, options));\n return this;\n }\n\n get startTask(): TaskBuilder | undefined {\n return this.tasks.find((task) => task.start) ?? this.tasks[0];\n }\n\n matchKey(): string {\n return this.name;\n }\n\n adopt(existing: AnyRecord): void {\n // Accepts the WorkflowDetail composition ({ workflow, draftRevision,\n // activeRevision }) — the orchestrator fetches it per matched name.\n // Root facts (id/uuid) live on `workflow`; graph facts (startTaskId)\n // live on the draft revision.\n const root = (existing.workflow ?? existing) as AnyRecord;\n super.adopt(root);\n const draft = existing.draftRevision as AnyRecord | undefined;\n this._draftRevisionId = (draft?.id ?? root.draftRevisionId) as number | undefined;\n const start = this.startTask;\n const startTaskId = draft?.startTaskId as number | undefined;\n if (start && startTaskId) {\n start._id = startTaskId;\n start._existed = true;\n }\n }\n\n planLine(): string {\n const details: string[] = [];\n if (this.tasks.length) details.push(`${this.tasks.length} tasks`);\n if (this.abilities.length) details.push(`${this.abilities.length} abilities`);\n return `Workflow: ${this.name}${details.length ? ` (${details.join(', ')})` : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed) return;\n const payload: WorkflowFormData = {\n name: this.name,\n description: this.description,\n createMode: 'taskless',\n ...(this.prompt ? { prompt: this.prompt } : {}),\n ...(this.copyFromAgentId ? { copyFromAgentId: this.copyFromAgentId } : {}),\n ...(this.abilities.length\n ? { abilities: this.abilities.map((ability) => ability.toAbility()) }\n : {}),\n };\n const result = await client.createWorkflow(payload);\n this._id = result.workflow.id;\n this._uuid = result.workflow.uuid;\n // Tasks attach to the draft revision, never the root — keep its id.\n this._draftRevisionId = result.draftRevision.id;\n this._created = true;\n }\n}\n\nexport class AgentBuilder extends WorkspaceBuilderResource {\n readonly chatModelId: string;\n readonly systemPrompt: string;\n readonly memberRoleId?: number;\n readonly tools: string[];\n readonly codeInterpreterEnabled: boolean;\n\n constructor(\n readonly name: string,\n options: AnyRecord = {}\n ) {\n super();\n this.chatModelId = options.chatModelId ?? options.chat_model_id ?? '';\n this.systemPrompt = options.systemPrompt ?? options.system_prompt ?? '';\n this.memberRoleId = options.roleId ?? options.role_id;\n this.tools = options.tools ?? [];\n this.codeInterpreterEnabled =\n options.codeInterpreterEnabled ?? options.code_interpreter_enabled ?? false;\n }\n\n planLine(): string {\n const parts: string[] = [];\n if (this.chatModelId) parts.push(`model=${this.chatModelId}`);\n if (this.tools.length) parts.push(`${this.tools.length} tools`);\n return `Agent: ${this.name}${parts.length ? ` (${parts.join(', ')})` : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this.memberRoleId === undefined) {\n throw new Error(`Agent '${this.name}' requires memberRoleId`);\n }\n if (!this.chatModelId) {\n throw new Error(`Agent '${this.name}' requires chatModelId`);\n }\n\n const payload: CreateAgentRequest = {\n name: this.name,\n memberRoleId: this.memberRoleId,\n chatModelId: this.chatModelId,\n systemPrompt: this.systemPrompt,\n ...(this.tools.length ? { tools: this.tools } : {}),\n ...(this.codeInterpreterEnabled ? { codeInterpreterEnabled: true } : {}),\n };\n const result = await client.createAgent(payload);\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n","import {\n EventRuleObjectType,\n type EventRule,\n type EventRuleFormData,\n type UpdateEventRuleFormData,\n} from '../types';\nimport { ApiError } from '../api/base';\nimport type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport { MemberFilterBuilder, NotificationRuleBuilder, RoutineBuilder } from './automation';\nimport { FormBuilder, MemberLabelBuilder } from './forms';\nimport {\n buildJourneyConnectionPayload,\n buildJourneyGoalPayload,\n JourneyBuilder,\n JourneyStepBuilder,\n} from './journeys';\nimport {\n type AnyRecord,\n type ResourceSummary,\n resolveRefs,\n WorkspaceBuilderResource,\n} from './resource';\nimport { RoleUpdate } from './role-update';\nimport {\n AgentBuilder,\n TaskBuilder,\n type TaskTransition,\n WorkflowBuilder,\n type WorkflowBuilderOptions,\n} from './workflows';\n\nconst PHASES = new Map<Function, number>([\n [FormBuilder, 0],\n [MemberLabelBuilder, 0],\n [AgentBuilder, 1],\n [WorkflowBuilder, 2],\n [TaskBuilder, 3],\n [RoleUpdate, 4],\n [MemberFilterBuilder, 5],\n [RoutineBuilder, 6],\n [NotificationRuleBuilder, 6],\n [JourneyBuilder, 7],\n [JourneyStepBuilder, 8],\n]);\n\nexport class WorkspaceBuilder {\n readonly resources: WorkspaceBuilderResource[] = [];\n\n constructor(readonly client: GravityRailWorkspaceClient) {}\n\n form(name: string, options: AnyRecord & { slug?: string } = {}): FormBuilder {\n const form = new FormBuilder(name, options.slug, options);\n this.resources.push(form);\n return form;\n }\n\n workflow(name: string, options: WorkflowBuilderOptions = {}): WorkflowBuilder {\n const workflow = new WorkflowBuilder(name, options);\n this.resources.push(workflow);\n return workflow;\n }\n\n label(\n name: string,\n options: { slug?: string; color?: string; description?: string } = {}\n ): MemberLabelBuilder {\n const label = new MemberLabelBuilder(\n name,\n options.slug,\n options.color,\n options.description ?? ''\n );\n this.resources.push(label);\n return label;\n }\n\n journey(name: string, options: AnyRecord = {}): JourneyBuilder {\n const journey = new JourneyBuilder(name, options);\n this.resources.push(journey);\n return journey;\n }\n\n agent(name: string, options: AnyRecord = {}): AgentBuilder {\n const agent = new AgentBuilder(name, options);\n this.resources.push(agent);\n return agent;\n }\n\n routine(name: string, cronSchedule = '', options: AnyRecord = {}): RoutineBuilder {\n const routine = new RoutineBuilder(name, cronSchedule, options);\n this.resources.push(routine);\n return routine;\n }\n\n memberFilter(name: string, options: AnyRecord = {}): MemberFilterBuilder {\n const filter = new MemberFilterBuilder(name, options);\n this.resources.push(filter);\n return filter;\n }\n\n notificationRule(name: string, options: AnyRecord = {}): NotificationRuleBuilder {\n const rule = new NotificationRuleBuilder(name, options);\n this.resources.push(rule);\n return rule;\n }\n\n roleUpdate(roleId: number, workflowIds?: number[], dataTypeIds?: number[]): RoleUpdate {\n const update = new RoleUpdate(roleId, workflowIds, dataTypeIds);\n this.resources.push(update);\n return update;\n }\n\n plan(): void {\n const resources = this.sortedResources();\n writeLine(`\\n${'='.repeat(50)}`);\n writeLine('Plan');\n writeLine('='.repeat(50));\n for (const resource of resources) {\n writeLine(` + ${resource.planLine()}`);\n }\n const wiring = this.collectWiringSummary(resources);\n if (wiring.length) {\n writeLine('\\n Wiring:');\n for (const line of wiring) writeLine(` ${line}`);\n }\n writeLine(`\\n Total: ${resources.length} resources, ${wiring.length} connections`);\n writeLine(`${'='.repeat(50)}\\n`);\n }\n\n async preview(): Promise<void> {\n const resources = this.sortedResources();\n await this.resolveExisting(resources);\n\n writeLine(`\\n${'='.repeat(50)}`);\n writeLine('Preview');\n writeLine('='.repeat(50));\n for (const resource of resources) {\n if (resource._existed) {\n writeLine(` = ${resource.planLine()} (exists, id=${resource._id})`);\n } else {\n writeLine(` + ${resource.planLine()}`);\n }\n }\n const wiring = this.collectWiringSummary(resources);\n if (wiring.length) {\n writeLine('\\n Wiring:');\n for (const line of wiring) writeLine(` ${line}`);\n }\n const toCreate = resources.filter((resource) => !resource._existed);\n const existing = resources.filter((resource) => resource._existed);\n writeLine(\n `\\n Total: ${toCreate.length} to create, ${existing.length} existing, ${wiring.length} connections`\n );\n writeLine(`${'='.repeat(50)}\\n`);\n }\n\n async apply(): Promise<ResourceSummary> {\n const resources = this.sortedResources();\n await this.resolveExisting(resources);\n const summary: ResourceSummary = {};\n\n writeLine('Applying...');\n for (const resource of resources) {\n try {\n if (resource._existed) {\n const key = resourceKey(resource);\n summary[key] ??= [];\n summary[key]!.push(resource._id);\n writeLine(` Exists ${resource.planLine()} -> id=${resource._id}`);\n continue;\n }\n\n await resource.apply(this.client);\n if (resource._created || resource._id !== undefined) {\n const key = resourceKey(resource);\n summary[key] ??= [];\n summary[key]!.push(resource._id);\n const startTag = resource instanceof TaskBuilder && resource.start ? ' [start]' : '';\n writeLine(` Created ${resource.planLine()}${startTag} -> id=${resource._id}`);\n } else {\n writeLine(` Skipped: ${resource.planLine()}`);\n }\n } catch (err) {\n writeLine(formatApplyFailureLine(resource, err));\n throw new ApplyError(resource, err, summary);\n }\n }\n\n await this.applyTransitions();\n await this.applyEventRules(resources);\n await this.applyJourneyConnections(resources);\n await this.applyJourneyGoals(resources);\n\n const count = Object.values(summary).reduce((total, ids) => total + ids.length, 0);\n writeLine(`\\nDone! Created ${count} resources.`);\n return summary;\n }\n\n private async resolveExisting(resources: WorkspaceBuilderResource[]): Promise<void> {\n const formSlugs = new Map(\n resources\n .filter((resource): resource is FormBuilder => resource instanceof FormBuilder)\n .map((resource) => [resource.slug, resource])\n );\n const labelSlugs = new Map(\n resources\n .filter(\n (resource): resource is MemberLabelBuilder => resource instanceof MemberLabelBuilder\n )\n .map((resource) => [resource.slug, resource])\n );\n const workflowNames = new Map(\n resources\n .filter((resource): resource is WorkflowBuilder => resource instanceof WorkflowBuilder)\n .map((resource) => [resource.name, resource])\n );\n\n if (formSlugs.size) {\n for (const existing of await this.client.getDataTypes()) {\n if (existing.slug && formSlugs.has(existing.slug)) {\n formSlugs.get(existing.slug)!.adopt(existing);\n }\n }\n }\n if (labelSlugs.size) {\n for (const existing of await this.client.getMemberLabels()) {\n if (existing.slug && labelSlugs.has(existing.slug)) {\n labelSlugs.get(existing.slug)!.adopt(existing);\n }\n }\n }\n if (!workflowNames.size) return;\n\n const existingWorkflows = await this.client.getWorkflows();\n for (const { workflow: existing } of existingWorkflows.items) {\n if (existing.name && workflowNames.has(existing.name)) {\n // List rows carry only the root + active-revision summary. Tasks\n // and startTaskId live on the DRAFT revision, so fetch the detail\n // composition for adoption (root ids and revision ids are\n // different entities — matching tasks by root id attaches them to\n // the wrong workflow once any workflow has been published).\n const detail = await this.client.getWorkflow(existing.id);\n workflowNames.get(existing.name)!.adopt(detail);\n }\n }\n\n const adoptedWorkflows = resources.filter(\n (resource): resource is WorkflowBuilder =>\n resource instanceof WorkflowBuilder && resource._existed && resource._id !== undefined\n );\n if (!adoptedWorkflows.length) return;\n\n const existingTasks = await this.client.getTasks();\n for (const workflow of adoptedWorkflows) {\n // Tasks belong to a revision graph — match against the adopted\n // workflow's DRAFT revision id (task.workflowRevisionId), falling\n // back to the legacy field for older payloads.\n const workflowTasks = existingTasks.filter(\n (task) =>\n ((task as { workflowRevisionId?: number }).workflowRevisionId ?? task.workflowId) ===\n workflow._draftRevisionId\n );\n const taskByName = new Map(workflowTasks.map((task) => [task.name, task]));\n for (const taskBuilder of workflow.tasks) {\n const match = taskByName.get(taskBuilder.name);\n if (match) taskBuilder.adopt(match);\n }\n\n const ids = new Map<number, TaskBuilder[]>();\n for (const taskBuilder of workflow.tasks) {\n if (taskBuilder._id !== undefined) {\n ids.set(taskBuilder._id, [...(ids.get(taskBuilder._id) ?? []), taskBuilder]);\n }\n }\n for (const builders of ids.values()) {\n if (builders.length <= 1) continue;\n const nameAdopted = builders.filter((task) => taskByName.has(task.name));\n for (const task of builders.filter((builder) => !nameAdopted.includes(builder))) {\n task._id = undefined;\n task._existed = false;\n }\n }\n }\n }\n\n private sortedResources(): WorkspaceBuilderResource[] {\n const all: WorkspaceBuilderResource[] = [];\n for (const resource of this.resources) {\n all.push(resource);\n if (resource instanceof WorkflowBuilder) {\n const start = resource.startTask;\n const tasks =\n start === undefined\n ? resource.tasks\n : [start, ...resource.tasks.filter((task) => task !== start)];\n all.push(...tasks);\n } else if (resource instanceof JourneyBuilder) {\n all.push(...resource.steps);\n }\n }\n return all.sort(\n (a, b) => (PHASES.get(a.constructor) ?? 99) - (PHASES.get(b.constructor) ?? 99)\n );\n }\n\n private collectWiringSummary(resources: WorkspaceBuilderResource[]): string[] {\n const lines: string[] = [];\n for (const resource of resources) {\n if (resource instanceof TaskBuilder) {\n for (const transition of resource.transitions) {\n lines.push(`${transition.parent.name} -> ${transition.child.name}`);\n }\n for (const rule of resource.eventRules) {\n lines.push(`${rule.actionType} on enter '${resource.name}'`);\n }\n } else if (resource instanceof FormBuilder) {\n for (const rule of resource.eventRules) {\n lines.push(`${rule.actionType} on ${rule.eventType} '${resource.name}'`);\n }\n } else if (resource instanceof RoutineBuilder) {\n for (const rule of resource.rules)\n lines.push(`${rule.actionType} rule on '${resource.name}'`);\n } else if (resource instanceof JourneyStepBuilder) {\n for (const connection of resource.connections) {\n lines.push(`${connection.parent.name} -> ${connection.child.name}`);\n }\n } else if (resource instanceof JourneyBuilder) {\n for (const goal of resource.goals) lines.push(`Goal: ${goal.name}`);\n }\n }\n return lines;\n }\n\n private async applyTransitions(): Promise<void> {\n const parentChildren = new Map<TaskBuilder, TaskTransition[]>();\n for (const resource of this.sortedResources()) {\n if (!(resource instanceof TaskBuilder)) continue;\n for (const transition of resource.transitions) {\n parentChildren.set(transition.parent, [\n ...(parentChildren.get(transition.parent) ?? []),\n transition,\n ]);\n }\n }\n\n for (const [parent, transitions] of parentChildren) {\n if (parent._id === undefined) continue;\n const childTasks = transitions.flatMap((transition) => {\n const taskId = transition.child._id;\n if (taskId === undefined || taskId === parent._id) return [];\n return [\n {\n taskId,\n choicePrompt: transition.when,\n celCondition: transition.celCondition ?? null,\n autoNext: transition.autoNext,\n required: transition.required,\n },\n ];\n });\n if (!childTasks.length) continue;\n await this.client.updateTask(parent._id, { childTasks });\n writeLine(\n ` Wired: ${parent.name} -> [${transitions.map((tr) => tr.child.name).join(', ')}]`\n );\n }\n }\n\n private async applyEventRules(resources: WorkspaceBuilderResource[]): Promise<void> {\n for (const resource of resources) {\n if (resource instanceof TaskBuilder) {\n for (const rule of resource.eventRules) {\n try {\n const payload: EventRuleFormData = {\n objectType: EventRuleObjectType.TASK,\n taskId: resource._id,\n eventType: rule.eventType,\n actionType: rule.actionType,\n actionParams: resolveRefs(rule.actionParams),\n ...(rule.name ? { name: rule.name } : {}),\n };\n await this.applyEventRule(\n payload,\n `${rule.actionType} on enter '${resource.name}'`\n );\n } catch (err) {\n handleEventRuleApplyFailure(resource.name, err);\n }\n }\n } else if (resource instanceof FormBuilder) {\n for (const rule of resource.eventRules) {\n try {\n const payload: EventRuleFormData = {\n objectType: EventRuleObjectType.DATA_RECORD,\n dataTypeId: resource._id,\n eventType: rule.eventType,\n actionType: rule.actionType,\n actionParams: resolveRefs(rule.actionParams),\n ...(rule.condition ? { conditions: rule.condition } : {}),\n ...(rule.name ? { name: rule.name } : {}),\n };\n await this.applyEventRule(\n payload,\n `${rule.actionType} on ${rule.eventType} '${resource.name}'`\n );\n } catch (err) {\n handleEventRuleApplyFailure(resource.name, err);\n }\n }\n }\n }\n }\n\n private async applyEventRule(payload: EventRuleFormData, label: string): Promise<void> {\n const existing = await this.findMatchingEventRule(payload);\n if (!existing) {\n await this.client.createEventRule(payload);\n writeLine(` Wired: ${label}`);\n return;\n }\n\n const update = eventRuleUpdate(existing, payload);\n if (Object.keys(update).length) {\n await this.client.updateEventRule(existing.id, update);\n writeLine(` Updated: ${label}`);\n } else {\n writeLine(` Exists: ${label}`);\n }\n }\n\n private async findMatchingEventRule(payload: EventRuleFormData): Promise<EventRule | undefined> {\n const sourceFilter = eventRuleSourceFilter(payload);\n const candidates = await this.client.searchEventRules({\n objectType: payload.objectType,\n eventType: payload.eventType,\n actionType: payload.actionType,\n includeDisabled: true,\n ...sourceFilter,\n });\n return candidates.find((candidate) => eventRulesMatch(candidate, payload));\n }\n\n private async applyJourneyConnections(resources: WorkspaceBuilderResource[]): Promise<void> {\n for (const resource of resources) {\n if (!(resource instanceof JourneyStepBuilder)) continue;\n for (const connection of resource.connections) {\n if (resource.journey._id === undefined) continue;\n const payload = buildJourneyConnectionPayload(connection);\n if (!payload) continue;\n await this.client.createConnection(resource.journey._id, payload);\n writeLine(` Wired: ${connection.parent.name} -> ${connection.child.name}`);\n }\n }\n }\n\n private async applyJourneyGoals(resources: WorkspaceBuilderResource[]): Promise<void> {\n for (const resource of resources) {\n if (!(resource instanceof JourneyBuilder) || resource._id === undefined) continue;\n for (const goal of resource.goals) {\n await this.client.createGoal(resource._id, buildJourneyGoalPayload(goal));\n writeLine(` Created goal: ${goal.name}`);\n }\n }\n }\n}\n\nexport class ApplyError extends Error {\n readonly createdSoFar: ResourceSummary;\n readonly #resource: WorkspaceBuilderResource;\n readonly #cause: unknown;\n\n constructor(resource: WorkspaceBuilderResource, cause: unknown, createdSoFar: ResourceSummary) {\n super(formatApplyErrorMessage(resource, cause, createdSoFar));\n this.name = 'ApplyError';\n this.createdSoFar = createdSoFar;\n this.#resource = resource;\n this.#cause = cause;\n }\n\n get resource(): WorkspaceBuilderResource {\n return this.#resource;\n }\n\n get cause(): unknown {\n return this.#cause;\n }\n}\n\nfunction resourceKey(resource: WorkspaceBuilderResource): string {\n if (resource instanceof RoleUpdate) return 'roleUpdates';\n if (resource instanceof FormBuilder) return 'forms';\n if (resource instanceof MemberLabelBuilder) return 'labels';\n if (resource instanceof WorkflowBuilder) return 'workflows';\n if (resource instanceof TaskBuilder) return 'tasks';\n if (resource instanceof MemberFilterBuilder) return 'memberFilters';\n if (resource instanceof RoutineBuilder) return 'routines';\n if (resource instanceof NotificationRuleBuilder) return 'notificationRules';\n if (resource instanceof JourneyBuilder) return 'journeys';\n if (resource instanceof JourneyStepBuilder) return 'journeySteps';\n if (resource instanceof AgentBuilder) return 'agents';\n return 'resources';\n}\n\nconst SEARCHABLE_EVENT_RULE_SOURCE_FIELDS = [\n 'taskId',\n 'dataTypeId',\n 'routineId',\n 'workflowRevisionId',\n 'journeyStepId',\n] as const;\n\nconst EVENT_RULE_SOURCE_FIELDS = [\n ...SEARCHABLE_EVENT_RULE_SOURCE_FIELDS,\n 'calendarId',\n 'calendarEventTypeId',\n] as const;\n\ntype SearchableEventRuleSourceField = (typeof SEARCHABLE_EVENT_RULE_SOURCE_FIELDS)[number];\n\nfunction eventRuleSourceFilter(\n payload: EventRuleFormData\n): Partial<Record<SearchableEventRuleSourceField, number>> {\n const filter: Partial<Record<SearchableEventRuleSourceField, number>> = {};\n for (const field of SEARCHABLE_EVENT_RULE_SOURCE_FIELDS) {\n const value = payload[field];\n if (value !== undefined && value !== null) {\n filter[field] = value;\n }\n }\n return filter;\n}\n\nfunction eventRulesMatch(existing: EventRule, payload: EventRuleFormData): boolean {\n if (normalizeString(existing.name) !== normalizeString(payload.name)) return false;\n if (existing.objectType !== payload.objectType) return false;\n if (existing.eventType !== payload.eventType) return false;\n if (existing.actionType !== payload.actionType) return false;\n\n for (const field of EVENT_RULE_SOURCE_FIELDS) {\n if ((existing[field] ?? null) !== (payload[field] ?? null)) return false;\n }\n\n if (normalizeString(payload.name)) return true;\n if (normalizeString(existing.conditions) !== normalizeString(payload.conditions)) return false;\n if (!eventRuleValueEqual(existing.actionParams, payload.actionParams ?? null)) return false;\n if (!eventRuleValueEqual(existing.triggerParams, payload.triggerParams ?? null)) return false;\n return true;\n}\n\nfunction eventRuleUpdate(existing: EventRule, payload: EventRuleFormData): UpdateEventRuleFormData {\n const update: UpdateEventRuleFormData = {};\n const conditions = payload.conditions ?? null;\n if (normalizeString(existing.conditions) !== normalizeString(conditions)) {\n update.conditions = conditions;\n }\n const actionParams = payload.actionParams ?? null;\n if (!eventRuleValueEqual(existing.actionParams, actionParams)) {\n update.actionParams = payload.actionParams;\n }\n const triggerParams = payload.triggerParams ?? null;\n if (!eventRuleValueEqual(existing.triggerParams, triggerParams)) {\n update.triggerParams = payload.triggerParams;\n }\n const active = payload.active ?? true;\n if (existing.active !== active) {\n update.active = active;\n }\n const delay = payload.delay ?? 0;\n if (existing.delay !== delay) {\n update.delay = delay;\n }\n const order = payload.order ?? 0;\n if (existing.order !== order) {\n update.order = order;\n }\n return update;\n}\n\nfunction normalizeString(value: string | null | undefined): string {\n return value ?? '';\n}\n\nfunction eventRuleValueEqual(left: unknown, right: unknown): boolean {\n return JSON.stringify(stableValue(left)) === JSON.stringify(stableValue(right));\n}\n\nfunction stableValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(stableValue);\n if (!value || typeof value !== 'object') return value;\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) return value;\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, nested]) => [key, stableValue(nested)])\n );\n}\n\nfunction writeLine(message = ''): void {\n process.stdout.write(`${message}\\n`);\n}\n\nfunction handleEventRuleApplyFailure(resourceName: string, err: unknown): void {\n if (hasStatus(err, 403)) {\n writeLine(\n ` WARNING: Event rule on '${resourceName}' failed (retry exec() with scopes=['automations:admin'])`\n );\n return;\n }\n const summary = summarizeError(err);\n writeLine(` FAILED: Event rule on '${resourceName}': ${summary}`);\n throw new Error(`Failed wiring event rule on '${resourceName}': ${summary}`);\n}\n\nfunction writeScopeForResource(resource: WorkspaceBuilderResource): string | null {\n if (resource instanceof FormBuilder) return 'datatypes:write';\n if (resource instanceof WorkflowBuilder || resource instanceof TaskBuilder) {\n return 'workflows:write';\n }\n if (resource instanceof AgentBuilder) return 'agents:write';\n if (resource instanceof MemberLabelBuilder || resource instanceof MemberFilterBuilder) {\n return 'members:write';\n }\n if (resource instanceof RoutineBuilder || resource instanceof NotificationRuleBuilder) {\n return 'automations:admin';\n }\n if (resource instanceof JourneyBuilder || resource instanceof JourneyStepBuilder) {\n return 'journeys:write';\n }\n if (resource instanceof RoleUpdate) return 'member_roles:write';\n return null;\n}\n\nfunction scopeRetryHint(resource: WorkspaceBuilderResource): string {\n const scope = writeScopeForResource(resource);\n return scope ? ` (retry exec with scopes=['${scope}'])` : '';\n}\n\nfunction formatApplyFailureLine(resource: WorkspaceBuilderResource, err: unknown): string {\n const line = ` FAILED: ${resource.planLine()}: ${summarizeError(err)}`;\n return hasStatus(err, 403) ? `${line}${scopeRetryHint(resource)}` : line;\n}\n\nfunction formatApplyErrorMessage(\n resource: WorkspaceBuilderResource,\n cause: unknown,\n createdSoFar: ResourceSummary\n): string {\n let message = `Failed creating ${resource.planLine()}: ${summarizeError(cause)}`;\n if (hasStatus(cause, 403)) {\n const scope = writeScopeForResource(resource);\n if (scope) {\n message += `\\nRetry exec with scopes=['${scope}']`;\n }\n }\n const createdKeys = Object.keys(createdSoFar);\n if (createdKeys.length > 0) {\n message += `\\nAlready created: ${JSON.stringify(createdSoFar)}`;\n }\n return message;\n}\n\nfunction summarizeError(err: unknown): string {\n if (hasStatus(err, 403)) {\n return 'Insufficient permissions for this operation';\n }\n if (err instanceof ApiError) {\n const msg = err.message.trim();\n const availableTypesIdx = msg.indexOf('Available types:');\n if (availableTypesIdx !== -1) {\n const head = msg.slice(0, availableTypesIdx).trim().replace(/\\.$/, '');\n return head ? `${head}.` : 'Request failed';\n }\n return msg.length > 240 ? `${msg.slice(0, 237)}...` : msg;\n }\n if (err instanceof Error) {\n return err.name || 'Error';\n }\n return typeof err;\n}\n\nfunction hasStatus(err: unknown, status: number): boolean {\n if (typeof err === 'object' && err !== null) {\n const candidate = err as { status?: unknown; statusCode?: unknown };\n if (candidate.status === status || candidate.statusCode === status) return true;\n }\n const message = err instanceof Error ? err.message : typeof err === 'string' ? err : '';\n return message.includes(String(status));\n}\n\nexport async function runWorkspaceScript(\n client: GravityRailWorkspaceClient,\n build: (workspace: WorkspaceBuilder) => void | Promise<void>,\n mode = 'plan'\n): Promise<ResourceSummary | void> {\n const workspace = new WorkspaceBuilder(client);\n await build(workspace);\n if (mode === 'plan') return workspace.plan();\n if (mode === 'preview') return workspace.preview();\n if (mode === 'apply') return workspace.apply();\n throw new Error(`Unknown mode '${mode}'. Use plan, preview, or apply.`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAQ,IAAI,UAAU,OAAO,QAAQ,WAAW,MAAM;AACrF,SAAO,QAAQ,SAAS,OAAO,MAAM,CAAC;AACzC;AAEA,eAAsB,mBACnB,QACA,OACA,OAAO,QACyB;AAChC,QAAM,YAAY,IAAI,iBAAiB,MAAM;AAC7C,QAAM,MAAM,SAAS;AACrB,MAAI,SAAS,OAAQ,QAAO,UAAU,KAAK;AAC3C,MAAI,SAAS,UAAW,QAAO,UAAU,QAAQ;AACjD,MAAI,SAAS,QAAS,QAAO,UAAU,MAAM;AAC7C,QAAM,IAAI,MAAM,iBAAiB,IAAI,iCAAiC;AACzE;","names":[]}
1
+ {"version":3,"sources":["../src/workspace-builder/resource.ts","../src/workspace-builder/automation.ts","../src/workspace-builder/forms.ts","../src/workspace-builder/journeys.ts","../src/workspace-builder/role-update.ts","../src/workspace-builder/workflows.ts","../src/workspace-builder/orchestrator.ts"],"sourcesContent":["import type { GravityRailWorkspaceClient } from '../client/workspace-client';\n\nexport type AnyRecord = Record<string, any>;\nexport type ResourceSummary = Record<string, Array<number | undefined>>;\n\nexport function isRecord(value: unknown): value is AnyRecord {\n return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isPlainRecord(value: unknown): value is AnyRecord {\n if (!isRecord(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nexport function slugify(name: string): string {\n return name.toLowerCase().replaceAll(' ', '_').replaceAll('-', '_');\n}\n\nexport abstract class WorkspaceBuilderResource {\n _id?: number;\n _uuid?: string;\n _created = false;\n _existed = false;\n\n /** Server-assigned numeric id — available after apply() or adopt(). */\n get id(): number {\n if (this._id === undefined) {\n throw new Error(\n `${this.constructor.name} has no id yet — ids are assigned during apply(). ` +\n 'Pass the builder object itself where a reference is needed; refs resolve at apply time.'\n );\n }\n return this._id;\n }\n\n /** Server-assigned uuid — available after apply() or adopt(). */\n get uuid(): string {\n if (this._uuid === undefined) {\n throw new Error(\n `${this.constructor.name} has no uuid yet — uuids are assigned during apply(). ` +\n 'Pass the builder object itself where a reference is needed; refs resolve at apply time.'\n );\n }\n return this._uuid;\n }\n\n abstract planLine(): string;\n abstract apply(client: GravityRailWorkspaceClient): Promise<void>;\n\n matchKey(): string | undefined {\n return undefined;\n }\n\n adopt(existing: AnyRecord): void {\n this._id = existing.id;\n this._uuid = existing.uuid;\n this._existed = true;\n }\n}\n\nexport function resolveRefs(params: AnyRecord): AnyRecord {\n return resolveRefValue(params) as AnyRecord;\n}\n\nfunction resolveRefValue(value: unknown): unknown {\n if (value instanceof WorkspaceBuilderResource) return value._uuid;\n if (Array.isArray(value)) return value.map(resolveRefValue);\n if (!isPlainRecord(value)) return value;\n\n const out: AnyRecord = {};\n for (const [key, nestedValue] of Object.entries(value)) {\n out[key] = resolveRefValue(nestedValue);\n }\n return out;\n}\n","import {\n EventRuleEventType,\n EventRuleObjectType,\n type CreateRoutineRequest,\n type EventRuleActionType,\n type MemberFilterFormData,\n type NotificationRuleCreate,\n} from '../types';\nimport type { QueryPredicate } from '../types/query-engine-types';\nimport type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport type { AnyRecord } from './resource';\nimport { WorkspaceBuilderResource } from './resource';\nimport type { WorkflowBuilder } from './workflows';\n\nexport class MemberFilterBuilder extends WorkspaceBuilderResource {\n readonly description: string;\n /** Query-engine predicate (JSON IR) authored on MemberFilter.query. */\n query: QueryPredicate | null = null;\n\n constructor(\n readonly name: string,\n options: AnyRecord = {}\n ) {\n super();\n this.description = options.description ?? '';\n this.query = options.query ?? null;\n }\n\n /** Set the filter's query-engine predicate (JSON IR). */\n setQuery(query: QueryPredicate): MemberFilterBuilder {\n this.query = query;\n return this;\n }\n\n planLine(): string {\n return `MemberFilter: ${this.name}${this.query ? ' (query)' : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n const payload: MemberFilterFormData = {\n name: this.name,\n description: this.description,\n query: this.query,\n };\n const result = await client.createMemberFilter(payload);\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n\ninterface RoutineRuleDraft {\n actionType: EventRuleActionType | string;\n workflow?: WorkflowBuilder;\n memberFilter?: MemberFilterBuilder;\n actionParams: AnyRecord;\n}\n\nexport class RoutineBuilder extends WorkspaceBuilderResource {\n readonly active: boolean;\n readonly description: string;\n readonly rules: RoutineRuleDraft[] = [];\n\n constructor(\n readonly name: string,\n readonly cronSchedule = '',\n options: AnyRecord = {}\n ) {\n super();\n this.active = options.active ?? false;\n this.description = options.description ?? '';\n }\n\n addRule(\n actionType: string,\n options: {\n workflow?: WorkflowBuilder;\n memberFilter?: MemberFilterBuilder;\n actionParams?: AnyRecord;\n } = {}\n ): RoutineBuilder {\n this.rules.push({\n actionType,\n workflow: options.workflow,\n memberFilter: options.memberFilter,\n actionParams: options.actionParams ?? {},\n });\n return this;\n }\n\n planLine(): string {\n const parts = [\n ...(this.cronSchedule ? [`cron=${this.cronSchedule}`] : []),\n ...(this.rules.length ? [`${this.rules.length} rules`] : []),\n this.active ? 'active' : 'inactive',\n ];\n return `Routine: ${this.name} (${parts.join(', ')})`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n const eventRules = this.rules.map((rule) => {\n const actionParams = { ...rule.actionParams };\n if (rule.workflow?._id !== undefined) actionParams.workflowId = rule.workflow._id;\n if (rule.memberFilter?._id !== undefined)\n actionParams.memberFilterId = rule.memberFilter._id;\n return {\n uuid: crypto.randomUUID(),\n objectType: EventRuleObjectType.ROUTINE,\n eventType: EventRuleEventType.ROUTINE_TRIGGERED,\n actionType: rule.actionType as EventRuleActionType,\n actionParams,\n active: true,\n };\n });\n const payload: CreateRoutineRequest = {\n name: this.name,\n cronString: this.cronSchedule,\n scheduleMode: this.cronSchedule ? 'CRON' : undefined,\n scheduleEnabled: this.active,\n ...(this.description ? { description: this.description } : {}),\n ...(eventRules.length ? { eventRules } : {}),\n };\n const result = await client.createRoutine(payload);\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n\nexport class NotificationRuleBuilder extends WorkspaceBuilderResource {\n readonly noticeType: string;\n readonly memberId: number;\n readonly workflow?: WorkflowBuilder;\n readonly prompt?: string;\n readonly notifySms: boolean;\n readonly notifyEmail: boolean;\n readonly notifyVoice: boolean;\n\n constructor(\n readonly name: string,\n options: AnyRecord = {}\n ) {\n super();\n this.noticeType = options.noticeType ?? options.notice_type ?? name;\n this.memberId = options.memberId ?? options.member_id;\n this.workflow = options.workflow;\n this.prompt = options.prompt ?? options.message;\n this.notifySms = Boolean(options.notifySms ?? options.notify_sms);\n this.notifyEmail = Boolean(options.notifyEmail ?? options.notify_email);\n this.notifyVoice = Boolean(options.notifyVoice ?? options.notify_voice);\n }\n\n planLine(): string {\n const parts: string[] = [];\n if (this.memberId !== undefined) parts.push(`memberId=${this.memberId}`);\n if (this.workflow) parts.push(`workflow='${this.workflow.name}'`);\n return `NotificationRule: ${this.name}${parts.length ? ` (${parts.join(', ')})` : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this.memberId === undefined) {\n throw new Error(`Notification rule '${this.name}' requires memberId`);\n }\n const payload: NotificationRuleCreate = {\n noticeType: this.noticeType,\n memberId: this.memberId,\n workflowId: this.workflow?._id,\n prompt: this.prompt ?? null,\n notifySms: this.notifySms,\n notifyEmail: this.notifyEmail,\n notifyVoice: this.notifyVoice,\n };\n const result = await client.createNotificationRule(payload);\n this._id = result.id;\n this._created = true;\n }\n}\n","import {\n DataFieldType,\n EventRuleEventType,\n type DataTypeFormData,\n type EnumOption,\n type EventRuleActionType,\n type MemberLabelFormData,\n type SchemaField,\n} from '../types';\nimport type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport type { WorkspaceBuilderEventRule } from './event-rules';\nimport { type AnyRecord, isRecord, slugify, WorkspaceBuilderResource } from './resource';\n\n// The client DataFieldType enum and the generated SchemaField fieldType\n// literal union share the same string values, but TS string enums are\n// nominal — convert once at draft construction.\ntype WorkspaceFieldDraft = SchemaField;\n\nfunction normalizeOptions(options: any[]): EnumOption[] {\n if (options.length === 0) return [];\n const first = options[0];\n if (isRecord(first)) return options as EnumOption[];\n if (Array.isArray(first)) {\n return options.map((entry) => ({ label: String(entry[0]), value: entry[1] }));\n }\n return options.map((option) => ({ label: String(option), value: String(option) }));\n}\n\nfunction createFieldDraft(\n fieldType: DataFieldType,\n name: string,\n slug: string,\n options: {\n required?: boolean;\n order?: number;\n description?: string;\n choices?: EnumOption[];\n cel?: string;\n } = {}\n): WorkspaceFieldDraft {\n return {\n name,\n slug,\n fieldType: fieldType as SchemaField['fieldType'],\n required: Boolean(options.required),\n order: options.order ?? 0,\n ...(options.description ? { description: options.description } : {}),\n ...(options.choices ? { options: options.choices } : {}),\n ...(options.cel ? { celFunction: options.cel } : {}),\n };\n}\n\nexport class FormBuilder extends WorkspaceBuilderResource {\n readonly name: string;\n readonly slug: string;\n readonly description: string;\n readonly prompt: string;\n readonly collection: boolean;\n readonly fields: WorkspaceFieldDraft[] = [];\n readonly eventRules: WorkspaceBuilderEventRule[] = [];\n\n constructor(name: string, slug?: string, options: AnyRecord = {}) {\n super();\n this.name = name;\n this.slug = slug ?? slugify(name);\n this.description = options.description ?? '';\n this.prompt = options.prompt ?? '';\n this.collection = options.collection ?? false;\n\n for (const field of options.fields ?? []) {\n if (!isRecord(field) || !field.name) continue;\n const choices = field.options ? normalizeOptions(field.options) : undefined;\n this.fields.push(\n createFieldDraft(\n (field.fieldType ?? field.field_type ?? DataFieldType.TEXT) as DataFieldType,\n field.name,\n field.slug ?? slugify(field.name),\n {\n required: Boolean(field.required ?? field.isRequired),\n order: field.order ?? 0,\n description: field.description,\n choices,\n }\n )\n );\n }\n }\n\n field(\n fieldType: DataFieldType,\n name: string,\n slug: string,\n options: {\n required?: boolean;\n order?: number;\n description?: string;\n choices?: any[];\n cel?: string;\n } = {}\n ): FormBuilder {\n this.fields.push(createFieldDraft(fieldType, name, slug, options));\n return this;\n }\n\n enumField(name: string, slug: string, options: any[], settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.ENUM, name, slug, {\n ...settings,\n choices: normalizeOptions(options),\n });\n }\n\n textField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.TEXT, name, slug, settings);\n }\n\n numberField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.NUMBER, name, slug, settings);\n }\n\n dateField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.DATE, name, slug, settings);\n }\n\n booleanField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.BOOLEAN, name, slug, settings);\n }\n\n functionField(name: string, slug: string, cel: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.FUNCTION, name, slug, { ...settings, cel });\n }\n\n emailField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.EMAIL, name, slug, settings);\n }\n\n phoneField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.PHONE, name, slug, settings);\n }\n\n longtextField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.LONGTEXT, name, slug, settings);\n }\n\n integerField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.INTEGER, name, slug, settings);\n }\n\n datetimeField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.DATETIME, name, slug, settings);\n }\n\n timeOfDayField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.TIME_OF_DAY, name, slug, settings);\n }\n\n usZipCodeField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.US_ZIP_CODE, name, slug, settings);\n }\n\n arrayField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.ARRAY, name, slug, settings);\n }\n\n objectField(name: string, slug: string, settings: AnyRecord = {}): FormBuilder {\n return this.field(DataFieldType.OBJECT, name, slug, settings);\n }\n\n onRecordCreated(\n action: string,\n params: AnyRecord = {},\n condition?: string,\n name?: string\n ): FormBuilder {\n this.eventRules.push({\n eventType: EventRuleEventType.DATA_RECORD_CREATED,\n actionType: action as EventRuleActionType,\n actionParams: params,\n condition,\n name,\n });\n return this;\n }\n\n onRecordUpdated(\n action: string,\n params: AnyRecord = {},\n condition?: string,\n name?: string\n ): FormBuilder {\n this.eventRules.push({\n eventType: EventRuleEventType.DATA_RECORD_UPDATED,\n actionType: action as EventRuleActionType,\n actionParams: params,\n condition,\n name,\n });\n return this;\n }\n\n matchKey(): string {\n return this.slug;\n }\n\n planLine(): string {\n return `Form: ${this.name} (slug=${this.slug}, ${this.fields.length} fields)`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed) return;\n const payload: DataTypeFormData = {\n name: this.name,\n slug: this.slug,\n description: this.description,\n prompt: this.prompt,\n isCollection: this.collection,\n fields: this.fields,\n };\n const result = await client.createDataType(payload);\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n\nexport class MemberLabelBuilder extends WorkspaceBuilderResource {\n readonly name: string;\n readonly slug: string;\n readonly color: string;\n readonly description: string;\n\n constructor(name: string, slug?: string, color = '8b5cf6', description = '') {\n super();\n this.name = name;\n this.slug = slug ?? slugify(name);\n this.color = color;\n this.description = description;\n }\n\n matchKey(): string {\n return this.slug;\n }\n\n planLine(): string {\n return `Label: ${this.name} (slug=${this.slug})`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed) return;\n const payload: MemberLabelFormData = {\n name: this.name,\n slug: this.slug,\n color: this.color,\n description: this.description,\n };\n const result = await client.createMemberLabel(payload);\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n","import type {\n JourneyGoalFormData,\n JourneyStepConnectionFormData,\n JourneyStepFormData,\n} from '../types';\nimport type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport type { AnyRecord } from './resource';\nimport { WorkspaceBuilderResource } from './resource';\n\nexport interface StepConnectionDraft {\n parent: JourneyStepBuilder;\n child: JourneyStepBuilder;\n condition?: string;\n required: boolean;\n timeoutSeconds?: number;\n}\n\nexport interface JourneyGoalDraft {\n name: string;\n description: string;\n step?: JourneyStepBuilder;\n completionCel?: string;\n value?: number;\n order: number;\n}\n\nexport class JourneyStepBuilder extends WorkspaceBuilderResource {\n readonly connections: StepConnectionDraft[] = [];\n\n // journey-decoupling Phase 7: a Journey step no longer links to a Workflow.\n // A step nudges via EventRule actions instead of running a Workflow, so the\n // builder no longer accepts or emits a workflow reference.\n constructor(\n readonly name: string,\n readonly journey: JourneyBuilder,\n readonly order = 0,\n readonly description = ''\n ) {\n super();\n }\n\n connectsTo(\n child: JourneyStepBuilder,\n condition?: string,\n required = false,\n timeoutSeconds?: number\n ): JourneyStepBuilder {\n this.connections.push({ parent: this, child, condition, required, timeoutSeconds });\n return this;\n }\n\n planLine(): string {\n return `Step: ${this.name}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this.journey._id === undefined) return;\n const payload: JourneyStepFormData = {\n name: this.name,\n description: this.description,\n order: this.order,\n };\n const result = await client.createStep(this.journey._id, payload);\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n\nexport class JourneyBuilder extends WorkspaceBuilderResource {\n readonly description: string;\n readonly steps: JourneyStepBuilder[] = [];\n readonly goals: JourneyGoalDraft[] = [];\n\n constructor(\n readonly name: string,\n options: AnyRecord = {}\n ) {\n super();\n this.description = options.description ?? '';\n }\n\n step(name: string, options: AnyRecord = {}): JourneyStepBuilder {\n const step = new JourneyStepBuilder(\n name,\n this,\n options.order ?? 0,\n options.description ?? ''\n );\n this.steps.push(step);\n return step;\n }\n\n goal(name: string, options: AnyRecord = {}): JourneyBuilder {\n this.goals.push({\n name,\n description: options.description ?? '',\n step: options.step,\n completionCel: options.completionCel ?? options.completion_cel,\n value: options.value,\n order: options.order ?? 0,\n });\n return this;\n }\n\n planLine(): string {\n const parts: string[] = [];\n if (this.steps.length) parts.push(`${this.steps.length} steps`);\n if (this.goals.length) parts.push(`${this.goals.length} goals`);\n return `Journey: ${this.name}${parts.length ? ` (${parts.join(', ')})` : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n const result = await client.createJourney({\n name: this.name,\n description: this.description,\n });\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n\nexport function buildJourneyConnectionPayload(\n connection: StepConnectionDraft\n): JourneyStepConnectionFormData | undefined {\n if (!connection.parent._uuid || !connection.child._uuid) return undefined;\n return {\n parentStepUuid: connection.parent._uuid,\n childStepUuid: connection.child._uuid,\n ...(connection.condition ? { celCondition: connection.condition } : {}),\n ...(connection.required ? { required: true } : {}),\n ...(connection.timeoutSeconds ? { timeoutSeconds: connection.timeoutSeconds } : {}),\n };\n}\n\nexport function buildJourneyGoalPayload(goal: JourneyGoalDraft): JourneyGoalFormData {\n return {\n name: goal.name,\n description: goal.description,\n order: goal.order,\n ...(goal.step?._uuid ? { goalStepUuid: goal.step._uuid } : {}),\n ...(goal.completionCel ? { completionCel: goal.completionCel } : {}),\n ...(goal.value !== undefined ? { value: goal.value } : {}),\n };\n}\n","import type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport type { AnyRecord } from './resource';\nimport { WorkspaceBuilderResource } from './resource';\n\nexport class RoleUpdate extends WorkspaceBuilderResource {\n constructor(\n readonly roleId: number,\n readonly workflowIds?: number[],\n readonly dataTypeIds?: number[]\n ) {\n super();\n }\n\n planLine(): string {\n const parts: string[] = [];\n if (this.workflowIds) parts.push(`workflows=${JSON.stringify(this.workflowIds)}`);\n if (this.dataTypeIds) parts.push(`dataTypes=${JSON.stringify(this.dataTypeIds)}`);\n return `RoleUpdate: roleId=${this.roleId}${parts.length ? ` (${parts.join(', ')})` : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n const payload: AnyRecord = {};\n if (this.workflowIds) payload.workflowIds = this.workflowIds;\n if (this.dataTypeIds) payload.dataTypeIds = this.dataTypeIds;\n if (Object.keys(payload).length) await client.updateMemberRole(this.roleId, payload);\n this._id = this.roleId;\n this._created = true;\n }\n}\n","import {\n EventRuleEventType,\n type CreateAgentRequest,\n type EventRuleActionType,\n type WorkflowFormData,\n} from '../types';\nimport type { Ability } from '../types/ability-types';\nimport type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport type { WorkspaceBuilderEventRule } from './event-rules';\nimport type { FormBuilder } from './forms';\nimport { type AnyRecord, WorkspaceBuilderResource } from './resource';\n\nconst PERM_KEYS: Record<string, string> = {\n canRead: 'canRead',\n canCreate: 'canCreate',\n canEdit: 'canEdit',\n can_read: 'canRead',\n can_create: 'canCreate',\n can_edit: 'canEdit',\n};\n\nconst ABILITY_TYPE_MAP: Record<string, string> = {\n data_access: 'integration:data_access',\n file_access: 'integration:file_access',\n escalation: 'oversight:escalation',\n};\n\nclass AbilityDef {\n readonly uuid = crypto.randomUUID();\n readonly config: AnyRecord;\n readonly enabled: boolean;\n readonly celCondition?: string;\n readonly form?: FormBuilder;\n readonly perms: AnyRecord = {};\n\n constructor(\n readonly abilityType: string,\n options: AnyRecord = {}\n ) {\n this.config = options.config ?? {};\n this.enabled = options.enabled ?? true;\n this.celCondition = options.celCondition ?? options.cel_condition;\n this.form = options.form;\n for (const [inputKey, outputKey] of Object.entries(PERM_KEYS)) {\n if (inputKey in options) this.perms[outputKey] = options[inputKey];\n }\n }\n\n toAbility(): Ability {\n const config = { ...this.config };\n if (this.form?._uuid) {\n config.dataTypeUuid = this.form._uuid;\n Object.assign(config, this.perms);\n }\n return {\n uuid: this.uuid,\n abilityType: ABILITY_TYPE_MAP[this.abilityType] ?? this.abilityType,\n config,\n enabled: this.enabled,\n ...(this.celCondition ? { celCondition: this.celCondition } : {}),\n };\n }\n}\n\nexport interface TaskTransition {\n parent: TaskBuilder;\n child: TaskBuilder;\n when: string;\n autoNext: boolean;\n required: boolean;\n celCondition?: string;\n}\n\nexport interface WorkflowBuilderOptions {\n description?: string;\n prompt?: string;\n copyFromAgentId?: number;\n}\n\nexport class TaskBuilder extends WorkspaceBuilderResource {\n readonly transitions: TaskTransition[] = [];\n readonly eventRules: WorkspaceBuilderEventRule[] = [];\n\n constructor(\n readonly name: string,\n readonly workflow: WorkflowBuilder,\n readonly prompt = '',\n readonly start = false,\n readonly description = ''\n ) {\n super();\n }\n\n transitionsTo(\n child: TaskBuilder,\n when: string,\n autoNext = false,\n required = false,\n celCondition?: string\n ): TaskBuilder {\n if (child === this) {\n throw new Error(`Task '${this.name}' cannot transition to itself`);\n }\n this.transitions.push({\n parent: this,\n child,\n when,\n autoNext,\n required,\n celCondition,\n });\n return this;\n }\n\n onEnter(action: string, params: AnyRecord = {}, name?: string): TaskBuilder {\n this.eventRules.push({\n eventType: EventRuleEventType.TASK_EXECUTE,\n actionType: action as EventRuleActionType,\n actionParams: params,\n name,\n });\n return this;\n }\n\n initialMessage(message: string, suggestions?: string[]): TaskBuilder {\n return this.onEnter('assistant:message', {\n message,\n ...(suggestions ? { suggestions } : {}),\n });\n }\n\n planLine(): string {\n return `Task: ${this.name}${this.start ? ' [start]' : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed || this.workflow._id === undefined) return;\n if (this.workflow._draftRevisionId === undefined) {\n // Root id without a draft revision id means the workflow was\n // created/adopted through a path that skipped revision resolution —\n // creating the task would attach it to whatever revision happens to\n // share the number (cross-workflow corruption). Fail loudly.\n throw new Error(\n `Workflow '${this.workflow.name}' has no draft revision id; ` +\n 'cannot create tasks. Tasks attach to a WorkflowRevision, ' +\n 'not the stable workflow root.'\n );\n }\n // Tasks belong to a revision graph — target the DRAFT revision\n // explicitly (edits always land on the draft; publish makes them live).\n const result = await client.createTask({\n workflowRevisionId: this.workflow._draftRevisionId,\n name: this.name,\n prompt: this.prompt,\n description: this.description,\n });\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n\nexport class WorkflowBuilder extends WorkspaceBuilderResource {\n readonly description: string;\n readonly prompt?: string;\n private copyFromAgentId?: number;\n readonly tasks: TaskBuilder[] = [];\n readonly abilities: AbilityDef[] = [];\n /** The DRAFT revision's id — where tasks and graph edits attach.\n * `_id` is the STABLE workflow root id; the two are different entities\n * and (after any publish) different numbers. */\n _draftRevisionId?: number;\n\n constructor(\n readonly name: string,\n options: WorkflowBuilderOptions = {}\n ) {\n super();\n this.description = options.description ?? '';\n this.prompt = options.prompt;\n this.copyFromAgentId = options.copyFromAgentId;\n }\n\n task(name: string, options: AnyRecord = {}): TaskBuilder {\n const task = new TaskBuilder(\n name,\n this,\n options.prompt ?? '',\n options.start ?? false,\n options.description ?? ''\n );\n this.tasks.push(task);\n return task;\n }\n\n ability(abilityType: string, options: AnyRecord = {}): WorkflowBuilder {\n this.abilities.push(new AbilityDef(abilityType, options));\n return this;\n }\n\n get startTask(): TaskBuilder | undefined {\n return this.tasks.find((task) => task.start) ?? this.tasks[0];\n }\n\n matchKey(): string {\n return this.name;\n }\n\n adopt(existing: AnyRecord): void {\n // Accepts the WorkflowDetail composition ({ workflow, draftRevision,\n // activeRevision }) — the orchestrator fetches it per matched name.\n // Root facts (id/uuid) live on `workflow`; graph facts (startTaskId)\n // live on the draft revision.\n const root = (existing.workflow ?? existing) as AnyRecord;\n super.adopt(root);\n const draft = existing.draftRevision as AnyRecord | undefined;\n this._draftRevisionId = (draft?.id ?? root.draftRevisionId) as number | undefined;\n const start = this.startTask;\n const startTaskId = draft?.startTaskId as number | undefined;\n if (start && startTaskId) {\n start._id = startTaskId;\n start._existed = true;\n }\n }\n\n planLine(): string {\n const details: string[] = [];\n if (this.tasks.length) details.push(`${this.tasks.length} tasks`);\n if (this.abilities.length) details.push(`${this.abilities.length} abilities`);\n return `Workflow: ${this.name}${details.length ? ` (${details.join(', ')})` : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this._existed) return;\n const payload: WorkflowFormData = {\n name: this.name,\n description: this.description,\n createMode: 'taskless',\n ...(this.prompt ? { prompt: this.prompt } : {}),\n ...(this.copyFromAgentId ? { copyFromAgentId: this.copyFromAgentId } : {}),\n ...(this.abilities.length\n ? { abilities: this.abilities.map((ability) => ability.toAbility()) }\n : {}),\n };\n const result = await client.createWorkflow(payload);\n this._id = result.workflow.id;\n this._uuid = result.workflow.uuid;\n // Tasks attach to the draft revision, never the root — keep its id.\n this._draftRevisionId = result.draftRevision.id;\n this._created = true;\n }\n}\n\nexport class AgentBuilder extends WorkspaceBuilderResource {\n readonly chatModelId: string;\n readonly systemPrompt: string;\n readonly memberRoleId?: number;\n readonly tools: string[];\n readonly codeInterpreterEnabled: boolean;\n\n constructor(\n readonly name: string,\n options: AnyRecord = {}\n ) {\n super();\n this.chatModelId = options.chatModelId ?? options.chat_model_id ?? '';\n this.systemPrompt = options.systemPrompt ?? options.system_prompt ?? '';\n this.memberRoleId = options.roleId ?? options.role_id;\n this.tools = options.tools ?? [];\n this.codeInterpreterEnabled =\n options.codeInterpreterEnabled ?? options.code_interpreter_enabled ?? false;\n }\n\n planLine(): string {\n const parts: string[] = [];\n if (this.chatModelId) parts.push(`model=${this.chatModelId}`);\n if (this.tools.length) parts.push(`${this.tools.length} tools`);\n return `Agent: ${this.name}${parts.length ? ` (${parts.join(', ')})` : ''}`;\n }\n\n async apply(client: GravityRailWorkspaceClient): Promise<void> {\n if (this.memberRoleId === undefined) {\n throw new Error(`Agent '${this.name}' requires memberRoleId`);\n }\n if (!this.chatModelId) {\n throw new Error(`Agent '${this.name}' requires chatModelId`);\n }\n\n const payload: CreateAgentRequest = {\n name: this.name,\n memberRoleId: this.memberRoleId,\n chatModelId: this.chatModelId,\n systemPrompt: this.systemPrompt,\n ...(this.tools.length ? { tools: this.tools } : {}),\n ...(this.codeInterpreterEnabled ? { codeInterpreterEnabled: true } : {}),\n };\n const result = await client.createAgent(payload);\n this._id = result.id;\n this._uuid = result.uuid;\n this._created = true;\n }\n}\n","import {\n EventRuleObjectType,\n type EventRule,\n type EventRuleFormData,\n type UpdateEventRuleFormData,\n} from '../types';\nimport { ApiError } from '../api/base';\nimport type { GravityRailWorkspaceClient } from '../client/workspace-client';\nimport { MemberFilterBuilder, NotificationRuleBuilder, RoutineBuilder } from './automation';\nimport { FormBuilder, MemberLabelBuilder } from './forms';\nimport {\n buildJourneyConnectionPayload,\n buildJourneyGoalPayload,\n JourneyBuilder,\n JourneyStepBuilder,\n} from './journeys';\nimport {\n type AnyRecord,\n type ResourceSummary,\n resolveRefs,\n WorkspaceBuilderResource,\n} from './resource';\nimport { RoleUpdate } from './role-update';\nimport {\n AgentBuilder,\n TaskBuilder,\n type TaskTransition,\n WorkflowBuilder,\n type WorkflowBuilderOptions,\n} from './workflows';\n\nconst PHASES = new Map<Function, number>([\n [FormBuilder, 0],\n [MemberLabelBuilder, 0],\n [AgentBuilder, 1],\n [WorkflowBuilder, 2],\n [TaskBuilder, 3],\n [RoleUpdate, 4],\n [MemberFilterBuilder, 5],\n [RoutineBuilder, 6],\n [NotificationRuleBuilder, 6],\n [JourneyBuilder, 7],\n [JourneyStepBuilder, 8],\n]);\n\nexport class WorkspaceBuilder {\n readonly resources: WorkspaceBuilderResource[] = [];\n\n constructor(readonly client: GravityRailWorkspaceClient) {}\n\n form(name: string, options: AnyRecord & { slug?: string } = {}): FormBuilder {\n const form = new FormBuilder(name, options.slug, options);\n this.resources.push(form);\n return form;\n }\n\n workflow(name: string, options: WorkflowBuilderOptions = {}): WorkflowBuilder {\n const workflow = new WorkflowBuilder(name, options);\n this.resources.push(workflow);\n return workflow;\n }\n\n label(\n name: string,\n options: { slug?: string; color?: string; description?: string } = {}\n ): MemberLabelBuilder {\n const label = new MemberLabelBuilder(\n name,\n options.slug,\n options.color,\n options.description ?? ''\n );\n this.resources.push(label);\n return label;\n }\n\n journey(name: string, options: AnyRecord = {}): JourneyBuilder {\n const journey = new JourneyBuilder(name, options);\n this.resources.push(journey);\n return journey;\n }\n\n agent(name: string, options: AnyRecord = {}): AgentBuilder {\n const agent = new AgentBuilder(name, options);\n this.resources.push(agent);\n return agent;\n }\n\n routine(name: string, cronSchedule = '', options: AnyRecord = {}): RoutineBuilder {\n const routine = new RoutineBuilder(name, cronSchedule, options);\n this.resources.push(routine);\n return routine;\n }\n\n memberFilter(name: string, options: AnyRecord = {}): MemberFilterBuilder {\n const filter = new MemberFilterBuilder(name, options);\n this.resources.push(filter);\n return filter;\n }\n\n notificationRule(name: string, options: AnyRecord = {}): NotificationRuleBuilder {\n const rule = new NotificationRuleBuilder(name, options);\n this.resources.push(rule);\n return rule;\n }\n\n roleUpdate(roleId: number, workflowIds?: number[], dataTypeIds?: number[]): RoleUpdate {\n const update = new RoleUpdate(roleId, workflowIds, dataTypeIds);\n this.resources.push(update);\n return update;\n }\n\n plan(): void {\n const resources = this.sortedResources();\n writeLine(`\\n${'='.repeat(50)}`);\n writeLine('Plan');\n writeLine('='.repeat(50));\n for (const resource of resources) {\n writeLine(` + ${resource.planLine()}`);\n }\n const wiring = this.collectWiringSummary(resources);\n if (wiring.length) {\n writeLine('\\n Wiring:');\n for (const line of wiring) writeLine(` ${line}`);\n }\n writeLine(`\\n Total: ${resources.length} resources, ${wiring.length} connections`);\n writeLine(`${'='.repeat(50)}\\n`);\n }\n\n async preview(): Promise<void> {\n const resources = this.sortedResources();\n await this.resolveExisting(resources);\n\n writeLine(`\\n${'='.repeat(50)}`);\n writeLine('Preview');\n writeLine('='.repeat(50));\n for (const resource of resources) {\n if (resource._existed) {\n writeLine(` = ${resource.planLine()} (exists, id=${resource._id})`);\n } else {\n writeLine(` + ${resource.planLine()}`);\n }\n }\n const wiring = this.collectWiringSummary(resources);\n if (wiring.length) {\n writeLine('\\n Wiring:');\n for (const line of wiring) writeLine(` ${line}`);\n }\n const toCreate = resources.filter((resource) => !resource._existed);\n const existing = resources.filter((resource) => resource._existed);\n writeLine(\n `\\n Total: ${toCreate.length} to create, ${existing.length} existing, ${wiring.length} connections`\n );\n writeLine(`${'='.repeat(50)}\\n`);\n }\n\n async apply(): Promise<ResourceSummary> {\n const resources = this.sortedResources();\n await this.resolveExisting(resources);\n const summary: ResourceSummary = {};\n\n writeLine('Applying...');\n for (const resource of resources) {\n try {\n if (resource._existed) {\n const key = resourceKey(resource);\n summary[key] ??= [];\n summary[key]!.push(resource._id);\n writeLine(` Exists ${resource.planLine()} -> id=${resource._id}`);\n continue;\n }\n\n await resource.apply(this.client);\n if (resource._created || resource._id !== undefined) {\n const key = resourceKey(resource);\n summary[key] ??= [];\n summary[key]!.push(resource._id);\n const startTag = resource instanceof TaskBuilder && resource.start ? ' [start]' : '';\n writeLine(` Created ${resource.planLine()}${startTag} -> id=${resource._id}`);\n } else {\n writeLine(` Skipped: ${resource.planLine()}`);\n }\n } catch (err) {\n writeLine(formatApplyFailureLine(resource, err));\n throw new ApplyError(resource, err, summary);\n }\n }\n\n await this.applyTransitions();\n await this.applyEventRules(resources);\n await this.applyJourneyConnections(resources);\n await this.applyJourneyGoals(resources);\n\n const count = Object.values(summary).reduce((total, ids) => total + ids.length, 0);\n writeLine(`\\nDone! Created ${count} resources.`);\n return summary;\n }\n\n private async resolveExisting(resources: WorkspaceBuilderResource[]): Promise<void> {\n const formSlugs = new Map(\n resources\n .filter((resource): resource is FormBuilder => resource instanceof FormBuilder)\n .map((resource) => [resource.slug, resource])\n );\n const labelSlugs = new Map(\n resources\n .filter(\n (resource): resource is MemberLabelBuilder => resource instanceof MemberLabelBuilder\n )\n .map((resource) => [resource.slug, resource])\n );\n const workflowNames = new Map(\n resources\n .filter((resource): resource is WorkflowBuilder => resource instanceof WorkflowBuilder)\n .map((resource) => [resource.name, resource])\n );\n\n if (formSlugs.size) {\n for (const existing of await this.client.getDataTypes()) {\n if (existing.slug && formSlugs.has(existing.slug)) {\n formSlugs.get(existing.slug)!.adopt(existing);\n }\n }\n }\n if (labelSlugs.size) {\n for (const existing of await this.client.getMemberLabels()) {\n if (existing.slug && labelSlugs.has(existing.slug)) {\n labelSlugs.get(existing.slug)!.adopt(existing);\n }\n }\n }\n if (!workflowNames.size) return;\n\n const existingWorkflows = await this.client.getWorkflows();\n for (const { workflow: existing } of existingWorkflows.items) {\n if (existing.name && workflowNames.has(existing.name)) {\n // List rows carry only the root + active-revision summary. Tasks\n // and startTaskId live on the DRAFT revision, so fetch the detail\n // composition for adoption (root ids and revision ids are\n // different entities — matching tasks by root id attaches them to\n // the wrong workflow once any workflow has been published).\n const detail = await this.client.getWorkflow(existing.id);\n workflowNames.get(existing.name)!.adopt(detail);\n }\n }\n\n const adoptedWorkflows = resources.filter(\n (resource): resource is WorkflowBuilder =>\n resource instanceof WorkflowBuilder && resource._existed && resource._id !== undefined\n );\n if (!adoptedWorkflows.length) return;\n\n const existingTasks = await this.client.getTasks();\n for (const workflow of adoptedWorkflows) {\n // Tasks belong to a revision graph — match against the adopted\n // workflow's DRAFT revision id (task.workflowRevisionId), falling\n // back to the legacy field for older payloads.\n const workflowTasks = existingTasks.filter(\n (task) =>\n ((task as { workflowRevisionId?: number }).workflowRevisionId ?? task.workflowId) ===\n workflow._draftRevisionId\n );\n const taskByName = new Map(workflowTasks.map((task) => [task.name, task]));\n for (const taskBuilder of workflow.tasks) {\n const match = taskByName.get(taskBuilder.name);\n if (match) taskBuilder.adopt(match);\n }\n\n const ids = new Map<number, TaskBuilder[]>();\n for (const taskBuilder of workflow.tasks) {\n if (taskBuilder._id !== undefined) {\n ids.set(taskBuilder._id, [...(ids.get(taskBuilder._id) ?? []), taskBuilder]);\n }\n }\n for (const builders of ids.values()) {\n if (builders.length <= 1) continue;\n const nameAdopted = builders.filter((task) => taskByName.has(task.name));\n for (const task of builders.filter((builder) => !nameAdopted.includes(builder))) {\n task._id = undefined;\n task._existed = false;\n }\n }\n }\n }\n\n private sortedResources(): WorkspaceBuilderResource[] {\n const all: WorkspaceBuilderResource[] = [];\n for (const resource of this.resources) {\n all.push(resource);\n if (resource instanceof WorkflowBuilder) {\n const start = resource.startTask;\n const tasks =\n start === undefined\n ? resource.tasks\n : [start, ...resource.tasks.filter((task) => task !== start)];\n all.push(...tasks);\n } else if (resource instanceof JourneyBuilder) {\n all.push(...resource.steps);\n }\n }\n return all.sort(\n (a, b) => (PHASES.get(a.constructor) ?? 99) - (PHASES.get(b.constructor) ?? 99)\n );\n }\n\n private collectWiringSummary(resources: WorkspaceBuilderResource[]): string[] {\n const lines: string[] = [];\n for (const resource of resources) {\n if (resource instanceof TaskBuilder) {\n for (const transition of resource.transitions) {\n lines.push(`${transition.parent.name} -> ${transition.child.name}`);\n }\n for (const rule of resource.eventRules) {\n lines.push(`${rule.actionType} on enter '${resource.name}'`);\n }\n } else if (resource instanceof FormBuilder) {\n for (const rule of resource.eventRules) {\n lines.push(`${rule.actionType} on ${rule.eventType} '${resource.name}'`);\n }\n } else if (resource instanceof RoutineBuilder) {\n for (const rule of resource.rules)\n lines.push(`${rule.actionType} rule on '${resource.name}'`);\n } else if (resource instanceof JourneyStepBuilder) {\n for (const connection of resource.connections) {\n lines.push(`${connection.parent.name} -> ${connection.child.name}`);\n }\n } else if (resource instanceof JourneyBuilder) {\n for (const goal of resource.goals) lines.push(`Goal: ${goal.name}`);\n }\n }\n return lines;\n }\n\n private async applyTransitions(): Promise<void> {\n const parentChildren = new Map<TaskBuilder, TaskTransition[]>();\n for (const resource of this.sortedResources()) {\n if (!(resource instanceof TaskBuilder)) continue;\n for (const transition of resource.transitions) {\n parentChildren.set(transition.parent, [\n ...(parentChildren.get(transition.parent) ?? []),\n transition,\n ]);\n }\n }\n\n for (const [parent, transitions] of parentChildren) {\n if (parent._id === undefined) continue;\n const childTasks = transitions.flatMap((transition) => {\n const taskId = transition.child._id;\n if (taskId === undefined || taskId === parent._id) return [];\n return [\n {\n taskId,\n choicePrompt: transition.when,\n celCondition: transition.celCondition ?? null,\n autoNext: transition.autoNext,\n required: transition.required,\n },\n ];\n });\n if (!childTasks.length) continue;\n await this.client.updateTask(parent._id, { childTasks });\n writeLine(\n ` Wired: ${parent.name} -> [${transitions.map((tr) => tr.child.name).join(', ')}]`\n );\n }\n }\n\n private async applyEventRules(resources: WorkspaceBuilderResource[]): Promise<void> {\n for (const resource of resources) {\n if (resource instanceof TaskBuilder) {\n for (const rule of resource.eventRules) {\n try {\n const payload: EventRuleFormData = {\n objectType: EventRuleObjectType.TASK,\n taskId: resource._id,\n eventType: rule.eventType,\n actionType: rule.actionType,\n actionParams: resolveRefs(rule.actionParams),\n ...(rule.name ? { name: rule.name } : {}),\n };\n await this.applyEventRule(\n payload,\n `${rule.actionType} on enter '${resource.name}'`\n );\n } catch (err) {\n handleEventRuleApplyFailure(resource.name, err);\n }\n }\n } else if (resource instanceof FormBuilder) {\n for (const rule of resource.eventRules) {\n try {\n const payload: EventRuleFormData = {\n objectType: EventRuleObjectType.DATA_RECORD,\n dataTypeId: resource._id,\n eventType: rule.eventType,\n actionType: rule.actionType,\n actionParams: resolveRefs(rule.actionParams),\n ...(rule.condition ? { conditions: rule.condition } : {}),\n ...(rule.name ? { name: rule.name } : {}),\n };\n await this.applyEventRule(\n payload,\n `${rule.actionType} on ${rule.eventType} '${resource.name}'`\n );\n } catch (err) {\n handleEventRuleApplyFailure(resource.name, err);\n }\n }\n }\n }\n }\n\n private async applyEventRule(payload: EventRuleFormData, label: string): Promise<void> {\n const existing = await this.findMatchingEventRule(payload);\n if (!existing) {\n await this.client.createEventRule(payload);\n writeLine(` Wired: ${label}`);\n return;\n }\n\n const update = eventRuleUpdate(existing, payload);\n if (Object.keys(update).length) {\n await this.client.updateEventRule(existing.id, update);\n writeLine(` Updated: ${label}`);\n } else {\n writeLine(` Exists: ${label}`);\n }\n }\n\n private async findMatchingEventRule(payload: EventRuleFormData): Promise<EventRule | undefined> {\n const sourceFilter = eventRuleSourceFilter(payload);\n const candidates = await this.client.searchEventRules({\n objectType: payload.objectType,\n eventType: payload.eventType,\n actionType: payload.actionType,\n includeDisabled: true,\n ...sourceFilter,\n });\n return candidates.find((candidate) => eventRulesMatch(candidate, payload));\n }\n\n private async applyJourneyConnections(resources: WorkspaceBuilderResource[]): Promise<void> {\n for (const resource of resources) {\n if (!(resource instanceof JourneyStepBuilder)) continue;\n for (const connection of resource.connections) {\n if (resource.journey._id === undefined) continue;\n const payload = buildJourneyConnectionPayload(connection);\n if (!payload) continue;\n await this.client.createConnection(resource.journey._id, payload);\n writeLine(` Wired: ${connection.parent.name} -> ${connection.child.name}`);\n }\n }\n }\n\n private async applyJourneyGoals(resources: WorkspaceBuilderResource[]): Promise<void> {\n for (const resource of resources) {\n if (!(resource instanceof JourneyBuilder) || resource._id === undefined) continue;\n for (const goal of resource.goals) {\n await this.client.createGoal(resource._id, buildJourneyGoalPayload(goal));\n writeLine(` Created goal: ${goal.name}`);\n }\n }\n }\n}\n\nexport class ApplyError extends Error {\n readonly createdSoFar: ResourceSummary;\n readonly #resource: WorkspaceBuilderResource;\n readonly #cause: unknown;\n\n constructor(resource: WorkspaceBuilderResource, cause: unknown, createdSoFar: ResourceSummary) {\n super(formatApplyErrorMessage(resource, cause, createdSoFar));\n this.name = 'ApplyError';\n this.createdSoFar = createdSoFar;\n this.#resource = resource;\n this.#cause = cause;\n }\n\n get resource(): WorkspaceBuilderResource {\n return this.#resource;\n }\n\n get cause(): unknown {\n return this.#cause;\n }\n}\n\nfunction resourceKey(resource: WorkspaceBuilderResource): string {\n if (resource instanceof RoleUpdate) return 'roleUpdates';\n if (resource instanceof FormBuilder) return 'forms';\n if (resource instanceof MemberLabelBuilder) return 'labels';\n if (resource instanceof WorkflowBuilder) return 'workflows';\n if (resource instanceof TaskBuilder) return 'tasks';\n if (resource instanceof MemberFilterBuilder) return 'memberFilters';\n if (resource instanceof RoutineBuilder) return 'routines';\n if (resource instanceof NotificationRuleBuilder) return 'notificationRules';\n if (resource instanceof JourneyBuilder) return 'journeys';\n if (resource instanceof JourneyStepBuilder) return 'journeySteps';\n if (resource instanceof AgentBuilder) return 'agents';\n return 'resources';\n}\n\nconst SEARCHABLE_EVENT_RULE_SOURCE_FIELDS = [\n 'taskId',\n 'dataTypeId',\n 'routineId',\n 'workflowRevisionId',\n 'journeyStepId',\n] as const;\n\nconst EVENT_RULE_SOURCE_FIELDS = [\n ...SEARCHABLE_EVENT_RULE_SOURCE_FIELDS,\n 'calendarId',\n 'calendarEventTypeId',\n] as const;\n\ntype SearchableEventRuleSourceField = (typeof SEARCHABLE_EVENT_RULE_SOURCE_FIELDS)[number];\n\nfunction eventRuleSourceFilter(\n payload: EventRuleFormData\n): Partial<Record<SearchableEventRuleSourceField, number>> {\n const filter: Partial<Record<SearchableEventRuleSourceField, number>> = {};\n for (const field of SEARCHABLE_EVENT_RULE_SOURCE_FIELDS) {\n const value = payload[field];\n if (value !== undefined && value !== null) {\n filter[field] = value;\n }\n }\n return filter;\n}\n\nfunction eventRulesMatch(existing: EventRule, payload: EventRuleFormData): boolean {\n if (normalizeString(existing.name) !== normalizeString(payload.name)) return false;\n if (existing.objectType !== payload.objectType) return false;\n if (existing.eventType !== payload.eventType) return false;\n if (existing.actionType !== payload.actionType) return false;\n\n for (const field of EVENT_RULE_SOURCE_FIELDS) {\n if ((existing[field] ?? null) !== (payload[field] ?? null)) return false;\n }\n\n if (normalizeString(payload.name)) return true;\n if (normalizeString(existing.conditions) !== normalizeString(payload.conditions)) return false;\n if (!eventRuleValueEqual(existing.actionParams, payload.actionParams ?? null)) return false;\n if (!eventRuleValueEqual(existing.triggerParams, payload.triggerParams ?? null)) return false;\n return true;\n}\n\nfunction eventRuleUpdate(existing: EventRule, payload: EventRuleFormData): UpdateEventRuleFormData {\n const update: UpdateEventRuleFormData = {};\n const conditions = payload.conditions ?? null;\n if (normalizeString(existing.conditions) !== normalizeString(conditions)) {\n update.conditions = conditions;\n }\n const actionParams = payload.actionParams ?? null;\n if (!eventRuleValueEqual(existing.actionParams, actionParams)) {\n update.actionParams = payload.actionParams;\n }\n const triggerParams = payload.triggerParams ?? null;\n if (!eventRuleValueEqual(existing.triggerParams, triggerParams)) {\n update.triggerParams = payload.triggerParams;\n }\n const active = payload.active ?? true;\n if (existing.active !== active) {\n update.active = active;\n }\n const delay = payload.delay ?? 0;\n if (existing.delay !== delay) {\n update.delay = delay;\n }\n const order = payload.order ?? 0;\n if (existing.order !== order) {\n update.order = order;\n }\n return update;\n}\n\nfunction normalizeString(value: string | null | undefined): string {\n return value ?? '';\n}\n\nfunction eventRuleValueEqual(left: unknown, right: unknown): boolean {\n return JSON.stringify(stableValue(left)) === JSON.stringify(stableValue(right));\n}\n\nfunction stableValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(stableValue);\n if (!value || typeof value !== 'object') return value;\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) return value;\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, nested]) => [key, stableValue(nested)])\n );\n}\n\nfunction writeLine(message = ''): void {\n process.stdout.write(`${message}\\n`);\n}\n\nfunction handleEventRuleApplyFailure(resourceName: string, err: unknown): void {\n if (hasStatus(err, 403)) {\n writeLine(\n ` WARNING: Event rule on '${resourceName}' failed (retry exec() with scopes=['automations:admin'])`\n );\n return;\n }\n const summary = summarizeError(err);\n writeLine(` FAILED: Event rule on '${resourceName}': ${summary}`);\n throw new Error(`Failed wiring event rule on '${resourceName}': ${summary}`);\n}\n\nfunction writeScopeForResource(resource: WorkspaceBuilderResource): string | null {\n if (resource instanceof FormBuilder) return 'datatypes:write';\n if (resource instanceof WorkflowBuilder || resource instanceof TaskBuilder) {\n return 'workflows:write';\n }\n if (resource instanceof AgentBuilder) return 'agents:write';\n if (resource instanceof MemberLabelBuilder || resource instanceof MemberFilterBuilder) {\n return 'members:write';\n }\n if (resource instanceof RoutineBuilder || resource instanceof NotificationRuleBuilder) {\n return 'automations:admin';\n }\n if (resource instanceof JourneyBuilder || resource instanceof JourneyStepBuilder) {\n return 'journeys:write';\n }\n if (resource instanceof RoleUpdate) return 'member_roles:write';\n return null;\n}\n\nfunction scopeRetryHint(resource: WorkspaceBuilderResource): string {\n const scope = writeScopeForResource(resource);\n return scope ? ` (retry exec with scopes=['${scope}'])` : '';\n}\n\nfunction formatApplyFailureLine(resource: WorkspaceBuilderResource, err: unknown): string {\n const line = ` FAILED: ${resource.planLine()}: ${summarizeError(err)}`;\n return hasStatus(err, 403) ? `${line}${scopeRetryHint(resource)}` : line;\n}\n\nfunction formatApplyErrorMessage(\n resource: WorkspaceBuilderResource,\n cause: unknown,\n createdSoFar: ResourceSummary\n): string {\n let message = `Failed creating ${resource.planLine()}: ${summarizeError(cause)}`;\n if (hasStatus(cause, 403)) {\n const scope = writeScopeForResource(resource);\n if (scope) {\n message += `\\nRetry exec with scopes=['${scope}']`;\n }\n }\n const createdKeys = Object.keys(createdSoFar);\n if (createdKeys.length > 0) {\n message += `\\nAlready created: ${JSON.stringify(createdSoFar)}`;\n }\n return message;\n}\n\nfunction summarizeError(err: unknown): string {\n if (hasStatus(err, 403)) {\n return 'Insufficient permissions for this operation';\n }\n if (err instanceof ApiError) {\n const msg = err.message.trim();\n const availableTypesIdx = msg.indexOf('Available types:');\n if (availableTypesIdx !== -1) {\n const head = msg.slice(0, availableTypesIdx).trim().replace(/\\.$/, '');\n return head ? `${head}.` : 'Request failed';\n }\n return msg.length > 240 ? `${msg.slice(0, 237)}...` : msg;\n }\n if (err instanceof Error) {\n return err.name || 'Error';\n }\n return typeof err;\n}\n\nfunction hasStatus(err: unknown, status: number): boolean {\n if (typeof err === 'object' && err !== null) {\n const candidate = err as { status?: unknown; statusCode?: unknown };\n if (candidate.status === status || candidate.statusCode === status) return true;\n }\n const message = err instanceof Error ? err.message : typeof err === 'string' ? err : '';\n return message.includes(String(status));\n}\n\nexport async function runWorkspaceScript(\n client: GravityRailWorkspaceClient,\n build: (workspace: WorkspaceBuilder) => void | Promise<void>,\n mode = 'plan'\n): Promise<ResourceSummary | void> {\n const workspace = new WorkspaceBuilder(client);\n await build(workspace);\n if (mode === 'plan') return workspace.plan();\n if (mode === 'preview') return workspace.preview();\n if (mode === 'apply') return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;AACvB,WAAO,IAAI,QAAQ;AAAA,EACtB;AACA,SAAO,OAAO;AACjB;AAEA,SAAS,UAAU,KAAc,QAAyB;AACvD,MAAI,OAAO,QAAQ,YAAY,QAAQ,MAAM;AAC1C,UAAM,YAAY;AAClB,QAAI,UAAU,WAAW,UAAU,UAAU,eAAe,OAAQ,QAAO;AAAA,EAC9E;AACA,QAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,QAAQ,WAAW,MAAM;AACrF,SAAO,QAAQ,SAAS,OAAO,MAAM,CAAC;AACzC;AAEA,eAAsB,mBACnB,QACA,OACA,OAAO,QACyB;AAChC,QAAM,YAAY,IAAI,iBAAiB,MAAM;AAC7C,QAAM,MAAM,SAAS;AACrB,MAAI,SAAS,OAAQ,QAAO,UAAU,KAAK;AAC3C,MAAI,SAAS,UAAW,QAAO,UAAU,QAAQ;AACjD,MAAI,SAAS,QAAS,QAAO,UAAU,MAAM;AAC7C,QAAM,IAAI,MAAM,iBAAiB,IAAI,iCAAiC;AACzE;","names":[]}
package/dist/internal.cjs CHANGED
@@ -198,6 +198,7 @@ __export(internal_exports, {
198
198
  ToolkitsApi: () => ToolkitsApi,
199
199
  VoiceApi: () => VoiceApi,
200
200
  WIDGET_SLUGS: () => WIDGET_SLUGS,
201
+ WORKFLOW_IMPLICIT_USE_SCOPE: () => WORKFLOW_IMPLICIT_USE_SCOPE,
201
202
  WorkflowAccessWarningResourceType: () => WorkflowAccessWarningResourceType,
202
203
  WorkflowNotesApi: () => WorkflowNotesApi,
203
204
  WorkflowResourceType: () => WorkflowAccessWarningResourceType,
@@ -274,6 +275,9 @@ __export(internal_exports, {
274
275
  parseExperimentStatCount: () => parseExperimentStatCount,
275
276
  parseOrgAuthChallenge: () => parseOrgAuthChallenge,
276
277
  requiresAssistantParticipant: () => requiresAssistantParticipant,
278
+ roleCanUseWorkflow: () => roleCanUseWorkflow,
279
+ roleImplicitWorkflowUseScope: () => roleImplicitWorkflowUseScope,
280
+ roleWorkflowAccess: () => roleWorkflowAccess,
277
281
  usesBuiltinAssistant: () => usesBuiltinAssistant,
278
282
  validateFeatureDependencies: () => validateFeatureDependencies
279
283
  });
@@ -320,6 +324,21 @@ function encodePermissions(permissions) {
320
324
  if (permissions.delete) accessMode |= PERMISSION_DELETE;
321
325
  return accessMode;
322
326
  }
327
+ var WORKFLOW_IMPLICIT_USE_SCOPE = "workflows:admin";
328
+ function roleImplicitWorkflowUseScope(role) {
329
+ return (role.grantedScopes ?? []).includes(WORKFLOW_IMPLICIT_USE_SCOPE) ? WORKFLOW_IMPLICIT_USE_SCOPE : null;
330
+ }
331
+ function roleWorkflowAccess(role, workflowId) {
332
+ const viaScope = roleImplicitWorkflowUseScope(role);
333
+ if (viaScope) {
334
+ return { accessMode: PERMISSION_USE | PERMISSION_EDIT, viaScope };
335
+ }
336
+ const entry = (role.workflowAccess ?? []).find((wa) => wa.workflowId === workflowId);
337
+ return { accessMode: entry?.accessMode ?? PERMISSION_NONE, viaScope: null };
338
+ }
339
+ function roleCanUseWorkflow(role, workflowId) {
340
+ return (roleWorkflowAccess(role, workflowId).accessMode & PERMISSION_USE) !== 0;
341
+ }
323
342
  var Scope = /* @__PURE__ */ ((Scope2) => {
324
343
  Scope2["WORKSPACE_READ"] = "workspace:read";
325
344
  Scope2["WORKSPACE_WRITE"] = "workspace:write";
@@ -478,6 +497,7 @@ var EventRuleEventType = /* @__PURE__ */ ((EventRuleEventType2) => {
478
497
  EventRuleEventType2["ROUTINE_TRIGGERED"] = "routine:triggered";
479
498
  EventRuleEventType2["ASSISTANT_MESSAGE"] = "workflow:assistant_message";
480
499
  EventRuleEventType2["USER_MESSAGE"] = "workflow:user_message";
500
+ EventRuleEventType2["WORKFLOW_EXECUTE"] = "workflow:execute";
481
501
  EventRuleEventType2["CALENDAR_EVENT_CREATED"] = "calendar_event:created";
482
502
  EventRuleEventType2["CALENDAR_EVENT_UPDATED"] = "calendar_event:updated";
483
503
  EventRuleEventType2["CALENDAR_EVENT_CANCELLED"] = "calendar_event:cancelled";
@@ -547,7 +567,6 @@ var WorkspaceFeature = /* @__PURE__ */ ((WorkspaceFeature2) => {
547
567
  WorkspaceFeature2["WEB_SEARCH"] = "web_search";
548
568
  WorkspaceFeature2["CALENDAR"] = "calendar";
549
569
  WorkspaceFeature2["EXPERIMENTS"] = "experiments";
550
- WorkspaceFeature2["OPERATOR"] = "operator";
551
570
  WorkspaceFeature2["GMAIL"] = "gmail";
552
571
  WorkspaceFeature2["GCALENDAR"] = "gcalendar";
553
572
  WorkspaceFeature2["GDRIVE"] = "gdrive";
@@ -3949,6 +3968,8 @@ var ChatsApi = class extends BaseApiClient {
3949
3968
  if (options.mine !== void 0) params.append("mine", options.mine.toString());
3950
3969
  if (options.needsResponse !== void 0)
3951
3970
  params.append("needsResponse", options.needsResponse.toString());
3971
+ if (options.needsResponseFirst !== void 0)
3972
+ params.append("needsResponseFirst", options.needsResponseFirst.toString());
3952
3973
  if (options.paused !== void 0) params.append("paused", options.paused.toString());
3953
3974
  if (options.archived !== void 0) params.append("archived", options.archived.toString());
3954
3975
  if (options.channel) params.append("channel", options.channel);
@@ -3998,6 +4019,25 @@ var ChatsApi = class extends BaseApiClient {
3998
4019
  async getChat(wid, id) {
3999
4020
  return this.fetch(`w/${wid}/chats/${id}`);
4000
4021
  }
4022
+ /**
4023
+ * Create-chat preflight for SMS: is a conversation already live between this
4024
+ * workspace number and this member?
4025
+ *
4026
+ * An SMS conversation with a member is a single stream — inbound SMS resolves
4027
+ * to ONE current chat per (member phone, workspace phone) pair — so creating
4028
+ * a new SMS chat SUPERSEDES the existing one and the member's next reply
4029
+ * lands on the new chat. Callers use this to say so before committing.
4030
+ *
4031
+ * Read-only, `chats:read`, and PHI-safe by construction: status and timing
4032
+ * only, no message content and no chat title.
4033
+ */
4034
+ async getCurrentSmsChat(wid, options) {
4035
+ const params = new URLSearchParams({
4036
+ memberId: options.memberId.toString(),
4037
+ phoneNumberId: options.phoneNumberId.toString()
4038
+ });
4039
+ return this.fetch(`w/${wid}/chats/current-sms?${params}`);
4040
+ }
4001
4041
  /** Get token usage statistics for a chat. */
4002
4042
  async getChatTokenUsage(wid, chatId) {
4003
4043
  return this.fetch(`w/${wid}/chats/${chatId}/token-usage`);
@@ -11260,6 +11300,7 @@ var WORKSPACE_METHOD_NAMES = [
11260
11300
  "getConnectionSyncConfig",
11261
11301
  "getCredentialUpdateInvites",
11262
11302
  "getCurrentMember",
11303
+ "getCurrentSmsChat",
11263
11304
  "getCustomToolkit",
11264
11305
  "getCustomToolkits",
11265
11306
  "getDashboard",
@@ -11795,6 +11836,7 @@ function bindTasksMethods(target, tasks, abilities) {
11795
11836
  function bindChatsMethods(target, chats) {
11796
11837
  target.getChats = chats.getChats.bind(chats);
11797
11838
  target.getChat = chats.getChat.bind(chats);
11839
+ target.getCurrentSmsChat = chats.getCurrentSmsChat.bind(chats);
11798
11840
  target.getChatCallbacks = chats.getChatCallbacks.bind(chats);
11799
11841
  target.cancelChatCallback = chats.cancelChatCallback.bind(chats);
11800
11842
  target.getChatTokenUsage = chats.getChatTokenUsage.bind(chats);
@@ -12833,6 +12875,7 @@ var GravityRailClient = class {
12833
12875
  // Chats API
12834
12876
  getChats;
12835
12877
  getChat;
12878
+ getCurrentSmsChat;
12836
12879
  getChatCallbacks;
12837
12880
  cancelChatCallback;
12838
12881
  getChatTokenUsage;
@@ -14149,6 +14192,7 @@ var GravityRailClient = class {
14149
14192
  ToolkitsApi,
14150
14193
  VoiceApi,
14151
14194
  WIDGET_SLUGS,
14195
+ WORKFLOW_IMPLICIT_USE_SCOPE,
14152
14196
  WorkflowAccessWarningResourceType,
14153
14197
  WorkflowNotesApi,
14154
14198
  WorkflowResourceType,
@@ -14225,6 +14269,9 @@ var GravityRailClient = class {
14225
14269
  parseExperimentStatCount,
14226
14270
  parseOrgAuthChallenge,
14227
14271
  requiresAssistantParticipant,
14272
+ roleCanUseWorkflow,
14273
+ roleImplicitWorkflowUseScope,
14274
+ roleWorkflowAccess,
14228
14275
  usesBuiltinAssistant,
14229
14276
  validateFeatureDependencies
14230
14277
  });