@yorha2b-lab/autodev 4.2.0 → 5.1.0

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 (58) hide show
  1. package/.github/scripts/deploy/publish.py +2 -2
  2. package/.github/scripts/render/dashboard.py +13 -9
  3. package/CONTRIBUTING.md +0 -18
  4. package/bin/autodev.js +28 -26
  5. package/config.js +3 -3
  6. package/package.json +1 -3
  7. package/src/bootstrap/dialogs.js +10 -0
  8. package/src/bootstrap/handlebars.js +26 -0
  9. package/src/bootstrap/handlers.js +10 -0
  10. package/src/bootstrap/index.js +56 -0
  11. package/src/bootstrap/infrastructure.js +16 -0
  12. package/src/bootstrap/openai.js +13 -0
  13. package/src/bootstrap/prompts.js +10 -0
  14. package/src/bootstrap/yorha.js +39 -0
  15. package/src/commands/watch.js +15 -42
  16. package/src/dialogs/EN-US.js +55 -0
  17. package/src/dialogs/ZH-CN.js +55 -0
  18. package/src/{core/react-compiler.js → framework/react/generator/index.js} +1 -1
  19. package/src/{prompts/react/watch-part.js → framework/react/prompts/part.js} +1 -1
  20. package/{templates → src/framework}/react/utils/utils.js +1 -1
  21. package/src/handlers/api.js +92 -0
  22. package/src/handlers/page.js +70 -0
  23. package/src/handlers/part.js +59 -0
  24. package/src/{services/api-linker.js → labs/linker.js} +14 -31
  25. package/src/{services/proxy-tower.js → labs/tower.js} +10 -23
  26. package/src/services/llm.js +21 -20
  27. package/src/utils/infrastructure.js +5 -2
  28. package/src/utils/ux.js +21 -18
  29. package/src/commands/handlers/api-handler.js +0 -111
  30. package/src/commands/handlers/page-handler.js +0 -96
  31. package/src/commands/handlers/part-handler.js +0 -77
  32. package/src/core/context.js +0 -93
  33. /package/{templates → src/framework}/react/components/EditableCell.js +0 -0
  34. /package/{templates → src/framework}/react/components/MyBaseForm.js +0 -0
  35. /package/{templates → src/framework}/react/components/MyImage.js +0 -0
  36. /package/{templates → src/framework}/react/components/MyModalForm.js +0 -0
  37. /package/{templates → src/framework}/react/components/MyModalTable.js +0 -0
  38. /package/{templates → src/framework}/react/components/MySearchForm.js +0 -0
  39. /package/{templates → src/framework}/react/components/MyTable.js +0 -0
  40. /package/{templates → src/framework}/react/components/index.js +0 -0
  41. /package/{templates/react → src/framework/react/handlebars}/index.hbs +0 -0
  42. /package/{templates/react/handlebars → src/framework/react/handlebars/partials}/AlertInfo.hbs +0 -0
  43. /package/{templates/react/handlebars → src/framework/react/handlebars/partials}/FunctionButtons.hbs +0 -0
  44. /package/{templates/react/handlebars → src/framework/react/handlebars/partials}/MySearchForm.hbs +0 -0
  45. /package/{templates/react/handlebars → src/framework/react/handlebars/partials}/MyTable.hbs +0 -0
  46. /package/{templates/react/handlebars → src/framework/react/handlebars/partials}/handleBlock.hbs +0 -0
  47. /package/{templates/react/handlebars → src/framework/react/handlebars/partials}/hookBlock.hbs +0 -0
  48. /package/{templates/react/handlebars → src/framework/react/handlebars/partials}/operateBlock.hbs +0 -0
  49. /package/{templates/react/handlebars → src/framework/react/handlebars/partials}/renderBlock.hbs +0 -0
  50. /package/{templates/react/handlebars → src/framework/react/handlebars/partials}/stateBlock.hbs +0 -0
  51. /package/{templates/react → src/framework/react/handlebars}/resource.hbs +0 -0
  52. /package/{templates → src/framework}/react/hooks/useTableQuery.js +0 -0
  53. /package/src/{prompts/react/watch-api.js → framework/react/prompts/api.js} +0 -0
  54. /package/src/{prompts/react/api-linker.js → framework/react/prompts/linker.js} +0 -0
  55. /package/src/{prompts → framework/react/prompts}/mock.js +0 -0
  56. /package/src/{prompts/react/watch-page.js → framework/react/prompts/page.js} +0 -0
  57. /package/src/{prompts → framework/react/prompts}/system.js +0 -0
  58. /package/src/{schema/react → framework/react/schema}/page.json +0 -0
