@wowok/agent-mcp 3.2.1 → 3.2.3

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 (176) hide show
  1. package/dist/chain-semantics/field-capability.d.ts +11 -0
  2. package/dist/chain-semantics/field-capability.js +1 -0
  3. package/dist/chain-semantics/freeze-map.d.ts +11 -0
  4. package/dist/chain-semantics/freeze-map.js +1 -0
  5. package/dist/chain-semantics/fund-flow.d.ts +10 -0
  6. package/dist/chain-semantics/fund-flow.js +1 -0
  7. package/dist/chain-semantics/guard-verbs.d.ts +22 -0
  8. package/dist/chain-semantics/guard-verbs.js +1 -0
  9. package/dist/chain-semantics/index.d.ts +10 -0
  10. package/dist/chain-semantics/index.js +1 -0
  11. package/dist/chain-semantics/object-graph.d.ts +18 -0
  12. package/dist/chain-semantics/object-graph.js +1 -0
  13. package/dist/communication/wts-attestation.d.ts +34 -0
  14. package/dist/communication/wts-attestation.js +1 -0
  15. package/dist/composition/audit.d.ts +10 -0
  16. package/dist/composition/audit.js +1 -0
  17. package/dist/composition/compile.d.ts +38 -0
  18. package/dist/composition/compile.js +1 -0
  19. package/dist/composition/materialize.d.ts +64 -0
  20. package/dist/composition/materialize.js +1 -0
  21. package/dist/composition/plan.d.ts +92 -0
  22. package/dist/composition/plan.js +1 -0
  23. package/dist/composition/reflux.d.ts +28 -0
  24. package/dist/composition/reflux.js +1 -0
  25. package/dist/config/judgment.d.ts +25 -0
  26. package/dist/config/rule-engine.d.ts +10 -0
  27. package/dist/config/rule-engine.js +1 -1
  28. package/dist/evaluation/builtins/graph-service.spec.js +1 -1
  29. package/dist/evaluation/engine.js +1 -1
  30. package/dist/experience/realtime-feedback.js +1 -1
  31. package/dist/extensions/business-modules.js +1 -1
  32. package/dist/extensions/industry-pack.js +1 -1
  33. package/dist/extensions/modes.js +1 -1
  34. package/dist/graph/onchain/expand.js +1 -1
  35. package/dist/graph/onchain/exposure.js +1 -1
  36. package/dist/graph/onchain/facts.js +1 -1
  37. package/dist/keeper/detectors.d.ts +7 -0
  38. package/dist/keeper/detectors.js +1 -1
  39. package/dist/keeper/types.d.ts +1 -1
  40. package/dist/keeper/types.js +1 -1
  41. package/dist/knowledge/allocation-ledger.js +1 -1
  42. package/dist/knowledge/allocation-puzzle.js +1 -1
  43. package/dist/knowledge/allocation-risk.d.ts +2 -1
  44. package/dist/knowledge/allocation-risk.js +1 -1
  45. package/dist/knowledge/allocation-templates.js +1 -1
  46. package/dist/knowledge/arb-fund-facts.d.ts +31 -0
  47. package/dist/knowledge/arb-fund-facts.js +1 -0
  48. package/dist/knowledge/audit-rules.js +1 -1
  49. package/dist/knowledge/baselines/rules/allocation.json +75 -16
  50. package/dist/knowledge/baselines/rules/guard.json +27 -8
  51. package/dist/knowledge/baselines/rules/plan.json +161 -0
  52. package/dist/knowledge/baselines/semantic-facts.d.ts +12 -0
  53. package/dist/knowledge/baselines/semantic-facts.js +1 -0
  54. package/dist/knowledge/builtin-templates.d.ts +3 -1
  55. package/dist/knowledge/builtin-templates.js +1 -1
  56. package/dist/knowledge/entity-recipient-guard.d.ts +21 -0
  57. package/dist/knowledge/entity-recipient-guard.js +1 -0
  58. package/dist/knowledge/getting-started.js +1 -1
  59. package/dist/knowledge/guard-design-patterns.js +1 -1
  60. package/dist/knowledge/guard-ledger.js +1 -1
  61. package/dist/knowledge/guard-risk.js +1 -1
  62. package/dist/knowledge/guard-templates.js +1 -1
  63. package/dist/knowledge/index.js +1 -1
  64. package/dist/knowledge/industry-registry.js +1 -1
  65. package/dist/knowledge/jsonrpc-enum.js +1 -1
  66. package/dist/knowledge/machine-topology.d.ts +34 -0
  67. package/dist/knowledge/machine-topology.js +1 -1
  68. package/dist/knowledge/onchain-constants.d.ts +2 -2
  69. package/dist/knowledge/onchain-constants.js +1 -1
  70. package/dist/knowledge/scenario-modes.d.ts +13 -0
  71. package/dist/knowledge/scenario-modes.js +1 -1
  72. package/dist/knowledge/service-allocation-semantics.js +1 -1
  73. package/dist/knowledge/service-ledger.js +1 -1
  74. package/dist/knowledge/service-templates.js +1 -1
  75. package/dist/knowledge/strategy-manuals.js +1 -1
  76. package/dist/knowledge/template-loader.d.ts +37 -1
  77. package/dist/knowledge/template-loader.js +1 -1
  78. package/dist/knowledge/template-registry.js +1 -1
  79. package/dist/knowledge/template-scanner.js +1 -1
  80. package/dist/knowledge/tool-constraints.js +1 -1
  81. package/dist/knowledge/tools-reference.js +1 -1
  82. package/dist/knowledge/workflow-guidance.d.ts +4 -0
  83. package/dist/knowledge/workflow-guidance.js +1 -1
  84. package/dist/monitor/MonitorLoop.js +1 -1
  85. package/dist/participation/radar-core.d.ts +6 -0
  86. package/dist/participation/radar-core.js +1 -1
  87. package/dist/playbooks/service-build/business-puzzle.js +1 -1
  88. package/dist/playbooks/service-build/index.d.ts +1 -0
  89. package/dist/playbooks/service-build/intent-analyzer.d.ts +1 -0
  90. package/dist/playbooks/service-build/intent-analyzer.js +1 -1
  91. package/dist/playbooks/service-build/machine-nodes.d.ts +1 -1
  92. package/dist/playbooks/service-build/machine-nodes.js +1 -1
  93. package/dist/playbooks/service-build/machine-panorama.js +1 -1
  94. package/dist/playbooks/service-build/merchant-guide.js +1 -1
  95. package/dist/playbooks/service-build/migration-planner.js +1 -1
  96. package/dist/playbooks/service-build/object-panorama.d.ts +27 -1
  97. package/dist/playbooks/service-build/object-panorama.js +1 -1
  98. package/dist/playbooks/service-build/participation-radar.js +1 -1
  99. package/dist/playbooks/service-build/pipeline-actions.d.ts +4 -0
  100. package/dist/playbooks/service-build/pipeline-actions.js +1 -1
  101. package/dist/playbooks/service-build/relationship-profile.js +1 -1
  102. package/dist/playbooks/service-build/semantic-graph.d.ts +1 -0
  103. package/dist/playbooks/service-build/semantic-graph.js +1 -1
  104. package/dist/playbooks/service-build/service-panorama.js +1 -1
  105. package/dist/playbooks/service-build/service-quote.js +1 -1
  106. package/dist/review/index.js +1 -1
  107. package/dist/safety/confirm-gate.js +1 -1
  108. package/dist/schema/call/machine.d.ts +1 -0
  109. package/dist/schema/call/machine.js +1 -1
  110. package/dist/schema/call/order.d.ts +60 -0
  111. package/dist/schema/call/order.js +1 -1
  112. package/dist/schema/call/semantic.js +1 -1
  113. package/dist/schema/call/service.d.ts +56 -0
  114. package/dist/schema/call/service.js +1 -1
  115. package/dist/schema/common/index.js +1 -1
  116. package/dist/schema/goal/planning.d.ts +7 -0
  117. package/dist/schema/goal/planning.js +1 -1
  118. package/dist/schema/index.d.ts +1 -0
  119. package/dist/schema/index.js +1 -1
  120. package/dist/schema/industry-pack/index.d.ts +26 -0
  121. package/dist/schema/industry-pack/index.js +1 -1
  122. package/dist/schema/local/index.js +1 -1
  123. package/dist/schema/messenger/index.d.ts +20 -0
  124. package/dist/schema/messenger/index.js +1 -1
  125. package/dist/schema/operations.d.ts +50 -0
  126. package/dist/schema/persona/index.d.ts +110 -0
  127. package/dist/schema/query/bi.d.ts +2 -0
  128. package/dist/schema/query/bi.js +1 -1
  129. package/dist/schema/query/index.js +1 -1
  130. package/dist/schema/schema-version.js +1 -1
  131. package/dist/schema/service-clone/index.d.ts +46 -0
  132. package/dist/schema/service-clone/index.js +1 -0
  133. package/dist/schema/utils/node-parser.js +1 -1
  134. package/dist/schema-query-impl/index.js +1 -1
  135. package/dist/schemas/index.json +7 -1
  136. package/dist/schemas/industry_pack_operation.output.json +113 -0
  137. package/dist/schemas/industry_pack_operation.schema.json +7 -1
  138. package/dist/schemas/messenger_operation.output.json +42 -4
  139. package/dist/schemas/onchain_operations.output.json +1 -1
  140. package/dist/schemas/onchain_operations.schema.json +409 -98
  141. package/dist/schemas/onchain_operations_allocation.schema.json +5 -5
  142. package/dist/schemas/onchain_operations_arbitration.schema.json +2 -2
  143. package/dist/schemas/onchain_operations_contact.schema.json +1 -1
  144. package/dist/schemas/onchain_operations_demand.schema.json +3 -3
  145. package/dist/schemas/onchain_operations_gen_passport.schema.json +1 -1
  146. package/dist/schemas/onchain_operations_guard.schema.json +59 -59
  147. package/dist/schemas/onchain_operations_machine.schema.json +3 -3
  148. package/dist/schemas/onchain_operations_order.schema.json +133 -1
  149. package/dist/schemas/onchain_operations_progress.schema.json +1 -1
  150. package/dist/schemas/onchain_operations_proof.schema.json +1 -1
  151. package/dist/schemas/onchain_operations_repository.schema.json +1 -1
  152. package/dist/schemas/onchain_operations_reward.schema.json +4 -4
  153. package/dist/schemas/onchain_operations_service.schema.json +188 -9
  154. package/dist/schemas/onchain_operations_treasury.schema.json +7 -7
  155. package/dist/schemas/onchain_table_data.output.json +5 -1
  156. package/dist/schemas/persona_operation.output.json +266 -0
  157. package/dist/schemas/persona_operation.schema.json +42 -0
  158. package/dist/schemas/query_toolkit.output.json +46 -46
  159. package/dist/schemas/query_toolkit.schema.json +5 -1
  160. package/dist/schemas/service_clone_operation.output.json +168 -0
  161. package/dist/schemas/service_clone_operation.schema.json +49 -0
  162. package/dist/schemas/workflow_operation.schema.json +1 -1
  163. package/dist/tools/handlers/benchmark-migration.d.ts +17 -0
  164. package/dist/tools/handlers/benchmark-migration.js +1 -1
  165. package/dist/tools/handlers/config.js +1 -1
  166. package/dist/tools/handlers/industry-pack.js +1 -1
  167. package/dist/tools/handlers/messenger.js +1 -1
  168. package/dist/tools/handlers/onchain.js +1 -1
  169. package/dist/tools/handlers/query.js +1 -1
  170. package/dist/tools/handlers/service-clone.d.ts +2 -0
  171. package/dist/tools/handlers/service-clone.js +1 -0
  172. package/dist/tools/index.js +1 -1
  173. package/dist/tools/registry/business.js +1 -1
  174. package/dist/tools/wrap.d.ts +6 -1
  175. package/dist/tools/wrap.js +1 -1
  176. package/package.json +4 -3
