econtone-studio 0.0.0-stage → 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/lib/index.js ADDED
@@ -0,0 +1,1456 @@
1
+ /**
2
+ * EconTone Studio — host half.
3
+ *
4
+ * Owns one HTTP surface under /econtone-studio/api and one subprocess call per
5
+ * run. All writing rules live in engine/studio_bridge.py; this file only moves
6
+ * bytes and keeps a small job table.
7
+ *
8
+ * Run artifacts: <workspace>/.econtone/runs/<runId>/ (input.md, run.json)
9
+ */
10
+ import { fileURLToPath } from 'node:url'
11
+ import { mkdir, writeFile, readFile, readdir } from 'node:fs/promises'
12
+ import { randomUUID } from 'node:crypto'
13
+ import { existsSync } from 'node:fs'
14
+ import os from 'node:os'
15
+ import path from 'node:path'
16
+ import { spawn as spawnProcess } from 'node:child_process'
17
+
18
+ export const inject = ['webServer', 'subprocess']
19
+
20
+ const BRIDGE = fileURLToPath(new URL('./engine/studio_bridge.py', import.meta.url))
21
+ const PREFIX = '/econtone-studio/api'
22
+ const MAX_BODY = 4 * 1024 * 1024
23
+
24
+ function defaultEngine() {
25
+ return path.join(os.homedir(), '.dsh', 'skills')
26
+ }
27
+
28
+ function send(res, status, payload) {
29
+ const body = JSON.stringify(payload)
30
+ res.statusCode = status
31
+ res.setHeader('content-type', 'application/json; charset=utf-8')
32
+ res.setHeader('cache-control', 'no-store')
33
+ res.end(body)
34
+ }
35
+
36
+ function ok(res, data) {
37
+ send(res, 200, { ok: true, data })
38
+ }
39
+
40
+ function fail(res, status, code, message, detail) {
41
+ send(res, status, { ok: false, error: { code, message, detail } })
42
+ }
43
+
44
+ function readBody(req) {
45
+ return new Promise((resolve, reject) => {
46
+ let size = 0
47
+ const chunks = []
48
+ req.on('data', (chunk) => {
49
+ size += chunk.length
50
+ if (size > MAX_BODY) {
51
+ reject(new Error('BODY_TOO_LARGE'))
52
+ req.destroy()
53
+ return
54
+ }
55
+ chunks.push(chunk)
56
+ })
57
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
58
+ req.on('error', reject)
59
+ })
60
+ }
61
+
62
+ function sameOrigin(ctx, req) {
63
+ const origin = req.headers.origin
64
+ if (!origin) return true
65
+ try {
66
+ return new URL(origin).host === new URL(ctx.webServer.getOrigin()).host
67
+ } catch {
68
+ return false
69
+ }
70
+ }
71
+
72
+ export function apply(ctx, config = {}) {
73
+ const engineRoot = config.engineRoot || defaultEngine()
74
+ const pythonPath = config.pythonPath || 'python'
75
+ const llmMaxTokens = Number(config.maxTokens || 2800)
76
+ const llmReasoningEffort = config.reasoningEffort || 'low'
77
+ const maxChars = Number(config.maxChars || 200000)
78
+ const timeoutMs = Number(config.timeoutMs || 120000)
79
+ const dshHome = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
80
+ const workspaceRoot = config.workspaceRoot || path.join(dshHome, 'workspace')
81
+ const jobs = new Map()
82
+ const diag = { llm: { at: 0 }, agent: { at: 0 }, lastRun: null }
83
+ let lastAgent = null
84
+
85
+ function runRoot() {
86
+ return path.join(workspaceRoot, '.econtone', 'runs')
87
+ }
88
+
89
+ function spawnBridge(args, cwd, signal) {
90
+ const spec = {
91
+ argv: [pythonPath, BRIDGE, ...args],
92
+ cwd,
93
+ stdio: {
94
+ stdin: 'ignore',
95
+ stdout: { maxBytes: 8 << 20, spill: { maxBytes: 64 << 20 } },
96
+ stderr: { maxBytes: 1 << 20 },
97
+ },
98
+ graceMs: 3000,
99
+ signal,
100
+ }
101
+ return ctx.subprocess.spawn(spec)
102
+ }
103
+
104
+ async function finish(handle, timeout) {
105
+ let timer
106
+ const timeoutPromise = new Promise((_, reject) => {
107
+ timer = setTimeout(() => {
108
+ try { handle.terminate() } catch {}
109
+ reject(Object.assign(new Error('bridge timeout'), { code: 'TIMEOUT' }))
110
+ }, timeout)
111
+ })
112
+ try {
113
+ const outcome = await Promise.race([handle.done, timeoutPromise])
114
+ const stdout = handle.collected.stdout ? handle.collected.stdout.readFrom(0) : { text: '' }
115
+ const stderr = handle.collected.stderr ? handle.collected.stderr.readFrom(0) : { text: '' }
116
+ return { code: outcome.exitCode, stdout: stdout.text || '', stderr: stderr.text || '' }
117
+ } finally {
118
+ clearTimeout(timer)
119
+ }
120
+ }
121
+
122
+ async function callBridge(args, cwd, timeout = timeoutMs) {
123
+ const handle = spawnBridge(args, cwd)
124
+ const out = await finish(handle, timeout)
125
+ if (out.code !== 0) {
126
+ let parsed
127
+ try { parsed = JSON.parse(out.stdout) } catch {}
128
+ const err = (parsed && parsed.error) || {}
129
+ throw Object.assign(new Error(err.message || out.stderr.slice(-400) || 'bridge failed'), {
130
+ code: err.code || 'ENGINE_FAILED',
131
+ detail: out.stderr.slice(-1200),
132
+ })
133
+ }
134
+ const parsed = JSON.parse(out.stdout)
135
+ if (!parsed.ok) {
136
+ throw Object.assign(new Error(parsed.error?.message || 'bridge error'), {
137
+ code: parsed.error?.code || 'ENGINE_FAILED',
138
+ })
139
+ }
140
+ return parsed.data
141
+ }
142
+
143
+ async function handleBuild(req, res) {
144
+ try {
145
+ let version = ''
146
+ for (const rel of ['./package.json', '../package.json']) {
147
+ try {
148
+ const pkg = JSON.parse(await readFile(new URL(rel, import.meta.url), 'utf8'))
149
+ version = String(pkg.version || '')
150
+ if (version) break
151
+ } catch {}
152
+ }
153
+ if (!version) throw new Error('package.json not readable')
154
+ ok(res, { version })
155
+ } catch (err) {
156
+ fail(res, 500, 'BUILD_INFO_FAILED', err.message)
157
+ }
158
+ }
159
+
160
+ async function handleHealth(req, res) {
161
+ try {
162
+ const data = await callBridge(['health', '--engine', engineRoot, '--json'], os.homedir(), 20000)
163
+ ok(res, data)
164
+ } catch (err) {
165
+ fail(res, 500, err.code || 'ENGINE_FAILED', err.message, err.detail)
166
+ }
167
+ }
168
+
169
+ function parseJsonObject(raw) {
170
+ const text = String(raw || '').trim()
171
+ const a = text.indexOf('{')
172
+ const b = text.lastIndexOf('}')
173
+ if (a < 0 || b <= a) return null
174
+ const body = text.slice(a, b + 1)
175
+ try {
176
+ const obj = JSON.parse(body)
177
+ return obj && typeof obj === 'object' ? obj : null
178
+ } catch {}
179
+ // 1) trailing commas
180
+ const repaired = body.replace(/,\s*([}\]])/g, '$1')
181
+ if (repaired !== body) {
182
+ try {
183
+ const obj = JSON.parse(repaired)
184
+ if (obj && typeof obj === 'object') return obj
185
+ } catch {}
186
+ }
187
+ // 2) a dropped closing brace or two — appending them is enough far more often
188
+ // than it is wrong, and a wrong guess simply fails to parse.
189
+ for (let extra = 1; extra <= 3; extra += 1) {
190
+ try {
191
+ const obj = JSON.parse(body + '}'.repeat(extra))
192
+ if (obj && typeof obj === 'object') return obj
193
+ } catch {}
194
+ }
195
+ return null
196
+ }
197
+
198
+ const SCORE_INSTRUCTION = [
199
+ 'Call the `econtone-score` skill and score the text below.',
200
+ 'Follow that skill exactly: it runs the four checks and returns the weighted scorecard.',
201
+ '',
202
+ 'Output format (must follow exactly):',
203
+ 'Return ONE JSON object and nothing else:',
204
+ '{"scorecard": {"rows": [{"id": "P1", "score": 0, "max": 40, "evidence": ""}],',
205
+ ' "total": 0, "editing_latitude": 0, "band": "", "advice": ""},',
206
+ ' "issues": [{"original": "<exact substring of the text>", "why": "<one short sentence>", "severity": "error|warn|info"}]}',
207
+ '- "rows" must contain P1 / P2 / T1 / R1 with max 40 / 40 / 10 / 10.',
208
+ '- "why" in ' + '{WHY}',
209
+ '- No markdown fence, no commentary.',
210
+ ].join('\n')
211
+
212
+ function scoreInstruction(whyLang) {
213
+ return SCORE_INSTRUCTION.replace('{WHY}', whyLang)
214
+ }
215
+
216
+ function isChineseText(t) {
217
+ const m = String(t || '').match(/[\u4e00-\u9fff]/g)
218
+ if (!m || m.length < 8) return false
219
+ return m.length / Math.max(1, String(t).length) >= 0.15
220
+ }
221
+
222
+ // 中译英:先用 agent 原生能力出初稿(不调 skill),再对初稿跑 econtone-score;合并成一次对话
223
+ function scoreInstructionZh(whyLang) {
224
+ const lines = [
225
+ 'STEP 1 — draft: translate the Chinese passage below into publishable English using only your own ability.',
226
+ 'Do NOT call any skill for this step; no skill, no tool, just translate.',
227
+ 'STEP 2 — score: call the `econtone-score` skill and score the English draft you produced in step 1.',
228
+ '',
229
+ 'Output format (must follow exactly):',
230
+ 'Return ONE JSON object and nothing else:',
231
+ '{"draft": "<the English translation from step 1>",',
232
+ ' "scorecard": {"rows": [{"id": "P1", "score": 0, "max": 40, "evidence": ""}],',
233
+ ' "total": 0, "editing_latitude": 0, "band": "", "advice": ""},',
234
+ ' "issues": [{"original": "<exact substring of the draft>", "why": "<one short sentence>", "severity": "error|warn|info"}]}',
235
+ '- "rows" must contain P1 / P2 / T1 / R1 with max 40 / 40 / 10 / 10, scored on the DRAFT.',
236
+ '- "why" in ' + whyLang,
237
+ '- No markdown fence, no commentary.',
238
+ ]
239
+ return lines.join('\n')
240
+ }
241
+
242
+ function parseRewritePayload(raw) {
243
+ const text = String(raw || '').trim()
244
+ const obj = parseJsonObject(text)
245
+ if (obj && typeof obj.revised === 'string' && obj.revised.trim()) {
246
+ return {
247
+ revised: obj.revised.trim(),
248
+ changes: Array.isArray(obj.changes) ? obj.changes.filter((c) => c && c.why) : [],
249
+ certificate: obj.certificate && typeof obj.certificate === 'object' ? obj.certificate : null,
250
+ scorecard: obj.scorecard && typeof obj.scorecard === 'object' ? obj.scorecard : null,
251
+ }
252
+ }
253
+ if (text.startsWith('{')) {
254
+ // A JSON payload we could not read is NOT a revised passage. Returning it as
255
+ // text is what produced quote-soup diffs; fail closed and let the host report it.
256
+ return { revised: '', changes: [], certificate: null, scorecard: null }
257
+ }
258
+ return {
259
+ revised: text.replace(/^```[a-z]*\n?/i, '').replace(/```$/, '').trim(),
260
+ changes: [],
261
+ certificate: null,
262
+ scorecard: null,
263
+ }
264
+ }
265
+
266
+ const PROMPT_FILE = fileURLToPath(new URL('./prompts/prompt_format.txt', import.meta.url))
267
+ const PROMPT_SINGLE = fileURLToPath(new URL('./prompts/prompt_single.txt', import.meta.url))
268
+ let promptTemplate = null
269
+
270
+ async function loadTemplate() {
271
+ if (promptTemplate != null) return promptTemplate
272
+ try {
273
+ promptTemplate = await readFile(PROMPT_FILE, 'utf8')
274
+ } catch {
275
+ promptTemplate = [
276
+ 'You are running inside the EconTone workbench.',
277
+ 'STEP 1 (mandatory): load the `econtone-equilibrium` skill and follow its protocol.',
278
+ 'STEP 2: apply the equilibrium schedule to the passage, then report what changed.',
279
+ '',
280
+ 'Run parameters chosen by the user in the workbench (obey them):',
281
+ '- game model: ',
282
+ '- game order: ',
283
+ '- game order: ',
284
+ '- coalition: ',
285
+ '- editing extent: ',
286
+ '- action mode: ',
287
+ '- time budget: ',
288
+ '- section profile: ',
289
+ '- target journal: ',
290
+ '- text position: ',
291
+ '- subject or area: ',
292
+ ].join('\n')
293
+ }
294
+ return promptTemplate
295
+ }
296
+
297
+ async function loadSingleTemplate() {
298
+ try {
299
+ return await readFile(PROMPT_SINGLE, 'utf8')
300
+ } catch {
301
+ return ''
302
+ }
303
+ }
304
+
305
+ // 单技能模式:填参数、换 {{ENGINE}} / {{WHY_LANG}}、截在 Text as follows
306
+ function buildSingleInstruction(template, p, whyLang) {
307
+ const values = {
308
+ 'engine': p.engine,
309
+ 'editing extent': p.extent,
310
+ 'section profile': p.profile,
311
+ 'target journal': p.journal || 'unspecified',
312
+ 'text position': p.section || p.profile,
313
+ 'subject or area': p.field || 'unspecified',
314
+ }
315
+ const filled = template.replace(/\r\n/g, '\n').split('\n').map((line) => {
316
+ const m = /^-\s*([A-Za-z ]+?)\s*:\s*$/.exec(line)
317
+ if (!m) return line
318
+ const key = m[1].trim().toLowerCase()
319
+ if (!(key in values)) return line
320
+ return '- ' + m[1].trim() + ': ' + (values[key] == null ? '' : values[key])
321
+ }).join('\n')
322
+ .replace(/\{\{ENGINE\}\}/g, p.engine)
323
+ .replace(/\{\{SKILL\}\}/g, p.skill || ('econtone-' + p.engine))
324
+ .replace(/\{\{WHY_LANG\}\}/g, whyLang)
325
+ const cut = filled.search(/Text as follows\s*[\uff1a:]/)
326
+ return (cut >= 0 ? filled.slice(0, cut) : filled).replace(/\s+$/, '')
327
+ }
328
+
329
+ // Fill the template's blank fields; the template owns the wording and order.
330
+ function buildInstruction(template, p, whyLang) {
331
+ const values = {
332
+ 'game model': p.model,
333
+ 'game order': p.order,
334
+ 'cooperation': p.cooperation,
335
+ 'coalition': p.coalition,
336
+ 'editing extent': p.extent,
337
+ 'action mode': p.actionMode,
338
+ 'time budget': p.budgetSec + 's',
339
+ 'section profile': p.profile,
340
+ 'target journal': p.journal || 'unspecified',
341
+ 'text position': p.section || p.profile,
342
+ 'subject or area': p.field || 'unspecified',
343
+ }
344
+ const filled = template.replace(/\r\n/g, '\n').split('\n').map((line) => {
345
+ const m = /^-\s*([A-Za-z ]+?)\s*:\s*$/.exec(line)
346
+ if (!m) return line
347
+ const key = m[1].trim().toLowerCase()
348
+ if (!(key in values)) return line
349
+ const v = values[key]
350
+ return '- ' + m[1].trim() + ': ' + (v == null ? '' : v)
351
+ })
352
+ // the template ends with "Text as follows��": cut it, the caller appends the passage
353
+ const joined = filled.join('\n')
354
+ const cut = joined.search(/Text as follows\s*[\uff1a:]/)
355
+ const head = (cut >= 0 ? joined.slice(0, cut) : joined)
356
+ .replace(/\{\{WHY_LANG\}\}/g, whyLang)
357
+ .replace(/\s+$/, '')
358
+ return head
359
+ }
360
+
361
+ function pickParent(ctx) {
362
+ const agents = ctx.get('agents')
363
+ try {
364
+ if (agents && typeof agents.roots === 'function') {
365
+ const roots = agents.roots()
366
+ if (roots.length) return roots[roots.length - 1]
367
+ }
368
+ if (agents && typeof agents.list === 'function') {
369
+ const all = agents.list()
370
+ if (all.length) return all[all.length - 1]
371
+ }
372
+ } catch {}
373
+ return lastAgent
374
+ }
375
+
376
+ async function awaitSessionReply(ctx, sessionId, sinceSeq, timeoutMs) {
377
+ const store = ctx.get('sessions')
378
+ if (!store || typeof store.get !== 'function') return null
379
+ const started = Date.now()
380
+ while (Date.now() - started < timeoutMs) {
381
+ const session = store.get(sessionId)
382
+ if (session) {
383
+ const events = session.snapshotEvents(sinceSeq)
384
+ if (events.some((e) => e.type === 'turn/end')) {
385
+ const texts = events
386
+ .filter((e) => e.type === 'assistant/message')
387
+ .map((e) => {
388
+ const blocks = (e.data && e.data.message && e.data.message.content) || []
389
+ return blocks.filter((b) => b && b.type === 'text').map((b) => b.text).join('')
390
+ })
391
+ .filter(Boolean)
392
+ return texts.length ? texts[texts.length - 1] : ''
393
+ }
394
+ }
395
+ await new Promise((r) => setTimeout(r, 500))
396
+ }
397
+ return null
398
+ }
399
+
400
+ // 用 sessionController 在固定的 EconTone 会话里跑一轮(已验证的调用链)。
401
+ async function rewriteViaAgent(ctx, text, instruction, budgetMs) {
402
+ const sc = ctx.get('sessionController')
403
+ if (!sc || typeof sc.resolveAgent !== 'function') {
404
+ diag.agent = { at: Date.now(), stage: 'service', hasController: !!sc }
405
+ return null
406
+ }
407
+
408
+ const ctrl = new AbortController()
409
+ const timer = setTimeout(() => ctrl.abort(), budgetMs)
410
+ const run = async () => {
411
+ const bound = await readBinding()
412
+ const cwd = (bound && bound.cwd) || workspaceRoot
413
+ let sessionId = bound && bound.sessionId ? String(bound.sessionId) : ''
414
+
415
+ if (!sessionId) {
416
+ const created = await sc.create({ cwd })
417
+ sessionId = String(created.sessionId)
418
+ try { await sc.rename({ sessionId, title: 'EconTone' }) } catch {}
419
+ try {
420
+ await writeBinding({
421
+ cwd, sessionId, name: (bound && bound.name) || 'EconTone', boundAt: Date.now(),
422
+ })
423
+ } catch {}
424
+ }
425
+
426
+ let resolved = await sc.resolveAgent(sessionId)
427
+ if (!resolved || resolved.error || !resolved.agent) {
428
+ diag.agent = { at: Date.now(), stage: 'resolve', sessionId, bound: sessionId,
429
+ error: (resolved && resolved.error) || 'no agent' }
430
+ // stale binding: start a fresh EconTone conversation once
431
+ const created = await sc.create({ cwd })
432
+ sessionId = String(created.sessionId)
433
+ try { await sc.rename({ sessionId, title: 'EconTone' }) } catch {}
434
+ try {
435
+ await writeBinding({ cwd, sessionId, name: 'EconTone', boundAt: Date.now() })
436
+ } catch {}
437
+ resolved = await sc.resolveAgent(sessionId)
438
+ if (!resolved || resolved.error || !resolved.agent) {
439
+ diag.agent = { at: Date.now(), stage: 'resolve-retry', sessionId,
440
+ error: (resolved && resolved.error) || 'no agent' }
441
+ return null
442
+ }
443
+ }
444
+
445
+ const agent = resolved.agent
446
+ const st = await sc.state({ sessionId }, ctrl.signal)
447
+ const afterSeq = st && typeof st.cursor === 'number' ? st.cursor : undefined
448
+
449
+ await agent.followup({
450
+ id: randomUUID(),
451
+ role: 'user',
452
+ content: [{ type: 'text', text: instruction + '\n\nText as follows\uff1a\n\n' + text }],
453
+ source: { kind: 'user', form: 'snapshot', sections: [] },
454
+ }, ctrl.signal)
455
+
456
+ const texts = []
457
+ let rounds = 0
458
+ let waitReason = null
459
+ let recordCount = 0
460
+ while (rounds < 3) {
461
+ rounds += 1
462
+ const w = await sc.wait(
463
+ { sessionId, timeoutMs: budgetMs, afterSeq, maxMessages: 60 },
464
+ ctrl.signal,
465
+ )
466
+ waitReason = w && w.reason
467
+ const records = (w && w.output && w.output.records) || []
468
+ recordCount = records.length
469
+ for (const rec of records) {
470
+ const ev = rec && rec.event
471
+ if (!ev || ev.type !== 'assistant/message') continue
472
+ const blocks = (ev.data && ev.data.message && ev.data.message.content) || []
473
+ const t = blocks.filter((b) => b && b.type === 'text').map((b) => b.text).join('')
474
+ if (t && !texts.includes(t)) texts.push(t)
475
+ }
476
+ if (texts.some((t) => t.includes('{')) || waitReason !== 'idle') break
477
+ }
478
+ // The JSON body may arrive after a preamble: prefer the message holding it.
479
+ const withJson = texts.filter((t) => t.includes('{'))
480
+ const reply = withJson.length ? withJson[withJson.length - 1] : texts.join('\n\n')
481
+ diag.agent = { at: Date.now(), stage: 'reply', sessionId, waitReason, rounds,
482
+ records: recordCount, replies: texts.length, replyLength: reply.length }
483
+ return reply.length >= 40 ? reply : null
484
+ }
485
+
486
+ try {
487
+ return await run()
488
+ } finally {
489
+ clearTimeout(timer)
490
+ }
491
+ }
492
+
493
+ async function rewriteCandidate(ctx, text, onProgress, instruction) {
494
+ const llm = ctx.get('llm')
495
+ const def = ctx.get('agentDefaultModel')
496
+ if (!llm || !def || typeof llm.stream !== 'function') {
497
+ diag.llm = { at: Date.now(), stage: 'service', hasLlm: !!llm, hasDefault: !!def }
498
+ return null
499
+ }
500
+ let sel
501
+ try { sel = def.currentSelection() } catch (e) {
502
+ diag.llm = { at: Date.now(), stage: 'selection', error: String(e && e.message) }
503
+ return null
504
+ }
505
+ if (!sel || !sel.provider || !sel.model) {
506
+ diag.llm = { at: Date.now(), stage: 'selection', selection: sel || null }
507
+ return null
508
+ }
509
+ diag.llm = { at: Date.now(), stage: 'streaming', provider: sel.provider, model: sel.model,
510
+ maxTokens: llmMaxTokens, reasoningEffort: llmReasoningEffort, text: 0, thinking: 0 }
511
+ let out = ''
512
+ let thinking = ''
513
+ const stream = llm.stream({
514
+ provider: sel.provider,
515
+ model: sel.model,
516
+ system: instruction,
517
+ messages: [{ role: 'user', content: [{ type: 'text', text }] }],
518
+ temperature: 0.2,
519
+ reasoningEffort: llmReasoningEffort,
520
+ maxTokens: llmMaxTokens,
521
+ })
522
+ for await (const chunk of stream) {
523
+ if (chunk.type === 'text-delta') {
524
+ out += chunk.text
525
+ diag.llm.text = (diag.llm.text || 0) + chunk.text.length
526
+ if (onProgress && out.length % 24 < chunk.text.length) onProgress(out.length, out.slice(-260))
527
+ } else if (typeof chunk.type === 'string' && /reason|think/i.test(chunk.type)) {
528
+ const t = chunk.text || chunk.delta || ''
529
+ if (t) {
530
+ thinking += t
531
+ diag.llm.thinking = (diag.llm.thinking || 0) + t.length
532
+ if (onProgress) onProgress(out.length, thinking.slice(-260))
533
+ }
534
+ }
535
+ if (chunk.type === 'finish') {
536
+ diag.llm.finish = chunk.reason ? chunk.reason.kind : null
537
+ if (chunk.reason && chunk.reason.kind === 'error') {
538
+ diag.llm.failure = (chunk.reason.failure && chunk.reason.failure.message) || null
539
+ return null
540
+ }
541
+ }
542
+ }
543
+ out = out.trim().replace(/^```[a-z]*\n?/i, '').replace(/```$/, '').trim()
544
+ diag.llm.outLength = out.length
545
+ return out.length >= 40 ? out : null
546
+ }
547
+
548
+ function patchJob(runId, patch) {
549
+ const job = jobs.get(runId)
550
+ if (job) Object.assign(job, patch)
551
+ }
552
+
553
+ async function persistRun(dir, result) {
554
+ try { await writeFile(path.join(dir, 'run.json'), JSON.stringify(result), 'utf8') } catch {}
555
+ }
556
+
557
+ function reconcileScore(result) {
558
+ try {
559
+ const s = result && result.score
560
+ if (!s || !Array.isArray(s.rows)) return
561
+ let changed = false
562
+ const findings = Array.isArray(result.findings) ? result.findings : []
563
+ const polish = findings.filter((f) => f && f.player === 'polish')
564
+ const p1 = s.rows.find((r) => r && r.id === 'P1')
565
+ if (p1 && polish.length) {
566
+ const max = Number(p1.max) || 40
567
+ if (Number(p1.score) >= max) {
568
+ const k = Math.min(8, polish.length)
569
+ const next = Math.max(24, max - 2 * k)
570
+ p1.score = next
571
+ p1.evidence = (p1.evidence ? p1.evidence + ' \u00b7 ' : '')
572
+ + `\u811a\u672c\u6838\u5bf9\uff1a\u5217\u51fa ${polish.length} \u6761\u8bed\u57df\u95ee\u9898\uff0c\u6309\u6bcf\u6761 2 \u5206\u6263\u81f3 ${next}`
573
+ changed = true
574
+ }
575
+ }
576
+ const r1 = s.rows.find((r) => r && r.id === 'R1')
577
+ if (r1) {
578
+ const ev = String(r1.evidence || '')
579
+ const mRed = /(\d+)\s*RED/i.exec(ev)
580
+ const mWarn = /(\d+)\s*WARN/i.exec(ev)
581
+ if (mRed || mWarn) {
582
+ const red = mRed ? Number(mRed[1]) : 0
583
+ const warn = mWarn ? Number(mWarn[1]) : 0
584
+ const max = Number(r1.max) || 10
585
+ const expected = Math.max(0, max - 4 * red - 1 * warn)
586
+ if (Number(r1.score) > expected) {
587
+ r1.score = expected
588
+ r1.evidence = ev + ` \u00b7 \u811a\u672c\u6838\u5bf9\uff1a${red} RED / ${warn} WARN\uff0c\u6263\u81f3 ${expected}`
589
+ changed = true
590
+ }
591
+ }
592
+ }
593
+ if (!changed) return
594
+ s.rows.forEach((r) => { r.score = Number(r.score) || 0 })
595
+ s.total = s.rows.reduce((sum, r) => sum + (Number(r.score) || 0), 0)
596
+ result.score = s
597
+ } catch {}
598
+ }
599
+
600
+ async function execute(runId, dir, inputPath, outPath, profile, mode, text, order, coalition, actionMode, model, uiLang, budgetSec, conn, extentValue, journal, sectionName, field, latitudeIn, baselineScore, engineName, engineSkill, draftId) {
601
+ try {
602
+ const common = ['--file', inputPath, '--profile', profile,
603
+ '--engine', engineRoot, '--out', outPath, '--run-id', runId, '--json']
604
+ let extra = []
605
+ let rewriteBy = 'llm'
606
+ const whyLang = uiLang === 'en' ? 'English' : 'Chinese (\u7b80\u4f53\u4e2d\u6587)'
607
+ let rewriteError = ''
608
+ const budgetMs = Math.min(180, Math.max(30, Number(budgetSec) || 60)) * 1000
609
+ // 期望时间是提示,不是硬停:到点后继续,只有远超预算的硬上限才失败
610
+ const hardMs = Math.max(budgetMs * 6, 15 * 60 * 1000)
611
+ if (mode === 'arbitrate') {
612
+ patchJob(runId, { phase: 'rewrite', chars: 0 })
613
+ try {
614
+ let rewritten = null
615
+ let by = 'llm'
616
+ const onDelta = (n, preview) => patchJob(runId, { chars: n, preview })
617
+ // 修改幅度:AUTO 不能直接传“auto”,要换成评分给出的 editing latitude
618
+ let extentText = extentValue
619
+ if (extentValue === 'auto') {
620
+ let lat = Number(latitudeIn)
621
+ if (!Number.isFinite(lat) || lat <= 0) {
622
+ try {
623
+ const m = await callBridge(['measure', '--file', inputPath, '--profile', profile,
624
+ '--engine', engineRoot, '--json'], dir, timeoutMs)
625
+ lat = Number(m && m.score && m.score.editing_latitude)
626
+ } catch {}
627
+ }
628
+ if (Number.isFinite(lat) && lat > 0) extentText = Math.round(lat) + '%'
629
+ else extentText = 'auto (infer from econtone-score)'
630
+ }
631
+ const runParams = {
632
+ model, order, coalition, actionMode, budgetSec, profile,
633
+ cooperation: coalition === 'none' ? 'non-cooperative' : 'cooperative',
634
+ extent: extentText, journal, section: sectionName, field, engine: engineName, skill: engineSkill || ('econtone-' + engineName),
635
+ }
636
+ let instruction = ''
637
+ const singleSkill = model === 'none'
638
+ try {
639
+ instruction = singleSkill
640
+ ? buildSingleInstruction(await loadSingleTemplate(), runParams, whyLang)
641
+ : buildInstruction(await loadTemplate(), runParams, whyLang)
642
+ await writeFile(path.join(dir, 'prompt.txt'),
643
+ instruction + '\n\nText as follows\uff1a\n\n' + text, 'utf8')
644
+ } catch {}
645
+ try {
646
+ if (conn === 'agent') {
647
+ rewritten = await Promise.race([
648
+ rewriteViaAgent(ctx, text, instruction, budgetMs),
649
+ new Promise((_, reject) => setTimeout(() => reject(new Error('REWRITE_HARD_TIMEOUT')), hardMs)),
650
+ ])
651
+ if (rewritten) by = 'agent'
652
+ } else {
653
+ rewritten = await Promise.race([
654
+ rewriteCandidate(ctx, text, onDelta, instruction),
655
+ new Promise((_, reject) => setTimeout(() => reject(new Error('REWRITE_HARD_TIMEOUT')), hardMs)),
656
+ ])
657
+ }
658
+ } catch (err) {
659
+ rewriteError = String((err && err.message) || err)
660
+ console.error('[econtone-studio] rewrite failed:', rewriteError)
661
+ }
662
+ rewriteBy = by
663
+ if (conn === 'agent' && !rewritten) {
664
+ patchJob(runId, {
665
+ status: 'error',
666
+ error: { code: 'AGENT_NO_RESULT',
667
+ message: '子 Agent 没有返回可用结果(未完成或已达硬上限),不生成改写稿'
668
+ + (rewriteError ? ' · ' + rewriteError : '') },
669
+ })
670
+ return
671
+ }
672
+ if (rewritten) {
673
+ const candDir = path.join(dir, 'cand')
674
+ await mkdir(candDir, { recursive: true })
675
+ const parsed = parseRewritePayload(rewritten)
676
+ if (!parsed.revised) {
677
+ patchJob(runId, {
678
+ status: 'error',
679
+ error: {
680
+ code: 'BAD_AGENT_PAYLOAD',
681
+ message: '模型回复的 JSON 无法解析(缺字段或括号不配对),未生成改写稿',
682
+ detail: String(rewritten).slice(0, 240),
683
+ },
684
+ })
685
+ return
686
+ }
687
+ await writeFile(path.join(candDir, 'model.md'), parsed.revised, 'utf8')
688
+ const movesPath = path.join(dir, 'moves.model.json')
689
+ await writeFile(movesPath, JSON.stringify([
690
+ { id: 'm-model', player: 'polish', kind: 'wording', after: 'cand/model.md' },
691
+ ], null, 2), 'utf8')
692
+ extra = ['--candidates', movesPath]
693
+ if (parsed.changes.length) {
694
+ const reasonsPath = path.join(candDir, 'reasons.json')
695
+ await writeFile(reasonsPath, JSON.stringify(parsed.changes, null, 2), 'utf8')
696
+ extra.push('--reasons', reasonsPath)
697
+ }
698
+ if (by === 'agent') {
699
+ // agent 已跑完脚本:宿主只传交结果
700
+ extra = ['--final', path.join(candDir, 'model.md')]
701
+ if (parsed.changes.length) extra.push('--reasons', path.join(candDir, 'reasons.json'))
702
+ if (parsed.scorecard) {
703
+ const scorePath = path.join(candDir, 'score.json')
704
+ await writeFile(scorePath, JSON.stringify(parsed.scorecard, null, 2), 'utf8')
705
+ extra.push('--score', scorePath)
706
+ }
707
+ if (baselineScore) {
708
+ const basePath = path.join(candDir, 'baseline.json')
709
+ await writeFile(basePath, JSON.stringify(baselineScore, null, 2), 'utf8')
710
+ extra.push('--baseline', basePath)
711
+ }
712
+ if (parsed.certificate) {
713
+ const certPath = path.join(candDir, 'cert.json')
714
+ await writeFile(certPath, JSON.stringify(parsed.certificate, null, 2), 'utf8')
715
+ extra.push('--cert', certPath)
716
+ }
717
+ }
718
+ }
719
+ } catch (err) {
720
+ console.error('[econtone-studio] rewrite failed:', err && err.message)
721
+ }
722
+ if (order === 'simultaneous') extra.push('--rounds', '1')
723
+ extra.push('--coalition', coalition, '--mode', actionMode)
724
+ // play.py 只实现了 stackelberg;nash/bayes/correlated 会报 "planned but not implemented"。
725
+ extra.push('--game', 'stackelberg')
726
+ patchJob(runId, { phase: 'arbitrate' })
727
+ }
728
+ const bridgeTimeout = Math.max(timeoutMs, Math.min(180, Math.max(30, Number(budgetSec) || 60)) * 1000 + 120000)
729
+
730
+ if (mode === 'measure') {
731
+ // 评分走 agent(econtone-score),失败才回退到脚本
732
+ patchJob(runId, { phase: 'score', chars: 0 })
733
+ const zhInput = isChineseText(text)
734
+ try {
735
+ const reply = await Promise.race([
736
+ rewriteViaAgent(ctx, text, (zhInput ? scoreInstructionZh : scoreInstruction)('Chinese (\u7b80\u4f53\u4e2d\u6587)'), budgetMs),
737
+ new Promise((_, reject) => setTimeout(() => reject(new Error('REWRITE_HARD_TIMEOUT')), hardMs)),
738
+ ])
739
+ const obj = parseJsonObject(reply)
740
+ if (obj && obj.scorecard && obj.scorecard.rows) {
741
+ const issues = Array.isArray(obj.issues) ? obj.issues : []
742
+ const findings = issues.map((it, i) => ({
743
+ id: 'f-' + String(i + 1).padStart(3, '0'),
744
+ op: 'none',
745
+ base_range: { start: 0, end: 0 },
746
+ after_range: { start: 0, end: 0 },
747
+ original: String(it.original || ''),
748
+ revised: '',
749
+ paragraph: 1,
750
+ player: 'polish',
751
+ kind: 'wording',
752
+ severity: it.severity === 'error' ? 'error' : (it.severity === 'warn' ? 'warn' : 'info'),
753
+ decision: 'pending',
754
+ reason: String(it.why || ''),
755
+ evidence: [{ source: 'model', code: 'MODEL', message: String(it.why || '') }],
756
+ locate: it.original ? 'exact' : 'none',
757
+ }))
758
+ const result = {
759
+ runId,
760
+ createdAt: new Date().toISOString(),
761
+ profile,
762
+ mode: 'measure',
763
+ score: obj.scorecard,
764
+ findings,
765
+ edits: [],
766
+ finalText: null,
767
+ scoreBy: 'agent',
768
+ draft: zhInput ? String(obj.draft || '') : null,
769
+ }
770
+ if (draftId) result.draftId = draftId
771
+ reconcileScore(result)
772
+ await persistRun(dir, result)
773
+ patchJob(runId, { status: 'done', phase: 'done', result })
774
+ return
775
+ }
776
+ } catch (err) {
777
+ console.error('[econtone-studio] agent score failed:', err && err.message)
778
+ }
779
+ patchJob(runId, { phase: 'measure' })
780
+ }
781
+
782
+ const data = mode === 'arbitrate'
783
+ ? await callBridge(['arbitrate', ...common, '--run-dir', dir, ...extra], dir, bridgeTimeout)
784
+ : await callBridge(['measure', ...common], dir, bridgeTimeout)
785
+ data.runId = runId
786
+ data.draftId = draftId
787
+ data.runDir = dir
788
+ data.rewriteBy = rewriteBy
789
+ if (rewriteError) data.rewriteError = rewriteError
790
+ reconcileScore(data)
791
+ await persistRun(dir, data)
792
+ patchJob(runId, { status: 'done', phase: 'done', result: data, elapsedMs: Date.now() - (jobs.get(runId)?.startedAt || Date.now()) })
793
+ } catch (err) {
794
+ patchJob(runId, {
795
+ status: 'error',
796
+ error: { code: err.code || 'ENGINE_FAILED', message: err.message, detail: err.detail },
797
+ })
798
+ }
799
+ }
800
+
801
+ function bindingPath() {
802
+ return path.join(workspaceRoot, '.econtone', 'binding.json')
803
+ }
804
+
805
+ async function writeBinding(data) {
806
+ await mkdir(path.dirname(bindingPath()), { recursive: true })
807
+ await writeFile(bindingPath(), JSON.stringify(data, null, 2), 'utf8')
808
+ return data
809
+ }
810
+
811
+ async function readBinding() {
812
+ try {
813
+ const raw = await readFile(bindingPath(), 'utf8')
814
+ const b = JSON.parse(raw)
815
+ return b && b.cwd ? b : null
816
+ } catch {
817
+ return null
818
+ }
819
+ }
820
+
821
+ function statePath() {
822
+ return path.join(workspaceRoot, '.econtone', 'state.json')
823
+ }
824
+
825
+ async function handleGetState(req, res) {
826
+ try {
827
+ const raw = await readFile(statePath(), 'utf8')
828
+ ok(res, { state: JSON.parse(raw) })
829
+ } catch {
830
+ ok(res, { state: null })
831
+ }
832
+ }
833
+
834
+ async function handleSetState(req, res) {
835
+ let body
836
+ try {
837
+ body = JSON.parse(await readBody(req))
838
+ } catch {
839
+ fail(res, 400, 'BAD_REQUEST', 'body must be JSON')
840
+ return
841
+ }
842
+ const state = body && body.state
843
+ if (!state || typeof state !== 'object') { fail(res, 400, 'BAD_STATE', 'state missing'); return }
844
+ await mkdir(path.dirname(statePath()), { recursive: true })
845
+ await writeFile(statePath(), JSON.stringify(state), 'utf8')
846
+ ok(res, { saved: true, bytes: JSON.stringify(state).length })
847
+ }
848
+
849
+ function shortId(id) {
850
+ const s = String(id || '')
851
+ return s.length > 16 ? s.slice(0, 9) + '\u2026' + s.slice(-4) : s
852
+ }
853
+
854
+ // 会话标题:走 sessionQuery 折叠会话日志里的标题事件,live 与 persisted 都能取到。
855
+ // 取不到(从未产生标题)就留空,由客户端退回短 id 显示——绝不把 id 当名字。
856
+ async function readTitles(ids) {
857
+ const out = Object.create(null)
858
+ const want = (ids || []).map((v) => String(v)).filter(Boolean)
859
+ if (!want.length) return out
860
+ const sq = ctx.get('sessionQuery')
861
+ if (!sq || typeof sq.readTitleSnapshots !== 'function') return out
862
+ try {
863
+ const results = await sq.readTitleSnapshots(want)
864
+ for (const r of results || []) {
865
+ if (!r || r.status !== 'fulfilled') continue
866
+ const snap = r.value && r.value.title
867
+ if (snap && snap.title) out[String(r.sessionId)] = String(snap.title)
868
+ }
869
+ } catch {}
870
+ return out
871
+ }
872
+
873
+ async function handleGetBinding(req, res) {
874
+ let sessions = []
875
+ try {
876
+ const store = ctx.get('sessions')
877
+ if (store && typeof store.list === 'function') {
878
+ sessions = store.list().map((s) => ({
879
+ id: String(s.id),
880
+ short: shortId(s.id),
881
+ cwd: (s.header && s.header.cwd) || '',
882
+ events: typeof s.seq === 'number' ? s.seq : 0,
883
+ }))
884
+ }
885
+ } catch {}
886
+ const bound = await readBinding()
887
+ const boundId = bound && bound.sessionId ? String(bound.sessionId) : ''
888
+ const ids = sessions.map((s) => s.id)
889
+ if (boundId && !ids.includes(boundId)) ids.push(boundId)
890
+ const titles = await readTitles(ids)
891
+ for (const s of sessions) {
892
+ s.bound = s.id === boundId
893
+ s.title = titles[s.id] || ''
894
+ }
895
+ ok(res, {
896
+ bound,
897
+ boundShort: boundId ? shortId(boundId) : '',
898
+ boundTitle: boundId ? (titles[boundId] || (bound && bound.title) || '') : '',
899
+ defaultCwd: workspaceRoot,
900
+ sessions,
901
+ })
902
+ }
903
+
904
+ async function handleSetBinding(req, res) {
905
+ let body
906
+ try {
907
+ body = JSON.parse(await readBody(req))
908
+ } catch {
909
+ fail(res, 400, 'BAD_REQUEST', 'body must be JSON')
910
+ return
911
+ }
912
+ const cwd = String(body.cwd || '').trim() || workspaceRoot
913
+ if (!path.isAbsolute(cwd)) { fail(res, 400, 'BAD_CWD', 'cwd must be absolute'); return }
914
+ const name = String(body.name || 'EconTone')
915
+ let sessionId = body.sessionId ? String(body.sessionId) : ''
916
+ let created = false
917
+ if (!sessionId) {
918
+ // Empty selection means "create one now", not "create it on the next run":
919
+ // the user pressed a button called 绑定并开始 and should see the conversation exist.
920
+ const sc = ctx.get('sessionController')
921
+ if (!sc || typeof sc.create !== 'function') {
922
+ fail(res, 503, 'NO_SESSION_CONTROLLER', 'sessionController missing; cannot create a conversation')
923
+ return
924
+ }
925
+ try {
926
+ const made = await sc.create({ cwd })
927
+ sessionId = String(made.sessionId)
928
+ created = true
929
+ try { await sc.rename({ sessionId, title: name }) } catch {}
930
+ } catch (err) {
931
+ fail(res, 500, 'CREATE_FAILED', String((err && err.message) || err))
932
+ return
933
+ }
934
+ }
935
+ const title = created ? name : ((await readTitles([sessionId]))[sessionId] || '')
936
+ const data = { cwd, sessionId, short: shortId(sessionId), title, name, boundAt: Date.now() }
937
+ await mkdir(path.dirname(bindingPath()), { recursive: true })
938
+ await writeFile(bindingPath(), JSON.stringify(data, null, 2), 'utf8')
939
+ ok(res, Object.assign({ created }, data))
940
+ }
941
+
942
+ async function handleProbeBinding(req, res) {
943
+ const sc = ctx.get('sessionController')
944
+ const out = { steps: [] }
945
+ if (!sc || typeof sc.resolveAgent !== 'function') {
946
+ fail(res, 503, 'NO_SESSION_CONTROLLER', 'sessionController missing', out)
947
+ return
948
+ }
949
+ const b = await readBinding()
950
+ if (!b || !b.sessionId) { fail(res, 400, 'NO_BINDING', 'no conversation bound yet', out); return }
951
+ out.sessionId = String(b.sessionId)
952
+ try {
953
+ const resolved = await sc.resolveAgent(out.sessionId)
954
+ if (!resolved || resolved.error || !resolved.agent) {
955
+ fail(res, 502, 'AGENT_UNAVAILABLE',
956
+ String((resolved && resolved.error) || 'agent not resumable'),
957
+ Object.assign(out, { stage: 'resolve' }))
958
+ return
959
+ }
960
+ out.steps.push('resolveAgent')
961
+ const agent = resolved.agent
962
+ const ctrl = new AbortController()
963
+ const st = await sc.state({ sessionId: out.sessionId }, ctrl.signal)
964
+ const afterSeq = st && typeof st.cursor === 'number' ? st.cursor : undefined
965
+ await agent.followup({
966
+ id: randomUUID(),
967
+ role: 'user',
968
+ content: [{ type: 'text', text: 'Reply with exactly: OK' }],
969
+ source: { kind: 'user', form: 'snapshot', sections: [] },
970
+ }, ctrl.signal)
971
+ out.steps.push('followup')
972
+ const w = await sc.wait({ sessionId: out.sessionId, timeoutMs: 30000, afterSeq, maxMessages: 12 }, ctrl.signal)
973
+ out.waitReason = w && w.reason
974
+ out.steps.push('wait')
975
+ const texts = []
976
+ for (const rec of (w && w.output && w.output.records) || []) {
977
+ const ev = rec && rec.event
978
+ if (!ev || ev.type !== 'assistant/message') continue
979
+ const blocks = (ev.data && ev.data.message && ev.data.message.content) || []
980
+ const t = blocks.filter((x) => x && x.type === 'text').map((x) => x.text).join('')
981
+ if (t) texts.push(t)
982
+ }
983
+ out.reply = texts.length ? texts[texts.length - 1] : ''
984
+ ok(res, out)
985
+ } catch (err) {
986
+ fail(res, 500, err.code || 'BIND_PROBE_FAILED', String((err && err.message) || err),
987
+ Object.assign(out, { stage: out.steps[out.steps.length - 1] || 'start' }))
988
+ }
989
+ }
990
+
991
+ function safeRunDir(runId) {
992
+ if (!/^r-[a-z0-9-]+$/.test(String(runId || ""))) return null
993
+ return path.join(runRoot(), String(runId))
994
+ }
995
+
996
+ async function handleSetDecisions(req, res) {
997
+ let body
998
+ try { body = JSON.parse(await readBody(req)) } catch { fail(res, 400, "BAD_REQUEST", "body must be JSON"); return }
999
+ const dir = safeRunDir(body.runId)
1000
+ if (!dir) { fail(res, 400, "BAD_RUN_ID", String(body.runId || "")); return }
1001
+ const decisions = (body.decisions && typeof body.decisions === "object") ? body.decisions : {}
1002
+ await mkdir(dir, { recursive: true })
1003
+ await writeFile(path.join(dir, "decisions.json"), JSON.stringify(decisions, null, 2), "utf8")
1004
+ ok(res, { runId: body.runId, saved: Object.keys(decisions).length })
1005
+ }
1006
+
1007
+ async function handleApplyDecisions(req, res) {
1008
+ let body
1009
+ try { body = JSON.parse(await readBody(req)) } catch { fail(res, 400, "BAD_REQUEST", "body must be JSON"); return }
1010
+ const dir = safeRunDir(body.runId)
1011
+ if (!dir) { fail(res, 400, "BAD_RUN_ID", String(body.runId || "")); return }
1012
+ const text = String(body.text == null ? "" : body.text)
1013
+ if (!text.trim()) { fail(res, 400, "EMPTY_TEXT", "nothing to save"); return }
1014
+ const decisions = (body.decisions && typeof body.decisions === "object") ? body.decisions : {}
1015
+ await mkdir(dir, { recursive: true })
1016
+ const outPath = path.join(dir, "final.applied.md")
1017
+ await writeFile(path.join(dir, "decisions.json"), JSON.stringify(decisions, null, 2), "utf8")
1018
+ await writeFile(outPath, text, "utf8")
1019
+ ok(res, { runId: body.runId, path: outPath, chars: text.length })
1020
+ }
1021
+
1022
+ async function handleDiag(req, res) {
1023
+ let binding = null
1024
+ try { binding = await readBinding() } catch {}
1025
+ let selection = null
1026
+ try { const d = ctx.get('agentDefaultModel'); selection = d ? d.currentSelection() : null } catch (e) { selection = String(e && e.message) }
1027
+ ok(res, {
1028
+ hasLlm: !!ctx.get('llm'),
1029
+ hasSessionController: !!ctx.get('sessionController'),
1030
+ selection,
1031
+ llmMaxTokens,
1032
+ llmReasoningEffort,
1033
+ binding,
1034
+ engineRoot,
1035
+ pythonPath,
1036
+ diag,
1037
+ })
1038
+ }
1039
+
1040
+ // ---- probe: sessionController.resolveAgent + agent.followup + wait ----
1041
+ async function handleProbe(req, res) {
1042
+ const sc = ctx.get('sessionController')
1043
+ if (!sc) { fail(res, 503, 'NO_SESSION_CONTROLLER', 'sessionController missing'); return }
1044
+ const out = { steps: [] }
1045
+ let sessionId = null
1046
+ try {
1047
+ const bound = await readBinding()
1048
+ const created = await sc.create({ cwd: (bound && bound.cwd) || workspaceRoot })
1049
+ sessionId = created.sessionId
1050
+ out.sessionId = sessionId
1051
+ out.steps.push('create')
1052
+
1053
+ try { await sc.rename({ sessionId, title: 'EconTone probe' }); out.steps.push('rename') } catch {}
1054
+
1055
+ const resolved = await sc.resolveAgent(sessionId)
1056
+ if (resolved.error) {
1057
+ out.error = resolved.error
1058
+ ok(res, out)
1059
+ return
1060
+ }
1061
+ out.steps.push('resolveAgent')
1062
+ const agent = resolved.agent
1063
+ out.agentKeys = agent ? Object.keys(agent) : []
1064
+ out.agentProto = agent ? Object.getOwnPropertyNames(Object.getPrototypeOf(agent)) : []
1065
+ out.hasFollowup = typeof agent.followup === 'function'
1066
+ out.hasWhenIdle = typeof agent.whenIdle === 'function'
1067
+ out.hasStatus = agent.status !== undefined
1068
+
1069
+ if (out.hasFollowup) {
1070
+ const probeSignal = new AbortController().signal
1071
+ const st0 = await sc.state({ sessionId }, probeSignal)
1072
+ const afterSeq = st0 && typeof st0.cursor === 'number' ? st0.cursor : undefined
1073
+ const msg = {
1074
+ id: randomUUID(),
1075
+ role: 'user',
1076
+ content: [{ type: 'text', text: 'Reply with exactly: OK' }],
1077
+ source: { kind: 'user', form: 'snapshot', sections: [] },
1078
+ }
1079
+ const ctrl = new AbortController()
1080
+ const attempts = [
1081
+ ['msg, signal', () => agent.followup(msg, ctrl.signal)],
1082
+ ['msg, {signal}', () => agent.followup(msg, { signal: ctrl.signal })],
1083
+ ['msg only', () => agent.followup(msg)],
1084
+ ]
1085
+ out.followupAttempts = []
1086
+ for (const [label, fn] of attempts) {
1087
+ try {
1088
+ await fn()
1089
+ out.followupOk = label
1090
+ out.followupAttempts.push(label + ':ok')
1091
+ break
1092
+ } catch (e) {
1093
+ out.followupAttempts.push(label + ':' + String(e && e.message).slice(0, 90))
1094
+ }
1095
+ }
1096
+ out.steps.push('followup')
1097
+ const w = await sc.wait({ sessionId, timeoutMs: 90000, afterSeq, maxMessages: 30 }, probeSignal)
1098
+ out.waitReason = w.reason
1099
+ out.steps.push('wait')
1100
+ const texts = []
1101
+ for (const rec of (w.output && w.output.records) || []) {
1102
+ const ev = rec && rec.event
1103
+ if (!ev) continue
1104
+ if (ev.type !== 'assistant/message') continue
1105
+ const blocks = (ev.data && ev.data.message && ev.data.message.content) || []
1106
+ const t = blocks.filter((b) => b && b.type === 'text').map((b) => b.text).join('')
1107
+ if (t) texts.push(t)
1108
+ }
1109
+ out.reply = texts.length ? texts[texts.length - 1] : null
1110
+ }
1111
+ ok(res, out)
1112
+ } catch (err) {
1113
+ fail(res, 500, err.code || 'PROBE_FAILED', err.message, out)
1114
+ }
1115
+ }
1116
+
1117
+ async function listSkills() {
1118
+ const dir = defaultEngine()
1119
+ const out = []
1120
+ try {
1121
+ const names = await readdir(dir)
1122
+ for (const n of names) {
1123
+ let text = ''
1124
+ try { text = await readFile(path.join(dir, n, 'SKILL.md'), 'utf8') } catch { continue }
1125
+ const fm = /^---\s*([\s\S]*?)\s*---/.exec(text)
1126
+ let name = n
1127
+ let description = ''
1128
+ if (fm) {
1129
+ const lines = fm[1].split('\n')
1130
+ for (let i = 0; i < lines.length; i++) {
1131
+ const line = lines[i]
1132
+ const nm = /^name:\s*(.+)$/.exec(line)
1133
+ if (nm) { name = nm[1].trim().replace(/^["']|["']$/g, ''); continue }
1134
+ const dm = /^description:\s*(.*)$/.exec(line)
1135
+ if (!dm) continue
1136
+ let v = dm[1].trim()
1137
+ if (v === '>' || v === '|' || v === '>-' || v === '|-') {
1138
+ const parts = []
1139
+ for (let j = i + 1; j < lines.length; j++) {
1140
+ if (/^\s+\S/.test(lines[j])) parts.push(lines[j].trim())
1141
+ else break
1142
+ }
1143
+ v = parts.join(' ')
1144
+ }
1145
+ description = v.replace(/^["']|["']$/g, '')
1146
+ }
1147
+ }
1148
+ const hay = (n + ' ' + name + ' ' + description).toLowerCase()
1149
+ const writing = /(polish|rewrit|writ|edit|prose|translat|academic|paper|tone|style|humaniz|\u6da6\u8272|\u5199\u4f5c|\u8bba\u6587|\u7ffb\u8bd1|\u6539\u5199|\u6587\u6848)/.test(hay)
1150
+ out.push({ id: n, name, description, kind: writing ? 'writing' : 'other' })
1151
+ }
1152
+ } catch {}
1153
+ out.sort((a, b) => String(a.name).localeCompare(String(b.name)))
1154
+ return out
1155
+ }
1156
+
1157
+ async function handleListSkills(req, res) {
1158
+ ok(res, { skills: await listSkills() })
1159
+ }
1160
+
1161
+ async function handleRun(req, res) {
1162
+ let payload
1163
+ try {
1164
+ payload = JSON.parse(await readBody(req))
1165
+ } catch {
1166
+ fail(res, 400, 'BAD_REQUEST', 'body must be JSON')
1167
+ return
1168
+ }
1169
+ const text = String(payload.text || '')
1170
+ const profile = ['body', 'abstract', 'intro'].includes(payload.profile) ? payload.profile : 'body'
1171
+ const mode = payload.mode === 'arbitrate' ? 'arbitrate' : 'measure'
1172
+ const order = payload.order === 'simultaneous' ? 'simultaneous' : 'sequential'
1173
+ const coalition = ['none', 'maxsum', 'nash'].includes(payload.coalition) ? payload.coalition : 'none'
1174
+ const actionMode = payload.actionMode === 'free' ? 'free' : 'constrained'
1175
+ const model = ['stack', 'maxsum', 'nash', 'cournot', 'bertrand', 'none'].includes(payload.model) ? payload.model : 'stack'
1176
+ const uiLang = payload.uiLang === 'en' ? 'en' : 'zh'
1177
+ const budgetSec = Math.min(180, Math.max(30, Number(payload.budgetSec) || 60))
1178
+ const conn = payload.conn === 'stream' ? 'stream' : 'agent'
1179
+ const extentValue = typeof payload.extent === 'string' ? payload.extent : 'auto'
1180
+ const rawEngine = typeof payload.engine === 'string' ? payload.engine.trim() : 'polish'
1181
+ let engineName = 'polish'
1182
+ let engineSkill = 'econtone-polish'
1183
+ if (rawEngine === 'equilibrium') { engineName = 'equilibrium'; engineSkill = 'econtone-equilibrium' }
1184
+ else if (['polish', 'ai-trace', 'prosody'].includes(rawEngine)) { engineName = rawEngine; engineSkill = 'econtone-' + rawEngine }
1185
+ else if (rawEngine.startsWith('skill:')) {
1186
+ const want = rawEngine.slice(6).trim()
1187
+ const skills = await listSkills()
1188
+ const hit = skills.find((s) => s.id === want || s.name === want)
1189
+ if (hit) { engineName = 'skill:' + hit.id; engineSkill = hit.name }
1190
+ }
1191
+ const baselineScore = payload.baselineScore && typeof payload.baselineScore === 'object' ? payload.baselineScore : null
1192
+ const latitudeIn = Number(payload.latitude)
1193
+ const journal = typeof payload.journal === 'string' ? payload.journal.trim() : ''
1194
+ const sectionName = typeof payload.section === 'string' ? payload.section.trim() : ''
1195
+ const field = typeof payload.field === 'string' ? payload.field.trim() : ''
1196
+ if (!text.trim()) { fail(res, 400, 'EMPTY_TEXT', 'text is empty'); return }
1197
+ if (text.length > maxChars) {
1198
+ fail(res, 413, 'DOC_TOO_LARGE', `text is ${text.length} chars, limit ${maxChars}`)
1199
+ return
1200
+ }
1201
+
1202
+ // 中译英:改写在英文初稿上进行,不再用中文原文
1203
+ const zhInput = isChineseText(text)
1204
+ const draftText = typeof payload.draftText === 'string' ? payload.draftText.trim() : ''
1205
+ let effectiveText = text
1206
+ if (mode === 'arbitrate' && zhInput) {
1207
+ if (!draftText) {
1208
+ fail(res, 409, 'DRAFT_REQUIRED', '\u6b63\u5728\u751f\u6210\u82f1\u6587\u521d\u7a3f\uff0c\u8bf7\u7a0d\u5019\u518d\u6539\u5199')
1209
+ return
1210
+ }
1211
+ effectiveText = draftText
1212
+ }
1213
+
1214
+ const taskId = typeof payload.taskId === 'string' ? payload.taskId : ''
1215
+ const draftId = typeof payload.draftId === 'string' ? payload.draftId.trim().slice(0, 64) : ''
1216
+ const runId = 'r-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 6)
1217
+ const dir = path.join(runRoot(), runId)
1218
+ await mkdir(dir, { recursive: true })
1219
+ const inputPath = path.join(dir, 'input.md')
1220
+ await writeFile(inputPath, effectiveText.replace(/\r\n/g, '\n'), 'utf8')
1221
+ try {
1222
+ await writeFile(path.join(dir, 'meta.json'), JSON.stringify({
1223
+ runId, taskId, mode, draftId, startedAt: Date.now(),
1224
+ }), 'utf8')
1225
+ } catch {}
1226
+ const outPath = path.join(dir, 'run.json')
1227
+ jobs.set(runId, {
1228
+ status: 'running', dir, mode,
1229
+ phase: mode === 'arbitrate' ? 'rewrite' : 'measure',
1230
+ chars: 0, startedAt: Date.now(),
1231
+ })
1232
+ void execute(runId, dir, inputPath, outPath, profile, mode, effectiveText, order, coalition, actionMode, model, uiLang, budgetSec, conn, extentValue, journal, sectionName, field, latitudeIn, baselineScore, engineName, engineSkill, draftId)
1233
+ ok(res, { runId, status: 'running', mode, runDir: dir })
1234
+ }
1235
+
1236
+ async function handleRunRefresh(req, res, url) {
1237
+ const taskId = String(url.searchParams.get('task') || '')
1238
+ const draftId = String(url.searchParams.get('draft') || '')
1239
+ if (!taskId && !draftId) { fail(res, 400, 'BAD_REQUEST', 'task or draft is required'); return }
1240
+ const root = runRoot()
1241
+ let best = null
1242
+ try {
1243
+ const names = await readdir(root)
1244
+ for (const name of names) {
1245
+ let meta = null
1246
+ try { meta = JSON.parse(await readFile(path.join(root, name, 'meta.json'), 'utf8')) } catch { continue }
1247
+ const sameDraft = draftId && String(meta.draftId || '') === draftId
1248
+ const sameTask = taskId && String(meta.taskId || '') === taskId
1249
+ if (!sameDraft && !sameTask) continue
1250
+ if (!best || (meta.startedAt || 0) > (best.startedAt || 0)) best = meta
1251
+ }
1252
+ } catch {}
1253
+ if (!best) { ok(res, { found: false }); return }
1254
+ const foundDraft = String(best.draftId || '')
1255
+ const job = jobs.get(best.runId)
1256
+ if (job && job.status === 'running') {
1257
+ ok(res, { found: true, runId: best.runId, draftId: foundDraft, status: 'running', startedAt: best.startedAt })
1258
+ return
1259
+ }
1260
+ if (job && job.status === 'error') {
1261
+ ok(res, { found: true, runId: best.runId, status: 'error', error: job.error, startedAt: best.startedAt })
1262
+ return
1263
+ }
1264
+ try {
1265
+ const result = JSON.parse(await readFile(path.join(root, best.runId, 'run.json'), 'utf8'))
1266
+ if (result && !result.baseText) {
1267
+ try { result.baseText = await readFile(path.join(root, best.runId, 'input.md'), 'utf8') } catch {}
1268
+ }
1269
+ try {
1270
+ const dec = JSON.parse(await readFile(path.join(root, best.runId, 'decisions.json'), 'utf8'))
1271
+ if (dec && typeof dec === 'object') result.decisions = dec
1272
+ } catch {}
1273
+ ok(res, { found: true, runId: best.runId, draftId: foundDraft, status: 'done', startedAt: best.startedAt, result })
1274
+ } catch {
1275
+ ok(res, { found: true, runId: best.runId, status: 'missing', startedAt: best.startedAt })
1276
+ }
1277
+ }
1278
+
1279
+ function textHash(s) {
1280
+ let h = 5381
1281
+ const str = String(s || '')
1282
+ for (let i = 0; i < str.length; i++) h = (((h << 5) + h) + str.charCodeAt(i)) >>> 0
1283
+ return 'k' + h.toString(36)
1284
+ }
1285
+
1286
+ async function handleHistory(req, res) {
1287
+ const root = runRoot()
1288
+ let names = []
1289
+ try { names = await readdir(root) } catch {}
1290
+ let tasks = []
1291
+ try {
1292
+ const st = JSON.parse(await readFile(statePath(), 'utf8'))
1293
+ tasks = Array.isArray(st.tasks) ? st.tasks : []
1294
+ } catch {}
1295
+ const nameOf = {}
1296
+ tasks.forEach((t) => { if (t && t.id) nameOf[t.id] = t.name || '' })
1297
+ const runs = []
1298
+ for (const n of names) {
1299
+ let meta = null
1300
+ try { meta = JSON.parse(await readFile(path.join(root, n, 'meta.json'), 'utf8')) } catch { continue }
1301
+ let result = null
1302
+ try { result = JSON.parse(await readFile(path.join(root, n, 'run.json'), 'utf8')) } catch {}
1303
+ const job = jobs.get(n)
1304
+ let inputText = ''
1305
+ try { inputText = await readFile(path.join(root, n, 'input.md'), 'utf8') } catch {}
1306
+ const preview = inputText.replace(/\s+/g, ' ').trim().slice(0, 120)
1307
+ const textKey = inputText.trim() ? textHash(inputText) : ('run-' + n)
1308
+ runs.push({
1309
+ textKey, preview,
1310
+ runId: n,
1311
+ taskId: meta.taskId || '',
1312
+ taskName: nameOf[meta.taskId] || '',
1313
+ draftId: meta.draftId || (result && result.draftId) || '',
1314
+ mode: meta.mode || (result && result.mode) || '',
1315
+ startedAt: meta.startedAt || 0,
1316
+ status: job ? job.status : (result ? 'done' : 'missing'),
1317
+ score: result && result.score ? result.score.total : null,
1318
+ edits: result && Array.isArray(result.edits) ? result.edits.length : 0,
1319
+ })
1320
+ }
1321
+ runs.sort((a, b) => (b.startedAt || 0) - (a.startedAt || 0))
1322
+ ok(res, { runs })
1323
+ }
1324
+
1325
+ async function handleGetRun(req, res, url) {
1326
+ const id = url.searchParams.get('id') || ''
1327
+ const job = jobs.get(id)
1328
+ if (!job) {
1329
+ // 进程重启后内存不在:从前次落盘的 run.json 里恢复
1330
+ try {
1331
+ const raw = await readFile(path.join(runRoot(), id, 'run.json'), 'utf8')
1332
+ const result = JSON.parse(raw)
1333
+ if (result && !result.baseText) {
1334
+ try {
1335
+ result.baseText = await readFile(path.join(runRoot(), id, 'input.md'), 'utf8')
1336
+ } catch {}
1337
+ }
1338
+ try {
1339
+ const dec = JSON.parse(await readFile(path.join(runRoot(), id, 'decisions.json'), 'utf8'))
1340
+ if (dec && typeof dec === 'object') result.decisions = dec
1341
+ } catch {}
1342
+ ok(res, { runId: id, status: 'done', result, fromDisk: true })
1343
+ return
1344
+ } catch {}
1345
+ fail(res, 404, 'RUN_NOT_FOUND', `no run ${id}`)
1346
+ return
1347
+ }
1348
+ if (job.status === 'error') {
1349
+ ok(res, { runId: id, status: 'error', error: job.error })
1350
+ return
1351
+ }
1352
+ if (job.status === 'done') {
1353
+ try {
1354
+ const dec = JSON.parse(await readFile(path.join(runRoot(), id, 'decisions.json'), 'utf8'))
1355
+ if (dec && typeof dec === 'object') job.result.decisions = dec
1356
+ } catch {}
1357
+ ok(res, { runId: id, status: 'done', result: job.result })
1358
+ return
1359
+ }
1360
+ ok(res, {
1361
+ runId: id,
1362
+ status: job.status || 'running',
1363
+ mode: job.mode,
1364
+ phase: job.phase || 'measure',
1365
+ chars: job.chars || 0,
1366
+ preview: job.preview || '',
1367
+ elapsedMs: Date.now() - (job.startedAt || Date.now()),
1368
+ })
1369
+ }
1370
+
1371
+ // 工作台背后要有 agent:捕获最近创建的 Agent 作为子代理的父节点。
1372
+ ctx.effect(() => ctx.on('agent/created', (agent) => { lastAgent = agent }),
1373
+ 'econtone-studio: track agent')
1374
+
1375
+ const PAGE_PATH = '/econtone-studio/page'
1376
+ const PAGE_FILE = fileURLToPath(new URL('./standalone.html', import.meta.url))
1377
+ let pageHtml = null
1378
+ async function standalonePage() {
1379
+ if (pageHtml == null) pageHtml = await readFile(PAGE_FILE, 'utf8')
1380
+ return pageHtml
1381
+ }
1382
+
1383
+ async function handleOpenPage(req, res) {
1384
+ let body = {}
1385
+ try { body = JSON.parse(await readBody(req)) } catch {}
1386
+ const asked = (body && typeof body.url === 'string') ? body.url.trim() : ''
1387
+ const url = /^https:\/\/[^\s]{3,}$/i.test(asked) ? asked : (ctx.webServer.getOrigin() + PAGE_PATH)
1388
+ const out = { url }
1389
+ if (body && body.dry) { ok(res, Object.assign(out, { opened: false, dry: true })); return }
1390
+ try {
1391
+ const electron = await import('electron')
1392
+ const shell = electron && (electron.shell || (electron.default && electron.default.shell))
1393
+ if (shell && typeof shell.openExternal === 'function') {
1394
+ await shell.openExternal(url)
1395
+ ok(res, Object.assign(out, { opened: true, via: 'electron' }))
1396
+ return
1397
+ }
1398
+ } catch {}
1399
+ try {
1400
+ const argv = process.platform === 'win32'
1401
+ ? ['cmd.exe', '/c', 'start', '', url]
1402
+ : (process.platform === 'darwin' ? ['open', url] : ['xdg-open', url])
1403
+ const child = spawnProcess(argv[0], argv.slice(1), { detached: true, stdio: 'ignore' })
1404
+ child.unref()
1405
+ ok(res, Object.assign(out, { opened: true, via: 'spawn' }))
1406
+ } catch (err) {
1407
+ fail(res, 500, 'OPEN_FAILED', String((err && err.message) || err), out)
1408
+ }
1409
+ }
1410
+
1411
+ ctx.effect(() => ctx.webServer.register({
1412
+ kind: 'exact',
1413
+ path: PAGE_PATH,
1414
+ resource: async () => new Response(await standalonePage(), {
1415
+ headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' },
1416
+ }),
1417
+ }), 'econtone-studio: standalone page')
1418
+
1419
+ ctx.effect(() => ctx.webServer.register({
1420
+ kind: 'prefix',
1421
+ path: PREFIX,
1422
+ handler: async (req, res) => {
1423
+ if (!sameOrigin(ctx, req)) { fail(res, 403, 'FORBIDDEN', 'cross-origin request'); return }
1424
+ const url = new URL(req.url, 'http://localhost')
1425
+ const rest = url.pathname.slice(PREFIX.length) || '/'
1426
+ try {
1427
+ if (req.method === 'GET' && rest === '/health') return await handleHealth(req, res)
1428
+ if (req.method === 'GET' && rest === '/build') return await handleBuild(req, res)
1429
+ if (req.method === 'GET' && rest === '/skills') return await handleListSkills(req, res)
1430
+ if (req.method === 'GET' && rest === '/history') return await handleHistory(req, res)
1431
+ if (rest === '/open-page' && req.method === 'POST') return await handleOpenPage(req, res)
1432
+ if (rest === '/run/decisions' && req.method === 'POST') return await handleSetDecisions(req, res)
1433
+ if (rest === '/run/apply' && req.method === 'POST') return await handleApplyDecisions(req, res)
1434
+ if (rest === '/run/refresh' && req.method === 'GET') return await handleRunRefresh(req, res, url)
1435
+ if (req.method === 'POST' && rest === '/run') return await handleRun(req, res)
1436
+ if (rest === '/state' && req.method === 'GET') return await handleGetState(req, res)
1437
+ if (rest === '/state' && req.method === 'POST') return await handleSetState(req, res)
1438
+ if (rest === '/binding/probe' && req.method === 'POST') return await handleProbeBinding(req, res)
1439
+ if (rest === '/binding' && req.method === 'GET') return await handleGetBinding(req, res)
1440
+ if (rest === '/probe' && req.method === 'POST') return await handleProbe(req, res)
1441
+ if (rest === '/diag' && req.method === 'GET') return await handleDiag(req, res)
1442
+ if (rest === '/binding' && req.method === 'POST') return await handleSetBinding(req, res)
1443
+ if (req.method === 'GET' && rest === '/run') return await handleGetRun(req, res, url)
1444
+ fail(res, 404, 'NOT_FOUND', `${req.method} ${rest}`)
1445
+ } catch (err) {
1446
+ fail(res, 500, err.code || 'INTERNAL', err.message, err.detail)
1447
+ }
1448
+ },
1449
+ }), 'econtone-studio: api')
1450
+
1451
+ ctx.effect(() => () => {
1452
+ for (const job of jobs.values()) {
1453
+ if (job.handle) { try { job.handle.terminate() } catch {} }
1454
+ }
1455
+ }, 'econtone-studio: jobs')
1456
+ }