@@ -0,0 +1,55 @@
1
+ module.exports = {
2
+ nineS: {
3
+ dataCamouflageComplete: 'Mock 数据生成成功',
4
+ scanningField: '正在扫描前后端字段差异... 执行语义桥接任务',
5
+ dataCamouflage: fileName => `正在突破目标防火墙... 执行数据伪装程序 [${fileName}]`,
6
+ },
7
+ pod042: {
8
+ extractingUiMetadata: '正在从神经云网络提取 UI 元数据...',
9
+ simulate: '拦截到实弹请求。正在空投标准模拟包: example.json',
10
+ queueEmpty: '队列已空,正在向 Bunker 同步 Menu 路由配置...',
11
+ uploadVisualMetadata: '正在上传视觉元数据至司令部进行语义分析...',
12
+ visualPartCaptured: `侦测到局部视觉样本。正在执行“碎片构筑协议”...`,
13
+ partialConstruction: time => `报告:局部构筑达成。耗时: ${time}s`,
14
+ partialRecommendation: '│ 建议:请手动将上述代码块物理装配至您的目标文件中',
15
+ constructionAborted: virus => `构筑中断。检测到逻辑病毒或连接超时:${virus}`,
16
+ partialConstructionAborted: virus => `[警告] 碎片构筑失败。系统检测到逻辑干扰:${virus}`,
17
+ visualCaptured: fileName => `视觉传感器捕捉完成: [${fileName}]。正在调配地堡资源进行物理构筑...`,
18
+ intercept: fileName => `模块 [${fileName}] 已存在于地堡数据库中。为了防止数据覆盖,构筑协议已跳过`,
19
+ assemblyComplete: (fileName, time) => `构筑协议执行完毕。模块 [${fileName}] 物理装配达成。耗时: ${time}s`,
20
+ },
21
+ pod153: {
22
+ signalLinkFault: virus => `信号链路故障: ${virus}`,
23
+ formatError: '数据格式非标准 JSON,将尝试原始字符对齐',
24
+ autonomousAddressing: `启动‘全频道自动寻址协议 [语义扫描版]’...`,
25
+ signalSynchronized: count => `信号同步完成,${count} 个节点已通电`,
26
+ alignmentFailed: virus => `信号对齐失败。接口数据遭遇强力防火墙:${virus}`,
27
+ inactiveModule: fileName => `发现未通电模块 [${fileName}],请求 9S 执行高精度对账...`,
28
+ capturedRuntimeSignal: fileName => `截获运行时信号 [${fileName}]。执行自动对齐协议...`,
29
+ reconEncryptedData: fileName => `发现加密数据源 [${fileName}]。正在尝试执行语义对齐协议...`,
30
+ unknownModule: fileName => `地堡数据库中未检索到模块 [${fileName}] 的资源文件。请先执行视觉构筑`,
31
+ bridgeProtocolComplete: (count, time) => `语义桥接协议执行完毕。已物理修正 ${count} 处字段偏差。耗时: ${time}s`,
32
+ },
33
+ bunker: {
34
+ envCopy: '.env 存储完毕',
35
+ argDesc: '指定前端框架模板',
36
+ systemStandby: '系统待机中...',
37
+ desc: 'AI驱动的前端CRUD代码生成器',
38
+ configCopy: 'config.js 存储完毕',
39
+ initDesc: '在当前目录初始化地堡构筑环境',
40
+ envCheck: '终端已存在 .env 文件,跳过生成',
41
+ configCheck: '终端已存在 config.js 文件,跳过生成',
42
+ linkSevered: '连接中断:请检查网络状态或黑盒共鸣情况',
43
+ systemOffline: '正在断开神经云链接,执行数据物理封存...',
44
+ towerOnline: port => `信号拦截塔已在线 [波段: ${port}]`,
45
+ watchDesc: '开启全频道联动监控:支持 Page/Part/API 协同构筑',
46
+ accessDenied: '司令部拒绝访问:API Key 无效或额度耗尽,请检查!',
47
+ disclaimer: '匹配结果仅供参考,不构成最终决策,各机体需根据实际情况进行调整',
48
+ towerConnected: port => `指令:请将您的代理目标指向 http://localhost:${port}`,
49
+ networkInstability: count => `神经云网络连接不稳,正在尝试重新链接... (第 ${count} 次重试)`,
50
+ initComplete: cmd => `地堡部署完毕, 为了更快捷地进入战场,建议手动执行 [物理装配]: 将 ${cmd} 加入您的 package.json scripts 中`,
51
+ },
52
+ operator6O: {
53
+ call2B: '呼叫 2B,地堡全频道联动监控已就绪!',
54
+ }
55
+ }
@@ -1,4 +1,4 @@
1
- module.exports = ({ config, contextStringify, indexTpl, resourceTpl, formatFormItemAndColumns, cleanCode, generateSmartImports }) => {
1
+ module.exports = ({ config, indexTpl, cleanCode, resourceTpl, contextStringify, generateSmartImports, formatFormItemAndColumns, }) => {
2
2
 
3
3
  const { needMock, responseSuccess } = config
4
4
 
@@ -8,7 +8,7 @@ module.exports = `
8
8
  3. 必须严格遵守以下字段规范。
9
9
 
10
10
  ## 1. 表格 (Table)
11
- - 结构: { columns: [{ title: '列名', dataIndex: '列名英文名词', type: '' }] }
11
+ - 结构: { columns: [{ title: '列名', dataIndex: '***englishName***', type: '' }] }
12
12
  - ⚠️ 字段白名单: [title, dataIndex, sorter, render, filters, onFilter]
13
13
  - **注意**: type为text时必须省略type属性。
14
14
  - 禁止输出:
@@ -100,7 +100,7 @@ export const timeRender = ({ time, date, minute }) => {
100
100
  * @param {Function} [formatter] - 数据预处理回调
101
101
  * @param {Array} columns - 表格列配置,支持 exportRender 优先级
102
102
  */
103
- export const exportDataToExcel = async (url, options, columns, fileName, formatter) => {
103
+ export const exportDataToExcel = async ({ url, options, columns, fileName, formatter }) => {
104
104
  /* const response = await request(url, options)
105
105
  const result = formatter ? formatter(response) : (response?.data ?? [])
106
106
  if (result?.length > 0) {
@@ -0,0 +1,92 @@
1
+ const fs = require('fs')
2
+ const path = require('path')
3
+
4
+ module.exports = {
5
+ watch: 'response',
6
+ async handle(filePath, liveResponse = null) {
7
+
8
+ const chalk = require('chalk')
9
+ const { ux, llm, core, yorha, dialogs, infrastructure } = require('../bootstrap').get()
10
+
11
+ const { local } = ux
12
+ const dialog = dialogs[local]
13
+ const { unwrapSignal } = core
14
+ const { nineS, pod153 } = yorha
15
+ const { config } = infrastructure
16
+ const { alignResponseFields } = llm
17
+
18
+ const { pagesDir } = config
19
+ const startTime = Date.now()
20
+ const fileName = liveResponse?.fileName ?? path.basename(filePath, path.extname(filePath))
21
+ const resourcePath = path.join(process.cwd(), pagesDir, fileName, 'resource.js')
22
+
23
+ const spinner = pod153.start(dialog.pod153.reconEncryptedData(fileName))
24
+
25
+ try {
26
+ if (!fs.existsSync(resourcePath)) {
27
+ pod153.fail(spinner, dialog.pod153.unknownModule(fileName))
28
+ return
29
+ }
30
+
31
+ let rawJson = liveResponse ? liveResponse.data : JSON.parse(fs.readFileSync(filePath, 'utf8'))
32
+ let resourceStr = fs.readFileSync(resourcePath, 'utf8')
33
+
34
+ const coreArray = unwrapSignal(rawJson)
35
+ if (!coreArray || coreArray.length === 0) {
36
+ pod153.warning(spinner, dialog.pod153.formatError)
37
+ }
38
+
39
+ nineS.update(spinner, dialog.nineS.scanningField)
40
+
41
+ const extractKeys = str => {
42
+ const keys = []
43
+ const regex = /(dataIndex|name)\s*:\s*['"]([^'"]+)['"]/g
44
+ let match
45
+ while ((match = regex.exec(str)) !== null) {
46
+ keys.push(match[2])
47
+ }
48
+ return Array.from(new Set(keys))
49
+ }
50
+
51
+ const sampleData = coreArray && coreArray.length > 0 ? [coreArray[0]] : rawJson
52
+ const result = await alignResponseFields({ responseStr: JSON.stringify(sampleData), resourceStr: extractKeys(resourceStr).join(',') })
53
+ let changeCount = 0
54
+ const resultMapping = {}
55
+ Object.entries(result).forEach(([oldField, newField]) => {
56
+ if (oldField === newField) return
57
+ const regex = new RegExp(`(dataIndex|name)\\s*:\\s*['"]${oldField}['"]`, 'g')
58
+ resourceStr = resourceStr.replace(regex, `$1: '${newField}'`)
59
+ changeCount++
60
+ resultMapping[oldField] = newField
61
+ })
62
+
63
+ fs.writeFileSync(resourcePath, resourceStr)
64
+ const endTime = Date.now()
65
+
66
+ pod153.success(spinner, dialog.pod153.bridgeProtocolComplete(changeCount, (endTime - startTime) / 1000))
67
+
68
+ if (changeCount > 0) {
69
+ console.log(chalk.magenta(`\n┌────── [ YoRHa Autonomous Backend Alignment ] ──────┐`))
70
+ const maxOldFieldLength = Math.max(...Object.keys(resultMapping).map(key => key.length))
71
+ Object.entries(resultMapping).forEach(([oldField, newField]) => {
72
+ const padding = ' '.repeat(Math.max(1, maxOldFieldLength + 1 - oldField.length))
73
+ console.log(
74
+ chalk.yellow(` │ `) +
75
+ chalk.yellow(oldField) +
76
+ padding +
77
+ chalk.cyan(` -> `) +
78
+ chalk.white(newField)
79
+ )
80
+ })
81
+ console.log(chalk.magenta(`└────────────────────────────────────────────────────┘`))
82
+ }
83
+
84
+ if (fs.existsSync(filePath)) {
85
+ fs.unlinkSync(filePath)
86
+ }
87
+
88
+ } catch (error) {
89
+ pod153.fail(spinner, dialog.pod153.alignmentFailed(error))
90
+ }
91
+ }
92
+ }
@@ -0,0 +1,70 @@
1
+ const fs = require('fs')
2
+ const path = require('path')
3
+
4
+ module.exports = {
5
+ watch: 'screenShot',
6
+ async handle(filePath) {
7
+
8
+ const { ux, llm, yorha, dialogs, prompts, generator, infrastructure } = require('../bootstrap').get()
9
+
10
+ const { local } = ux
11
+ const dialog = dialogs[local]
12
+ const { pagePrompt } = prompts
13
+ const { nineS, pod042 } = yorha
14
+ const { index, resource } = generator
15
+ const { generateMock, recognizePage } = llm
16
+ const { menus, config, contextStringify } = infrastructure
17
+
18
+ const { useDemo, pagesDir, needMock } = config
19
+
20
+ const startTime = Date.now()
21
+ const fileName = path.basename(filePath, path.extname(filePath))
22
+ const mockDir = path.join(process.cwd(), 'mock')
23
+ const targetDir = path.join(process.cwd(), pagesDir, fileName)
24
+
25
+ const spinner = pod042.start(dialog.pod042.visualCaptured(fileName))
26
+
27
+ try {
28
+ if (fs.existsSync(targetDir)) {
29
+ pod042.warning(spinner, dialog.pod042.intercept(fileName))
30
+ return
31
+ }
32
+
33
+ if (!fs.existsSync(mockDir)) fs.mkdirSync(mockDir, { recursive: true })
34
+ if (!fs.existsSync(targetDir)) fs.mkdirSync(targetDir, { recursive: true })
35
+
36
+ let pageConfig
37
+ if (useDemo) {
38
+ pod042.report(dialog.pod042.simulate)
39
+ pageConfig = require('../../example/example.json')
40
+ } else {
41
+ pod042.update(spinner, dialog.pod042.uploadVisualMetadata)
42
+ pageConfig = await recognizePage({ prompt: pagePrompt, filePath })
43
+ }
44
+
45
+ fs.writeFileSync(path.join(targetDir, 'resource.js'), resource({ pageConfig }))
46
+ fs.writeFileSync(path.join(targetDir, 'index.js'), index({ fileName, pageConfig }))
47
+
48
+ if (!menus.find(m => m.key === fileName)) {
49
+ menus.push({ label: fileName, key: fileName })
50
+ }
51
+
52
+ if (needMock) {
53
+ nineS.update(spinner, dialog.nineS.dataCamouflage(fileName))
54
+ const rawContent = await generateMock({ columns: pageConfig.table.columns, fileName })
55
+ fs.writeFileSync(path.join(mockDir, `${fileName}.js`), `export default ${contextStringify({ context: rawContent })}`)
56
+ nineS.success(spinner, dialog.nineS.dataCamouflageComplete)
57
+ }
58
+
59
+ const endTime = Date.now()
60
+ pod042.success(spinner, dialog.pod042.assemblyComplete(fileName, (endTime - startTime) / 1000))
61
+
62
+ if (fs.existsSync(filePath)) {
63
+ fs.unlinkSync(filePath)
64
+ }
65
+
66
+ } catch (error) {
67
+ pod042.fail(spinner, dialog.pod042.constructionAborted(error))
68
+ }
69
+ }
70
+ }
@@ -0,0 +1,59 @@
1
+ const fs = require('fs')
2
+
3
+ module.exports = {
4
+ watch: 'screenPart',
5
+ async handle(filePath) {
6
+
7
+ const chalk = require('chalk')
8
+ const { ux, llm, core, yorha, dialogs, prompts, infrastructure } = require('../bootstrap').get()
9
+
10
+ const { local } = ux
11
+ const { pod042 } = yorha
12
+ const dialog = dialogs[local]
13
+ const { recognizePage } = llm
14
+ const { partPrompt } = prompts
15
+ const { contextStringify } = infrastructure
16
+ const { cleanCode, formatFormItemAndColumns } = core
17
+
18
+ const startTime = Date.now()
19
+
20
+ const spinner = pod042.start(dialog.pod042.visualPartCaptured)
21
+
22
+ try {
23
+ pod042.update(spinner, dialog.pod042.extractingUiMetadata)
24
+
25
+ const pageConfig = await recognizePage({ prompt: partPrompt, filePath, taskType: 'part' })
26
+
27
+ const { formItems, dictBlocks, processedColumns } = formatFormItemAndColumns({ pageConfig })
28
+
29
+ const result = Object.fromEntries(Object.entries({ formItems, processedColumns }).filter(([key, value]) => value?.length > 0))
30
+
31
+ let mainConfigStr = cleanCode(contextStringify({ context: result }))
32
+
33
+ let optionsCodeStr = ''
34
+ dictBlocks.forEach(key => {
35
+ const optionsArray = pageConfig.optionDict?.[key] ?? []
36
+ const arrayItemsStr = optionsArray.map(opt => ` { label: '${opt.label}', value: '${opt.value}' }`).join(',\n')
37
+ optionsCodeStr += `\nexport const ${key} = [\n${arrayItemsStr}\n]\n`
38
+ })
39
+
40
+ const finalResult = `${mainConfigStr}\n${optionsCodeStr}`
41
+ const endTime = Date.now()
42
+ spinner.stop()
43
+ console.log(chalk.magenta(`\n┌────────────────── [ YoRHa Construction Output ] ─────────────────┐`))
44
+ console.log(chalk.magenta(`│ Source: ${filePath}`))
45
+ console.log(chalk.magenta(`│ Protocol: Partial UI Fragment | Status: SUCCESS`))
46
+ console.log(chalk.magenta(`├───────────────────────────────────────────────────────────────────┘`))
47
+ console.log(chalk.white(finalResult))
48
+ pod042.success(spinner, dialog.pod042.partialConstruction((endTime - startTime) / 1000))
49
+ pod042.success(spinner, dialog.pod042.partialRecommendation)
50
+
51
+ if (fs.existsSync(filePath)) {
52
+ fs.unlinkSync(filePath)
53
+ }
54
+
55
+ } catch (error) {
56
+ pod042.fail(spinner, dialog.pod042.partialConstructionAborted(error))
57
+ }
58
+ }
59
+ }
@@ -1,23 +1,20 @@
1
+ const fs = require('fs')
2
+ const path = require('path')
3
+
1
4
  module.exports = async () => {
2
5
 
3
- const fs = require('fs')
4
- const path = require('path')
5
- const chalk = require('chalk')
6
+ const { ux, llm, yorha, dialogs, infrastructure } = require('../bootstrap').get()
6
7
 
7
- const {
8
- config,
9
- language,
10
- apiLinker,
11
- getLocalScore, getSemanticKeywords,
12
- } = require('../core/context').get()
8
+ const { local } = ux
9
+ const { apiLinker } = llm
10
+ const dialog = dialogs[local]
11
+ const { pod153, commander } = yorha
12
+ const { config, getLocalScore, getSemanticKeywords, } = infrastructure
13
13
 
14
14
  const { apiDoc, pagesDir } = config
15
15
  if (!apiDoc) return
16
16
 
17
- console.log(chalk.cyan(language(
18
- `\n🤖 Pod 153: 启动‘全频道自动寻址协议 [语义扫描版]’...`,
19
- `\n🤖 Pod 153: Initiating 'Full-Channel Autonomous Addressing Protocol [Semantic Scan]'...`
20
- )))
17
+ pod153.report(dialog.pod153.autonomousAddressing, 'magenta')
21
18
 
22
19
  try {
23
20
  // 1. 抓取情报
@@ -64,12 +61,7 @@ module.exports = async () => {
64
61
  .slice(0, 20) // 💡 拓宽至前 20 名,给 AI 更多的判别空间
65
62
 
66
63
  const finalCandidates = candidates.map(item => `${item.method} ${item.path} ${item.desc}`).join('\n')
67
-
68
- console.log(chalk.yellow(language(
69
- ` 🛰️ Inactive module: [${fileName}]. Requesting 9S for precise alignment...`,
70
- ` 🛰️ 发现未通电模块 [${fileName}],请求 9S 执行高精度对账...`
71
- )))
72
-
64
+ pod153.report(dialog.pod153.inactiveModule(fileName), 'yellow')
73
65
  // 3. 驱动 9S 最终裁决
74
66
  const result = await apiLinker({ bunkerAnchors, realApis: finalCandidates })
75
67
 
@@ -100,23 +92,14 @@ module.exports = async () => {
100
92
  indexCode = indexCode.replaceAll(`/api/${anchor}`, `/api${cleanPath}`)
101
93
  })
102
94
  fs.writeFileSync(indexPath, indexCode)
103
- console.log(chalk.green(language(
104
- `✅ 信号同步完成,${Object.keys(result).length} 个节点已通电。`,
105
- `✅ Signal Synchronized: ${Object.keys(result).length} nodes energized.`
106
- )))
95
+ pod153.report(dialog.pod153.signalSynchronized(Object.keys(result).length))
107
96
  // 💡 战术免责补丁:采用橙黄色高亮,提醒指挥官保持警惕
108
- console.log(chalk.yellow(language(
109
- `⚠️ 匹配结果仅供参考,不构成最终决策,各机体需根据实际情况进行调整。`,
110
- `⚠️ Match Result Reference Only. Not Final Decision. Each Unit should adjust based on battlefield conditions.`
111
- )))
97
+ commander.log(dialog.bunker.disclaimer, 'yellow')
112
98
  }
113
99
  }
