femo-plugin 1.0.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 (166) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +627 -0
  3. package/femo2host/__init__.py +4 -0
  4. package/femo2host/femoToolcall/chronica.py +156 -0
  5. package/femo2host/femoToolcall/femo-chat.mjs +69 -0
  6. package/femo2host/femoToolcall/femo_debugger.py +1515 -0
  7. package/femo2host/femo_api.py +437 -0
  8. package/femo2host/femo_gen_api.jsx +77 -0
  9. package/femoBridges/ContextExample.py +555 -0
  10. package/femoBridges/MemoryExample.py +163 -0
  11. package/femoBridges/__init__.py +1 -0
  12. package/femoBridges/getDir/get_dir.py +56 -0
  13. package/femoBridges/getDir//344/275/240/345/217/257/344/273/245/350/256/276/345/256/232/344/273/273/346/204/217/346/226/207/344/273/266/345/244/271/344/270/272/347/224/250/346/210/267/346/225/260/346/215/256/346/226/207/344/273/266/345/244/271.txt +10 -0
  14. package/femoBridges/llmBridge.py +247 -0
  15. package/femoBridges/llmProviders.py +308 -0
  16. package/femoCompiler/FEMO_CLIrenderer.py +198 -0
  17. package/femoCompiler/FEMO_config.py +35 -0
  18. package/femoCompiler/FEMO_errors.py +278 -0
  19. package/femoCompiler/FEMO_interpreter.py +163 -0
  20. package/femoCompiler/FEMO_normalizer.py +396 -0
  21. package/femoCompiler/FEMO_parser.py +2468 -0
  22. package/femoCompiler/FEMO_runtime.py +3630 -0
  23. package/femoCompiler/FEMO_scope_resolver.py +209 -0
  24. package/femoCompiler/__init__.py +1 -0
  25. package/femoCompiler/actor_resolver.py +86 -0
  26. package/femoCompiler/block_collector.py +441 -0
  27. package/femoCompiler/db_utils.py +485 -0
  28. package/femoCompiler/femoAsync.py +401 -0
  29. package/femoCompiler/host_manifest.py +68 -0
  30. package/femoCompiler/job_manager.py +767 -0
  31. package/femoCompiler/protocol.py +126 -0
  32. package/femoCompiler/save_dialog.py +402 -0
  33. package/femoCompiler/task_world.py +544 -0
  34. package/femoCompiler/vars/__init__.py +19 -0
  35. package/femoCompiler/vars/checkpoint.py +113 -0
  36. package/femoCompiler/vars/env.py +686 -0
  37. package/femoCompiler/vars/evaluator.py +567 -0
  38. package/femoCompiler/vars/join.py +303 -0
  39. package/femoCompiler/vars/merge.py +157 -0
  40. package/femoCompiler/vars/model.py +245 -0
  41. package/femoExamples/AI/345/211/252/350/247/206/351/242/221/AI/345/211/252/350/247/206/351/242/221.femo +192 -0
  42. package/femoExamples/AI/350/201/212/345/244/251/345/256/244/group-chat.femo +42 -0
  43. package/femoExamples/AI/350/201/212/345/244/251/345/256/244/random_wait_time.py +10 -0
  44. package/femoExamples/LuxFiat/luxfiat.femo +38 -0
  45. package/femoExamples/LuxFiat/wait.py +29 -0
  46. package/femoExamples/debug/347/245/236/345/231/250/debug/347/245/236/345/231/250.femo +222 -0
  47. package/femoExamples/discussion.femo +70 -0
  48. package/femoExamples/goal-mode.femo +23 -0
  49. package/femoExamples//345/270/270/347/224/250/345/267/245/345/205/267python/wait.py +29 -0
  50. package/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils.py +205 -0
  51. package/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils2.py +324 -0
  52. package/femoExamples//347/213/274/344/272/272/346/235/200//347/213/274/344/272/272/346/235/200-/350/255/246/351/225/277/347/211/210.femo +544 -0
  53. package/femoExamples//347/213/274/344/272/272/346/235/200//347/213/274/344/272/272/346/235/200.femo +331 -0
  54. package/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225/undercover_utils.py +683 -0
  55. package/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225//350/260/201/346/230/257/345/215/247/345/272/225-/350/217/234/345/270/202/345/234/272/345/261/200.femo +348 -0
  56. package/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225//350/260/201/346/230/257/345/215/247/345/272/225.femo +392 -0
  57. package/femoGen/document_ch.html +2352 -0
  58. package/femoGen/document_en.html +2279 -0
  59. package/femoGen/index.html +19 -0
  60. package/femoGen/intro_ch.html +942 -0
  61. package/femoGen/intro_en.html +932 -0
  62. package/femoGen/package-lock.json +1698 -0
  63. package/femoGen/package.json +19 -0
  64. package/femoGen/public/character_need.ttf +0 -0
  65. package/femoGen/public/favicon.ico +0 -0
  66. package/femoGen/public/femo-logo-slogan.svg +83 -0
  67. package/femoGen/public/femo-logo.svg +55 -0
  68. package/femoGen/public/logo-fullsize.ico +0 -0
  69. package/femoGen/src/FemoWorAuto.jsx +5444 -0
  70. package/femoGen/src/actionModal.jsx +358 -0
  71. package/femoGen/src/bubbleOverlay.jsx +701 -0
  72. package/femoGen/src/canvasNodes.jsx +608 -0
  73. package/femoGen/src/common.jsx +715 -0
  74. package/femoGen/src/debugPanel.jsx +530 -0
  75. package/femoGen/src/faIcons.jsx +84 -0
  76. package/femoGen/src/femoDiagnostics.js +122 -0
  77. package/femoGen/src/femoFileList.jsx +357 -0
  78. package/femoGen/src/femoGenerator.jsx +1198 -0
  79. package/femoGen/src/femoLog.js +107 -0
  80. package/femoGen/src/femoParser.jsx +2255 -0
  81. package/femoGen/src/femoPreview.jsx +297 -0
  82. package/femoGen/src/graphBuilder.jsx +358 -0
  83. package/femoGen/src/libPanel.jsx +519 -0
  84. package/femoGen/src/main.jsx +22 -0
  85. package/femoGen/src/mobileView.jsx +2796 -0
  86. package/femoGen/src/projectPanel.jsx +529 -0
  87. package/femoGen/src/soulModal.jsx +162 -0
  88. package/femoGen/src/styles/font.css +10 -0
  89. package/femoGen/src/themes.js +465 -0
  90. package/femoGen/src/useCanvasInteraction.jsx +319 -0
  91. package/femoGen/vite.config.js +28 -0
  92. package/femoGen//347/222/207/345/255/230/346/247/221.txt +15 -0
  93. package/hostAdapter/dshAdapter/README.md +68 -0
  94. package/hostAdapter/dshAdapter/build.mjs +75 -0
  95. package/hostAdapter/dshAdapter/client/client-ui/chat-node.tsx +339 -0
  96. package/hostAdapter/dshAdapter/client/client-ui/composer.tsx +997 -0
  97. package/hostAdapter/dshAdapter/client/client-ui/editor-page.tsx +726 -0
  98. package/hostAdapter/dshAdapter/client/client-ui/editor-view.tsx +88 -0
  99. package/hostAdapter/dshAdapter/client/client-ui/femo-stream-live.tsx +264 -0
  100. package/hostAdapter/dshAdapter/client/client-ui/proj2/frame-router.ts +282 -0
  101. package/hostAdapter/dshAdapter/client/client-ui/proj2/index.ts +44 -0
  102. package/hostAdapter/dshAdapter/client/client-ui/proj2/ledger.ts +329 -0
  103. package/hostAdapter/dshAdapter/client/client-ui/proj2/turn-view.tsx +211 -0
  104. package/hostAdapter/dshAdapter/client/client-ui/proj2/window-id.ts +28 -0
  105. package/hostAdapter/dshAdapter/client/client-ui/stream-store.ts +550 -0
  106. package/hostAdapter/dshAdapter/client/client-ui/styles.ts +144 -0
  107. package/hostAdapter/dshAdapter/client/client-ui/view-button.tsx +572 -0
  108. package/hostAdapter/dshAdapter/client/client-ui/view-state.ts +61 -0
  109. package/hostAdapter/dshAdapter/client/client.tsx +518 -0
  110. package/hostAdapter/dshAdapter/client/fa-icons.tsx +112 -0
  111. package/hostAdapter/dshAdapter/client/femo-reasoning-row.tsx +103 -0
  112. package/hostAdapter/dshAdapter/client/lineage-fork-native.jsx +624 -0
  113. package/hostAdapter/dshAdapter/client/lineage-fork.jsx +585 -0
  114. package/hostAdapter/dshAdapter/cordis.patch.yml +8 -0
  115. package/hostAdapter/dshAdapter/dshPatch/DSH-0.1.2-fork/344/277/256/346/224/271/351/234/200/346/261/202.md +184 -0
  116. package/hostAdapter/dshAdapter/dshPatch/MEOW_MODIFICATIONS.md +3105 -0
  117. package/hostAdapter/dshAdapter/dshPatch/patch-dsh-0.1.2-alpha.1.py +313 -0
  118. package/hostAdapter/dshAdapter/host/api-retry.ts +141 -0
  119. package/hostAdapter/dshAdapter/host/bridge.ts +224 -0
  120. package/hostAdapter/dshAdapter/host/config.ts +124 -0
  121. package/hostAdapter/dshAdapter/host/debug-log.ts +29 -0
  122. package/hostAdapter/dshAdapter/host/debug-run.ts +793 -0
  123. package/hostAdapter/dshAdapter/host/diag-feed.ts +56 -0
  124. package/hostAdapter/dshAdapter/host/engine-events.ts +891 -0
  125. package/hostAdapter/dshAdapter/host/engine-transcript.ts +122 -0
  126. package/hostAdapter/dshAdapter/host/femo-files.ts +210 -0
  127. package/hostAdapter/dshAdapter/host/god-mirror.ts +234 -0
  128. package/hostAdapter/dshAdapter/host/host-log.ts +101 -0
  129. package/hostAdapter/dshAdapter/host/http.ts +66 -0
  130. package/hostAdapter/dshAdapter/host/index.ts +633 -0
  131. package/hostAdapter/dshAdapter/host/list-cache.ts +183 -0
  132. package/hostAdapter/dshAdapter/host/main-actor.ts +853 -0
  133. package/hostAdapter/dshAdapter/host/main-delivery-queue.ts +115 -0
  134. package/hostAdapter/dshAdapter/host/native-state.ts +21 -0
  135. package/hostAdapter/dshAdapter/host/node-retry.ts +246 -0
  136. package/hostAdapter/dshAdapter/host/persona.ts +146 -0
  137. package/hostAdapter/dshAdapter/host/pre-step-gate.ts +95 -0
  138. package/hostAdapter/dshAdapter/host/proj-trace.ts +49 -0
  139. package/hostAdapter/dshAdapter/host/projection-input.ts +238 -0
  140. package/hostAdapter/dshAdapter/host/projection.ts +742 -0
  141. package/hostAdapter/dshAdapter/host/routes.ts +1196 -0
  142. package/hostAdapter/dshAdapter/host/run-control.ts +641 -0
  143. package/hostAdapter/dshAdapter/host/safe-steer.ts +33 -0
  144. package/hostAdapter/dshAdapter/host/section-gate.ts +108 -0
  145. package/hostAdapter/dshAdapter/host/session-events.ts +45 -0
  146. package/hostAdapter/dshAdapter/host/state-files.ts +301 -0
  147. package/hostAdapter/dshAdapter/host/stream-frames.ts +229 -0
  148. package/hostAdapter/dshAdapter/host/subagent-native.ts +997 -0
  149. package/hostAdapter/dshAdapter/host/subagent.ts +1205 -0
  150. package/hostAdapter/dshAdapter/host/tools.ts +486 -0
  151. package/hostAdapter/dshAdapter/host/windowing-native.ts +294 -0
  152. package/hostAdapter/dshAdapter/host.manifest.json +6 -0
  153. package/hostAdapter/dshAdapter/lib/client.js +19161 -0
  154. package/hostAdapter/dshAdapter/lib/client.js.map +7 -0
  155. package/hostAdapter/dshAdapter/lib/index.js +8173 -0
  156. package/hostAdapter/dshAdapter/lib/index.js.map +7 -0
  157. package/hostAdapter/dshAdapter/package-lock.json +500 -0
  158. package/hostAdapter/dshAdapter/package.json +55 -0
  159. package/hostAdapter/dshAdapter/pnpm-lock.yaml +596 -0
  160. package/hostAdapter/dshAdapter/pnpm-workspace.yaml +2 -0
  161. package/hostAdapter/dshAdapter/python/dev-bridge-test.py +43 -0
  162. package/hostAdapter/dshAdapter/python/femo_bridge.py +533 -0
  163. package/hostAdapter/dshAdapter/tsconfig.host.json +9 -0
  164. package/hostAdapter/dshAdapter/tsconfig.json +21 -0
  165. package/package.json +40 -0
  166. package//350/257/255/346/263/225/346/226/207/346/241/243.md +1136 -0
