@wowok/agent-mcp 2.3.14 → 2.3.18

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 (189) hide show
  1. package/dist/config/index.d.ts +1 -0
  2. package/dist/config/index.js +1 -0
  3. package/dist/config/runtime.d.ts +26 -0
  4. package/dist/config/runtime.js +217 -0
  5. package/dist/customer/index.d.ts +9 -0
  6. package/dist/customer/index.js +9 -0
  7. package/dist/customer/industry-risks.d.ts +40 -0
  8. package/dist/customer/industry-risks.js +438 -0
  9. package/dist/customer/info-puzzle.d.ts +102 -0
  10. package/dist/customer/info-puzzle.js +312 -0
  11. package/dist/customer/order-monitor.d.ts +75 -0
  12. package/dist/customer/order-monitor.js +327 -0
  13. package/dist/customer/order-strategy.d.ts +36 -0
  14. package/dist/customer/order-strategy.js +373 -0
  15. package/dist/customer/post-purchase.d.ts +42 -0
  16. package/dist/customer/post-purchase.js +350 -0
  17. package/dist/customer/reminder-system.d.ts +42 -0
  18. package/dist/customer/reminder-system.js +295 -0
  19. package/dist/customer/risk-assessment.d.ts +8 -0
  20. package/dist/customer/risk-assessment.js +337 -0
  21. package/dist/customer/types.d.ts +193 -0
  22. package/dist/customer/types.js +13 -0
  23. package/dist/customer/user-preferences.d.ts +70 -0
  24. package/dist/customer/user-preferences.js +460 -0
  25. package/dist/experience/experience-reuse.d.ts +10 -0
  26. package/dist/experience/experience-reuse.js +103 -0
  27. package/dist/experience/index.d.ts +6 -0
  28. package/dist/experience/index.js +5 -0
  29. package/dist/experience/intent-distill.d.ts +3 -0
  30. package/dist/experience/intent-distill.js +83 -0
  31. package/dist/experience/realtime-feedback.d.ts +5 -0
  32. package/dist/experience/realtime-feedback.js +94 -0
  33. package/dist/experience/types.d.ts +50 -0
  34. package/dist/experience/types.js +1 -0
  35. package/dist/experience/user-profile.d.ts +25 -0
  36. package/dist/experience/user-profile.js +171 -0
  37. package/dist/index.js +842 -371
  38. package/dist/knowledge/acquisition-flywheel.d.ts +53 -0
  39. package/dist/knowledge/acquisition-flywheel.js +192 -0
  40. package/dist/knowledge/arbitration-trust.d.ts +24 -0
  41. package/dist/knowledge/arbitration-trust.js +117 -0
  42. package/dist/knowledge/audit-rules.d.ts +28 -0
  43. package/dist/knowledge/audit-rules.js +141 -0
  44. package/dist/knowledge/demand-matching.d.ts +29 -0
  45. package/dist/knowledge/demand-matching.js +132 -0
  46. package/dist/knowledge/dynamic-pricing.d.ts +31 -0
  47. package/dist/knowledge/dynamic-pricing.js +87 -0
  48. package/dist/knowledge/flywheel-loop.d.ts +87 -0
  49. package/dist/knowledge/flywheel-loop.js +378 -0
  50. package/dist/knowledge/glossary.d.ts +18 -0
  51. package/dist/knowledge/glossary.js +209 -0
  52. package/dist/knowledge/guard-ledger.d.ts +19 -0
  53. package/dist/knowledge/guard-ledger.js +219 -0
  54. package/dist/knowledge/guard-puzzle.d.ts +93 -0
  55. package/dist/knowledge/guard-puzzle.js +278 -0
  56. package/dist/knowledge/guard-risk.d.ts +60 -0
  57. package/dist/knowledge/guard-risk.js +474 -0
  58. package/dist/knowledge/guard-translation.d.ts +46 -0
  59. package/dist/knowledge/guard-translation.js +487 -0
  60. package/dist/knowledge/index.d.ts +77 -0
  61. package/dist/knowledge/index.js +79 -0
  62. package/dist/knowledge/industry-evolution.d.ts +82 -0
  63. package/dist/knowledge/industry-evolution.js +323 -0
  64. package/dist/knowledge/industry-generalizer.d.ts +17 -0
  65. package/dist/knowledge/industry-generalizer.js +381 -0
  66. package/dist/knowledge/industry-registry.d.ts +48 -0
  67. package/dist/knowledge/industry-registry.js +187 -0
  68. package/dist/knowledge/intent-metrics.d.ts +42 -0
  69. package/dist/knowledge/intent-metrics.js +566 -0
  70. package/dist/knowledge/process-model.d.ts +24 -0
  71. package/dist/knowledge/process-model.js +160 -0
  72. package/dist/knowledge/reputation-rules.d.ts +42 -0
  73. package/dist/knowledge/reputation-rules.js +99 -0
  74. package/dist/knowledge/reward-templates.d.ts +25 -0
  75. package/dist/knowledge/reward-templates.js +125 -0
  76. package/dist/knowledge/safety-rules.d.ts +36 -0
  77. package/dist/knowledge/safety-rules.js +232 -0
  78. package/dist/knowledge/tool-constraints.d.ts +30 -0
  79. package/dist/knowledge/tool-constraints.js +175 -0
  80. package/dist/knowledge/trust-metrics.d.ts +37 -0
  81. package/dist/knowledge/trust-metrics.js +138 -0
  82. package/dist/loop-engineering/diagnose.d.ts +3 -2
  83. package/dist/loop-engineering/diagnose.js +94 -0
  84. package/dist/loop-engineering/improve.d.ts +1 -1
  85. package/dist/loop-engineering/improve.js +52 -1
  86. package/dist/project/graph.d.ts +71 -0
  87. package/dist/project/graph.js +314 -0
  88. package/dist/project/index.d.ts +62 -0
  89. package/dist/project/index.js +167 -0
  90. package/dist/project/namespace.d.ts +62 -0
  91. package/dist/project/namespace.js +181 -0
  92. package/dist/project/query.d.ts +40 -0
  93. package/dist/project/query.js +110 -0
  94. package/dist/safety/confirm-gate.d.ts +17 -0
  95. package/dist/safety/confirm-gate.js +88 -0
  96. package/dist/safety/index.d.ts +3 -0
  97. package/dist/safety/index.js +3 -0
  98. package/dist/safety/preview.d.ts +2 -0
  99. package/dist/safety/preview.js +36 -0
  100. package/dist/schema/call/allocation.d.ts +39 -14
  101. package/dist/schema/call/arbitration.d.ts +187 -162
  102. package/dist/schema/call/base.d.ts +1971 -87
  103. package/dist/schema/call/base.js +135 -3
  104. package/dist/schema/call/bridge-handler.js +15 -2
  105. package/dist/schema/call/bridge.d.ts +1478 -53
  106. package/dist/schema/call/bridge.js +50 -2
  107. package/dist/schema/call/contact.d.ts +25 -0
  108. package/dist/schema/call/demand.d.ts +79 -54
  109. package/dist/schema/call/guard.d.ts +125 -50
  110. package/dist/schema/call/handler.d.ts +3 -0
  111. package/dist/schema/call/handler.js +60 -14
  112. package/dist/schema/call/machine.d.ts +988 -938
  113. package/dist/schema/call/order.d.ts +25 -0
  114. package/dist/schema/call/payment.d.ts +25 -0
  115. package/dist/schema/call/permission.d.ts +244 -219
  116. package/dist/schema/call/personal.d.ts +25 -0
  117. package/dist/schema/call/progress.d.ts +25 -0
  118. package/dist/schema/call/proof.d.ts +62 -12
  119. package/dist/schema/call/proof.js +3 -3
  120. package/dist/schema/call/repository.d.ts +101 -76
  121. package/dist/schema/call/reward.d.ts +55 -30
  122. package/dist/schema/call/semantic.d.ts +10 -2
  123. package/dist/schema/call/semantic.js +616 -11
  124. package/dist/schema/call/service.d.ts +442 -417
  125. package/dist/schema/call/treasury.d.ts +25 -0
  126. package/dist/schema/common/index.js +3 -3
  127. package/dist/schema/config/index.d.ts +18 -0
  128. package/dist/schema/config/index.js +17 -0
  129. package/dist/schema/index.d.ts +6 -0
  130. package/dist/schema/index.js +5 -0
  131. package/dist/schema/local/index.d.ts +237 -81
  132. package/dist/schema/local/index.js +42 -6
  133. package/dist/schema/messenger/index.d.ts +1018 -79
  134. package/dist/schema/messenger/index.js +26 -17
  135. package/dist/schema/operations.d.ts +3192 -1746
  136. package/dist/schema/operations.js +93 -98
  137. package/dist/schema/project/index.d.ts +21 -0
  138. package/dist/schema/project/index.js +32 -0
  139. package/dist/schema/query/index.d.ts +2762 -1856
  140. package/dist/schema/query/index.js +38 -35
  141. package/dist/schema/schema-query/index.d.ts +33 -0
  142. package/dist/schema/schema-query/index.js +36 -0
  143. package/dist/schema/schema-version.d.ts +25 -0
  144. package/dist/schema/schema-version.js +76 -0
  145. package/dist/schema/trust/index.d.ts +407 -0
  146. package/dist/schema/trust/index.js +113 -0
  147. package/dist/schemas/account_operation.output.json +25 -16
  148. package/dist/schemas/account_operation.schema.json +1 -1
  149. package/dist/schemas/bridge_operation.output.json +744 -0
  150. package/dist/schemas/bridge_operation.schema.json +82 -8
  151. package/dist/schemas/config_operation.output.json +18 -0
  152. package/dist/schemas/config_operation.schema.json +34 -0
  153. package/dist/schemas/guard-node-schema.json +82 -0
  154. package/dist/schemas/guard2file.schema.json +23 -0
  155. package/dist/schemas/index.json +19 -1
  156. package/dist/schemas/local_info_operation.output.json +23 -0
  157. package/dist/schemas/local_info_operation.schema.json +1 -1
  158. package/dist/schemas/local_mark_operation.output.json +24 -1
  159. package/dist/schemas/local_mark_operation.schema.json +4 -4
  160. package/dist/schemas/machineNode2file.schema.json +23 -0
  161. package/dist/schemas/messenger_operation.output.json +752 -0
  162. package/dist/schemas/onchain_events.output.json +718 -0
  163. package/dist/schemas/onchain_operations.output.json +627 -18
  164. package/dist/schemas/onchain_operations.schema.json +115 -39
  165. package/dist/schemas/onchain_operations_allocation.schema.json +23 -0
  166. package/dist/schemas/onchain_operations_arbitration.schema.json +23 -0
  167. package/dist/schemas/onchain_operations_contact.schema.json +23 -0
  168. package/dist/schemas/onchain_operations_demand.schema.json +23 -0
  169. package/dist/schemas/onchain_operations_gen_passport.schema.json +46 -0
  170. package/dist/schemas/onchain_operations_guard.schema.json +26 -16
  171. package/dist/schemas/onchain_operations_machine.schema.json +89 -23
  172. package/dist/schemas/onchain_operations_order.schema.json +23 -0
  173. package/dist/schemas/onchain_operations_payment.schema.json +23 -0
  174. package/dist/schemas/onchain_operations_permission.schema.json +23 -0
  175. package/dist/schemas/onchain_operations_personal.schema.json +23 -0
  176. package/dist/schemas/onchain_operations_progress.schema.json +23 -0
  177. package/dist/schemas/onchain_operations_repository.schema.json +23 -0
  178. package/dist/schemas/onchain_operations_reward.schema.json +23 -0
  179. package/dist/schemas/onchain_operations_service.schema.json +23 -0
  180. package/dist/schemas/onchain_operations_treasury.schema.json +23 -0
  181. package/dist/schemas/onchain_table_data.output.json +939 -69
  182. package/dist/schemas/onchain_table_data.schema.json +2 -2
  183. package/dist/schemas/project_operation.output.json +18 -0
  184. package/dist/schemas/project_operation.schema.json +42 -0
  185. package/dist/schemas/query_toolkit.schema.json +360 -368
  186. package/dist/schemas/schema_query.schema.json +6 -3
  187. package/dist/schemas/trust_score.output.json +327 -0
  188. package/dist/schemas/trust_score.schema.json +46 -0
  189. package/package.json +2 -2