114
100
  }
115
101
  }
116
102
  } catch (e) {
117
- console.error(chalk.red(language(
118
- `\n❌ Pod 153: 信号链路故障: ${e.message}\n`,
119
- `\n❌ Pod 153: Signal Link Fault: ${e.message}\n`
120
- )))
103
+ pod153.report(dialog.pod153.signalLinkFault(e.message), 'red')
121
104
  }
122
105
  }
@@ -7,16 +7,15 @@ module.exports = () => {
7
7
 
8
8
  const http = require('http')
9
9
  const zlib = require('zlib')
10
- const chalk = require('chalk')
11
10
  const httpProxy = require('http-proxy')
12
11
 
13
- const {
14
- config,
15
- language,
16
- apiHandler,
17
- unwrapSignal, isQuerySignal
18
- } = require('../core/context').get()
12
+ const { ux, core, yorha, dialogs, handlers, infrastructure } = require('../bootstrap').get()
19
13
 
14
+ const { local } = ux
15
+ const { pod153 } = yorha
16
+ const dialog = dialogs[local]
17
+ const { config } = infrastructure
18
+ const { unwrapSignal, isQuerySignal } = core
20
19
  const { routeMap = {}, proxyTarget } = config
21
20
 
22
21
  const TOWER_PORT = 42153
@@ -59,16 +58,13 @@ module.exports = () => {
59
58
  return
60
59
  }
61
60
 
62
- console.log(chalk.cyan(language(
63
- `\n📡 Pod 153: 截获运行时信号 [${fileName}]。执行自动对齐协议...`,
64
- `\n📡 Pod 153: Captured runtime signal [${fileName}]. Executing semantic alignment protocol...`
65
- )))
61
+ pod153.report(dialog.pod153.capturedRuntimeSignal(fileName))
66
62
  // 💡 直接调用 api-handler 物理更新 resource.js
67
- await apiHandler(null, { fileName, data: json })
63
+ await handlers.api.handle(null, { fileName, data: json })
68
64
  hackedRegistry.set(fileName, fingerprint)
69
65
  } catch (e) {
70
- console.log(e)
71
66
  // 非 JSON 信号,保持静默
67
+ console.log(e)
72
68
  }