@@ -0,0 +1,297 @@
1
+ // ════════════════════════════════════════
2
+ // ═══════. femoPreview.jsx ═════════
3
+ // ════════════════════════════════════════
4
+
5
+
6
+ import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';
7
+
8
+ // 头排统一芯片配方(2026-09-07):复制/图到文本/文本到图/恢复四键同构——
9
+ // 浅色同系底 + 1px 同色细边 + 同字号字重,仅用颜色区分语义。可点击态用
10
+ // 主题强调色(灰底像禁用,用户反馈);文本到图有未应用修改时用更强填充。
11
+ // 色值全走主题 CSS var,深浅主题自适应。
12
+ const PRIMARY = 'var(--femo-primary)';
13
+ const chip = (color, active = false) => ({
14
+ padding: '3px 10px',
15
+ borderRadius: 'var(--femo-radius-md)',
16
+ background: `color-mix(in srgb, ${color} ${active ? 16 : 10}%, transparent)`,
17
+ border: `1px solid color-mix(in srgb, ${color} ${active ? 45 : 35}%, transparent)`,
18
+ color,
19
+ cursor: 'pointer',
20
+ fontSize: 10,
21
+ fontWeight: 700,
22
+ fontFamily: 'var(--femo-font-sans)',
23
+ transition: 'background 0.15s, color 0.15s, border-color 0.15s',
24
+ });
25
+
26
+ function FemoPreview({ value, onChange, error, warnings = [], dirty, onApply, onRestore, onGraphToFemo }) {
27
+ const lineNumbersRef = useRef(null);
28
+ const textareaRef = useRef(null);
29
+ const highlightRef = useRef(null);
30
+ const [lineCount, setLineCount] = useState(1);
31
+ // 复制回执:按钮短暂变「✓ 已复制」(成功绿),1.6s 自动还原。
32
+ const [copied, setCopied] = useState(false);
33
+ const copyTimerRef = useRef(null);
34
+ // 图↔文同步回执(2026-09-07):与复制同款设计语言。flash 窗口期内按钮
35
+ // 文案/配色按 error prop 实时推导——onApply 同步 setFemoError,与
36
+ // setFlash 同一批次提交,render 时 error 已是新值,无需额外状态。
37
+ const [g2tFlash, setG2tFlash] = useState(false);
38
+ const g2tTimerRef = useRef(null);
39
+ const [applyFlash, setApplyFlash] = useState(false);
40
+ const applyTimerRef = useRef(null);
41
+
42
+ useEffect(() => () => {
43
+ if (copyTimerRef.current) clearTimeout(copyTimerRef.current);
44
+ if (g2tTimerRef.current) clearTimeout(g2tTimerRef.current);
45
+ if (applyTimerRef.current) clearTimeout(applyTimerRef.current);
46
+ }, []);
47
+
48
+ const flash = (setter, timerRef, ms = 1600) => {
49
+ if (timerRef.current) clearTimeout(timerRef.current);
50
+ setter(true);
51
+ timerRef.current = setTimeout(() => setter(false), ms);
52
+ };
53
+
54
+ const handleCopy = useCallback(async () => {
55
+ let ok = false;
56
+ try {
57
+ if (navigator.clipboard && window.isSecureContext) {
58
+ await navigator.clipboard.writeText(value || '');
59
+ ok = true;
60
+ } else {
61
+ // 非安全上下文(如 http://tailscale-ip 手机访问)剪贴板 API 不可用
62
+ // → 隐藏 textarea + execCommand 降级。
63
+ const ta = document.createElement('textarea');
64
+ ta.value = value || '';
65
+ ta.style.position = 'fixed';
66
+ ta.style.opacity = '0';
67
+ document.body.appendChild(ta);
68
+ ta.select();
69
+ ok = document.execCommand('copy');
70
+ document.body.removeChild(ta);
71
+ }
72
+ } catch {
73
+ ok = false;
74
+ }
75
+ if (copyTimerRef.current) clearTimeout(copyTimerRef.current);
76
+ setCopied(ok);
77
+ copyTimerRef.current = setTimeout(() => setCopied(false), 1600);
78
+ }, [value]);
79
+
80
+ // 从错误信息提取行号:优先取统一报错链路的结构化诊断(精确),
81
+ // 否则退回正则匹配「第 N 行:」前缀(formatDiagnostic 保证该前缀存在)。
82
+ const errorLine = useMemo(() => {
83
+ if (!error) return null;
84
+ const diag = (Array.isArray(error?.diagnostics) ? error.diagnostics : [])
85
+ .find((d) => d?.severity === 'error' && d.line != null);
86
+ if (diag) return diag.line;
87
+ const match = error.match(/第\s*(\d+)\s*行/);
88
+ return match ? parseInt(match[1], 10) : null;
89
+ }, [error]);
90
+
91
+ useEffect(() => {
92
+ setLineCount(value.split('\n').length);
93
+ }, [value]);
94
+
95
+ const handleScroll = useCallback(() => {
96
+ if (lineNumbersRef.current && textareaRef.current) {
97
+ lineNumbersRef.current.scrollTop = textareaRef.current.scrollTop;
98
+ }
99
+ // 同步高亮条的位置
100
+ if (highlightRef.current && textareaRef.current && errorLine != null) {
101
+ const scrollTop = textareaRef.current.scrollTop;
102
+ const lineHeight = 18.9; // 10.5px * 1.8
103
+ highlightRef.current.style.top =
104
+ 11 + (errorLine - 1) * lineHeight - scrollTop + 'px';
105
+ }
106
+ }, [errorLine]);
107
+
108
+ // 当错误行号或内容变化时,更新高亮条位置(基于当前滚动位置)
109
+ useEffect(() => {
110
+ if (textareaRef.current && highlightRef.current && errorLine != null) {
111
+ const scrollTop = textareaRef.current.scrollTop;
112
+ const lineHeight = 18.9;
113
+ highlightRef.current.style.top =
114
+ 11 + (errorLine - 1) * lineHeight - scrollTop + 'px';
115
+ }
116
+ }, [errorLine, value]);
117
+
118
+ return (
119
+ <div
120
+ style={{
121
+ flex: 1,
122
+ display: 'flex',
123
+ flexDirection: 'column',
124
+ overflow: 'hidden',
125
+ padding: '14px 14px 14px',
126
+ }}
127
+ >
128
+ <div
129
+ style={{
130
+ display: 'flex',
131
+ justifyContent: 'space-between',
132
+ alignItems: 'center',
133
+ marginBottom: 9,
134
+ }}
135
+ >
136
+ <span
137
+ style={{
138
+ fontSize: 9.5,
139
+ fontWeight: 800,
140
+ color: 'var(--femo-neutral)',
141
+ textTransform: 'uppercase',
142
+ letterSpacing: '0.1em',
143
+ }}
144
+ >
145
+ FEMO 预览
146
+ </span>
147
+ <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
148
+ {error && (
149
+ <button onClick={onRestore} style={chip('var(--femo-warning)', true)}>
150
+ 恢复
151
+ </button>
152
+ )}
153
+ <button
154
+ onClick={handleCopy}
155
+ title="复制全文到剪贴板"
156
+ style={chip(copied ? 'var(--femo-success)' : PRIMARY, copied)}
157
+ >
158
+ {copied ? '✓ 已复制' : '复制'}
159
+ </button>
160
+ <button
161
+ onClick={() => { onGraphToFemo?.(); flash(setG2tFlash, g2tTimerRef); }}
162
+ style={chip(g2tFlash ? 'var(--femo-success)' : PRIMARY, g2tFlash)}
163
+ >
164
+ {g2tFlash ? '✓ 已生成' : '图到文本'}
165
+ </button>
166
+ <button
167
+ onClick={() => { onApply?.(); flash(setApplyFlash, applyTimerRef); }}
168
+ style={chip(
169
+ applyFlash
170
+ ? (error ? 'var(--femo-danger)' : 'var(--femo-success)')
171
+ : PRIMARY,
172
+ applyFlash || dirty,
173
+ )}
174
+ >
175
+ {applyFlash ? (error ? '✕ 失败' : '✓ 已应用') : '文本到图'}
176
+ </button>
177
+ </div>
178
+ </div>
179
+
180
+ {error && (
181
+ <div
182
+ style={{
183
+ marginBottom: 8,
184
+ padding: '6px 9px',
185
+ background: 'var(--femo-danger-soft)',
186
+ border: 'var(--femo-border-w) solid var(--femo-danger-border)',
187
+ borderRadius: 'var(--femo-radius-sm)',
188
+ fontSize: 10,
189
+ color: 'var(--femo-danger)',
190
+ lineHeight: 1.5,
191
+ maxHeight: 60,
192
+ overflow: 'auto',
193
+ }}
194
+ >
195
+ {error}
196
+ </div>
197
+ )}
198
+
199
+ {/* 非阻断警告(统一报错链路 warning 级):可运行,仅提醒 */}
200
+ {Array.isArray(warnings) && warnings.length > 0 && (
201
+ <div
202
+ style={{
203
+ marginBottom: 8,
204
+ padding: '6px 9px',
205
+ background: 'var(--femo-warning-soft)',
206
+ border: 'var(--femo-border-w) solid var(--femo-warning-border)',
207
+ borderRadius: 'var(--femo-radius-sm)',
208
+ fontSize: 10,
209
+ color: 'var(--femo-warning-strong)',
210
+ lineHeight: 1.5,
211
+ maxHeight: 60,
212
+ overflow: 'auto',
213
+ whiteSpace: 'pre-wrap',
214
+ }}
215
+ >
216
+ {warnings.map((w, i) => {
217
+ const loc = w?.line != null ? `第 ${w.line} 行: ` : '';
218
+ return <div key={i}>⚠ {loc}{w?.message || ''}</div>;
219
+ })}
220
+ </div>
221
+ )}
222
+
223
+ <div style={{ display: 'flex', flex: 1, minHeight: 0, borderRadius: 'var(--femo-radius-lg)', overflow: 'hidden' }}>
224
+ <div
225
+ ref={lineNumbersRef}
226
+ style={{
227
+ // 行号区整体缩为原 75%(30 → 22.5),左侧空间同步收紧
228
+ width: 22.5,
229
+ background: 'var(--femo-preview-bg-2)',
230
+ color: 'var(--femo-mobile-text-3)',
231
+ fontFamily: 'var(--femo-font-mono)',
232
+ fontSize: 10.5,
233
+ lineHeight: 1.8,
234
+ padding: '11px 3px 11px 6px',
235
+ textAlign: 'right',
236
+ userSelect: 'none',
237
+ overflow: 'hidden',
238
+ whiteSpace: 'pre',
239
+ borderRight: 'var(--femo-border-w) solid var(--femo-preview-border)',
240
+ }}
241
+ >
242
+ {Array.from({ length: lineCount }, (_, i) => (
243
+ <div key={i + 1}>{i + 1}</div>
244
+ ))}
245
+ </div>
246
+
247
+ {/* 带高亮覆盖层的文本区 */}
248
+ <div style={{ position: 'relative', flex: 1 }}>
249
+ <textarea
250
+ ref={textareaRef}
251
+ value={value}
252
+ onChange={(e) => {
253
+ onChange(e.target.value);
254
+ }}
255
+ onScroll={handleScroll}
256
+ spellCheck={false}
257
+ style={{
258
+ width: '100%',
259
+ height: '100%',
260
+ background: 'var(--femo-mobile-bg-2)',
261
+ // 左 padding 归零:顶格代码紧贴行号区边缘
262
+ padding: '11px 0',
263
+ overflow: 'auto',
264
+ resize: 'none',
265
+ fontFamily: 'var(--femo-font-mono)',
266
+ fontSize: 10.5,
267
+ lineHeight: 1.8,
268
+ color: 'var(--femo-mobile-text-2-alt)',
269
+ border: 'none',
270
+ outline: 'none',
271
+ whiteSpace: 'pre',
272
+ display: 'block', // 确保覆盖层可以正确定位
273
+ }}
274
+ />
275
+ {errorLine != null && (
276
+ <div
277
+ ref={highlightRef}
278
+ style={{
279
+ position: 'absolute',
280
+ left: 0,
281
+ right: 0,
282
+ top: 0,
283
+ height: 18.9,
284
+ background: 'var(--femo-danger-soft-2)',
285
+ borderLeft: 'var(--femo-border-w-accent) solid var(--femo-danger)',
286
+ pointerEvents: 'none',
287
+ zIndex: 1,
288
+ }}
289
+ />
290
+ )}
291
+ </div>
292
+ </div>
293
+ </div>
294
+ );
295
+ }
296
+
297
+ export { FemoPreview };
@@ -0,0 +1,358 @@
1
+
2
+ // ═══════════════════════════════════════════════════════════════
3
+ // ═══ graphBuilder.jsx ═══
4
+ // ═══════════════════════════════════════════════════════════════
5
+
6
+
7
+ import { nid, eid, mid, actionId, getNodeSize, makeDefaultNodes, SPW, SPH } from './common';
8
+
9
+ // ═══ Convert parsed FEMO to internal graph state ═══
10
+ function parsedToGraph(parsed, currentMode, currentModName) {
11
+ const proj = {
12
+ id: parsed.meta.id || '',
13
+ name: parsed.meta.name || '未命名项目',
14
+ version: parsed.meta.version || '1.0',
15
+ owner: parsed.meta.owner || '',
16
+ database: parsed.meta.database || '',
17
+ session: parsed.meta.session || '',
18
+ system_safety: parsed.meta.system_safety || '',
19
+ output_style: parsed.meta.output_style || '',
20
+ // 文件头原文(meta: 之前的注释)透传给生成端回写,见 femoParser.parseFEMO
21
+ preamble: parsed.preamble || '',
22
+ code: parsed.code || [],
23
+ vars: (parsed.vars || []).map(v => ({ name: v.name, defaultValue: v.defaultValue })),
24
+ actors: parsed.actors.map((a) => ({
25
+ name: a.name.startsWith('@') ? a.name : '@' + a.name,
26
+ type: a.type,
27
+ soul: a.soul,
28
+ source: a.source,
29
+ // ⚠️ tools 五态直通,不许归一:null=未声明(宿主默认全开)/ false=禁用 /
30
+ // true=显式全开 / []=显式空白名单(≡禁用)/ [..]=白名单。
31
+ // 历史教训:a.tools || [] 曾把 false 吞成 [](禁用标记静默丢失);
32
+ // ?? [] 也曾把「未声明」和「显式空列表」搅混(2026-09-12)。
33
+ tools: a.tools,
34
+ thinking: a.thinking || '',
35
+ })),
36
+ };
37
+
38
+ // ═══ 构建所有 action 列表(主流程 + 所有模块内部)═══
39
+ let libActions = parsed.actions.map((a) => ({
40
+ id: actionId(['mainflow'], a.name),
41
+ path: ['mainflow'],
42
+ ...a,
43
+ }));
44
+
45
+ // 提前收集各模块内部 action,并分配稳定 ID 与路径
46
+ const moduleInternalActions = [];
47
+ parsed.modules.forEach((m) => {
48
+ const modPath = m.path || ['mainflow', m.name];
49
+ (m.actions || []).forEach((a) => {
50
+ moduleInternalActions.push({
51
+ id: actionId(modPath, a.name),
52
+ path: modPath,
53
+ ...a,
54
+ });
55
+ });
56
+ });
57
+
58
+ // 合并所有 action,保证后续构建图时任何模块都能找到自己的 action
59
+ libActions = libActions.concat(moduleInternalActions);
60
+
61
+ // ═══ 构建所有模块图 ═══
62
+ const libModules = parsed.modules.map((m) => {
63
+ const modPath = m.path || ['mainflow', m.name];
64
+ const { nodes: mNodes, edges: mEdges } = flowDeclsToGraph(
65
+ m.nodeDecls,
66
+ m.edges,
67
+ 'module',
68
+ libActions, // 现在已经包含该模块的 action
69
+ parsed.modules,
70
+ m.layout || {}
71
+ );
72
+ // 该模块自身的 action 列表(从 moduleInternalActions 中过滤)
73
+ const internalActions = moduleInternalActions.filter(
74
+ (a) => a.path.length === modPath.length && a.path.every((seg, i) => seg === modPath[i])
75
+ );
76
+ return {
77
+ id: mid(),
78
+ name: m.name,
79
+ path: modPath,
80
+ meta: m.meta || {},
81
+ code: m.code || [],
82
+ vars: m.vars || [],
83
+ nodes: mNodes,
84
+ edges: mEdges,
85
+ internalActions,
86
+ };
87
+ });
88
+ // 注意:moduleInternalActions 已经合并入 libActions,无需再次合并
89
+
90
+ // Determine which flow to load onto canvas
91
+ let flowDecls, flowMode;
92
+ if (currentMode === 'module' && currentModName) {
93
+ const targetMod = parsed.modules.find((m) => m.name === currentModName);
94
+ if (targetMod) {
95
+ flowDecls = { nodeDecls: targetMod.nodeDecls, edges: targetMod.edges, layout: targetMod.layout || {} };
96
+ flowMode = 'module';
97
+ } else {
98
+ throw new Error(
99
+ `FEMO 脚本中未找到名为 "${currentModName}" 的 module 定义。请确认 module 名称拼写正确`
100
+ );
101
+ }
102
+ } else {
103
+ flowDecls = parsed.mainflow;
104
+ flowMode = 'mainflow';
105
+ }
106
+
107
+ const { nodes, edges } = flowDeclsToGraph(
108
+ flowDecls.nodeDecls,
109
+ flowDecls.edges,
110
+ flowMode,
111
+ libActions,
112
+ parsed.modules,
113
+ flowDecls.layout || {}
114
+ );
115
+
116
+ // 无论当前在哪个视图,都计算 mainflow 的图(供 flowStore 使用)
117
+ let mainflowNodes, mainflowEdges;
118
+ if (flowMode === 'mainflow') {
119
+ mainflowNodes = nodes;
120
+ mainflowEdges = edges;
121
+ } else {
122
+ //console.log('[parsedToGraph] flowMode !== mainflow, 重新构建 mainflow 图, layout:', parsed.mainflow.layout);
123
+ const mainResult = flowDeclsToGraph(
124
+ parsed.mainflow.nodeDecls,
125
+ parsed.mainflow.edges,
126
+ 'mainflow',
127
+ libActions,
128
+ parsed.modules,
129
+ parsed.mainflow.layout || {}
130
+ );
131
+ mainflowNodes = mainResult.nodes;
132
+ mainflowEdges = mainResult.edges;
133
+ //console.log('[parsedToGraph] mainflow 图构建结果: nodes=', mainflowNodes.map(n => `${n.label}(${Math.round(n.x)},${Math.round(n.y)})`));
134
+ }
135
+
136
+ return { proj, libActions, libModules, nodes, edges, mainflowNodes, mainflowEdges };
137
+ }
138
+
139
+ const SPECIAL_LABELS = new Set(['START', 'END', 'IN', 'OUT', 'BREAK']);
140
+
141
+ function flowDeclsToGraph(
142
+ nodeDecls,
143
+ flowEdges,
144
+ mode,
145
+ libActions,
146
+ parsedModules,
147
+ layoutMap = {}
148
+ ) {
149
+ const ANCHOR_X = 80;
150
+ const ANCHOR_Y = 200;
151
+ const lp = (label, defaultX, defaultY) => {
152
+ const e = layoutMap[label] || layoutMap[`[${label}]`];
153
+ if (e) {
154
+ return { x: e.dx !== undefined ? e.dx : 0, y: e.dy !== undefined ? e.dy : 0 };
155
+ }
156
+ return { x: defaultX, y: defaultY };
157
+ };
158
+ const nodes = [];
159
+ const edges = [];
160
+ const labelToId = new Map();
161
+
162
+ // Collect all labels referenced in flow edges
163
+ const allLabels = new Set();
164
+ for (const fe of flowEdges) {
165
+ allLabels.add(fe.srcLabel);
166
+ allLabels.add(fe.tgtLabel);
167
+ }
168
+
169
+ // Create special nodes from flow references
170
+ let specialY = 200;
171
+ const forNodeMap = new Map(); // forLabel -> { forNodeId, forOutNodeId }
172
+
173
+ // 先处理所有 FOR/PAR 节点的声明,创建 FOR/PAR 和对应出口节点
174
+ for (const decl of nodeDecls) {
175
+ if (decl.specialType === 'FOR' || decl.specialType === 'PAR') {
176
+ const isPar = decl.specialType === 'PAR';
177
+ const spType = isPar ? 'PAR' : 'FOR';
178
+ const outType = isPar ? 'par_out' : 'for_out';
179
+ const outSpType = isPar ? 'PAR_OUT' : 'FOR_OUT';
180
+ const forId = nid();
181
+ const outId = nid();
182
+ const pos = lp(`[${decl.label}]`, 200, specialY);
183
+ const xPos = pos.x;
184
+ const yPos = pos.y;
185
+
186
+ // 特殊节点
187
+ nodes.push({
188
+ id: forId,
189
+ type: 'special',
190
+ specialType: spType,
191
+ x: xPos,
192
+ y: yPos,
193
+ label: `[${decl.label}]`,
194
+ forOutNodeId: outId,
195
+ forCondition: decl.forCondition || '',
196
+ });
197
+
198
+ // 出口节点坐标:优先使用 sketch 中的 [label_出] 或 [label_out]
199
+ const outKey1 = `${decl.label}_出`;
200
+ const outKey2 = `${decl.label}_out`;
201
+ const outLayout = layoutMap[outKey1] || layoutMap[`[${outKey1}]`] || layoutMap[outKey2] || layoutMap[`[${outKey2}]`];
202
+ const outX = outLayout ? outLayout.dx : (xPos + SPW - 22);
203
+ const outY = outLayout ? outLayout.dy : (yPos + (SPH - 22) / 2);
204
+
205
+ // 出口节点
206
+ nodes.push({
207
+ id: outId,
208
+ type: outType,
209
+ specialType: outSpType,
210
+ x: outX,
211
+ y: outY,
212
+ label: `[${decl.label}_出]`,
213
+ forNodeId: forId,
214
+ });
215
+
216
+ labelToId.set(decl.label, forId);
217
+ labelToId.set(`[${decl.label}]`, forId);
218
+ labelToId.set(`${decl.label}_out`, outId);
219
+ labelToId.set(`[${decl.label}_out]`, outId);
220
+ labelToId.set(outKey1, outId);
221
+ labelToId.set(`[${outKey1}]`, outId);
222
+
223
+ forNodeMap.set(decl.label, { forId, outId });
224
+ specialY += 100;
225
+ }
226
+ }
227
+
228
+ // 再处理其他特殊节点
229
+ for (const lbl of allLabels) {
230
+ if (!SPECIAL_LABELS.has(lbl) && !lbl.match(/^(END|OUT|BREAK)_\d+$/))
231
+ continue;
232
+ // 跳过已经被 FOR 节点占用的标签
233
+ if (labelToId.has(lbl) || labelToId.has(`[${lbl}]`)) continue;
234
+
235
+ const baseType = lbl.replace(/_\d+$/, '');
236
+ const id = nid();
237
+ const defX = baseType === 'START' || baseType === 'IN' ? 0 : 600;
238
+ const pos = lp(`[${lbl}]`, defX, specialY);
239
+ nodes.push({
240
+ id,
241
+ type: 'special',
242
+ specialType: baseType,
243
+ x: pos.x,
244
+ y: pos.y,
245
+ label: `[${lbl}]`,
246
+ });
247
+ labelToId.set(lbl, id);
248
+ labelToId.set(`[${lbl}]`, id);
249
+ specialY += 80;
250
+ }
251
+
252
+ // Ensure default entry/exit exist
253
+ const entryType = mode === 'mainflow' ? 'START' : 'IN';
254
+ const exitType = mode === 'mainflow' ? 'END' : 'OUT';
255
+ if (!labelToId.has(entryType)) {
256
+ const id = nid();
257
+ nodes.push({
258
+ id,
259
+ type: 'special',
260
+ specialType: entryType,
261
+ x: 80,
262
+ y: 200,
263
+ label: `[${entryType}]`,
264
+ });
265
+ labelToId.set(entryType, id);
266
+ labelToId.set(`[${entryType}]`, id);
267
+ }
268
+ if (!labelToId.has(exitType)) {
269
+ const id = nid();
270
+ nodes.push({
271
+ id,
272
+ type: 'special',
273
+ specialType: exitType,
274
+ x: 600,
275
+ y: 200,
276
+ label: `[${exitType}]`,
277
+ });
278
+ labelToId.set(exitType, id);
279
+ labelToId.set(`[${exitType}]`, id);
280
+ }
281
+
282
+ // Create nodes from declarations
283
+ let col = 0,
284
+ row = 0;
285
+ for (const decl of nodeDecls) {
286
+ if (labelToId.has(decl.label) || labelToId.has(`[${decl.label}]`)) continue;
287
+
288
+ const id = nid();
289
+ const label = `[${decl.label}]`;
290
+ labelToId.set(decl.label, id);
291
+ labelToId.set(label, id);
292
+
293
+ const joinEntries = decl.joinEntries || [];
294
+
295
+ if (decl.ref === '') {
296
+ const pos = lp(label, 180 + col * 240, 120 + row * 140);
297
+ nodes.push({ id, type: 'position', x: pos.x, y: pos.y, label, joinEntries });
298
+ } else if (decl.ref.startsWith('&')) {
299
+ const modName = decl.ref.substring(1);
300
+ const modDef = parsedModules?.find((m) => m.name === modName);
301
+ const pos = lp(label, 180 + col * 260, 120 + row * 150);
302
+ nodes.push({ id, type: 'module', modRef: modName, modDef, x: pos.x, y: pos.y, label, joinEntries });
303
+ } else {
304
+ const actionDef = libActions.find((a) => a.name === decl.ref);
305
+ if (!actionDef) {
306
+ throw new Error(
307
+ `节点 "${decl.label}" 引用了未定义的 action "${decl.ref}"`
308
+ );
309
+ }
310
+ const pos = lp(label, 180 + col * 240, 120 + row * 140);
311
+ nodes.push({
312
+ id,
313
+ type: 'action',
314
+ actionId: actionDef.id,
315
+ x: pos.x,
316
+ y: pos.y,
317
+ label,
318
+ joinEntries,
319
+ });
320
+ }
321
+ col++;
322
+ if (col >= 3) {
323
+ col = 0;
324
+ row++;
325
+ }
326
+ }
327
+
328
+ // Create edges
329
+ for (const fe of flowEdges) {
330
+ //console.log('[flowDeclsToGraph] 处理边 srcLabel=', fe.srcLabel, 'tgtLabel=', fe.tgtLabel, 'cond=', fe.cond);
331
+ const srcId =
332
+ labelToId.get(fe.srcLabel) || labelToId.get(`[${fe.srcLabel}]`);
333
+ const tgtId =
334
+ labelToId.get(fe.tgtLabel) || labelToId.get(`[${fe.tgtLabel}]`);
335
+ //console.log('[flowDeclsToGraph] srcId=', srcId, 'tgtId=', tgtId);
336
+ if (!srcId)
337
+ throw new Error(
338
+ `流程引用了未声明的节点: "[${fe.srcLabel}]"。请确认该节点已在节点声明区定义,或它是合法的特殊节点`
339
+ );
340
+ if (!tgtId)
341
+ throw new Error(
342
+ `流程引用了未声明的节点: "[${fe.tgtLabel}]"。请确认该节点已在节点声明区定义,或它是合法的特殊节点`
343
+ );
344
+ edges.push({ id: eid(), src: srcId, tgt: tgtId, cond: fe.cond || '' });
345
+ }
346
+
347
+ // 强制入口节点为 (0,0),因为 sketch 所有坐标以此为基准
348
+ const entryNode = nodes.find(n => n.type === 'special' && (n.specialType === 'START' || n.specialType === 'IN'));
349
+ if (entryNode) {
350
+ entryNode.x = 0;
351
+ entryNode.y = 0;
352
+ }
353
+
354
+ return { nodes, edges };
355
+ }
356
+
357
+
358
+ export { parsedToGraph, flowDeclsToGraph };