@ixo/editor 3.0.0-beta.3 → 3.0.0-beta.31

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.
@@ -0,0 +1,2848 @@
1
+ // src/core/lib/actionRegistry/registry.ts
2
+ var actions = /* @__PURE__ */ new Map();
3
+ var ACTION_TYPE_ALIASES = {
4
+ bid: "qi/bid.submit",
5
+ claim: "qi/claim.submit",
6
+ evaluateBid: "qi/bid.evaluate",
7
+ evaluateClaim: "qi/claim.evaluate",
8
+ "email.send": "qi/email.send",
9
+ "http.request": "qi/http.request",
10
+ "form.submit": "qi/form.submit",
11
+ "human.form.submit": "qi/human.form.submit",
12
+ "human.checkbox.set": "qi/human.checkbox.set",
13
+ "notification.push": "qi/notification.push",
14
+ "proposal.create": "qi/proposal.create",
15
+ "proposal.vote": "qi/proposal.vote",
16
+ "protocol.select": "qi/protocol.select",
17
+ "domain.sign": "qi/domain.sign",
18
+ "domain.create": "qi/domain.create",
19
+ "credential.store": "qi/credential.store",
20
+ payment: "qi/payment.execute",
21
+ "matrix.dm": "qi/matrix.dm"
22
+ };
23
+ var aliases = new Map(Object.entries(ACTION_TYPE_ALIASES));
24
+ function resolveActionType(type) {
25
+ return aliases.get(type) ?? type;
26
+ }
27
+ function registerAction(definition) {
28
+ actions.set(definition.type, definition);
29
+ }
30
+ function getAction(type) {
31
+ return actions.get(resolveActionType(type));
32
+ }
33
+ function getAllActions() {
34
+ return Array.from(actions.values());
35
+ }
36
+ function hasAction(type) {
37
+ return actions.has(resolveActionType(type));
38
+ }
39
+ function getActionByCan(can) {
40
+ for (const action of actions.values()) {
41
+ if (action.can === can) return action;
42
+ }
43
+ return void 0;
44
+ }
45
+
46
+ // src/core/lib/actionRegistry/canMapping.ts
47
+ var CAN_TO_TYPE = {
48
+ "bid/submit": "qi/bid.submit",
49
+ "bid/evaluate": "qi/bid.evaluate",
50
+ "claim/submit": "qi/claim.submit",
51
+ "claim/evaluate": "qi/claim.evaluate",
52
+ "email/send": "qi/email.send",
53
+ "notification/push": "qi/notification.push",
54
+ "matrix/dm": "qi/matrix.dm",
55
+ "proposal/create": "qi/proposal.create",
56
+ "proposal/vote": "qi/proposal.vote",
57
+ "domain/create": "qi/domain.create",
58
+ "domain/sign": "qi/domain.sign",
59
+ "credential/store": "qi/credential.store",
60
+ "payment/execute": "qi/payment.execute",
61
+ "http/request": "qi/http.request",
62
+ "protocol/select": "qi/protocol.select",
63
+ "human/checkbox": "qi/human.checkbox.set",
64
+ "human/form": "qi/human.form.submit",
65
+ "oracle/query": "oracle"
66
+ };
67
+ var TYPE_TO_CAN = Object.fromEntries(Object.entries(CAN_TO_TYPE).map(([can, type]) => [type, can]));
68
+ function canToType(can) {
69
+ return CAN_TO_TYPE[can];
70
+ }
71
+ function typeToCan(type) {
72
+ return TYPE_TO_CAN[type];
73
+ }
74
+ function getAllCanMappings() {
75
+ return Object.entries(CAN_TO_TYPE).map(([can, type]) => ({ can, type }));
76
+ }
77
+
78
+ // src/core/lib/actionRegistry/adapters.ts
79
+ function buildServicesFromHandlers(handlers) {
80
+ return {
81
+ http: {
82
+ request: async (params) => {
83
+ const fetchOptions = {
84
+ method: params.method,
85
+ headers: { "Content-Type": "application/json", ...params.headers }
86
+ };
87
+ if (params.method !== "GET" && params.body) {
88
+ fetchOptions.body = typeof params.body === "string" ? params.body : JSON.stringify(params.body);
89
+ }
90
+ const res = await fetch(params.url, fetchOptions);
91
+ const data = await res.json().catch(() => ({}));
92
+ const responseHeaders = {};
93
+ res.headers.forEach((value, key) => {
94
+ responseHeaders[key] = value;
95
+ });
96
+ return {
97
+ status: res.status,
98
+ headers: responseHeaders,
99
+ data
100
+ };
101
+ }
102
+ },
103
+ email: handlers?.sendEmail ? {
104
+ send: async (params) => {
105
+ const result = await handlers.sendEmail(params);
106
+ return {
107
+ messageId: result.id || "",
108
+ sentAt: (/* @__PURE__ */ new Date()).toISOString()
109
+ };
110
+ }
111
+ } : void 0,
112
+ notify: handlers?.sendNotification ? {
113
+ send: async (params) => {
114
+ const result = await handlers.sendNotification(params);
115
+ return {
116
+ messageId: result.messageId,
117
+ sentAt: result.timestamp || (/* @__PURE__ */ new Date()).toISOString()
118
+ };
119
+ }
120
+ } : void 0,
121
+ bid: handlers?.submitBid && handlers?.approveBid && handlers?.rejectBid && handlers?.approveServiceAgentApplication && handlers?.approveEvaluatorApplication ? {
122
+ submitBid: async (params) => handlers.submitBid(params),
123
+ approveBid: async (params) => handlers.approveBid(params),
124
+ rejectBid: async (params) => handlers.rejectBid(params),
125
+ approveServiceAgentApplication: async (params) => handlers.approveServiceAgentApplication(params),
126
+ approveEvaluatorApplication: async (params) => handlers.approveEvaluatorApplication(params)
127
+ } : void 0,
128
+ claim: handlers?.requestPin && handlers?.submitClaim && handlers?.evaluateClaim && handlers?.getCurrentUser ? {
129
+ requestPin: async (config) => handlers.requestPin(config),
130
+ submitClaim: async (params) => handlers.submitClaim(params),
131
+ evaluateClaim: async (granteeAddress, did, payload) => handlers.evaluateClaim(granteeAddress, did, payload),
132
+ getCurrentUser: () => handlers.getCurrentUser(),
133
+ createUdid: handlers?.createUdid ? async (params) => handlers.createUdid(params) : void 0
134
+ } : void 0,
135
+ matrix: handlers?.storeMatrixCredential ? {
136
+ storeCredential: async (params) => handlers.storeMatrixCredential(params)
137
+ } : void 0
138
+ };
139
+ }
140
+
141
+ // src/core/lib/matrixDm.ts
142
+ function getHomeserver(matrixClient) {
143
+ const userId = matrixClient.getUserId();
144
+ if (!userId) throw new Error("Matrix client has no user ID");
145
+ const idx = userId.indexOf(":");
146
+ if (idx === -1) throw new Error(`Invalid Matrix user ID: ${userId}`);
147
+ return userId.substring(idx + 1);
148
+ }
149
+ function didToMatrixUserId(did, homeserver) {
150
+ const localpart = did.replace(/:/g, "-");
151
+ return `@${localpart}:${homeserver}`;
152
+ }
153
+ async function findOrCreateDMRoom(matrixClient, targetUserId) {
154
+ try {
155
+ const directEvent = matrixClient.getAccountData("m.direct");
156
+ const directContent = directEvent?.getContent() || {};
157
+ const existingRooms = directContent[targetUserId];
158
+ if (existingRooms && existingRooms.length > 0) {
159
+ return existingRooms[0];
160
+ }
161
+ } catch {
162
+ }
163
+ const response = await matrixClient.createRoom({
164
+ is_direct: true,
165
+ invite: [targetUserId],
166
+ preset: "trusted_private_chat",
167
+ initial_state: []
168
+ });
169
+ const roomId = response.room_id;
170
+ try {
171
+ const directEvent = matrixClient.getAccountData("m.direct");
172
+ const directContent = directEvent?.getContent() || {};
173
+ const updatedContent = {
174
+ ...directContent,
175
+ [targetUserId]: [...directContent[targetUserId] || [], roomId]
176
+ };
177
+ await matrixClient.setAccountData("m.direct", updatedContent);
178
+ } catch (error) {
179
+ console.warn("[MatrixDM] Failed to update m.direct account data:", error);
180
+ }
181
+ return roomId;
182
+ }
183
+ async function sendMatrixMessage(matrixClient, roomId, message) {
184
+ await matrixClient.sendEvent(roomId, "m.room.message", {
185
+ msgtype: "m.text",
186
+ body: message
187
+ });
188
+ }
189
+ async function sendDirectMessage(matrixClient, targetDid, message) {
190
+ const homeserver = getHomeserver(matrixClient);
191
+ const targetUserId = didToMatrixUserId(targetDid, homeserver);
192
+ const roomId = await findOrCreateDMRoom(matrixClient, targetUserId);
193
+ await sendMatrixMessage(matrixClient, roomId, message);
194
+ return { roomId };
195
+ }
196
+
197
+ // src/core/lib/actionRegistry/diffRegistry.ts
198
+ var diffResolvers = /* @__PURE__ */ new Map();
199
+ function registerDiffResolver(actionType, reg) {
200
+ diffResolvers.set(actionType, reg);
201
+ }
202
+ function getDiffResolver(actionType) {
203
+ return diffResolvers.get(actionType);
204
+ }
205
+ function hasDiffResolver(actionType) {
206
+ return diffResolvers.has(actionType);
207
+ }
208
+
209
+ // src/core/lib/actionRegistry/actions/httpRequest.ts
210
+ registerAction({
211
+ type: "qi/http.request",
212
+ can: "http/request",
213
+ sideEffect: false,
214
+ defaultRequiresConfirmation: false,
215
+ run: async (inputs, ctx) => {
216
+ const { url, method = "GET", headers = {}, body } = inputs;
217
+ const requestFn = ctx.services.http?.request;
218
+ if (requestFn) {
219
+ const result = await requestFn({ url, method, headers, body });
220
+ return {
221
+ output: {
222
+ status: result.status,
223
+ data: result.data,
224
+ response: JSON.stringify(result.data, null, 2)
225
+ }
226
+ };
227
+ }
228
+ const fetchOptions = {
229
+ method,
230
+ headers: { "Content-Type": "application/json", ...headers }
231
+ };
232
+ if (method !== "GET" && body) {
233
+ fetchOptions.body = typeof body === "string" ? body : JSON.stringify(body);
234
+ }
235
+ const response = await fetch(url, fetchOptions);
236
+ const data = await response.json().catch(() => ({}));
237
+ return {
238
+ output: {
239
+ status: response.status,
240
+ data,
241
+ response: JSON.stringify(data, null, 2)
242
+ }
243
+ };
244
+ }
245
+ });
246
+
247
+ // src/core/lib/actionRegistry/actions/emailSend.ts
248
+ registerAction({
249
+ type: "qi/email.send",
250
+ can: "email/send",
251
+ sideEffect: true,
252
+ defaultRequiresConfirmation: true,
253
+ requiredCapability: "email/send",
254
+ outputSchema: [
255
+ { path: "messageId", displayName: "Message ID", type: "string", description: "The unique ID of the sent email" },
256
+ { path: "sentAt", displayName: "Sent At", type: "string", description: "Timestamp when the email was sent" }
257
+ ],
258
+ run: async (inputs, ctx) => {
259
+ if (!ctx.services.email) {
260
+ throw new Error("Email service not configured");
261
+ }
262
+ const { to, subject, template, templateName, templateVersion, variables, cc, bcc, replyTo } = inputs;
263
+ const resolvedTemplate = template || templateName;
264
+ if (!resolvedTemplate) throw new Error("No template selected");
265
+ if (!to) throw new Error("Recipient (to) is required");
266
+ let resolvedVariables = variables;
267
+ if (typeof resolvedVariables === "string") {
268
+ try {
269
+ resolvedVariables = JSON.parse(resolvedVariables);
270
+ } catch {
271
+ resolvedVariables = {};
272
+ }
273
+ }
274
+ const result = await ctx.services.email.send({
275
+ to,
276
+ subject,
277
+ template: resolvedTemplate,
278
+ templateVersion,
279
+ variables: resolvedVariables,
280
+ cc,
281
+ bcc,
282
+ replyTo
283
+ });
284
+ return {
285
+ output: {
286
+ messageId: result.messageId,
287
+ sentAt: result.sentAt || (/* @__PURE__ */ new Date()).toISOString()
288
+ }
289
+ };
290
+ }
291
+ });
292
+
293
+ // src/core/lib/actionRegistry/actions/humanCheckbox.ts
294
+ registerAction({
295
+ type: "qi/human.checkbox.set",
296
+ can: "human/checkbox",
297
+ sideEffect: true,
298
+ defaultRequiresConfirmation: false,
299
+ requiredCapability: "flow/execute",
300
+ run: async (inputs) => {
301
+ const checked = inputs.checked !== void 0 ? !!inputs.checked : true;
302
+ return { output: { checked } };
303
+ }
304
+ });
305
+
306
+ // src/core/lib/actionRegistry/actions/humanForm.ts
307
+ function normalizeAnswers(rawAnswers) {
308
+ if (rawAnswers == null) {
309
+ return {};
310
+ }
311
+ if (typeof rawAnswers === "string") {
312
+ try {
313
+ const parsed = JSON.parse(rawAnswers);
314
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
315
+ throw new Error();
316
+ }
317
+ return parsed;
318
+ } catch {
319
+ throw new Error("answers must be a valid JSON object");
320
+ }
321
+ }
322
+ if (typeof rawAnswers !== "object" || Array.isArray(rawAnswers)) {
323
+ throw new Error("answers must be an object");
324
+ }
325
+ return rawAnswers;
326
+ }
327
+ function registerFormSubmitAction(type, can) {
328
+ registerAction({
329
+ type,
330
+ can,
331
+ sideEffect: true,
332
+ defaultRequiresConfirmation: false,
333
+ requiredCapability: "flow/execute",
334
+ outputSchema: [
335
+ { path: "form.answers", displayName: "Form Answers JSON", type: "string", description: "JSON stringified form answers, matching form block runtime output." },
336
+ { path: "answers", displayName: "Form Answers", type: "object", description: "Parsed form answers object for convenience." }
337
+ ],
338
+ run: async (inputs) => {
339
+ const answers = normalizeAnswers(inputs.answers ?? inputs.form?.answers);
340
+ const answersJson = JSON.stringify(answers);
341
+ return {
342
+ output: {
343
+ form: {
344
+ answers: answersJson
345
+ },
346
+ answers
347
+ }
348
+ };
349
+ }
350
+ });
351
+ }
352
+ registerFormSubmitAction("qi/form.submit", "form/submit");
353
+ registerFormSubmitAction("qi/human.form.submit", "human/form");
354
+
355
+ // src/core/lib/actionRegistry/actions/notificationPush.ts
356
+ registerAction({
357
+ type: "qi/notification.push",
358
+ can: "notification/push",
359
+ sideEffect: true,
360
+ defaultRequiresConfirmation: true,
361
+ requiredCapability: "notify/send",
362
+ run: async (inputs, ctx) => {
363
+ if (!ctx.services.notify) {
364
+ throw new Error("Notification service not configured");
365
+ }
366
+ const { channel, to, cc, bcc, subject, body, bodyType, from, replyTo } = inputs;
367
+ if (!to || Array.isArray(to) && to.length === 0) {
368
+ throw new Error("At least one recipient is required");
369
+ }
370
+ const result = await ctx.services.notify.send({
371
+ channel,
372
+ to: Array.isArray(to) ? to : [to],
373
+ cc,
374
+ bcc,
375
+ subject,
376
+ body,
377
+ bodyType,
378
+ from,
379
+ replyTo
380
+ });
381
+ return {
382
+ output: {
383
+ messageId: result.messageId,
384
+ sentAt: result.sentAt || (/* @__PURE__ */ new Date()).toISOString()
385
+ }
386
+ };
387
+ }
388
+ });
389
+
390
+ // src/core/lib/actionRegistry/actions/bid/bid.ts
391
+ function normalizeBidRole(role) {
392
+ const normalized = String(role || "").trim().toLowerCase();
393
+ if (normalized === "service_agent" || normalized === "sa") return "SA";
394
+ if (normalized === "evaluation_agent" || normalized === "ea") return "EA";
395
+ throw new Error("Invalid bid role. Expected service_agent or evaluation_agent");
396
+ }
397
+ registerAction({
398
+ type: "qi/bid.submit",
399
+ can: "bid/submit",
400
+ sideEffect: true,
401
+ defaultRequiresConfirmation: true,
402
+ requiredCapability: "flow/block/execute",
403
+ outputSchema: [
404
+ { path: "bidId", displayName: "Bid ID", type: "string", description: "The submitted bid identifier" },
405
+ { path: "collectionId", displayName: "Collection ID", type: "string", description: "Claim collection identifier" },
406
+ { path: "role", displayName: "Role", type: "string", description: "Submitted role (service_agent or evaluation_agent)" },
407
+ { path: "submitterDid", displayName: "Submitter DID", type: "string", description: "Actor DID that submitted the bid" },
408
+ { path: "deedDid", displayName: "Deed DID", type: "string", description: "Deed identifier if provided" }
409
+ ],
410
+ run: async (inputs, ctx) => {
411
+ const service = ctx.services.bid;
412
+ if (!service) {
413
+ throw new Error("Bid service not configured");
414
+ }
415
+ const collectionId = String(inputs.collectionId || "").trim();
416
+ const roleInput = String(inputs.role || "").trim();
417
+ let surveyAnswers = inputs.surveyAnswers;
418
+ const deedDid = String(inputs.deedDid || "").trim();
419
+ if (!collectionId) throw new Error("collectionId is required");
420
+ if (!roleInput) throw new Error("role is required");
421
+ if (typeof surveyAnswers === "string") {
422
+ try {
423
+ surveyAnswers = JSON.parse(surveyAnswers);
424
+ } catch {
425
+ throw new Error("surveyAnswers must be a valid JSON object");
426
+ }
427
+ }
428
+ if (!surveyAnswers || typeof surveyAnswers !== "object" || Array.isArray(surveyAnswers)) {
429
+ throw new Error("surveyAnswers must be an object");
430
+ }
431
+ const chainRole = normalizeBidRole(roleInput);
432
+ const submission = await service.submitBid({
433
+ collectionId,
434
+ role: chainRole,
435
+ surveyAnswers
436
+ });
437
+ const bidId = String(submission?.claimId || submission?.bidId || submission?.id || "");
438
+ if (!bidId) {
439
+ throw new Error("submitBid returned no bid identifier");
440
+ }
441
+ return {
442
+ output: {
443
+ bidId,
444
+ collectionId,
445
+ role: roleInput,
446
+ submitterDid: ctx.actorDid || "",
447
+ deedDid
448
+ }
449
+ };
450
+ }
451
+ });
452
+
453
+ // src/core/lib/actionRegistry/actions/evaluateBid/evaluateBid.ts
454
+ function normalizeDecision(value) {
455
+ const normalized = String(value || "").trim().toLowerCase();
456
+ if (normalized === "approve" || normalized === "reject") {
457
+ return normalized;
458
+ }
459
+ throw new Error("decision must be either approve or reject");
460
+ }
461
+ function isServiceAgentRole(role) {
462
+ const normalized = String(role || "").trim().toLowerCase();
463
+ return normalized === "service_agent" || normalized === "sa";
464
+ }
465
+ function isEvaluationAgentRole(role) {
466
+ const normalized = String(role || "").trim().toLowerCase();
467
+ return normalized === "evaluation_agent" || normalized === "ea";
468
+ }
469
+ registerAction({
470
+ type: "qi/bid.evaluate",
471
+ can: "bid/evaluate",
472
+ sideEffect: true,
473
+ defaultRequiresConfirmation: true,
474
+ requiredCapability: "flow/block/execute",
475
+ outputSchema: [
476
+ { path: "bidId", displayName: "Bid ID", type: "string", description: "Evaluated bid identifier" },
477
+ { path: "decision", displayName: "Decision", type: "string", description: "approve or reject" },
478
+ { path: "status", displayName: "Status", type: "string", description: "approved or rejected" },
479
+ { path: "evaluatedByDid", displayName: "Evaluated By DID", type: "string", description: "Actor DID that evaluated the bid" },
480
+ { path: "evaluatedAt", displayName: "Evaluated At", type: "string", description: "ISO timestamp of evaluation" },
481
+ { path: "reason", displayName: "Reason", type: "string", description: "Rejection reason when decision is reject" },
482
+ { path: "collectionId", displayName: "Collection ID", type: "string", description: "Claim collection identifier" },
483
+ { path: "role", displayName: "Role", type: "string", description: "Applicant role" },
484
+ { path: "deedDid", displayName: "Deed DID", type: "string", description: "Deed identifier" },
485
+ { path: "applicantDid", displayName: "Applicant DID", type: "string", description: "Applicant DID" },
486
+ { path: "applicantAddress", displayName: "Applicant Address", type: "string", description: "Applicant wallet address" }
487
+ ],
488
+ run: async (inputs, ctx) => {
489
+ const service = ctx.services.bid;
490
+ if (!service) {
491
+ throw new Error("Bid service not configured");
492
+ }
493
+ const decision = normalizeDecision(inputs.decision);
494
+ const bidId = String(inputs.bidId || "").trim();
495
+ const collectionId = String(inputs.collectionId || "").trim();
496
+ const deedDid = String(inputs.deedDid || "").trim();
497
+ const role = String(inputs.role || "").trim();
498
+ const applicantDid = String(inputs.applicantDid || "").trim();
499
+ const applicantAddress = String(inputs.applicantAddress || "").trim();
500
+ if (!bidId) throw new Error("bidId is required");
501
+ if (!collectionId) throw new Error("collectionId is required");
502
+ if (!deedDid) throw new Error("deedDid is required");
503
+ if (!role) throw new Error("role is required");
504
+ if (!applicantDid) throw new Error("applicantDid is required");
505
+ if (!applicantAddress) throw new Error("applicantAddress is required");
506
+ if (decision === "approve") {
507
+ const adminAddress = String(inputs.adminAddress || "").trim();
508
+ if (!adminAddress) {
509
+ throw new Error("adminAddress is required when decision is approve");
510
+ }
511
+ if (isServiceAgentRole(role)) {
512
+ await service.approveServiceAgentApplication({
513
+ adminAddress,
514
+ collectionId,
515
+ agentQuota: 30,
516
+ deedDid,
517
+ currentUserAddress: applicantAddress
518
+ });
519
+ } else if (isEvaluationAgentRole(role)) {
520
+ let maxAmounts = inputs.maxAmounts;
521
+ if (typeof maxAmounts === "string") {
522
+ try {
523
+ maxAmounts = JSON.parse(maxAmounts);
524
+ } catch {
525
+ throw new Error("maxAmounts must be valid JSON when provided");
526
+ }
527
+ }
528
+ await service.approveEvaluatorApplication({
529
+ adminAddress,
530
+ collectionId,
531
+ deedDid,
532
+ evaluatorAddress: applicantAddress,
533
+ agentQuota: 10,
534
+ maxAmounts: Array.isArray(maxAmounts) ? maxAmounts : void 0
535
+ });
536
+ } else {
537
+ throw new Error("Invalid role for evaluation. Expected service_agent or evaluation_agent");
538
+ }
539
+ await service.approveBid({
540
+ bidId,
541
+ collectionId,
542
+ did: applicantDid
543
+ });
544
+ } else {
545
+ const reason = String(inputs.reason || "").trim();
546
+ if (!reason) {
547
+ throw new Error("reason is required when decision is reject");
548
+ }
549
+ await service.rejectBid({
550
+ bidId,
551
+ collectionId,
552
+ did: deedDid,
553
+ reason
554
+ });
555
+ }
556
+ return {
557
+ output: {
558
+ bidId,
559
+ decision,
560
+ status: decision === "approve" ? "approved" : "rejected",
561
+ evaluatedByDid: ctx.actorDid || "",
562
+ evaluatedAt: (/* @__PURE__ */ new Date()).toISOString(),
563
+ reason: decision === "reject" ? String(inputs.reason || "") : "",
564
+ collectionId,
565
+ role,
566
+ deedDid,
567
+ applicantDid,
568
+ applicantAddress
569
+ }
570
+ };
571
+ }
572
+ });
573
+
574
+ // src/core/lib/actionRegistry/actions/claim/claim.ts
575
+ registerAction({
576
+ type: "qi/claim.submit",
577
+ can: "claim/submit",
578
+ sideEffect: true,
579
+ defaultRequiresConfirmation: true,
580
+ requiredCapability: "flow/block/execute",
581
+ outputSchema: [
582
+ { path: "claimId", displayName: "Claim ID", type: "string", description: "The submitted claim identifier" },
583
+ { path: "transactionHash", displayName: "Transaction Hash", type: "string", description: "Submission transaction hash" },
584
+ { path: "collectionId", displayName: "Collection ID", type: "string", description: "Claim collection identifier" },
585
+ { path: "deedDid", displayName: "Deed DID", type: "string", description: "Deed identifier" },
586
+ { path: "submittedByDid", displayName: "Submitted By DID", type: "string", description: "Actor DID that submitted the claim" },
587
+ { path: "submittedAt", displayName: "Submitted At", type: "string", description: "ISO timestamp of submission" }
588
+ ],
589
+ run: async (inputs, ctx) => {
590
+ const service = ctx.services.claim;
591
+ if (!service) {
592
+ throw new Error("Claim service not configured");
593
+ }
594
+ const deedDid = String(inputs.deedDid || "").trim();
595
+ const collectionId = String(inputs.collectionId || "").trim();
596
+ const adminAddress = String(inputs.adminAddress || "").trim();
597
+ if (!deedDid) throw new Error("deedDid is required");
598
+ if (!collectionId) throw new Error("collectionId is required");
599
+ if (!adminAddress) throw new Error("adminAddress is required");
600
+ let surveyAnswers = inputs.surveyAnswers;
601
+ if (typeof surveyAnswers === "string") {
602
+ try {
603
+ surveyAnswers = JSON.parse(surveyAnswers);
604
+ } catch {
605
+ throw new Error("surveyAnswers must be valid JSON");
606
+ }
607
+ }
608
+ if (!surveyAnswers || typeof surveyAnswers !== "object" || Array.isArray(surveyAnswers)) {
609
+ throw new Error("surveyAnswers must be an object");
610
+ }
611
+ let pin = String(inputs.pin || "").trim();
612
+ if (!pin) {
613
+ pin = await service.requestPin({
614
+ title: "Verify Identity",
615
+ description: "Enter your PIN to submit the claim",
616
+ submitText: "Verify"
617
+ });
618
+ }
619
+ if (!pin) {
620
+ throw new Error("PIN is required to submit claim");
621
+ }
622
+ const result = await service.submitClaim({
623
+ surveyData: surveyAnswers,
624
+ deedDid,
625
+ collectionId,
626
+ adminAddress,
627
+ pin
628
+ });
629
+ const claimId = String(result?.claimId || result?.id || "");
630
+ if (!claimId) {
631
+ throw new Error("submitClaim returned no claim identifier");
632
+ }
633
+ return {
634
+ output: {
635
+ claimId,
636
+ transactionHash: String(result?.transactionHash || ""),
637
+ collectionId,
638
+ deedDid,
639
+ submittedByDid: ctx.actorDid || "",
640
+ submittedAt: (/* @__PURE__ */ new Date()).toISOString()
641
+ }
642
+ };
643
+ }
644
+ });
645
+
646
+ // src/core/lib/actionRegistry/actions/evaluateClaim/evaluateClaim.ts
647
+ function normalizeDecision2(value) {
648
+ const normalized = String(value || "").trim().toLowerCase();
649
+ if (normalized === "approve" || normalized === "reject") {
650
+ return normalized;
651
+ }
652
+ throw new Error("decision must be either approve or reject");
653
+ }
654
+ function toStatus(decision) {
655
+ return decision === "approve" ? 1 : 2;
656
+ }
657
+ function isEvaluatorRole(role) {
658
+ const normalized = String(role || "").trim().toLowerCase();
659
+ return normalized === "ea" || normalized === "evaluation_agent";
660
+ }
661
+ registerAction({
662
+ type: "qi/claim.evaluate",
663
+ can: "claim/evaluate",
664
+ sideEffect: true,
665
+ defaultRequiresConfirmation: true,
666
+ requiredCapability: "flow/block/execute",
667
+ outputSchema: [
668
+ { path: "claimId", displayName: "Claim ID", type: "string", description: "Evaluated claim identifier" },
669
+ { path: "decision", displayName: "Decision", type: "string", description: "approve or reject" },
670
+ { path: "status", displayName: "Status", type: "string", description: "approved or rejected" },
671
+ { path: "verificationProof", displayName: "Verification Proof", type: "string", description: "UDID URL proof if generated" },
672
+ { path: "collectionId", displayName: "Collection ID", type: "string", description: "Claim collection identifier" },
673
+ { path: "deedDid", displayName: "Deed DID", type: "string", description: "Deed identifier" },
674
+ { path: "evaluatedByDid", displayName: "Evaluated By DID", type: "string", description: "Actor DID that evaluated the claim" },
675
+ { path: "evaluatedAt", displayName: "Evaluated At", type: "string", description: "ISO timestamp of evaluation" }
676
+ ],
677
+ run: async (inputs, ctx) => {
678
+ const service = ctx.services.claim;
679
+ if (!service) {
680
+ throw new Error("Claim service not configured");
681
+ }
682
+ const decision = normalizeDecision2(inputs.decision);
683
+ const claimId = String(inputs.claimId || "").trim();
684
+ const collectionId = String(inputs.collectionId || "").trim();
685
+ const deedDid = String(inputs.deedDid || "").trim();
686
+ const adminAddress = String(inputs.adminAddress || "").trim();
687
+ if (!claimId) throw new Error("claimId is required");
688
+ if (!collectionId) throw new Error("collectionId is required");
689
+ if (!deedDid) throw new Error("deedDid is required");
690
+ if (!adminAddress) throw new Error("adminAddress is required");
691
+ const handlers = ctx.handlers;
692
+ const actorAddress = String(ctx.actorDid || service.getCurrentUser?.()?.address || "").trim();
693
+ if (!actorAddress) {
694
+ throw new Error("Unable to resolve actor address for evaluator authorization");
695
+ }
696
+ if (typeof handlers?.getUserRoles !== "function") {
697
+ throw new Error("Evaluator authorization check unavailable (getUserRoles handler missing)");
698
+ }
699
+ const roles = await handlers.getUserRoles({
700
+ userAddress: actorAddress,
701
+ adminAddress,
702
+ deedDid,
703
+ collectionIds: [collectionId]
704
+ });
705
+ const roleForCollection = Array.isArray(roles) ? roles.find((r) => r?.collectionId === collectionId)?.role : void 0;
706
+ if (!isEvaluatorRole(roleForCollection)) {
707
+ throw new Error("Not authorized: evaluator role required to evaluate claims for this collection");
708
+ }
709
+ let amount = inputs.amount;
710
+ if (typeof amount === "string" && amount.trim()) {
711
+ try {
712
+ amount = JSON.parse(amount);
713
+ } catch {
714
+ throw new Error("amount must be valid JSON when provided as string");
715
+ }
716
+ }
717
+ const normalizeCoin = (coin) => {
718
+ if (!coin || typeof coin !== "object" || Array.isArray(coin)) return null;
719
+ const denom = String(coin.denom || "").trim();
720
+ const tokenAmount = String(coin.amount || "").trim();
721
+ if (!denom || !tokenAmount) return null;
722
+ return { denom, amount: tokenAmount };
723
+ };
724
+ let normalizedAmounts;
725
+ if (Array.isArray(amount)) {
726
+ normalizedAmounts = amount.map(normalizeCoin).filter((coin) => !!coin);
727
+ if (normalizedAmounts.length !== amount.length) {
728
+ throw new Error("amount must contain valid coin objects with denom and amount");
729
+ }
730
+ } else if (amount != null) {
731
+ const coin = normalizeCoin(amount);
732
+ if (!coin) {
733
+ throw new Error("amount must be a coin object or an array of coin objects");
734
+ }
735
+ normalizedAmounts = [coin];
736
+ }
737
+ let verificationProof = String(inputs.verificationProof || "").trim();
738
+ const shouldCreateUdid = Boolean(inputs.createUdid);
739
+ if (!verificationProof && shouldCreateUdid && service.createUdid) {
740
+ const pin = await service.requestPin({
741
+ title: "Sign Evaluation Result",
742
+ description: "Enter your PIN to sign the evaluation UDID",
743
+ submitText: "Sign"
744
+ });
745
+ if (!pin) {
746
+ throw new Error("PIN is required to sign evaluation proof");
747
+ }
748
+ const udid = await service.createUdid({
749
+ claimCid: claimId,
750
+ deedDid,
751
+ collectionId,
752
+ capabilityCid: String(inputs.capabilityCid || deedDid),
753
+ rubricAuthority: String(inputs.rubricAuthority || deedDid),
754
+ rubricId: String(inputs.rubricId || deedDid),
755
+ outcome: toStatus(decision),
756
+ tag: decision === "approve" ? "approved" : "rejected",
757
+ issuerType: "user",
758
+ pin,
759
+ traceCid: inputs.traceCid,
760
+ items: inputs.items,
761
+ patch: inputs.patch
762
+ });
763
+ verificationProof = String(udid?.url || udid?.cid || "");
764
+ }
765
+ const currentUser = service.getCurrentUser();
766
+ const granteeAddress = String(inputs.granteeAddress || currentUser?.address || "").trim();
767
+ if (!granteeAddress) {
768
+ throw new Error("granteeAddress could not be resolved");
769
+ }
770
+ await service.evaluateClaim(granteeAddress, deedDid, {
771
+ claimId,
772
+ collectionId,
773
+ adminAddress,
774
+ status: toStatus(decision),
775
+ verificationProof,
776
+ amount: normalizedAmounts && normalizedAmounts.length > 0 ? normalizedAmounts.length === 1 ? normalizedAmounts[0] : normalizedAmounts : void 0
777
+ });
778
+ return {
779
+ output: {
780
+ claimId,
781
+ decision,
782
+ status: decision === "approve" ? "approved" : "rejected",
783
+ verificationProof,
784
+ collectionId,
785
+ deedDid,
786
+ evaluatedByDid: ctx.actorDid || granteeAddress,
787
+ evaluatedAt: (/* @__PURE__ */ new Date()).toISOString()
788
+ }
789
+ };
790
+ }
791
+ });
792
+
793
+ // src/core/lib/actionRegistry/actions/proposalCreate.ts
794
+ registerAction({
795
+ type: "qi/proposal.create",
796
+ can: "proposal/create",
797
+ sideEffect: true,
798
+ defaultRequiresConfirmation: true,
799
+ requiredCapability: "flow/block/execute",
800
+ outputSchema: [
801
+ { path: "proposalId", displayName: "Proposal ID", type: "string", description: "The on-chain proposal identifier" },
802
+ { path: "status", displayName: "Proposal Status", type: "string", description: "Current proposal status (open, passed, rejected, executed, etc.)" },
803
+ { path: "proposalContractAddress", displayName: "Proposal Contract Address", type: "string", description: "The proposal module contract address" },
804
+ { path: "coreAddress", displayName: "Core Address", type: "string", description: "The DAO core contract address" },
805
+ { path: "createdAt", displayName: "Created At", type: "string", description: "ISO timestamp of proposal creation" }
806
+ ],
807
+ run: async (inputs, ctx) => {
808
+ const handlers = ctx.handlers;
809
+ if (!handlers) {
810
+ throw new Error("Handlers not available");
811
+ }
812
+ const coreAddress = String(inputs.coreAddress || "").trim();
813
+ const title = String(inputs.title || "").trim();
814
+ const description = String(inputs.description || "").trim();
815
+ if (!coreAddress) throw new Error("coreAddress is required");
816
+ if (!title) throw new Error("title is required");
817
+ if (!description) throw new Error("description is required");
818
+ let actions2 = [];
819
+ if (inputs.actions) {
820
+ if (typeof inputs.actions === "string") {
821
+ try {
822
+ actions2 = JSON.parse(inputs.actions);
823
+ } catch {
824
+ throw new Error("actions must be valid JSON array");
825
+ }
826
+ } else if (Array.isArray(inputs.actions)) {
827
+ actions2 = inputs.actions;
828
+ }
829
+ }
830
+ const { preProposalContractAddress } = await handlers.getPreProposalContractAddress({
831
+ coreAddress
832
+ });
833
+ const { groupContractAddress } = await handlers.getGroupContractAddress({
834
+ coreAddress
835
+ });
836
+ const { proposalContractAddress } = await handlers.getProposalContractAddress({
837
+ coreAddress
838
+ });
839
+ const params = {
840
+ preProposalContractAddress,
841
+ title,
842
+ description,
843
+ actions: actions2.length > 0 ? actions2 : void 0,
844
+ coreAddress,
845
+ groupContractAddress
846
+ };
847
+ const proposalId = await handlers.createProposal(params);
848
+ return {
849
+ output: {
850
+ proposalId: String(proposalId),
851
+ status: "open",
852
+ proposalContractAddress: proposalContractAddress || "",
853
+ coreAddress,
854
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
855
+ }
856
+ };
857
+ }
858
+ });
859
+
860
+ // src/core/lib/actionRegistry/actions/proposalVote.ts
861
+ registerAction({
862
+ type: "qi/proposal.vote",
863
+ can: "proposal/vote",
864
+ sideEffect: true,
865
+ defaultRequiresConfirmation: true,
866
+ requiredCapability: "flow/block/execute",
867
+ outputSchema: [
868
+ { path: "vote", displayName: "Vote", type: "string", description: "The vote cast (yes, no, no_with_veto, abstain)" },
869
+ { path: "rationale", displayName: "Rationale", type: "string", description: "Optional rationale provided with the vote" },
870
+ { path: "proposalId", displayName: "Proposal ID", type: "string", description: "The proposal that was voted on" },
871
+ { path: "votedAt", displayName: "Voted At", type: "string", description: "ISO timestamp of when the vote was cast" }
872
+ ],
873
+ run: async (inputs, ctx) => {
874
+ const handlers = ctx.handlers;
875
+ if (!handlers) {
876
+ throw new Error("Handlers not available");
877
+ }
878
+ const proposalId = Number(inputs.proposalId);
879
+ const vote = String(inputs.vote || "").trim();
880
+ const rationale = String(inputs.rationale || "").trim();
881
+ const proposalContractAddress = String(inputs.proposalContractAddress || "").trim();
882
+ if (!proposalId || isNaN(proposalId)) throw new Error("proposalId is required");
883
+ if (!vote) throw new Error("vote is required");
884
+ if (!proposalContractAddress) throw new Error("proposalContractAddress is required");
885
+ const validVotes = ["yes", "no", "no_with_veto", "abstain"];
886
+ if (!validVotes.includes(vote)) {
887
+ throw new Error(`vote must be one of: ${validVotes.join(", ")}`);
888
+ }
889
+ await handlers.vote({
890
+ proposalId,
891
+ vote,
892
+ rationale: rationale || void 0,
893
+ proposalContractAddress
894
+ });
895
+ return {
896
+ output: {
897
+ vote,
898
+ rationale: rationale || "",
899
+ proposalId: String(proposalId),
900
+ votedAt: (/* @__PURE__ */ new Date()).toISOString()
901
+ }
902
+ };
903
+ }
904
+ });
905
+
906
+ // src/core/lib/actionRegistry/actions/protocolSelect.ts
907
+ registerAction({
908
+ type: "qi/protocol.select",
909
+ can: "protocol/select",
910
+ sideEffect: false,
911
+ defaultRequiresConfirmation: false,
912
+ outputSchema: [
913
+ { path: "selectedProtocolDid", displayName: "Selected Protocol DID", type: "string", description: "DID of the selected protocol" },
914
+ { path: "selectedProtocolName", displayName: "Selected Protocol Name", type: "string", description: "Display name of the selected protocol" },
915
+ { path: "selectedProtocolType", displayName: "Selected Protocol Type", type: "string", description: "Type of the selected protocol" }
916
+ ],
917
+ run: async (inputs, _ctx) => {
918
+ const selectedProtocolDid = String(inputs.selectedProtocolDid || "").trim();
919
+ const selectedProtocolName = String(inputs.selectedProtocolName || "").trim();
920
+ const selectedProtocolType = String(inputs.selectedProtocolType || "").trim();
921
+ if (!selectedProtocolDid) throw new Error("selectedProtocolDid is required");
922
+ return {
923
+ output: {
924
+ selectedProtocolDid,
925
+ selectedProtocolName,
926
+ selectedProtocolType
927
+ }
928
+ };
929
+ }
930
+ });
931
+
932
+ // src/mantine/blocks/domainCreator/utils/buildVerifiableCredential.ts
933
+ var DOMAIN_CARD_CONTEXT = [
934
+ "https://w3id.org/ixo/context/v1",
935
+ {
936
+ schema: "https://schema.org/",
937
+ ixo: "https://w3id.org/ixo/vocab/v1",
938
+ prov: "http://www.w3.org/ns/prov#",
939
+ proj: "http://www.w3.org/ns/project#",
940
+ id: "@id",
941
+ type: "@type",
942
+ "@protected": true
943
+ }
944
+ ];
945
+ var DOMAIN_CARD_SCHEMA = {
946
+ id: "https://w3id.org/ixo/protocol/schema/v1#domainCard",
947
+ type: "JsonSchema"
948
+ };
949
+ function toISOString(dateInput, fallback = /* @__PURE__ */ new Date()) {
950
+ if (!dateInput) {
951
+ return fallback.toISOString();
952
+ }
953
+ if (dateInput instanceof Date) {
954
+ return dateInput.toISOString();
955
+ }
956
+ if (/^\d{4}-\d{2}-\d{2}$/.test(dateInput)) {
957
+ return (/* @__PURE__ */ new Date(dateInput + "T00:00:00.000Z")).toISOString();
958
+ }
959
+ if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(dateInput)) {
960
+ return (/* @__PURE__ */ new Date(dateInput + ":00.000Z")).toISOString();
961
+ }
962
+ const parsed = new Date(dateInput);
963
+ if (!isNaN(parsed.getTime())) {
964
+ return parsed.toISOString();
965
+ }
966
+ return fallback.toISOString();
967
+ }
968
+ function getDefaultValidUntil(validFrom) {
969
+ const fromDate = new Date(validFrom);
970
+ const untilDate = new Date(fromDate);
971
+ untilDate.setFullYear(untilDate.getFullYear() + 5);
972
+ return untilDate.toISOString();
973
+ }
974
+ function buildVerifiableCredential(params) {
975
+ const { entityDid, issuerDid, credentialSubject, validFrom, validUntil } = params;
976
+ const validFromISO = toISOString(validFrom);
977
+ const validUntilISO = validUntil ? toISOString(validUntil) : getDefaultValidUntil(validFromISO);
978
+ return {
979
+ "@context": DOMAIN_CARD_CONTEXT,
980
+ id: `${entityDid}#dmn`,
981
+ type: ["VerifiableCredential", "ixo:DomainCard"],
982
+ issuer: {
983
+ id: issuerDid
984
+ },
985
+ validFrom: validFromISO,
986
+ validUntil: validUntilISO,
987
+ credentialSchema: DOMAIN_CARD_SCHEMA,
988
+ credentialSubject: {
989
+ ...credentialSubject,
990
+ // Ensure the subject ID matches the entity DID
991
+ id: entityDid
992
+ }
993
+ };
994
+ }
995
+ function buildDomainCardLinkedResource(params) {
996
+ return {
997
+ id: `${params.entityDid}#dmn`,
998
+ type: "domainCard",
999
+ proof: params.cid,
1000
+ right: "",
1001
+ encrypted: "false",
1002
+ mediaType: "application/json",
1003
+ description: params.description || "Domain Card",
1004
+ serviceEndpoint: params.serviceEndpoint
1005
+ };
1006
+ }
1007
+
1008
+ // src/mantine/blocks/domainCreatorSign/utils/buildLinkedEntityResource.ts
1009
+ function parseLinkedEntities(entitiesString) {
1010
+ if (!entitiesString || entitiesString === "[]") return [];
1011
+ try {
1012
+ return JSON.parse(entitiesString);
1013
+ } catch {
1014
+ return [];
1015
+ }
1016
+ }
1017
+ function buildGovernanceGroupLinkedEntities(linkedEntities) {
1018
+ return linkedEntities.filter((entity) => entity.type === "governanceGroup" && entity.coreAddress).map((entity) => ({
1019
+ id: entity.coreAddress,
1020
+ type: "group",
1021
+ relationship: "governs",
1022
+ service: ""
1023
+ }));
1024
+ }
1025
+
1026
+ // src/core/lib/actionRegistry/actions/domainSign.ts
1027
+ registerAction({
1028
+ type: "qi/domain.sign",
1029
+ can: "domain/sign",
1030
+ sideEffect: true,
1031
+ defaultRequiresConfirmation: true,
1032
+ requiredCapability: "flow/block/execute",
1033
+ outputSchema: [
1034
+ { path: "entityDid", displayName: "Entity DID", type: "string", description: "The DID of the newly created domain entity" },
1035
+ { path: "transactionHash", displayName: "Transaction Hash", type: "string", description: "The on-chain transaction hash for domain creation" }
1036
+ ],
1037
+ run: async (inputs, ctx) => {
1038
+ const handlers = ctx.handlers;
1039
+ if (!handlers) {
1040
+ throw new Error("Handlers not available");
1041
+ }
1042
+ if (!handlers.requestPin) throw new Error("requestPin handler not available");
1043
+ if (!handlers.signCredential) throw new Error("signCredential handler not implemented");
1044
+ if (!handlers.publicFileUpload) throw new Error("publicFileUpload handler not available");
1045
+ if (!handlers.createDomain) throw new Error("createDomain handler not implemented");
1046
+ let domainCardData;
1047
+ if (typeof inputs.domainCardData === "string") {
1048
+ try {
1049
+ domainCardData = JSON.parse(inputs.domainCardData);
1050
+ } catch {
1051
+ throw new Error("domainCardData must be valid JSON");
1052
+ }
1053
+ } else if (inputs.domainCardData && typeof inputs.domainCardData === "object") {
1054
+ domainCardData = inputs.domainCardData;
1055
+ } else {
1056
+ throw new Error("domainCardData is required");
1057
+ }
1058
+ if (!domainCardData?.credentialSubject?.name) {
1059
+ throw new Error("domainCardData is missing or invalid (credentialSubject.name required)");
1060
+ }
1061
+ const extractEntityType = (type) => type.replace(/^schema:/i, "").toLowerCase();
1062
+ const entityType = String(inputs.entityType || "").trim() || (domainCardData.credentialSubject?.type?.[0] ? extractEntityType(domainCardData.credentialSubject.type[0]) : "dao");
1063
+ const issuerDid = handlers.getEntityDid?.() || handlers.getCurrentUser?.()?.address;
1064
+ if (!issuerDid) throw new Error("Unable to determine issuer DID");
1065
+ const entityDidPlaceholder = "did:ixo:entity:pending";
1066
+ const validFrom = domainCardData.validFrom || (/* @__PURE__ */ new Date()).toISOString();
1067
+ const validUntil = domainCardData.validUntil || (() => {
1068
+ const d = /* @__PURE__ */ new Date();
1069
+ d.setFullYear(d.getFullYear() + 100);
1070
+ return d.toISOString();
1071
+ })();
1072
+ const credentialSubject = {
1073
+ ...domainCardData.credentialSubject,
1074
+ id: entityDidPlaceholder
1075
+ };
1076
+ const unsignedCredential = buildVerifiableCredential({
1077
+ entityDid: entityDidPlaceholder,
1078
+ issuerDid,
1079
+ credentialSubject,
1080
+ validFrom,
1081
+ validUntil
1082
+ });
1083
+ const pin = await handlers.requestPin({
1084
+ title: "Sign Domain Card",
1085
+ description: "Enter your PIN to sign the Domain Card credential",
1086
+ submitText: "Sign"
1087
+ });
1088
+ const { signedCredential } = await handlers.signCredential({
1089
+ issuerDid,
1090
+ issuerType: "user",
1091
+ credential: unsignedCredential,
1092
+ pin
1093
+ });
1094
+ const credentialBlob = new Blob([JSON.stringify(signedCredential, null, 2)], {
1095
+ type: "application/json"
1096
+ });
1097
+ const credentialFile = new File([credentialBlob], "domainCard.json", {
1098
+ type: "application/json"
1099
+ });
1100
+ const uploadResult = await handlers.publicFileUpload(credentialFile);
1101
+ const domainCardLinkedResource = buildDomainCardLinkedResource({
1102
+ entityDid: entityDidPlaceholder,
1103
+ cid: uploadResult.cid,
1104
+ serviceEndpoint: uploadResult.url,
1105
+ description: `Domain Card for ${domainCardData.credentialSubject?.name || "Domain"}`
1106
+ });
1107
+ let linkedEntitiesData = [];
1108
+ if (inputs.linkedEntities) {
1109
+ if (typeof inputs.linkedEntities === "string") {
1110
+ try {
1111
+ linkedEntitiesData = JSON.parse(inputs.linkedEntities);
1112
+ } catch {
1113
+ }
1114
+ } else if (Array.isArray(inputs.linkedEntities)) {
1115
+ linkedEntitiesData = inputs.linkedEntities;
1116
+ }
1117
+ }
1118
+ const governanceGroupLinkedEntities = buildGovernanceGroupLinkedEntities(parseLinkedEntities(JSON.stringify(linkedEntitiesData)));
1119
+ const endDate = domainCardData.endDate || validUntil;
1120
+ const { entityDid: newEntityDid, transactionHash } = await handlers.createDomain({
1121
+ entityType,
1122
+ linkedResource: [domainCardLinkedResource],
1123
+ linkedEntity: governanceGroupLinkedEntities.length > 0 ? governanceGroupLinkedEntities : void 0,
1124
+ startDate: validFrom,
1125
+ endDate
1126
+ });
1127
+ return {
1128
+ output: {
1129
+ entityDid: newEntityDid,
1130
+ transactionHash
1131
+ }
1132
+ };
1133
+ }
1134
+ });
1135
+
1136
+ // src/mantine/blocks/domainCreator/utils/transformSurveyToCredentialSubject.ts
1137
+ function extractPanelDynamicItems(surveyData, panelName, itemMapper) {
1138
+ const items = surveyData[panelName];
1139
+ if (!Array.isArray(items)) return [];
1140
+ return items.map(itemMapper).filter((item) => item !== null);
1141
+ }
1142
+ function parseCommaSeparated(value) {
1143
+ if (!value || typeof value !== "string") return [];
1144
+ return value.split(",").map((s) => s.trim()).filter(Boolean);
1145
+ }
1146
+ function parseLanguageCodes(value) {
1147
+ return parseCommaSeparated(value);
1148
+ }
1149
+ function buildImageObject(url) {
1150
+ if (!url) return null;
1151
+ return {
1152
+ type: "schema:ImageObject",
1153
+ id: url,
1154
+ contentUrl: url
1155
+ };
1156
+ }
1157
+ function transformSurveyToCredentialSubject(surveyData, entityDid) {
1158
+ const types = [];
1159
+ if (surveyData["type_1"]) types.push(`ixo:${surveyData["type_1"]}`);
1160
+ if (surveyData["type_2"]) types.push(surveyData["type_2"]);
1161
+ const additionalType = [];
1162
+ if (surveyData["daoType"]) additionalType.push(surveyData["daoType"]);
1163
+ const alternateNames = extractPanelDynamicItems(surveyData, "pannel_schema:alternateName", (item) => item["schema:alternateName"] || null);
1164
+ const sameAsUrls = extractPanelDynamicItems(surveyData, "schema:sameAs", (item) => item["schema:sameAs.url"] || null);
1165
+ const logoUrl = surveyData["ixo:imageLogo_url"] || surveyData["ixo:imageLogo"]?.[0]?.content;
1166
+ const logo = buildImageObject(logoUrl);
1167
+ const profileImageUrl = surveyData["ixo:imageProfile_url"] || surveyData["ixo:imageProfile"]?.[0]?.content;
1168
+ const profileImage = buildImageObject(profileImageUrl);
1169
+ const keywords = parseCommaSeparated(surveyData["schema:keywords"]);
1170
+ const knowsAbout = extractPanelDynamicItems(surveyData, "pannel_ixo:knowsAbout", (item) => item["ixo:knowsAbout"] || null);
1171
+ const hasAddressData = surveyData["schema:streetAddress"] || surveyData["schema:addressLocality"] || surveyData["schema:addressRegion"] || surveyData["schema:postalCode"] || surveyData["schema:addressCountry"];
1172
+ const address = hasAddressData ? {
1173
+ type: "schema:PostalAddress",
1174
+ streetAddress: surveyData["schema:streetAddress"] || void 0,
1175
+ addressLocality: surveyData["schema:addressLocality"] || void 0,
1176
+ addressRegion: surveyData["schema:addressRegion"] || void 0,
1177
+ postalCode: surveyData["schema:postalCode"] || void 0,
1178
+ addressCountry: surveyData["schema:addressCountry"] || void 0
1179
+ } : void 0;
1180
+ const areaServed = surveyData["schema:AdministrativeArea"] ? {
1181
+ type: "schema:AdministrativeArea",
1182
+ name: surveyData["schema:AdministrativeArea"]
1183
+ } : void 0;
1184
+ const contactPoints = extractPanelDynamicItems(surveyData, "pannel:schema_contactPoint", (item) => {
1185
+ if (!item["schema:contactType"] && !item["schema:email"] && !item["schema:telephone"]) return null;
1186
+ return {
1187
+ type: "schema:ContactPoint",
1188
+ contactType: item["schema:contactType"] || "general",
1189
+ email: item["schema:email"] || void 0,
1190
+ telephone: item["schema:telephone"] || void 0,
1191
+ availableLanguage: parseLanguageCodes(item["schema:availableLanguage"])
1192
+ };
1193
+ });
1194
+ const hasParts = extractPanelDynamicItems(surveyData, "schema:hasPart", (item) => {
1195
+ if (!item["schema:hasPart.name"] && !item["schema:hasPart.id"]) return null;
1196
+ return {
1197
+ type: "schema:CreativeWork",
1198
+ id: item["schema:hasPart.id"] || void 0,
1199
+ name: item["schema:hasPart.name"] || void 0,
1200
+ description: item["schema:hasPart.description"] || void 0,
1201
+ url: item["schema:hasPart.url"] || void 0,
1202
+ creator: item["schema:hasPart.creator.name"] ? {
1203
+ type: "schema:Organization",
1204
+ name: item["schema:hasPart.creator.name"]
1205
+ } : void 0
1206
+ };
1207
+ });
1208
+ const subjectOf = extractPanelDynamicItems(surveyData, "schema:subjectOf", (item) => {
1209
+ if (!item["schema:subjectOf.name"]) return null;
1210
+ return {
1211
+ type: "schema:CreativeWork",
1212
+ name: item["schema:subjectOf.name"],
1213
+ url: item["schema:subjectOf.url"] || void 0,
1214
+ author: item["schema:subjectOf.author.name"] ? {
1215
+ type: "schema:Organisation",
1216
+ name: item["schema:subjectOf.author.name"]
1217
+ } : void 0
1218
+ };
1219
+ });
1220
+ const composition = hasParts.length > 0 || subjectOf.length > 0 ? {
1221
+ type: "schema:Collection",
1222
+ hasPart: hasParts.length > 0 ? hasParts : void 0,
1223
+ subjectOf: subjectOf.length > 0 ? subjectOf : void 0
1224
+ } : void 0;
1225
+ const makesOffer = extractPanelDynamicItems(surveyData, "schema:makesOffer", (item) => {
1226
+ if (!item["schema:itemOffered.name"]) return null;
1227
+ return {
1228
+ type: "schema:Offer",
1229
+ itemOffered: {
1230
+ type: item["schema:itemOffered.type"] === "service" ? "schema:Service" : "schema:Product",
1231
+ name: item["schema:itemOffered.name"] || void 0,
1232
+ description: item["schema:itemOffered.description"] || void 0,
1233
+ url: item["schema:itemOffered.url"] || void 0
1234
+ }
1235
+ };
1236
+ });
1237
+ const memberOf = extractPanelDynamicItems(surveyData, "schema:memberOf", (item) => {
1238
+ if (!item["schema:memberOf.name"]) return null;
1239
+ return {
1240
+ type: "schema:Organization",
1241
+ name: item["schema:memberOf.name"]
1242
+ };
1243
+ });
1244
+ const wasAssociatedWith = extractPanelDynamicItems(surveyData, "schema:wasAssociatedWith", (item) => {
1245
+ if (!item["schema:wasAssociatedWith.name"]) return null;
1246
+ return {
1247
+ type: "schema:Organization",
1248
+ name: item["schema:wasAssociatedWith.name"],
1249
+ url: item["schema:wasAssociatedWith.url"] || void 0
1250
+ };
1251
+ });
1252
+ const funding = extractPanelDynamicItems(surveyData, "schema:funding", (item) => {
1253
+ if (!item["schema:funder.name"]) return null;
1254
+ return {
1255
+ type: "schema:MonetaryGrant",
1256
+ funder: {
1257
+ type: "schema:Organization",
1258
+ name: item["schema:funder.name"]
1259
+ },
1260
+ amount: item["schema:amount.value"] || item["schema:amount.currency"] ? {
1261
+ type: "schema:MonetaryAmount",
1262
+ currency: item["schema:amount.currency"] || "USD",
1263
+ value: item["schema:amount.value"] || "0"
1264
+ } : void 0
1265
+ };
1266
+ });
1267
+ const relationships = memberOf.length > 0 || wasAssociatedWith.length > 0 || funding.length > 0 ? {
1268
+ memberOf: memberOf.length > 0 ? memberOf : void 0,
1269
+ "prov:wasAssociatedWith": wasAssociatedWith.length > 0 ? wasAssociatedWith : void 0,
1270
+ funding: funding.length > 0 ? funding : void 0
1271
+ } : void 0;
1272
+ const agents = extractPanelDynamicItems(surveyData, "ixo:agentCard", (item) => {
1273
+ if (!item["ixo:agentCard.name"] && !item["ixo:agentCard.id"]) return null;
1274
+ return {
1275
+ type: "ixo:AgentCard",
1276
+ id: item["ixo:agentCard.id"] || void 0,
1277
+ name: item["ixo:agentCard.name"] || void 0,
1278
+ description: item["ixo:agentCard.description"] || void 0
1279
+ };
1280
+ });
1281
+ const credentials = extractPanelDynamicItems(surveyData, "ixo:verifiableCredential", (item) => {
1282
+ if (!item["schema:Name"] && !item["schema:ID"]) return null;
1283
+ return {
1284
+ type: "VerifiableCredential",
1285
+ id: item["schema:ID"] || void 0,
1286
+ name: item["schema:Name"] || void 0,
1287
+ description: item["schema:description"] || void 0
1288
+ };
1289
+ });
1290
+ const attributes = extractPanelDynamicItems(surveyData, "ixo:attribute", (item) => {
1291
+ if (!item["schema:name_2"]) return null;
1292
+ return {
1293
+ "@type": "ixo:Attribute",
1294
+ "@id": item["schema:ID_2"] || `attribute:${item["schema:name_2"].replace(/\s+/g, "_").toLowerCase()}`,
1295
+ name: item["schema:name_2"],
1296
+ value: item["schema:description_2"] || ""
1297
+ };
1298
+ });
1299
+ const projects = extractPanelDynamicItems(surveyData, "pannel_proj:project", (item) => {
1300
+ if (!item["proj:project.name"]) return null;
1301
+ const objectives = extractPanelDynamicItems(item, "proj:project.hadObjective", (objItem) => objItem["proj:hadObjective"] || null);
1302
+ const projectFunding = extractPanelDynamicItems(item, "proj:wasFundedThrough", (fundItem) => ({
1303
+ type: "proj:FundingAssociation",
1304
+ moneyAmount: fundItem["proj:moneyAmount"] || void 0,
1305
+ moneyCurrency: fundItem["proj:moneyCurrency"] || void 0,
1306
+ agent: fundItem["prov.agent.name"] || fundItem["prov:agent.id"] ? {
1307
+ type: "prov:Agent",
1308
+ id: fundItem["prov:agent.id"] || void 0,
1309
+ name: fundItem["prov.agent.name"] || void 0
1310
+ } : void 0
1311
+ }));
1312
+ return {
1313
+ type: "proj:Project",
1314
+ name: item["proj:project.name"],
1315
+ description: item["proj:project.description"] || void 0,
1316
+ hadObjective: objectives.length > 0 ? objectives : void 0,
1317
+ plannedStart: item["proj:plannedStart"] || void 0,
1318
+ plannedEnd: item["proj:plannedEnd"] || void 0,
1319
+ wasFundedThrough: projectFunding.length > 0 ? projectFunding : void 0
1320
+ };
1321
+ });
1322
+ const project = projects.length > 0 ? projects[0] : void 0;
1323
+ const seedQueries = extractPanelDynamicItems(surveyData, "ixo:ResearchProfile", (item) => item["ixo:seedQueries"] || null);
1324
+ const citations = extractPanelDynamicItems(surveyData, "schema:creativeWork", (item) => {
1325
+ if (!item["schema:creativeWork.name"]) return null;
1326
+ return {
1327
+ type: "schema:CreativeWork",
1328
+ name: item["schema:creativeWork.name"],
1329
+ url: item["schema:creativeWork.url"] || void 0,
1330
+ publisher: item["schema:creativeWork.publisher"] || void 0,
1331
+ datePublished: item["schema:creativeWork.datePublished"] || void 0
1332
+ };
1333
+ });
1334
+ const researchProfile = seedQueries.length > 0 || citations.length > 0 ? {
1335
+ type: "ixo:ResearchProfile",
1336
+ "ixo:seedQueries": seedQueries.length > 0 ? seedQueries : void 0,
1337
+ citation: citations.length > 0 ? citations : void 0,
1338
+ dateModified: (/* @__PURE__ */ new Date()).toISOString()
1339
+ } : void 0;
1340
+ const credentialSubject = {
1341
+ id: entityDid,
1342
+ type: types.length > 0 ? types : ["ixo:dao"],
1343
+ name: surveyData["schema:name"] || "",
1344
+ description: surveyData["schema.description"] || ""
1345
+ };
1346
+ if (additionalType.length > 0) credentialSubject.additionalType = additionalType;
1347
+ if (alternateNames.length > 0) credentialSubject.alternateName = alternateNames;
1348
+ if (surveyData["schema:url"]) credentialSubject.url = surveyData["schema:url"];
1349
+ if (sameAsUrls.length > 0) credentialSubject.sameAs = sameAsUrls;
1350
+ if (logo) credentialSubject.logo = logo;
1351
+ if (profileImage) credentialSubject.image = [profileImage];
1352
+ if (keywords.length > 0) credentialSubject.keywords = keywords;
1353
+ if (knowsAbout.length > 0) credentialSubject.knowsAbout = knowsAbout;
1354
+ if (address) credentialSubject.address = address;
1355
+ if (areaServed) credentialSubject.areaServed = areaServed;
1356
+ if (contactPoints.length > 0) credentialSubject.contactPoint = contactPoints;
1357
+ if (composition) credentialSubject.composition = composition;
1358
+ if (makesOffer.length > 0) credentialSubject.makesOffer = makesOffer;
1359
+ if (relationships) credentialSubject.relationships = relationships;
1360
+ if (agents.length > 0) credentialSubject.agents = agents;
1361
+ if (credentials.length > 0) credentialSubject.credentials = credentials;
1362
+ if (attributes.length > 0) credentialSubject.attributes = attributes;
1363
+ if (project) credentialSubject.project = project;
1364
+ if (researchProfile) credentialSubject.researchProfile = researchProfile;
1365
+ return credentialSubject;
1366
+ }
1367
+
1368
+ // src/mantine/blocks/domainCreator/utils/extractSurveyAnswersTemplate.ts
1369
+ function extractFieldsFromElements(elements, fields) {
1370
+ for (const element of elements) {
1371
+ if (element.type === "panel" && element.elements) {
1372
+ extractFieldsFromElements(element.elements, fields);
1373
+ continue;
1374
+ }
1375
+ if (element.type === "paneldynamic" && element.name) {
1376
+ fields[element.name] = [];
1377
+ if (element.templateElements) {
1378
+ extractFieldsFromElements(element.templateElements, fields);
1379
+ }
1380
+ continue;
1381
+ }
1382
+ if (element.name && element.type !== "panel") {
1383
+ switch (element.type) {
1384
+ case "boolean":
1385
+ fields[element.name] = false;
1386
+ break;
1387
+ case "checkbox":
1388
+ fields[element.name] = [];
1389
+ break;
1390
+ case "file":
1391
+ fields[element.name] = [];
1392
+ break;
1393
+ default:
1394
+ fields[element.name] = "";
1395
+ }
1396
+ }
1397
+ if (element.elements) {
1398
+ extractFieldsFromElements(element.elements, fields);
1399
+ }
1400
+ }
1401
+ }
1402
+ function extractSurveyAnswersTemplate(surveyDef) {
1403
+ const fields = {};
1404
+ for (const page of surveyDef.pages) {
1405
+ extractFieldsFromElements(page.elements, fields);
1406
+ }
1407
+ return fields;
1408
+ }
1409
+
1410
+ // src/core/lib/actionRegistry/actions/domainCreate.ts
1411
+ registerAction({
1412
+ type: "qi/domain.create",
1413
+ can: "domain/create",
1414
+ sideEffect: true,
1415
+ defaultRequiresConfirmation: true,
1416
+ requiredCapability: "flow/block/execute",
1417
+ outputSchema: [
1418
+ { path: "entityDid", displayName: "Entity DID", type: "string", description: "The created domain entity DID" },
1419
+ { path: "transactionHash", displayName: "Transaction Hash", type: "string", description: "Blockchain transaction hash" },
1420
+ { path: "credentialId", displayName: "Credential ID", type: "string", description: "The uploaded domain card credential identifier (CID)" },
1421
+ { path: "entityType", displayName: "Entity Type", type: "string", description: "The type of domain entity created" }
1422
+ ],
1423
+ run: async (inputs, ctx) => {
1424
+ const handlers = ctx.handlers;
1425
+ if (!handlers) throw new Error("Handlers not available");
1426
+ if (!handlers.signCredential) throw new Error("signCredential handler not implemented");
1427
+ if (!handlers.publicFileUpload) throw new Error("publicFileUpload handler not available");
1428
+ if (!handlers.createDomain) throw new Error("createDomain handler not implemented");
1429
+ if (!handlers.requestPin) throw new Error("requestPin handler not available");
1430
+ const configEntityType = String(inputs.entityType || "dao").trim();
1431
+ let surveyData = {};
1432
+ if (inputs.surveyData) {
1433
+ if (typeof inputs.surveyData === "string") {
1434
+ try {
1435
+ surveyData = JSON.parse(inputs.surveyData);
1436
+ } catch {
1437
+ throw new Error("surveyData must be valid JSON");
1438
+ }
1439
+ } else if (typeof inputs.surveyData === "object" && !Array.isArray(inputs.surveyData)) {
1440
+ surveyData = inputs.surveyData;
1441
+ }
1442
+ }
1443
+ const issuerDid = handlers.getEntityDid?.() || handlers.getCurrentUser?.()?.address;
1444
+ if (!issuerDid) throw new Error("Unable to determine issuer DID");
1445
+ const entityDid = "did:ixo:entity:pending";
1446
+ const credentialSubject = transformSurveyToCredentialSubject(surveyData, entityDid);
1447
+ const unsignedCredential = buildVerifiableCredential({
1448
+ entityDid,
1449
+ issuerDid,
1450
+ credentialSubject,
1451
+ validFrom: surveyData["schema:validFrom"] || (/* @__PURE__ */ new Date()).toISOString(),
1452
+ validUntil: surveyData["schema:validUntil"]
1453
+ });
1454
+ const pin = await handlers.requestPin({
1455
+ title: "Sign Domain Card",
1456
+ description: "Enter your PIN to sign the Domain Card credential",
1457
+ submitText: "Sign"
1458
+ });
1459
+ const { signedCredential } = await handlers.signCredential({
1460
+ issuerDid,
1461
+ issuerType: "user",
1462
+ credential: unsignedCredential,
1463
+ pin
1464
+ });
1465
+ const credentialBlob = new Blob([JSON.stringify(signedCredential, null, 2)], {
1466
+ type: "application/json"
1467
+ });
1468
+ const credentialFile = new File([credentialBlob], "domainCard.json", {
1469
+ type: "application/json"
1470
+ });
1471
+ const uploadResult = await handlers.publicFileUpload(credentialFile);
1472
+ const domainCardLinkedResource = buildDomainCardLinkedResource({
1473
+ entityDid,
1474
+ cid: uploadResult.cid,
1475
+ serviceEndpoint: uploadResult.url,
1476
+ description: `Domain Card for ${surveyData["schema:name"] || "Domain"}`
1477
+ });
1478
+ const finalEntityType = surveyData["type_2"] || surveyData["daoType"] || configEntityType;
1479
+ const { entityDid: newEntityDid, transactionHash } = await handlers.createDomain({
1480
+ entityType: finalEntityType,
1481
+ linkedResource: [domainCardLinkedResource],
1482
+ startDate: surveyData["schema:validFrom"],
1483
+ endDate: surveyData["schema:validUntil"]
1484
+ });
1485
+ return {
1486
+ output: {
1487
+ entityDid: newEntityDid,
1488
+ transactionHash,
1489
+ credentialId: uploadResult.cid,
1490
+ entityType: finalEntityType
1491
+ }
1492
+ };
1493
+ }
1494
+ });
1495
+
1496
+ // src/core/lib/actionRegistry/actions/oracle.ts
1497
+ registerAction({
1498
+ type: "oracle",
1499
+ can: "oracle/query",
1500
+ sideEffect: false,
1501
+ defaultRequiresConfirmation: false,
1502
+ outputSchema: [{ path: "prompt", displayName: "Prompt", type: "string", description: "The prompt sent to the companion" }],
1503
+ run: async (inputs, ctx) => {
1504
+ const prompt = String(inputs.prompt || "").trim();
1505
+ if (!prompt) throw new Error("prompt is required");
1506
+ if (!ctx.handlers?.askCompanion) {
1507
+ throw new Error("askCompanion handler is not available");
1508
+ }
1509
+ await ctx.handlers.askCompanion(prompt);
1510
+ return {
1511
+ output: { prompt }
1512
+ };
1513
+ }
1514
+ });
1515
+
1516
+ // src/core/lib/actionRegistry/actions/credentialStore.ts
1517
+ registerAction({
1518
+ type: "qi/credential.store",
1519
+ can: "credential/store",
1520
+ sideEffect: true,
1521
+ defaultRequiresConfirmation: true,
1522
+ requiredCapability: "flow/execute",
1523
+ outputSchema: [
1524
+ { path: "credentialKey", displayName: "Credential Key", type: "string", description: "Key under which credential was stored (e.g. kycamllevel1)" },
1525
+ { path: "cid", displayName: "Content ID", type: "string", description: "IPFS-compatible CID of the credential (used for deduplication)" },
1526
+ { path: "storedAt", displayName: "Stored At", type: "string", description: "ISO timestamp of when the credential was stored" },
1527
+ { path: "duplicate", displayName: "Duplicate", type: "boolean", description: "Whether this credential was already stored (matched by CID)" }
1528
+ ],
1529
+ run: async (inputs, ctx) => {
1530
+ const { credential, credentialKey, roomId } = inputs;
1531
+ if (!credentialKey) throw new Error("credentialKey is required");
1532
+ if (!credential) throw new Error("credential is required");
1533
+ let parsedCredential = credential;
1534
+ if (typeof parsedCredential === "string") {
1535
+ for (let i = 0; i < 3 && typeof parsedCredential === "string"; i++) {
1536
+ try {
1537
+ parsedCredential = JSON.parse(parsedCredential);
1538
+ } catch {
1539
+ throw new Error("credential must be a valid JSON object or JSON string");
1540
+ }
1541
+ }
1542
+ }
1543
+ if (typeof parsedCredential !== "object" || parsedCredential === null || Array.isArray(parsedCredential)) {
1544
+ throw new Error("credential must be a JSON object");
1545
+ }
1546
+ if (!ctx.services.matrix?.storeCredential) {
1547
+ throw new Error("Matrix credential storage service not configured");
1548
+ }
1549
+ const { computeJsonCID } = await import("./cid-6O646X2I.mjs");
1550
+ const cid = await computeJsonCID(parsedCredential);
1551
+ const result = await ctx.services.matrix.storeCredential({
1552
+ roomId: roomId || "",
1553
+ credentialKey: String(credentialKey),
1554
+ credential: parsedCredential,
1555
+ cid
1556
+ });
1557
+ return {
1558
+ output: {
1559
+ credentialKey: String(credentialKey),
1560
+ cid,
1561
+ storedAt: result.storedAt,
1562
+ duplicate: result.duplicate
1563
+ }
1564
+ };
1565
+ }
1566
+ });
1567
+
1568
+ // src/core/lib/actionRegistry/actions/payment.ts
1569
+ registerAction({
1570
+ type: "qi/payment.execute",
1571
+ can: "payment/execute",
1572
+ sideEffect: true,
1573
+ defaultRequiresConfirmation: true,
1574
+ requiredCapability: "flow/block/execute",
1575
+ outputSchema: [
1576
+ { path: "transactionId", displayName: "Transaction ID", type: "string", description: "Payment transaction identifier from the provider" },
1577
+ { path: "status", displayName: "Status", type: "string", description: "Payment status (proposed, submitted, pending, completed, failed)" },
1578
+ { path: "proposal", displayName: "Proposal", type: "object", description: "Payment proposal object for review before execution" },
1579
+ { path: "summary", displayName: "Summary", type: "object", description: "Human-readable payment summary" }
1580
+ ],
1581
+ run: async (inputs, ctx) => {
1582
+ const config = inputs.paymentConfig;
1583
+ if (!config || typeof config === "string" && !config.trim()) {
1584
+ throw new Error("paymentConfig is required");
1585
+ }
1586
+ if (!ctx.handlers?.askCompanion) {
1587
+ throw new Error("askCompanion handler is not available");
1588
+ }
1589
+ const parsed = typeof config === "string" ? JSON.parse(config) : config;
1590
+ const configJson = JSON.stringify(parsed, null, 2);
1591
+ await ctx.handlers.askCompanion(
1592
+ [
1593
+ "Execute payment action with this configuration.",
1594
+ "IMPORTANT: First read the flow context and settings \u2014 the flow may contain parameters required by the skill. Also review all blocks in the flow to understand the basic workflow before executing.",
1595
+ `Payment configuration JSON:
1596
+ ${configJson}`
1597
+ ].join("\n")
1598
+ );
1599
+ return {
1600
+ output: {
1601
+ status: "requested",
1602
+ paymentConfig: parsed
1603
+ }
1604
+ };
1605
+ }
1606
+ });
1607
+
1608
+ // src/core/lib/actionRegistry/actions/matrixDm.ts
1609
+ registerAction({
1610
+ type: "qi/matrix.dm",
1611
+ can: "matrix/dm",
1612
+ sideEffect: true,
1613
+ defaultRequiresConfirmation: false,
1614
+ outputSchema: [
1615
+ { path: "roomId", displayName: "Room ID", type: "string", description: "The Matrix room ID used for the DM" },
1616
+ { path: "sentAt", displayName: "Sent At", type: "string", description: "Timestamp when the message was sent" }
1617
+ ],
1618
+ run: async (inputs, ctx) => {
1619
+ const matrixClient = ctx.editor?.getMatrixClient?.();
1620
+ if (!matrixClient) {
1621
+ throw new Error("Matrix client not available");
1622
+ }
1623
+ const targetDid = String(inputs.targetDid || "").trim();
1624
+ const message = String(inputs.message || "").trim();
1625
+ if (!targetDid) throw new Error("Recipient DID is required");
1626
+ if (!message) throw new Error("Message is required");
1627
+ const result = await sendDirectMessage(matrixClient, targetDid, message);
1628
+ return {
1629
+ output: {
1630
+ roomId: result.roomId,
1631
+ sentAt: (/* @__PURE__ */ new Date()).toISOString()
1632
+ }
1633
+ };
1634
+ }
1635
+ });
1636
+
1637
+ // src/core/lib/actionRegistry/actions/bid/bid.diff.ts
1638
+ registerDiffResolver("bid", {
1639
+ resolver: async (inputs, _ctx) => {
1640
+ if (!inputs.surveyStarted) return [];
1641
+ const collectionId = String(inputs.collectionId || "").trim();
1642
+ const role = String(inputs.role || "").trim();
1643
+ const roleLabel = role === "evaluation_agent" || role === "ea" ? "Evaluator" : role ? "Contributor" : "Selected at runtime";
1644
+ return [
1645
+ {
1646
+ key: "applicationStatus",
1647
+ label: "Application Status",
1648
+ before: "None",
1649
+ after: "Pending",
1650
+ changeType: "replace",
1651
+ severity: "info"
1652
+ },
1653
+ {
1654
+ key: "role",
1655
+ label: "Role",
1656
+ before: "None",
1657
+ after: roleLabel,
1658
+ changeType: role ? "replace" : "unchanged"
1659
+ },
1660
+ {
1661
+ key: "collection",
1662
+ label: "Collection",
1663
+ before: collectionId || "Not configured",
1664
+ after: collectionId || "Not configured",
1665
+ changeType: "unchanged"
1666
+ },
1667
+ {
1668
+ key: "surveyAnswers",
1669
+ label: "Survey Answers",
1670
+ before: "None",
1671
+ after: "Submitted at runtime",
1672
+ changeType: "replace"
1673
+ }
1674
+ ];
1675
+ }
1676
+ });
1677
+
1678
+ // src/core/lib/actionRegistry/actions/evaluateBid/evaluateBid.diff.ts
1679
+ var USDC_DENOM = "ibc/6BBE9BD4246F8E04948D5A4EEE7164B2630263B9EBB5E7DC5F0A46C62A2FF97B";
1680
+ function formatCoin(coin) {
1681
+ const denom = coin.denom === USDC_DENOM ? "USDC" : coin.denom === "uixo" ? "IXO" : coin.denom;
1682
+ return `${coin.amount} ${denom}`;
1683
+ }
1684
+ registerDiffResolver("evaluateBid", {
1685
+ resolver: async (inputs, _ctx) => {
1686
+ const bidId = String(inputs.bidId || "").trim();
1687
+ if (!bidId) return [];
1688
+ const decision = String(inputs.decision || "").trim().toLowerCase();
1689
+ const role = String(inputs.role || "").trim();
1690
+ const collectionId = String(inputs.collectionId || "").trim();
1691
+ const applicantDid = String(inputs.applicantDid || "").trim();
1692
+ const roleLower = role.toLowerCase();
1693
+ const isEvaluator = roleLower === "evaluation_agent" || roleLower === "ea";
1694
+ const roleLabel = isEvaluator ? "Evaluator" : roleLower === "service_agent" || roleLower === "sa" ? "Contributor" : role || "Unknown";
1695
+ const isApprove = decision === "approve";
1696
+ const isReject = decision === "reject";
1697
+ const decisionLabel = isApprove ? "Approve" : isReject ? "Reject" : "Not selected";
1698
+ const afterStatus = isApprove ? "Approved" : isReject ? "Rejected" : "Pending";
1699
+ const results = [
1700
+ {
1701
+ key: "bidStatus",
1702
+ label: "Bid Status",
1703
+ before: "Pending",
1704
+ after: afterStatus,
1705
+ changeType: decision ? "replace" : "unchanged",
1706
+ severity: isReject ? "warning" : "info"
1707
+ },
1708
+ {
1709
+ key: "decision",
1710
+ label: "Decision",
1711
+ before: "None",
1712
+ after: decisionLabel,
1713
+ changeType: decision ? "replace" : "unchanged"
1714
+ },
1715
+ {
1716
+ key: "applicantRole",
1717
+ label: "Applicant Role",
1718
+ before: roleLabel,
1719
+ after: roleLabel,
1720
+ changeType: "unchanged"
1721
+ },
1722
+ {
1723
+ key: "bidId",
1724
+ label: "Bid ID",
1725
+ before: bidId || "Not selected",
1726
+ after: bidId || "Not selected",
1727
+ changeType: "unchanged"
1728
+ },
1729
+ {
1730
+ key: "collection",
1731
+ label: "Collection",
1732
+ before: collectionId || "Not configured",
1733
+ after: collectionId || "Not configured",
1734
+ changeType: "unchanged"
1735
+ }
1736
+ ];
1737
+ if (isEvaluator) {
1738
+ let amountsLabel = "None";
1739
+ try {
1740
+ const parsed = typeof inputs.maxAmounts === "string" ? JSON.parse(inputs.maxAmounts) : inputs.maxAmounts;
1741
+ if (Array.isArray(parsed) && parsed.length > 0) {
1742
+ amountsLabel = parsed.map((a) => formatCoin(a)).join(", ");
1743
+ }
1744
+ } catch {
1745
+ }
1746
+ results.push({
1747
+ key: "maxAmounts",
1748
+ label: "Max Amounts",
1749
+ before: "None",
1750
+ after: amountsLabel,
1751
+ changeType: amountsLabel !== "None" ? "replace" : "unchanged"
1752
+ });
1753
+ }
1754
+ if (isReject) {
1755
+ const reason = String(inputs.rejectReason || inputs.reason || "").trim();
1756
+ results.push({
1757
+ key: "reason",
1758
+ label: "Rejection Reason",
1759
+ before: "None",
1760
+ after: reason || "Not provided",
1761
+ changeType: reason ? "replace" : "unchanged",
1762
+ severity: "warning"
1763
+ });
1764
+ }
1765
+ if (applicantDid) {
1766
+ results.push({
1767
+ key: "applicant",
1768
+ label: "Applicant",
1769
+ before: applicantDid,
1770
+ after: applicantDid,
1771
+ changeType: "unchanged"
1772
+ });
1773
+ }
1774
+ return results;
1775
+ }
1776
+ });
1777
+
1778
+ // src/core/lib/actionRegistry/actions/claim/claim.diff.ts
1779
+ registerDiffResolver("claim", {
1780
+ resolver: async (inputs, _ctx) => {
1781
+ if (!inputs.claimStarted) return [];
1782
+ const collectionId = String(inputs.collectionId || "").trim();
1783
+ const deedDid = String(inputs.deedDid || "").trim();
1784
+ return [
1785
+ {
1786
+ key: "claimStatus",
1787
+ label: "Claim Status",
1788
+ before: "None",
1789
+ after: "Pending",
1790
+ changeType: "replace",
1791
+ severity: "info"
1792
+ },
1793
+ {
1794
+ key: "collection",
1795
+ label: "Collection",
1796
+ before: collectionId || "Not configured",
1797
+ after: collectionId || "Not configured",
1798
+ changeType: "unchanged"
1799
+ },
1800
+ {
1801
+ key: "deed",
1802
+ label: "Deed",
1803
+ before: deedDid || "Not configured",
1804
+ after: deedDid || "Not configured",
1805
+ changeType: "unchanged"
1806
+ },
1807
+ {
1808
+ key: "surveyAnswers",
1809
+ label: "Survey Answers",
1810
+ before: "None",
1811
+ after: "Submitted at runtime",
1812
+ changeType: "replace"
1813
+ }
1814
+ ];
1815
+ }
1816
+ });
1817
+
1818
+ // src/core/lib/actionRegistry/actions/evaluateClaim/evaluateClaim.diff.ts
1819
+ var USDC_DENOM2 = "ibc/6BBE9BD4246F8E04948D5A4EEE7164B2630263B9EBB5E7DC5F0A46C62A2FF97B";
1820
+ var DECIMALS = 6;
1821
+ function formatCoin2(coin) {
1822
+ const denom = coin.denom === USDC_DENOM2 ? "USDC" : coin.denom === "uixo" ? "IXO" : coin.denom;
1823
+ const raw = Number(coin.amount);
1824
+ const display = raw >= Math.pow(10, DECIMALS) ? raw / Math.pow(10, DECIMALS) : raw;
1825
+ return `${display} ${denom}`;
1826
+ }
1827
+ registerDiffResolver("evaluateClaim", {
1828
+ resolver: async (inputs, _ctx) => {
1829
+ const claimId = String(inputs.claimId || "").trim();
1830
+ if (!claimId || inputs.alreadyEvaluated) return [];
1831
+ const decision = String(inputs.decision || "").trim().toLowerCase();
1832
+ const collectionId = String(inputs.collectionId || "").trim();
1833
+ const createUdid = Boolean(inputs.createUdid);
1834
+ const isApprove = decision === "approve";
1835
+ const isReject = decision === "reject";
1836
+ const decisionLabel = isApprove ? "Approve" : isReject ? "Reject" : "Not selected";
1837
+ const afterStatus = isApprove ? "Approved" : isReject ? "Rejected" : "Pending";
1838
+ const results = [
1839
+ {
1840
+ key: "claimStatus",
1841
+ label: "Claim Status",
1842
+ before: "Pending",
1843
+ after: afterStatus,
1844
+ changeType: decision ? "replace" : "unchanged",
1845
+ severity: isReject ? "warning" : "info"
1846
+ },
1847
+ {
1848
+ key: "decision",
1849
+ label: "Decision",
1850
+ before: "None",
1851
+ after: decisionLabel,
1852
+ changeType: decision ? "replace" : "unchanged"
1853
+ },
1854
+ {
1855
+ key: "claimId",
1856
+ label: "Claim ID",
1857
+ before: claimId || "Not selected",
1858
+ after: claimId || "Not selected",
1859
+ changeType: "unchanged"
1860
+ },
1861
+ {
1862
+ key: "collection",
1863
+ label: "Collection",
1864
+ before: collectionId || "Not configured",
1865
+ after: collectionId || "Not configured",
1866
+ changeType: "unchanged"
1867
+ },
1868
+ {
1869
+ key: "udidProof",
1870
+ label: "UDID Proof",
1871
+ before: "None",
1872
+ after: createUdid ? "Will be generated" : "Skipped",
1873
+ changeType: createUdid ? "replace" : "unchanged"
1874
+ }
1875
+ ];
1876
+ let amountsLabel = "None";
1877
+ try {
1878
+ const raw = typeof inputs.amount === "string" ? JSON.parse(inputs.amount) : inputs.amount;
1879
+ if (Array.isArray(raw) && raw.length > 0) {
1880
+ amountsLabel = raw.map((a) => formatCoin2(a)).join(", ");
1881
+ } else if (raw && typeof raw === "object" && raw.denom) {
1882
+ amountsLabel = formatCoin2(raw);
1883
+ }
1884
+ } catch {
1885
+ }
1886
+ results.push({
1887
+ key: "payment",
1888
+ label: "Payment",
1889
+ before: "None",
1890
+ after: amountsLabel,
1891
+ changeType: amountsLabel !== "None" ? "replace" : "unchanged"
1892
+ });
1893
+ if (inputs.outcomeComplete !== void 0) {
1894
+ results.push({
1895
+ key: "outcome",
1896
+ label: "Outcome Template",
1897
+ before: "None",
1898
+ after: inputs.outcomeComplete ? "Completed" : "Not completed",
1899
+ changeType: inputs.outcomeComplete ? "replace" : "unchanged",
1900
+ severity: inputs.outcomeComplete ? "info" : "warning"
1901
+ });
1902
+ }
1903
+ return results;
1904
+ }
1905
+ });
1906
+
1907
+ // src/core/lib/ucanDelegationStore.ts
1908
+ var ROOT_DELEGATION_KEY = "__root__";
1909
+ var STORE_VERSION_KEY = "__version__";
1910
+ var CURRENT_VERSION = 2;
1911
+ var isValidEntry = (value) => {
1912
+ if (!value || typeof value !== "object") return false;
1913
+ const entry = value;
1914
+ return entry.v === CURRENT_VERSION && entry.data !== void 0;
1915
+ };
1916
+ var isReservedKey = (key) => key === ROOT_DELEGATION_KEY || key === STORE_VERSION_KEY;
1917
+ var createUcanDelegationStore = (yMap) => {
1918
+ const get = (cid) => {
1919
+ if (isReservedKey(cid)) return null;
1920
+ const raw = yMap.get(cid);
1921
+ if (!raw) return null;
1922
+ if (isValidEntry(raw)) return raw.data;
1923
+ return null;
1924
+ };
1925
+ const set = (delegation) => {
1926
+ const entry = { v: CURRENT_VERSION, data: delegation };
1927
+ yMap.set(delegation.cid, entry);
1928
+ };
1929
+ const remove = (cid) => {
1930
+ yMap.delete(cid);
1931
+ };
1932
+ const has = (cid) => {
1933
+ return yMap.has(cid) && !isReservedKey(cid);
1934
+ };
1935
+ const getRoot = () => {
1936
+ const rootCid = yMap.get(ROOT_DELEGATION_KEY);
1937
+ if (!rootCid) return null;
1938
+ return get(rootCid);
1939
+ };
1940
+ const setRootCid = (cid) => {
1941
+ yMap.set(ROOT_DELEGATION_KEY, cid);
1942
+ };
1943
+ const getRootCid = () => {
1944
+ return yMap.get(ROOT_DELEGATION_KEY) || null;
1945
+ };
1946
+ const getAll = () => {
1947
+ const delegations = [];
1948
+ yMap.forEach((value, key) => {
1949
+ if (isReservedKey(key)) return;
1950
+ if (isValidEntry(value)) {
1951
+ delegations.push(value.data);
1952
+ }
1953
+ });
1954
+ return delegations;
1955
+ };
1956
+ const getByAudience = (audienceDid) => {
1957
+ return getAll().filter((d) => d.audienceDid === audienceDid);
1958
+ };
1959
+ const getByIssuer = (issuerDid) => {
1960
+ return getAll().filter((d) => d.issuerDid === issuerDid);
1961
+ };
1962
+ const findByCapability = (can, withUri) => {
1963
+ return getAll().filter(
1964
+ (d) => d.capabilities.some((c) => {
1965
+ if (c.can === can && c.with === withUri) return true;
1966
+ if (c.can === "*" || c.can === "flow/*") return true;
1967
+ if (c.can.endsWith("/*")) {
1968
+ const prefix = c.can.slice(0, -1);
1969
+ if (can.startsWith(prefix)) return true;
1970
+ }
1971
+ if (c.with === "*") return true;
1972
+ if (c.with.endsWith("*")) {
1973
+ const prefix = c.with.slice(0, -1);
1974
+ if (withUri.startsWith(prefix)) return true;
1975
+ }
1976
+ return false;
1977
+ })
1978
+ );
1979
+ };
1980
+ return {
1981
+ get,
1982
+ set,
1983
+ remove,
1984
+ has,
1985
+ getRoot,
1986
+ setRootCid,
1987
+ getRootCid,
1988
+ getAll,
1989
+ getByAudience,
1990
+ getByIssuer,
1991
+ findByCapability
1992
+ };
1993
+ };
1994
+ var createMemoryUcanDelegationStore = () => {
1995
+ const store = /* @__PURE__ */ new Map();
1996
+ const get = (cid) => {
1997
+ if (isReservedKey(cid)) return null;
1998
+ const raw = store.get(cid);
1999
+ if (!raw) return null;
2000
+ if (isValidEntry(raw)) return raw.data;
2001
+ return null;
2002
+ };
2003
+ const set = (delegation) => {
2004
+ const entry = { v: CURRENT_VERSION, data: delegation };
2005
+ store.set(delegation.cid, entry);
2006
+ };
2007
+ const remove = (cid) => {
2008
+ store.delete(cid);
2009
+ };
2010
+ const has = (cid) => {
2011
+ return store.has(cid) && !isReservedKey(cid);
2012
+ };
2013
+ const getRoot = () => {
2014
+ const rootCid = store.get(ROOT_DELEGATION_KEY);
2015
+ if (!rootCid) return null;
2016
+ return get(rootCid);
2017
+ };
2018
+ const setRootCid = (cid) => {
2019
+ store.set(ROOT_DELEGATION_KEY, cid);
2020
+ };
2021
+ const getRootCid = () => {
2022
+ return store.get(ROOT_DELEGATION_KEY) || null;
2023
+ };
2024
+ const getAll = () => {
2025
+ const delegations = [];
2026
+ store.forEach((value, key) => {
2027
+ if (isReservedKey(key)) return;
2028
+ if (isValidEntry(value)) {
2029
+ delegations.push(value.data);
2030
+ }
2031
+ });
2032
+ return delegations;
2033
+ };
2034
+ const getByAudience = (audienceDid) => {
2035
+ return getAll().filter((d) => d.audienceDid === audienceDid);
2036
+ };
2037
+ const getByIssuer = (issuerDid) => {
2038
+ return getAll().filter((d) => d.issuerDid === issuerDid);
2039
+ };
2040
+ const findByCapability = (can, withUri) => {
2041
+ return getAll().filter(
2042
+ (d) => d.capabilities.some((c) => {
2043
+ if (c.can === can && c.with === withUri) return true;
2044
+ if (c.can === "*" || c.can === "flow/*") return true;
2045
+ if (c.can.endsWith("/*")) {
2046
+ const prefix = c.can.slice(0, -1);
2047
+ if (can.startsWith(prefix)) return true;
2048
+ }
2049
+ if (c.with === "*") return true;
2050
+ if (c.with.endsWith("*")) {
2051
+ const prefix = c.with.slice(0, -1);
2052
+ if (withUri.startsWith(prefix)) return true;
2053
+ }
2054
+ return false;
2055
+ })
2056
+ );
2057
+ };
2058
+ return {
2059
+ get,
2060
+ set,
2061
+ remove,
2062
+ has,
2063
+ getRoot,
2064
+ setRootCid,
2065
+ getRootCid,
2066
+ getAll,
2067
+ getByAudience,
2068
+ getByIssuer,
2069
+ findByCapability
2070
+ };
2071
+ };
2072
+
2073
+ // src/core/lib/invocationStore.ts
2074
+ var createInvocationStore = (yMap) => {
2075
+ const add = (invocation) => {
2076
+ yMap.set(invocation.cid, invocation);
2077
+ };
2078
+ const get = (cid) => {
2079
+ const raw = yMap.get(cid);
2080
+ if (!raw || typeof raw !== "object") return null;
2081
+ return raw;
2082
+ };
2083
+ const remove = (cid) => {
2084
+ yMap.delete(cid);
2085
+ };
2086
+ const getAll = () => {
2087
+ const invocations = [];
2088
+ yMap.forEach((value) => {
2089
+ if (value && typeof value === "object" && "cid" in value) {
2090
+ invocations.push(value);
2091
+ }
2092
+ });
2093
+ return invocations.sort((a, b) => b.executedAt - a.executedAt);
2094
+ };
2095
+ const getByInvoker = (invokerDid) => {
2096
+ return getAll().filter((i) => i.invokerDid === invokerDid);
2097
+ };
2098
+ const getByFlow = (flowId) => {
2099
+ return getAll().filter((i) => i.flowId === flowId);
2100
+ };
2101
+ const getByBlock = (flowId, blockId) => {
2102
+ return getAll().filter((i) => i.flowId === flowId && i.blockId === blockId);
2103
+ };
2104
+ const getByCapability = (can, withUri) => {
2105
+ return getAll().filter((i) => i.capability.can === can && i.capability.with === withUri);
2106
+ };
2107
+ const hasBeenInvoked = (cid) => {
2108
+ return yMap.has(cid);
2109
+ };
2110
+ const getInDateRange = (startMs, endMs) => {
2111
+ return getAll().filter((i) => i.executedAt >= startMs && i.executedAt <= endMs);
2112
+ };
2113
+ const getSuccessful = () => {
2114
+ return getAll().filter((i) => i.result === "success");
2115
+ };
2116
+ const getFailures = () => {
2117
+ return getAll().filter((i) => i.result === "failure");
2118
+ };
2119
+ const getPendingSubmission = () => {
2120
+ return getAll().filter((i) => i.result === "success" && !i.transactionHash);
2121
+ };
2122
+ const markSubmitted = (cid, transactionHash) => {
2123
+ const invocation = get(cid);
2124
+ if (invocation) {
2125
+ const updated = {
2126
+ ...invocation,
2127
+ transactionHash
2128
+ };
2129
+ yMap.set(cid, updated);
2130
+ }
2131
+ };
2132
+ const getCount = () => {
2133
+ return getAll().length;
2134
+ };
2135
+ const getCountByResult = () => {
2136
+ const all = getAll();
2137
+ return {
2138
+ success: all.filter((i) => i.result === "success").length,
2139
+ failure: all.filter((i) => i.result === "failure").length
2140
+ };
2141
+ };
2142
+ return {
2143
+ add,
2144
+ get,
2145
+ remove,
2146
+ getAll,
2147
+ getByInvoker,
2148
+ getByFlow,
2149
+ getByBlock,
2150
+ getByCapability,
2151
+ hasBeenInvoked,
2152
+ getInDateRange,
2153
+ getSuccessful,
2154
+ getFailures,
2155
+ getPendingSubmission,
2156
+ markSubmitted,
2157
+ getCount,
2158
+ getCountByResult
2159
+ };
2160
+ };
2161
+ var createMemoryInvocationStore = () => {
2162
+ const store = /* @__PURE__ */ new Map();
2163
+ const add = (invocation) => {
2164
+ store.set(invocation.cid, invocation);
2165
+ };
2166
+ const get = (cid) => {
2167
+ return store.get(cid) || null;
2168
+ };
2169
+ const remove = (cid) => {
2170
+ store.delete(cid);
2171
+ };
2172
+ const getAll = () => {
2173
+ const invocations = Array.from(store.values());
2174
+ return invocations.sort((a, b) => b.executedAt - a.executedAt);
2175
+ };
2176
+ const getByInvoker = (invokerDid) => {
2177
+ return getAll().filter((i) => i.invokerDid === invokerDid);
2178
+ };
2179
+ const getByFlow = (flowId) => {
2180
+ return getAll().filter((i) => i.flowId === flowId);
2181
+ };
2182
+ const getByBlock = (flowId, blockId) => {
2183
+ return getAll().filter((i) => i.flowId === flowId && i.blockId === blockId);
2184
+ };
2185
+ const getByCapability = (can, withUri) => {
2186
+ return getAll().filter((i) => i.capability.can === can && i.capability.with === withUri);
2187
+ };
2188
+ const hasBeenInvoked = (cid) => {
2189
+ return store.has(cid);
2190
+ };
2191
+ const getInDateRange = (startMs, endMs) => {
2192
+ return getAll().filter((i) => i.executedAt >= startMs && i.executedAt <= endMs);
2193
+ };
2194
+ const getSuccessful = () => {
2195
+ return getAll().filter((i) => i.result === "success");
2196
+ };
2197
+ const getFailures = () => {
2198
+ return getAll().filter((i) => i.result === "failure");
2199
+ };
2200
+ const getPendingSubmission = () => {
2201
+ return getAll().filter((i) => i.result === "success" && !i.transactionHash);
2202
+ };
2203
+ const markSubmitted = (cid, transactionHash) => {
2204
+ const invocation = get(cid);
2205
+ if (invocation) {
2206
+ store.set(cid, { ...invocation, transactionHash });
2207
+ }
2208
+ };
2209
+ const getCount = () => {
2210
+ return store.size;
2211
+ };
2212
+ const getCountByResult = () => {
2213
+ const all = getAll();
2214
+ return {
2215
+ success: all.filter((i) => i.result === "success").length,
2216
+ failure: all.filter((i) => i.result === "failure").length
2217
+ };
2218
+ };
2219
+ return {
2220
+ add,
2221
+ get,
2222
+ remove,
2223
+ getAll,
2224
+ getByInvoker,
2225
+ getByFlow,
2226
+ getByBlock,
2227
+ getByCapability,
2228
+ hasBeenInvoked,
2229
+ getInDateRange,
2230
+ getSuccessful,
2231
+ getFailures,
2232
+ getPendingSubmission,
2233
+ markSubmitted,
2234
+ getCount,
2235
+ getCountByResult
2236
+ };
2237
+ };
2238
+
2239
+ // src/core/lib/flowEngine/utils.ts
2240
+ var parseActivationStatus = (value) => {
2241
+ if (value === "pending" || value === "approved" || value === "rejected") {
2242
+ return value;
2243
+ }
2244
+ return void 0;
2245
+ };
2246
+ var buildAuthzFromProps = (props) => {
2247
+ const activationRequiredStatus = parseActivationStatus(props.activationRequiredStatus);
2248
+ const activationUpstreamNodeId = typeof props.activationUpstreamNodeId === "string" ? props.activationUpstreamNodeId.trim() : "";
2249
+ const linkedClaimCollectionId = typeof props.linkedClaimCollectionId === "string" ? props.linkedClaimCollectionId.trim() : "";
2250
+ const authz = {};
2251
+ if (linkedClaimCollectionId) {
2252
+ authz.linkedClaim = { collectionId: linkedClaimCollectionId };
2253
+ }
2254
+ if (activationUpstreamNodeId && activationRequiredStatus) {
2255
+ authz.activationCondition = {
2256
+ upstreamNodeId: activationUpstreamNodeId,
2257
+ requiredStatus: activationRequiredStatus,
2258
+ requireAuthorisedActor: Boolean(props.activationRequireAuthorisedActor)
2259
+ };
2260
+ }
2261
+ return authz;
2262
+ };
2263
+ var buildFlowNodeFromBlock = (block) => {
2264
+ const base = {
2265
+ id: block.id,
2266
+ type: block.type,
2267
+ props: block.props || {}
2268
+ };
2269
+ const authz = buildAuthzFromProps(block.props || {});
2270
+ return {
2271
+ ...base,
2272
+ ...authz
2273
+ };
2274
+ };
2275
+
2276
+ // src/core/lib/flowEngine/runtime.ts
2277
+ var ensureStateObject = (value) => {
2278
+ if (!value || typeof value !== "object") {
2279
+ return {};
2280
+ }
2281
+ return { ...value };
2282
+ };
2283
+ var createYMapManager = (map) => {
2284
+ return {
2285
+ get: (nodeId) => {
2286
+ const stored = map.get(nodeId);
2287
+ return ensureStateObject(stored);
2288
+ },
2289
+ update: (nodeId, updates) => {
2290
+ const current = ensureStateObject(map.get(nodeId));
2291
+ map.set(nodeId, { ...current, ...updates });
2292
+ }
2293
+ };
2294
+ };
2295
+ var createMemoryManager = () => {
2296
+ const memory = /* @__PURE__ */ new Map();
2297
+ return {
2298
+ get: (nodeId) => ensureStateObject(memory.get(nodeId)),
2299
+ update: (nodeId, updates) => {
2300
+ const current = ensureStateObject(memory.get(nodeId));
2301
+ memory.set(nodeId, { ...current, ...updates });
2302
+ }
2303
+ };
2304
+ };
2305
+ var createRuntimeStateManager = (editor) => {
2306
+ if (editor?._yRuntime) {
2307
+ return createYMapManager(editor._yRuntime);
2308
+ }
2309
+ return createMemoryManager();
2310
+ };
2311
+ function clearRuntimeForTemplateClone(yDoc) {
2312
+ const runtime = yDoc.getMap("runtime");
2313
+ const invocations = yDoc.getMap("invocations");
2314
+ yDoc.transact(() => {
2315
+ runtime.forEach((_, key) => runtime.delete(key));
2316
+ invocations.forEach((_, key) => invocations.delete(key));
2317
+ });
2318
+ }
2319
+
2320
+ // src/core/lib/flowEngine/activation.ts
2321
+ var isNodeActive = (node, runtime) => {
2322
+ if (!node.activationCondition) {
2323
+ return { active: true };
2324
+ }
2325
+ const { upstreamNodeId, requiredStatus, requireAuthorisedActor } = node.activationCondition;
2326
+ if (!upstreamNodeId) {
2327
+ return { active: true };
2328
+ }
2329
+ const upstreamState = runtime.get(upstreamNodeId);
2330
+ if (!upstreamState.claimId) {
2331
+ return { active: false, reason: `Upstream node ${upstreamNodeId} has no claim submission yet.` };
2332
+ }
2333
+ if (upstreamState.evaluationStatus !== requiredStatus) {
2334
+ return {
2335
+ active: false,
2336
+ reason: `Upstream node ${upstreamNodeId} status is ${upstreamState.evaluationStatus || "unknown"}, requires ${requiredStatus}.`
2337
+ };
2338
+ }
2339
+ if (requireAuthorisedActor) {
2340
+ const upstreamActor = upstreamState.submittedByDid;
2341
+ if (!upstreamActor) {
2342
+ return { active: false, reason: "Upstream submission actor is unknown." };
2343
+ }
2344
+ if (!upstreamState.lastInvocationCid) {
2345
+ return { active: false, reason: "Upstream execution has no invocation proof." };
2346
+ }
2347
+ }
2348
+ return { active: true };
2349
+ };
2350
+
2351
+ // src/core/lib/flowEngine/authorization.ts
2352
+ var isAuthorized = async (blockId, actorDid, ucanService, flowUri) => {
2353
+ const capability = {
2354
+ can: "flow/block/execute",
2355
+ with: `${flowUri}:${blockId}`
2356
+ };
2357
+ const result = await ucanService.validateDelegationChain(actorDid, capability);
2358
+ if (!result.valid) {
2359
+ return {
2360
+ authorized: false,
2361
+ reason: result.error || "No valid capability chain found"
2362
+ };
2363
+ }
2364
+ const proofCids = result.proofChain?.map((d) => d.cid) || [];
2365
+ return {
2366
+ authorized: true,
2367
+ capabilityId: proofCids[0],
2368
+ proofCids
2369
+ };
2370
+ };
2371
+
2372
+ // src/core/lib/flowEngine/executor.ts
2373
+ var updateRuntimeAfterSuccess = (node, actorDid, runtime, actionResult, invocationCid, now) => {
2374
+ const updates = {
2375
+ submittedByDid: actionResult.submittedByDid || actorDid,
2376
+ evaluationStatus: actionResult.evaluationStatus || "pending",
2377
+ executionTimestamp: now ? now() : Date.now(),
2378
+ lastInvocationCid: invocationCid
2379
+ };
2380
+ if (actionResult.claimId) {
2381
+ updates.claimId = actionResult.claimId;
2382
+ }
2383
+ runtime.update(node.id, updates);
2384
+ };
2385
+ var executeNode = async ({ node, actorDid, actorType, entityRoomId, context, action, pin }) => {
2386
+ const { runtime, ucanService, invocationStore, flowUri, flowId, now } = context;
2387
+ const activation = isNodeActive(node, runtime);
2388
+ if (!activation.active) {
2389
+ return { success: false, stage: "activation", error: activation.reason };
2390
+ }
2391
+ const auth = await isAuthorized(node.id, actorDid, ucanService, flowUri);
2392
+ if (!auth.authorized) {
2393
+ return { success: false, stage: "authorization", error: auth.reason };
2394
+ }
2395
+ if (node.linkedClaim && !node.linkedClaim.collectionId) {
2396
+ return { success: false, stage: "claim", error: "Linked claim collection is required but missing." };
2397
+ }
2398
+ let invocationCid;
2399
+ let invocationData;
2400
+ if (auth.proofCids && auth.proofCids.length > 0) {
2401
+ const capability = {
2402
+ can: "flow/block/execute",
2403
+ with: `${flowUri}:${node.id}`
2404
+ };
2405
+ try {
2406
+ const invocationResult = await ucanService.createAndValidateInvocation(
2407
+ {
2408
+ invokerDid: actorDid,
2409
+ invokerType: actorType,
2410
+ entityRoomId,
2411
+ capability,
2412
+ proofs: auth.proofCids,
2413
+ pin
2414
+ },
2415
+ flowId,
2416
+ node.id
2417
+ );
2418
+ if (!invocationResult.valid) {
2419
+ return {
2420
+ success: false,
2421
+ stage: "authorization",
2422
+ error: `Invocation validation failed: ${invocationResult.error}`
2423
+ };
2424
+ }
2425
+ invocationCid = invocationResult.cid;
2426
+ invocationData = invocationResult.invocation;
2427
+ } catch (error) {
2428
+ const message = error instanceof Error ? error.message : "Failed to create invocation";
2429
+ return { success: false, stage: "authorization", error: message };
2430
+ }
2431
+ }
2432
+ try {
2433
+ const result = await action();
2434
+ if (node.linkedClaim && !result.claimId) {
2435
+ if (invocationStore && invocationCid && invocationData) {
2436
+ const storedInvocation = {
2437
+ cid: invocationCid,
2438
+ invocation: invocationData,
2439
+ invokerDid: actorDid,
2440
+ capability: { can: "flow/block/execute", with: `${flowUri}:${node.id}` },
2441
+ executedAt: now ? now() : Date.now(),
2442
+ flowId,
2443
+ blockId: node.id,
2444
+ result: "failure",
2445
+ error: "Execution did not return a claimId for linked claim requirement.",
2446
+ proofCids: auth.proofCids || []
2447
+ };
2448
+ invocationStore.add(storedInvocation);
2449
+ }
2450
+ return {
2451
+ success: false,
2452
+ stage: "claim",
2453
+ error: "Execution did not return a claimId for linked claim requirement.",
2454
+ invocationCid
2455
+ };
2456
+ }
2457
+ if (invocationStore && invocationCid && invocationData) {
2458
+ const storedInvocation = {
2459
+ cid: invocationCid,
2460
+ invocation: invocationData,
2461
+ invokerDid: actorDid,
2462
+ capability: { can: "flow/block/execute", with: `${flowUri}:${node.id}` },
2463
+ executedAt: now ? now() : Date.now(),
2464
+ flowId,
2465
+ blockId: node.id,
2466
+ result: "success",
2467
+ proofCids: auth.proofCids || [],
2468
+ claimId: result.claimId
2469
+ };
2470
+ invocationStore.add(storedInvocation);
2471
+ }
2472
+ updateRuntimeAfterSuccess(node, actorDid, runtime, result, invocationCid || auth.capabilityId, now);
2473
+ return {
2474
+ success: true,
2475
+ stage: "complete",
2476
+ result,
2477
+ capabilityId: auth.capabilityId,
2478
+ invocationCid
2479
+ };
2480
+ } catch (error) {
2481
+ const message = error instanceof Error ? error.message : "Execution failed";
2482
+ if (invocationStore && invocationCid && invocationData) {
2483
+ const storedInvocation = {
2484
+ cid: invocationCid,
2485
+ invocation: invocationData,
2486
+ invokerDid: actorDid,
2487
+ capability: { can: "flow/block/execute", with: `${flowUri}:${node.id}` },
2488
+ executedAt: now ? now() : Date.now(),
2489
+ flowId,
2490
+ blockId: node.id,
2491
+ result: "failure",
2492
+ error: message,
2493
+ proofCids: auth.proofCids || []
2494
+ };
2495
+ invocationStore.add(storedInvocation);
2496
+ }
2497
+ return { success: false, stage: "action", error: message, invocationCid };
2498
+ }
2499
+ };
2500
+
2501
+ // src/core/services/ucanService.ts
2502
+ import {
2503
+ createDelegation as ucanCreateDelegation,
2504
+ createInvocation as ucanCreateInvocation,
2505
+ serializeDelegation,
2506
+ serializeInvocation,
2507
+ parseDelegation,
2508
+ parseSigner,
2509
+ signerFromMnemonic
2510
+ } from "@ixo/ucan";
2511
+ function toSupportedDID(did) {
2512
+ if (did.startsWith("did:ixo:") || did.startsWith("did:key:")) {
2513
+ return did;
2514
+ }
2515
+ return void 0;
2516
+ }
2517
+ function toUcantoCapabilities(capabilities) {
2518
+ return capabilities.map((cap) => ({
2519
+ can: cap.can,
2520
+ with: cap.with,
2521
+ ...cap.nb && { nb: cap.nb }
2522
+ }));
2523
+ }
2524
+ async function getSigner(handlers, did, didType, entityRoomId, pin) {
2525
+ const supportedDid = toSupportedDID(did);
2526
+ if (handlers.getPrivateKey) {
2527
+ const privateKey = await handlers.getPrivateKey({ did, didType, entityRoomId, pin });
2528
+ return parseSigner(privateKey, supportedDid);
2529
+ }
2530
+ if (handlers.getMnemonic) {
2531
+ const mnemonic = await handlers.getMnemonic({ did, didType, entityRoomId, pin });
2532
+ const result = await signerFromMnemonic(mnemonic, supportedDid);
2533
+ return result.signer;
2534
+ }
2535
+ throw new Error("No signer handler configured (need getPrivateKey or getMnemonic)");
2536
+ }
2537
+ function getCidFromDelegation(delegation) {
2538
+ return delegation.cid.toString();
2539
+ }
2540
+ var createUcanService = (config) => {
2541
+ const { delegationStore, invocationStore, handlers, flowOwnerDid } = config;
2542
+ const delegationCache = /* @__PURE__ */ new Map();
2543
+ const isConfigured = () => {
2544
+ const hasSessionHandlers = !!(handlers.createSignerSession && handlers.signWithSession);
2545
+ const hasLegacyHandlers = !!(handlers.getPrivateKey || handlers.getMnemonic);
2546
+ return hasSessionHandlers || hasLegacyHandlers;
2547
+ };
2548
+ const parseDelegationFromStore = async (cid) => {
2549
+ if (delegationCache.has(cid)) {
2550
+ return delegationCache.get(cid);
2551
+ }
2552
+ const stored = delegationStore.get(cid);
2553
+ if (!stored || !stored.delegation) {
2554
+ return null;
2555
+ }
2556
+ try {
2557
+ const delegation = await parseDelegation(stored.delegation);
2558
+ delegationCache.set(cid, delegation);
2559
+ return delegation;
2560
+ } catch {
2561
+ return null;
2562
+ }
2563
+ };
2564
+ const getProofDelegations = async (proofCids) => {
2565
+ const proofs = [];
2566
+ for (const cid of proofCids) {
2567
+ const delegation = await parseDelegationFromStore(cid);
2568
+ if (delegation) {
2569
+ proofs.push(delegation);
2570
+ }
2571
+ }
2572
+ return proofs;
2573
+ };
2574
+ const createRootDelegation = async (params) => {
2575
+ const { flowOwnerDid: ownerDid, issuerType, entityRoomId, flowUri: uri, pin } = params;
2576
+ const signer = await getSigner(handlers, ownerDid, issuerType, entityRoomId, pin);
2577
+ const capabilities = [{ can: "flow/*", with: uri }];
2578
+ const delegation = await ucanCreateDelegation({
2579
+ issuer: signer,
2580
+ audience: ownerDid,
2581
+ capabilities,
2582
+ proofs: []
2583
+ });
2584
+ const serialized = await serializeDelegation(delegation);
2585
+ const cid = getCidFromDelegation(delegation);
2586
+ const storedDelegation = {
2587
+ cid,
2588
+ delegation: serialized,
2589
+ issuerDid: ownerDid,
2590
+ audienceDid: ownerDid,
2591
+ capabilities,
2592
+ createdAt: Date.now(),
2593
+ format: "car",
2594
+ proofCids: []
2595
+ };
2596
+ delegationStore.set(storedDelegation);
2597
+ delegationStore.setRootCid(cid);
2598
+ delegationCache.set(cid, delegation);
2599
+ return storedDelegation;
2600
+ };
2601
+ const createDelegation = async (params) => {
2602
+ const { issuerDid, issuerType, entityRoomId, audience, capabilities, proofs = [], expiration, pin } = params;
2603
+ const signer = await getSigner(handlers, issuerDid, issuerType, entityRoomId, pin);
2604
+ const proofCids = proofs.length > 0 ? proofs : [delegationStore.getRootCid()].filter(Boolean);
2605
+ const proofDelegations = await getProofDelegations(proofCids);
2606
+ const delegation = await ucanCreateDelegation({
2607
+ issuer: signer,
2608
+ audience,
2609
+ capabilities: toUcantoCapabilities(capabilities),
2610
+ proofs: proofDelegations,
2611
+ expiration: expiration ? Math.floor(expiration / 1e3) : void 0
2612
+ });
2613
+ const serialized = await serializeDelegation(delegation);
2614
+ const cid = getCidFromDelegation(delegation);
2615
+ const storedDelegation = {
2616
+ cid,
2617
+ delegation: serialized,
2618
+ issuerDid,
2619
+ audienceDid: audience,
2620
+ capabilities,
2621
+ expiration,
2622
+ createdAt: Date.now(),
2623
+ format: "car",
2624
+ proofCids
2625
+ };
2626
+ delegationStore.set(storedDelegation);
2627
+ delegationCache.set(cid, delegation);
2628
+ return storedDelegation;
2629
+ };
2630
+ const revokeDelegation = (cid) => {
2631
+ delegationStore.remove(cid);
2632
+ delegationCache.delete(cid);
2633
+ };
2634
+ const getDelegation = (cid) => {
2635
+ return delegationStore.get(cid);
2636
+ };
2637
+ const getAllDelegations = () => {
2638
+ return delegationStore.getAll();
2639
+ };
2640
+ const getRootDelegation = () => {
2641
+ return delegationStore.getRoot();
2642
+ };
2643
+ const findValidProofs = async (audienceDid, capability) => {
2644
+ const delegations = delegationStore.getByAudience(audienceDid);
2645
+ if (delegations.length === 0) {
2646
+ const root = delegationStore.getRoot();
2647
+ if (root && root.audienceDid === audienceDid) {
2648
+ return { found: true, proofCids: [root.cid] };
2649
+ }
2650
+ return { found: false, error: "No delegations found for actor" };
2651
+ }
2652
+ for (const delegation of delegations) {
2653
+ const covers = delegation.capabilities.some((c) => {
2654
+ if (c.can === capability.can && c.with === capability.with) return true;
2655
+ if (c.can === "*" || c.can === "flow/*") return true;
2656
+ if (c.can.endsWith("/*")) {
2657
+ const prefix = c.can.slice(0, -1);
2658
+ if (capability.can.startsWith(prefix)) return true;
2659
+ }
2660
+ if (c.with === "*") return true;
2661
+ if (c.with.endsWith("*")) {
2662
+ const prefix = c.with.slice(0, -1);
2663
+ if (capability.with.startsWith(prefix)) return true;
2664
+ }
2665
+ return false;
2666
+ });
2667
+ if (covers) {
2668
+ if (delegation.expiration && delegation.expiration < Date.now()) {
2669
+ continue;
2670
+ }
2671
+ const proofCids = [delegation.cid, ...delegation.proofCids];
2672
+ return { found: true, proofCids };
2673
+ }
2674
+ }
2675
+ return { found: false, error: "No valid delegation found for capability" };
2676
+ };
2677
+ const validateDelegationChain = async (audienceDid, capability) => {
2678
+ const proofsResult = await findValidProofs(audienceDid, capability);
2679
+ if (!proofsResult.found || !proofsResult.proofCids) {
2680
+ return { valid: false, error: proofsResult.error };
2681
+ }
2682
+ const proofChain = [];
2683
+ for (const cid of proofsResult.proofCids) {
2684
+ const delegation = delegationStore.get(cid);
2685
+ if (!delegation) {
2686
+ return { valid: false, error: `Proof delegation ${cid} not found` };
2687
+ }
2688
+ proofChain.push(delegation);
2689
+ }
2690
+ for (let i = 0; i < proofChain.length - 1; i++) {
2691
+ const current = proofChain[i];
2692
+ const parent = proofChain[i + 1];
2693
+ if (parent.audienceDid !== current.issuerDid) {
2694
+ return {
2695
+ valid: false,
2696
+ error: `Chain broken: ${parent.cid} audience (${parent.audienceDid}) != ${current.cid} issuer (${current.issuerDid})`
2697
+ };
2698
+ }
2699
+ }
2700
+ const root = proofChain[proofChain.length - 1];
2701
+ if (root.issuerDid !== flowOwnerDid) {
2702
+ return { valid: false, error: `Root issuer ${root.issuerDid} is not flow owner ${flowOwnerDid}` };
2703
+ }
2704
+ return { valid: true, proofChain };
2705
+ };
2706
+ const createAndValidateInvocation = async (params, _flowId, _blockId) => {
2707
+ const { invokerDid, invokerType, entityRoomId, capability, proofs, pin } = params;
2708
+ const validation = await validateDelegationChain(invokerDid, capability);
2709
+ if (!validation.valid) {
2710
+ return {
2711
+ cid: "",
2712
+ invocation: "",
2713
+ valid: false,
2714
+ error: validation.error
2715
+ };
2716
+ }
2717
+ const signer = await getSigner(handlers, invokerDid, invokerType, entityRoomId, pin);
2718
+ const proofDelegations = await getProofDelegations(proofs);
2719
+ const ucantoCapability = {
2720
+ can: capability.can,
2721
+ with: capability.with,
2722
+ ...capability.nb && { nb: capability.nb }
2723
+ };
2724
+ const invocation = await ucanCreateInvocation({
2725
+ issuer: signer,
2726
+ audience: flowOwnerDid,
2727
+ capability: ucantoCapability,
2728
+ proofs: proofDelegations
2729
+ });
2730
+ const serialized = await serializeInvocation(invocation);
2731
+ const built = await invocation.buildIPLDView();
2732
+ const cid = built.cid.toString();
2733
+ return {
2734
+ cid,
2735
+ invocation: serialized,
2736
+ valid: true
2737
+ };
2738
+ };
2739
+ const executeWithInvocation = async (params, action, flowId, blockId) => {
2740
+ const invocationResult = await createAndValidateInvocation(params, flowId, blockId);
2741
+ if (!invocationResult.valid) {
2742
+ return {
2743
+ success: false,
2744
+ invocationCid: invocationResult.cid,
2745
+ error: invocationResult.error
2746
+ };
2747
+ }
2748
+ if (invocationStore.hasBeenInvoked(invocationResult.cid)) {
2749
+ return {
2750
+ success: false,
2751
+ invocationCid: invocationResult.cid,
2752
+ error: "Invocation has already been used (replay attack prevented)"
2753
+ };
2754
+ }
2755
+ try {
2756
+ const actionResult = await action();
2757
+ const storedInvocation = {
2758
+ cid: invocationResult.cid,
2759
+ invocation: invocationResult.invocation,
2760
+ invokerDid: params.invokerDid,
2761
+ capability: params.capability,
2762
+ executedAt: Date.now(),
2763
+ flowId,
2764
+ blockId,
2765
+ result: "success",
2766
+ proofCids: params.proofs
2767
+ };
2768
+ invocationStore.add(storedInvocation);
2769
+ return {
2770
+ success: true,
2771
+ invocationCid: invocationResult.cid,
2772
+ result: actionResult,
2773
+ actionResult
2774
+ };
2775
+ } catch (error) {
2776
+ const storedInvocation = {
2777
+ cid: invocationResult.cid,
2778
+ invocation: invocationResult.invocation,
2779
+ invokerDid: params.invokerDid,
2780
+ capability: params.capability,
2781
+ executedAt: Date.now(),
2782
+ flowId,
2783
+ blockId,
2784
+ result: "failure",
2785
+ error: error instanceof Error ? error.message : "Unknown error",
2786
+ proofCids: params.proofs
2787
+ };
2788
+ invocationStore.add(storedInvocation);
2789
+ return {
2790
+ success: false,
2791
+ invocationCid: invocationResult.cid,
2792
+ error: error instanceof Error ? error.message : "Unknown error"
2793
+ };
2794
+ }
2795
+ };
2796
+ return {
2797
+ createRootDelegation,
2798
+ createDelegation,
2799
+ revokeDelegation,
2800
+ getDelegation,
2801
+ getAllDelegations,
2802
+ getRootDelegation,
2803
+ createAndValidateInvocation,
2804
+ executeWithInvocation,
2805
+ validateDelegationChain,
2806
+ findValidProofs,
2807
+ parseDelegationFromStore,
2808
+ isConfigured
2809
+ };
2810
+ };
2811
+
2812
+ export {
2813
+ resolveActionType,
2814
+ registerAction,
2815
+ getAction,
2816
+ getAllActions,
2817
+ hasAction,
2818
+ getActionByCan,
2819
+ canToType,
2820
+ typeToCan,
2821
+ getAllCanMappings,
2822
+ buildServicesFromHandlers,
2823
+ getDiffResolver,
2824
+ hasDiffResolver,
2825
+ buildVerifiableCredential,
2826
+ buildDomainCardLinkedResource,
2827
+ parseLinkedEntities,
2828
+ buildGovernanceGroupLinkedEntities,
2829
+ transformSurveyToCredentialSubject,
2830
+ extractSurveyAnswersTemplate,
2831
+ getHomeserver,
2832
+ didToMatrixUserId,
2833
+ findOrCreateDMRoom,
2834
+ sendDirectMessage,
2835
+ createUcanDelegationStore,
2836
+ createMemoryUcanDelegationStore,
2837
+ createInvocationStore,
2838
+ createMemoryInvocationStore,
2839
+ buildAuthzFromProps,
2840
+ buildFlowNodeFromBlock,
2841
+ createRuntimeStateManager,
2842
+ clearRuntimeForTemplateClone,
2843
+ isNodeActive,
2844
+ isAuthorized,
2845
+ executeNode,
2846
+ createUcanService
2847
+ };
2848
+ //# sourceMappingURL=chunk-5D26UG3I.mjs.map