@@ -0,0 +1,232 @@
1
+ export const DEFAULT_VALUE_WARNINGS = {
2
+ defaultAccount: 'Using default account (env.account="")',
3
+ mainnet: "Operating on mainnet — irreversible",
4
+ replaceExistName: "replaceExistName=true will unbind the existing name (breaking refs)",
5
+ defaultToken: "Using default token 0x2::wow::WOW",
6
+ };
7
+ export const DEFAULT_AMOUNT_THRESHOLD = BigInt(100_000_000_000);
8
+ export function getAmountThreshold() {
9
+ const raw = process.env.WOWOK_AMOUNT_THRESHOLD;
10
+ if (!raw)
11
+ return DEFAULT_AMOUNT_THRESHOLD;
12
+ try {
13
+ return BigInt(raw);
14
+ }
15
+ catch {
16
+ return DEFAULT_AMOUNT_THRESHOLD;
17
+ }
18
+ }
19
+ const WOW_PRECISION = 1000000000n;
20
+ export function formatAmount(value, precision = WOW_PRECISION) {
21
+ const v = typeof value === "string" ? BigInt(value) : value;
22
+ const whole = v / precision;
23
+ const frac = v % precision;
24
+ if (frac === 0n)
25
+ return `${whole.toString()}`;
26
+ const fracStr = frac.toString().padStart(Number(precision.toString().length) - 1, "0");
27
+ return `${whole.toString()}.${fracStr}`;
28
+ }
29
+ export function collectDefaultWarnings(env, data) {
30
+ const w = [];
31
+ const acc = env?.account;
32
+ if (acc === undefined || acc === "") {
33
+ w.push(DEFAULT_VALUE_WARNINGS.defaultAccount);
34
+ }
35
+ const net = env?.network;
36
+ if (net && /mainnet/i.test(String(net))) {
37
+ w.push(DEFAULT_VALUE_WARNINGS.mainnet);
38
+ }
39
+ const nn = data?.namedNew ?? data?.object;
40
+ if (nn && typeof nn === "object" && nn.replaceExistName === true) {
41
+ w.push(DEFAULT_VALUE_WARNINGS.replaceExistName);
42
+ }
43
+ return w;
44
+ }
45
+ export const CONFIRMATION_RULES = [
46
+ {
47
+ id: "irreversible_fund_or_verdict",
48
+ when: (ot, data, _env) => {
49
+ if (ot === "payment")
50
+ return true;
51
+ if (ot === "arbitration" && data?.arbitration !== undefined)
52
+ return true;
53
+ if (ot === "treasury" && /withdraw|receive/i.test(JSON.stringify(data)))
54
+ return true;
55
+ return false;
56
+ },
57
+ level: "irreversible",
58
+ preview: (ot, data, env) => ({
59
+ level: "irreversible",
60
+ operation: ot,
61
+ irreversible: true,
62
+ network: env?.network,
63
+ account: env?.account ?? "",
64
+ warnings: collectDefaultWarnings(env, data),
65
+ amount: ot === "payment" && data?.amount
66
+ ? {
67
+ value: String(data.amount.amount ?? data.amount.balance ?? ""),
68
+ token: data?.token_type ?? "0x2::wow::WOW",
69
+ human_readable: formatAmount(String(data.amount.amount ?? data.amount.balance ?? "0")),
70
+ recipient: data?.to ?? data?.recipient,
71
+ }
72
+ : undefined,
73
+ }),
74
+ bypass_on_explicit_intent: [],
75
+ },
76
+ {
77
+ id: "publish_immutable",
78
+ when: (ot, data, _env) => {
79
+ if (ot === "service" && (data?.publish === true || data?.bPublished === true))
80
+ return true;
81
+ if (ot === "machine" && data?.publish === true)
82
+ return true;
83
+ return false;
84
+ },
85
+ level: "publish",
86
+ preview: (ot, data, env) => ({
87
+ level: "publish",
88
+ operation: ot,
89
+ object: data?.object ?? data?.namedNew?.name,
90
+ network: env?.network,
91
+ account: env?.account ?? "",
92
+ immutable_after: ot === "service"
93
+ ? ["machine", "order_allocators"]
94
+ : ["nodes", "pairs", "forwards"],
95
+ warnings: collectDefaultWarnings(env, data),
96
+ }),
97
+ bypass_on_explicit_intent: ["force publish", "publish now"],
98
+ },
99
+ {
100
+ id: "amount_sensitive",
101
+ when: (ot, data, _env) => {
102
+ const amt = extractAmount(data);
103
+ if (amt === null)
104
+ return false;
105
+ if (ot === "reward" || ot === "treasury")
106
+ return true;
107
+ if (ot === "service" && data?.compensation_fund_add)
108
+ return true;
109
+ return false;
110
+ },
111
+ level: "amount",
112
+ preview: (ot, data, env) => {
113
+ const amt = extractAmount(data);
114
+ return {
115
+ level: "amount",
116
+ operation: ot,
117
+ object: data?.object ?? data?.namedNew?.name,
118
+ network: env?.network,
119
+ account: env?.account ?? "",
120
+ amount: amt
121
+ ? {
122
+ value: amt,
123
+ token: data?.token_type ?? "0x2::wow::WOW",
124
+ human_readable: formatAmount(amt),
125
+ }
126
+ : undefined,
127
+ warnings: collectDefaultWarnings(env, data),
128
+ };
129
+ },
130
+ bypass_on_explicit_intent: [],
131
+ },
132
+ {
133
+ id: "default_values",
134
+ when: (_ot, _data, env) => {
135
+ return collectDefaultWarnings(env, _data).length > 0;
136
+ },
137
+ level: "standard",
138
+ preview: (ot, data, env) => ({
139
+ level: "standard",
140
+ operation: ot,
141
+ object: data?.object ?? data?.namedNew?.name,
142
+ network: env?.network,
143
+ account: env?.account ?? "",
144
+ warnings: collectDefaultWarnings(env, data),
145
+ }),
146
+ bypass_on_explicit_intent: [
147
+ "use default account",
148
+ "default account is fine",
149
+ "用默认账户",
150
+ "用默认账户即可",
151
+ ],
152
+ },
153
+ {
154
+ id: "guard_create_immutable",
155
+ when: (ot, data, _env) => {
156
+ if (ot === "guard")
157
+ return true;
158
+ return false;
159
+ },
160
+ level: "irreversible",
161
+ preview: (ot, data, env) => {
162
+ const table = data?.table ?? [];
163
+ const root = data?.root;
164
+ const rely = data?.rely;
165
+ const rootType = typeof root === 'object' && root !== null && 'type' in root
166
+ ? root.type
167
+ : typeof root === 'object' && root !== null && 'type' in root && root.type === 'file'
168
+ ? 'file'
169
+ : 'unknown';
170
+ const immutable_fields = ['table', 'root'];
171
+ if (rely)
172
+ immutable_fields.push('rely');
173
+ return {
174
+ level: "irreversible",
175
+ operation: ot,
176
+ object: data?.namedNew?.name,
177
+ network: env?.network,
178
+ account: env?.account ?? "",
179
+ immutable_after: immutable_fields,
180
+ irreversible: true,
181
+ warnings: [
182
+ ...collectDefaultWarnings(env, data),
183
+ `Guard is CREATE-only and immutable — cannot be edited or deleted after creation`,
184
+ `Table entries: ${table.length} (max 256)`,
185
+ `Root node type: ${rootType} (must return Bool)`,
186
+ ...(rely ? [`Rely dependencies: ${rely.guards?.length ?? 0} (max 4, AND/OR logic)`] : []),
187
+ `To modify later: export via guard2file → edit → CREATE new → rebind`,
188
+ ],
189
+ };
190
+ },
191
+ bypass_on_explicit_intent: [],
192
+ },
193
+ {
194
+ id: "guard_gen_passport_test",
195
+ when: (ot, _data, _env) => {
196
+ if (ot === "gen_passport")
197
+ return true;
198
+ return false;
199
+ },
200
+ level: "standard",
201
+ preview: (ot, data, env) => ({
202
+ level: "standard",
203
+ operation: ot,
204
+ object: data?.guard,
205
+ network: env?.network,
206
+ account: env?.account ?? "",
207
+ warnings: [
208
+ ...collectDefaultWarnings(env, data),
209
+ "gen_passport will consume gas for static testing",
210
+ ],
211
+ }),
212
+ bypass_on_explicit_intent: ["test guard", "测试 guard", "gen passport", "生成 passport"],
213
+ },
214
+ ];
215
+ function extractAmount(data) {
216
+ if (!data)
217
+ return null;
218
+ const candidates = [
219
+ data?.amount?.amount,
220
+ data?.amount?.balance,
221
+ data?.balance,
222
+ data?.amount,
223
+ data?.compensation_fund_add,
224
+ data?.deposit,
225
+ ];
226
+ for (const c of candidates) {
227
+ if (c !== undefined && c !== null && c !== "")
228
+ return String(c);
229
+ }
230
+ return null;
231
+ }
232
+ export const SAFETY_RULES_VERSION = 1;
@@ -0,0 +1,30 @@
1
+ export type ConstraintSeverity = "error" | "warning";
2
+ export interface FieldConstraint {
3
+ field: string;
4
+ description: string;
5
+ severity: ConstraintSeverity;
6
+ check: (data: any) => boolean;
7
+ message: (data: any) => string;
8
+ }
9
+ export interface OperationConstraint {
10
+ operation_type: string;
11
+ constraints: FieldConstraint[];
12
+ mutuallyExclusive?: Array<{
13
+ fields: string[];
14
+ reason: string;
15
+ }>;
16
+ requireOneOf?: Array<{
17
+ fields: string[];
18
+ reason: string;
19
+ }>;
20
+ }
21
+ export declare const TOOL_CONSTRAINTS: OperationConstraint[];
22
+ export interface ConstraintViolation {
23
+ field: string;
24
+ severity: ConstraintSeverity;
25
+ message: string;
26
+ }
27
+ export declare function validateOperation(operation_type: string, data: any): ConstraintViolation[];
28
+ export declare function hasBlockingViolations(violations: ConstraintViolation[]): boolean;
29
+ export declare function getWarningViolations(violations: ConstraintViolation[]): ConstraintViolation[];
30
+ export declare const TOOL_CONSTRAINTS_VERSION = 1;
@@ -0,0 +1,175 @@
1
+ export const TOOL_CONSTRAINTS = [
2
+ {
3
+ operation_type: "service",
4
+ constraints: [
5
+ {
6
+ field: "namedNew.name",
7
+ description: "Service should have a name for easy reference",
8
+ severity: "warning",
9
+ check: (d) => !!d?.namedNew?.name || typeof d?.object === "string",
10
+ message: () => "Service without a name is hard to reference later. Consider setting namedNew.name.",
11
+ },
12
+ {
13
+ field: "price",
14
+ description: "Service price should be set before publish",
15
+ severity: "warning",
16
+ check: (d) => d?.price !== undefined || !d?.publish,
17
+ message: () => "Publishing a service without a price — customers won't know the cost.",
18
+ },
19
+ ],
20
+ requireOneOf: [
21
+ { fields: ["object", "namedNew"], reason: "Must specify either an existing object (string) or create new (namedNew)" },
22
+ ],
23
+ },
24
+ {
25
+ operation_type: "machine",
26
+ constraints: [
27
+ {
28
+ field: "node.nodes",
29
+ description: "Machine should have at least one node when published",
30
+ severity: "warning",
31
+ check: (d) => {
32
+ if (typeof d?.object === "string")
33
+ return true;
34
+ if (!d?.publish)
35
+ return true;
36
+ return Array.isArray(d?.node?.nodes) && d.node.nodes.length > 0;
37
+ },
38
+ message: () => "Publishing a Machine without nodes — a workflow template requires at least one node. Consider adding nodes before publish, or publish later after adding nodes.",
39
+ },
40
+ ],
41
+ },
42
+ {
43
+ operation_type: "payment",
44
+ constraints: [
45
+ {
46
+ field: "revenue",
47
+ description: "Payment requires at least one revenue entry",
48
+ severity: "error",
49
+ check: (d) => Array.isArray(d?.revenue) && d.revenue.length > 0,
50
+ message: () => "Payment requires a non-empty 'revenue' array (payment recipients and amounts).",
51
+ },
52
+ {
53
+ field: "revenue[0].amount",
54
+ description: "Payment revenue amount must be specified",
55
+ severity: "error",
56
+ check: (d) => Array.isArray(d?.revenue) && d.revenue.length > 0 &&
57
+ (!!d.revenue[0]?.amount?.balance || !!d.revenue[0]?.amount?.coin),
58
+ message: () => "Payment revenue[0].amount must specify either 'balance' value or 'coin' object (see CoinParamSchema).",
59
+ },
60
+ ],
61
+ },
62
+ {
63
+ operation_type: "order",
64
+ constraints: [],
65
+ },
66
+ {
67
+ operation_type: "reward",
68
+ constraints: [
69
+ {
70
+ field: "coin_add",
71
+ description: "Reward funding requires coin_add",
72
+ severity: "warning",
73
+ check: (d) => {
74
+ if (d?.claim || d?.guard_add || d?.guard_remove_expired || d?.owner_receive || d?.receive) {
75
+ return true;
76
+ }
77
+ return !!d?.coin_add?.balance || !!d?.coin_add?.coin;
78
+ },
79
+ message: () => "Reward funding requires 'coin_add' with either 'balance' value or 'coin' object (see CoinParamSchema). Other operations (claim, guard_add, etc.) don't need coin_add.",
80
+ },
81
+ ],
82
+ },
83
+ {
84
+ operation_type: "guard",
85
+ constraints: [
86
+ {
87
+ field: "root",
88
+ description: "Guard must specify root (node tree or file)",
89
+ severity: "error",
90
+ check: (d) => !!d?.root,
91
+ message: () => "Guard requires a 'root' field (type='node' for tree or type='file' to load from file).",
92
+ },
93
+ ],
94
+ },
95
+ {
96
+ operation_type: "permission",
97
+ constraints: [
98
+ {
99
+ field: "with_forbidden",
100
+ description: "Permission should have at least one rule",
101
+ severity: "warning",
102
+ check: (d) => Array.isArray(d?.with_forbidden) && d.with_forbidden.length > 0 || Array.isArray(d?.with_allowed) && d.with_allowed.length > 0,
103
+ message: () => "Permission has no rules (with_forbidden/with_allowed). An empty permission allows nothing.",
104
+ },
105
+ ],
106
+ },
107
+ {
108
+ operation_type: "demand",
109
+ constraints: [
110
+ {
111
+ field: "reward",
112
+ description: "Demand should have a reward to attract solutions",
113
+ severity: "warning",
114
+ check: (d) => !!d?.reward,
115
+ message: () => "Demand without a reward pool may not attract solution providers.",
116
+ },
117
+ ],
118
+ },
119
+ {
120
+ operation_type: "progress",
121
+ constraints: [],
122
+ },
123
+ ];
124
+ const CONSTRAINT_INDEX = new Map(TOOL_CONSTRAINTS.map((c) => [c.operation_type, c]));
125
+ export function validateOperation(operation_type, data) {
126
+ const constraint = CONSTRAINT_INDEX.get(operation_type);
127
+ if (!constraint)
128
+ return [];
129
+ const violations = [];
130
+ for (const c of constraint.constraints) {
131
+ try {
132
+ if (!c.check(data)) {
133
+ violations.push({
134
+ field: c.field,
135
+ severity: c.severity,
136
+ message: c.message(data),
137
+ });
138
+ }
139
+ }
140
+ catch {
141
+ }
142
+ }
143
+ if (constraint.requireOneOf) {
144
+ for (const req of constraint.requireOneOf) {
145
+ const hasAtLeastOne = req.fields.some((f) => data?.[f] !== undefined && data?.[f] !== null);
146
+ if (!hasAtLeastOne) {
147
+ violations.push({
148
+ field: req.fields.join("|"),
149
+ severity: "error",
150
+ message: req.reason,
151
+ });
152
+ }
153
+ }
154
+ }
155
+ if (constraint.mutuallyExclusive) {
156
+ for (const mex of constraint.mutuallyExclusive) {
157
+ const setFields = mex.fields.filter((f) => data?.[f] !== undefined && data?.[f] !== null);
158
+ if (setFields.length > 1) {
159
+ violations.push({
160
+ field: setFields.join("|"),
161
+ severity: "error",
162
+ message: `Fields are mutually exclusive: ${setFields.join(", ")}. ${mex.reason}`,
163
+ });
164
+ }
165
+ }
166
+ }
167
+ return violations;
168
+ }
169
+ export function hasBlockingViolations(violations) {
170
+ return violations.some((v) => v.severity === "error");
171
+ }
172
+ export function getWarningViolations(violations) {
173
+ return violations.filter((v) => v.severity === "warning");
174
+ }
175
+ export const TOOL_CONSTRAINTS_VERSION = 1;
@@ -0,0 +1,37 @@
1
+ export interface ServiceTrustMetrics {
2
+ arbitrationScore?: number;
3
+ arbitrationCases?: number;
4
+ reviewStats?: {
5
+ likes: number;
6
+ dislikes: number;
7
+ verifiedReviews: number;
8
+ totalReviews: number;
9
+ };
10
+ orderCount?: number;
11
+ completedRate?: number;
12
+ avgCompletionTime?: number;
13
+ compensationFundBalance?: bigint;
14
+ hasPublishedEvents?: boolean;
15
+ hasMachineBound?: boolean;
16
+ hasBuyGuard?: boolean;
17
+ }
18
+ export interface TrustDimension {
19
+ name: string;
20
+ score: number;
21
+ maxScore: number;
22
+ description: string;
23
+ humanReadable: string;
24
+ }
25
+ export interface ServiceTrustScore {
26
+ score: number;
27
+ level: "high_risk" | "caution" | "moderate" | "trusted";
28
+ breakdown: TrustDimension[];
29
+ summary: string;
30
+ warnings: string[];
31
+ }
32
+ export declare const TRUST_METRICS_VERSION = 1;
33
+ export declare function computeServiceTrustScore(metrics: ServiceTrustMetrics): ServiceTrustScore;
34
+ export declare function quickTrustCheck(metrics: ServiceTrustMetrics): {
35
+ pass: boolean;
36
+ reason: string;
37
+ };
@@ -0,0 +1,138 @@
1
+ export const TRUST_METRICS_VERSION = 1;
2
+ const TRUST_LEVELS = [
3
+ { min: 75, level: "trusted", label: "高信任" },
4
+ { min: 50, level: "moderate", label: "中等信任" },
5
+ { min: 25, level: "caution", label: "需注意" },
6
+ { min: 0, level: "high_risk", label: "高风险" },
7
+ ];
8
+ export function computeServiceTrustScore(metrics) {
9
+ const breakdown = [];
10
+ const warnings = [];
11
+ const arbScore = computeArbitrationDimension(metrics);
12
+ breakdown.push(arbScore);
13
+ if (arbScore.score < arbScore.maxScore * 0.3) {
14
+ warnings.push("仲裁信任分较低,建议检查仲裁记录");
15
+ }
16
+ const reviewScore = computeReviewDimension(metrics);
17
+ breakdown.push(reviewScore);
18
+ if (reviewScore.score < reviewScore.maxScore * 0.3 && metrics.reviewStats) {
19
+ warnings.push(`好评率较低 (${metrics.reviewStats.likes}/${metrics.reviewStats.totalReviews})`);
20
+ }
21
+ const fulfillmentScore = computeFulfillmentDimension(metrics);
22
+ breakdown.push(fulfillmentScore);
23
+ if (metrics.completedRate !== undefined && metrics.completedRate < 0.7) {
24
+ warnings.push(`完成率仅 ${Math.round(metrics.completedRate * 100)}%`);
25
+ }
26
+ const fundScore = computeFundDimension(metrics);
27
+ breakdown.push(fundScore);
28
+ if (metrics.compensationFundBalance === undefined || metrics.compensationFundBalance === 0n) {
29
+ warnings.push("无赔偿金,客户权益保障不足");
30
+ }
31
+ const transparencyScore = computeTransparencyDimension(metrics);
32
+ breakdown.push(transparencyScore);
33
+ const totalScore = breakdown.reduce((sum, d) => sum + d.score, 0);
34
+ const level = TRUST_LEVELS.find((l) => totalScore >= l.min)?.level ?? "high_risk";
35
+ const label = TRUST_LEVELS.find((l) => totalScore >= l.min)?.label ?? "高风险";
36
+ const summary = buildSummary(totalScore, label, metrics, breakdown);
37
+ return { score: totalScore, level, breakdown, summary, warnings };
38
+ }
39
+ function computeArbitrationDimension(metrics) {
40
+ const maxScore = 30;
41
+ if (metrics.arbitrationScore === undefined) {
42
+ return { name: "arbitration", score: maxScore * 0.5, maxScore, description: "仲裁信任分(无数据,默认中等)", humanReadable: "仲裁记录: 无数据" };
43
+ }
44
+ const score = Math.round((metrics.arbitrationScore / 100) * maxScore);
45
+ return {
46
+ name: "arbitration",
47
+ score,
48
+ maxScore,
49
+ description: `仲裁信任分 ${metrics.arbitrationScore}/100`,
50
+ humanReadable: `仲裁信任: ${metrics.arbitrationScore}/100${metrics.arbitrationCases !== undefined ? ` (${metrics.arbitrationCases} 案件)` : ""}`,
51
+ };
52
+ }
53
+ function computeReviewDimension(metrics) {
54
+ const maxScore = 25;
55
+ if (!metrics.reviewStats || metrics.reviewStats.totalReviews === 0) {
56
+ return { name: "reviews", score: maxScore * 0.5, maxScore, description: "评价声誉(无评价数据)", humanReadable: "评价: 无数据" };
57
+ }
58
+ const { likes, dislikes, verifiedReviews, totalReviews } = metrics.reviewStats;
59
+ const likeRate = likes / Math.max(1, totalReviews);
60
+ const verifiedBoost = Math.min(5, verifiedReviews);
61
+ const score = Math.round(likeRate * (maxScore - 5) + verifiedBoost);
62
+ return {
63
+ name: "reviews",
64
+ score: Math.min(maxScore, score),
65
+ maxScore,
66
+ description: `好评率 ${Math.round(likeRate * 100)}% (${totalReviews} 条评价, ${verifiedReviews} 条带凭证)`,
67
+ humanReadable: `好评率 ${Math.round(likeRate * 100)}% (${totalReviews} 评价)`,
68
+ };
69
+ }
70
+ function computeFulfillmentDimension(metrics) {
71
+ const maxScore = 20;
72
+ if (metrics.orderCount === undefined) {
73
+ return { name: "fulfillment", score: maxScore * 0.5, maxScore, description: "履约记录(无订单数据)", humanReadable: "履约: 无数据" };
74
+ }
75
+ let score = 0;
76
+ const orderScore = Math.min(10, Math.floor(metrics.orderCount / 5));
77
+ score += orderScore;
78
+ if (metrics.completedRate !== undefined) {
79
+ score += Math.round(metrics.completedRate * 10);
80
+ }
81
+ else {
82
+ score += 5;
83
+ }
84
+ return {
85
+ name: "fulfillment",
86
+ score: Math.min(maxScore, score),
87
+ maxScore,
88
+ description: `已完成 ${metrics.orderCount} 单, 完成率 ${metrics.completedRate !== undefined ? Math.round(metrics.completedRate * 100) + "%" : "未知"}`,
89
+ humanReadable: `履约: ${metrics.orderCount} 单${metrics.avgCompletionTime !== undefined ? `, 平均 ${metrics.avgCompletionTime}h` : ""}`,
90
+ };
91
+ }
92
+ function computeFundDimension(metrics) {
93
+ const maxScore = 15;
94
+ if (metrics.compensationFundBalance === undefined || metrics.compensationFundBalance === 0n) {
95
+ return { name: "fund_safety", score: 0, maxScore, description: "无赔偿金", humanReadable: "赔偿金: 无" };
96
+ }
97
+ const threshold = 1000000000000n;
98
+ const ratio = Number(metrics.compensationFundBalance * 100n / threshold) / 100;
99
+ const score = Math.min(maxScore, Math.round(ratio * maxScore));
100
+ return {
101
+ name: "fund_safety",
102
+ score,
103
+ maxScore,
104
+ description: `赔偿金 ${metrics.compensationFundBalance} 最小单位`,
105
+ humanReadable: `赔偿金: 充足`,
106
+ };
107
+ }
108
+ function computeTransparencyDimension(metrics) {
109
+ const maxScore = 10;
110
+ let score = 0;
111
+ if (metrics.hasPublishedEvents)
112
+ score += 4;
113
+ if (metrics.hasMachineBound)
114
+ score += 3;
115
+ if (metrics.hasBuyGuard)
116
+ score += 3;
117
+ return {
118
+ name: "transparency",
119
+ score: Math.min(maxScore, score),
120
+ maxScore,
121
+ description: `链上事件 ${metrics.hasPublishedEvents ? "✓" : "✗"}, Machine ${metrics.hasMachineBound ? "✓" : "✗"}, Guard ${metrics.hasBuyGuard ? "✓" : "✗"}`,
122
+ humanReadable: `透明度: ${["事件", "Machine", "Guard"].filter((_, i) => [metrics.hasPublishedEvents, metrics.hasMachineBound, metrics.hasBuyGuard][i]).join("+") || "无"}`,
123
+ };
124
+ }
125
+ function buildSummary(score, label, metrics, breakdown) {
126
+ const parts = [`信任分 ${score}/100 (${label})`];
127
+ for (const d of breakdown) {
128
+ parts.push(`${d.humanReadable}`);
129
+ }
130
+ return parts.join("; ");
131
+ }
132
+ export function quickTrustCheck(metrics) {
133
+ const result = computeServiceTrustScore(metrics);
134
+ if (result.score < 25) {
135
+ return { pass: false, reason: `信任分 ${result.score}/100,高风险: ${result.warnings.join("; ")}` };
136
+ }
137
+ return { pass: true, reason: `信任分 ${result.score}/100 (${result.level})` };
138
+ }
@@ -1,5 +1,5 @@
1
1
  import type { AggregatedStats } from "./aggregate.js";
