@igorjpimenta/manifold 0.0.0-bootstrap.1 → 0.0.0-stage

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/README.md +2 -1583
  2. package/package.json +4 -49
  3. package/.migrations/ops/0000_futuristic_karma.sql +0 -111
  4. package/.migrations/ops/0001_low_maximus.sql +0 -7
  5. package/.migrations/ops/meta/0000_snapshot.json +0 -763
  6. package/.migrations/ops/meta/0001_snapshot.json +0 -173
  7. package/.migrations/ops/meta/_journal.json +0 -20
  8. package/.migrations/runtime/0000_real_boomer.sql +0 -180
  9. package/.migrations/runtime/0001_hot_dakota_north.sql +0 -2
  10. package/.migrations/runtime/0002_breezy_vertigo.sql +0 -8
  11. package/.migrations/runtime/0003_dashing_jack_flag.sql +0 -5
  12. package/.migrations/runtime/0004_panoramic_ego.sql +0 -1
  13. package/.migrations/runtime/0005_tidy_ben_grimm.sql +0 -10
  14. package/.migrations/runtime/0006_wet_nightmare.sql +0 -57
  15. package/.migrations/runtime/0007_ambiguous_chronomancer.sql +0 -8
  16. package/.migrations/runtime/0008_wealthy_thundra.sql +0 -301
  17. package/.migrations/runtime/0009_lying_shocker.sql +0 -96
  18. package/.migrations/runtime/0010_solid_phantom_reporter.sql +0 -160
  19. package/.migrations/runtime/0011_windy_demogoblin.sql +0 -175
  20. package/.migrations/runtime/0012_restore_harness_fks.sql +0 -103
  21. package/.migrations/runtime/meta/0000_snapshot.json +0 -1181
  22. package/.migrations/runtime/meta/0001_snapshot.json +0 -1209
  23. package/.migrations/runtime/meta/0002_snapshot.json +0 -1261
  24. package/.migrations/runtime/meta/0003_snapshot.json +0 -1292
  25. package/.migrations/runtime/meta/0004_snapshot.json +0 -1240
  26. package/.migrations/runtime/meta/0006_snapshot.json +0 -1310
  27. package/.migrations/runtime/meta/0007_snapshot.json +0 -1362
  28. package/.migrations/runtime/meta/0008_snapshot.json +0 -1742
  29. package/.migrations/runtime/meta/0009_snapshot.json +0 -2413
  30. package/.migrations/runtime/meta/0010_snapshot.json +0 -2562
  31. package/.migrations/runtime/meta/0011_snapshot.json +0 -2812
  32. package/.migrations/runtime/meta/0012_snapshot.json +0 -2812
  33. package/.migrations/runtime/meta/_journal.json +0 -97
  34. package/RELEASING.md +0 -89
  35. package/agent/fleet.js +0 -100
  36. package/bin/cli.js +0 -854
  37. package/bin/manifold.js +0 -4
  38. package/boot/flow-revival.js +0 -536
  39. package/budget/index.js +0 -495
  40. package/budget/lib.js +0 -59
  41. package/dashboard/cost.js +0 -528
  42. package/dashboard/dist/assets/index-CUfp63sj.css +0 -1
  43. package/dashboard/dist/assets/index-Qy9JMpma.js +0 -371
  44. package/dashboard/dist/index.html +0 -13
  45. package/dashboard/event-log.js +0 -267
  46. package/dashboard/index.html +0 -12
  47. package/dashboard/package-lock.json +0 -2877
  48. package/dashboard/package.json +0 -37
  49. package/dashboard/pipeline-graph.js +0 -131
  50. package/dashboard/postcss.config.js +0 -6
  51. package/dashboard/search.js +0 -183
  52. package/dashboard/server.js +0 -1015
  53. package/dashboard/src/App.tsx +0 -42
  54. package/dashboard/src/api/client.ts +0 -118
  55. package/dashboard/src/api/types.ts +0 -510
  56. package/dashboard/src/api/ws.tsx +0 -112
  57. package/dashboard/src/components/CancelButton.tsx +0 -63
  58. package/dashboard/src/components/ClickToCopy.tsx +0 -68
  59. package/dashboard/src/components/CopyButton.tsx +0 -61
  60. package/dashboard/src/components/DailyCostTrend.tsx +0 -85
  61. package/dashboard/src/components/DailyTimeTrend.tsx +0 -94
  62. package/dashboard/src/components/Funnel.tsx +0 -149
  63. package/dashboard/src/components/GateForm.tsx +0 -158
  64. package/dashboard/src/components/GraphView.tsx +0 -302
  65. package/dashboard/src/components/GroupPathsSummary.tsx +0 -47
  66. package/dashboard/src/components/Histogram.tsx +0 -292
  67. package/dashboard/src/components/Layout.tsx +0 -28
  68. package/dashboard/src/components/NeedsAttention.tsx +0 -98
  69. package/dashboard/src/components/NodeContextCard.tsx +0 -132
  70. package/dashboard/src/components/PathTrail.tsx +0 -35
  71. package/dashboard/src/components/PipelineCostBreakdown.tsx +0 -277
  72. package/dashboard/src/components/RerunButton.tsx +0 -46
  73. package/dashboard/src/components/RunComparison.tsx +0 -53
  74. package/dashboard/src/components/Sparkline.tsx +0 -94
  75. package/dashboard/src/components/StatStrip.tsx +0 -147
  76. package/dashboard/src/components/StateTree.tsx +0 -84
  77. package/dashboard/src/components/StatusBadge.tsx +0 -18
  78. package/dashboard/src/components/SubflowPathPills.tsx +0 -38
  79. package/dashboard/src/components/SubflowSummary.tsx +0 -24
  80. package/dashboard/src/components/SubflowsCard.tsx +0 -327
  81. package/dashboard/src/components/TodayStrip.tsx +0 -86
  82. package/dashboard/src/components/TranscriptPane.tsx +0 -99
  83. package/dashboard/src/components/TranscriptRow.tsx +0 -69
  84. package/dashboard/src/components/ui/badge.tsx +0 -38
  85. package/dashboard/src/components/ui/button.tsx +0 -28
  86. package/dashboard/src/components/ui/card.tsx +0 -42
  87. package/dashboard/src/components/ui/skeleton.tsx +0 -9
  88. package/dashboard/src/components/ui/table.tsx +0 -62
  89. package/dashboard/src/index.css +0 -26
  90. package/dashboard/src/lib/anomaly.ts +0 -42
  91. package/dashboard/src/lib/format.ts +0 -30
  92. package/dashboard/src/lib/step-history.ts +0 -13
  93. package/dashboard/src/lib/subflow.ts +0 -154
  94. package/dashboard/src/lib/use-click-outside.ts +0 -28
  95. package/dashboard/src/lib/use-ignored-clusters.ts +0 -67
  96. package/dashboard/src/lib/utils.ts +0 -6
  97. package/dashboard/src/main.tsx +0 -10
  98. package/dashboard/src/types/shims.d.ts +0 -4
  99. package/dashboard/src/views/Home.tsx +0 -478
  100. package/dashboard/src/views/PipelineDetail.tsx +0 -1185
  101. package/dashboard/src/views/PipelinesList.tsx +0 -111
  102. package/dashboard/src/views/RunDetail.tsx +0 -248
  103. package/dashboard/src/views/Search.tsx +0 -196
  104. package/dashboard/stats.js +0 -668
  105. package/dashboard/tailwind.config.ts +0 -43
  106. package/dashboard/tree-stats.js +0 -12
  107. package/dashboard/tsconfig.json +0 -25
  108. package/dashboard/views.js +0 -231
  109. package/dashboard/vite.config.ts +0 -34
  110. package/drizzle.config.js +0 -12
  111. package/drizzle.config.ops.js +0 -12
  112. package/elevation.js +0 -116
  113. package/engine/admission-promotion-resume.js +0 -127
  114. package/engine/agent-dispatch.js +0 -64
  115. package/engine/child-resume-trigger.js +0 -315
  116. package/engine/executor-budget.js +0 -87
  117. package/engine/executor-cancel.js +0 -83
  118. package/engine/executor-errors.js +0 -122
  119. package/engine/executor-helpers.js +0 -254
  120. package/engine/executor-nodes.js +0 -292
  121. package/engine/executor-persist.js +0 -212
  122. package/engine/executor-subflow-children.js +0 -275
  123. package/engine/executor.js +0 -1013
  124. package/engine/global-concurrency.js +0 -33
  125. package/engine/loader.js +0 -528
  126. package/engine/needs-resolver.js +0 -229
  127. package/engine/pipelines-watcher.js +0 -133
  128. package/engine/result-replay.js +0 -34
  129. package/engine/revival-messages.js +0 -11
  130. package/engine/spawn-child.js +0 -55
  131. package/engine/wait-for-flow-settlement.js +0 -109
  132. package/events/catalog.js +0 -26
  133. package/events/emit.js +0 -44
  134. package/events/kinds.js +0 -118
  135. package/events/serve-ws.js +0 -74
  136. package/events/stream.js +0 -35
  137. package/events/ws-dialog.js +0 -257
  138. package/events/ws-frame.js +0 -194
  139. package/events/ws-run-events.js +0 -70
  140. package/events.js +0 -32
  141. package/gates/gate-resolver.js +0 -576
  142. package/gates/paused-flows.js +0 -55
  143. package/graphql/columns.js +0 -67
  144. package/graphql/schema.js +0 -333
  145. package/index.js +0 -49
  146. package/mcp/http.js +0 -159
  147. package/mcp/identity.js +0 -94
  148. package/mcp/stdio.js +0 -80
  149. package/mcp/tools.js +0 -245
  150. package/mcp/wire-ops.js +0 -178
  151. package/routes/bearer-auth.js +0 -57
  152. package/routes/discuss-audio.js +0 -87
  153. package/routes/discuss-component.js +0 -39
  154. package/routes/discuss-draft.js +0 -159
  155. package/routes/discuss-helpers.js +0 -20
  156. package/routes/discuss.js +0 -848
  157. package/routes/failures.js +0 -104
  158. package/routes/graphql.js +0 -61
  159. package/routes/health.js +0 -54
  160. package/routes/operator-discuss.js +0 -193
  161. package/routes/operator-resume.js +0 -32
  162. package/routes/operator-retry.js +0 -301
  163. package/routes/operator.js +0 -539
  164. package/routes/pipelines.js +0 -118
  165. package/routes/runs.js +0 -1129
  166. package/scripts/ci/import-check.mjs +0 -50
  167. package/scripts/link-core-self.mjs +0 -31
  168. package/scripts/with-guard.sh +0 -24
  169. package/server/app.js +0 -503
  170. package/server/registry.js +0 -53
  171. package/server/serve.js +0 -163
  172. package/state/admission-queue-store.js +0 -325
  173. package/state/attribution-registries.js +0 -102
  174. package/state/batch-writer.js +0 -162
  175. package/state/db-guard.js +0 -63
  176. package/state/db-health.js +0 -27
  177. package/state/db.js +0 -122
  178. package/state/discuss-store.js +0 -299
  179. package/state/failure-store.js +0 -427
  180. package/state/migrate.js +0 -104
  181. package/state/node-cost.js +0 -67
  182. package/state/node-executions.js +0 -775
  183. package/state/node-health-store.js +0 -124
  184. package/state/ops-merge.js +0 -93
  185. package/state/paths.js +0 -146
  186. package/state/pipeline-dirs.js +0 -99
  187. package/state/pipeline-registry.js +0 -449
  188. package/state/run-store.js +0 -697
  189. package/state/schema.js +0 -438
  190. package/state/schema.ops.js +0 -44
  191. package/state/session-index.js +0 -177
  192. package/state/session-keys.js +0 -39
  193. package/state/state-store.js +0 -311
  194. package/state/subflow-state.js +0 -126
  195. package/state/tool-handoff.js +0 -169
  196. package/telemetry/budget-alert.js +0 -353
  197. package/telemetry/cli.js +0 -331
  198. package/telemetry/grammar.js +0 -119
  199. package/telemetry/http-budget.js +0 -132
  200. package/telemetry/http-cost.js +0 -670
  201. package/telemetry/http-helpers.js +0 -134
  202. package/telemetry/http-tree.js +0 -349
  203. package/telemetry/http.js +0 -44
  204. package/telemetry/index.js +0 -307
  205. package/telemetry/ingest.js +0 -134
  206. package/telemetry/labels.js +0 -115
  207. package/telemetry/pricer.js +0 -77
  208. package/telemetry/resolver.js +0 -314
  209. package/telemetry/store.js +0 -147
  210. package/utils/run-patch.js +0 -43
