@wowok/agent-mcp 2.3.13 → 2.3.16

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 (194) 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/industry-risks.d.ts +36 -0
  6. package/dist/customer/industry-risks.js +424 -0
  7. package/dist/customer/info-puzzle.d.ts +102 -0
  8. package/dist/customer/info-puzzle.js +312 -0
  9. package/dist/customer/order-monitor.d.ts +75 -0
  10. package/dist/customer/order-monitor.js +327 -0
  11. package/dist/customer/order-strategy.d.ts +36 -0
  12. package/dist/customer/order-strategy.js +373 -0
  13. package/dist/customer/post-purchase.d.ts +42 -0
  14. package/dist/customer/post-purchase.js +350 -0
  15. package/dist/customer/reminder-system.d.ts +42 -0
  16. package/dist/customer/reminder-system.js +295 -0
  17. package/dist/customer/risk-assessment.d.ts +8 -0
  18. package/dist/customer/risk-assessment.js +337 -0
  19. package/dist/customer/types.d.ts +193 -0
  20. package/dist/customer/types.js +13 -0
  21. package/dist/customer/user-preferences.d.ts +67 -0
  22. package/dist/customer/user-preferences.js +451 -0
  23. package/dist/experience/experience-reuse.d.ts +10 -0
  24. package/dist/experience/experience-reuse.js +103 -0
  25. package/dist/experience/index.d.ts +6 -0
  26. package/dist/experience/index.js +5 -0
  27. package/dist/experience/intent-distill.d.ts +3 -0
  28. package/dist/experience/intent-distill.js +83 -0
  29. package/dist/experience/realtime-feedback.d.ts +5 -0
  30. package/dist/experience/realtime-feedback.js +77 -0
  31. package/dist/experience/types.d.ts +50 -0
  32. package/dist/experience/types.js +1 -0
  33. package/dist/experience/user-profile.d.ts +25 -0
  34. package/dist/experience/user-profile.js +171 -0
  35. package/dist/harness/checkpoint.d.ts +8 -0
  36. package/dist/harness/checkpoint.js +129 -0
  37. package/dist/harness/index.d.ts +33 -0
  38. package/dist/harness/index.js +75 -0
  39. package/dist/harness/plan.d.ts +18 -0
  40. package/dist/harness/plan.js +252 -0
  41. package/dist/harness/recover.d.ts +17 -0
  42. package/dist/harness/recover.js +139 -0
  43. package/dist/harness/types.d.ts +137 -0
  44. package/dist/harness/types.js +1 -0
  45. package/dist/harness/verify.d.ts +42 -0
  46. package/dist/harness/verify.js +237 -0
  47. package/dist/index.js +667 -201
  48. package/dist/knowledge/acquisition-flywheel.d.ts +50 -0
  49. package/dist/knowledge/acquisition-flywheel.js +183 -0
  50. package/dist/knowledge/arbitration-trust.d.ts +24 -0
  51. package/dist/knowledge/arbitration-trust.js +117 -0
  52. package/dist/knowledge/audit-rules.d.ts +28 -0
  53. package/dist/knowledge/audit-rules.js +141 -0
  54. package/dist/knowledge/demand-matching.d.ts +29 -0
  55. package/dist/knowledge/demand-matching.js +132 -0
  56. package/dist/knowledge/dynamic-pricing.d.ts +31 -0
  57. package/dist/knowledge/dynamic-pricing.js +87 -0
  58. package/dist/knowledge/flywheel-loop.d.ts +87 -0
  59. package/dist/knowledge/flywheel-loop.js +378 -0
  60. package/dist/knowledge/glossary.d.ts +18 -0
  61. package/dist/knowledge/glossary.js +209 -0
  62. package/dist/knowledge/index.d.ts +64 -0
  63. package/dist/knowledge/index.js +66 -0
  64. package/dist/knowledge/industry-evolution.d.ts +82 -0
  65. package/dist/knowledge/industry-evolution.js +323 -0
  66. package/dist/knowledge/industry-generalizer.d.ts +17 -0
  67. package/dist/knowledge/industry-generalizer.js +381 -0
  68. package/dist/knowledge/industry-registry.d.ts +49 -0
  69. package/dist/knowledge/industry-registry.js +167 -0
  70. package/dist/knowledge/intent-metrics.d.ts +42 -0
  71. package/dist/knowledge/intent-metrics.js +566 -0
  72. package/dist/knowledge/process-model.d.ts +24 -0
  73. package/dist/knowledge/process-model.js +160 -0
  74. package/dist/knowledge/reputation-rules.d.ts +42 -0
  75. package/dist/knowledge/reputation-rules.js +99 -0
  76. package/dist/knowledge/reward-templates.d.ts +25 -0
  77. package/dist/knowledge/reward-templates.js +125 -0
  78. package/dist/knowledge/safety-rules.d.ts +36 -0
  79. package/dist/knowledge/safety-rules.js +171 -0
  80. package/dist/knowledge/tool-constraints.d.ts +30 -0
  81. package/dist/knowledge/tool-constraints.js +185 -0
  82. package/dist/knowledge/trust-metrics.d.ts +37 -0
  83. package/dist/knowledge/trust-metrics.js +138 -0
  84. package/dist/loop-engineering/aggregate.d.ts +50 -0
  85. package/dist/loop-engineering/aggregate.js +132 -0
  86. package/dist/loop-engineering/diagnose.d.ts +22 -0
  87. package/dist/loop-engineering/diagnose.js +273 -0
  88. package/dist/loop-engineering/improve.d.ts +26 -0
  89. package/dist/loop-engineering/improve.js +229 -0
  90. package/dist/loop-engineering/index.d.ts +4 -0
  91. package/dist/loop-engineering/index.js +4 -0
  92. package/dist/loop-engineering/pipeline.d.ts +17 -0
  93. package/dist/loop-engineering/pipeline.js +56 -0
  94. package/dist/mode-market/index.d.ts +3 -0
  95. package/dist/mode-market/index.js +3 -0
  96. package/dist/mode-market/registry.d.ts +53 -0
  97. package/dist/mode-market/registry.js +124 -0
  98. package/dist/mode-market/review.d.ts +27 -0
  99. package/dist/mode-market/review.js +214 -0
  100. package/dist/mode-market/submission.d.ts +25 -0
  101. package/dist/mode-market/submission.js +85 -0
  102. package/dist/project/graph.d.ts +71 -0
  103. package/dist/project/graph.js +314 -0
  104. package/dist/project/index.d.ts +62 -0
  105. package/dist/project/index.js +167 -0
  106. package/dist/project/namespace.d.ts +62 -0
  107. package/dist/project/namespace.js +181 -0
  108. package/dist/project/query.d.ts +40 -0
  109. package/dist/project/query.js +110 -0
  110. package/dist/safety/confirm-gate.d.ts +15 -0
  111. package/dist/safety/confirm-gate.js +44 -0
  112. package/dist/safety/index.d.ts +3 -0
  113. package/dist/safety/index.js +3 -0
  114. package/dist/safety/preview.d.ts +2 -0
  115. package/dist/safety/preview.js +36 -0
  116. package/dist/schema/call/allocation.d.ts +55 -40
  117. package/dist/schema/call/arbitration.d.ts +201 -186
  118. package/dist/schema/call/base.d.ts +2104 -24
  119. package/dist/schema/call/base.js +168 -22
  120. package/dist/schema/call/bridge-handler.js +36 -18
  121. package/dist/schema/call/bridge.d.ts +777 -120
  122. package/dist/schema/call/bridge.js +13 -2
  123. package/dist/schema/call/contact.d.ts +15 -0
  124. package/dist/schema/call/demand.d.ts +69 -54
  125. package/dist/schema/call/guard.d.ts +125 -80
  126. package/dist/schema/call/handler.d.ts +5 -1
  127. package/dist/schema/call/handler.js +108 -3
  128. package/dist/schema/call/index.d.ts +1 -0
  129. package/dist/schema/call/index.js +1 -0
  130. package/dist/schema/call/machine.d.ts +830 -800
  131. package/dist/schema/call/order.d.ts +27 -12
  132. package/dist/schema/call/payment.d.ts +15 -0
  133. package/dist/schema/call/permission.d.ts +15 -0
  134. package/dist/schema/call/personal.d.ts +15 -0
  135. package/dist/schema/call/progress.d.ts +21 -6
  136. package/dist/schema/call/proof.d.ts +42 -12
  137. package/dist/schema/call/proof.js +3 -3
  138. package/dist/schema/call/repository.d.ts +91 -76
  139. package/dist/schema/call/reward.d.ts +51 -36
  140. package/dist/schema/call/semantic.d.ts +24 -0
  141. package/dist/schema/call/semantic.js +981 -0
  142. package/dist/schema/call/service.d.ts +444 -429
  143. package/dist/schema/call/treasury.d.ts +219 -204
  144. package/dist/schema/common/index.js +3 -3
  145. package/dist/schema/local/index.d.ts +341 -74
  146. package/dist/schema/local/index.js +44 -7
  147. package/dist/schema/messenger/index.d.ts +1034 -92
  148. package/dist/schema/messenger/index.js +18 -0
  149. package/dist/schema/operations.d.ts +2634 -1817
  150. package/dist/schema/operations.js +16 -5
  151. package/dist/schema/query/index.d.ts +2293 -2289
  152. package/dist/schema/query/index.js +34 -28
  153. package/dist/schemas/account_operation.output.json +28 -16
  154. package/dist/schemas/account_operation.schema.json +2 -2
  155. package/dist/schemas/bridge_operation.output.json +520 -0
  156. package/dist/schemas/bridge_operation.schema.json +15 -0
  157. package/dist/schemas/guard2file.schema.json +15 -0
  158. package/dist/schemas/index.json +1 -1
  159. package/dist/schemas/local_info_operation.output.json +26 -0
  160. package/dist/schemas/local_info_operation.schema.json +1 -1
  161. package/dist/schemas/local_mark_operation.output.json +27 -1
  162. package/dist/schemas/local_mark_operation.schema.json +4 -4
  163. package/dist/schemas/machineNode2file.schema.json +15 -0
  164. package/dist/schemas/messenger_operation.output.json +549 -0
  165. package/dist/schemas/messenger_operation.schema.json +21 -0
  166. package/dist/schemas/onchain_events.output.json +3 -0
  167. package/dist/schemas/onchain_operations.output.json +814 -37
  168. package/dist/schemas/onchain_operations.schema.json +117 -40
  169. package/dist/schemas/onchain_operations_allocation.schema.json +26 -9
  170. package/dist/schemas/onchain_operations_arbitration.schema.json +26 -9
  171. package/dist/schemas/onchain_operations_contact.schema.json +26 -9
  172. package/dist/schemas/onchain_operations_demand.schema.json +26 -9
  173. package/dist/schemas/onchain_operations_gen_passport.schema.json +51 -17
  174. package/dist/schemas/onchain_operations_guard.schema.json +26 -9
  175. package/dist/schemas/onchain_operations_machine.schema.json +92 -32
  176. package/dist/schemas/onchain_operations_order.schema.json +26 -9
  177. package/dist/schemas/onchain_operations_payment.schema.json +26 -9
  178. package/dist/schemas/onchain_operations_permission.schema.json +26 -9
  179. package/dist/schemas/onchain_operations_personal.schema.json +26 -9
  180. package/dist/schemas/onchain_operations_progress.schema.json +26 -9
  181. package/dist/schemas/onchain_operations_repository.schema.json +26 -9
  182. package/dist/schemas/onchain_operations_reward.schema.json +26 -9
  183. package/dist/schemas/onchain_operations_service.schema.json +26 -9
  184. package/dist/schemas/onchain_operations_treasury.schema.json +26 -9
  185. package/dist/schemas/onchain_table_data.output.json +224 -69
  186. package/dist/schemas/onchain_table_data.schema.json +2 -2
  187. package/dist/schemas/query_toolkit.schema.json +5 -1
  188. package/dist/telemetry/index.d.ts +19 -0
  189. package/dist/telemetry/index.js +112 -0
  190. package/dist/telemetry/redact.d.ts +2 -0
  191. package/dist/telemetry/redact.js +23 -0
  192. package/dist/telemetry/storage.d.ts +8 -0
  193. package/dist/telemetry/storage.js +80 -0
  194. package/package.json +6 -3
