@wowok/agent-mcp 2.6.3 → 2.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/dist/customer/customer-advice.d.ts +31 -0
  2. package/dist/customer/customer-advice.js +129 -0
  3. package/dist/customer/index.d.ts +2 -0
  4. package/dist/customer/index.js +2 -0
  5. package/dist/customer/info-puzzle.d.ts +8 -1
  6. package/dist/customer/info-puzzle.js +30 -5
  7. package/dist/customer/order-monitor.d.ts +2 -0
  8. package/dist/customer/order-monitor.js +3 -2
  9. package/dist/customer/post-purchase.d.ts +2 -0
  10. package/dist/customer/post-purchase.js +6 -5
  11. package/dist/customer/preorder-compare.d.ts +24 -0
  12. package/dist/customer/preorder-compare.js +34 -0
  13. package/dist/customer/reminder-system.d.ts +2 -0
  14. package/dist/customer/reminder-system.js +2 -1
  15. package/dist/customer/risk-assessment.js +4 -3
  16. package/dist/customer/types.d.ts +5 -0
  17. package/dist/examples/arbitration-dispute-create.json +41 -0
  18. package/dist/examples/arbitration-vote-weighted.json +35 -0
  19. package/dist/examples/arbitration-voting-guard-add.json +38 -0
  20. package/dist/examples/demand-present-service.json +33 -0
  21. package/dist/examples/gen-passport-verify-guard.json +48 -0
  22. package/dist/examples/guard-template-balance-check.json +36 -15
  23. package/dist/examples/guard-template-time-lock.json +33 -12
  24. package/dist/examples/insurance-guard-claim-timelock.json +75 -0
  25. package/dist/examples/insurance-guard-withdraw-allocation.json +96 -0
  26. package/dist/examples/insurance-machine-create-publish.json +75 -0
  27. package/dist/examples/insurance-service-allocators-publish.json +56 -0
  28. package/dist/examples/machine-multisig-threshold.json +86 -0
  29. package/dist/examples/machine-template-7node-rental.json +99 -94
  30. package/dist/examples/payment-scenario-bound.json +45 -0
  31. package/dist/examples/rental-ziroom-machine-create.json +126 -114
  32. package/dist/examples/rental-ziroom-permission-create.json +10 -3
  33. package/dist/examples/rental-ziroom-service-create.json +27 -18
  34. package/dist/examples/retail-adv-guard-customer-win-create.json +80 -0
  35. package/dist/examples/retail-adv-guard-messenger-proof-create.json +65 -0
  36. package/dist/examples/retail-adv-guard-reward-timeout-create.json +92 -0
  37. package/dist/examples/retail-adv-reward-guard-add.json +51 -0
  38. package/dist/examples/retail-myshop-allocation-activate.json +55 -0
  39. package/dist/examples/retail-myshop-arbitration-create.json +40 -0
  40. package/dist/examples/retail-myshop-contact-create.json +43 -0
  41. package/dist/examples/retail-myshop-order-create.json +56 -0
  42. package/dist/examples/retail-myshop-progress-operate.json +38 -0
  43. package/dist/examples/retail-myshop-reward-create.json +35 -0
  44. package/dist/examples/service-discount-issue.json +46 -0
  45. package/dist/examples/threebody-guard-create.json +56 -0
  46. package/dist/examples/threebody-machine-create.json +72 -0
  47. package/dist/examples/threebody-permission-create.json +38 -0
  48. package/dist/examples/threebody-service-allocators.json +49 -0
  49. package/dist/examples/travel-guard-time-lock.json +69 -0
  50. package/dist/examples/travel-guard-weather-oracle.json +70 -0
  51. package/dist/examples/travel-machine-create.json +136 -0
  52. package/dist/examples/travel-repository-create.json +47 -0
  53. package/dist/examples/travel-service-create.json +102 -0
  54. package/dist/examples/travel-treasury-create.json +34 -0
  55. package/dist/examples/treasury-deposit.json +37 -0
  56. package/dist/examples/treasury-withdraw.json +38 -0
  57. package/dist/extensions/business-modules.d.ts +49 -0
  58. package/dist/extensions/business-modules.js +287 -0
  59. package/dist/extensions/capability-manifest.js +192 -5
  60. package/dist/extensions/constraint-registry.js +3 -1
  61. package/dist/extensions/modes.js +10 -4
  62. package/dist/extensions/registry.d.ts +14 -9
  63. package/dist/extensions/registry.js +69 -14
  64. package/dist/extensions/types.d.ts +1 -0
  65. package/dist/knowledge/fund-layer.d.ts +67 -1
  66. package/dist/knowledge/fund-layer.js +561 -12
  67. package/dist/knowledge/guard-templates.d.ts +10 -0
  68. package/dist/knowledge/guard-templates.js +50 -0
  69. package/dist/knowledge/index.d.ts +2 -2
  70. package/dist/knowledge/index.js +2 -2
  71. package/dist/knowledge/machine-risk.js +4 -1
  72. package/dist/knowledge/progress-context.js +1 -1
  73. package/dist/knowledge/progress-ledger.js +3 -3
  74. package/dist/knowledge/progress-templates.js +1 -1
  75. package/dist/knowledge/progress-translation.js +1 -1
  76. package/dist/knowledge/safety-rules.d.ts +83 -1
  77. package/dist/knowledge/safety-rules.js +166 -2
  78. package/dist/knowledge/scenario-modes.d.ts +1 -1
  79. package/dist/knowledge/scenario-modes.js +13 -11
  80. package/dist/knowledge/template-registry.d.ts +48 -0
  81. package/dist/knowledge/template-registry.js +341 -0
  82. package/dist/knowledge/tool-constraints.js +6 -6
  83. package/dist/knowledge/tools-reference.js +11 -8
  84. package/dist/participation/merchant-interest.d.ts +32 -0
  85. package/dist/participation/merchant-interest.js +100 -0
  86. package/dist/participation/radar-core.d.ts +104 -0
  87. package/dist/participation/radar-core.js +269 -0
  88. package/dist/project/context-assembly.js +8 -0
  89. package/dist/project/edit-planner.js +27 -56
  90. package/dist/project/evaluation.d.ts +36 -0
  91. package/dist/project/evaluation.js +422 -56
  92. package/dist/project/game-theory.d.ts +43 -0
  93. package/dist/project/game-theory.js +177 -0
  94. package/dist/project/graph-builder.js +1 -0
  95. package/dist/project/handlers.d.ts +38 -0
  96. package/dist/project/handlers.js +65 -35
  97. package/dist/project/intent-analyzer.d.ts +71 -0
  98. package/dist/project/intent-analyzer.js +149 -0
  99. package/dist/project/machine-nodes.d.ts +2 -0
  100. package/dist/project/machine-nodes.js +36 -0
  101. package/dist/project/merchant-guide.d.ts +165 -0
  102. package/dist/project/merchant-guide.js +264 -0
  103. package/dist/project/mode-actions.d.ts +199 -0
  104. package/dist/project/mode-actions.js +309 -0
  105. package/dist/project/participation-radar.d.ts +18 -0
  106. package/dist/project/participation-radar.js +428 -0
  107. package/dist/project/pipeline-actions.d.ts +101 -0
  108. package/dist/project/pipeline-actions.js +109 -0
  109. package/dist/project/semantic-graph.d.ts +95 -0
  110. package/dist/project/semantic-graph.js +245 -0
  111. package/dist/schema/call/allocation.d.ts +11 -11
  112. package/dist/schema/call/allocation.js +11 -1
  113. package/dist/schema/call/arbitration.d.ts +21 -21
  114. package/dist/schema/call/arbitration.js +17 -9
  115. package/dist/schema/call/base.d.ts +2 -2
  116. package/dist/schema/call/base.js +1 -1
  117. package/dist/schema/call/bridge.d.ts +127 -127
  118. package/dist/schema/call/bridge.js +12 -12
  119. package/dist/schema/call/contact.d.ts +3 -3
  120. package/dist/schema/call/demand.d.ts +3 -3
  121. package/dist/schema/call/guard.d.ts +11 -11
  122. package/dist/schema/call/guard.js +1 -1
  123. package/dist/schema/call/machine.d.ts +216 -21
  124. package/dist/schema/call/machine.js +1 -1
  125. package/dist/schema/call/order.d.ts +7 -7
  126. package/dist/schema/call/payment.d.ts +3 -3
  127. package/dist/schema/call/permission.d.ts +3 -3
  128. package/dist/schema/call/personal.d.ts +337 -3
  129. package/dist/schema/call/personal.js +10 -0
  130. package/dist/schema/call/progress.d.ts +177 -9
  131. package/dist/schema/call/progress.js +7 -3
  132. package/dist/schema/call/proof.d.ts +6 -6
  133. package/dist/schema/call/repository.d.ts +3 -3
  134. package/dist/schema/call/reward.d.ts +57 -57
  135. package/dist/schema/call/semantic.js +41 -1
  136. package/dist/schema/call/service.d.ts +114 -114
  137. package/dist/schema/call/service.js +11 -2
  138. package/dist/schema/call/treasury.d.ts +57 -57
  139. package/dist/schema/messenger/index.js +4 -1
  140. package/dist/schema/operations.d.ts +713 -291
  141. package/dist/schema/operations.js +33 -0
  142. package/dist/schema/project/index.d.ts +4635 -100
  143. package/dist/schema/project/index.js +868 -1
  144. package/dist/schema/query/index.d.ts +363 -19
  145. package/dist/schema/query/index.js +25 -3
  146. package/dist/schema/schema-query/index.d.ts +13 -7
  147. package/dist/schema/schema-query/index.js +29 -5
  148. package/dist/schema/trust/index.d.ts +1012 -6
  149. package/dist/schema/trust/index.js +212 -11
  150. package/dist/schema/utils/skills-recommendation.js +1 -0
  151. package/dist/schema-query/index.d.ts +4 -1
  152. package/dist/schema-query/index.js +255 -1
  153. package/dist/schemas/bridge_operation.schema.json +14 -7
  154. package/dist/schemas/guard2file.schema.json +2 -0
  155. package/dist/schemas/index.json +1 -1
  156. package/dist/schemas/machineNode2file.schema.json +2 -0
  157. package/dist/schemas/messenger_operation.schema.json +1 -1
  158. package/dist/schemas/onchain_operations.schema.json +143 -15
  159. package/dist/schemas/onchain_operations_allocation.schema.json +2 -1
  160. package/dist/schemas/onchain_operations_arbitration.schema.json +7 -5
  161. package/dist/schemas/onchain_operations_contact.schema.json +1 -0
  162. package/dist/schemas/onchain_operations_demand.schema.json +1 -0
  163. package/dist/schemas/onchain_operations_gen_passport.schema.json +2 -0
  164. package/dist/schemas/onchain_operations_gen_proof.schema.json +2 -0
  165. package/dist/schemas/onchain_operations_guard.schema.json +578 -0
  166. package/dist/schemas/onchain_operations_machine.schema.json +1 -0
  167. package/dist/schemas/onchain_operations_order.schema.json +4 -3
  168. package/dist/schemas/onchain_operations_payment.schema.json +1 -0
  169. package/dist/schemas/onchain_operations_permission.schema.json +1 -0
  170. package/dist/schemas/onchain_operations_personal.schema.json +37 -0
  171. package/dist/schemas/onchain_operations_progress.schema.json +90 -3
  172. package/dist/schemas/onchain_operations_proof.schema.json +1 -0
  173. package/dist/schemas/onchain_operations_repository.schema.json +1 -0
  174. package/dist/schemas/onchain_operations_reward.schema.json +1 -0
  175. package/dist/schemas/onchain_operations_service.schema.json +4 -3
  176. package/dist/schemas/onchain_operations_treasury.schema.json +1 -0
  177. package/dist/schemas/project_operation.output.json +2243 -1
  178. package/dist/schemas/project_operation.schema.json +683 -1
  179. package/dist/schemas/query_toolkit.output.json +1 -1
  180. package/dist/schemas/query_toolkit.schema.json +37 -0
  181. package/dist/schemas/schema_query.output.json +1 -1
  182. package/dist/schemas/schema_query.schema.json +30 -5
  183. package/dist/schemas/trust_score.output.json +392 -1
  184. package/dist/schemas/trust_score.schema.json +275 -1
  185. package/dist/tools/handlers/onchain.js +73 -8
  186. package/dist/tools/handlers/project.js +46 -0
  187. package/dist/tools/handlers/query.js +117 -2
  188. package/dist/tools/handlers/schema-query.js +41 -0
  189. package/dist/tools/handlers/trust.js +192 -6
  190. package/dist/tools/index.js +52 -9
  191. package/dist/tools/wrap.js +194 -15
  192. package/package.json +2 -2