package/routes/discuss.js DELETED
@@ -1,848 +0,0 @@
1
- import path from "node:path";
2
- import { mkdirSync, existsSync } from "node:fs";
3
- import { randomUUID } from "node:crypto";
4
- import { persistRevisedDraft, persistRevisedMeta } from "./discuss-draft.js";
5
- import { AUDIO_MIME_EXT, EXT_TO_MIME, audioDirForFlow, audioRootsForFlow, loadAudioMetasForFlow, resolveAudioHarness } from "./discuss-audio.js";
6
- import { assembleState } from "../engine/executor-helpers.js";
7
-
8
- // ── Factory ─────────────────────────────────────────────────────────────────
9
- // All handlers close over the deps passed from index.js / runs.js / operator.js
10
- // rather than using module-level singletons.
11
-
12
- // Shared prompt projection for every discuss turn entry point (HTTP route,
13
- // audio route, WS dialog door): feed the gate's promptBuilder the same
14
- // assembleState-enriched state the engine's own dispatch loop reads.
15
- // Returns the prompt string or null (no builder, or the builder threw).
16
- export async function buildDiscussPrompt({ flow, target, runStore, nodeExecutionsStore, logger = null } = {}) {
17
- if (!target?.promptBuilder) return null;
18
- try {
19
- const ctx = {
20
- // B2.5 — read via assembleState() (resultJson replayed on top of
21
- // the still-live stateJson) instead of trusting the raw blob
22
- // directly, matching how the engine's own dispatch loop reads
23
- // state. Fixes a real gap too: this call site never enriched
24
- // with _subflowGroups before, so a discuss promptBuilder reading
25
- // state.loop (the pre-migration field name) always got nothing.
26
- state: await assembleState(flow.flowId, { runStore, nodeExecutionsStore, baseState: flow.stateJson ?? {} }),
27
- itemId: target.itemId,
28
- flowId: flow.flowId,
29
- pipelineId: flow.stateJson?.pipelineId ?? null,
30
- };
31
- return await Promise.resolve(target.promptBuilder(ctx));
32
- } catch (err) {
33
- try { logger?.warn?.(`manifold discuss promptBuilder threw for ${flow.flowId.slice(0, 8)}/${target.itemId}: ${err?.message ?? err}`); } catch {}
34
- return null;
35
- }
36
- }
37
-
38
- export function registerDiscussHandlers({
39
- api,
40
- store,
41
- pipelinesRef,
42
- emit,
43
- discussDefaultAgent,
44
- invokeElevated,
45
- discussStore,
46
- runStore,
47
- nodeExecutionsStore,
48
- // Injected gateway adapter, not core state: discuss thread ids come from
49
- // the harness (sessions.newDiscussSessionId), never minted here — core
50
- // never imports the gateway's session store (same seam as operator.js).
51
- sessions,
52
- // The roster records what each thread was given, keyed by its coordinates.
53
- sessionIndex,
54
- }) {
55
-
56
- // ── Resolve discuss target ────────────────────────────────────────────────
57
-
58
- async function resolveDiscussTarget(sourceFlow, wantItemId) {
59
- const items = Array.isArray(sourceFlow.waitJson?.items) ? sourceFlow.waitJson.items : [];
60
- let normalizedItemId = null;
61
- let gateNodeId = null;
62
- let branchSubNodeId = null;
63
-
64
- if ((sourceFlow.waitJson?.kind === "human-gate" || sourceFlow.waitJson?.kind === "gate") && items.length > 0) {
65
- const resolveItemId = (raw) =>
66
- typeof raw === "string" ? raw : (raw?.id ?? null);
67
- const item = wantItemId
68
- ? items.find((it) => resolveItemId(it.itemId) === wantItemId)
69
- : items[0];
70
- if (!item) {
71
- return { ok: false, status: 404, code: "item_not_found", error: `no pending item: ${wantItemId}` };
72
- }
73
- normalizedItemId = resolveItemId(item.itemId) ?? String(item.itemId);
74
- gateNodeId = sourceFlow.waitJson?.nodeId;
75
- } else if (sourceFlow.status === "running") {
76
- // Old-model mid-batch path (flow_branches / branchService) removed.
77
- // All subflow gates now surface their pending items via waitJson.
78
- return { ok: false, status: 503, code: "gate_transition", error: "gate is transitioning, try again shortly" };
79
- } else {
80
- return { ok: false, status: 409, code: "no_pending_gate", error: "flow has no pending gate item to discuss" };
81
- }
82
-
83
- const pipelineId = sourceFlow.stateJson?.pipelineId;
84
- const pipeline = pipelineId ? pipelinesRef.value.get(pipelineId) : null;
85
- if (pipelineId && !pipeline) {
86
- return { ok: false, status: 503, code: "pipeline_loading", error: "pipeline registry not ready, try again shortly" };
87
- }
88
- const topNode = pipeline?.nodes?.[gateNodeId];
89
- let discuss = null;
90
- // Cost/lineage attribution wants the MOST SPECIFIC node the discuss
91
- // session is actually about. For a bare top-level gate that's just
92
- // gateNodeId; for a gate nested inside a loop's branch, waitJson.nodeId
93
- // only ever names the LOOP (e.g. "PROPOSE"), never the nested gate sub-
94
- // node — so every discuss session under any loop's gate was being
95
- // attributed to the loop itself instead of the specific gate, making
96
- // real human-review cost look like coarse loop-level activity in the
97
- // dashboard's cost breakdown. `${gateNodeId}.${subNodeId}` matches the
98
- // executor's own branch-child naming convention (see nodeKindMap/
99
- // stepOrder in the dashboard, which key branch children the same way).
100
- let effectiveNodeId = gateNodeId;
101
- if (topNode?.kind === "human-gate") {
102
- discuss = topNode.discuss;
103
- } else if (topNode?.kind === "subflow") {
104
- const flowNodes = topNode.flow?.nodes ?? {};
105
- if (branchSubNodeId && flowNodes[branchSubNodeId]?.kind === "human-gate") {
106
- discuss = flowNodes[branchSubNodeId].discuss;
107
- effectiveNodeId = `${gateNodeId}.${branchSubNodeId}`;
108
- } else {
109
- for (const [subNodeId, subNode] of Object.entries(flowNodes)) {
110
- if (subNode?.kind === "human-gate" && subNode?.discuss) {
111
- discuss = subNode.discuss;
112
- effectiveNodeId = `${gateNodeId}.${subNodeId}`;
113
- break;
114
- }
115
- }
116
- }
117
- }
118
- const effectiveDiscuss = (discuss && typeof discuss === "object" && discuss.agent)
119
- ? discuss
120
- : discussDefaultAgent ? { agent: discussDefaultAgent } : null;
121
- if (!effectiveDiscuss) {
122
- return {
123
- ok: false,
124
- status: 400,
125
- code: "discuss_not_supported",
126
- error: "this gate's pipeline hasn't opted into discussion (set `discuss: { agent, promptBuilder }` on the gate node, or set `discuss.defaultAgent` in the manifold plugin config in openclaw.json)",
127
- };
128
- }
129
- // Thread identity: the roster (keyed by flow, gate, item) holds what
130
- // earlier turns used; a thread with no row asks the harness for an id,
131
- // because the harness owns the session namespace. A missing row means
132
- // no turn ran yet — the caller records the new thread.
133
- const stamp = await sessionIndex?.findThread?.(sourceFlow.flowId, gateNodeId, normalizedItemId);
134
- const resolvedAgent = stamp?.agentId ?? effectiveDiscuss.agent;
135
- const session = stamp?.session
136
- ?? sessions?.newDiscussSessionId?.({
137
- agentId: resolvedAgent, flowId: sourceFlow.flowId,
138
- gateNodeId, itemId: normalizedItemId,
139
- });
140
- if (typeof session !== "string" || !session) {
141
- return {
142
- ok: false,
143
- status: 503,
144
- code: "discuss_session_unavailable",
145
- error: "harness did not provide a discuss session id (sessions.newDiscussSessionId missing or empty)",
146
- };
147
- }
148
- // Core names the thread `session`: the harness's own id, in whatever
149
- // shape it uses. The agent travels as its own field — core reads no
150
- // shape out of a session.
151
- return {
152
- ok: true,
153
- session,
154
- itemId: normalizedItemId,
155
- agent: resolvedAgent,
156
- needsStamp: !stamp,
157
- // Coarse node id the discuss thread itself is keyed under in the
158
- // roster — the loop's own id for a branch-mode gate, not the
159
- // fine-grained per-sub-node id below.
160
- gateNodeId,
161
- // Specific node this discuss session is actually about, for cost/
162
- // lineage attribution — "PROPOSE.GATE", not just "PROPOSE", when the
163
- // gate lives inside a loop's branch. The sidecar stays keyed on the
164
- // coarser gateNodeId above (a harness id is opaque to core, so only
165
- // the (flow, gate, item) coordinates re-find the thread).
166
- nodeId: effectiveNodeId,
167
- modelOverride: typeof effectiveDiscuss.model === "string" && effectiveDiscuss.model.trim()
168
- ? effectiveDiscuss.model.trim()
169
- : null,
170
- promptBuilder: typeof effectiveDiscuss.promptBuilder === "function" ? effectiveDiscuss.promptBuilder : null,
171
- };
172
- }
173
-
174
- // ── handleDiscuss ─────────────────────────────────────────────────────────
175
-
176
- async function handleDiscuss(req, res, sourceFlow) {
177
- let raw = "";
178
- for await (const chunk of req) raw += chunk;
179
- let body;
180
- try { body = raw ? JSON.parse(raw) : {}; }
181
- catch { res.statusCode = 400; res.end("invalid json"); return true; }
182
- const text = typeof body.text === "string" ? body.text.trim() : "";
183
- if (!text) {
184
- res.statusCode = 400;
185
- res.setHeader("Content-Type", "application/json");
186
- res.end(JSON.stringify({ ok: false, code: "missing_text", error: "text is required" }));
187
- return true;
188
- }
189
- const wantItemId = typeof body.itemId === "string" ? body.itemId : null;
190
- const target = await resolveDiscussTarget(sourceFlow, wantItemId);
191
- if (!target.ok) {
192
- res.statusCode = target.status;
193
- res.setHeader("Content-Type", "application/json");
194
- res.end(JSON.stringify({ ok: false, code: target.code, error: target.error }));
195
- return true;
196
- }
197
- let systemPrompt = await buildDiscussPrompt({ flow: sourceFlow, target, runStore, nodeExecutionsStore, logger: api.logger });
198
- const turnId = randomUUID();
199
- const flowIdShort = sourceFlow.flowId.slice(0, 8);
200
- res.statusCode = 202;
201
- res.setHeader("Content-Type", "application/json");
202
- res.end(JSON.stringify({ ok: true, turnId }));
203
-
204
- try {
205
- await discussStore.appendMessage(sourceFlow.flowId, target.itemId, {
206
- turnId, role: "operator", text, ts: Date.now(),
207
- });
208
- await discussStore.setTurnStatus(sourceFlow.flowId, target.itemId, "running", turnId);
209
- } catch (err) {
210
- api.logger.warn(`discuss-store write (operator msg): ${err?.message ?? err}`);
211
- }
212
-
213
- if (target.needsStamp) {
214
- try {
215
- await sessionIndex?.recordThread?.({
216
- flowId: sourceFlow.flowId, gateNodeId: target.gateNodeId ?? "",
217
- itemId: target.itemId, agentId: target.agent ?? null, session: target.session,
218
- });
219
- } catch {}
220
- api.runtime?.lineage?.recordSpawn?.({ childSession: target.session, flowId: sourceFlow.flowId, nodeId: target.nodeId?.toLowerCase() ?? null, itemKey: target.itemId, pipelineId: sourceFlow.stateJson?.pipelineId ?? null, agentId: target.agent ?? null, kind: "flow-gate-discuss", source: "spawn_hook" });
221
- }
222
- // Transcript roster lives in flow_sessions alongside dispatch rows, so
223
- // the transcripts endpoint attributes this thread from stored columns
224
- // (nodeId, branchItemId) instead of parsing the session. Best-effort:
225
- // the discuss turn itself is already durable in discuss-store above.
226
- try { await sessionIndex?.record?.({ flowId: sourceFlow.flowId, session: target.session, nodeId: target.nodeId ?? null, branchItemId: target.itemId ?? null, agent: target.agent ?? null }); } catch {}
227
-
228
- setImmediate(async () => {
229
- try {
230
- const elev = await invokeElevated("/manifold/_elev/discuss", {
231
- flowId: sourceFlow.flowId,
232
- session: target.session,
233
- agentId: target.agent,
234
- gateNodeId: target.gateNodeId,
235
- modelOverride: target.modelOverride,
236
- text,
237
- itemId: target.itemId,
238
- systemPrompt: typeof systemPrompt === "string" ? systemPrompt : null,
239
- }, { timeoutMs: 360_000 });
240
- let payload;
241
- try { payload = JSON.parse(elev.body || "{}"); } catch { payload = {}; }
242
- const succeeded = elev.ok && payload.ok;
243
- try {
244
- if (succeeded) {
245
- await discussStore.appendMessage(sourceFlow.flowId, target.itemId, {
246
- turnId, role: "agent",
247
- text: payload.reply ?? "",
248
- proposedDraft: payload.proposedDraft ?? null,
249
- proposedMeta: payload.proposedMeta ?? null,
250
- ts: Date.now(),
251
- });
252
- await discussStore.clearPending(sourceFlow.flowId, target.itemId);
253
- await discussStore.setTurnStatus(sourceFlow.flowId, target.itemId, "idle", null);
254
- } else {
255
- const errText = payload.error || payload.code || elev.error || `HTTP ${elev.status}`;
256
- await discussStore.stampMessageError(sourceFlow.flowId, target.itemId, turnId, errText);
257
- await discussStore.setTurnStatus(sourceFlow.flowId, target.itemId, "error", null);
258
- }
259
- } catch (err) {
260
- api.logger.warn(`discuss-store write (agent reply): ${err?.message ?? err}`);
261
- }
262
- const turnKind = succeeded ? "session.transcript.completed" : "session.transcript.failed";
263
- const emitRes = await emit(turnKind, succeeded
264
- ? {
265
- scope: "discuss",
266
- turnId,
267
- flowId: sourceFlow.flowId,
268
- itemId: target.itemId,
269
- text: payload.reply ?? "",
270
- durationMs: payload.durationMs ?? null,
271
- emittedAtMs: Date.now(),
272
- }
273
- : {
274
- scope: "discuss",
275
- turnId,
276
- flowId: sourceFlow.flowId,
277
- itemId: target.itemId,
278
- error: payload.error || payload.code || elev.error || `HTTP ${elev.status}`,
279
- emittedAtMs: Date.now(),
280
- });
281
- if (!emitRes.ok) {
282
- api.logger.warn(`manifold discuss async [${flowIdShort}/${turnId.slice(0, 8)}]: canonical emit failed`);
283
- } else {
284
- api.logger.info(`manifold discuss async [${flowIdShort}/${turnId.slice(0, 8)}]: ${turnKind} emitted`);
285
- }
286
- } catch (err) {
287
- api.logger.warn(`manifold discuss async [${flowIdShort}/${turnId.slice(0, 8)}]: runner error: ${err?.message ?? err}`);
288
- try {
289
- await discussStore.stampMessageError(sourceFlow.flowId, target.itemId, turnId, err?.message ?? String(err));
290
- await discussStore.setTurnStatus(sourceFlow.flowId, target.itemId, "error", null);
291
- } catch {}
292
- await emit("session.transcript.failed", {
293
- scope: "discuss",
294
- turnId,
295
- flowId: sourceFlow.flowId,
296
- itemId: target.itemId,
297
- error: err?.message ?? String(err),
298
- });
299
- }
300
- });
301
- return true;
302
- }
303
-
304
- // ── transcribeAndDispatch ─────────────────────────────────────────────────
305
- // Shared by handleDiscussAudio (fresh upload) and handleDiscussAudioRetry
306
- // (re-transcribe an already-persisted file, e.g. after the operator taps
307
- // Retry on a failed voice message) — transcribes, updates the meta
308
- // sidecar, pushes session.transcript.updated, and on success dispatches
309
- // the agent turn + session.transcript.completed. Callers wrap this in
310
- // setImmediate since the HTTP response has already been sent by the time
311
- // it runs.
312
-
313
- async function transcribeAndDispatch({
314
- sourceFlow, target, turnId, audioPath, audioUrl, metaPath,
315
- mime, language, systemPrompt, createdAtMs, logPrefix,
316
- }) {
317
- const mu = api.runtime?.mediaUnderstanding;
318
- let transcript = "";
319
- let transcribeError = null;
320
- try {
321
- const muResult = await mu.transcribeAudioFile({ cfg: api.config, filePath: audioPath, mime, language });
322
- transcript = typeof muResult?.text === "string" ? muResult.text.trim() : "";
323
- } catch (err) {
324
- transcribeError = err?.message ?? String(err);
325
- api.logger.warn(`${logPrefix}: transcribe failed: ${transcribeError}`);
326
- }
327
-
328
- try {
329
- const { writeFile: writeFileFs } = await import("node:fs/promises");
330
- const status = transcribeError ? "failed" : transcript ? "completed" : "empty";
331
- await writeFileFs(metaPath, JSON.stringify({
332
- turnId, itemId: target.itemId, audioUrl,
333
- transcript: transcript || null,
334
- status, error: transcribeError || null,
335
- createdAtMs, transcribedAtMs: Date.now(),
336
- }, null, 2));
337
- } catch (err) {
338
- api.logger.warn(`${logPrefix}: meta sidecar update failed: ${err?.message ?? err}`);
339
- }
340
-
341
- const transcriptStatus = transcribeError ? "failed" : transcript ? "completed" : "empty";
342
- await emit("session.transcript.updated", {
343
- scope: "discuss",
344
- turnId,
345
- flowId: sourceFlow.flowId,
346
- itemId: target.itemId,
347
- status: transcriptStatus,
348
- text: transcript || null,
349
- audioUrl,
350
- error: transcribeError,
351
- emittedAtMs: Date.now(),
352
- });
353
-
354
- if (transcriptStatus !== "completed") return;
355
-
356
- try {
357
- const elev = await invokeElevated("/manifold/_elev/discuss", {
358
- flowId: sourceFlow.flowId,
359
- session: target.session,
360
- agentId: target.agent,
361
- gateNodeId: target.gateNodeId,
362
- modelOverride: target.modelOverride,
363
- text: transcript,
364
- itemId: target.itemId,
365
- systemPrompt: typeof systemPrompt === "string" ? systemPrompt : null,
366
- }, { timeoutMs: 360_000 });
367
- let payload;
368
- try { payload = JSON.parse(elev.body || "{}"); } catch { payload = {}; }
369
- const turnKind = elev.ok && payload.ok
370
- ? "session.transcript.completed"
371
- : "session.transcript.failed";
372
- const emitRes = await emit(turnKind, elev.ok && payload.ok
373
- ? {
374
- scope: "discuss",
375
- turnId,
376
- flowId: sourceFlow.flowId,
377
- itemId: target.itemId,
378
- text: payload.reply ?? "",
379
- durationMs: payload.durationMs ?? null,
380
- operatorAudioUrl: audioUrl,
381
- operatorTranscript: transcript,
382
- emittedAtMs: Date.now(),
383
- }
384
- : {
385
- scope: "discuss",
386
- turnId,
387
- flowId: sourceFlow.flowId,
388
- itemId: target.itemId,
389
- error: payload.error || payload.code || elev.error || `HTTP ${elev.status}`,
390
- operatorAudioUrl: audioUrl,
391
- operatorTranscript: transcript,
392
- emittedAtMs: Date.now(),
393
- });
394
- if (!emitRes.ok) {
395
- api.logger.warn(`${logPrefix}: canonical emit failed`);
396
- }
397
- } catch (err) {
398
- api.logger.warn(`${logPrefix}: runner error: ${err?.message ?? err}`);
399
- await emit("session.transcript.failed", {
400
- scope: "discuss",
401
- turnId,
402
- flowId: sourceFlow.flowId,
403
- itemId: target.itemId,
404
- error: err?.message ?? String(err),
405
- operatorAudioUrl: audioUrl,
406
- operatorTranscript: transcript,
407
- emittedAtMs: Date.now(),
408
- });
409
- }
410
- }
411
-
412
- // ── handleDiscussAudio ────────────────────────────────────────────────────
413
-
414
- // Connection-declared harness for audio file paths (X-Manifold-Harness,
415
- // same declaration the MCP transport requires). Refuses before any
416
- // filesystem touch — audio is namespaced per harness, never defaulted.
417
- function requireAudioHarness(req, res) {
418
- try {
419
- return resolveAudioHarness(req);
420
- } catch {
421
- res.statusCode = 400;
422
- res.setHeader("Content-Type", "application/json");
423
- res.end(JSON.stringify({ ok: false, code: "missing_harness", error: "missing or reserved X-Manifold-Harness" }));
424
- return null;
425
- }
426
- }
427
-
428
- async function handleDiscussAudio(req, res, sourceFlow) {
429
- const harness = requireAudioHarness(req, res);
430
- if (!harness) return true;
431
- let raw = "";
432
- for await (const chunk of req) raw += chunk;
433
- let body;
434
- try { body = raw ? JSON.parse(raw) : {}; }
435
- catch { res.statusCode = 400; res.end("invalid json"); return true; }
436
- const audioB64 = typeof body.audio === "string" ? body.audio : "";
437
- const contentType = typeof body.contentType === "string" ? body.contentType.toLowerCase() : "audio/m4a";
438
- const language = typeof body.language === "string" ? body.language : undefined;
439
- if (!audioB64) {
440
- res.statusCode = 400;
441
- res.setHeader("Content-Type", "application/json");
442
- res.end(JSON.stringify({ ok: false, code: "missing_audio", error: "audio (base64) is required" }));
443
- return true;
444
- }
445
- const ext = AUDIO_MIME_EXT[contentType] ?? "m4a";
446
- const wantItemId = typeof body.itemId === "string" ? body.itemId : null;
447
- const target = await resolveDiscussTarget(sourceFlow, wantItemId);
448
- if (!target.ok) {
449
- res.statusCode = target.status;
450
- res.setHeader("Content-Type", "application/json");
451
- res.end(JSON.stringify({ ok: false, code: target.code, error: target.error }));
452
- return true;
453
- }
454
- const mu = api.runtime?.mediaUnderstanding;
455
- if (!mu?.transcribeAudioFile) {
456
- res.statusCode = 503;
457
- res.setHeader("Content-Type", "application/json");
458
- res.end(JSON.stringify({ ok: false, code: "media_understanding_unavailable", error: "no audio transcription provider bound" }));
459
- return true;
460
- }
461
- const turnId = randomUUID();
462
- const flowIdShort = sourceFlow.flowId.slice(0, 8);
463
- const audioDir = audioDirForFlow(sourceFlow.flowId, target.itemId, harness);
464
- const audioPath = path.join(audioDir, `${turnId}.${ext}`);
465
- try {
466
- const { mkdir, writeFile } = await import("node:fs/promises");
467
- await mkdir(audioDir, { recursive: true });
468
- await writeFile(audioPath, Buffer.from(audioB64, "base64"));
469
- } catch (err) {
470
- api.logger.warn(`manifold discuss/audio [${flowIdShort}/${turnId.slice(0, 8)}]: persist failed: ${err?.message ?? err}`);
471
- res.statusCode = 500;
472
- res.setHeader("Content-Type", "application/json");
473
- res.end(JSON.stringify({ ok: false, code: "audio_persist_failed", error: err?.message ?? String(err) }));
474
- return true;
475
- }
476
- const audioUrl = `/manifold/runs/${sourceFlow.flowId}/discuss/audio/${turnId}.${ext}`;
477
- const metaPath = path.join(audioDir, `${turnId}.meta.json`);
478
- const createdAtMs = Date.now();
479
- try {
480
- const { writeFile: writeFileFs } = await import("node:fs/promises");
481
- await writeFileFs(metaPath, JSON.stringify({
482
- turnId, itemId: target.itemId, audioUrl, transcript: null, status: "pending", createdAtMs,
483
- }, null, 2));
484
- } catch (err) {
485
- api.logger.warn(`manifold discuss/audio [${flowIdShort}/${turnId.slice(0, 8)}]: pending meta sidecar failed: ${err?.message ?? err}`);
486
- }
487
-
488
- res.statusCode = 202;
489
- res.setHeader("Content-Type", "application/json");
490
- res.end(JSON.stringify({ ok: true, turnId, audioUrl }));
491
-
492
- let systemPrompt = await buildDiscussPrompt({ flow: sourceFlow, target, runStore, nodeExecutionsStore, logger: api.logger });
493
-
494
- setImmediate(() => transcribeAndDispatch({
495
- sourceFlow, target, turnId, audioPath, audioUrl, metaPath,
496
- mime: contentType, language, systemPrompt, createdAtMs,
497
- logPrefix: `manifold discuss/audio async [${flowIdShort}/${turnId.slice(0, 8)}]`,
498
- }));
499
- return true;
500
- }
501
-
502
- // ── handleDiscussAudioRetry ───────────────────────────────────────────────
503
- // Re-runs transcription on an already-uploaded voice message (identified
504
- // by turnId) without re-uploading the audio bytes — the operator's Retry
505
- // tap on a failed/empty transcription bubble. Reuses the same turnId and
506
- // audioUrl so the existing bubble updates in place via the session
507
- // transcript events rather than creating a new turn.
508
-
509
- async function handleDiscussAudioRetry(req, res, sourceFlow) {
510
- const harness = requireAudioHarness(req, res);
511
- if (!harness) return true;
512
- let raw = "";
513
- for await (const chunk of req) raw += chunk;
514
- let body;
515
- try { body = raw ? JSON.parse(raw) : {}; }
516
- catch { res.statusCode = 400; res.end("invalid json"); return true; }
517
- const turnId = typeof body.turnId === "string" ? body.turnId : "";
518
- if (!turnId) {
519
- res.statusCode = 400;
520
- res.setHeader("Content-Type", "application/json");
521
- res.end(JSON.stringify({ ok: false, code: "missing_turn_id", error: "turnId is required" }));
522
- return true;
523
- }
524
- const wantItemId = typeof body.itemId === "string" ? body.itemId : null;
525
- const target = await resolveDiscussTarget(sourceFlow, wantItemId);
526
- if (!target.ok) {
527
- res.statusCode = target.status;
528
- res.setHeader("Content-Type", "application/json");
529
- res.end(JSON.stringify({ ok: false, code: target.code, error: target.error }));
530
- return true;
531
- }
532
- const mu = api.runtime?.mediaUnderstanding;
533
- if (!mu?.transcribeAudioFile) {
534
- res.statusCode = 503;
535
- res.setHeader("Content-Type", "application/json");
536
- res.end(JSON.stringify({ ok: false, code: "media_understanding_unavailable", error: "no audio transcription provider bound" }));
537
- return true;
538
- }
539
- const flowIdShort = sourceFlow.flowId.slice(0, 8);
540
- const audioDir = audioDirForFlow(sourceFlow.flowId, target.itemId, harness);
541
- const metaPath = path.join(audioDir, `${turnId}.meta.json`);
542
- let meta;
543
- try {
544
- const { readFile } = await import("node:fs/promises");
545
- meta = JSON.parse(await readFile(metaPath, "utf8"));
546
- } catch {
547
- res.statusCode = 404;
548
- res.setHeader("Content-Type", "application/json");
549
- res.end(JSON.stringify({ ok: false, code: "turn_not_found", error: "no audio recorded for this turnId" }));
550
- return true;
551
- }
552
- const ext = (typeof meta.audioUrl === "string" ? meta.audioUrl.split(".").pop() : null) || "m4a";
553
- const audioPath = path.join(audioDir, `${turnId}.${ext}`);
554
- if (!existsSync(audioPath)) {
555
- res.statusCode = 404;
556
- res.setHeader("Content-Type", "application/json");
557
- res.end(JSON.stringify({ ok: false, code: "audio_missing", error: "original audio file no longer on disk" }));
558
- return true;
559
- }
560
- const audioUrl = meta.audioUrl;
561
-
562
- let systemPrompt = null;
563
- if (target.promptBuilder) {
564
- try {
565
- const ctx = {
566
- state: await assembleState(sourceFlow.flowId, { runStore, nodeExecutionsStore, baseState: sourceFlow.stateJson ?? {} }),
567
- itemId: target.itemId,
568
- flowId: sourceFlow.flowId,
569
- pipelineId: sourceFlow.stateJson?.pipelineId ?? null,
570
- };
571
- systemPrompt = await Promise.resolve(target.promptBuilder(ctx));
572
- } catch (err) {
573
- api.logger.warn(`manifold discuss/audio/retry promptBuilder threw for ${flowIdShort}/${target.itemId}: ${err?.message ?? err}`);
574
- }
575
- }
576
-
577
- res.statusCode = 202;
578
- res.setHeader("Content-Type", "application/json");
579
- res.end(JSON.stringify({ ok: true, turnId, audioUrl }));
580
-
581
- setImmediate(() => transcribeAndDispatch({
582
- sourceFlow, target, turnId, audioPath, audioUrl, metaPath,
583
- mime: EXT_TO_MIME[ext] ?? "audio/m4a", language: undefined, systemPrompt,
584
- createdAtMs: typeof meta.createdAtMs === "number" ? meta.createdAtMs : Date.now(),
585
- logPrefix: `manifold discuss/audio/retry async [${flowIdShort}/${turnId.slice(0, 8)}]`,
586
- }));
587
- return true;
588
- }
589
-
590
- // ── handleDiscussAudioGet ─────────────────────────────────────────────────
591
-
592
- async function handleDiscussAudioGet(req, res, sourceFlow, audioFileName) {
593
- const harness = requireAudioHarness(req, res);
594
- if (!harness) return true;
595
- if (!/^[a-zA-Z0-9-]{8,64}\.[a-zA-Z0-9]{1,8}$/.test(audioFileName)) {
596
- res.statusCode = 400;
597
- res.end("invalid audio file name");
598
- return true;
599
- }
600
- const ext = audioFileName.split(".").pop().toLowerCase();
601
- const { readdir, readFile, stat } = await import("node:fs/promises");
602
- for (const flowRoot of audioRootsForFlow(sourceFlow.flowId, harness)) {
603
- let entries;
604
- try { entries = await readdir(flowRoot); }
605
- catch { continue; }
606
- for (const itemDir of entries) {
607
- const candidate = path.join(flowRoot, itemDir, audioFileName);
608
- try {
609
- const st = await stat(candidate);
610
- if (!st.isFile()) continue;
611
- const bytes = await readFile(candidate);
612
- res.statusCode = 200;
613
- res.setHeader("Content-Type", EXT_TO_MIME[ext] ?? "application/octet-stream");
614
- res.setHeader("Content-Length", String(bytes.length));
615
- res.setHeader("Cache-Control", "private, max-age=86400");
616
- res.end(bytes);
617
- return true;
618
- } catch { /* try next */ }
619
- }
620
- }
621
- res.statusCode = 404;
622
- res.end("not found");
623
- return true;
624
- }
625
-
626
- // ── handleDiscussHistory ──────────────────────────────────────────────────
627
-
628
- async function handleDiscussHistory(req, res, sourceFlow) {
629
- const harness = requireAudioHarness(req, res);
630
- if (!harness) return true;
631
- const url = new URL(req.url, `http://${req.headers.host || "localhost"}`);
632
- const wantItemId = url.searchParams.get("itemId");
633
- const offsetParam = Number(url.searchParams.get("offset"));
634
- const offset = Number.isFinite(offsetParam) && offsetParam > 0 ? Math.floor(offsetParam) : 0;
635
- const target = await resolveDiscussTarget(sourceFlow, wantItemId);
636
- if (!target.ok) {
637
- res.statusCode = target.status;
638
- res.setHeader("Content-Type", "application/json");
639
- res.end(JSON.stringify({ ok: false, code: target.code, error: target.error }));
640
- return true;
641
- }
642
- const dsState = await discussStore.getState(sourceFlow.flowId, target.itemId);
643
- let parsed;
644
- if (dsState && dsState.messages.length > 0) {
645
- parsed = {
646
- ok: true,
647
- messages: dsState.messages.map((m) => ({
648
- isOperator: m.role === "operator",
649
- text: m.text ?? null,
650
- ts: m.ts ?? null,
651
- turnId: m.turnId ?? null,
652
- audioKey: m.audioKey ?? null,
653
- proposedDraft: m.proposedDraft ?? null,
654
- proposedMeta: m.proposedMeta ?? null,
655
- error: m.error ?? null,
656
- })),
657
- turnStatus: dsState.turnStatus,
658
- activeTurnId: dsState.activeTurnId ?? null,
659
- // In-memory store always returns the full thread — nothing paged
660
- // out, so there's never more to load from this branch.
661
- hasMore: false,
662
- };
663
- const pending = dsState.pending;
664
- if (pending && (pending.text || (pending.fields && Object.keys(pending.fields ?? {}).length > 0))) {
665
- parsed.pending = {
666
- text: typeof pending.text === "string" ? pending.text : null,
667
- fields: pending.fields && typeof pending.fields === "object" ? pending.fields : null,
668
- updatedAt: typeof pending.updatedAt === "number" ? pending.updatedAt : null,
669
- };
670
- }
671
- } else {
672
- const pending = await discussStore.readPending(sourceFlow.flowId, target.itemId);
673
- const hasPending = pending && (pending.text || (pending.fields && Object.keys(pending.fields ?? {}).length > 0));
674
- if (hasPending) {
675
- parsed = { ok: true, messages: [] };
676
- parsed.pending = {
677
- text: typeof pending.text === "string" ? pending.text : null,
678
- fields: pending.fields && typeof pending.fields === "object" ? pending.fields : null,
679
- updatedAt: typeof pending.updatedAt === "number" ? pending.updatedAt : null,
680
- };
681
- } else {
682
- // No recorded turn yet — the thread is empty. Discuss history is the
683
- // discuss store's own record (both directions of every turn); the
684
- // harness's session files are not a source for it.
685
- parsed = { ok: true, messages: [] };
686
- }
687
- parsed.turnStatus = dsState?.turnStatus ?? "idle";
688
- parsed.activeTurnId = dsState?.activeTurnId ?? null;
689
- }
690
- try {
691
- if (parsed && parsed.ok) {
692
- parsed.messages = Array.isArray(parsed.messages) ? parsed.messages : [];
693
- const audioMetas = await loadAudioMetasForFlow(sourceFlow.flowId, harness);
694
- if (audioMetas.length > 0) {
695
- const matchedTurnIds = new Set();
696
- for (const msg of parsed.messages) {
697
- if (!msg || !msg.isOperator) continue;
698
- const t = typeof msg.text === "string" ? msg.text.trim() : "";
699
- if (!t) continue;
700
- const meta = audioMetas.find((m) =>
701
- typeof m.transcript === "string"
702
- && m.transcript.trim() === t
703
- && !matchedTurnIds.has(m.turnId)
704
- );
705
- if (meta && typeof meta.audioUrl === "string") {
706
- msg.audioUrl = meta.audioUrl;
707
- msg.turnId = meta.turnId;
708
- matchedTurnIds.add(meta.turnId);
709
- }
710
- }
711
- for (const meta of audioMetas) {
712
- if (!meta || !meta.turnId || !meta.audioUrl) continue;
713
- if (matchedTurnIds.has(meta.turnId)) continue;
714
- if (target.itemId && meta.itemId && meta.itemId !== target.itemId) continue;
715
- const status = typeof meta.status === "string" ? meta.status : "completed";
716
- const isPending = status === "pending";
717
- const audioTs = typeof meta.createdAtMs === "number" ? meta.createdAtMs : 0;
718
- const hasSubsequentAgentReply = parsed.messages.some(
719
- (m) => m && !m.isOperator && (m.ts ?? 0) > audioTs
720
- );
721
- parsed.messages.push({
722
- isOperator: true,
723
- text: typeof meta.transcript === "string" ? meta.transcript : "",
724
- ts: audioTs || null,
725
- audioUrl: meta.audioUrl,
726
- turnId: meta.turnId,
727
- transcribing: isPending,
728
- pendingAgentReply: !hasSubsequentAgentReply && (status === "completed" || isPending),
729
- transcribeStatus: status,
730
- error: status === "failed" ? (meta.error || null) : null,
731
- });
732
- }
733
- parsed.messages.sort((a, b) => (a.ts ?? 0) - (b.ts ?? 0));
734
- }
735
- }
736
- } catch (err) {
737
- api.logger.warn(`manifold discuss history enrichment error: ${err?.message ?? err}`);
738
- if (!parsed) parsed = { ok: false, code: "internal", error: err?.message ?? String(err) };
739
- }
740
- if (parsed?.ok) {
741
- // No channel plugin anymore: replies go back through the same HTTP
742
- // discuss route this history came from, or the WS dialog door.
743
- parsed.channelId = "manifold-dialog";
744
- parsed.channelInboundUrl = null;
745
- }
746
- res.statusCode = (parsed?.ok) ? 200 : 500;
747
- res.setHeader("Content-Type", "application/json");
748
- res.end(JSON.stringify(parsed ?? { ok: false, code: "internal" }));
749
- return true;
750
- }
751
-
752
- // ── handleDiscussApplyDraft ───────────────────────────────────────────────
753
-
754
- async function handleDiscussApplyDraft(req, res, sourceFlow) {
755
- let raw = "";
756
- for await (const chunk of req) raw += chunk;
757
- let body;
758
- try { body = raw ? JSON.parse(raw) : {}; }
759
- catch { res.statusCode = 400; res.end("invalid json"); return true; }
760
- let text = typeof body.text === "string" ? body.text.trim() : "";
761
- let fields = (body.fields && typeof body.fields === "object" && !Array.isArray(body.fields))
762
- ? body.fields
763
- : null;
764
- const source = typeof body.source === "string" ? body.source : null;
765
- const wantItemId = typeof body.itemId === "string" ? body.itemId : null;
766
- // Resolve target first so we can use target.itemId for the sidecar
767
- // lookup before checking whether payload is present.
768
- const target = await resolveDiscussTarget(sourceFlow, wantItemId);
769
- if (!target.ok) {
770
- res.statusCode = target.status;
771
- res.setHeader("Content-Type", "application/json");
772
- res.end(JSON.stringify({ ok: false, code: target.code, error: target.error }));
773
- return true;
774
- }
775
- // No explicit payload — fall back to the pending proposal so a client
776
- // can commit a pre-built proposal with a single tap without
777
- // needing to fetch and re-POST the full draft text.
778
- if (!text && !fields) {
779
- const pending = await discussStore.readPending(sourceFlow.flowId, target.itemId);
780
- if (pending?.text) text = pending.text;
781
- if (pending?.fields && typeof pending.fields === "object" && !Array.isArray(pending.fields)) {
782
- fields = pending.fields;
783
- }
784
- }
785
- if (!text && !fields) {
786
- res.statusCode = 400;
787
- res.setHeader("Content-Type", "application/json");
788
- res.end(JSON.stringify({ ok: false, code: "missing_payload", error: "text and/or fields is required" }));
789
- return true;
790
- }
791
- const summary = [];
792
- if (text) {
793
- const r = await persistRevisedDraft({
794
- flowId: sourceFlow.flowId,
795
- itemId: target.itemId,
796
- newDraft: text,
797
- source,
798
- store,
799
- logger: api.logger,
800
- });
801
- if (!r.applied) {
802
- api.logger.warn(`manifold discuss apply-draft [${sourceFlow.flowId.slice(0, 8)}]: body persist failed: ${r.code}`);
803
- res.statusCode = r.code === "rejected_meta_narration" ? 400 : 500;
804
- res.setHeader("Content-Type", "application/json");
805
- res.end(JSON.stringify({ ok: false, code: r.code }));
806
- return true;
807
- }
808
- summary.push(`body ${text.length}ch`);
809
- }
810
- if (fields) {
811
- const r = await persistRevisedMeta({
812
- flowId: sourceFlow.flowId,
813
- itemId: target.itemId,
814
- fields,
815
- store,
816
- logger: api.logger,
817
- });
818
- if (!r.applied) {
819
- api.logger.warn(`manifold discuss apply-draft [${sourceFlow.flowId.slice(0, 8)}]: meta persist failed: ${r.code}`);
820
- res.statusCode = 500;
821
- res.setHeader("Content-Type", "application/json");
822
- res.end(JSON.stringify({ ok: false, code: r.code }));
823
- return true;
824
- }
825
- summary.push(`meta=${Object.keys(fields).join("+")}`);
826
- }
827
- // INTENTIONAL: no gateResolver.recordItemDecision here.
828
- // Apply revises; Approve commits. They are separate operator intents.
829
- try { await discussStore.clearPending(sourceFlow.flowId, target.itemId); } catch {}
830
- api.logger.info(`manifold discuss apply-draft [${sourceFlow.flowId.slice(0, 8)}]: applied (${summary.join(", ")})`);
831
- res.statusCode = 200;
832
- res.setHeader("Content-Type", "application/json");
833
- res.end(JSON.stringify({ ok: true }));
834
- return true;
835
- }
836
-
837
- // ── Return all exported symbols ───────────────────────────────────────────
838
-
839
- return {
840
- handleDiscuss,
841
- handleDiscussAudio,
842
- handleDiscussAudioGet,
843
- handleDiscussAudioRetry,
844
- handleDiscussHistory,
845
- handleDiscussApplyDraft,
846
- resolveDiscussTarget,
847
- };
848
- }