@@ -0,0 +1,168 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+ "$id": "https://wowok.net/schemas/service_clone_operation.output.json",
4
+ "title": "Service Clone - Rebuild On-chain Services",
5
+ "description": "Clone an existing on-chain Service into a new object. Actions: clone_plan (read the source Service — fields, machine graph, guards, permission, allocators — and emit a reconstruction plan; optional overrides: token_type, network, description, location, sales, compensation_fund, order_allocators), clone_apply (apply overrides to a prior plan, run the pre-publish gate, emit the exact onchain_operations payloads in execution order). Never executes on-chain.",
6
+ "type": "object",
7
+ "properties": {
8
+ "result": {
9
+ "oneOf": [
10
+ {
11
+ "type": "object",
12
+ "properties": {
13
+ "action": {
14
+ "type": "string",
15
+ "const": "clone_plan"
16
+ },
17
+ "source": {
18
+ "type": "object",
19
+ "properties": {
20
+ "service": {
21
+ "type": "string"
22
+ },
23
+ "network": {
24
+ "type": "string"
25
+ },
26
+ "name": {
27
+ "anyOf": [
28
+ {
29
+ "type": "string"
30
+ },
31
+ {
32
+ "type": "null"
33
+ }
34
+ ]
35
+ }
36
+ },
37
+ "required": [
38
+ "service",
39
+ "network",
40
+ "name"
41
+ ],
42
+ "additionalProperties": false
43
+ },
44
+ "plan": {
45
+ "type": "object",
46
+ "propertyNames": {
47
+ "type": "string"
48
+ },
49
+ "additionalProperties": {},
50
+ "description": "The reconstruction plan."
51
+ },
52
+ "overrides_applied": {
53
+ "type": "object",
54
+ "propertyNames": {
55
+ "type": "string"
56
+ },
57
+ "additionalProperties": {}
58
+ }
59
+ },
60
+ "required": [
61
+ "action",
62
+ "source",
63
+ "plan",
64
+ "overrides_applied"
65
+ ],
66
+ "additionalProperties": false
67
+ },
68
+ {
69
+ "type": "object",
70
+ "properties": {
71
+ "action": {
72
+ "type": "string",
73
+ "const": "clone_apply"
74
+ },
75
+ "source": {
76
+ "type": "object",
77
+ "properties": {
78
+ "service": {
79
+ "type": "string"
80
+ },
81
+ "network": {
82
+ "type": "string"
83
+ }
84
+ },
85
+ "required": [
86
+ "service",
87
+ "network"
88
+ ],
89
+ "additionalProperties": false
90
+ },
91
+ "gate": {
92
+ "type": "object",
93
+ "properties": {
94
+ "critical": {
95
+ "type": "array",
96
+ "items": {
97
+ "type": "string"
98
+ }
99
+ },
100
+ "warnings": {
101
+ "type": "array",
102
+ "items": {
103
+ "type": "string"
104
+ }
105
+ },
106
+ "passed": {
107
+ "type": "boolean"
108
+ }
109
+ },
110
+ "required": [
111
+ "critical",
112
+ "warnings",
113
+ "passed"
114
+ ],
115
+ "additionalProperties": false
116
+ },
117
+ "operations": {
118
+ "type": "array",
119
+ "items": {
120
+ "type": "object",
121
+ "properties": {
122
+ "step": {
123
+ "type": "number"
124
+ },
125
+ "op_type": {
126
+ "type": "string"
127
+ },
128
+ "description": {
129
+ "type": "string"
130
+ },
131
+ "payload": {
132
+ "type": "object",
133
+ "propertyNames": {
134
+ "type": "string"
135
+ },
136
+ "additionalProperties": {}
137
+ }
138
+ },
139
+ "required": [
140
+ "step",
141
+ "op_type",
142
+ "description",
143
+ "payload"
144
+ ],
145
+ "additionalProperties": false
146
+ }
147
+ },
148
+ "next_step": {
149
+ "type": "string"
150
+ }
151
+ },
152
+ "required": [
153
+ "action",
154
+ "source",
155
+ "gate",
156
+ "operations",
157
+ "next_step"
158
+ ],
159
+ "additionalProperties": false
160
+ }
161
+ ]
162
+ }
163
+ },
164
+ "required": [
165
+ "result"
166
+ ],
167
+ "additionalProperties": false
168
+ }
@@ -0,0 +1,49 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+ "$id": "https://wowok.net/schemas/service_clone_operation.json",
4
+ "title": "Service Clone - Rebuild On-chain Services",
5
+ "description": "Clone an existing on-chain Service into a new object. Actions: clone_plan (read the source Service — fields, machine graph, guards, permission, allocators — and emit a reconstruction plan; optional overrides: token_type, network, description, location, sales, compensation_fund, order_allocators), clone_apply (apply overrides to a prior plan, run the pre-publish gate, emit the exact onchain_operations payloads in execution order). Never executes on-chain.",
6
+ "type": "object",
7
+ "properties": {
8
+ "action": {
9
+ "type": "string",
10
+ "enum": [
11
+ "clone_plan",
12
+ "clone_apply"
13
+ ],
14
+ "description": "Action: 'clone_plan' = read the source Service and emit a reconstruction plan (source_service required; never executes on-chain); 'clone_apply' = run a prior clone_plan through the pre-publish gate and emit the exact onchain_operations payloads ready for execution (plan required; never executes on-chain)."
15
+ },
16
+ "source_service": {
17
+ "description": "Source Service object ID or LocalMark name (required for clone_plan).",
18
+ "type": "string"
19
+ },
20
+ "plan": {
21
+ "description": "A prior clone_plan result (required for clone_apply).",
22
+ "type": "object",
23
+ "propertyNames": {
24
+ "type": "string"
25
+ },
26
+ "additionalProperties": {}
27
+ },
28
+ "overrides": {
29
+ "description": "Configuration overrides for the cloned Service. Supported keys: 'token_type' (new payment token, e.g. '0x2::wow::WOW' or '0x2::usdt::USDT'); 'network' (target network — overrides the top-level network field); 'description' (new service description); 'location' (new service location); 'sales' (array of sale overrides, merged by name); 'compensation_fund' (new fund amount in smallest unit); 'order_allocators' (replace allocator plan entirely).",
30
+ "type": "object",
31
+ "propertyNames": {
32
+ "type": "string"
33
+ },
34
+ "additionalProperties": {}
35
+ },
36
+ "network": {
37
+ "description": "Target network (default: the source Service's network).",
38
+ "type": "string",
39
+ "enum": [
40
+ "testnet",
41
+ "mainnet"
42
+ ]
43
+ }
44
+ },
45
+ "required": [
46
+ "action"
47
+ ],
48
+ "additionalProperties": false
49
+ }
@@ -143,7 +143,7 @@
143
143
  "type": "integer",
144
144
  "minimum": 0,
145
145
  "maximum": 255,
146
- "description": "Identifier (0-255) for data lookup in Guard table."
146
+ "description": "Identifier (0-255) for data lookup in Guard table. Slot consensus (enforced on-chain at guard table construction): 0-220 = user slots (free for business guards); 221-253 = PROTOCOL-RESERVED (rejected on-chain — reserved so future protocol features get fixed slots without colliding with published guards); 255 = ONCE replay-protection slot on Allocation (byte-keyed, the submitted bytes are the once-key — use for per-period keys like period-<N>); 254 = ONCE-FOR-OBJECT slot on Allocation (chain-derived key = bcs(the Allocation's payment_info.for_object); the submitted bytes are ignored and the submission only arms the slot — use for one-shot per-order rails such as full refunds)."
147
147
  },