@@ -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,185 @@
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 must have at least one node",
30
+ severity: "error",
31
+ check: (d) => Array.isArray(d?.node?.nodes) && d.node.nodes.length > 0,
32
+ message: () => "Machine has no nodes. A workflow template requires at least one node.",
33
+ },
34
+ ],
35
+ },
36
+ {
37
+ operation_type: "payment",
38
+ constraints: [
39
+ {
40
+ field: "revenue",
41
+ description: "Payment requires at least one revenue entry",
42
+ severity: "error",
43
+ check: (d) => Array.isArray(d?.revenue) && d.revenue.length > 0,
44
+ message: () => "Payment requires a non-empty 'revenue' array (payment recipients and amounts).",
45
+ },
46
+ {
47
+ field: "revenue[0].amount",
48
+ description: "Payment revenue amount must be specified",
49
+ severity: "error",
50
+ check: (d) => Array.isArray(d?.revenue) && d.revenue.length > 0 &&
51
+ (!!d.revenue[0]?.amount?.balance || !!d.revenue[0]?.amount?.coin),
52
+ message: () => "Payment revenue[0].amount must specify either 'balance' value or 'coin' object (see CoinParamSchema).",
53
+ },
54
+ ],
55
+ },
56
+ {
57
+ operation_type: "order",
58
+ constraints: [
59
+ {
60
+ field: "service",
61
+ description: "Order must reference a service",
62
+ severity: "error",
63
+ check: (d) => !!d?.service,
64
+ message: () => "Order requires a 'service' field pointing to the service being ordered.",
65
+ },
66
+ ],
67
+ },
68
+ {
69
+ operation_type: "reward",
70
+ constraints: [
71
+ {
72
+ field: "coin_add",
73
+ description: "Reward funding requires coin_add",
74
+ severity: "warning",
75
+ check: (d) => {
76
+ if (d?.claim || d?.guard_add || d?.guard_remove_expired || d?.owner_receive || d?.receive) {
77
+ return true;
78
+ }
79
+ return !!d?.coin_add?.balance || !!d?.coin_add?.coin;
80
+ },
81
+ 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.",
82
+ },
83
+ ],
84
+ },
85
+ {
86
+ operation_type: "guard",
87
+ constraints: [
88
+ {
89
+ field: "root",
90
+ description: "Guard must specify root (node tree or file)",
91
+ severity: "error",
92
+ check: (d) => !!d?.root,
93
+ message: () => "Guard requires a 'root' field (type='node' for tree or type='file' to load from file).",
94
+ },
95
+ ],
96
+ },
97
+ {
98
+ operation_type: "permission",
99
+ constraints: [
100
+ {
101
+ field: "with_forbidden",
102
+ description: "Permission should have at least one rule",
103
+ severity: "warning",
104
+ check: (d) => Array.isArray(d?.with_forbidden) && d.with_forbidden.length > 0 || Array.isArray(d?.with_allowed) && d.with_allowed.length > 0,
105
+ message: () => "Permission has no rules (with_forbidden/with_allowed). An empty permission allows nothing.",
106
+ },
107
+ ],
108
+ },
109
+ {
110
+ operation_type: "demand",
111
+ constraints: [
112
+ {
113
+ field: "reward",
114
+ description: "Demand should have a reward to attract solutions",
115
+ severity: "warning",
116
+ check: (d) => !!d?.reward,
117
+ message: () => "Demand without a reward pool may not attract solution providers.",
118
+ },
119
+ ],
120
+ },
121
+ {
122
+ operation_type: "progress",
123
+ constraints: [
124
+ {
125
+ field: "parent",
126
+ description: "Progress must reference a parent machine",
127
+ severity: "error",
128
+ check: (d) => !!d?.parent,
129
+ message: () => "Progress requires a 'parent' field pointing to the Machine.",
130
+ },
131
+ ],
132
+ },
133
+ ];
134
+ const CONSTRAINT_INDEX = new Map(TOOL_CONSTRAINTS.map((c) => [c.operation_type, c]));
135
+ export function validateOperation(operation_type, data) {
136
+ const constraint = CONSTRAINT_INDEX.get(operation_type);
137
+ if (!constraint)
138
+ return [];
139
+ const violations = [];
140
+ for (const c of constraint.constraints) {
141
+ try {
142
+ if (!c.check(data)) {
143
+ violations.push({
144
+ field: c.field,
145
+ severity: c.severity,
146
+ message: c.message(data),
147
+ });
148
+ }
149
+ }
150
+ catch {
151
+ }
152
+ }
153
+ if (constraint.requireOneOf) {
154
+ for (const req of constraint.requireOneOf) {
155
+ const hasAtLeastOne = req.fields.some((f) => data?.[f] !== undefined && data?.[f] !== null);
156
+ if (!hasAtLeastOne) {
157
+ violations.push({
158
+ field: req.fields.join("|"),
159
+ severity: "error",
160
+ message: req.reason,
161
+ });
162
+ }
163
+ }
164
+ }
165
+ if (constraint.mutuallyExclusive) {
166
+ for (const mex of constraint.mutuallyExclusive) {
167
+ const setFields = mex.fields.filter((f) => data?.[f] !== undefined && data?.[f] !== null);
168
+ if (setFields.length > 1) {
169
+ violations.push({
170
+ field: setFields.join("|"),
171
+ severity: "error",
172
+ message: `Fields are mutually exclusive: ${setFields.join(", ")}. ${mex.reason}`,
173
+ });
174
+ }
175
+ }
176
+ }
177
+ return violations;
178
+ }
179
+ export function hasBlockingViolations(violations) {
180
+ return violations.some((v) => v.severity === "error");
181
+ }
182
+ export function getWarningViolations(violations) {
183
+ return violations.filter((v) => v.severity === "warning");
184
+ }
185
+ 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
+ }
@@ -0,0 +1,50 @@
1
+ import type { TelemetryEvent } from "../telemetry/index.js";
2
+ export interface ToolStats {
3
+ tool_name: string;
4
+ total_calls: number;
5
+ success_count: number;
6
+ failed_count: number;
7
+ pending_input_count: number;
8
+ success_rate: number;
9
+ avg_duration_ms: number;
10
+ p50_duration_ms: number;
11
+ p95_duration_ms: number;
12
+ semantic_hit_rate: number;
13
+ error_distribution: Record<string, number>;
14
+ top_error_messages: Array<{
15
+ message: string;
16
+ count: number;
17
+ }>;
18
+ }
19
+ export interface OperationStats {
20
+ operation_type: string;
21
+ total_calls: number;
22
+ success_rate: number;
23
+ semantic_hit_rate: number;
24
+ error_distribution: Record<string, number>;
25
+ }
26
+ export interface AggregatedStats {
27
+ aggregation_date: string;
28
+ total_events: number;
29
+ date_range: {
30
+ earliest: string;
31
+ latest: string;
32
+ };
33
+ per_tool: ToolStats[];
34
+ per_operation: OperationStats[];
35
+ overall: {
36
+ total_calls: number;
37
+ success_count: number;
38
+ failed_count: number;
39
+ success_rate: number;
40
+ semantic_hit_rate: number;
41
+ unknown_error_count: number;
42
+ unknown_error_rate: number;
43
+ avg_duration_ms: number;
44
+ };
45
+ error_code_distribution: Record<string, number>;
46
+ intent_distribution: Record<string, number>;
47
+ }
48
+ export declare function aggregateByTool(events: TelemetryEvent[]): ToolStats[];
49
+ export declare function aggregateByOperation(events: TelemetryEvent[]): OperationStats[];
50
+ export declare function aggregate(events: TelemetryEvent[]): AggregatedStats;
@@ -0,0 +1,132 @@
1
+ function percentile(sortedValues, p) {
2
+ if (sortedValues.length === 0)
3
+ return 0;
4
+ const idx = Math.ceil((p / 100) * sortedValues.length) - 1;
5
+ return sortedValues[Math.max(0, idx)];
6
+ }
7
+ function topMessages(messages, limit = 5) {
8
+ const counts = new Map();
9
+ for (const msg of messages) {
10
+ if (!msg)
11
+ continue;
12
+ counts.set(msg, (counts.get(msg) || 0) + 1);
13
+ }
14
+ return Array.from(counts.entries())
15
+ .map(([message, count]) => ({ message, count }))
16
+ .sort((a, b) => b.count - a.count)
17
+ .slice(0, limit);
18
+ }
19
+ export function aggregateByTool(events) {
20
+ const groups = new Map();
21
+ for (const e of events) {
22
+ const key = e.tool_name || "unknown";
23
+ if (!groups.has(key))
24
+ groups.set(key, []);
25
+ groups.get(key).push(e);
26
+ }
27
+ const results = [];
28
+ for (const [tool_name, group] of groups) {
29
+ const total = group.length;
30
+ const success = group.filter((e) => e.status === "success").length;
31
+ const failed = group.filter((e) => e.status === "failed").length;
32
+ const pending = group.filter((e) => e.status === "pending_input").length;
33
+ const semanticHits = group.filter((e) => e.semantic_hit).length;
34
+ const durations = group.map((e) => e.duration_ms).sort((a, b) => a - b);
35
+ const errorDist = {};
36
+ const errorMsgs = [];
37
+ for (const e of group) {
38
+ if (e.error_code) {
39
+ errorDist[e.error_code] = (errorDist[e.error_code] || 0) + 1;
40
+ }
41
+ if (e.error_message)
42
+ errorMsgs.push(e.error_message);
43
+ }
44
+ results.push({
45
+ tool_name,
46
+ total_calls: total,
47
+ success_count: success,
48
+ failed_count: failed,
49
+ pending_input_count: pending,
50
+ success_rate: total > 0 ? success / total : 0,
51
+ avg_duration_ms: durations.length > 0 ? durations.reduce((a, b) => a + b, 0) / durations.length : 0,
52
+ p50_duration_ms: percentile(durations, 50),
53
+ p95_duration_ms: percentile(durations, 95),
54
+ semantic_hit_rate: total > 0 ? semanticHits / total : 0,
55
+ error_distribution: errorDist,
56
+ top_error_messages: topMessages(errorMsgs),
57
+ });
58
+ }
59
+ return results.sort((a, b) => b.total_calls - a.total_calls);
60
+ }
61
+ export function aggregateByOperation(events) {
62
+ const groups = new Map();
63
+ for (const e of events) {
64
+ const key = e.operation_type || "unknown";
65
+ if (!groups.has(key))
66
+ groups.set(key, []);
67
+ groups.get(key).push(e);
68
+ }
69
+ const results = [];
70
+ for (const [operation_type, group] of groups) {
71
+ const total = group.length;
72
+ const success = group.filter((e) => e.status === "success").length;
73
+ const semanticHits = group.filter((e) => e.semantic_hit).length;
74
+ const errorDist = {};
75
+ for (const e of group) {
76
+ if (e.error_code) {
77
+ errorDist[e.error_code] = (errorDist[e.error_code] || 0) + 1;
78
+ }
79
+ }
80
+ results.push({
81
+ operation_type,
82
+ total_calls: total,
83
+ success_rate: total > 0 ? success / total : 0,
84
+ semantic_hit_rate: total > 0 ? semanticHits / total : 0,
85
+ error_distribution: errorDist,
86
+ });
87
+ }
88
+ return results.sort((a, b) => b.total_calls - a.total_calls);
89
+ }
90
+ export function aggregate(events) {
91
+ const total = events.length;
92
+ const success = events.filter((e) => e.status === "success").length;
93
+ const semanticHits = events.filter((e) => e.semantic_hit).length;
94
+ const unknownErrors = events.filter((e) => e.error_code === "unknown").length;
95
+ const durations = events.map((e) => e.duration_ms);
96
+ const errorDist = {};
97
+ const intentDist = {};
98
+ for (const e of events) {
99
+ if (e.error_code) {
100
+ errorDist[e.error_code] = (errorDist[e.error_code] || 0) + 1;
101
+ }
102
+ if (e.intent) {
103
+ intentDist[e.intent] = (intentDist[e.intent] || 0) + 1;
104
+ }
105
+ }
106
+ const timestamps = events
107
+ .map((e) => e.timestamp)
108
+ .filter(Boolean)
109
+ .sort();
110
+ return {
111
+ aggregation_date: new Date().toISOString(),
112
+ total_events: total,
113
+ date_range: {
114
+ earliest: timestamps[0] || "",
115
+ latest: timestamps[timestamps.length - 1] || "",
116
+ },
117
+ per_tool: aggregateByTool(events),
118
+ per_operation: aggregateByOperation(events),
119
+ overall: {
120
+ total_calls: total,
121
+ success_count: success,
122
+ failed_count: events.filter((e) => e.status === "failed").length,
123
+ success_rate: total > 0 ? success / total : 0,
124
+ semantic_hit_rate: total > 0 ? semanticHits / total : 0,
125
+ unknown_error_count: unknownErrors,
126
+ unknown_error_rate: total > 0 ? unknownErrors / total : 0,
127
+ avg_duration_ms: durations.length > 0 ? durations.reduce((a, b) => a + b, 0) / durations.length : 0,
128
+ },
129
+ error_code_distribution: errorDist,
130
+ intent_distribution: intentDist,
131
+ };
132
+ }
@@ -0,0 +1,22 @@
1
+ import type { AggregatedStats } from "./aggregate.js";
2
+ export type DiagnosisType = "rule_gap" | "description_quality" | "skill_need" | "recovery_ineffectiveness" | "latency_anomaly" | "industry_health_anomaly";
3
+ export type DiagnosisSeverity = "P0" | "P1" | "P2" | "P3";
4
+ export interface Diagnosis {
5
+ diagnosis_id: string;
6
+ type: DiagnosisType;
7
+ severity: DiagnosisSeverity;
8
+ title: string;
9
+ description: string;
10
+ evidence: Record<string, unknown>;
11
+ target: string;
12
+ proposed_improvement_type: "rule_addition" | "description_rewrite" | "skill_creation" | "recovery_priority_adjustment" | "investigation" | "industry_update_application";
13
+ }
14
+ export interface DiagnosisReport {
15
+ report_id: string;
16
+ diagnosis_date: string;
17
+ total_diagnoses: number;
18
+ diagnoses: Diagnosis[];
19
+ summary: string;
20
+ }
21
+ export declare function diagnoseIndustryHealth(industries?: string[]): Diagnosis[];
22
+ export declare function diagnose(stats: AggregatedStats): DiagnosisReport;