@@ -0,0 +1,428 @@
1
+ import { LocalMark, query_objects, query_table, watch_conversations, } from "@wowok/wowok";
2
+ import { analyzeOrderParticipation, aggregateRadar, isConsequenceNode, } from "../participation/radar-core.js";
3
+ import { monitorOrder } from "../customer/order-monitor.js";
4
+ import { analyzeMerchantInterest } from "../participation/merchant-interest.js";
5
+ import { fetchMachineNodes } from "./machine-nodes.js";
6
+ import { extractGenericTokenType, registryDisplayHint } from "../knowledge/fund-layer.js";
7
+ const QUERY_BATCH = 50;
8
+ function fld(obj, key) {
9
+ return (obj?.[key] ?? obj?.data?.[key]);
10
+ }
11
+ async function resolveAddress(nameOrAddress, what) {
12
+ const addr = await LocalMark.Instance().get_address(nameOrAddress);
13
+ if (!addr) {
14
+ throw new Error(`Cannot resolve ${what} '${nameOrAddress}' — not a valid address and no LocalMark entry found. ` +
15
+ `Register it via local_mark_operation or pass the 0x address directly.`);
16
+ }
17
+ return addr;
18
+ }
19
+ function balanceStr(v) {
20
+ if (v == null)
21
+ return undefined;
22
+ if (typeof v === "object" && "balance" in v)
23
+ return String(v.balance);
24
+ return String(v);
25
+ }
26
+ function balanceToken(v) {
27
+ if (v != null && typeof v === "object" && typeof v.token_type === "string") {
28
+ return v.token_type;
29
+ }
30
+ return undefined;
31
+ }
32
+ function summarizeAllocation(raw, account) {
33
+ const list = Array.isArray(raw)
34
+ ? raw
35
+ : Array.isArray(raw?.allocators)
36
+ ? raw.allocators
37
+ : [];
38
+ if (list.length === 0)
39
+ return undefined;
40
+ let recipient_slots = 0;
41
+ let guard_gated_slots = 0;
42
+ let direct_to_me_slots = 0;
43
+ let to_payer_slots = 0;
44
+ const me = account.toLowerCase();
45
+ for (const allocator of list) {
46
+ for (const s of allocator?.sharing ?? []) {
47
+ recipient_slots++;
48
+ const who = s?.who;
49
+ if (who == null)
50
+ continue;
51
+ if (typeof who === "object" && "GuardIdentifier" in who)
52
+ guard_gated_slots++;
53
+ else if (typeof who === "object" && "Signer" in who)
54
+ to_payer_slots++;
55
+ else if (typeof who === "object" && "Entity" in who) {
56
+ const entity = who.Entity;
57
+ const addr = typeof entity === "string" ? entity : entity?.name_or_address;
58
+ if (typeof addr === "string" && addr.toLowerCase() === me)
59
+ direct_to_me_slots++;
60
+ }
61
+ else if (typeof who === "string" && who.toLowerCase() === me) {
62
+ direct_to_me_slots++;
63
+ }
64
+ }
65
+ }
66
+ return { recipient_slots, guard_gated_slots, direct_to_me_slots, to_payer_slots };
67
+ }
68
+ async function queryObjectsBatched(addresses, network) {
69
+ const out = [];
70
+ for (let i = 0; i < addresses.length; i += QUERY_BATCH) {
71
+ const batch = addresses.slice(i, i + QUERY_BATCH);
72
+ const res = await query_objects({ objects: batch, network });
73
+ out.push(...(res?.objects ?? []));
74
+ }
75
+ return out;
76
+ }
77
+ async function fetchEntityPermissions(permissionAddress, network) {
78
+ const map = new Map();
79
+ const fieldIds = [];
80
+ let cursor = undefined;
81
+ for (;;) {
82
+ const tableResult = await query_table({
83
+ parent: permissionAddress,
84
+ cursor: cursor ?? undefined,
85
+ network,
86
+ });
87
+ if (!tableResult?.items || tableResult.items.length === 0)
88
+ break;
89
+ for (const item of tableResult.items) {
90
+ if (item.object)
91
+ fieldIds.push(item.object);
92
+ }
93
+ if (!tableResult.hasNextPage || !tableResult.nextCursor)
94
+ break;
95
+ cursor = tableResult.nextCursor;
96
+ }
97
+ const items = (await queryObjectsBatched(fieldIds, network));
98
+ for (const item of items) {
99
+ if (item?.type !== "TableItem_PermissionPerm")
100
+ continue;
101
+ const entity = fld(item, "address");
102
+ const permRaw = fld(item, "perm") ?? [];
103
+ const indexes = permRaw
104
+ .map(p => (typeof p === "number" ? p : typeof p?.index === "number" ? p.index : null))
105
+ .filter((p) => p !== null);
106
+ if (entity)
107
+ map.set(entity, indexes);
108
+ }
109
+ return map;
110
+ }
111
+ function toRadarMachineNodes(raw) {
112
+ return raw.map(n => ({
113
+ name: n.name,
114
+ pairs: (Array.isArray(n.value) ? n.value : []).map(pair => ({
115
+ prev_node: pair.prev_node,
116
+ forwards: (pair.forwards ?? []).map(f => ({
117
+ name: f.name,
118
+ permissionIndex: f.permissionIndex ?? null,
119
+ namedOperator: f.namedOperator ?? null,
120
+ guard: f.guard?.guard ?? (typeof f.guard === "string" ? f.guard : null),
121
+ weight: f.weight ?? null,
122
+ })),
123
+ })),
124
+ }));
125
+ }
126
+ export async function handleParticipationRadar(v) {
127
+ if (!v.radar_account) {
128
+ throw new Error("'radar_account' is required for participation_radar");
129
+ }
130
+ if (!v.radar_targets || v.radar_targets.length === 0) {
131
+ throw new Error("'radar_targets' (1-20 in-flight orders) is required for participation_radar");
132
+ }
133
+ const network = (v.network ?? "testnet");
134
+ const includeAlerts = v.radar_include_alerts ?? true;
135
+ const gaps = [];
136
+ const account = await resolveAddress(v.radar_account, "radar_account");
137
+ const targets = await Promise.all(v.radar_targets.map(async (t) => ({
138
+ progress: await resolveAddress(t.progress, "progress"),
139
+ order: t.order ? await resolveAddress(t.order, "order") : undefined,
140
+ })));
141
+ const allAddrs = targets.flatMap(t => (t.order ? [t.progress, t.order] : [t.progress]));
142
+ const objects = await queryObjectsBatched(allAddrs, network);
143
+ const byAddress = new Map();
144
+ for (const o of objects) {
145
+ const addr = fld(o, "object");
146
+ if (addr)
147
+ byAddress.set(addr, o);
148
+ }
149
+ const progressObjs = new Map();
150
+ const orderObjs = new Map();
151
+ for (const t of targets) {
152
+ const p = byAddress.get(t.progress);
153
+ if (!p) {
154
+ gaps.push(`Progress ${t.progress} not found on ${network} — target skipped.`);
155
+ continue;
156
+ }
157
+ progressObjs.set(t.progress, p);
158
+ if (t.order) {
159
+ const o = byAddress.get(t.order);
160
+ if (o)
161
+ orderObjs.set(t.order, o);
162
+ else
163
+ gaps.push(`Order ${t.order} not found on ${network} — order-holder detection disabled for ${t.progress}.`);
164
+ }
165
+ }
166
+ if (targets.length > 0 && progressObjs.size === 0) {
167
+ gaps.push(`NETWORK MISMATCH SUSPECTED: 0/${targets.length} radar targets exist on network='${network}'. ` +
168
+ `These objects most likely live on a different network — re-run with the matching 'network' parameter.`);
169
+ }
170
+ const machineAddrs = [...new Set([...progressObjs.values()].map(p => fld(p, "machine")).filter((x) => !!x))];
171
+ const serviceAddrs = [...new Set([...orderObjs.values()].map(o => fld(o, "service")).filter((x) => !!x))];
172
+ const arbAddrs = [...new Set([...orderObjs.values()].flatMap(o => {
173
+ const d = fld(o, "dispute");
174
+ return Array.isArray(d) ? d : [];
175
+ }))];
176
+ const machineObjs = new Map();
177
+ const machineNodes = new Map();
178
+ const serviceObjs = new Map();
179
+ const arbObjs = new Map();
180
+ await Promise.all([
181
+ ...machineAddrs.map(async (addr) => {
182
+ try {
183
+ const [objArr, nodes] = await Promise.all([
184
+ queryObjectsBatched([addr], network),
185
+ fetchMachineNodes(addr, network),
186
+ ]);
187
+ if (objArr[0])
188
+ machineObjs.set(addr, objArr[0]);
189
+ machineNodes.set(addr, toRadarMachineNodes(nodes));
190
+ }
191
+ catch (e) {
192
+ gaps.push(`Machine ${addr} fetch failed: ${e.message} — workflow unknown for its orders.`);
193
+ }
194
+ }),
195
+ (async () => {
196
+ if (serviceAddrs.length === 0)
197
+ return;
198
+ try {
199
+ const arr = await queryObjectsBatched(serviceAddrs, network);
200
+ for (const s of arr) {
201
+ const addr = fld(s, "object");
202
+ if (addr)
203
+ serviceObjs.set(addr, s);
204
+ }
205
+ }
206
+ catch (e) {
207
+ gaps.push(`Service query failed: ${e.message} — compensation/reward context degraded.`);
208
+ }
209
+ })(),
210
+ (async () => {
211
+ if (arbAddrs.length === 0)
212
+ return;
213
+ try {
214
+ const arr = await queryObjectsBatched(arbAddrs, network);
215
+ for (const a of arr) {
216
+ const addr = fld(a, "object");
217
+ if (addr)
218
+ arbObjs.set(addr, a);
219
+ }
220
+ }
221
+ catch (e) {
222
+ gaps.push(`Arb query failed: ${e.message} — compensation claim detection disabled.`);
223
+ }
224
+ })(),
225
+ ]);
226
+ const permissionByMachine = new Map();
227
+ const permAddrs = [...new Set(machineAddrs.map(a => fld(machineObjs.get(a), "permission")).filter((x) => !!x))];
228
+ const permData = new Map();
229
+ await Promise.all(permAddrs.map(async (addr) => {
230
+ try {
231
+ const [objArr, entityPermissions] = await Promise.all([
232
+ queryObjectsBatched([addr], network),
233
+ fetchEntityPermissions(addr, network),
234
+ ]);
235
+ const permObj = objArr[0];
236
+ permData.set(addr, {
237
+ address: addr,
238
+ entity_count: fld(permObj, "entity_count"),
239
+ perm_remark: fld(permObj, "perm_remark"),
240
+ entityPermissions,
241
+ });
242
+ }
243
+ catch (e) {
244
+ gaps.push(`Permission ${addr} fetch failed: ${e.message} — operator permission matching degraded.`);
245
+ }
246
+ }));
247
+ for (const mAddr of machineAddrs) {
248
+ const pAddr = fld(machineObjs.get(mAddr), "permission");
249
+ if (pAddr && permData.has(pAddr))
250
+ permissionByMachine.set(mAddr, permData.get(pAddr));
251
+ }
252
+ let unreadTotal = 0;
253
+ const unreadByPeer = new Map();
254
+ try {
255
+ const convos = await watch_conversations({
256
+ account,
257
+ unreadOnly: true,
258
+ previewMessageCount: 0,
259
+ skipAutoMarkViewed: true,
260
+ });
261
+ const list = Array.isArray(convos) ? convos : convos?.conversations ?? [];
262
+ for (const c of list) {
263
+ const peer = c?.peerAddress;
264
+ const n = typeof c?.unreadCount === "number" ? c.unreadCount : 0;
265
+ if (typeof peer === "string" && n > 0) {
266
+ unreadByPeer.set(peer.toLowerCase(), n);
267
+ unreadTotal += n;
268
+ }
269
+ }
270
+ }
271
+ catch {
272
+ gaps.push("Messenger unread unavailable (radar account is not a local messenger account, or messenger storage offline) " +
273
+ "— unread_messages_total reported as 0.");
274
+ }
275
+ const results = [];
276
+ const now = Date.now();
277
+ for (const t of targets) {
278
+ const progress = progressObjs.get(t.progress);
279
+ if (!progress)
280
+ continue;
281
+ const order = t.order ? orderObjs.get(t.order) : undefined;
282
+ const machineAddr = fld(progress, "machine");
283
+ const currentNode = fld(progress, "current") ?? "";
284
+ const namedOperators = fld(progress, "namedOperator") ?? [];
285
+ const namedAccounts = {};
286
+ for (const n of namedOperators) {
287
+ if (n?.name)
288
+ namedAccounts[n.name] = Array.isArray(n.operators) ? n.operators : [];
289
+ }
290
+ const serviceAddr = order ? fld(order, "service") : undefined;
291
+ const service = serviceAddr ? serviceObjs.get(serviceAddr) : undefined;
292
+ let pendingCompensation;
293
+ const builder = order ? fld(order, "builder") : undefined;
294
+ if (order && builder === account) {
295
+ const disputes = fld(order, "dispute") ?? [];
296
+ for (const arbAddr of disputes) {
297
+ const arb = arbObjs.get(arbAddr);
298
+ if (!arb)
299
+ continue;
300
+ const indemnity = fld(arb, "indemnity");
301
+ if (indemnity) {
302
+ pendingCompensation = {
303
+ arbitration: fld(arb, "arbitration") ?? arbAddr,
304
+ note: `Arbitration verdict recorded an indemnity (Arb ${arbAddr}). ` +
305
+ `Claim via service op='compensation_claim' — paid directly from the Service compensation_fund. ` +
306
+ `(Claimed-status is not readable from the Arb object; the contract rejects double-claims.)`,
307
+ };
308
+ break;
309
+ }
310
+ }
311
+ }
312
+ const claimableRewards = [];
313
+ if (service && builder === account) {
314
+ const rewards = fld(service, "rewards") ?? [];
315
+ for (const r of rewards) {
316
+ claimableRewards.push({
317
+ address: r,
318
+ description: `Service reward ${r} (guard-gated — eligibility verified at claim time)`,
319
+ });
320
+ }
321
+ }
322
+ const completed = isConsequenceNode(currentNode, "completed");
323
+ const refunded = isConsequenceNode(currentNode, "refunded");
324
+ let orderUnread = 0;
325
+ if (unreadByPeer.size > 0) {
326
+ const counterparties = new Set();
327
+ if (builder)
328
+ counterparties.add(builder.toLowerCase());
329
+ for (const ops of Object.values(namedAccounts)) {
330
+ for (const op of ops)
331
+ counterparties.add(op.toLowerCase());
332
+ }
333
+ counterparties.delete(account.toLowerCase());
334
+ for (const peer of counterparties) {
335
+ orderUnread += unreadByPeer.get(peer) ?? 0;
336
+ }
337
+ }
338
+ const radarInput = {
339
+ account,
340
+ progress_address: t.progress,
341
+ order_address: t.order,
342
+ current_node: currentNode,
343
+ order_holder: builder,
344
+ machine_nodes: machineAddr ? machineNodes.get(machineAddr) : undefined,
345
+ permission: machineAddr ? permissionByMachine.get(machineAddr) ?? null : null,
346
+ named_accounts: namedAccounts,
347
+ claimable_rewards: claimableRewards.length > 0 ? claimableRewards : undefined,
348
+ pending_compensation: pendingCompensation,
349
+ rating_pending: completed && builder === account,
350
+ unread_messages: orderUnread > 0 ? orderUnread : undefined,
351
+ last_progress_at: fld(progress, "current_time") ?? undefined,
352
+ now,
353
+ };
354
+ const result = analyzeOrderParticipation(radarInput);
355
+ if (result.perspective === "operator") {
356
+ result.interest_analysis = analyzeMerchantInterest({
357
+ account,
358
+ current_node: currentNode,
359
+ operable: result.operable,
360
+ waiting_on: result.waiting_on,
361
+ order_amount: balanceStr(fld(order, "amount")),
362
+ token_type: balanceToken(fld(order, "amount")),
363
+ allocation: summarizeAllocation(fld(service, "order_allocators"), account),
364
+ compensation_fund: balanceStr(fld(service, "compensation_fund")),
365
+ arbitration_bound: (fld(service, "arbitrations") ?? []).length > 0,
366
+ rewards_count: (fld(service, "rewards") ?? []).length,
367
+ stalled_hours: radarInput.last_progress_at != null
368
+ ? (now - radarInput.last_progress_at) / 3_600_000
369
+ : undefined,
370
+ terminal: completed ? "completed" : refunded ? "refunded" : null,
371
+ unread_messages: orderUnread > 0 ? orderUnread : undefined,
372
+ });
373
+ }
374
+ if (includeAlerts && order) {
375
+ const snapshot = {
376
+ order_id: t.order,
377
+ service_id: serviceAddr ?? "",
378
+ current_node: currentNode || undefined,
379
+ created_at: Number(fld(order, "time") ?? now) || now,
380
+ last_progress_at: fld(progress, "current_time") ?? undefined,
381
+ now,
382
+ order_amount: (() => { try {
383
+ return BigInt(fld(order, "amount") ?? 0);
384
+ }
385
+ catch {
386
+ return undefined;
387
+ } })(),
388
+ compensation_balance: (() => { try {
389
+ const c = fld(service, "compensation_fund");
390
+ return c != null ? BigInt(c) : undefined;
391
+ }
392
+ catch {
393
+ return undefined;
394
+ } })(),
395
+ token: registryDisplayHint(extractGenericTokenType(fld(service, "type_raw"))),
396
+ has_arbitration: (fld(service, "arbitrations") ?? []).length > 0,
397
+ pending_user_action: result.operable.some(f => f.execution_path === "order_holder"),
398
+ completed,
399
+ refunded,
400
+ };
401
+ try {
402
+ const alerts = monitorOrder({
403
+ current: snapshot,
404
+ thresholds: v.radar_monitor_thresholds,
405
+ });
406
+ if (alerts.length > 0) {
407
+ result.attached_alerts = alerts;
408
+ }
409
+ }
410
+ catch (e) {
411
+ gaps.push(`Order monitor failed for ${t.order}: ${e.message}.`);
412
+ }
413
+ }
414
+ results.push(result);
415
+ }
416
+ const dashboard = aggregateRadar(results, unreadTotal);
417
+ return {
418
+ action: "participation_radar",
419
+ account,
420
+ orders_analyzed: dashboard.orders_analyzed,
421
+ actionable: dashboard.actionable,
422
+ waiting: dashboard.waiting,
423
+ all_pending_claims: dashboard.all_pending_claims,
424
+ unread_messages_total: dashboard.unread_messages_total,
425
+ data_gaps: gaps,
426
+ summary: dashboard.summary,
427
+ };
428
+ }
@@ -0,0 +1,101 @@
1
+ import type { ObjectPuzzleEntry } from "./business-puzzle.js";
2
+ import type { SubstepRecord, SubstepEdge } from "./substep-trace.js";
3
+ export interface AnalyzeIntentInput {
4
+ intent?: string;
5
+ project_description?: string;
6
+ project_name?: string;
7
+ target_objects?: string[];
8
+ project_industry?: string;
9
+ project?: string;
10
+ version?: string;
11
+ }
12
+ export declare function handleAnalyzeIntent(v: AnalyzeIntentInput): {
13
+ intent_parsed: import("./business-puzzle.js").IntentParsed;
14
+ puzzles: Record<string, ObjectPuzzleEntry>;
15
+ overall_completeness: "complete" | "partial" | "empty";
16
+ next_step: string;
17
+ recommended_creation_order: string[];
18
+ warnings: string[];
19
+ action: "analyze_intent";
20
+ };
21
+ export interface AggregateRisksInput {
22
+ project?: string;
23
+ version?: string;
24
+ project_industry?: string;
25
+ intent?: string;
26
+ project_description?: string;
27
+ project_name?: string;
28
+ puzzles?: Record<string, {
29
+ puzzle?: unknown;
30
+ completeness?: unknown;
31
+ missing_dimensions: string[];
32
+ }>;
33
+ severity_threshold?: "CRITICAL" | "HIGH" | "MEDIUM" | "LOW" | "INFO";
34
+ user_confirmed_high_risks?: string[];
35
+ planned_objects?: {
36
+ object_type: string;
37
+ is_new: boolean;
38
+ name?: string;
39
+ }[];
40
+ planned_operations?: {
41
+ object_type: string;
42
+ trigger: "create" | "publish";
43
+ name?: string;
44
+ }[];
45
+ }
46
+ export declare function handleAggregateRisks(v: AggregateRisksInput): {
47
+ intent_echo?: {
48
+ primary_object: string;
49
+ industry: string;
50
+ overall_completeness: "complete" | "partial" | "empty";
51
+ } | undefined;
52
+ safety_findings?: import("../knowledge/safety-rules.js").SafetyRiskItem[] | undefined;
53
+ namespace: {
54
+ prefix: string;
55
+ version: string;
56
+ industry?: import("./namespace.js").IndustryMode;
57
+ };
58
+ findings: import("./risk-aggregator.js").AggregatedRisk[];
59
+ severity_summary: Record<import("./risk-aggregator.js").RiskSeverity, number>;
60
+ status: "RISK_PASSED" | "RISK_BLOCKED" | "RISK_PENDING_CONFIRM" | "RISK_CANCELLED";
61
+ pending_confirmations?: Array<{
62
+ risk_rule_id: string;
63
+ description: string;
64
+ fix_suggestion: string;
65
+ object_type: import("./namespace.js").ProjectObjectType;
66
+ entry_id: string;
67
+ }>;
68
+ calibrated_at: number;
69
+ fix_suggestions_grouped?: Record<string, Array<{
70
+ risk_rule_id: string;
71
+ severity: import("./risk-aggregator.js").RiskSeverity;
72
+ message: string;
73
+ fix_suggestion: string;
74
+ entry_id: string;
75
+ }>>;
76
+ warnings: string[];
77
+ action: "aggregate_risks";
78
+ };
79
+ export interface TraceSubstepsInput {
80
+ project?: string;
81
+ version?: string;
82
+ network?: "testnet" | "mainnet";
83
+ substeps?: SubstepRecord[];
84
+ substep_edges?: SubstepEdge[];
85
+ }
86
+ export declare function handleTraceSubsteps(v: TraceSubstepsInput): {
87
+ namespace: {
88
+ prefix: string;
89
+ version: string;
90
+ };
91
+ network: import("./substep-trace.js").SubstepNetwork;
92
+ coherent: boolean;
93
+ dangling_inputs: import("./substep-trace.js").DanglingInput[];
94
+ circular_refs: import("./substep-trace.js").CircularRef[];
95
+ missing_outputs: import("./substep-trace.js").MissingOutput[];
96
+ cross_step_breaks: import("./substep-trace.js").CrossStepBreak[];
97
+ step_details: import("./substep-trace.js").StepTraceDetail[];
98
+ topological_order: string[];
99
+ d10_check: import("./substep-trace.js").D10CheckResult;
100
+ action: "trace_substeps";
101
+ };
@@ -0,0 +1,109 @@
1
+ import { analyzeBusinessIntent } from "./business-puzzle.js";
2
+ import { aggregateProjectRisks } from "./risk-aggregator.js";
3
+ import { traceSubsteps } from "./substep-trace.js";
4
+ import { updateStageCache } from "./index.js";
5
+ import { checkObjectReuseRules, checkImmutabilityRules, } from "../knowledge/safety-rules.js";
6
+ export function handleAnalyzeIntent(v) {
7
+ const user_intent = (v.intent ?? v.project_description ?? v.project_name ?? "").trim();
8
+ if (!user_intent) {
9
+ throw new Error("analyze_intent requires 'intent' (business description text). " +
10
+ "Example: intent='I want to open an online toy store with escrow and dispute resolution'.");
11
+ }
12
+ const result = analyzeBusinessIntent({
13
+ user_intent,
14
+ project_name: v.project_name,
15
+ target_objects: v.target_objects,
16
+ industry: v.project_industry,
17
+ });
18
+ const project_prefix = (v.project ?? "").trim();
19
+ if (project_prefix) {
20
+ updateStageCache(project_prefix, (v.version ?? "v1").trim(), {
21
+ stage: 2,
22
+ puzzles: result.puzzles,
23
+ business_intent: user_intent,
24
+ industry: result.intent_parsed.industry,
25
+ });
26
+ }
27
+ return { action: "analyze_intent", ...result };
28
+ }
29
+ export function handleAggregateRisks(v) {
30
+ const project_prefix = (v.project ?? "").trim();
31
+ if (!project_prefix) {
32
+ throw new Error("aggregate_risks requires 'project' (project prefix, e.g. 'myshop'). " +
33
+ "Use the same prefix as create_project so findings map to the project namespace.");
34
+ }
35
+ const version = (v.version ?? "v1").trim();
36
+ let puzzles;
37
+ let intent_echo;
38
+ if (v.puzzles) {
39
+ puzzles = Object.fromEntries(Object.entries(v.puzzles).map(([k, e]) => [
40
+ k,
41
+ { puzzle: e.puzzle, completeness: e.completeness, missing_dimensions: e.missing_dimensions },
42
+ ]));
43
+ }
44
+ else {
45
+ const user_intent = (v.intent ?? v.project_description ?? v.project_name ?? "").trim();
46
+ if (!user_intent) {
47
+ throw new Error("aggregate_risks requires 'puzzles' (from a prior analyze_intent result) " +
48
+ "OR 'intent' (business description — analyze_intent runs automatically first).");
49
+ }
50
+ const analyzed = analyzeBusinessIntent({
51
+ user_intent,
52
+ project_name: v.project_name,
53
+ industry: v.project_industry,
54
+ });
55
+ puzzles = analyzed.puzzles;
56
+ intent_echo = {
57
+ primary_object: analyzed.intent_parsed.primary_object,
58
+ industry: analyzed.intent_parsed.industry,
59
+ overall_completeness: analyzed.overall_completeness,
60
+ };
61
+ }
62
+ const result = aggregateProjectRisks({
63
+ project_prefix,
64
+ version,
65
+ industry: v.project_industry,
66
+ puzzles,
67
+ severity_threshold: v.severity_threshold,
68
+ user_confirmed_high_risks: v.user_confirmed_high_risks,
69
+ });
70
+ const safety_findings = [
71
+ ...(v.planned_objects ? checkObjectReuseRules(v.planned_objects) : []),
72
+ ...(v.planned_operations ? checkImmutabilityRules(v.planned_operations) : []),
73
+ ];
74
+ updateStageCache(project_prefix, version, {
75
+ stage: 3,
76
+ risk_status: result.status,
77
+ risk_can_proceed: result.status === "RISK_PASSED",
78
+ });
79
+ return {
80
+ action: "aggregate_risks",
81
+ ...result,
82
+ ...(safety_findings.length > 0 ? { safety_findings } : {}),
83
+ ...(intent_echo ? { intent_echo } : {}),
84
+ };
85
+ }
86
+ export function handleTraceSubsteps(v) {
87
+ const project_prefix = (v.project ?? "").trim();
88
+ if (!project_prefix) {
89
+ throw new Error("trace_substeps requires 'project' (project prefix, e.g. 'myshop').");
90
+ }
91
+ if (!v.substeps || v.substeps.length === 0) {
92
+ throw new Error("trace_substeps requires 'substeps' (non-empty array of substep execution records, " +
93
+ "63-spec §2.1). Construct them from your deployment execution trace: each onchain_operations " +
94
+ "call = one substep with step_id 'T<step>.<substep>', input_refs pointing at upstream substeps.");
95
+ }
96
+ const result = traceSubsteps({
97
+ project_prefix,
98
+ version: (v.version ?? "v1").trim(),
99
+ network: v.network ?? "testnet",
100
+ substeps: v.substeps,
101
+ edges: v.substep_edges,
102
+ });
103
+ updateStageCache(project_prefix, (v.version ?? "v1").trim(), {
104
+ stage: 5,
105
+ trace_coherent: result.coherent,
106
+ trace_can_proceed: result.coherent,
107
+ });
108
+ return { action: "trace_substeps", ...result };
109
+ }