148
148
  "b_submission": {
149
149
  "type": "boolean",
@@ -1,2 +1,19 @@
1
+ import { type IndustryTemplate } from "../../knowledge/template-loader.js";
2
+ import type { DeliverableDefinition } from "../../playbooks/service-build/intent-analyzer.js";
3
+ import type { IndustryMode } from "../../extensions/index.js";
1
4
  import type { ToolDispatchResult } from "../types.js";
5
+ export declare function validateAllocatorRows(t: IndustryTemplate): string[];
6
+ interface PlanDivergence {
7
+ severity: "critical" | "warning";
8
+ item: string;
9
+ detail: string;
10
+ action: string;
11
+ }
12
+ export declare function planDivergences(t: IndustryTemplate, allocation: Array<{
13
+ recipient: string;
14
+ percentage: number;
15
+ }> | undefined): PlanDivergence[];
16
+ export declare function variantPaymentModel(t: IndustryTemplate): "milestone" | "subscription" | "escrow";
17
+ export declare function variantDeliverables(t: IndustryTemplate, traits: IndustryMode["traits"] | undefined): DeliverableDefinition[];
2
18
  export declare function handleBenchmarkMigrationOperation(args: unknown): Promise<ToolDispatchResult>;
19
+ export {};
@@ -1 +1 @@
1
- import{strictParse}from'../../schema/index.js';import{BenchmarkMigrationSchema}from'../../schema/benchmark-migration/index.js';import{getTemplate,listTemplates}from'../../knowledge/template-loader.js';import{scanTemplate}from'../../knowledge/template-scanner.js';import{planMigration}from'../../playbooks/service-build/migration-planner.js';import{handleMerchantGuide}from'../../playbooks/service-build/merchant-guide.js';import{getIndustryModeRegistry}from'../../extensions/index.js';import{resolveIndustryName}from'../../knowledge/industry-registry.js';function templateSummary(a){return{'id':a['id'],'industry':a['industry'],'variant':a['variant'],'product_ref':a['product_ref'],'archetype':a['archetype'],'key_risk':a['key_risk'],'node_count':a['machine_shape']['length'],'guard_count':a['guards']['length'],'recommended_role':a['recommended_role']};}function requireTemplate(a,b){if(!a)throw new Error('\x27template_id\x27\x20is\x20required\x20for\x20action=\x27'+b+'\x27');const c=getTemplate(a);if(!c)throw new Error('Unknown\x20template\x20id:\x20'+a+'\x20(use\x20action=\x27template_list\x27\x20to\x20see\x20valid\x20ids)');return c;}function scanSummary(a){const b={};for(const c of a['findings'])b[c['severity']]=(b[c['severity']]??0x0)+0x1;return{'risk_level':a['risk_level'],'passed':a['passed'],'finding_count':a['findings']['length'],'findings_by_severity':b,'red_flags':a['red_flags'],'findings':a['findings']};}function assertScanPassed(a,b){if(a['passed'])return;throw new Error('action=\x27'+b+'\x27\x20blocked:\x20pre-deploy\x20scan\x20of\x20template\x20\x27'+a['template_id']+'\x27\x20found\x20CRITICAL\x20risk\x20—\x20'+a['red_flags']['join'](';\x20')+'.\x20Fix\x20the\x20template\x20(frontmatter\x20or\x20body)\x20and\x20re-run\x20action=\x27template_scan\x27.');}function templateIntent(a,b){if(b&&b['trim']())return b['trim']();return'Adopt\x20the\x20'+a['id']+'\x20industry\x20archetype\x20template\x20('+a['archetype']+')\x20for\x20the\x20'+a['industry']+'\x20industry.\x20'+('Primary\x20risk\x20to\x20mitigate:\x20'+a['key_risk']+'.');}function effectiveFeeParams(a,b){return{...a['fee_params'],...b??{}};}function validateFeeParams(a,b){const c=[];let d=0x0;for(const [e,f]of Object['entries'](a)){if(typeof f!=='number'||!Number['isFinite'](f))continue;if(e['endsWith']('_bps')){(!Number['isInteger'](f)||f<0x0||f>0x2710)&&c['push'](e+'='+f+'\x20is\x20not\x20an\x20integer\x20rate\x20in\x20[0,\x2010000]\x20bps');if(e['endsWith']('_share_bps'))d+=Math['max'](0x0,f);}else{if(e['endsWith']('_days')){if(f<=0x0||f>0xe42)c['push'](e+'='+f+'\x20is\x20outside\x20the\x20sane\x20window\x20range\x20(0,\x203650]\x20days');}else{if(e['endsWith']('_hours')){if(f<=0x0||f>0x2238)c['push'](e+'='+f+'\x20is\x20outside\x20the\x20sane\x20window\x20range\x20(0,\x208760]\x20hours');}}}}if(d>0x2710)c['push']('*_share_bps\x20sum\x20'+d+'\x20exceeds\x2010000\x20(a\x20pool\x20splits\x20into\x20at\x20most\x20100%)');if(c['length']>0x0)throw new Error('invalid\x20fee\x20parameters\x20for\x20template\x20\x27'+b+'\x27:\x20'+c['join'](';\x20')+'.\x20'+'Correct\x20the\x20template\x27s\x20fee_params\x20or\x20pass\x20valid\x20\x27fee_overrides\x27.');}function validateAllocatorRows(a){const b=a['allocator']['rows'];if(b===undefined||b['length']===0x0)return[];const c=[],d=b['filter'](f=>f['track']==='settlement'),e=b['filter'](f=>f['track']==='refund');d['length']!==a['allocator']['count']&&c['push']('settlement\x20rows\x20'+d['length']+'\x20!=\x20allocator.count\x20'+a['allocator']['count']);e['length']>0x0&&!a['allocator']['refund_track']&&c['push']('refund\x20rows\x20declared\x20but\x20allocator.refund_track\x20is\x20missing');a['allocator']['refund_track']&&e['length']===0x0&&c['push']('refund_track\x20\x27'+a['allocator']['refund_track']+'\x27\x20declared\x20but\x20no\x20refund\x20row\x20carries\x20it');for(const [f,g]of[['settlement',d],['refund',e]]){const h=g['filter'](j=>j['mode']==='surplus')['length'];if(h>0x1)c['push'](f+'\x20track\x20has\x20'+h+'\x20Surplus\x20rows\x20(allocation.move\x20allows\x20at\x20most\x20one)');const i=g['filter'](j=>j['mode']==='rate');if(i['length']===g['length']&&i['length']>0x0&&h===0x0){const j=i['reduce']((k,l)=>k+(typeof l['value']==='number'?l['value']:Number(l['value']??NaN)),0x0);(!Number['isFinite'](j)||j!==0x2710)&&c['push'](f+'\x20track\x20is\x20all-Rate\x20but\x20sums\x20to\x20'+j+',\x20not\x2010000\x20bps');}for(const k of g){if(k['mode']==='surplus'&&k['value']!==undefined)c['push'](f+'/'+(k['recipient_key']??'?')+':\x20surplus\x20row\x20must\x20not\x20carry\x20a\x20value');k['mode']==='amount'&&k['value']===undefined&&k['value_from']===undefined&&c['push'](f+'/'+(k['recipient_key']??'?')+':\x20amount\x20row\x20needs\x20value\x20or\x20value_from'),k['value_from']!==undefined&&!(k['value_from']in a['fee_params'])&&c['push'](f+'/'+(k['recipient_key']??'?')+':\x20value_from\x20\x27'+k['value_from']+'\x27\x20is\x20not\x20a\x20fee_params\x20key'),k['recipient']==='guard_identifier'&&k['track']==='settlement'&&c['push']('settlement\x20row\x20uses\x20GuardIdentifier\x20—\x20order-anchored\x20recipients\x20belong\x20to\x20the\x20refund\x20track\x20(see\x20refund_track)');}}return c;}function planDivergences(a,b){const c=[],d=b?.['length']??0x0,e=(a['allocator']['rows']?.['length']??0x0)>0x0;if(e){const h=validateAllocatorRows(a);h['length']>0x0&&c['push']({'severity':'critical','item':'allocator_rows_invalid','detail':'Template\x20allocator\x20rows\x20are\x20internally\x20inconsistent:\x20'+h['join'](';\x20')+'.','action':'Fix\x20the\x20template\x27s\x20allocator.rows\x20(they\x20are\x20the\x20authoritative\x20money\x20plan;\x20order_allocators\x20is\x20L1-frozen\x20at\x20publish).'});}else d!==a['allocator']['count']&&c['push']({'severity':'critical','item':'allocator_row_count','detail':'Template\x20declares\x20'+a['allocator']['count']+'\x20sharing\x20row(s);\x20the\x20generated\x20plan\x20carries\x20'+d+'\x20percentage\x20row(s).','action':'Build\x20the\x20Allocation\x20with\x20the\x20template\x27s\x20own\x20row\x20set\x20(order_allocators\x20is\x20L1\x20—\x20frozen\x20at\x20Service\x20publish),\x20or\x20declare\x20allocator.rows\x20in\x20the\x20template.'}),a['allocator']['mode']!=='rate'&&c['push']({'severity':'critical','item':'allocation_mode','detail':'Template\x20allocator\x20mode\x20is\x20\x27'+a['allocator']['mode']+'\x27,\x20which\x20a\x20percentage\x20pair\x20cannot\x20represent\x20—\x20no\x20percentage\x20hint\x20was\x20emitted.','action':'Declare\x20allocator.rows\x20in\x20the\x20template\x20(per-row\x20amount\x20/\x20rate\x20/\x20surplus);\x20the\x20pipeline\x20will\x20then\x20carry\x20the\x20real\x20split\x20instead\x20of\x20a\x20hint.'});const f=a['allocator']['refund_track']!==undefined||/refund/i['test'](a['allocator']['description']);a['allocator']['refund_track']&&c['push']({'severity':'critical','item':'refund_track_not_in_plan','detail':'Template\x20declares\x20a\x20\x27'+a['allocator']['refund_track']+'\x27\x20refund\x20track;\x20the\x20generated\x20plan\x20carries\x20only\x20the\x20settlement\x20split.','action':'Build\x20the\x20second\x20Allocator\x20(Rate\x2010000\x20to\x20the\x20buyer,\x20order-anchored\x20GuardIdentifier\x20recipients)\x20bound\x20to\x20the\x20refund\x20Guard\x20before\x20publish.'});if(!f)c['push']({'severity':'critical','item':'refund_track','detail':'The\x20template\x27s\x20allocator\x20declares\x20no\x20refund\x20track\x20—\x20returns/refunds\x20have\x20no\x20funded\x20path\x20in\x20the\x20money\x20plan.','action':'Add\x20the\x20second\x20Allocator\x20(Rate\x2010000\x20to\x20the\x20buyer)\x20bound\x20to\x20the\x20refund\x20Guard,\x20or\x20confirm\x20with\x20the\x20merchant\x20that\x20refunds\x20are\x20out\x20of\x20scope.'});else!a['allocator']['refund_track']&&c['push']({'severity':'warning','item':'refund_track','detail':'A\x20refund\x20track\x20is\x20declared\x20but\x20not\x20order-anchored,\x20so\x20the\x20refund\x20recipient\x20is\x20resolved\x20from\x20the\x20signer/Entity\x20rather\x20than\x20the\x20paying\x20Order.','action':'Gate\x20the\x20refund\x20track\x20with\x20AND[signer\x20==\x20order.owner,\x20progress.node\x20==\x20X]\x20or\x20move\x20it\x20to\x20an\x20order-anchored\x20GuardIdentifier(0)\x20recipient.'});const g=Object['keys'](a['fee_params'])['filter'](i=>/_(?:days|hours)$/['test'](i));return g['length']>0x0&&!a['time_anchors']&&c['push']({'severity':'warning','item':'window_anchors','detail':'fee_params\x20declares\x20business\x20windows\x20('+g['join'](',\x20')+')\x20but\x20the\x20template\x20declares\x20no\x20time_anchors.','action':'Add\x20time_anchors\x20(or\x20name\x20the\x20window\x20in\x20the\x20Guard\x20set)\x20so\x20the\x20plan\x20emits\x20the\x20release/timeout\x20build\x20steps.'}),c;}function platformShareBps(a){const b=Object['keys'](a)['find'](c=>/(?:platform|commission|service_fee)[a-z_]*_bps$/['test'](c)&&!/^attributed_/['test'](c)&&typeof a[c]==='number');return b!==undefined?a[b]:undefined;}function variantPaymentModel(a){const b=a['machine_shape']['map'](c=>c['name']+'\x20'+c['role'])['join']('\x20')['toLowerCase']();if(/\b(milestone|revision|revis|draft|deliverable)\b/['test'](b))return'milestone';if(/\b(charge|renew|subscription|cycle|billing|monthly)\b/['test'](b))return'subscription';return'escrow';}function variantRefundPolicy(a){const b=a['allocator']['description']['toLowerCase']();if(/full[ -]?refund|100% refund|refund .*100/['test'](b))return'full';if(/pro-?rata|prorated/['test'](b))return'milestone_prorated';if(/partial/['test'](b))return'partial';return undefined;}function variantDeliverables(a,b){const c=[...a['machine_shape']]['reverse']()['find'](e=>!/refund|cancel|dispute|terminat/i['test'](e['name']+'\x20'+e['role']))??a['machine_shape'][a['machine_shape']['length']-0x1],d=b?.['has_logistics']?'physical':b?.['pure_digital']?'digital':'service_session';return[{'name':a['variant']+'\x20fulfillment','type':d,'acceptanceCriteria':'Order\x20reaches\x20the\x20terminal\x20workflow\x20node\x20\x27'+c['name']+'\x27\x20('+c['role']+')','proofOfDelivery':'manual_confirm'}];}function variantModePrior(a,b){if(!b)return undefined;return{...b,'name':a['industry']+'_'+a['variant'],'display_name':a['variant']+'\x20archetype\x20('+a['industry']+')','source':'custom','machine_shape':a['machine_shape']['map'](c=>({...c})),'guards':a['guards']['map'](c=>({...c})),'allocator':{...a['allocator']},'key_risk':a['key_risk'],'build_notes':[...a['build_notes']],...a['time_anchors']?{'time_anchors':{...a['time_anchors']}}:{}};}async function runGuide(a,b,c){const d=effectiveFeeParams(a,c);validateFeeParams(d,a['id']);const e=getIndustryModeRegistry()['getMode'](a['industry']),f=platformShareBps(d),g={'model':variantPaymentModel(a)},h=[],i=(a['allocator']['rows']?.['length']??0x0)>0x0;if(f!==undefined&&f>0x0&&!i&&a['allocator']['mode']==='rate'){const n=Math['round'](f)/0x64;h['push']({'recipient':'merchant','percentage':Math['round']((0x64-n)*0x64)/0x64}),h['push']({'recipient':'platform','percentage':n}),g['allocation']=h;}const j=variantRefundPolicy(a),k={'escrow':!![]};if(j)k['refundPolicy']=j;const l=await handleMerchantGuide({'intent':templateIntent(a,b),'guide_confirm':{'industry':a['industry'],'payment':g,'trust':k,'deliverables':variantDeliverables(a,e?.['traits'])},'mode_prior_override':variantModePrior(a,e),'name_base':a['id']}),m=planDivergences(a,h);if(a['allocator']['rows']?.['length'])l['template_allocator_rows']=a['allocator']['rows']['map'](o=>({...o}));m['length']>0x0&&(l['plan_divergence']={'template_allocator':{...a['allocator']},'template_guard_refs':a['guards']['length'],'plan_allocation':h,'divergences':m,'publish_ready':![]});l['template']={'id':a['id'],'archetype':a['archetype'],'recommended_role':a['recommended_role'],'fee_params':d};if(c&&Object['keys'](c)['length']>0x0)l['template_fee_overrides']=c;return l;}export async function handleBenchmarkMigrationOperation(a){const b=strictParse(BenchmarkMigrationSchema,a,'benchmark_migration_operation\x20input'),c=b['industry']?resolveIndustryName(b['industry'])??b['industry']['toLowerCase']():undefined;let d;switch(b['action']){case'template_list':{const {templates:e,errors:f}=listTemplates(),g=c?e['filter'](h=>h['industry']===c):e;d={'action':'template_list','count':g['length'],'templates':g['map'](templateSummary),'load_errors':f};break;}case'template_get':{const h=requireTemplate(b['template_id'],'template_get');d={'action':'template_get','template':{...h}};break;}case'template_generate':{const i=requireTemplate(b['template_id'],'template_generate'),j=scanTemplate(i);assertScanPassed(j,'template_generate');const k=await runGuide(i,b['description'],b['fee_overrides']);d={'action':'template_generate','template_id':i['id'],'scan':scanSummary(j),'plan':k};break;}case'template_scan':{const l=requireTemplate(b['template_id'],'template_scan');d={'action':'template_scan','scan':scanTemplate(l)};break;}case'migration_import':{if(!b['description']||!b['description']['trim']())throw new Error('\x27description\x27\x20is\x20required\x20for\x20action=\x27migration_import\x27');const m=planMigration({'url':b['url'],'description':b['description'],'industry':c,'network':b['network']});if(!m)throw new Error('No\x20industry\x20template\x20matched\x20the\x20description.\x20Refine\x20the\x20description\x20or\x20pass\x20an\x20explicit\x20\x27industry\x27\x20hint.');d={'action':'migration_import','log':m};break;}case'migration_review':{if(!b['log'])throw new Error('\x27log\x27\x20is\x20required\x20for\x20action=\x27migration_review\x27');const n=b['log'],o=Array['isArray'](n['mapped'])?n['mapped']:[],p=Array['isArray'](n['unmapped'])?n['unmapped']:[],q=Array['isArray'](n['manual_review'])?n['manual_review']:[],r=n['risk_check']??{};d={'action':'migration_review','log':n,'review_summary':{'mapped_count':o['length'],'unmapped_count':p['length'],'manual_review_count':q['length'],'risk_passed':r['passed']===!![]}};break;}case'migration_apply':{const s=requireTemplate(b['template_id'],'migration_apply'),t=scanTemplate(s);assertScanPassed(t,'migration_apply');const u=b['network']??'testnet',v=await runGuide(s,b['description'],b['fee_overrides']);d={'action':'migration_apply','template_id':s['id'],'network':u,'scan':scanSummary(t),'plan':v};break;}default:throw new Error('Unknown\x20benchmark_migration_operation\x20action:\x20'+String(b['action']));}return{'content':[{'type':'text','text':JSON['stringify']({'result':d})}],'structuredContent':{'result':d}};}
1
+ import{strictParse}from'../../schema/index.js';import{BenchmarkMigrationSchema}from'../../schema/benchmark-migration/index.js';import{getTemplate,listTemplates}from'../../knowledge/template-loader.js';import{scanTemplate}from'../../knowledge/template-scanner.js';import{planMigration}from'../../playbooks/service-build/migration-planner.js';import{handleMerchantGuide}from'../../playbooks/service-build/merchant-guide.js';import{inferArbitration}from'../../playbooks/service-build/intent-analyzer.js';import{getIndustryModeRegistry}from'../../extensions/index.js';import{resolveIndustryName}from'../../knowledge/industry-registry.js';function templateSummary(a){return{'id':a['id'],'industry':a['industry'],'variant':a['variant'],'product_ref':a['product_ref'],'archetype':a['archetype'],'key_risk':a['key_risk'],'node_count':a['machine_shape']['length'],'guard_count':a['guards']['length'],'recommended_role':a['recommended_role']};}function requireTemplate(a,b){if(!a)throw new Error('\x27template_id\x27\x20is\x20required\x20for\x20action=\x27'+b+'\x27');const c=getTemplate(a);if(!c)throw new Error('Unknown\x20template\x20id:\x20'+a+'\x20(use\x20action=\x27template_list\x27\x20to\x20see\x20valid\x20ids)');return c;}function scanSummary(a){const b={};for(const c of a['findings'])b[c['severity']]=(b[c['severity']]??0x0)+0x1;return{'risk_level':a['risk_level'],'passed':a['passed'],'finding_count':a['findings']['length'],'findings_by_severity':b,'red_flags':a['red_flags'],'findings':a['findings']};}function assertScanPassed(a,b){if(a['passed'])return;throw new Error('action=\x27'+b+'\x27\x20blocked:\x20pre-deploy\x20scan\x20of\x20template\x20\x27'+a['template_id']+'\x27\x20found\x20CRITICAL\x20risk\x20—\x20'+a['red_flags']['join'](';\x20')+'.\x20Fix\x20the\x20template\x20(frontmatter\x20or\x20body)\x20and\x20re-run\x20action=\x27template_scan\x27.');}function templateIntent(a,b){if(b&&b['trim']())return b['trim']();return'Adopt\x20the\x20'+a['id']+'\x20industry\x20archetype\x20template\x20('+a['archetype']+')\x20for\x20the\x20'+a['industry']+'\x20industry.\x20'+('Primary\x20risk\x20to\x20mitigate:\x20'+a['key_risk']+'.');}function effectiveFeeParams(a,b){return{...a['fee_params'],...b??{}};}function validateFeeParams(a,b){const c=[];let d=0x0;for(const [e,f]of Object['entries'](a)){if(typeof f!=='number'||!Number['isFinite'](f))continue;if(e['endsWith']('_bps')){(!Number['isInteger'](f)||f<0x0||f>0x2710)&&c['push'](e+'='+f+'\x20is\x20not\x20an\x20integer\x20rate\x20in\x20[0,\x2010000]\x20bps');if(e['endsWith']('_share_bps'))d+=Math['max'](0x0,f);}else{if(e['endsWith']('_days')){if(f<=0x0||f>0xe42)c['push'](e+'='+f+'\x20is\x20outside\x20the\x20sane\x20window\x20range\x20(0,\x203650]\x20days');}else{if(e['endsWith']('_hours')){if(f<=0x0||f>0x2238)c['push'](e+'='+f+'\x20is\x20outside\x20the\x20sane\x20window\x20range\x20(0,\x208760]\x20hours');}}}}if(d>0x2710)c['push']('*_share_bps\x20sum\x20'+d+'\x20exceeds\x2010000\x20(a\x20pool\x20splits\x20into\x20at\x20most\x20100%)');if(c['length']>0x0)throw new Error('invalid\x20fee\x20parameters\x20for\x20template\x20\x27'+b+'\x27:\x20'+c['join'](';\x20')+'.\x20'+'Correct\x20the\x20template\x27s\x20fee_params\x20or\x20pass\x20valid\x20\x27fee_overrides\x27.');}export function validateAllocatorRows(a){const b=a['allocator']['rows'];if(b===undefined||b['length']===0x0)return[];const c=[],d=b['filter'](f=>f['track']==='settlement'),e=b['filter'](f=>f['track']==='refund');d['length']!==a['allocator']['count']&&c['push']('settlement\x20rows\x20'+d['length']+'\x20!=\x20allocator.count\x20'+a['allocator']['count']);e['length']>0x0&&!a['allocator']['refund_track']&&c['push']('refund\x20rows\x20declared\x20but\x20allocator.refund_track\x20is\x20missing');a['allocator']['refund_track']&&e['length']===0x0&&c['push']('refund_track\x20\x27'+a['allocator']['refund_track']+'\x27\x20declared\x20but\x20no\x20refund\x20row\x20carries\x20it');for(const [f,g]of[['settlement',d],['refund',e]]){const h=g['filter'](j=>j['mode']==='surplus')['length'];if(h>0x1)c['push'](f+'\x20track\x20has\x20'+h+'\x20Surplus\x20rows\x20(allocation.move\x20allows\x20at\x20most\x20one)');const i=g['filter'](j=>j['mode']==='rate');if(i['length']===g['length']&&i['length']>0x0&&h===0x0){const j=i['reduce']((k,l)=>k+(typeof l['value']==='number'?l['value']:Number(l['value']??NaN)),0x0);(!Number['isFinite'](j)||j!==0x2710)&&c['push'](f+'\x20track\x20is\x20all-Rate\x20but\x20sums\x20to\x20'+j+',\x20not\x2010000\x20bps');}for(const k of g){if(k['mode']==='surplus'&&k['value']!==undefined)c['push'](f+'/'+(k['recipient_key']??'?')+':\x20surplus\x20row\x20must\x20not\x20carry\x20a\x20value');k['mode']==='amount'&&k['value']===undefined&&k['value_from']===undefined&&c['push'](f+'/'+(k['recipient_key']??'?')+':\x20amount\x20row\x20needs\x20value\x20or\x20value_from'),k['value_from']!==undefined&&!(k['value_from']in a['fee_params'])&&c['push'](f+'/'+(k['recipient_key']??'?')+':\x20value_from\x20\x27'+k['value_from']+'\x27\x20is\x20not\x20a\x20fee_params\x20key'),k['recipient']==='guard_identifier'&&k['track']==='settlement'&&c['push']('settlement\x20row\x20uses\x20GuardIdentifier\x20—\x20order-anchored\x20recipients\x20belong\x20to\x20the\x20refund\x20track\x20(see\x20refund_track)');}}return c;}export function planDivergences(a,b){const c=[],d=b?.['length']??0x0,e=(a['allocator']['rows']?.['length']??0x0)>0x0;if(e){const i=validateAllocatorRows(a);i['length']>0x0&&c['push']({'severity':'critical','item':'allocator_rows_invalid','detail':'Template\x20allocator\x20rows\x20are\x20internally\x20inconsistent:\x20'+i['join'](';\x20')+'.','action':'Fix\x20the\x20template\x27s\x20allocator.rows\x20(they\x20are\x20the\x20authoritative\x20money\x20plan;\x20order_allocators\x20is\x20L1-frozen\x20at\x20publish).'});}else d!==a['allocator']['count']&&c['push']({'severity':'critical','item':'allocator_row_count','detail':'Template\x20declares\x20'+a['allocator']['count']+'\x20sharing\x20row(s);\x20the\x20generated\x20plan\x20carries\x20'+d+'\x20percentage\x20row(s).','action':'Build\x20the\x20Allocation\x20with\x20the\x20template\x27s\x20own\x20row\x20set\x20(order_allocators\x20is\x20L1\x20—\x20frozen\x20at\x20Service\x20publish),\x20or\x20declare\x20allocator.rows\x20in\x20the\x20template.'}),a['allocator']['mode']!=='rate'&&c['push']({'severity':'critical','item':'allocation_mode','detail':'Template\x20allocator\x20mode\x20is\x20\x27'+a['allocator']['mode']+'\x27,\x20which\x20a\x20percentage\x20pair\x20cannot\x20represent\x20—\x20no\x20percentage\x20hint\x20was\x20emitted.','action':'Declare\x20allocator.rows\x20in\x20the\x20template\x20(per-row\x20amount\x20/\x20rate\x20/\x20surplus);\x20the\x20pipeline\x20will\x20then\x20carry\x20the\x20real\x20split\x20instead\x20of\x20a\x20hint.'});const f=a['allocator']['refund_track']!==undefined||/refund/i['test'](a['allocator']['description']),g=(a['allocator']['rows']??[])['some'](j=>j['track']==='refund');a['allocator']['refund_track']&&!g&&c['push']({'severity':'critical','item':'refund_track_not_in_plan','detail':'Template\x20declares\x20a\x20\x27'+a['allocator']['refund_track']+'\x27\x20refund\x20track\x20but\x20declares\x20no\x20allocator\x20row\x20with\x20track=\x27refund\x27;\x20the\x20generated\x20plan\x20cannot\x20carry\x20the\x20promised\x20refund\x20rail.','action':'Declare\x20a\x20refund\x20row\x20in\x20allocator.rows\x20(recipient\x20guard_identifier,\x20recipient_key\x20\x270\x27,\x20mode\x20rate,\x20value\x2010000)\x20so\x20the\x20order-anchored\x20full-refund\x20rail\x20rides\x20with\x20the\x20plan.'});if(!f)c['push']({'severity':'critical','item':'refund_track','detail':'The\x20template\x27s\x20allocator\x20declares\x20no\x20refund\x20track\x20—\x20returns/refunds\x20have\x20no\x20funded\x20path\x20in\x20the\x20money\x20plan.','action':'Add\x20the\x20second\x20Allocator\x20(Rate\x2010000\x20to\x20the\x20buyer)\x20bound\x20to\x20the\x20refund\x20Guard,\x20or\x20confirm\x20with\x20the\x20merchant\x20that\x20refunds\x20are\x20out\x20of\x20scope.'});else!a['allocator']['refund_track']&&c['push']({'severity':'warning','item':'refund_track','detail':'A\x20refund\x20track\x20is\x20declared\x20but\x20not\x20order-anchored,\x20so\x20the\x20refund\x20recipient\x20is\x20resolved\x20from\x20the\x20signer/Entity\x20rather\x20than\x20the\x20paying\x20Order.','action':'Gate\x20the\x20refund\x20track\x20with\x20AND[signer\x20==\x20order.owner,\x20progress.node\x20==\x20X]\x20or\x20move\x20it\x20to\x20an\x20order-anchored\x20GuardIdentifier(0)\x20recipient.'});const h=Object['keys'](a['fee_params'])['filter'](j=>/_(?:days|hours)$/['test'](j));return h['length']>0x0&&!a['time_anchors']&&c['push']({'severity':'warning','item':'window_anchors','detail':'fee_params\x20declares\x20business\x20windows\x20('+h['join'](',\x20')+')\x20but\x20the\x20template\x20declares\x20no\x20time_anchors.','action':'Add\x20time_anchors\x20(or\x20name\x20the\x20window\x20in\x20the\x20Guard\x20set)\x20so\x20the\x20plan\x20emits\x20the\x20release/timeout\x20build\x20steps.'}),c;}function platformShareBps(a){const b=Object['keys'](a)['find'](c=>/(?:platform|commission|service_fee)[a-z_]*_bps$/['test'](c)&&!/^attributed_/['test'](c)&&typeof a[c]==='number');return b!==undefined?a[b]:undefined;}export function variantPaymentModel(a){if(a['payment_model'])return a['payment_model'];const b=a['machine_shape']['map'](c=>c['name']+'\x20'+c['role'])['join']('\x20')['toLowerCase']();if(/\b(milestone|revision|revis|draft|deliverable)\b/['test'](b))return'milestone';if(/\b(charge|renew|subscription|cycle|billing|monthly)\b/['test'](b))return'subscription';return'escrow';}function variantRefundPolicy(a){const b=a['allocator']['description']['toLowerCase']();if(/full[ -]?refund|100% refund|refund .*100/['test'](b))return'full';if(/pro-?rata|prorated/['test'](b))return'milestone_prorated';if(/partial/['test'](b))return'partial';return undefined;}export function variantDeliverables(a,b){const c=a['machine_shape']['filter'](g=>g['semantic_role']==='final'),d=c[c['length']-0x1]??[...a['machine_shape']]['reverse']()['find'](g=>!/refund|cancel|dispute|terminat/i['test'](g['name']+'\x20'+g['role']))??a['machine_shape'][a['machine_shape']['length']-0x1],e=b?.['has_logistics']?'physical':b?.['pure_digital']?'digital':'service_session',f=(a['guards']??[])['filter'](h=>/repository_data_check|required_info_evidence_gate|allocator_order_anchor/['test'](h['template_id']));return[{'name':a['variant']+'\x20fulfillment','type':e,'acceptanceCriteria':'Order\x20reaches\x20the\x20terminal\x20workflow\x20node\x20\x27'+d['name']+'\x27\x20('+d['role']+')','proofOfDelivery':f['length']>0x0?'wip_hash':'manual_confirm'}];}function variantModePrior(a,b){if(!b)return undefined;return{...b,'name':a['industry']+'_'+a['variant'],'display_name':a['variant']+'\x20archetype\x20('+a['industry']+')','source':'custom','machine_shape':a['machine_shape']['map'](c=>({...c})),'guards':a['guards']['map'](c=>({...c})),'allocator':{...a['allocator']},'key_risk':a['key_risk'],'build_notes':[...a['build_notes']],...a['time_anchors']?{'time_anchors':{...a['time_anchors']}}:{}};}async function runGuide(a,b,c){const d=effectiveFeeParams(a,c);validateFeeParams(d,a['id']);const e=getIndustryModeRegistry()['getMode'](a['industry']),f=platformShareBps(d),g={'model':variantPaymentModel(a)},h=[],i=(a['allocator']['rows']?.['length']??0x0)>0x0;if(f!==undefined&&f>0x0&&!i&&a['allocator']['mode']==='rate'){const n=Math['round'](f)/0x64;h['push']({'recipient':'merchant','percentage':Math['round']((0x64-n)*0x64)/0x64}),h['push']({'recipient':'platform','percentage':n}),g['allocation']=h;}const j=variantRefundPolicy(a),k={'escrow':!![]};if(j)k['refundPolicy']=j;k['arbitration']=a['arbitration_mode']??k['arbitration']??inferArbitration(templateIntent(a,b));const l=await handleMerchantGuide({'intent':templateIntent(a,b),'guide_confirm':{'industry':a['industry'],'payment':g,'trust':k,'deliverables':variantDeliverables(a,e?.['traits'])},'mode_prior_override':variantModePrior(a,e),'name_base':a['id']}),m=planDivergences(a,h);if(a['allocator']['rows']?.['length'])l['template_allocator_rows']=a['allocator']['rows']['map'](o=>({...o}));if(m['length']>0x0){l['plan_divergence']={'template_allocator':{...a['allocator']},'template_guard_refs':a['guards']['length'],'plan_allocation':h,'divergences':m,'publish_ready':![]};const o=m['filter'](q=>q['severity']==='critical'),p=a['allocator']['refund_track']!==undefined;if(o['length']>0x0&&p&&!(a['allocator']['rows']?.['length']??0x0))throw new Error('action\x20blocked:\x20template\x20\x27'+a['id']+'\x27\x20declares\x20refund_track=\x27'+a['allocator']['refund_track']+'\x27\x20but\x20'+'carries\x20no\x20allocator.rows,\x20so\x20the\x20generated\x20plan\x20would\x20ship\x20WITHOUT\x20the\x20refund\x20rail\x20it\x20'+'promises.\x20Because\x20order_allocators\x20is\x20L1\x20and\x20one-way-frozen\x20at\x20Service\x20publish,\x20escrow\x20'+'locked\x20under\x20such\x20a\x20plan\x20can\x20never\x20be\x20returned.\x20Refusing\x20to\x20emit\x20an\x20unsafe\x20build\x20plan.\x20'+'Critical\x20divergences:\x20'+o['map'](q=>'['+q['item']+']\x20'+q['detail']+'\x20→\x20'+q['action'])['join']('\x20|\x20')+'.\x20Fix\x20the\x20template\x20by\x20declaring\x20allocator.rows\x20(one\x20row\x20per\x20sharing\x20entry,\x20including\x20the\x20'+'refund\x20track).\x20If\x20the\x20template\x20is\x20already\x20correct\x20on\x20disk\x20but\x20the\x20running\x20build\x20predates\x20'+'it,\x20run\x20industry_pack_operation\x20action=\x27repair_builtin_templates\x27\x20(and\x20'+'action=\x27template_drift\x27\x20to\x20diagnose)\x20first.');}l['template']={'id':a['id'],'archetype':a['archetype'],'recommended_role':a['recommended_role'],'fee_params':d};if(c&&Object['keys'](c)['length']>0x0)l['template_fee_overrides']=c;return l;}export async function handleBenchmarkMigrationOperation(a){const b=strictParse(BenchmarkMigrationSchema,a,'benchmark_migration_operation\x20input'),c=b['industry']?resolveIndustryName(b['industry'])??b['industry']['toLowerCase']():undefined;let d;switch(b['action']){case'template_list':{const {templates:e,errors:f}=listTemplates(),g=c?e['filter'](h=>h['industry']===c):e;d={'action':'template_list','count':g['length'],'templates':g['map'](templateSummary),'load_errors':f};break;}case'template_get':{const h=requireTemplate(b['template_id'],'template_get');d={'action':'template_get','template':{...h}};break;}case'template_generate':{const i=requireTemplate(b['template_id'],'template_generate'),j=scanTemplate(i);assertScanPassed(j,'template_generate');const k=await runGuide(i,b['description'],b['fee_overrides']);d={'action':'template_generate','template_id':i['id'],'scan':scanSummary(j),'plan':k};break;}case'template_scan':{const l=requireTemplate(b['template_id'],'template_scan');d={'action':'template_scan','scan':scanTemplate(l)};break;}case'migration_import':{if(!b['description']||!b['description']['trim']())throw new Error('\x27description\x27\x20is\x20required\x20for\x20action=\x27migration_import\x27');const m=planMigration({'url':b['url'],'description':b['description'],'industry':c,'network':b['network']});if(!m)throw new Error('No\x20industry\x20template\x20matched\x20the\x20description.\x20Refine\x20the\x20description\x20or\x20pass\x20an\x20explicit\x20\x27industry\x27\x20hint.');d={'action':'migration_import','log':m};break;}case'migration_review':{if(!b['log'])throw new Error('\x27log\x27\x20is\x20required\x20for\x20action=\x27migration_review\x27');const n=b['log'],o=Array['isArray'](n['mapped'])?n['mapped']:[],p=Array['isArray'](n['unmapped'])?n['unmapped']:[],q=Array['isArray'](n['manual_review'])?n['manual_review']:[],r=n['risk_check']??{};d={'action':'migration_review','log':n,'review_summary':{'mapped_count':o['length'],'unmapped_count':p['length'],'manual_review_count':q['length'],'risk_passed':r['passed']===!![]}};break;}case'migration_apply':{const s=requireTemplate(b['template_id'],'migration_apply'),t=scanTemplate(s);assertScanPassed(t,'migration_apply');const u=b['network']??'testnet',v=await runGuide(s,b['description'],b['fee_overrides']);d={'action':'migration_apply','template_id':s['id'],'network':u,'scan':scanSummary(t),'plan':v};break;}default:throw new Error('Unknown\x20benchmark_migration_operation\x20action:\x20'+String(b['action']));}return{'content':[{'type':'text','text':JSON['stringify']({'result':d})}],'structuredContent':{'result':d}};}
@@ -1 +1 @@
1
- import{listServices,getServiceInfo,toggle as a422a,setEnabled as a422b,reset as a422c}from'../../config/index.js';import{judgmentStatus,setJudgmentOverride,clearJudgmentOverride,clearJudgmentOverrides,patchUserJudgmentDoc,readUserJudgmentDocView}from'../../config/judgment.js';import{strictParse}from'../../schema/index.js';import{ConfigOperationInputSchema}from'../../schema/config/index.js';export async function handleConfigOperation(a){const b=strictParse(ConfigOperationInputSchema,a,'config_operation\x20input'),{action:c,service:d,path:e,value:f}=b;let g;switch(c){case'list':g={'action':'list','services':listServices()};break;case'toggle':{if(!d)throw new Error('\x27service\x27\x20param\x20is\x20required\x20for\x20toggle');const h=d,i=getServiceInfo(h);if(!i)throw new Error('Unknown\x20service:\x20'+h+'.\x20Use\x20action=\x27list\x27\x20to\x20see\x20all\x20valid\x20services.');if(h==='confirm_gate'&&i['enabled'])throw new Error('confirm_gate\x20cannot\x20be\x20disabled\x20at\x20runtime.\x20'+'Set\x20WOWOK_CONFIRM_GATE=0\x20in\x20the\x20server\x20environment\x20and\x20restart\x20if\x20you\x20really\x20want\x20it\x20off.');const j=a422a(h);g={'action':'toggle','service':h,'enabled':j,'reminder':i['reminder']};break;}case'disable':{if(!d)throw new Error('\x27service\x27\x20param\x20is\x20required\x20for\x20disable');const k=d,l=getServiceInfo(k);if(!l)throw new Error('Unknown\x20service:\x20'+k+'.\x20Use\x20action=\x27list\x27\x20to\x20see\x20all\x20valid\x20services.');if(k==='confirm_gate')throw new Error('confirm_gate\x20cannot\x20be\x20disabled\x20at\x20runtime.\x20'+'Set\x20WOWOK_CONFIRM_GATE=0\x20in\x20the\x20server\x20environment\x20and\x20restart\x20if\x20you\x20really\x20want\x20it\x20off.');a422b(k,![]),g={'action':'disable','service':k,'enabled':![],'reminder':l['reminder']};break;}case'enable':{if(!d)throw new Error('\x27service\x27\x20param\x20is\x20required\x20for\x20enable');const m=d,n=getServiceInfo(m);if(!n)throw new Error('Unknown\x20service:\x20'+m+'.\x20Use\x20action=\x27list\x27\x20to\x20see\x20all\x20valid\x20services.');a422b(m,!![]),g={'action':'enable','service':m,'enabled':!![],'reminder':n['reminder']};break;}case'reset':{if(!d)throw new Error('\x27service\x27\x20param\x20is\x20required\x20for\x20reset');const o=d,p=getServiceInfo(o);if(!p)throw new Error('Unknown\x20service:\x20'+o+'.\x20Use\x20action=\x27list\x27\x20to\x20see\x20all\x20valid\x20services.');a422c(o),g={'action':'reset','service':o,'enabled':getServiceInfo(o)?.['enabled'],'reminder':p['reminder'],'reset':!![]};break;}case'info':{if(!d)throw new Error('\x27service\x27\x20param\x20is\x20required\x20for\x20info');const q=d,r=getServiceInfo(q);if(!r)throw new Error('Unknown\x20service:\x20'+q+'.\x20Use\x20action=\x27list\x27\x20to\x20see\x20all\x20valid\x20services.');g={'action':'info',...r};break;}case'judgment_list':g={'action':'judgment_list',...judgmentStatus()};break;case'judgment_set':{if(!e)throw new Error('\x27path\x27\x20param\x20is\x20required\x20for\x20judgment_set\x20(dotted,\x20e.g.\x20\x27evaluation.weights.trust_reviews\x27)');if(!('value'in b))throw new Error('\x27value\x27\x20param\x20is\x20required\x20for\x20judgment_set');const s=setJudgmentOverride(e,f);if(!s['ok'])throw new Error(s['error']);g={'action':'judgment_set','path':e,'value':f,'applied':!![]};break;}case'judgment_reset':{const t=e?clearJudgmentOverride(e)?0x1:0x0:clearJudgmentOverrides();g={'action':'judgment_reset',...e?{'path':e}:{},'cleared':t};break;}case'judgment_doc_read':{g={'action':'judgment_doc_read',...readUserJudgmentDocView()};break;}case'judgment_doc_patch':{if(!b['patch']||typeof b['patch']!=='object'||Array['isArray'](b['patch']))throw new Error('\x27patch\x27\x20param\x20is\x20required\x20for\x20judgment_doc_patch\x20(a\x20partial\x20judgment\x20document\x20object,\x20e.g.\x20{\x22evaluation\x22:\x20{\x22weights\x22:\x20{…}}})');g={'action':'judgment_doc_patch',...patchUserJudgmentDoc(b['patch'])};break;}default:throw new Error('Unknown\x20config_operation\x20action:\x20'+String(c));}return{'content':[{'type':'text','text':JSON['stringify']({'result':g})}],'structuredContent':{'result':g}};}
1
+ import{listServices,getServiceInfo,toggle as a438a,setEnabled as a438b,reset as a438c}from'../../config/index.js';import{judgmentStatus,setJudgmentOverride,clearJudgmentOverride,clearJudgmentOverrides,patchUserJudgmentDoc,readUserJudgmentDocView}from'../../config/judgment.js';import{strictParse}from'../../schema/index.js';import{ConfigOperationInputSchema}from'../../schema/config/index.js';export async function handleConfigOperation(a){const b=strictParse(ConfigOperationInputSchema,a,'config_operation\x20input'),{action:c,service:d,path:e,value:f}=b;let g;switch(c){case'list':g={'action':'list','services':listServices()};break;case'toggle':{if(!d)throw new Error('\x27service\x27\x20param\x20is\x20required\x20for\x20toggle');const h=d,i=getServiceInfo(h);if(!i)throw new Error('Unknown\x20service:\x20'+h+'.\x20Use\x20action=\x27list\x27\x20to\x20see\x20all\x20valid\x20services.');if(h==='confirm_gate'&&i['enabled'])throw new Error('confirm_gate\x20cannot\x20be\x20disabled\x20at\x20runtime.\x20'+'Set\x20WOWOK_CONFIRM_GATE=0\x20in\x20the\x20server\x20environment\x20and\x20restart\x20if\x20you\x20really\x20want\x20it\x20off.');const j=a438a(h);g={'action':'toggle','service':h,'enabled':j,'reminder':i['reminder']};break;}case'disable':{if(!d)throw new Error('\x27service\x27\x20param\x20is\x20required\x20for\x20disable');const k=d,l=getServiceInfo(k);if(!l)throw new Error('Unknown\x20service:\x20'+k+'.\x20Use\x20action=\x27list\x27\x20to\x20see\x20all\x20valid\x20services.');if(k==='confirm_gate')throw new Error('confirm_gate\x20cannot\x20be\x20disabled\x20at\x20runtime.\x20'+'Set\x20WOWOK_CONFIRM_GATE=0\x20in\x20the\x20server\x20environment\x20and\x20restart\x20if\x20you\x20really\x20want\x20it\x20off.');a438b(k,![]),g={'action':'disable','service':k,'enabled':![],'reminder':l['reminder']};break;}case'enable':{if(!d)throw new Error('\x27service\x27\x20param\x20is\x20required\x20for\x20enable');const m=d,n=getServiceInfo(m);if(!n)throw new Error('Unknown\x20service:\x20'+m+'.\x20Use\x20action=\x27list\x27\x20to\x20see\x20all\x20valid\x20services.');a438b(m,!![]),g={'action':'enable','service':m,'enabled':!![],'reminder':n['reminder']};break;}case'reset':{if(!d)throw new Error('\x27service\x27\x20param\x20is\x20required\x20for\x20reset');const o=d,p=getServiceInfo(o);if(!p)throw new Error('Unknown\x20service:\x20'+o+'.\x20Use\x20action=\x27list\x27\x20to\x20see\x20all\x20valid\x20services.');a438c(o),g={'action':'reset','service':o,'enabled':getServiceInfo(o)?.['enabled'],'reminder':p['reminder'],'reset':!![]};break;}case'info':{if(!d)throw new Error('\x27service\x27\x20param\x20is\x20required\x20for\x20info');const q=d,r=getServiceInfo(q);if(!r)throw new Error('Unknown\x20service:\x20'+q+'.\x20Use\x20action=\x27list\x27\x20to\x20see\x20all\x20valid\x20services.');g={'action':'info',...r};break;}case'judgment_list':g={'action':'judgment_list',...judgmentStatus()};break;case'judgment_set':{if(!e)throw new Error('\x27path\x27\x20param\x20is\x20required\x20for\x20judgment_set\x20(dotted,\x20e.g.\x20\x27evaluation.weights.trust_reviews\x27)');if(!('value'in b))throw new Error('\x27value\x27\x20param\x20is\x20required\x20for\x20judgment_set');const s=setJudgmentOverride(e,f);if(!s['ok'])throw new Error(s['error']);g={'action':'judgment_set','path':e,'value':f,'applied':!![]};break;}case'judgment_reset':{const t=e?clearJudgmentOverride(e)?0x1:0x0:clearJudgmentOverrides();g={'action':'judgment_reset',...e?{'path':e}:{},'cleared':t};break;}case'judgment_doc_read':{g={'action':'judgment_doc_read',...readUserJudgmentDocView()};break;}case'judgment_doc_patch':{if(!b['patch']||typeof b['patch']!=='object'||Array['isArray'](b['patch']))throw new Error('\x27patch\x27\x20param\x20is\x20required\x20for\x20judgment_doc_patch\x20(a\x20partial\x20judgment\x20document\x20object,\x20e.g.\x20{\x22evaluation\x22:\x20{\x22weights\x22:\x20{…}}})');g={'action':'judgment_doc_patch',...patchUserJudgmentDoc(b['patch'])};break;}default:throw new Error('Unknown\x20config_operation\x20action:\x20'+String(c));}return{'content':[{'type':'text','text':JSON['stringify']({'result':g})}],'structuredContent':{'result':g}};}
@@ -1 +1 @@
1
- import{readdirSync,readFileSync,writeFileSync,existsSync,mkdirSync,statSync,cpSync,renameSync,rmSync}from'node:fs';import{join,relative,resolve,sep,dirname,basename}from'node:path';import{strictParse}from'../../schema/index.js';import{IndustryPackOperationInputSchema}from'../../schema/industry-pack/index.js';import{validateJudgmentFragment}from'../../config/judgment.js';import{scaffoldIndustryPack,listRegisteredPacks,scanDefaultIndustryPacks,seedBuiltinIndustryTemplates,seedBuiltinStrategyManuals,ensureIndustryReadme,resolveIndustryPackDir,rescanPack,resolveDisputeRules,resolveComplianceRules,resolveSupplyRules,resolveIndustryRules,resolveIndustryPlaybook,diffIndustryPack,resetIndustryPath}from'../../extensions/index.js';import{getIndustryModeRegistry}from'../../extensions/registry.js';import{handleRecommendIndustry,handleListModes,handleDeriveUserMode,handleEvolveUserMode,handleRegisterUserMode,handleUnregisterUserMode,handleRegisterCustomMetric,handleUnregisterCustomMetric,handleRegisterCustomConstraint,handleUnregisterCustomConstraint,handleListMetricsConstraints}from'../../playbooks/service-build/mode-actions.js';const INDUSTRY_ROOT=resolveIndustryPackDir();function resolveIndustryPath(a){const b=resolve(INDUSTRY_ROOT,a);if(b!==INDUSTRY_ROOT&&!b['startsWith'](INDUSTRY_ROOT+sep))throw new Error('path\x20\x27'+a+'\x27\x20escapes\x20the\x20industry\x20root');return b;}function rescanAffectedPack(a){const b=a['split'](/[\\/]+/)['find'](c=>c['length']>0x0);if(!b)return;rescanPack(b);}const BASELINES_FILENAME='baselines.json',PACK_FILENAME='pack.json';function assertBaselinesContentValid(a,b){const c=a['split'](/[\\/]+/)['pop']()??'';if(c!==BASELINES_FILENAME&&c!==PACK_FILENAME)return;let d;try{d=JSON['parse'](b);}catch{return;}if(!d||typeof d!=='object'||Array['isArray'](d))return;const e=d,f=c===BASELINES_FILENAME?d:e['baselines'];if(f===undefined||f===null)return;const g=validateJudgmentFragment(f,a+'\x20baselines');if(g)throw new Error('write\x20rejected\x20—\x20the\x20baselines\x20fragment\x20in\x20\x27'+a+'\x27\x20is\x20not\x20a\x20valid\x20judgment\x20fragment:\x20'+g);}function listRecursive(a,b,c,d=0x0){if(d>0x8)return;let f;try{f=readdirSync(a,{'withFileTypes':!![]});}catch{return;}for(const g of f){const h=join(a,g['name']),i=relative(b,h)['split'](sep)['join']('/');let j=0x0,k=0x0;try{const l=statSync(h);k=l['size'],j=l['mtimeMs'];}catch{}g['isDirectory']()?(c['push']({'path':i,'is_dir':!![],'size':0x0,'mtime':j}),listRecursive(h,b,c,d+0x1)):c['push']({'path':i,'is_dir':![],'size':k,'mtime':j});}}export async function handleIndustryPackOperation(a){const b=strictParse(IndustryPackOperationInputSchema,a,'industry_pack_operation\x20input');mkdirSync(INDUSTRY_ROOT,{'recursive':!![]}),seedBuiltinIndustryTemplates(),seedBuiltinStrategyManuals(),ensureIndustryReadme();let c;switch(b['action']){case'scaffold':{if(!b['name'])throw new Error('\x27name\x27\x20is\x20required\x20for\x20action=\x27scaffold\x27');const d=scaffoldIndustryPack(b['name']);c={'action':'scaffold','ok':d['ok'],'dir':d['dir'],'files':d['files'],'errors':d['errors']};if(d['ok'])rescanPack(b['name']);break;}case'list':{c={'action':'list','packs':listRegisteredPacks()};break;}case'scan':{c={'action':'scan','results':scanDefaultIndustryPacks()};break;}case'resolve':{c={'action':'resolve','dir':INDUSTRY_ROOT};break;}case'list_files':{const e=[];listRecursive(INDUSTRY_ROOT,INDUSTRY_ROOT,e),c={'action':'list_files','dir':INDUSTRY_ROOT,'files':e};break;}case'read_file':{if(!b['path'])throw new Error('\x27path\x27\x20is\x20required\x20for\x20action=\x27read_file\x27');const f=resolveIndustryPath(b['path']);if(!existsSync(f))throw new Error('file\x20not\x20found:\x20'+b['path']);c={'action':'read_file','path':f,'content':readFileSync(f,'utf-8')};break;}case'write_file':{if(!b['path'])throw new Error('\x27path\x27\x20is\x20required\x20for\x20action=\x27write_file\x27');if(b['content']===undefined)throw new Error('\x27content\x27\x20is\x20required\x20for\x20action=\x27write_file\x27');const g=resolveIndustryPath(b['path']);assertBaselinesContentValid(b['path'],b['content']),mkdirSync(dirname(g),{'recursive':!![]}),writeFileSync(g,b['content'],'utf-8'),c={'action':'write_file','path':g,'ok':!![]},rescanAffectedPack(b['path']);break;}case'get':{if(!b['name'])throw new Error('\x27name\x27\x20is\x20required\x20for\x20action=\x27get\x27');const h=b['name'],i=getIndustryModeRegistry()['getMode'](h),j=i?{'name':i['name'],'display_name':i['display_name'],'key_risk':i['key_risk'],'needs':i['needs']['map'](k=>k['description']),...i['analyze']?.['key_questions']?.['length']?{'analyze_questions':i['analyze']['key_questions']['slice'](0x0,0x2)}:{}}:undefined;c={'action':'get','category':h,...j?{'mode':j}:{},...resolveDisputeRules(h)?{'dispute':resolveDisputeRules(h)}:{},...resolveComplianceRules(h)?{'compliance':resolveComplianceRules(h)}:{},...resolveSupplyRules(h)?{'supply':resolveSupplyRules(h)}:{},...resolveIndustryRules(h)?{'rules':resolveIndustryRules(h)}:{},...resolveIndustryPlaybook(h)?{'playbook':resolveIndustryPlaybook(h)}:{}};break;}case'diff':{if(!b['name'])throw new Error('\x27name\x27\x20is\x20required\x20for\x20action=\x27diff\x27');c={'action':'diff',...diffIndustryPack(b['name'])};break;}case'reset':{if(!b['path'])throw new Error('\x27path\x27\x20is\x20required\x20for\x20action=\x27reset\x27');const k=resetIndustryPath(b['path']);c={'action':'reset','ok':k['ok'],'layout':k['layout'],'target':k['target'],'restored_files':k['restored_files'],'errors':k['errors']},rescanAffectedPack(b['path']);break;}case'delete_file':{if(!b['path'])throw new Error('\x27path\x27\x20is\x20required\x20for\x20action=\x27delete_file\x27');const l=resolveIndustryPath(b['path']);if(!existsSync(l))throw new Error('file\x20not\x20found:\x20'+b['path']);rmSync(l,{'recursive':!![],'force':!![]}),c={'action':'delete_file','path':l,'ok':!![]},rescanAffectedPack(b['path']);break;}case'create_file':{if(!b['path'])throw new Error('\x27path\x27\x20is\x20required\x20for\x20action=\x27create_file\x27');const m=resolveIndustryPath(b['path']);if(existsSync(m))throw new Error('file\x20already\x20exists:\x20'+b['path']);if(b['content']!==undefined)assertBaselinesContentValid(b['path'],b['content']);mkdirSync(dirname(m),{'recursive':!![]}),writeFileSync(m,b['content']??'','utf-8'),c={'action':'create_file','path':m,'ok':!![]},rescanAffectedPack(b['path']);break;}case'create_dir':{if(!b['path'])throw new Error('\x27path\x27\x20is\x20required\x20for\x20action=\x27create_dir\x27');const n=resolveIndustryPath(b['path']);mkdirSync(n,{'recursive':!![]}),c={'action':'create_dir','path':n,'ok':!![]},rescanAffectedPack(b['path']);break;}case'copy':{if(!b['from'])throw new Error('\x27from\x27\x20is\x20required\x20for\x20action=\x27copy\x27');if(!b['to'])throw new Error('\x27to\x27\x20is\x20required\x20for\x20action=\x27copy\x27');const o=resolveIndustryPath(b['from']);let p=resolveIndustryPath(b['to']);if(!existsSync(o))throw new Error('source\x20not\x20found:\x20'+b['from']);try{existsSync(p)&&statSync(p)['isDirectory']()&&(p=join(p,basename(o)));}catch{}if(p===o)throw new Error('\x27copy\x27\x20cannot\x20copy\x20a\x20file\x20onto\x20itself');mkdirSync(dirname(p),{'recursive':!![]}),cpSync(o,p,{'recursive':!![],'force':!![]}),c={'action':'copy','from':o,'to':p,'ok':!![]},rescanAffectedPack(b['to']);break;}case'move':case'rename':{if(!b['from'])throw new Error('\x27from\x27\x20is\x20required\x20for\x20action=\x27'+b['action']+'\x27');if(!b['to'])throw new Error('\x27to\x27\x20is\x20required\x20for\x20action=\x27'+b['action']+'\x27');const q=resolveIndustryPath(b['from']);let t=resolveIndustryPath(b['to']);if(!existsSync(q))throw new Error('source\x20not\x20found:\x20'+b['from']);try{existsSync(t)&&statSync(t)['isDirectory']()&&(t=join(t,basename(q)));}catch{}if(t===q)throw new Error('\x27'+b['action']+'\x27\x20cannot\x20move\x20onto\x20itself');mkdirSync(dirname(t),{'recursive':!![]}),renameSync(q,t),c={'action':b['action'],'from':q,'to':t,'ok':!![]},rescanAffectedPack(b['from']),rescanAffectedPack(b['to']);break;}case'recommend_industry':c=await handleRecommendIndustry(b);break;case'list_modes':c=await handleListModes();break;case'derive_user_mode':c=await handleDeriveUserMode(b);break;case'evolve_user_mode':c=await handleEvolveUserMode(b);break;case'register_user_mode':c=await handleRegisterUserMode(b);break;case'unregister_user_mode':c=await handleUnregisterUserMode(b);break;case'register_custom_metric':c=await handleRegisterCustomMetric(b);break;case'unregister_custom_metric':c=await handleUnregisterCustomMetric(b);break;case'register_custom_constraint':c=await handleRegisterCustomConstraint(b);break;case'unregister_custom_constraint':c=await handleUnregisterCustomConstraint(b);break;case'list_metrics_constraints':c=await handleListMetricsConstraints(b);break;default:throw new Error('Unknown\x20industry_pack_operation\x20action:\x20'+String(b['action']));}return{'content':[{'type':'text','text':JSON['stringify']({'result':c})}],'structuredContent':{'result':c}};}
1
+ import{readdirSync,readFileSync,writeFileSync,existsSync,mkdirSync,statSync,cpSync,renameSync,rmSync}from'node:fs';import{join,relative,resolve,sep,dirname,basename}from'node:path';import{strictParse}from'../../schema/index.js';import{IndustryPackOperationInputSchema}from'../../schema/industry-pack/index.js';import{validateJudgmentFragment}from'../../config/judgment.js';import{scaffoldIndustryPack,listRegisteredPacks,scanDefaultIndustryPacks,seedBuiltinIndustryTemplates,seedBuiltinStrategyManuals,ensureIndustryReadme,resolveIndustryPackDir,rescanPack,resolveDisputeRules,resolveComplianceRules,resolveSupplyRules,resolveIndustryRules,resolveIndustryPlaybook,diffIndustryPack,resetIndustryPath}from'../../extensions/index.js';import{getIndustryModeRegistry}from'../../extensions/registry.js';import{handleRecommendIndustry,handleListModes,handleDeriveUserMode,handleEvolveUserMode,handleRegisterUserMode,handleUnregisterUserMode,handleRegisterCustomMetric,handleUnregisterCustomMetric,handleRegisterCustomConstraint,handleUnregisterCustomConstraint,handleListMetricsConstraints}from'../../playbooks/service-build/mode-actions.js';import{repairBuiltinTemplates,builtinTemplateDrift,resolveTemplatesDir}from'../../knowledge/template-loader.js';const INDUSTRY_ROOT=resolveIndustryPackDir(),resolveTemplatesDirSafe=resolveTemplatesDir;function resolveIndustryPath(a){const b=resolve(INDUSTRY_ROOT,a);if(b!==INDUSTRY_ROOT&&!b['startsWith'](INDUSTRY_ROOT+sep))throw new Error('path\x20\x27'+a+'\x27\x20escapes\x20the\x20industry\x20root');return b;}function isTemplateTreePath(a){const b=a['split'](/[\\/]+/)['filter'](c=>c['length']>0x0);return b['length']>=0x2&&b[0x1]==='templates';}function assertTemplateWriteAuthorized(a,b,c){if(c===!![])return;const d=b['find'](e=>e!==undefined&&isTemplateTreePath(e));if(!d)return;throw new Error('action=\x27'+a+'\x27\x20modifies\x20the\x20user-editable\x20template\x20file\x20\x27'+d+'\x27.\x20'+'Present\x20the\x20intended\x20change\x20to\x20the\x20user\x20first;\x20after\x20the\x20user\x20explicitly\x20confirms,\x20'+'re-call\x20with\x20authorize=true\x20(C5).');}function rescanAffectedPack(a){const b=a['split'](/[\\/]+/)['find'](c=>c['length']>0x0);if(!b)return;rescanPack(b);}const BASELINES_FILENAME='baselines.json',PACK_FILENAME='pack.json';function assertBaselinesContentValid(a,b){const c=a['split'](/[\\/]+/)['pop']()??'';if(c!==BASELINES_FILENAME&&c!==PACK_FILENAME)return;let d;try{d=JSON['parse'](b);}catch{return;}if(!d||typeof d!=='object'||Array['isArray'](d))return;const e=d,f=c===BASELINES_FILENAME?d:e['baselines'];if(f===undefined||f===null)return;const g=validateJudgmentFragment(f,a+'\x20baselines');if(g)throw new Error('write\x20rejected\x20—\x20the\x20baselines\x20fragment\x20in\x20\x27'+a+'\x27\x20is\x20not\x20a\x20valid\x20judgment\x20fragment:\x20'+g);}function listRecursive(a,b,c,d=0x0){if(d>0x8)return;let f;try{f=readdirSync(a,{'withFileTypes':!![]});}catch{return;}for(const g of f){const h=join(a,g['name']),i=relative(b,h)['split'](sep)['join']('/');let j=0x0,k=0x0;try{const l=statSync(h);k=l['size'],j=l['mtimeMs'];}catch{}g['isDirectory']()?(c['push']({'path':i,'is_dir':!![],'size':0x0,'mtime':j}),listRecursive(h,b,c,d+0x1)):c['push']({'path':i,'is_dir':![],'size':k,'mtime':j});}}export async function handleIndustryPackOperation(a){const b=strictParse(IndustryPackOperationInputSchema,a,'industry_pack_operation\x20input');mkdirSync(INDUSTRY_ROOT,{'recursive':!![]}),seedBuiltinIndustryTemplates(),seedBuiltinStrategyManuals(),ensureIndustryReadme();let c;switch(b['action']){case'scaffold':{if(!b['name'])throw new Error('\x27name\x27\x20is\x20required\x20for\x20action=\x27scaffold\x27');const d=scaffoldIndustryPack(b['name']);c={'action':'scaffold','ok':d['ok'],'dir':d['dir'],'files':d['files'],'errors':d['errors']};if(d['ok'])rescanPack(b['name']);break;}case'list':{c={'action':'list','packs':listRegisteredPacks()};break;}case'scan':{c={'action':'scan','results':scanDefaultIndustryPacks()};break;}case'repair_builtin_templates':{if(b['authorize']!==!![]){const g=repairBuiltinTemplates({'backup':!![],'dryRun':!![]}),h=g['filter'](i=>i['status']==='would_update');c={'action':'repair_builtin_templates','dir':resolveTemplatesDirSafe(),'reseeded_count':0x0,'requires_authorization':!![],'results':g,'note':h['length']?'PLAN\x20ONLY\x20(no\x20writes)\x20—\x20'+h['length']+'\x20legacy\x20sentinel-less\x20builtin\x20file(s)\x20would\x20be\x20reseeded\x20from\x20the\x20in-code\x20catalog,\x20each\x20previous\x20body\x20preserved\x20as\x20<file>.bak.\x20Present\x20this\x20plan\x20to\x20the\x20user;\x20after\x20the\x20user\x20explicitly\x20confirms,\x20re-call\x20with\x20authorize=true\x20to\x20execute.':'No\x20legacy\x20sentinel-less\x20builtin\x20files\x20found\x20—\x20every\x20builtin\x20template\x20already\x20carries\x20a\x20release\x20sentinel.'};break;}const e=repairBuiltinTemplates({'backup':!![]}),f=e['filter'](i=>i['status']==='updated');c={'action':'repair_builtin_templates','dir':resolveTemplatesDirSafe(),'reseeded_count':f['length'],'results':e,'note':f['length']?'Legacy\x20sentinel-less\x20builtin\x20files\x20were\x20reseeded\x20from\x20the\x20in-code\x20catalog.\x20Each\x20previous\x20body\x20is\x20preserved\x20as\x20<file>.bak.':'No\x20legacy\x20sentinel-less\x20builtin\x20files\x20found\x20—\x20every\x20builtin\x20template\x20already\x20carries\x20a\x20release\x20sentinel.'};break;}case'template_drift':{const i=builtinTemplateDrift();c={'action':'template_drift','dir':resolveTemplatesDirSafe(),'drift_count':i['length'],'drift':i,'note':i['length']?'On-disk\x20builtin\x20templates\x20differ\x20from\x20the\x20in-code\x20catalog.\x20Run\x20action=\x27repair_builtin_templates\x27\x20to\x20reseed.':'Every\x20builtin\x20template\x20on\x20disk\x20matches\x20the\x20in-code\x20catalog.'};break;}case'resolve':{c={'action':'resolve','dir':INDUSTRY_ROOT};break;}case'list_files':{const j=[];listRecursive(INDUSTRY_ROOT,INDUSTRY_ROOT,j),c={'action':'list_files','dir':INDUSTRY_ROOT,'files':j};break;}case'read_file':{if(!b['path'])throw new Error('\x27path\x27\x20is\x20required\x20for\x20action=\x27read_file\x27');const k=resolveIndustryPath(b['path']);if(!existsSync(k))throw new Error('file\x20not\x20found:\x20'+b['path']);c={'action':'read_file','path':k,'content':readFileSync(k,'utf-8')};break;}case'write_file':{if(!b['path'])throw new Error('\x27path\x27\x20is\x20required\x20for\x20action=\x27write_file\x27');if(b['content']===undefined)throw new Error('\x27content\x27\x20is\x20required\x20for\x20action=\x27write_file\x27');assertTemplateWriteAuthorized('write_file',[b['path']],b['authorize']);const l=resolveIndustryPath(b['path']);assertBaselinesContentValid(b['path'],b['content']),mkdirSync(dirname(l),{'recursive':!![]}),writeFileSync(l,b['content'],'utf-8'),c={'action':'write_file','path':l,'ok':!![]},rescanAffectedPack(b['path']);break;}case'get':{if(!b['name'])throw new Error('\x27name\x27\x20is\x20required\x20for\x20action=\x27get\x27');const m=b['name'],n=getIndustryModeRegistry()['getMode'](m),o=n?{'name':n['name'],'display_name':n['display_name'],'key_risk':n['key_risk'],'needs':n['needs']['map'](p=>p['description']),...n['analyze']?.['key_questions']?.['length']?{'analyze_questions':n['analyze']['key_questions']['slice'](0x0,0x2)}:{}}:undefined;c={'action':'get','category':m,...o?{'mode':o}:{},...resolveDisputeRules(m)?{'dispute':resolveDisputeRules(m)}:{},...resolveComplianceRules(m)?{'compliance':resolveComplianceRules(m)}:{},...resolveSupplyRules(m)?{'supply':resolveSupplyRules(m)}:{},...resolveIndustryRules(m)?{'rules':resolveIndustryRules(m)}:{},...resolveIndustryPlaybook(m)?{'playbook':resolveIndustryPlaybook(m)}:{}};break;}case'diff':{if(!b['name'])throw new Error('\x27name\x27\x20is\x20required\x20for\x20action=\x27diff\x27');c={'action':'diff',...diffIndustryPack(b['name'])};break;}case'reset':{if(!b['path'])throw new Error('\x27path\x27\x20is\x20required\x20for\x20action=\x27reset\x27');assertTemplateWriteAuthorized('reset',[b['path']],b['authorize']);const p=resetIndustryPath(b['path']);c={'action':'reset','ok':p['ok'],'layout':p['layout'],'target':p['target'],'restored_files':p['restored_files'],'errors':p['errors']},rescanAffectedPack(b['path']);break;}case'delete_file':{if(!b['path'])throw new Error('\x27path\x27\x20is\x20required\x20for\x20action=\x27delete_file\x27');assertTemplateWriteAuthorized('delete_file',[b['path']],b['authorize']);const q=resolveIndustryPath(b['path']);if(!existsSync(q))throw new Error('file\x20not\x20found:\x20'+b['path']);rmSync(q,{'recursive':!![],'force':!![]}),c={'action':'delete_file','path':q,'ok':!![]},rescanAffectedPack(b['path']);break;}case'create_file':{if(!b['path'])throw new Error('\x27path\x27\x20is\x20required\x20for\x20action=\x27create_file\x27');const t=resolveIndustryPath(b['path']);if(existsSync(t))throw new Error('file\x20already\x20exists:\x20'+b['path']);if(b['content']!==undefined)assertBaselinesContentValid(b['path'],b['content']);mkdirSync(dirname(t),{'recursive':!![]}),writeFileSync(t,b['content']??'','utf-8'),c={'action':'create_file','path':t,'ok':!![]},rescanAffectedPack(b['path']);break;}case'create_dir':{if(!b['path'])throw new Error('\x27path\x27\x20is\x20required\x20for\x20action=\x27create_dir\x27');const u=resolveIndustryPath(b['path']);mkdirSync(u,{'recursive':!![]}),c={'action':'create_dir','path':u,'ok':!![]},rescanAffectedPack(b['path']);break;}case'copy':{if(!b['from'])throw new Error('\x27from\x27\x20is\x20required\x20for\x20action=\x27copy\x27');if(!b['to'])throw new Error('\x27to\x27\x20is\x20required\x20for\x20action=\x27copy\x27');const v=resolveIndustryPath(b['from']);let w=resolveIndustryPath(b['to']);if(!existsSync(v))throw new Error('source\x20not\x20found:\x20'+b['from']);try{existsSync(w)&&statSync(w)['isDirectory']()&&(w=join(w,basename(v)));}catch{}if(w===v)throw new Error('\x27copy\x27\x20cannot\x20copy\x20a\x20file\x20onto\x20itself');existsSync(w)&&isTemplateTreePath(b['to'])&&assertTemplateWriteAuthorized('copy',[b['to']],b['authorize']);mkdirSync(dirname(w),{'recursive':!![]}),cpSync(v,w,{'recursive':!![],'force':!![]}),c={'action':'copy','from':v,'to':w,'ok':!![]},rescanAffectedPack(b['to']);break;}case'move':case'rename':{if(!b['from'])throw new Error('\x27from\x27\x20is\x20required\x20for\x20action=\x27'+b['action']+'\x27');if(!b['to'])throw new Error('\x27to\x27\x20is\x20required\x20for\x20action=\x27'+b['action']+'\x27');assertTemplateWriteAuthorized(b['action'],[b['from'],b['to']],b['authorize']);const x=resolveIndustryPath(b['from']);let y=resolveIndustryPath(b['to']);if(!existsSync(x))throw new Error('source\x20not\x20found:\x20'+b['from']);try{existsSync(y)&&statSync(y)['isDirectory']()&&(y=join(y,basename(x)));}catch{}if(y===x)throw new Error('\x27'+b['action']+'\x27\x20cannot\x20move\x20onto\x20itself');mkdirSync(dirname(y),{'recursive':!![]}),renameSync(x,y),c={'action':b['action'],'from':x,'to':y,'ok':!![]},rescanAffectedPack(b['from']),rescanAffectedPack(b['to']);break;}case'recommend_industry':c=await handleRecommendIndustry(b);break;case'list_modes':c=await handleListModes();break;case'derive_user_mode':c=await handleDeriveUserMode(b);break;case'evolve_user_mode':c=await handleEvolveUserMode(b);break;case'register_user_mode':c=await handleRegisterUserMode(b);break;case'unregister_user_mode':c=await handleUnregisterUserMode(b);break;case'register_custom_metric':c=await handleRegisterCustomMetric(b);break;case'unregister_custom_metric':c=await handleUnregisterCustomMetric(b);break;case'register_custom_constraint':c=await handleRegisterCustomConstraint(b);break;case'unregister_custom_constraint':c=await handleUnregisterCustomConstraint(b);break;case'list_metrics_constraints':c=await handleListMetricsConstraints(b);break;default:throw new Error('Unknown\x20industry_pack_operation\x20action:\x20'+String(b['action']));}return{'content':[{'type':'text','text':JSON['stringify']({'result':c})}],'structuredContent':{'result':c}};}
@@ -1 +1 @@
1
- import{strictParse,MessengerOperationInputSchema}from'../../schema/index.js';import{watch_conversations,send_message,send_file,watch_messages,export_attachment,pull_messages,generate_wts,verify_wts,sign_wts,wts2html,proof_message,mark_messages_as_viewed,mark_conversation_as_viewed,blacklist,friendslist,guardlist,settings,LocalInfo}from'@wowok/wowok';import{classifyError,buildDataSemantic}from'../../schema/call/semantic.js';import{classifyCommunicationEvidence}from'../../communication/evidence.js';import{goalEngine}from'../../goal/GoalEngine.js';export function normalizeAccountOrMark(a){if(typeof a==='string')return{'name_or_address':a,'local_mark_first':!![]};return a;}export function normalizeOptionalAccountOrMark(a){if(a===undefined||a===null)return undefined;return normalizeAccountOrMark(a);}export function normalizeManyAccountOrMark(a){if(a===undefined||a===null)return undefined;if(Array['isArray'](a))return{'entities':a['map'](b=>typeof b==='string'?{'name_or_address':b,'local_mark_first':!![]}:b),'check_all_founded':!![]};return a;}function communicationEvidencePayload(a,b){const c=b??{};switch(a){case'send_message':case'send_file':{const d=typeof c['messageId']==='string'?c['messageId']:undefined;return{'detail':d?'message\x20'+d:'message\x20sent','data':d?{'message_id':d}:{}};}case'send_required_info':{const e=typeof c['messageId']==='string'?c['messageId']:undefined,f=Array['isArray'](c['sent_fields'])?c['sent_fields']:undefined;return{'detail':'required-info\x20confirmation\x20sent','data':{...e?{'message_id':e}:{},...f?{'sent_fields':f}:{}}};}case'generate_wts':{const g=typeof c['totalMessageCount']==='number'?c['totalMessageCount']:undefined,h=Array['isArray'](c['files'])?c['files']:undefined,i=Array['isArray'](c['htmlFiles'])?c['htmlFiles']:undefined;return{'detail':'WTS\x20evidence\x20packet\x20generated','data':{...g!==undefined?{'message_count':g}:{},...h?{'files':h}:{},...i?{'html_reports':i}:{}}};}case'verify_wts':{return{'detail':'WTS\x20evidence\x20verification','data':{'valid':c['valid']===!![]}};}case'sign_wts':{return{'detail':typeof b==='string'?b:'WTS\x20evidence\x20signed','data':{}};}case'proof_message':{const j=typeof c['proofAddress']==='string'?c['proofAddress']:undefined;return{'detail':j?'proof\x20'+j:'message\x20proofed\x20on-chain','data':j?{'proof_address':j}:{}};}default:return{'detail':a,'data':{}};}}export async function handleMessengerOperation(a){let b;try{b=strictParse(MessengerOperationInputSchema,a,'messenger_operation\x20input');const c=b['operation'];let d;switch(b['operation']){case'watch_conversations':{const g=await watch_conversations(b['filter']);d={'operation':'watch_conversations','result':g};break;}case'send_message':{const h=await send_message(normalizeOptionalAccountOrMark(b['from']),normalizeAccountOrMark(b['to']),b['content'],b['options']);if(h['authRequired']){d={'operation':'send_message','result':h};break;}const i=h,j={...i,'merkleData':i['merkleData']?{'leafIndex':i['merkleData']['leafIndex'],'prevRoot':i['merkleData']['prevRoot'],'newRoot':i['merkleData']['newRoot'],'serverSignature':i['merkleData']['serverSignature'],'serverTimestamp':i['merkleData']['serverTimestamp'],'serverPublicKey':i['merkleData']['serverPublicKey']}:undefined};d={'operation':'send_message','result':j};break;}case'send_file':{const k=await send_file(normalizeOptionalAccountOrMark(b['from']),normalizeAccountOrMark(b['to']),b['filePath'],b['options']),l=k,m={...l,'merkleData':l['merkleData']?{'leafIndex':l['merkleData']['leafIndex'],'prevRoot':l['merkleData']['prevRoot'],'newRoot':l['merkleData']['newRoot'],'serverSignature':l['merkleData']['serverSignature'],'serverTimestamp':l['merkleData']['serverTimestamp'],'serverPublicKey':l['merkleData']['serverPublicKey']}:undefined};d={'operation':'send_file','result':m};break;}case'send_required_info':{let n=b['content'];const o=[];if(!n){const s=await LocalInfo['Instance']()['list'](),t=b['fields'],u=t&&t['length']>0x0?s['filter'](v=>t['includes'](v['name'])):s;if(u['length']===0x0)throw new Error('No\x20LocalInfo\x20fields\x20available.\x20Add\x20private\x20info\x20first\x20via\x20local_info_operation.');n=u['map'](v=>v['name']+':\x20'+v['default'])['join']('\x0a'),o['push'](...u['map'](v=>v['name']));}const p=await send_message(normalizeOptionalAccountOrMark(b['from']),normalizeAccountOrMark(b['to']),n,b['options']),q=p,r={...q,'merkleData':q['merkleData']?{'leafIndex':q['merkleData']['leafIndex'],'prevRoot':q['merkleData']['prevRoot'],'newRoot':q['merkleData']['newRoot'],'serverSignature':q['merkleData']['serverSignature'],'serverTimestamp':q['merkleData']['serverTimestamp'],'serverPublicKey':q['merkleData']['serverPublicKey']}:undefined,'sent_fields':o};d={'operation':'send_required_info','result':r};break;}case'watch_messages':{const v=b['filter']?{...b['filter'],'peerAddress':b['filter']['peerAddress']?normalizeAccountOrMark(b['filter']['peerAddress']):undefined,'account':b['filter']['account']?normalizeOptionalAccountOrMark(b['filter']['account']):undefined}:undefined,w=await watch_messages(v);d={'operation':'watch_messages','result':w};break;}case'save_attachment':{const x=await export_attachment(normalizeOptionalAccountOrMark(b['account']),b['messageId'],{'outputDir':b['outputDir'],'saveAs':b['saveAs']});d={'operation':'save_attachment','result':x};break;}case'generate_wts':{const y=b['params']?{...b['params'],'peerAccount':normalizeAccountOrMark(b['params']['peerAccount']),'myAccount':normalizeOptionalAccountOrMark(b['params']['myAccount'])}:undefined,z=await generate_wts(y);d={'operation':'generate_wts','result':z};break;}case'verify_wts':{const A=await verify_wts(b['wtsFilePath']);d={'operation':'verify_wts','result':A};break;}case'sign_wts':{const B=await sign_wts(b['wtsFilePath'],normalizeOptionalAccountOrMark(b['account']),b['outputPath']);d={'operation':'sign_wts','result':B};break;}case'wts2html':{const C=await wts2html(b['wtsPath'],b['options']);d={'operation':'wts2html','result':C};break;}case'proof_message':{const D=await proof_message(normalizeOptionalAccountOrMark(b['account']),b['messageId'],b['network']);d={'operation':'proof_message','result':D};break;}case'blacklist':{const E={'account':normalizeOptionalAccountOrMark(b['account']),'op':b['blacklist']['op']};'users'in b['blacklist']&&(E['users']=normalizeManyAccountOrMark(b['blacklist']['users']));const F=await blacklist(E);d={'operation':'blacklist','op':b['blacklist']['op'],'result':F['result']};break;}case'friendslist':{const G={'account':normalizeOptionalAccountOrMark(b['account']),'op':b['friendslist']['op']};'users'in b['friendslist']&&(G['users']=normalizeManyAccountOrMark(b['friendslist']['users']));const H=await friendslist(G);d={'operation':'friendslist','op':b['friendslist']['op'],'result':H['result']};break;}case'guardlist':{const I=await guardlist({'account':normalizeOptionalAccountOrMark(b['account']),...b['guardlist']});d={'operation':'guardlist','op':b['guardlist']['op'],'result':I['result']};break;}case'settings':{const J=await settings({'account':normalizeOptionalAccountOrMark(b['account']),...b['settings']});d={'operation':'settings','op':b['settings']['op'],'result':J['result']};break;}case'mark_messages_as_viewed':{const K=await mark_messages_as_viewed(b['messageIds'],normalizeOptionalAccountOrMark(b['account']));d={'operation':'mark_messages_as_viewed','result':K};break;}case'mark_conversation_as_viewed':{const L=await mark_conversation_as_viewed(normalizeAccountOrMark(b['peerAddress']),normalizeOptionalAccountOrMark(b['account']));d={'operation':'mark_conversation_as_viewed','result':L};break;}case'pull_messages':{const M=await pull_messages(normalizeOptionalAccountOrMark(b['account']),b['limit'],{'allAccounts':b['allAccounts'],'accounts':b['accounts']?.['map'](N=>normalizeAccountOrMark(N)),'concurrency':b['concurrency']});d={'operation':'pull_messages','result':M};break;}default:throw new Error('Unknown\x20messenger\x20operation:\x20'+c);}const e=classifyCommunicationEvidence(c),f=b['goal_id'];if(e&&f){const N=d['result'],{detail:O,data:P}=communicationEvidencePayload(c,N);await goalEngine['recordCommunicationEvidence'](f,{'operation':c,'kind':e['kind'],'title':e['title'],'detail':O,'data':P},b['network']??'default');}return{'content':[{'type':'text','text':JSON['stringify'](d)}],'structuredContent':{'result':d}};}catch(Q){const R=Q instanceof Error?Q['message']:String(Q),S=b?{'operation_type':'messenger_'+b['operation'],'data':b}:undefined,T=classifyError(R),U={'operation':'error','error':R};if(T['error_code']!==undefined)U['error_code']=T['error_code'];if(T['retryable']!==undefined)U['retryable']=T['retryable'];if(T['recovery_hint']!==undefined)U['recovery_hint']=T['recovery_hint'];return{'content':[{'type':'text','text':'Error:\x20'+R}],'structuredContent':{'result':U,'semantic':buildDataSemantic(undefined,S,!![],R)}};}}
1
+ import{strictParse,MessengerOperationInputSchema}from'../../schema/index.js';import{watch_conversations,send_message,send_file,watch_messages,export_attachment,pull_messages,generate_wts,verify_wts,sign_wts,wts2html,proof_message,mark_messages_as_viewed,mark_conversation_as_viewed,blacklist,friendslist,guardlist,settings,LocalInfo}from'@wowok/wowok';import{classifyError,buildDataSemantic}from'../../schema/call/semantic.js';import{classifyCommunicationEvidence}from'../../communication/evidence.js';import{attestWtsFile}from'../../communication/wts-attestation.js';import{goalEngine}from'../../goal/GoalEngine.js';export function normalizeAccountOrMark(a){if(typeof a==='string')return{'name_or_address':a,'local_mark_first':!![]};return a;}export function normalizeOptionalAccountOrMark(a){if(a===undefined||a===null)return undefined;return normalizeAccountOrMark(a);}export function normalizeManyAccountOrMark(a){if(a===undefined||a===null)return undefined;if(Array['isArray'](a))return{'entities':a['map'](b=>typeof b==='string'?{'name_or_address':b,'local_mark_first':!![]}:b),'check_all_founded':!![]};return a;}function communicationEvidencePayload(a,b){const c=b??{};switch(a){case'send_message':case'send_file':{const d=typeof c['messageId']==='string'?c['messageId']:undefined;return{'detail':d?'message\x20'+d:'message\x20sent','data':d?{'message_id':d}:{}};}case'send_required_info':{const e=typeof c['messageId']==='string'?c['messageId']:undefined,f=Array['isArray'](c['sent_fields'])?c['sent_fields']:undefined;return{'detail':'required-info\x20confirmation\x20sent','data':{...e?{'message_id':e}:{},...f?{'sent_fields':f}:{}}};}case'generate_wts':{const g=typeof c['totalMessageCount']==='number'?c['totalMessageCount']:undefined,h=Array['isArray'](c['files'])?c['files']:undefined,i=Array['isArray'](c['htmlFiles'])?c['htmlFiles']:undefined;return{'detail':'WTS\x20evidence\x20packet\x20generated','data':{...g!==undefined?{'message_count':g}:{},...h?{'files':h}:{},...i?{'html_reports':i}:{}}};}case'verify_wts':{const j=c['attestation'],k=typeof c['error']==='string'?c['error']:undefined;return{'detail':j?'WTS\x20verification\x20—\x20'+j['attested_count']+'/'+j['total_messages']+'\x20message(s)\x20server-attested':'WTS\x20verification\x20—\x20server\x20attestation\x20unavailable','data':{'valid':c['valid']===!![],'hash_valid':c['hashValid']===!![],'has_signature':c['hasSignature']===!![],...c['signatureValid']===undefined?{}:{'packet_signature_valid':c['signatureValid']===!![]},...k?{'error':k}:{},...j?{'attested_messages':j['attested_count'],'total_messages':j['total_messages'],'fully_attested':j['fully_attested'],'packet_signed':j['packet_signed'],'server_public_keys':j['server_public_keys'],'verdict':j['verdict']}:{'attestation':'unavailable\x20—\x20cross-check\x20the\x20seal\x20signer\x20and\x20server\x20keys\x20independently\x20before\x20treating\x20the\x20packet\x20as\x20third-party\x20evidence'}}};}case'sign_wts':{return{'detail':typeof b==='string'?b:'WTS\x20evidence\x20signed','data':{}};}case'proof_message':{const l=typeof c['proofAddress']==='string'?c['proofAddress']:undefined;return{'detail':l?'proof\x20'+l:'message\x20proofed\x20on-chain','data':l?{'proof_address':l}:{}};}default:return{'detail':a,'data':{}};}}export async function handleMessengerOperation(a){let b;try{b=strictParse(MessengerOperationInputSchema,a,'messenger_operation\x20input');const c=b['operation'];let d;switch(b['operation']){case'watch_conversations':{const g=await watch_conversations(b['filter']);d={'operation':'watch_conversations','result':g};break;}case'send_message':{const h=await send_message(normalizeOptionalAccountOrMark(b['from']),normalizeAccountOrMark(b['to']),b['content'],b['options']);if(h['authRequired']){d={'operation':'send_message','result':h};break;}const i=h,j={...i,'merkleData':i['merkleData']?{'leafIndex':i['merkleData']['leafIndex'],'prevRoot':i['merkleData']['prevRoot'],'newRoot':i['merkleData']['newRoot'],'serverSignature':i['merkleData']['serverSignature'],'serverTimestamp':i['merkleData']['serverTimestamp'],'serverPublicKey':i['merkleData']['serverPublicKey']}:undefined};d={'operation':'send_message','result':j};break;}case'send_file':{const k=await send_file(normalizeOptionalAccountOrMark(b['from']),normalizeAccountOrMark(b['to']),b['filePath'],b['options']),l=k,m={...l,'merkleData':l['merkleData']?{'leafIndex':l['merkleData']['leafIndex'],'prevRoot':l['merkleData']['prevRoot'],'newRoot':l['merkleData']['newRoot'],'serverSignature':l['merkleData']['serverSignature'],'serverTimestamp':l['merkleData']['serverTimestamp'],'serverPublicKey':l['merkleData']['serverPublicKey']}:undefined};d={'operation':'send_file','result':m};break;}case'send_required_info':{let n=b['content'];const o=[];if(!n){const s=await LocalInfo['Instance']()['list'](),t=b['fields'],u=t&&t['length']>0x0?s['filter'](v=>t['includes'](v['name'])):s;if(u['length']===0x0)throw new Error('No\x20LocalInfo\x20fields\x20available.\x20Add\x20private\x20info\x20first\x20via\x20local_info_operation.');n=u['map'](v=>v['name']+':\x20'+v['default'])['join']('\x0a'),o['push'](...u['map'](v=>v['name']));}const p=await send_message(normalizeOptionalAccountOrMark(b['from']),normalizeAccountOrMark(b['to']),n,b['options']),q=p,r={...q,'merkleData':q['merkleData']?{'leafIndex':q['merkleData']['leafIndex'],'prevRoot':q['merkleData']['prevRoot'],'newRoot':q['merkleData']['newRoot'],'serverSignature':q['merkleData']['serverSignature'],'serverTimestamp':q['merkleData']['serverTimestamp'],'serverPublicKey':q['merkleData']['serverPublicKey']}:undefined,'sent_fields':o};d={'operation':'send_required_info','result':r};break;}case'watch_messages':{const v=b['filter']?{...b['filter'],'peerAddress':b['filter']['peerAddress']?normalizeAccountOrMark(b['filter']['peerAddress']):undefined,'account':b['filter']['account']?normalizeOptionalAccountOrMark(b['filter']['account']):undefined}:undefined,w=await watch_messages(v);d={'operation':'watch_messages','result':w};break;}case'save_attachment':{const x=await export_attachment(normalizeOptionalAccountOrMark(b['account']),b['messageId'],{'outputDir':b['outputDir'],'saveAs':b['saveAs']});d={'operation':'save_attachment','result':x};break;}case'generate_wts':{const y=b['params']?{...b['params'],'peerAccount':normalizeAccountOrMark(b['params']['peerAccount']),'myAccount':normalizeOptionalAccountOrMark(b['params']['myAccount'])}:undefined,z=await generate_wts(y);d={'operation':'generate_wts','result':z};break;}case'verify_wts':{const A=await verify_wts(b['wtsFilePath']),B=await attestWtsFile(b['wtsFilePath']);d={'operation':'verify_wts','result':B?{...A,'attestation':B}:{...A,'attestation_unavailable':'Per-message\x20server\x20attestation\x20could\x20not\x20be\x20computed\x20(file\x20not\x20readable\x20locally\x20or\x20not\x20JSON).\x20The\x20guarded\x20verifier\x27s\x20valid\x20flag\x20already\x20required\x20server\x20attestation\x20+\x20seal;\x20cross-check\x20the\x20seal\x20signer\x20and\x20server\x20keys\x20yourself\x20before\x20treating\x20it\x20as\x20third-party\x20evidence.'}};break;}case'sign_wts':{const C=await sign_wts(b['wtsFilePath'],normalizeOptionalAccountOrMark(b['account']),b['outputPath']);d={'operation':'sign_wts','result':C};break;}case'wts2html':{const D=await wts2html(b['wtsPath'],b['options']);d={'operation':'wts2html','result':D};break;}case'proof_message':{const E=await proof_message(normalizeOptionalAccountOrMark(b['account']),b['messageId'],b['network']);d={'operation':'proof_message','result':E};break;}case'blacklist':{const F={'account':normalizeOptionalAccountOrMark(b['account']),'op':b['blacklist']['op']};'users'in b['blacklist']&&(F['users']=normalizeManyAccountOrMark(b['blacklist']['users']));const G=await blacklist(F);d={'operation':'blacklist','op':b['blacklist']['op'],'result':G['result']};break;}case'friendslist':{const H={'account':normalizeOptionalAccountOrMark(b['account']),'op':b['friendslist']['op']};'users'in b['friendslist']&&(H['users']=normalizeManyAccountOrMark(b['friendslist']['users']));const I=await friendslist(H);d={'operation':'friendslist','op':b['friendslist']['op'],'result':I['result']};break;}case'guardlist':{const J=await guardlist({'account':normalizeOptionalAccountOrMark(b['account']),...b['guardlist']});d={'operation':'guardlist','op':b['guardlist']['op'],'result':J['result']};break;}case'settings':{const K=await settings({'account':normalizeOptionalAccountOrMark(b['account']),...b['settings']});d={'operation':'settings','op':b['settings']['op'],'result':K['result']};break;}case'mark_messages_as_viewed':{const L=await mark_messages_as_viewed(b['messageIds'],normalizeOptionalAccountOrMark(b['account']));d={'operation':'mark_messages_as_viewed','result':L};break;}case'mark_conversation_as_viewed':{const M=await mark_conversation_as_viewed(normalizeAccountOrMark(b['peerAddress']),normalizeOptionalAccountOrMark(b['account']));d={'operation':'mark_conversation_as_viewed','result':M};break;}case'pull_messages':{const N=await pull_messages(normalizeOptionalAccountOrMark(b['account']),b['limit'],{'allAccounts':b['allAccounts'],'accounts':b['accounts']?.['map'](O=>normalizeAccountOrMark(O)),'concurrency':b['concurrency']});d={'operation':'pull_messages','result':N};break;}default:throw new Error('Unknown\x20messenger\x20operation:\x20'+c);}const e=classifyCommunicationEvidence(c),f=b['goal_id'];if(e&&f){const O=d['result'],{detail:P,data:Q}=communicationEvidencePayload(c,O);await goalEngine['recordCommunicationEvidence'](f,{'operation':c,'kind':e['kind'],'title':e['title'],'detail':P,'data':Q},b['network']??'default');}return{'content':[{'type':'text','text':JSON['stringify'](d)}],'structuredContent':{'result':d}};}catch(R){const S=R instanceof Error?R['message']:String(R),T=b?{'operation_type':'messenger_'+b['operation'],'data':b}:undefined,U=classifyError(S),V={'operation':'error','error':S};if(U['error_code']!==undefined)V['error_code']=U['error_code'];if(U['retryable']!==undefined)V['retryable']=U['retryable'];if(U['recovery_hint']!==undefined)V['recovery_hint']=U['recovery_hint'];return{'content':[{'type':'text','text':'Error:\x20'+S}],'structuredContent':{'result':V,'semantic':buildDataSemantic(undefined,T,!![],S)}};}}