2
- export type DiagnosisType = "rule_gap" | "description_quality" | "skill_need" | "recovery_ineffectiveness" | "latency_anomaly";
2
+ export type DiagnosisType = "rule_gap" | "description_quality" | "skill_need" | "recovery_ineffectiveness" | "latency_anomaly" | "industry_health_anomaly";
3
3
  export type DiagnosisSeverity = "P0" | "P1" | "P2" | "P3";
4
4
  export interface Diagnosis {
5
5
  diagnosis_id: string;
@@ -9,7 +9,7 @@ export interface Diagnosis {
9
9
  description: string;
10
10
  evidence: Record<string, unknown>;
11
11
  target: string;
12
- proposed_improvement_type: "rule_addition" | "description_rewrite" | "skill_creation" | "recovery_priority_adjustment" | "investigation";
12
+ proposed_improvement_type: "rule_addition" | "description_rewrite" | "skill_creation" | "recovery_priority_adjustment" | "investigation" | "industry_update_application";
13
13
  }
14
14
  export interface DiagnosisReport {
15
15
  report_id: string;
@@ -18,4 +18,5 @@ export interface DiagnosisReport {
18
18
  diagnoses: Diagnosis[];
19
19
  summary: string;
20
20
  }
21
+ export declare function diagnoseIndustryHealth(industries?: string[]): Diagnosis[];
21
22
  export declare function diagnose(stats: AggregatedStats): DiagnosisReport;