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.
- package/LICENSE +201 -0
- package/README.md +627 -0
- package/femo2host/__init__.py +4 -0
- package/femo2host/femoToolcall/chronica.py +156 -0
- package/femo2host/femoToolcall/femo-chat.mjs +69 -0
- package/femo2host/femoToolcall/femo_debugger.py +1515 -0
- package/femo2host/femo_api.py +437 -0
- package/femo2host/femo_gen_api.jsx +77 -0
- package/femoBridges/ContextExample.py +555 -0
- package/femoBridges/MemoryExample.py +163 -0
- package/femoBridges/__init__.py +1 -0
- package/femoBridges/getDir/get_dir.py +56 -0
- 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
- package/femoBridges/llmBridge.py +247 -0
- package/femoBridges/llmProviders.py +308 -0
- package/femoCompiler/FEMO_CLIrenderer.py +198 -0
- package/femoCompiler/FEMO_config.py +35 -0
- package/femoCompiler/FEMO_errors.py +278 -0
- package/femoCompiler/FEMO_interpreter.py +163 -0
- package/femoCompiler/FEMO_normalizer.py +396 -0
- package/femoCompiler/FEMO_parser.py +2468 -0
- package/femoCompiler/FEMO_runtime.py +3630 -0
- package/femoCompiler/FEMO_scope_resolver.py +209 -0
- package/femoCompiler/__init__.py +1 -0
- package/femoCompiler/actor_resolver.py +86 -0
- package/femoCompiler/block_collector.py +441 -0
- package/femoCompiler/db_utils.py +485 -0
- package/femoCompiler/femoAsync.py +401 -0
- package/femoCompiler/host_manifest.py +68 -0
- package/femoCompiler/job_manager.py +767 -0
- package/femoCompiler/protocol.py +126 -0
- package/femoCompiler/save_dialog.py +402 -0
- package/femoCompiler/task_world.py +544 -0
- package/femoCompiler/vars/__init__.py +19 -0
- package/femoCompiler/vars/checkpoint.py +113 -0
- package/femoCompiler/vars/env.py +686 -0
- package/femoCompiler/vars/evaluator.py +567 -0
- package/femoCompiler/vars/join.py +303 -0
- package/femoCompiler/vars/merge.py +157 -0
- package/femoCompiler/vars/model.py +245 -0
- 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
- package/femoExamples/AI/350/201/212/345/244/251/345/256/244/group-chat.femo +42 -0
- package/femoExamples/AI/350/201/212/345/244/251/345/256/244/random_wait_time.py +10 -0
- package/femoExamples/LuxFiat/luxfiat.femo +38 -0
- package/femoExamples/LuxFiat/wait.py +29 -0
- package/femoExamples/debug/347/245/236/345/231/250/debug/347/245/236/345/231/250.femo +222 -0
- package/femoExamples/discussion.femo +70 -0
- package/femoExamples/goal-mode.femo +23 -0
- package/femoExamples//345/270/270/347/224/250/345/267/245/345/205/267python/wait.py +29 -0
- package/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils.py +205 -0
- package/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils2.py +324 -0
- 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
- package/femoExamples//347/213/274/344/272/272/346/235/200//347/213/274/344/272/272/346/235/200.femo +331 -0
- package/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225/undercover_utils.py +683 -0
- 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
- 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
- package/femoGen/document_ch.html +2352 -0
- package/femoGen/document_en.html +2279 -0
- package/femoGen/index.html +19 -0
- package/femoGen/intro_ch.html +942 -0
- package/femoGen/intro_en.html +932 -0
- package/femoGen/package-lock.json +1698 -0
- package/femoGen/package.json +19 -0
- package/femoGen/public/character_need.ttf +0 -0
- package/femoGen/public/favicon.ico +0 -0
- package/femoGen/public/femo-logo-slogan.svg +83 -0
- package/femoGen/public/femo-logo.svg +55 -0
- package/femoGen/public/logo-fullsize.ico +0 -0
- package/femoGen/src/FemoWorAuto.jsx +5444 -0
- package/femoGen/src/actionModal.jsx +358 -0
- package/femoGen/src/bubbleOverlay.jsx +701 -0
- package/femoGen/src/canvasNodes.jsx +608 -0
- package/femoGen/src/common.jsx +715 -0
- package/femoGen/src/debugPanel.jsx +530 -0
- package/femoGen/src/faIcons.jsx +84 -0
- package/femoGen/src/femoDiagnostics.js +122 -0
- package/femoGen/src/femoFileList.jsx +357 -0
- package/femoGen/src/femoGenerator.jsx +1198 -0
- package/femoGen/src/femoLog.js +107 -0
- package/femoGen/src/femoParser.jsx +2255 -0
- package/femoGen/src/femoPreview.jsx +297 -0
- package/femoGen/src/graphBuilder.jsx +358 -0
- package/femoGen/src/libPanel.jsx +519 -0
- package/femoGen/src/main.jsx +22 -0
- package/femoGen/src/mobileView.jsx +2796 -0
- package/femoGen/src/projectPanel.jsx +529 -0
- package/femoGen/src/soulModal.jsx +162 -0
- package/femoGen/src/styles/font.css +10 -0
- package/femoGen/src/themes.js +465 -0
- package/femoGen/src/useCanvasInteraction.jsx +319 -0
- package/femoGen/vite.config.js +28 -0
- package/femoGen//347/222/207/345/255/230/346/247/221.txt +15 -0
- package/hostAdapter/dshAdapter/README.md +68 -0
- package/hostAdapter/dshAdapter/build.mjs +75 -0
- package/hostAdapter/dshAdapter/client/client-ui/chat-node.tsx +339 -0
- package/hostAdapter/dshAdapter/client/client-ui/composer.tsx +997 -0
- package/hostAdapter/dshAdapter/client/client-ui/editor-page.tsx +726 -0
- package/hostAdapter/dshAdapter/client/client-ui/editor-view.tsx +88 -0
- package/hostAdapter/dshAdapter/client/client-ui/femo-stream-live.tsx +264 -0
- package/hostAdapter/dshAdapter/client/client-ui/proj2/frame-router.ts +282 -0
- package/hostAdapter/dshAdapter/client/client-ui/proj2/index.ts +44 -0
- package/hostAdapter/dshAdapter/client/client-ui/proj2/ledger.ts +329 -0
- package/hostAdapter/dshAdapter/client/client-ui/proj2/turn-view.tsx +211 -0
- package/hostAdapter/dshAdapter/client/client-ui/proj2/window-id.ts +28 -0
- package/hostAdapter/dshAdapter/client/client-ui/stream-store.ts +550 -0
- package/hostAdapter/dshAdapter/client/client-ui/styles.ts +144 -0
- package/hostAdapter/dshAdapter/client/client-ui/view-button.tsx +572 -0
- package/hostAdapter/dshAdapter/client/client-ui/view-state.ts +61 -0
- package/hostAdapter/dshAdapter/client/client.tsx +518 -0
- package/hostAdapter/dshAdapter/client/fa-icons.tsx +112 -0
- package/hostAdapter/dshAdapter/client/femo-reasoning-row.tsx +103 -0
- package/hostAdapter/dshAdapter/client/lineage-fork-native.jsx +624 -0
- package/hostAdapter/dshAdapter/client/lineage-fork.jsx +585 -0
- package/hostAdapter/dshAdapter/cordis.patch.yml +8 -0
- package/hostAdapter/dshAdapter/dshPatch/DSH-0.1.2-fork/344/277/256/346/224/271/351/234/200/346/261/202.md +184 -0
- package/hostAdapter/dshAdapter/dshPatch/MEOW_MODIFICATIONS.md +3105 -0
- package/hostAdapter/dshAdapter/dshPatch/patch-dsh-0.1.2-alpha.1.py +313 -0
- package/hostAdapter/dshAdapter/host/api-retry.ts +141 -0
- package/hostAdapter/dshAdapter/host/bridge.ts +224 -0
- package/hostAdapter/dshAdapter/host/config.ts +124 -0
- package/hostAdapter/dshAdapter/host/debug-log.ts +29 -0
- package/hostAdapter/dshAdapter/host/debug-run.ts +793 -0
- package/hostAdapter/dshAdapter/host/diag-feed.ts +56 -0
- package/hostAdapter/dshAdapter/host/engine-events.ts +891 -0
- package/hostAdapter/dshAdapter/host/engine-transcript.ts +122 -0
- package/hostAdapter/dshAdapter/host/femo-files.ts +210 -0
- package/hostAdapter/dshAdapter/host/god-mirror.ts +234 -0
- package/hostAdapter/dshAdapter/host/host-log.ts +101 -0
- package/hostAdapter/dshAdapter/host/http.ts +66 -0
- package/hostAdapter/dshAdapter/host/index.ts +633 -0
- package/hostAdapter/dshAdapter/host/list-cache.ts +183 -0
- package/hostAdapter/dshAdapter/host/main-actor.ts +853 -0
- package/hostAdapter/dshAdapter/host/main-delivery-queue.ts +115 -0
- package/hostAdapter/dshAdapter/host/native-state.ts +21 -0
- package/hostAdapter/dshAdapter/host/node-retry.ts +246 -0
- package/hostAdapter/dshAdapter/host/persona.ts +146 -0
- package/hostAdapter/dshAdapter/host/pre-step-gate.ts +95 -0
- package/hostAdapter/dshAdapter/host/proj-trace.ts +49 -0
- package/hostAdapter/dshAdapter/host/projection-input.ts +238 -0
- package/hostAdapter/dshAdapter/host/projection.ts +742 -0
- package/hostAdapter/dshAdapter/host/routes.ts +1196 -0
- package/hostAdapter/dshAdapter/host/run-control.ts +641 -0
- package/hostAdapter/dshAdapter/host/safe-steer.ts +33 -0
- package/hostAdapter/dshAdapter/host/section-gate.ts +108 -0
- package/hostAdapter/dshAdapter/host/session-events.ts +45 -0
- package/hostAdapter/dshAdapter/host/state-files.ts +301 -0
- package/hostAdapter/dshAdapter/host/stream-frames.ts +229 -0
- package/hostAdapter/dshAdapter/host/subagent-native.ts +997 -0
- package/hostAdapter/dshAdapter/host/subagent.ts +1205 -0
- package/hostAdapter/dshAdapter/host/tools.ts +486 -0
- package/hostAdapter/dshAdapter/host/windowing-native.ts +294 -0
- package/hostAdapter/dshAdapter/host.manifest.json +6 -0
- package/hostAdapter/dshAdapter/lib/client.js +19161 -0
- package/hostAdapter/dshAdapter/lib/client.js.map +7 -0
- package/hostAdapter/dshAdapter/lib/index.js +8173 -0
- package/hostAdapter/dshAdapter/lib/index.js.map +7 -0
- package/hostAdapter/dshAdapter/package-lock.json +500 -0
- package/hostAdapter/dshAdapter/package.json +55 -0
- package/hostAdapter/dshAdapter/pnpm-lock.yaml +596 -0
- package/hostAdapter/dshAdapter/pnpm-workspace.yaml +2 -0
- package/hostAdapter/dshAdapter/python/dev-bridge-test.py +43 -0
- package/hostAdapter/dshAdapter/python/femo_bridge.py +533 -0
- package/hostAdapter/dshAdapter/tsconfig.host.json +9 -0
- package/hostAdapter/dshAdapter/tsconfig.json +21 -0
- package/package.json +40 -0
- package//350/257/255/346/263/225/346/226/207/346/241/243.md +1136 -0
|
@@ -0,0 +1,793 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* debug-run.ts — 零 token 调试干跑(femo_debugger.py FakeHost)的两条消费路径。
|
|
3
|
+
*
|
|
4
|
+
* 同一个干跑器、同一份 DebugLogBus 流水,两种取用方式:
|
|
5
|
+
* ① 编辑器「🐞 调试」按钮 → POST /femo-plugin/debug-run:NDJSON 流式转发,
|
|
6
|
+
* 前端逐行渲染进调试窗(Print 效果)——人看;
|
|
7
|
+
* ② 主模型 femo-debug 工具 → collectDebugRun():整跑收集,流水 + 终报
|
|
8
|
+
* 一次性回给主模型——AI 写完剧本先干跑自检(2026-09-11 新增)。
|
|
9
|
+
*
|
|
10
|
+
* 两条路径共用同一份沙盒装配(spawnDebugger)与同一枚单飞闸(inFlight):
|
|
11
|
+
* 同一插件实例同时只允许一条干跑(femo_debugger 的类级 patch 是进程内的,
|
|
12
|
+
* 并发两条会互相污染 tracker——单飞是最便宜的诚实做法),第二条明确报错。
|
|
13
|
+
*
|
|
14
|
+
* 设计要点(两条路径一致):
|
|
15
|
+
* - 与正式运行链路完全解耦:不起 job、不碰 bridge stdio 协议、不发 SSE
|
|
16
|
+
* 广播——调试是独立一次性流;不调任何 LLM(FakeHost 替 AI/human 发言)。
|
|
17
|
+
* - 剧本落 cache/debug-sandbox/web-<ts>.femo(与 femo_debugger 的
|
|
18
|
+
* DB 沙盒同目录,只建不删——想清理手动删目录);流水落同目录
|
|
19
|
+
* web-<ts>.jsonl、终报落 web-<ts>.report.json,都留档可查。
|
|
20
|
+
* - 子进程经宿主 subprocess 服务(与 bridge 同一 python 解析);退出后
|
|
21
|
+
* 再 drain 残余日志,补发 debug_done 哨兵;客户端断开或 180s 看门狗
|
|
22
|
+
* 超时则 terminate(不留僵尸 python)。
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
26
|
+
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
27
|
+
import type { SubprocessHandle } from '@deepseek-ai/dsh-subprocess'
|
|
28
|
+
import { basename, dirname, join } from 'node:path'
|
|
29
|
+
import { mkdir, open, readFile, stat, writeFile } from 'node:fs/promises'
|
|
30
|
+
import { readBody, writeJson } from './http'
|
|
31
|
+
import { pushDiag } from './diag-feed'
|
|
32
|
+
import type { ResolvedConfig } from './config'
|
|
33
|
+
|
|
34
|
+
/** 单轮干跑通常秒级;par/fork 重试链可能慢(实测 139s),给 180s 上限。 */
|
|
35
|
+
const DEBUG_TIMEOUT_MS = 180_000
|
|
36
|
+
const TAIL_INTERVAL_MS = 150
|
|
37
|
+
/** 回传主模型的流水行数上限:超了中段省略(首 600 + 尾 900),完整流水在
|
|
38
|
+
* jsonl 落盘路径里——剪掉的是重复噪音,不是信息源。 */
|
|
39
|
+
const TRANSCRIPT_MAX_LINES = 1500
|
|
40
|
+
const TRANSCRIPT_HEAD_LINES = 600
|
|
41
|
+
/** stderr 回传上限(编译失败的 SyntaxError 原话在 traceback 末尾)。 */
|
|
42
|
+
const STDERR_MAX_CHARS = 2000
|
|
43
|
+
/** 终报渲染上限(变量快照/提示逐条列,超了截断并注明总数)。 */
|
|
44
|
+
const REPORT_SNAPSHOT_MAX = 40
|
|
45
|
+
const REPORT_WARNING_MAX = 20
|
|
46
|
+
|
|
47
|
+
interface DebugRunBody {
|
|
48
|
+
femo?: unknown
|
|
49
|
+
runs?: unknown
|
|
50
|
+
seed?: unknown
|
|
51
|
+
/** 只干跑某 module(femoGen 模块子画布里按「调试」时由前端按当前画布
|
|
52
|
+
* 推导;嵌套模块点路径 'Outer.Inner')。缺省=主画布=整剧本。
|
|
53
|
+
* 未知模块由调试器响亮报错(列出可用名,经 stderr 抵达)。 */
|
|
54
|
+
module?: unknown
|
|
55
|
+
/** 会话剧本原路径(前端传 savedPath):code: file:"xxx.py" 相对引用按它
|
|
56
|
+
* 所在目录解析——与正式运行同语义。缺省/目录不存在则回退沙盒目录
|
|
57
|
+
* (引用会 404,但报错响亮可见)。 */
|
|
58
|
+
scriptPath?: unknown
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** 一次干跑请求(两条路径共用)。 */
|
|
62
|
+
export interface DebugRunRequest {
|
|
63
|
+
/** 剧本文本(挂载版/编辑器版——由调用方决定取哪一份)。 */
|
|
64
|
+
femo: string
|
|
65
|
+
/** 剧本原路径:file: 相对引用按它所在目录解析;缺省回退沙盒目录。 */
|
|
66
|
+
scriptPath?: string
|
|
67
|
+
/** 只干跑某 module(点路径);缺省整剧本。 */
|
|
68
|
+
module?: string
|
|
69
|
+
/** 跑几轮(每轮换种子);缺省 1,钳到 1~20。 */
|
|
70
|
+
runs?: number
|
|
71
|
+
/** 起始种子(可复现);缺省由调试器随机。 */
|
|
72
|
+
seed?: number
|
|
73
|
+
/** 看门狗上限(毫秒);缺省 180s。仅 collect 路径用(测试注短值)。 */
|
|
74
|
+
timeoutMs?: number
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** 终报里的一轮结局(femo_debugger --report 的 runs 元素)。 */
|
|
78
|
+
export interface DebugReportRun {
|
|
79
|
+
seed: number
|
|
80
|
+
outcome: string
|
|
81
|
+
error: string | null
|
|
82
|
+
elapsed: number
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** 变量赋值快照(old/new 已是调试器侧 repr 字符串)。 */
|
|
86
|
+
export interface DebugVarSnapshot {
|
|
87
|
+
node: string
|
|
88
|
+
var: string
|
|
89
|
+
old: unknown
|
|
90
|
+
new: unknown
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** femo_debugger --report 写出的 JSON 终报形状(字段名即协议,snake_case)。 */
|
|
94
|
+
export interface DebugRunReport {
|
|
95
|
+
script: string
|
|
96
|
+
module_mode: string | null
|
|
97
|
+
runs: DebugReportRun[]
|
|
98
|
+
node_visits: Record<string, number>
|
|
99
|
+
node_order: string[]
|
|
100
|
+
edges_taken: string[]
|
|
101
|
+
total_edges: number
|
|
102
|
+
var_snapshots: DebugVarSnapshot[]
|
|
103
|
+
guess_warnings: string[]
|
|
104
|
+
silences: string[]
|
|
105
|
+
flaky_fired: string[]
|
|
106
|
+
/** 一次没走到的作者节点;2026-09-11 起写进终报,老版本无此键。 */
|
|
107
|
+
unreached_nodes?: string[]
|
|
108
|
+
/** module 模式静态检测:被测模块 flow 是否有 [OUT]/[BREAK](null/缺省=
|
|
109
|
+
* 非 module 模式或老版本)。false=持续循环型——max_steps 结局属预期。 */
|
|
110
|
+
module_has_out?: boolean | null
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** 整跑收集结果(femo-debug 工具的数据面)。 */
|
|
114
|
+
export interface DebugRunCollect {
|
|
115
|
+
exitCode: number
|
|
116
|
+
/** 看门狗超时被强制终止(疑似死循环/链路太慢)。 */
|
|
117
|
+
timedOut: boolean
|
|
118
|
+
/** 调用方中途撤销(工具被取消)而终止。 */
|
|
119
|
+
aborted: boolean
|
|
120
|
+
/** 实际请求的轮数。 */
|
|
121
|
+
runs: number
|
|
122
|
+
seed?: number
|
|
123
|
+
/** 本场干跑墙钟耗时(毫秒)——多轮是线性叠加:用户实测「AI 调一次等很久」
|
|
124
|
+
* 就是 runs=6 把 6 轮的秒数加了六份,回传里给出总耗时便于模型/人对照。 */
|
|
125
|
+
elapsedMs: number
|
|
126
|
+
/** DebugLogBus 记录原样(解析失败的行已剔除)。 */
|
|
127
|
+
records: Array<Record<string, unknown>>
|
|
128
|
+
/** 终报;未生成(编译失败/超时)时为 undefined——stderr 里有原话。 */
|
|
129
|
+
report?: DebugRunReport
|
|
130
|
+
/** 流水文本(与 femoGen 调试窗同款渲染)。 */
|
|
131
|
+
transcript: string
|
|
132
|
+
/** 流水里省略掉的行数(0=完整)。 */
|
|
133
|
+
transcriptDropped: number
|
|
134
|
+
/** 被中断(撤销/超时)且已产出流水时,同目录留一份可读的部分信息留档
|
|
135
|
+
* (<log>.partial.md)——框架会把 aborted 的工具结果整条丢掉(用户按停止
|
|
136
|
+
* 即如此),留档保证「数据实时产出了却没人看到」不至于白跑。 */
|
|
137
|
+
partialPath?: string
|
|
138
|
+
/** 引擎 stderr 尾部(编译失败的 SyntaxError 原话在末尾)。 */
|
|
139
|
+
stderr: string
|
|
140
|
+
/** 本次干跑的沙盒剧本 / 流水 / 终报路径(留档可查)。 */
|
|
141
|
+
sandboxScript: string
|
|
142
|
+
logPath: string
|
|
143
|
+
reportPath: string
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** 同一插件实例同时只跑一条干跑(见模块注释「单飞闸」)。 */
|
|
147
|
+
let inFlight = false
|
|
148
|
+
|
|
149
|
+
const sleep = (ms: number): Promise<void> => new Promise((resolve) => { setTimeout(resolve, ms) })
|
|
150
|
+
|
|
151
|
+
/** runs 钳制:NaN/0/负数 → 1,上限 20(与前端按钮同口径)。 */
|
|
152
|
+
function clampRuns(value: unknown): number {
|
|
153
|
+
return Math.min(Math.max(Math.trunc(Number(value)) || 1, 1), 20)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** seed 归一:非有限数一律当"没给"(调试器自选随机种子)。 */
|
|
157
|
+
function normalizeSeed(value: unknown): number | undefined {
|
|
158
|
+
return value !== undefined && value !== null && Number.isFinite(Number(value))
|
|
159
|
+
? Math.trunc(Number(value))
|
|
160
|
+
: undefined
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** module 归一:剥空白与 '&' 前缀(用户习惯 &Mod 引用);空串当"没给"
|
|
164
|
+
* (=整剧本)。合法性(段存在/嵌套路径)交给调试器编译时响亮校验。 */
|
|
165
|
+
function normalizeModule(value: unknown): string | undefined {
|
|
166
|
+
const s = typeof value === 'string' ? value.trim().replace(/^&+/, '') : ''
|
|
167
|
+
return s.length > 0 ? s : undefined
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** 子进程装配结果(stdout/stderr 累积数组:流式模式下为空)。 */
|
|
171
|
+
interface DebugSpawn {
|
|
172
|
+
procHandle: SubprocessHandle
|
|
173
|
+
sandboxScript: string
|
|
174
|
+
logPath: string
|
|
175
|
+
reportPath: string
|
|
176
|
+
out: string[]
|
|
177
|
+
err: string[]
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* 沙盒装配 + 起子进程(两条路径共用)。失败抛 Error(原话上浮,调用方决定
|
|
182
|
+
* 是 500 还是工具 ❌)。mode='capture' 时 stdout/stderr 进数组(工具路径要
|
|
183
|
+
* 拿编译失败的 traceback);'stream' 时 stdout 丢弃、stderr 转发控制台——
|
|
184
|
+
* 与调试窗按钮的历史行为逐字一致(引擎 tracebacks 不能静默消失)。
|
|
185
|
+
*/
|
|
186
|
+
async function spawnDebugger(
|
|
187
|
+
ctx: Context,
|
|
188
|
+
resolved: ResolvedConfig,
|
|
189
|
+
req: DebugRunRequest,
|
|
190
|
+
mode: 'stream' | 'capture',
|
|
191
|
+
): Promise<DebugSpawn> {
|
|
192
|
+
const subprocess = ctx.get('subprocess') as {
|
|
193
|
+
resolveExecutable(command: string): Promise<string>
|
|
194
|
+
spawn(spec: unknown): SubprocessHandle
|
|
195
|
+
} | undefined
|
|
196
|
+
/** 干跑沙盒滚动清理:删除 mtime 超过 3 天的旧文件(web-* 三件套与 run-*.wor)。
|
|
197
|
+
* 2026-09-12 由「只建不删」改制——只增不减的沙盒会无限长胖。单文件失败
|
|
198
|
+
* 不阻断;整体失败不影响干跑主路。 */
|
|
199
|
+
async function sweepDebugSandbox(sandboxDir: string, keepDays = 3): Promise<void> {
|
|
200
|
+
try {
|
|
201
|
+
const { readdir, stat, unlink } = await import('node:fs/promises')
|
|
202
|
+
const cutoff = Date.now() - keepDays * 86400_000
|
|
203
|
+
for (const name of await readdir(sandboxDir)) {
|
|
204
|
+
const fp = join(sandboxDir, name)
|
|
205
|
+
try {
|
|
206
|
+
const st = await stat(fp)
|
|
207
|
+
if (st.isFile() && st.mtimeMs < cutoff) await unlink(fp)
|
|
208
|
+
} catch { /* 单文件失败不阻断 */ }
|
|
209
|
+
}
|
|
210
|
+
} catch { /* 清理失败不影响干跑主路 */ }
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
if (subprocess === undefined) {
|
|
214
|
+
throw new Error('subprocess 服务不可用(无法拉起调试器子进程)')
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// 剧本与日志都落调试沙盒(滚动保留最近 3 天,与 femo_debugger 的 .wor 同策略)
|
|
218
|
+
const sandboxDir = join(resolved.femoRoot, 'cache', 'debug-sandbox')
|
|
219
|
+
await mkdir(sandboxDir, { recursive: true })
|
|
220
|
+
void sweepDebugSandbox(sandboxDir)
|
|
221
|
+
const stamp = Date.now()
|
|
222
|
+
const sandboxScript = join(sandboxDir, `web-${stamp}.femo`)
|
|
223
|
+
const logPath = join(sandboxDir, `web-${stamp}.jsonl`)
|
|
224
|
+
const reportPath = join(sandboxDir, `web-${stamp}.report.json`)
|
|
225
|
+
await writeFile(sandboxScript, req.femo, 'utf8')
|
|
226
|
+
|
|
227
|
+
const pythonPath = await subprocess.resolveExecutable(resolved.python)
|
|
228
|
+
// code: file:"xxx.py" 相对引用的解析目录:带了剧本原路径(savedPath)就按
|
|
229
|
+
// 其所在目录解析(与正式运行同语义);没带则回退沙盒目录——引用会
|
|
230
|
+
// FileNotFoundError,但错误经 run_end 记录响亮抵达,不静默。
|
|
231
|
+
let baseDirArg: string[] = []
|
|
232
|
+
const savedScriptPath = req.scriptPath?.trim() ?? ''
|
|
233
|
+
if (savedScriptPath.length > 0) {
|
|
234
|
+
const dir = dirname(savedScriptPath)
|
|
235
|
+
try {
|
|
236
|
+
await stat(dir)
|
|
237
|
+
baseDirArg = ['--base-dir', dir]
|
|
238
|
+
} catch {
|
|
239
|
+
console.log(`[femo-plugin] debug-run: scriptPath 目录不存在,回退沙盒解析: ${dir}`)
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
const argv = [
|
|
243
|
+
pythonPath,
|
|
244
|
+
join(resolved.femoRoot, 'femo2host', 'femoToolcall', 'femo_debugger.py'),
|
|
245
|
+
'run', sandboxScript,
|
|
246
|
+
'--quiet', '--log-jsonl', logPath,
|
|
247
|
+
// 终报 JSON:工具路径的唯一权威汇总(人读版 print_report 只进 stdout)。
|
|
248
|
+
'--report', reportPath,
|
|
249
|
+
'--runs', String(clampRuns(req.runs)),
|
|
250
|
+
...baseDirArg,
|
|
251
|
+
]
|
|
252
|
+
const seed = normalizeSeed(req.seed)
|
|
253
|
+
if (seed !== undefined) argv.push('--seed', String(seed))
|
|
254
|
+
// 模块单测(femoGen 模块子画布按「调试」/ femo-debug 工具带 module 时):
|
|
255
|
+
// 调试器合成 wrapper 直进被测模块,嵌套用点路径;未知模块调试器响亮报错。
|
|
256
|
+
const debugModule = normalizeModule(req.module)
|
|
257
|
+
if (debugModule !== undefined) argv.push('--module', debugModule)
|
|
258
|
+
|
|
259
|
+
const out: string[] = []
|
|
260
|
+
const err: string[] = []
|
|
261
|
+
let procHandle: SubprocessHandle
|
|
262
|
+
try {
|
|
263
|
+
procHandle = subprocess.spawn({
|
|
264
|
+
argv,
|
|
265
|
+
cwd: resolved.femoRoot,
|
|
266
|
+
stdio: { stdin: 'ignore', stdout: mode === 'capture' ? 'pipe' : 'ignore', stderr: 'pipe' },
|
|
267
|
+
graceMs: 3000,
|
|
268
|
+
env: { PYTHONIOENCODING: 'utf-8', PYTHONUTF8: '1' },
|
|
269
|
+
})
|
|
270
|
+
} catch (error: unknown) {
|
|
271
|
+
throw new Error(`调试器子进程启动失败: ${String(error)}`)
|
|
272
|
+
}
|
|
273
|
+
procHandle.stderr?.on('data', (chunk: Buffer) => {
|
|
274
|
+
for (const line of chunk.toString('utf8').split(/\r?\n/)) {
|
|
275
|
+
if (line.trim().length === 0) continue
|
|
276
|
+
if (mode === 'capture') err.push(line)
|
|
277
|
+
// 【2026-09-11 Host 页口径】调试器(引擎)的 stderr 是"引擎的话",绕过
|
|
278
|
+
// console 直写 stdout——harness 日志照旧有,但不进调试窗『Host』页。
|
|
279
|
+
else process.stdout.write(`[femo-debug:stderr] ${line}\n`)
|
|
280
|
+
// 【2026-09-11 编译器页补 stderr】两条路径都补一路进调试窗『编译器』页
|
|
281
|
+
// (capture 走 err 回调用方,stream 是面板「编译」按钮那条)。
|
|
282
|
+
pushDiag('engine', `[stderr] ${line}`.slice(0, 400))
|
|
283
|
+
}
|
|
284
|
+
})
|
|
285
|
+
if (mode === 'capture') {
|
|
286
|
+
procHandle.stdout?.on('data', (chunk: Buffer) => { out.push(chunk.toString('utf8')) })
|
|
287
|
+
}
|
|
288
|
+
return { procHandle, sandboxScript, logPath, reportPath, out, err }
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** POST /femo-plugin/debug-run:NDJSON 流式响应(每行一条 DebugLogBus 记录)。 */
|
|
292
|
+
export async function handleDebugRun(
|
|
293
|
+
req: IncomingMessage,
|
|
294
|
+
res: ServerResponse,
|
|
295
|
+
ctx: Context,
|
|
296
|
+
resolved: ResolvedConfig,
|
|
297
|
+
): Promise<void> {
|
|
298
|
+
if (inFlight) {
|
|
299
|
+
writeJson(res, 409, { ok: false, error: '已有调试干跑在进行中,请等它结束再点' })
|
|
300
|
+
return
|
|
301
|
+
}
|
|
302
|
+
const body = await readBody(req) as DebugRunBody
|
|
303
|
+
const femo = typeof body.femo === 'string' ? body.femo : ''
|
|
304
|
+
if (femo.trim().length === 0) {
|
|
305
|
+
writeJson(res, 400, { ok: false, error: 'femo 剧本文本为空' })
|
|
306
|
+
return
|
|
307
|
+
}
|
|
308
|
+
const runs = clampRuns(body.runs)
|
|
309
|
+
const seed = normalizeSeed(body.seed)
|
|
310
|
+
const module = normalizeModule(body.module)
|
|
311
|
+
|
|
312
|
+
inFlight = true
|
|
313
|
+
|
|
314
|
+
// ── 流式会话状态(try 前声明:close 回调 / finally 都要摸到)──
|
|
315
|
+
let streaming = false // writeHead 之后 true——只有它为 true 才允许 res.end()
|
|
316
|
+
let clientGone = false
|
|
317
|
+
let procHandle: SubprocessHandle | undefined
|
|
318
|
+
let exited = false
|
|
319
|
+
const onClientClose = (): void => {
|
|
320
|
+
clientGone = true
|
|
321
|
+
// 客户端走人=干跑失去意义:不留僵尸 python
|
|
322
|
+
if (!exited && procHandle !== undefined) {
|
|
323
|
+
try { procHandle.terminate() } catch { /* 已退出则忽略 */ }
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
try {
|
|
328
|
+
let spawned: DebugSpawn
|
|
329
|
+
try {
|
|
330
|
+
spawned = await spawnDebugger(ctx, resolved, {
|
|
331
|
+
femo, runs, ...(seed !== undefined ? { seed } : {}),
|
|
332
|
+
...(module !== undefined ? { module } : {}),
|
|
333
|
+
...(typeof body.scriptPath === 'string' ? { scriptPath: body.scriptPath } : {}),
|
|
334
|
+
}, 'stream')
|
|
335
|
+
} catch (error: unknown) {
|
|
336
|
+
writeJson(res, 500, { ok: false, error: String(error instanceof Error ? error.message : error) })
|
|
337
|
+
return
|
|
338
|
+
}
|
|
339
|
+
procHandle = spawned.procHandle
|
|
340
|
+
const logPath = spawned.logPath
|
|
341
|
+
req.on('close', onClientClose)
|
|
342
|
+
res.on('close', onClientClose)
|
|
343
|
+
|
|
344
|
+
// ── 流式阶段开始:之后任何失败都以一条 debug_error 记录收尾(响应头
|
|
345
|
+
// 已发出,半路换状态码是谎报)。
|
|
346
|
+
streaming = true
|
|
347
|
+
res.writeHead(200, {
|
|
348
|
+
'content-type': 'application/x-ndjson; charset=utf-8',
|
|
349
|
+
'cache-control': 'no-cache',
|
|
350
|
+
})
|
|
351
|
+
const send = (rec: unknown): void => {
|
|
352
|
+
if (!clientGone && !res.destroyed) res.write(`${JSON.stringify(rec)}\n`)
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// tail JSONL:offset 增量读,按行转发(femo_debugger 每条 flush,延迟≈TAIL 间隔)
|
|
356
|
+
let offset = 0
|
|
357
|
+
let tailRemainder = ''
|
|
358
|
+
const tailOnce = async (): Promise<void> => {
|
|
359
|
+
let fh
|
|
360
|
+
try { fh = await open(logPath, 'r') } catch { return } // 文件未创建=还没跑到
|
|
361
|
+
try {
|
|
362
|
+
const st = await fh.stat()
|
|
363
|
+
if (st.size > offset) {
|
|
364
|
+
const buf = Buffer.alloc(st.size - offset)
|
|
365
|
+
const { bytesRead } = await fh.read(buf, 0, buf.length, offset)
|
|
366
|
+
offset += bytesRead
|
|
367
|
+
tailRemainder += buf.toString('utf8')
|
|
368
|
+
let idx: number
|
|
369
|
+
while ((idx = tailRemainder.indexOf('\n')) !== -1) {
|
|
370
|
+
const line = tailRemainder.slice(0, idx).trim()
|
|
371
|
+
tailRemainder = tailRemainder.slice(idx + 1)
|
|
372
|
+
if (line.length === 0) continue
|
|
373
|
+
try { send(JSON.parse(line)) } catch {
|
|
374
|
+
send({ kind: 'debug_error', error: `日志行解析失败: ${line.slice(0, 200)}` })
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
} finally {
|
|
379
|
+
await fh.close()
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
void procHandle.done.then((outcome: unknown) => {
|
|
384
|
+
exited = true
|
|
385
|
+
}, () => { exited = true })
|
|
386
|
+
|
|
387
|
+
const started = Date.now()
|
|
388
|
+
let timedOut = false
|
|
389
|
+
let exitCode = -1
|
|
390
|
+
while (!exited && !clientGone) {
|
|
391
|
+
await tailOnce()
|
|
392
|
+
if (exited || clientGone) break
|
|
393
|
+
if (Date.now() - started > DEBUG_TIMEOUT_MS) {
|
|
394
|
+
timedOut = true
|
|
395
|
+
try { procHandle.terminate() } catch { /* 已退出则忽略 */ }
|
|
396
|
+
break
|
|
397
|
+
}
|
|
398
|
+
await sleep(TAIL_INTERVAL_MS)
|
|
399
|
+
}
|
|
400
|
+
const outcome = await procHandle.done.catch(() => undefined as unknown)
|
|
401
|
+
exitCode = (outcome as { exitCode?: number } | undefined)?.exitCode ?? -1
|
|
402
|
+
await tailOnce() // 进程退出后再 drain 一次残余日志
|
|
403
|
+
|
|
404
|
+
if (timedOut) send({ kind: 'debug_error', error: `调试干跑超时(${DEBUG_TIMEOUT_MS / 1000}s),已强制终止` })
|
|
405
|
+
send({ kind: 'debug_done', exitCode })
|
|
406
|
+
} finally {
|
|
407
|
+
inFlight = false
|
|
408
|
+
req.off?.('close', onClientClose)
|
|
409
|
+
res.off?.('close', onClientClose)
|
|
410
|
+
if (streaming && !clientGone && !res.destroyed) res.end()
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* 主模型工具路径:整跑收集(不流式)。跑完一次性读回流水 + 终报 + stderr,
|
|
416
|
+
* 交给调用方渲染(见 formatDebugRunText / debugRunToolOutcome)。
|
|
417
|
+
*
|
|
418
|
+
* 与流式路径共用单飞闸:调试窗正在跑时调用会明确报错,反之亦然。
|
|
419
|
+
*/
|
|
420
|
+
export async function collectDebugRun(
|
|
421
|
+
ctx: Context,
|
|
422
|
+
resolved: ResolvedConfig,
|
|
423
|
+
req: DebugRunRequest,
|
|
424
|
+
signal?: AbortSignal,
|
|
425
|
+
): Promise<DebugRunCollect> {
|
|
426
|
+
if (inFlight) {
|
|
427
|
+
throw new Error('已有调试干跑在进行中(femoGen 调试窗或另一次 femo-debug 调用),请等它结束再试')
|
|
428
|
+
}
|
|
429
|
+
const runs = clampRuns(req.runs)
|
|
430
|
+
const seed = normalizeSeed(req.seed)
|
|
431
|
+
const timeoutMs = req.timeoutMs ?? DEBUG_TIMEOUT_MS
|
|
432
|
+
// 【2026-09-11】调用方已经撤销(工具 round 被中断/用户按了停止):别再起子进程——
|
|
433
|
+
// 起了也留不住结果,只会白跑一场、把单飞闸占住直到跑完。
|
|
434
|
+
if (signal?.aborted === true) {
|
|
435
|
+
return emptyCollect(runs, seed)
|
|
436
|
+
}
|
|
437
|
+
inFlight = true
|
|
438
|
+
const startedAt = Date.now()
|
|
439
|
+
let spawned: DebugSpawn | undefined
|
|
440
|
+
let timedOut = false
|
|
441
|
+
let aborted = false
|
|
442
|
+
const onAbort = (): void => {
|
|
443
|
+
aborted = true
|
|
444
|
+
if (spawned !== undefined) {
|
|
445
|
+
try { spawned.procHandle.terminate() } catch { /* 已退出则忽略 */ }
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
try {
|
|
449
|
+
spawned = await spawnDebugger(ctx, resolved, {
|
|
450
|
+
...req, runs, ...(seed !== undefined ? { seed } : {}),
|
|
451
|
+
}, 'capture')
|
|
452
|
+
const local = spawned
|
|
453
|
+
if (signal !== undefined) {
|
|
454
|
+
if (signal.aborted) onAbort()
|
|
455
|
+
else signal.addEventListener('abort', onAbort, { once: true })
|
|
456
|
+
}
|
|
457
|
+
// 进度可见化(用户实测「AI 调一次等很久,以为卡死了」):起跑/收尾各一条
|
|
458
|
+
// 诊断流——多轮干跑是线性叠加(runs=6 × 每轮几秒到十几秒),看诊窗/log 窗
|
|
459
|
+
// 的人能分辨「在跑」与「死了」。模型看不到这两条(不占它的上下文)。
|
|
460
|
+
pushDiag('femo-debug', `干跑启动:${runs} 轮${seed !== undefined ? `,seed=${seed}` : ''}(沙盒脚本 ${basename(local.sandboxScript)})`)
|
|
461
|
+
const done = local.procHandle.done.then((outcome: unknown) => outcome, () => undefined)
|
|
462
|
+
const timer = setTimeout(() => {
|
|
463
|
+
timedOut = true
|
|
464
|
+
try { local.procHandle.terminate() } catch { /* 已退出则忽略 */ }
|
|
465
|
+
}, timeoutMs)
|
|
466
|
+
try {
|
|
467
|
+
await done
|
|
468
|
+
} finally {
|
|
469
|
+
clearTimeout(timer)
|
|
470
|
+
}
|
|
471
|
+
const outcome = await done
|
|
472
|
+
const exitCode = (outcome as { exitCode?: number } | undefined)?.exitCode ?? -1
|
|
473
|
+
|
|
474
|
+
// ── 收账:流水 JSONL(半行=终止时最后一行不完整,丢弃不谎报)+ 终报 ──
|
|
475
|
+
const rawLog = await readFile(local.logPath, 'utf8').catch(() => '')
|
|
476
|
+
const records: Array<Record<string, unknown>> = []
|
|
477
|
+
for (const line of rawLog.split(/\r?\n/)) {
|
|
478
|
+
if (line.trim().length === 0) continue
|
|
479
|
+
try {
|
|
480
|
+
const rec = JSON.parse(line) as Record<string, unknown>
|
|
481
|
+
records.push(rec)
|
|
482
|
+
} catch { /* 截断的半行:跳过(不计入流水行数) */ }
|
|
483
|
+
}
|
|
484
|
+
let report: DebugRunReport | undefined
|
|
485
|
+
try {
|
|
486
|
+
report = JSON.parse(await readFile(local.reportPath, 'utf8')) as DebugRunReport
|
|
487
|
+
} catch { report = undefined }
|
|
488
|
+
|
|
489
|
+
const { lines, dropped } = debugTranscriptLines(records)
|
|
490
|
+
const stderr = local.err.join('\n')
|
|
491
|
+
const elapsedMs = Date.now() - startedAt
|
|
492
|
+
// 被中断(撤销/超时)但已产出流水:同目录留一份可读留档(.partial.md)。
|
|
493
|
+
// 用户实测语境:框架会把 aborted 的工具结果整条替换成 "tool call aborted"
|
|
494
|
+
// ——数据实时产出了却没人看到;留档后用户/AI 都能按路径把它捞出来。
|
|
495
|
+
let partialPath: string | undefined
|
|
496
|
+
if ((aborted || timedOut) && lines.length > 0) {
|
|
497
|
+
partialPath = local.logPath.replace(/\.jsonl$/, '.partial.md')
|
|
498
|
+
const header = `# 干跑被中断时的部分信息(${aborted ? '调用方撤销(回合被中断/用户停止)' : '看门狗超时强制终止'})\n\n`
|
|
499
|
+
+ `- 沙盒剧本:${local.sandboxScript}\n- 原始流水(JSONL):${local.logPath}\n`
|
|
500
|
+
+ `- 用时:${(elapsedMs / 1000).toFixed(1)}s 流水:${records.length} 条\n`
|
|
501
|
+
+ `- 终报:未生成(引擎未跑完,没有 --report 产出)\n\n## 流水(与 femoGen 调试窗同款渲染)\n\n`
|
|
502
|
+
try {
|
|
503
|
+
await writeFile(partialPath, header + lines.join('\n') + '\n', 'utf8')
|
|
504
|
+
} catch {
|
|
505
|
+
partialPath = undefined // 留档失败不拦主流程(原流水仍在)
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
pushDiag('femo-debug', `干跑结束:exit=${exitCode} 流水 ${records.length} 条 终报${report === undefined ? '无' : '有'}`
|
|
509
|
+
+ `${timedOut ? '(看门狗超时)' : ''}${aborted ? '(被撤销)' : ''} 用时 ${(elapsedMs / 1000).toFixed(1)}s`
|
|
510
|
+
+ `${partialPath !== undefined ? ` 部分信息留档:${partialPath}` : ''}`)
|
|
511
|
+
return {
|
|
512
|
+
exitCode,
|
|
513
|
+
timedOut,
|
|
514
|
+
aborted,
|
|
515
|
+
runs,
|
|
516
|
+
...(seed !== undefined ? { seed } : {}),
|
|
517
|
+
elapsedMs,
|
|
518
|
+
records,
|
|
519
|
+
...(report !== undefined ? { report } : {}),
|
|
520
|
+
transcript: lines.join('\n'),
|
|
521
|
+
transcriptDropped: dropped,
|
|
522
|
+
...(partialPath !== undefined ? { partialPath } : {}),
|
|
523
|
+
stderr: stderr.length > STDERR_MAX_CHARS ? stderr.slice(-STDERR_MAX_CHARS) : stderr,
|
|
524
|
+
sandboxScript: local.sandboxScript,
|
|
525
|
+
logPath: local.logPath,
|
|
526
|
+
reportPath: local.reportPath,
|
|
527
|
+
}
|
|
528
|
+
} finally {
|
|
529
|
+
inFlight = false
|
|
530
|
+
if (signal !== undefined) signal.removeEventListener('abort', onAbort)
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/** 空结果(调用方在起子进程前就撤销了):形状与真结果一致,让裁决函数
|
|
535
|
+
* 统一按「没跑起来 + 被撤销」处理,不必在调用方分叉。 */
|
|
536
|
+
function emptyCollect(runs: number, seed: number | undefined): DebugRunCollect {
|
|
537
|
+
return {
|
|
538
|
+
exitCode: -1,
|
|
539
|
+
timedOut: false,
|
|
540
|
+
aborted: true,
|
|
541
|
+
runs,
|
|
542
|
+
...(seed !== undefined ? { seed } : {}),
|
|
543
|
+
elapsedMs: 0,
|
|
544
|
+
records: [],
|
|
545
|
+
transcript: '',
|
|
546
|
+
transcriptDropped: 0,
|
|
547
|
+
stderr: '',
|
|
548
|
+
sandboxScript: '',
|
|
549
|
+
logPath: '',
|
|
550
|
+
reportPath: '',
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/**
|
|
555
|
+
* DebugLogBus 记录 → 一行可读流水。与 femoGen 调试窗 debugRecToLine 同款
|
|
556
|
+
* 语义(同一套 kind、同一套丢弃规则):edge 高频噪音不上流水(边覆盖在终报
|
|
557
|
+
* 里给全)、flow_outcome 与 run_end 重复、debug_done 是收尾哨兵。返回 null
|
|
558
|
+
* = 这条不上流水。
|
|
559
|
+
*/
|
|
560
|
+
export function formatDebugRecordLine(rec: Record<string, unknown>): string | null {
|
|
561
|
+
const s = (value: unknown): string => (value === undefined || value === null ? '' : String(value))
|
|
562
|
+
switch (rec.kind) {
|
|
563
|
+
case 'run_start':
|
|
564
|
+
return `▶ 第 ${s(rec.run) || '-'} 轮干跑开始:${s(rec.script) || '(未命名)'}`
|
|
565
|
+
+ `${rec.module ? `(module ${s(rec.module)})` : ''}(seed=${s(rec.seed) || '-'})`
|
|
566
|
+
case 'node_start':
|
|
567
|
+
return `→ ${s(rec.node)}${rec.node_type ? `(${s(rec.node_type)})` : ''}`
|
|
568
|
+
case 'action_outs': {
|
|
569
|
+
const exprs = Array.isArray(rec.exprs) ? rec.exprs.map(String).join(',') : ''
|
|
570
|
+
if (exprs.length === 0) return null
|
|
571
|
+
return rec.node_type === 'func'
|
|
572
|
+
? `🔧 ${s(rec.node)} 写回:${exprs}`
|
|
573
|
+
: `📝 ${s(rec.node)} 赋值:${exprs}`
|
|
574
|
+
}
|
|
575
|
+
case 'func_result': {
|
|
576
|
+
const out = rec.output === null || rec.output === undefined
|
|
577
|
+
? ''
|
|
578
|
+
: typeof rec.output === 'object' ? JSON.stringify(rec.output) : String(rec.output)
|
|
579
|
+
if (out.length === 0) return null
|
|
580
|
+
let ins = ''
|
|
581
|
+
const input = rec.func_input
|
|
582
|
+
if (input !== null && typeof input === 'object') {
|
|
583
|
+
const map = input as Record<string, unknown>
|
|
584
|
+
const keys = Object.keys(map)
|
|
585
|
+
if (keys.length > 0) ins = `(入参 ${keys.map(k => `${k}=${JSON.stringify(map[k])}`).join(',')})`
|
|
586
|
+
}
|
|
587
|
+
return `🔧 ${s(rec.node)} 函数返回:${out.slice(0, 300)}${ins}`
|
|
588
|
+
}
|
|
589
|
+
case 'assign':
|
|
590
|
+
return `${s(rec.node)} ${s(rec.var)}: ${s(rec.old)} → ${s(rec.new)}`
|
|
591
|
+
case 'ai_reply': {
|
|
592
|
+
const values = (rec.values ?? {}) as Record<string, { value?: unknown; source?: unknown }>
|
|
593
|
+
const entries = Object.entries(values)
|
|
594
|
+
if (entries.length === 0) return null
|
|
595
|
+
return `🤖 ${s(rec.node)} 合成赋值:${entries.map(([k, v]) => `${k}=${s(v?.value)}(${s(v?.source)})`).join(',')}`
|
|
596
|
+
}
|
|
597
|
+
case 'human_input': {
|
|
598
|
+
const parts = Object.entries((rec.variables ?? {}) as Record<string, unknown>)
|
|
599
|
+
.map(([k, v]) => `${k}=${s(v)}`)
|
|
600
|
+
if (parts.length === 0) return null
|
|
601
|
+
return `👤 ${s(rec.node)} 合成输入:${parts.join(',')}`
|
|
602
|
+
}
|
|
603
|
+
case 'retry':
|
|
604
|
+
return `🔁 ${s(rec.node)} 重试换值:${s(rec.feedback).slice(0, 160)}`
|
|
605
|
+
case 'silence':
|
|
606
|
+
return `🎲 ${s(rec.node)} 概率沉默(不赋值 ${s(rec.var)})`
|
|
607
|
+
case 'flaky':
|
|
608
|
+
return `💥 ${s(rec.node)} 注入无效赋值(测重试链路)`
|
|
609
|
+
case 'warning':
|
|
610
|
+
return `⚠ ${s(rec.msg)}`
|
|
611
|
+
case 'flow_outcome':
|
|
612
|
+
return null // run_end 已带结局,不重复
|
|
613
|
+
case 'run_end':
|
|
614
|
+
return `${rec.outcome === 'completed' ? '■' : '❌'} 第 ${s(rec.run) || '-'} 轮结束:${s(rec.outcome)}`
|
|
615
|
+
+ `${rec.error ? ` — ${String(rec.error).slice(0, 200)}` : ''}(${s(rec.elapsed) || '?'}s)`
|
|
616
|
+
case 'debug_done':
|
|
617
|
+
return null // 退出码语义见终报尾部说明;真崩溃经 stderr/退出码表达
|
|
618
|
+
case 'debug_error':
|
|
619
|
+
return `❌ ${s(rec.error)}`
|
|
620
|
+
default:
|
|
621
|
+
return null
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/** 流水行(含超限时的中段省略:首段 + 尾段,尾部是结局/报错最密的区段)。 */
|
|
626
|
+
export function debugTranscriptLines(records: Array<Record<string, unknown>>): { lines: string[]; dropped: number } {
|
|
627
|
+
const all: string[] = []
|
|
628
|
+
for (const rec of records) {
|
|
629
|
+
const line = formatDebugRecordLine(rec)
|
|
630
|
+
if (line !== null) all.push(line)
|
|
631
|
+
}
|
|
632
|
+
if (all.length <= TRANSCRIPT_MAX_LINES) return { lines: all, dropped: 0 }
|
|
633
|
+
const tailCount = TRANSCRIPT_MAX_LINES - TRANSCRIPT_HEAD_LINES
|
|
634
|
+
const dropped = all.length - TRANSCRIPT_MAX_LINES
|
|
635
|
+
return {
|
|
636
|
+
lines: [
|
|
637
|
+
...all.slice(0, TRANSCRIPT_HEAD_LINES),
|
|
638
|
+
`…(中段 ${dropped} 行已省略——完整流水见 jsonl 落盘路径)…`,
|
|
639
|
+
...all.slice(all.length - tailCount),
|
|
640
|
+
],
|
|
641
|
+
dropped,
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
/** 退出码语义(femo_debugger CLI 契约,2026-09-12 起 max_steps 算可接受结局
|
|
646
|
+
* ——跑满步数预算未停=「可能是无限循环」,退出码 0 非错误)。 */
|
|
647
|
+
function exitCodeNote(exitCode: number): string {
|
|
648
|
+
return exitCode === 0 ? '0(全部轮次 completed,或 max_steps=可能是无限循环)'
|
|
649
|
+
: exitCode === 2 ? '2(部分轮次 completed/max_steps)'
|
|
650
|
+
: exitCode === 1 ? '1(无一轮可接受结局 / 编译或装配失败)'
|
|
651
|
+
: `${exitCode}(非正常退出)`
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
/** 终报 → 文本(节点顺序 / 边覆盖 / 变量快照 / 提示 / 未达节点)。 */
|
|
655
|
+
function formatReport(report: DebugRunReport, timeoutNote: string | undefined): string[] {
|
|
656
|
+
const lines: string[] = []
|
|
657
|
+
const okRuns = report.runs.filter(r => r.outcome === 'completed').length
|
|
658
|
+
const loopRuns = report.runs.filter(r => r.outcome === 'max_steps').length
|
|
659
|
+
// 各轮合计耗时(多轮=线性叠加;用户实测「AI 调一次等很久」就是 runs 开大的
|
|
660
|
+
// 正常代价——把成本摆在结局行,模型下次自己就会掂量轮数)。
|
|
661
|
+
const sumElapsed = report.runs.reduce((sum, r) => sum + (Number.isFinite(r.elapsed) ? r.elapsed : 0), 0)
|
|
662
|
+
lines.push(`结局:${okRuns}/${report.runs.length} 轮 completed(各轮合计 ${sumElapsed.toFixed(1)}s)`
|
|
663
|
+
+ (loopRuns > 0 ? `,${loopRuns} 轮 max_steps(跑满步数预算未停——可能是无限循环,非错误)` : '')
|
|
664
|
+
+ `${timeoutNote !== undefined ? ` ${timeoutNote}` : ''}`)
|
|
665
|
+
if (report.module_mode) {
|
|
666
|
+
lines.push(`范围:module ${report.module_mode}`
|
|
667
|
+
+ (report.module_has_out === false
|
|
668
|
+
? '(无 [OUT]/[BREAK] 出口——持续循环型设计,max_steps 属预期)'
|
|
669
|
+
: ''))
|
|
670
|
+
}
|
|
671
|
+
for (const r of report.runs) {
|
|
672
|
+
lines.push(` seed=${r.seed}: ${r.outcome === 'max_steps' ? 'max_steps(可能是无限循环,非错误)' : r.outcome}`
|
|
673
|
+
+ (r.error ? ` — ${String(r.error).slice(0, 300)}` : '')
|
|
674
|
+
+ `(${r.elapsed}s)`)
|
|
675
|
+
}
|
|
676
|
+
if (report.node_order.length > 0) {
|
|
677
|
+
lines.push(`节点执行(${report.node_order.length} 步):${report.node_order.slice(0, 60).join(' → ')}`
|
|
678
|
+
+ (report.node_order.length > 60 ? ' …' : ''))
|
|
679
|
+
} else {
|
|
680
|
+
lines.push('节点执行:(无——一个节点都没跑到)')
|
|
681
|
+
}
|
|
682
|
+
const coverage = report.total_edges > 0
|
|
683
|
+
? `${report.edges_taken.length}/${report.total_edges} (${Math.round(report.edges_taken.length / report.total_edges * 100)}%)`
|
|
684
|
+
: '0/0'
|
|
685
|
+
lines.push(`边覆盖:${coverage}`)
|
|
686
|
+
if (report.edges_taken.length > 0) {
|
|
687
|
+
lines.push(` 走过的边:${report.edges_taken.slice(0, 40).join(',')}`
|
|
688
|
+
+ (report.edges_taken.length > 40 ? ` …共 ${report.edges_taken.length} 条` : ''))
|
|
689
|
+
}
|
|
690
|
+
if (report.var_snapshots.length > 0) {
|
|
691
|
+
lines.push(`变量快照(${report.var_snapshots.length} 条):`)
|
|
692
|
+
for (const s of report.var_snapshots.slice(0, REPORT_SNAPSHOT_MAX)) {
|
|
693
|
+
lines.push(` ${String(s.node)} ${String(s.var)}: ${String(s.old)} → ${String(s.new)}`)
|
|
694
|
+
}
|
|
695
|
+
if (report.var_snapshots.length > REPORT_SNAPSHOT_MAX) {
|
|
696
|
+
lines.push(` …(还有 ${report.var_snapshots.length - REPORT_SNAPSHOT_MAX} 条)`)
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
const warnings = [
|
|
700
|
+
...report.guess_warnings,
|
|
701
|
+
...report.silences.map(s => `概率沉默: ${s}`),
|
|
702
|
+
...report.flaky_fired.map(s => `flaky 无效赋值: ${s}`),
|
|
703
|
+
]
|
|
704
|
+
if (warnings.length > 0) {
|
|
705
|
+
lines.push(`⚠ 提示 ${warnings.length} 条(调试器猜值降级/兜底/概率沉默等):`)
|
|
706
|
+
for (const w of warnings.slice(0, REPORT_WARNING_MAX)) lines.push(` • ${w}`)
|
|
707
|
+
if (warnings.length > REPORT_WARNING_MAX) lines.push(` …(还有 ${warnings.length - REPORT_WARNING_MAX} 条)`)
|
|
708
|
+
}
|
|
709
|
+
const unreached = report.unreached_nodes ?? []
|
|
710
|
+
if (unreached.length > 0) {
|
|
711
|
+
lines.push(`未达节点(本场一次没走到——死分支/漏接线/条件永远为假):${unreached.join(',')}`)
|
|
712
|
+
}
|
|
713
|
+
return lines
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
/**
|
|
717
|
+
* 工具结果裁决 + 完整文本:
|
|
718
|
+
* - 干跑完全没跑起来(无流水、无终报、非零退出)= 编译/装配失败 → ok:false,
|
|
719
|
+
* 把 stderr 末尾的异常原话(如 SyntaxError: 条件 "y == 1" 引用了未声明的
|
|
720
|
+
* 变量…)放在最前,traceback 尾巴附后;
|
|
721
|
+
* - 其余(含超时、跑挂的轮次)都有信息可回 → ok:true,流水 + 终报全文。
|
|
722
|
+
*/
|
|
723
|
+
export function debugRunToolOutcome(
|
|
724
|
+
result: DebugRunCollect,
|
|
725
|
+
): { ok: true; text: string } | { ok: false; error: string } {
|
|
726
|
+
const stderrTail = result.stderr.trim()
|
|
727
|
+
if (result.records.length === 0 && result.report === undefined && result.exitCode !== 0) {
|
|
728
|
+
if (result.aborted) {
|
|
729
|
+
// 收窄口径(用户指正 2026-09-11):干跑数据是实时产的,中途被撤销时上面
|
|
730
|
+
// 那条 records>0 分支会把已产出的流水照常回传——走到这里只可能是「还没
|
|
731
|
+
// 写出任何一条流水就被撤销」(起步阶段/主会话未装载等),别一律说"没有
|
|
732
|
+
// 产生调试数据"(那会冤枉整条链路)。
|
|
733
|
+
return {
|
|
734
|
+
ok: false,
|
|
735
|
+
error: '本次干跑在产出任何流水之前就被撤销(回合被中断/用户停止;也可能卡在起跑阶段——看诊断流的「干跑启动」那行有没有出现)。'
|
|
736
|
+
+ '需要结果的话重新调用一次(轮数别开太大:runs 是线性耗时,每轮≈一次 femoGen 调试)。',
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
const errorLine = stderrTail.split('\n').reverse()
|
|
740
|
+
.find(line => /^[A-Za-z_][\w.]*(Error|Exception|Warning)?:\s/.test(line.trim()))?.trim()
|
|
741
|
+
return {
|
|
742
|
+
ok: false,
|
|
743
|
+
error: `干跑未能跑起来(退出码 ${result.exitCode})——`
|
|
744
|
+
+ `${result.timedOut ? '看门狗超时强制终止' : '编译/装配错误原话'}:\n`
|
|
745
|
+
+ (errorLine !== undefined ? `${errorLine}\n\n` : '')
|
|
746
|
+
+ (stderrTail.length > 0 ? stderrTail : '(stderr 为空——可直接跑 femoGen「编译」按钮看报错)'),
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
const parts: string[] = []
|
|
751
|
+
parts.push('📋 剧本干跑(零 token 空跑:AI/人类节点全部由调试器合成替答,未调用任何模型)')
|
|
752
|
+
parts.push('')
|
|
753
|
+
if (result.aborted) {
|
|
754
|
+
parts.push('⏹ 本次干跑被调用方撤销(回合被中断/用户停止);**已实时产出的流水照常回传在下方**'
|
|
755
|
+
+ '——注意:框架会把 aborted 的工具结果整条替换成 "tool call aborted",这种时候这份数据到你手里可能已经丢了,'
|
|
756
|
+
+ (result.partialPath !== undefined
|
|
757
|
+
? `可让用户按留档路径直接读:${result.partialPath}`
|
|
758
|
+
: '沙盒里的原始 JSONL 仍在。'))
|
|
759
|
+
parts.push('')
|
|
760
|
+
}
|
|
761
|
+
if (result.timedOut) {
|
|
762
|
+
parts.push(`⏱ 干跑超时(${DEBUG_TIMEOUT_MS / 1000}s 看门狗)已强制终止——疑似死循环,或 par/fork 重试链太慢;以下是终止前跑出的部分信息。`)
|
|
763
|
+
parts.push('')
|
|
764
|
+
}
|
|
765
|
+
if (result.report !== undefined) {
|
|
766
|
+
parts.push(...formatReport(result.report, undefined))
|
|
767
|
+
} else {
|
|
768
|
+
// 终报缺席但流水在(超时/被撤销):从 run_end 记录拼结局,诚实标注。
|
|
769
|
+
const ends = result.records.filter(r => r.kind === 'run_end')
|
|
770
|
+
parts.push(`结局:终报未生成(干跑未正常跑完)${ends.length > 0 ? ';已跑完的轮次:' : ''}`)
|
|
771
|
+
for (const e of ends) {
|
|
772
|
+
parts.push(` 第 ${String(e.run ?? '-')} 轮:${String(e.outcome ?? '?')}`
|
|
773
|
+
+ (e.error ? ` — ${String(e.error).slice(0, 300)}` : '')
|
|
774
|
+
+ `(${String(e.elapsed ?? '?')}s)`)
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
parts.push('')
|
|
778
|
+
const transcriptLines = result.transcript.length > 0 ? result.transcript.split('\n').length : 0
|
|
779
|
+
parts.push(`──── 调试流水(${transcriptLines} 行${result.transcriptDropped > 0 ? `,中段省略 ${result.transcriptDropped} 行` : ''})────`)
|
|
780
|
+
parts.push(result.transcript.length > 0 ? result.transcript : '(无流水记录——先看上面的结局/报错)')
|
|
781
|
+
parts.push('')
|
|
782
|
+
parts.push(`退出码 ${exitCodeNote(result.exitCode)}`
|
|
783
|
+
+ ` · 用时 ${(result.elapsedMs / 1000).toFixed(1)}s`
|
|
784
|
+
+ ` · 沙盒剧本:${result.sandboxScript}`
|
|
785
|
+
+ ` · 完整流水(JSONL):${result.logPath}`
|
|
786
|
+
+ (result.partialPath !== undefined ? ` · 部分信息留档:${result.partialPath}` : '')
|
|
787
|
+
+ (result.report !== undefined ? ` · 终报(JSON):${result.reportPath}` : ''))
|
|
788
|
+
if (result.stderr.trim().length > 0 && result.report === undefined) {
|
|
789
|
+
parts.push('')
|
|
790
|
+
parts.push(`引擎 stderr 尾部(诊断用):\n${result.stderr.trim().slice(-800)}`)
|
|
791
|
+
}
|
|
792
|
+
return { ok: true, text: parts.join('\n') }
|
|
793
|
+
}
|