73
69
  })
74
70
  })
@@ -82,14 +78,5 @@ module.exports = () => {
82
78
  proxy.web(req, res, { target: proxyTarget, changeOrigin: true })
83
79
  })
84
80
 
85
- server.listen(TOWER_PORT, () => {
86
- console.log(chalk.magenta(language(
87
- `✨ YoRHa 联合基站:信号拦截塔已在线 [波段: ${TOWER_PORT}]`,
88
- `✨ YoRHa Joint Station: Signal Intercept Tower Online [Band: ${TOWER_PORT}]`
89
- )))
90
- console.log(chalk.gray(language(
91
- `💡 指令:请将您的代理目标指向 http://localhost:${TOWER_PORT}`,
92
- `💡 Command: Please point your local proxy target to http://localhost:${TOWER_PORT}`
93
- )))
94
- })
81
+ server.listen(TOWER_PORT, () => {})
95
82
  }
@@ -1,14 +1,9 @@
1
1
 
2
- const chalk = require('chalk')
3
- const { language } = require('../utils/ux')
4
-
5
- const askAI = async ({ model, openAI, messages, response_format = { type: 'json_object' }, retryCount = 0 }) => {
2
+ const askAI = async ({ model, yorha, dialog, openAI, messages, response_format = { type: 'json_object' }, retryCount = 0 }) => {
6
3
 
7
4
  if (retryCount > 3) {
8
- throw new Error(language(
9
- 'YoRHa 司令部连接中断:请检查网络状态或黑盒共鸣情况。',
10
- 'YoRHa Command Link Severed: Check network status or Black Box resonance.'
11
- ))
5
+ yorha.commander.log(dialog.bunker.linkSevered, 'red')
6
+ throw new Error()
12
7
  }
13
8
 
14
9
  try {
@@ -28,32 +23,32 @@ const askAI = async ({ model, openAI, messages, response_format = { type: 'json_
28
23
  const statusCode = err.status || err.response?.status
29
24
  const isAuthError = err.message.includes('401') || err.message.includes('402') || [401, 402].includes(statusCode)
30
25
  if (isAuthError) {
31
- throw new Error(language(
32
- '[系统警告] YoRHa 司令部拒绝访问:API Key 无效或额度耗尽,请检查!',
33
- '[SYSTEM ALERT] YoRHa Command Center Access Denied: Invalid API Key or quota exhausted!'
34
- ))
26
+ yorha.commander.log(dialog.bunker.accessDenied, 'red')
27
+ throw new Error()
35
28
  }
36
29
 
37
- console.warn(chalk.yellow(language(
38
- `[系统警告] 神经云网络连接不稳,正在尝试重新链接... (第 ${retryCount + 1} 次重试)`,
39
- `[SYSTEM ALERT] Neural Network instability detected. Attempting to re-establish link... (Retry #${retryCount + 1})`
40
- )), err.message)
30
+ yorha.commander.log(dialog.bunker.networkInstability(retryCount + 1))
41
31
 
42
- return askAI({ model, messages, response_format, retryCount: retryCount + 1 })
32
+ return askAI({ model, yorha, dialog, openAI, messages, response_format, retryCount: retryCount + 1 })
43
33
  }
44
34
  }
45
35
 
46
- module.exports = ({ config, openAI, template, sysPrompt, apiPrompt, mockPrompt, linkerPrompt }) => {
36
+ module.exports = ({ ux, config, yorha, openAI, dialogs, template, ...prompts }) => {
47
37
 
48
38
  const sharp = require('sharp')
49
39
 
40
+ const { local } = ux
41
+ const dialog = dialogs[local]
50
42
  const { textModel, visionModel } = config
51
- const { UI_DESIGNER, API_DESIGNER, MOCK_DESIGNER } = sysPrompt
43
+ const { systemPrompt, apiPrompt, mockPrompt, linkerPrompt } = prompts
44
+ const { UI_DESIGNER, API_DESIGNER, MOCK_DESIGNER } = systemPrompt
52
45
 
53
46
  return {
54
47
  generateMock: async ({ columns, fileName }) => {
55
48
  return askAI({
49
+ yorha,
56
50
  openAI,
51
+ dialog,
57
52
  model: textModel,
58
53
  messages: [
59
54
  { role: 'system', content: MOCK_DESIGNER },
@@ -63,7 +58,9 @@ module.exports = ({ config, openAI, template, sysPrompt, apiPrompt, mockPrompt,
63
58
  },
64
59
  apiLinker: async ({ bunkerAnchors, realApis }) => {
65
60
  return askAI({
61
+ yorha,
66
62
  openAI,
63
+ dialog,
67
64
  model: textModel,
68
65
  messages: [
69
66
  { role: 'system', content: API_DESIGNER },
@@ -73,7 +70,9 @@ module.exports = ({ config, openAI, template, sysPrompt, apiPrompt, mockPrompt,
73
70
  },
74
71
  alignResponseFields: async ({ responseStr, resourceStr }) => {
75
72
  return askAI({
73
+ yorha,
76
74
  openAI,
75
+ dialog,
77
76
  model: textModel,
78
77
  messages: [
79
78
  { role: 'system', content: API_DESIGNER },
@@ -89,7 +88,9 @@ module.exports = ({ config, openAI, template, sysPrompt, apiPrompt, mockPrompt,
89
88
  const base64Image = compressedBuffer.toString('base64')
90
89
 
91
90
  return askAI({
91
+ yorha,
92
92
  openAI,
93
+ dialog,
93
94
  model: visionModel,
94
95
  messages: [
95
96
  { role: 'system', content: UI_DESIGNER },
@@ -101,7 +102,7 @@ module.exports = ({ config, openAI, template, sysPrompt, apiPrompt, mockPrompt,
101
102
  ]
102
103
  }
103
104
  ],
104
- response_format: taskType === 'page' ? { type: 'json_schema', strict: true, json_schema: require(`../schema/${template}/page.json`) } : { type: 'json_object' }
105
+ response_format: taskType === 'page' ? { type: 'json_schema', strict: true, json_schema: require(`../framework/${template}/schema/page.json`) } : { type: 'json_object' }
105
106
  })
106
107
  },
107
108
  }
@@ -10,6 +10,7 @@
10
10
  const fs = require('fs')
11
11
  const path = require('path')
12
12
  const { Segment, useDefault } = require('segmentit')
13
+ const stringify = require('json-stringify-pretty-compact')
13
14
  const segmentit = useDefault(new Segment())
14
15
 
15
16
  /**
@@ -87,7 +88,7 @@ const getLocalScore = (api, pageKeywords, moduleName) => {
87
88
  */
88
89
  const copyTemplateDir = (options, templateSubDir, targetSubDir) => {
89
90
  const targetDir = path.join(process.cwd(), targetSubDir)
90
- const sourceDir = path.join(__dirname, `../../templates/${options.template}/${templateSubDir}`)
91
+ const sourceDir = path.join(__dirname, `../framework/${options.template}/${templateSubDir}`)
91
92
  if (!fs.existsSync(sourceDir)) return
92
93
  fs.mkdirSync(targetDir, { recursive: true })
93
94
  fs.readdirSync(sourceDir).forEach(file => {
@@ -99,4 +100,6 @@ const copyTemplateDir = (options, templateSubDir, targetSubDir) => {
99
100
  })
100
101
  }
101
102
 
102
- module.exports = { getConfig, getLocalScore, getExistingMenus, copyTemplateDir, getSemanticKeywords }
103
+ const contextStringify = ({ context, indent = 4, maxLength = 200 }) => stringify.default(context, { indent, maxLength })
104
+
105
+ module.exports = { getConfig, getLocalScore, getExistingMenus, copyTemplateDir, contextStringify, getSemanticKeywords }
package/src/utils/ux.js CHANGED
@@ -6,8 +6,7 @@
6
6
  const chalk = require('chalk')
7
7
  const figlet = require('figlet')
8
8
 
9
- const isCN = Intl.DateTimeFormat().resolvedOptions().locale.includes('zh')
10
- const language = (zh, en) => (isCN ? zh : en)
9
+ const local = Intl.DateTimeFormat().resolvedOptions().locale.includes('zh') ? 'ZH-CN' : 'EN-US'
11
10
 
12
11
  const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
13
12
 
@@ -16,22 +15,26 @@ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
16
15
  * 模拟系统引导过程中的动画效果
17
16
  * @returns {void}
18
17
  */
19
- const bootSequence = async version => {
18
+ const bootSequence = async ({ dialog, version, bootTower, commander }) => {
20
19
  const lines = [
21
20
  chalk.cyan(figlet.textSync('AutoDev', { horizontalLayout: 'full' })),
22
- chalk.gray('Booting System...'),
23
- chalk.white(' [System] ') + chalk.green('Locale Detection: ') + chalk.cyan(language('ZH-CN', 'EN-US')),
24
- chalk.white(' [System] ') + chalk.green('YoRHa No.2 Type B Unit: ') + chalk.cyan('Online'),
25
- chalk.white(' [System] ') + chalk.green('Scanner Type 9S Unit: ') + chalk.cyan('Standby'),
26
- chalk.white(' [System] ') + chalk.green('Full-Channel Link: ') + chalk.cyan('Established'),
27
- chalk.white(' [Mission] ') + chalk.yellow('Bunker Construction Protocol: ') + chalk.cyan('v' + version),
28
- chalk.white(' [Bunker] ') + chalk.magenta('Glory to mankind. (人类荣光永存)'),
29
- chalk.gray('--------------------------------------------------\n')
21
+ chalk.gray('[BUNKER] Booting System...'),
22
+ chalk.white('[BUNKER] ') + chalk.green('Locale Detection: ') + chalk.cyan(local),
23
+ chalk.white('[BUNKER] ') + chalk.green('YoRHa No.2 Type B Unit: ') + chalk.cyan('Online'),
24
+ chalk.white('[BUNKER] ') + chalk.green('Scanner Type 9S Unit: ') + chalk.cyan('Standby'),
25
+ chalk.white('[BUNKER] ') + chalk.green('Full-Channel Link: ') + chalk.cyan('Established'),
26
+ chalk.white('[BUNKER] ') + chalk.yellow('Construction Protocol: ') + chalk.cyan('v' + version),
27
+ chalk.white('[BUNKER] ') + chalk.magenta('Glory to mankind. (人类荣光永存)'),
28
+ chalk.gray('--------------------------------------------------')
30
29
  ]
31
30
  for (const line of lines) {
32
31
  console.log(line)
33
32
  await sleep(line.includes('AutoDev') ? 300 : 80)
34
33
  }
34
+ if (bootTower) {
35
+ commander.log(dialog.bunker.towerOnline('42153'), 'magenta')
36
+ commander.log(dialog.bunker.towerConnected('42153'), 'magenta')
37
+ }
35
38
  }
36
39
 
37
40
  /**
@@ -83,17 +86,17 @@ const matrixEffect = async (duration = 1500) => {
83
86
  const interval = setInterval(() => {
84
87
  if (Date.now() > endTime) {
85
88
  clearInterval(interval)
86
- console.log(chalk.white(' [System] ') + chalk.green(language('所有构筑数据已同步至 Bunker 存储节点。', 'All data synced to Bunker storage nodes.')))
89
+ console.log(local ? '所有构筑数据已同步至 Bunker 存储节点。' : 'All data synced to Bunker storage nodes.')
87
90
  if (currentTotal !== 0) {
88
91
  if (isLegendary) {
89
- console.log(chalk.yellow.bold(language(` [Achievement] 物理克隆总数已超越 ${threshold} 战略阈值!当前战力:${currentTotal}`, ` [Achievement] Physical clone count has exceeded ${threshold} strategic threshold! Current power: ${currentTotal}`)))
90
- console.log(chalk.yellow(language(' [Bunker] 恭喜指挥官,您的构筑协议已成为人类荣光的一部分。', ' [Bunker] Congratulations, your construction protocol is now part of humanity.')))
92
+ console.log(chalk.yellow.bold(local ? `物理克隆总数已超越 ${threshold} 战略阈值!当前战力:${currentTotal}` : `Physical clone count has exceeded ${threshold} strategic threshold! Current power: ${currentTotal}`))
93
+ console.log(chalk.yellow(local ? '恭喜您指挥官,您的构筑协议已成为人类荣光的一部分。' : 'Congratulations, your construction protocol is now part of humanity.'))
91
94
  } else {
92
- console.log(chalk.cyan(language(` [System] 当前构筑总数:${currentTotal}。距离 ${threshold} 勋章还剩 ${threshold - currentTotal} 次。`, ` [System] Current clones: ${currentTotal}. ${threshold - currentTotal} to Achievement.`)))
95
+ console.log(chalk.cyan(local ? `当前构筑总数:${currentTotal}。距离 ${threshold} 勋章还剩 ${threshold - currentTotal} 次。` : `Current clones: ${currentTotal}. ${threshold - currentTotal} to Achievement.`))
93
96
  }
94
97
  }
95
- console.log(chalk.cyan(language(' [System] 如果它能帮您节省时间,请在 GitHub 上给它点个赞 ⭐。', ' [System] If it saves you time, feel free to give it a ⭐ on GitHub.')))
96
- console.log(chalk.cyan('\n[System] Signal Lost. Glory to Mankind.\n'))
98
+ console.log(chalk.cyan(local ? '如果它能帮您节省时间,请在 GitHub 上给它点个赞 ⭐。' : 'If it saves you time, feel free to give it a ⭐ on GitHub.'))
99
+ console.log(chalk.cyan(local ? '系统信号已丢失。' : 'Signal Lost'))
97
100
  process.exit(0)
98
101
  return
99
102
  }
@@ -112,4 +115,4 @@ const matrixEffect = async (duration = 1500) => {
112
115
  }, 40)
113
116
  }
114
117
 
115
- module.exports = { language, matrixEffect, bootSequence }
118
+ module.exports = { local, matrixEffect, bootSequence }