@igorjpimenta/manifold 0.0.0-stage → 2026.11.22-beta.3

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/.migrations/ops/0000_futuristic_karma.sql +111 -0
  2. package/.migrations/ops/0001_low_maximus.sql +7 -0
  3. package/.migrations/ops/meta/0000_snapshot.json +763 -0
  4. package/.migrations/ops/meta/0001_snapshot.json +173 -0
  5. package/.migrations/ops/meta/_journal.json +20 -0
  6. package/.migrations/runtime/0000_real_boomer.sql +180 -0
  7. package/.migrations/runtime/0001_hot_dakota_north.sql +2 -0
  8. package/.migrations/runtime/0002_breezy_vertigo.sql +8 -0
  9. package/.migrations/runtime/0003_dashing_jack_flag.sql +5 -0
  10. package/.migrations/runtime/0004_panoramic_ego.sql +1 -0
  11. package/.migrations/runtime/0005_tidy_ben_grimm.sql +10 -0
  12. package/.migrations/runtime/0006_wet_nightmare.sql +57 -0
  13. package/.migrations/runtime/0007_ambiguous_chronomancer.sql +8 -0
  14. package/.migrations/runtime/0008_wealthy_thundra.sql +301 -0
  15. package/.migrations/runtime/0009_lying_shocker.sql +96 -0
  16. package/.migrations/runtime/0010_solid_phantom_reporter.sql +160 -0
  17. package/.migrations/runtime/0011_windy_demogoblin.sql +175 -0
  18. package/.migrations/runtime/0012_restore_harness_fks.sql +103 -0
  19. package/.migrations/runtime/meta/0000_snapshot.json +1181 -0
  20. package/.migrations/runtime/meta/0001_snapshot.json +1209 -0
  21. package/.migrations/runtime/meta/0002_snapshot.json +1261 -0
  22. package/.migrations/runtime/meta/0003_snapshot.json +1292 -0
  23. package/.migrations/runtime/meta/0004_snapshot.json +1240 -0
  24. package/.migrations/runtime/meta/0006_snapshot.json +1310 -0
  25. package/.migrations/runtime/meta/0007_snapshot.json +1362 -0
  26. package/.migrations/runtime/meta/0008_snapshot.json +1742 -0
  27. package/.migrations/runtime/meta/0009_snapshot.json +2413 -0
  28. package/.migrations/runtime/meta/0010_snapshot.json +2562 -0
  29. package/.migrations/runtime/meta/0011_snapshot.json +2812 -0
  30. package/.migrations/runtime/meta/0012_snapshot.json +2812 -0
  31. package/.migrations/runtime/meta/_journal.json +97 -0
  32. package/README.md +1583 -2
  33. package/RELEASING.md +89 -0
  34. package/agent/fleet.js +100 -0
  35. package/bin/cli.js +854 -0
  36. package/bin/manifold.js +4 -0
  37. package/boot/flow-revival.js +536 -0
  38. package/budget/index.js +495 -0
  39. package/budget/lib.js +59 -0
  40. package/dashboard/cost.js +528 -0
  41. package/dashboard/dist/assets/index-CUfp63sj.css +1 -0
  42. package/dashboard/dist/assets/index-Qy9JMpma.js +371 -0
  43. package/dashboard/dist/index.html +13 -0
  44. package/dashboard/event-log.js +267 -0
  45. package/dashboard/index.html +12 -0
  46. package/dashboard/package-lock.json +2877 -0
  47. package/dashboard/package.json +37 -0
  48. package/dashboard/pipeline-graph.js +131 -0
  49. package/dashboard/postcss.config.js +6 -0
  50. package/dashboard/search.js +183 -0
  51. package/dashboard/server.js +1015 -0
  52. package/dashboard/src/App.tsx +42 -0
  53. package/dashboard/src/api/client.ts +118 -0
  54. package/dashboard/src/api/types.ts +510 -0
  55. package/dashboard/src/api/ws.tsx +112 -0
  56. package/dashboard/src/components/CancelButton.tsx +63 -0
  57. package/dashboard/src/components/ClickToCopy.tsx +68 -0
  58. package/dashboard/src/components/CopyButton.tsx +61 -0
  59. package/dashboard/src/components/DailyCostTrend.tsx +85 -0
  60. package/dashboard/src/components/DailyTimeTrend.tsx +94 -0
  61. package/dashboard/src/components/Funnel.tsx +149 -0
  62. package/dashboard/src/components/GateForm.tsx +158 -0
  63. package/dashboard/src/components/GraphView.tsx +302 -0
  64. package/dashboard/src/components/GroupPathsSummary.tsx +47 -0
  65. package/dashboard/src/components/Histogram.tsx +292 -0
  66. package/dashboard/src/components/Layout.tsx +28 -0
  67. package/dashboard/src/components/NeedsAttention.tsx +98 -0
  68. package/dashboard/src/components/NodeContextCard.tsx +132 -0
  69. package/dashboard/src/components/PathTrail.tsx +35 -0
  70. package/dashboard/src/components/PipelineCostBreakdown.tsx +277 -0
  71. package/dashboard/src/components/RerunButton.tsx +46 -0
  72. package/dashboard/src/components/RunComparison.tsx +53 -0
  73. package/dashboard/src/components/Sparkline.tsx +94 -0
  74. package/dashboard/src/components/StatStrip.tsx +147 -0
  75. package/dashboard/src/components/StateTree.tsx +84 -0
  76. package/dashboard/src/components/StatusBadge.tsx +18 -0
  77. package/dashboard/src/components/SubflowPathPills.tsx +38 -0
  78. package/dashboard/src/components/SubflowSummary.tsx +24 -0
  79. package/dashboard/src/components/SubflowsCard.tsx +327 -0
  80. package/dashboard/src/components/TodayStrip.tsx +86 -0
  81. package/dashboard/src/components/TranscriptPane.tsx +99 -0
  82. package/dashboard/src/components/TranscriptRow.tsx +69 -0
  83. package/dashboard/src/components/ui/badge.tsx +38 -0
  84. package/dashboard/src/components/ui/button.tsx +28 -0
  85. package/dashboard/src/components/ui/card.tsx +42 -0
  86. package/dashboard/src/components/ui/skeleton.tsx +9 -0
  87. package/dashboard/src/components/ui/table.tsx +62 -0
  88. package/dashboard/src/index.css +26 -0
  89. package/dashboard/src/lib/anomaly.ts +42 -0
  90. package/dashboard/src/lib/format.ts +30 -0
  91. package/dashboard/src/lib/step-history.ts +13 -0
  92. package/dashboard/src/lib/subflow.ts +154 -0
  93. package/dashboard/src/lib/use-click-outside.ts +28 -0
  94. package/dashboard/src/lib/use-ignored-clusters.ts +67 -0
  95. package/dashboard/src/lib/utils.ts +6 -0
  96. package/dashboard/src/main.tsx +10 -0
  97. package/dashboard/src/types/shims.d.ts +4 -0
  98. package/dashboard/src/views/Home.tsx +478 -0
  99. package/dashboard/src/views/PipelineDetail.tsx +1185 -0
  100. package/dashboard/src/views/PipelinesList.tsx +111 -0
  101. package/dashboard/src/views/RunDetail.tsx +248 -0
  102. package/dashboard/src/views/Search.tsx +196 -0
  103. package/dashboard/stats.js +668 -0
  104. package/dashboard/tailwind.config.ts +43 -0
  105. package/dashboard/tree-stats.js +12 -0
  106. package/dashboard/tsconfig.json +25 -0
  107. package/dashboard/views.js +231 -0
  108. package/dashboard/vite.config.ts +34 -0
  109. package/drizzle.config.js +12 -0
  110. package/drizzle.config.ops.js +12 -0
  111. package/elevation.js +116 -0
  112. package/engine/admission-promotion-resume.js +127 -0
  113. package/engine/agent-dispatch.js +64 -0
  114. package/engine/child-resume-trigger.js +315 -0
  115. package/engine/executor-budget.js +87 -0
  116. package/engine/executor-cancel.js +83 -0
  117. package/engine/executor-errors.js +122 -0
  118. package/engine/executor-helpers.js +254 -0
  119. package/engine/executor-nodes.js +292 -0
  120. package/engine/executor-persist.js +212 -0
  121. package/engine/executor-subflow-children.js +275 -0
  122. package/engine/executor.js +1013 -0
  123. package/engine/global-concurrency.js +33 -0
  124. package/engine/loader.js +528 -0
  125. package/engine/needs-resolver.js +229 -0
  126. package/engine/pipelines-watcher.js +133 -0
  127. package/engine/result-replay.js +34 -0
  128. package/engine/revival-messages.js +11 -0
  129. package/engine/spawn-child.js +55 -0
  130. package/engine/wait-for-flow-settlement.js +109 -0
  131. package/events/catalog.js +26 -0
  132. package/events/emit.js +44 -0
  133. package/events/kinds.js +118 -0
  134. package/events/serve-ws.js +74 -0
  135. package/events/stream.js +35 -0
  136. package/events/ws-dialog.js +257 -0
  137. package/events/ws-frame.js +194 -0
  138. package/events/ws-run-events.js +70 -0
  139. package/events.js +32 -0
  140. package/gates/gate-resolver.js +576 -0
  141. package/gates/paused-flows.js +55 -0
  142. package/graphql/columns.js +67 -0
  143. package/graphql/schema.js +333 -0
  144. package/index.js +49 -0
  145. package/mcp/http.js +159 -0
  146. package/mcp/identity.js +94 -0
  147. package/mcp/stdio.js +80 -0
  148. package/mcp/tools.js +245 -0
  149. package/mcp/wire-ops.js +178 -0
  150. package/package.json +49 -4
  151. package/routes/bearer-auth.js +57 -0
  152. package/routes/discuss-audio.js +87 -0
  153. package/routes/discuss-component.js +39 -0
  154. package/routes/discuss-draft.js +159 -0
  155. package/routes/discuss-helpers.js +20 -0
  156. package/routes/discuss.js +848 -0
  157. package/routes/failures.js +104 -0
  158. package/routes/graphql.js +61 -0
  159. package/routes/health.js +54 -0
  160. package/routes/operator-discuss.js +193 -0
  161. package/routes/operator-resume.js +32 -0
  162. package/routes/operator-retry.js +301 -0
  163. package/routes/operator.js +539 -0
  164. package/routes/pipelines.js +118 -0
  165. package/routes/runs.js +1129 -0
  166. package/scripts/ci/import-check.mjs +50 -0
  167. package/scripts/link-core-self.mjs +31 -0
  168. package/scripts/with-guard.sh +24 -0
  169. package/server/app.js +503 -0
  170. package/server/registry.js +53 -0
  171. package/server/serve.js +163 -0
  172. package/state/admission-queue-store.js +325 -0
  173. package/state/attribution-registries.js +102 -0
  174. package/state/batch-writer.js +162 -0
  175. package/state/db-guard.js +63 -0
  176. package/state/db-health.js +27 -0
  177. package/state/db.js +122 -0
  178. package/state/discuss-store.js +299 -0
  179. package/state/failure-store.js +427 -0
  180. package/state/migrate.js +104 -0
  181. package/state/node-cost.js +67 -0
  182. package/state/node-executions.js +775 -0
  183. package/state/node-health-store.js +124 -0
  184. package/state/ops-merge.js +93 -0
  185. package/state/paths.js +146 -0
  186. package/state/pipeline-dirs.js +99 -0
  187. package/state/pipeline-registry.js +449 -0
  188. package/state/run-store.js +697 -0
  189. package/state/schema.js +438 -0
  190. package/state/schema.ops.js +44 -0
  191. package/state/session-index.js +177 -0
  192. package/state/session-keys.js +39 -0
  193. package/state/state-store.js +311 -0
  194. package/state/subflow-state.js +126 -0
  195. package/state/tool-handoff.js +169 -0
  196. package/telemetry/budget-alert.js +353 -0
  197. package/telemetry/cli.js +331 -0
  198. package/telemetry/grammar.js +119 -0
  199. package/telemetry/http-budget.js +132 -0
  200. package/telemetry/http-cost.js +670 -0
  201. package/telemetry/http-helpers.js +134 -0
  202. package/telemetry/http-tree.js +349 -0
  203. package/telemetry/http.js +44 -0
  204. package/telemetry/index.js +307 -0
  205. package/telemetry/ingest.js +134 -0
  206. package/telemetry/labels.js +115 -0
  207. package/telemetry/pricer.js +77 -0
  208. package/telemetry/resolver.js +314 -0
  209. package/telemetry/store.js +147 -0
  210. package/utils/run-patch.js +43 -0
@@ -0,0 +1,104 @@
1
+ // failures.js — companion-facing HTTP surface over failure-store.js.
2
+ //
3
+ // Ignore is a pure client device-local annotation with no server round trip
4
+ // at all, so it has no route here. Only GET (list) and POST .../retry
5
+ // (implemented in routes/operator-retry.js) remain.
6
+ import { authorizeBearerRequest, sendUnauthorized } from "./bearer-auth.js";
7
+
8
+ export function registerFailureRoutes({ api, failureStore, invokeElevated }) {
9
+ // ── GET /manifold/failures ─────────────────────────────────────────────
10
+ api.registerHttpRoute({
11
+ path: "/manifold/failures",
12
+ auth: "plugin",
13
+ match: "exact",
14
+ handler: async (req, res) => {
15
+ if (req.method !== "GET") {
16
+ res.statusCode = 405;
17
+ res.setHeader("Allow", "GET");
18
+ res.end("method not allowed");
19
+ return true;
20
+ }
21
+ const authz = authorizeBearerRequest(req, { logger: api.logger });
22
+ if (!authz.ok) { sendUnauthorized(res, authz.reason); return true; }
23
+ const url = new URL(req.url, `http://${req.headers.host || "localhost"}`);
24
+ const resolved = url.searchParams.get("resolved");
25
+ const limit = Math.min(200, Number(url.searchParams.get("limit") ?? 50) || 50);
26
+ const sinceMs = Number(url.searchParams.get("since")) || undefined;
27
+ try {
28
+ const resolvedFilter = resolved === "true" ? true
29
+ : resolved === "all" || resolved === "null" ? null
30
+ : false;
31
+ const rows = await failureStore.list({
32
+ resolved: resolvedFilter,
33
+ limit,
34
+ since: sinceMs,
35
+ });
36
+ res.statusCode = 200;
37
+ res.setHeader("Content-Type", "application/json");
38
+ res.end(JSON.stringify({ rows, count: rows.length }));
39
+ } catch (err) {
40
+ api.logger.warn(`manifold /failures handler error: ${err?.message ?? err}`);
41
+ res.statusCode = 500;
42
+ res.setHeader("Content-Type", "application/json");
43
+ res.end(JSON.stringify({ ok: false, error: err?.message ?? String(err) }));
44
+ }
45
+ return true;
46
+ },
47
+ });
48
+
49
+ // ── POST /manifold/failures/<id>/retry ──────────────────────────────────
50
+ api.registerHttpRoute({
51
+ path: "/manifold/failures/",
52
+ auth: "plugin",
53
+ match: "prefix",
54
+ handler: async (req, res) => {
55
+ if (req.method !== "POST") {
56
+ res.statusCode = 405;
57
+ res.setHeader("Allow", "POST");
58
+ res.end("method not allowed");
59
+ return true;
60
+ }
61
+ const authz = authorizeBearerRequest(req, { logger: api.logger });
62
+ if (!authz.ok) { sendUnauthorized(res, authz.reason); return true; }
63
+
64
+ const url = new URL(req.url, `http://${req.headers.host || "localhost"}`);
65
+ const tail = url.pathname.slice("/manifold/failures/".length);
66
+ let raw = "";
67
+ for await (const chunk of req) raw += chunk;
68
+ let body = {};
69
+ try { body = raw ? JSON.parse(raw) : {}; }
70
+ catch { res.statusCode = 400; res.end("invalid json"); return true; }
71
+ const via = typeof body?.via === "string" ? body.via : "app";
72
+
73
+ try {
74
+ const retryMatch = tail.match(/^([^/]+)\/retry$/);
75
+ if (retryMatch) {
76
+ const id = decodeURIComponent(retryMatch[1]);
77
+ try {
78
+ const elev = await invokeElevated("/manifold/_elev/retry-failure", {
79
+ id, via,
80
+ session: body?.session, agentId: body?.agentId,
81
+ });
82
+ res.statusCode = elev.status || 500;
83
+ res.setHeader("Content-Type", "application/json");
84
+ res.end(elev.body || JSON.stringify({ ok: false, code: "elevation_no_body" }));
85
+ } catch (err) {
86
+ api.logger.warn(`manifold retry handler error: ${err?.message ?? err}`);
87
+ res.statusCode = 500;
88
+ res.setHeader("Content-Type", "application/json");
89
+ res.end(JSON.stringify({ ok: false, code: "internal", error: err?.message ?? String(err) }));
90
+ }
91
+ return true;
92
+ }
93
+ res.statusCode = 404;
94
+ res.end("unknown failures subroute");
95
+ } catch (err) {
96
+ api.logger.warn(`manifold /failures/ handler error: ${err?.message ?? err}`);
97
+ res.statusCode = 500;
98
+ res.setHeader("Content-Type", "application/json");
99
+ res.end(JSON.stringify({ ok: false, error: err?.message ?? String(err) }));
100
+ }
101
+ return true;
102
+ },
103
+ });
104
+ }
@@ -0,0 +1,61 @@
1
+ // graphql.js — client-agnostic query surface over manifold state.
2
+ //
3
+ // POST /manifold/graphql replaces per-view REST polling for read models:
4
+ // the consumer picks fields, the core stays the single writer. Mutations
5
+ // are intentionally absent — writes go through the existing POST routes.
6
+ import { createRootValue, executeQuery } from "../graphql/schema.js";
7
+ import { authorizeBearerRequest, sendUnauthorized } from "./bearer-auth.js";
8
+
9
+ export function registerGraphqlRoutes({
10
+ api,
11
+ failureStore,
12
+ runStore,
13
+ runtimeDbPath,
14
+ opsDbPath,
15
+ }) {
16
+ // ── POST /manifold/graphql ───────────────────────────────────────────
17
+ api.registerHttpRoute({
18
+ path: "/manifold/graphql",
19
+ auth: "plugin",
20
+ match: "exact",
21
+ handler: async (req, res) => {
22
+ if (req.method !== "POST") {
23
+ res.statusCode = 405;
24
+ res.setHeader("Allow", "POST");
25
+ res.end("method not allowed");
26
+ return true;
27
+ }
28
+ const authz = authorizeBearerRequest(req, { logger: api.logger });
29
+ if (!authz.ok) { sendUnauthorized(res, authz.reason); return true; }
30
+ let raw = "";
31
+ try {
32
+ for await (const chunk of req) raw += chunk;
33
+ } catch {
34
+ res.statusCode = 400;
35
+ res.end("unreadable body");
36
+ return true;
37
+ }
38
+ let payload;
39
+ try {
40
+ payload = raw ? JSON.parse(raw) : {};
41
+ } catch {
42
+ res.statusCode = 400;
43
+ res.end("invalid json");
44
+ return true;
45
+ }
46
+ const root = createRootValue({
47
+ failureStore,
48
+ runStore,
49
+ ...(runtimeDbPath ? { runtimeDbPath } : {}),
50
+ ...(opsDbPath ? { opsDbPath } : {}),
51
+ logger: api.logger,
52
+ });
53
+ const out = await executeQuery({ root, query: payload?.query, variables: payload?.variables });
54
+ res.statusCode = 200;
55
+ res.setHeader("Content-Type", "application/json");
56
+ res.setHeader("Cache-Control", "no-cache");
57
+ res.end(JSON.stringify(out));
58
+ return true;
59
+ },
60
+ });
61
+ }
@@ -0,0 +1,54 @@
1
+ // health.js — manifold's own liveness plus per-file DB reachability.
2
+ //
3
+ // The app's connectivity probe and any consumer's readiness check land
4
+ // here instead of the harness status surface. `ok` is the AND of every
5
+ // check: a degraded database reports ok:false with the failing file
6
+ // named, never a blanket ok over silent rot. No harness contact.
7
+ import { createRequire } from "node:module";
8
+ import { checkDb } from "../state/db-health.js";
9
+ import { resolveStorePaths } from "../state/paths.js";
10
+ import { noteDbFailure } from "../state/db-guard.js";
11
+ import { authorizeBearerRequest, sendUnauthorized } from "./bearer-auth.js";
12
+
13
+ const require = createRequire(import.meta.url);
14
+ const MANIFOLD_VERSION = require("../package.json").version;
15
+
16
+ // The app's own store home (MANIFOLD_DATA_DIR / MANIFOLD_*_DB), never a
17
+ // harness default: the health answer must describe the files this process
18
+ // actually reads.
19
+ const DB_PATHS = () => resolveStorePaths();
20
+
21
+ export function registerHealthRoutes({ api }) {
22
+ api.registerHttpRoute({
23
+ path: "/manifold/health",
24
+ auth: "plugin",
25
+ match: "exact",
26
+ handler: async (req, res) => {
27
+ if (req.method !== "GET") {
28
+ res.statusCode = 405;
29
+ res.setHeader("Allow", "GET");
30
+ res.end("method not allowed");
31
+ return true;
32
+ }
33
+ const authz = authorizeBearerRequest(req, { logger: api.logger });
34
+ if (!authz.ok) { sendUnauthorized(res, authz.reason); return true; }
35
+ const db = {};
36
+ let ok = true;
37
+ const paths = DB_PATHS();
38
+ for (const [name, dbPath] of [["runtime", paths.runtimeDb], ["ops", paths.opsDb]]) {
39
+ const check = checkDb(dbPath);
40
+ db[name] = check.ok ? { ok: true, latencyMs: check.latencyMs } : { ok: false, error: check.error };
41
+ if (!check.ok) {
42
+ ok = false;
43
+ const err = new Error(check.error);
44
+ err.code = check.code;
45
+ noteDbFailure(err, { dbPath, logger: api.logger });
46
+ }
47
+ }
48
+ res.statusCode = 200;
49
+ res.setHeader("Content-Type", "application/json");
50
+ res.end(JSON.stringify({ ok, manifold: MANIFOLD_VERSION, uptimeMs: Math.round(process.uptime() * 1000), db }));
51
+ return true;
52
+ },
53
+ });
54
+ }
@@ -0,0 +1,193 @@
1
+
2
+ // ── Pure helpers ──────────────────────────────────────────────────────────────
3
+
4
+ export function stringifyMessageContent(content) {
5
+ if (typeof content === "string") return content;
6
+ if (Array.isArray(content)) {
7
+ return content
8
+ .filter((c) => c?.type === "text" || typeof c?.text === "string")
9
+ .map((c) => c.text ?? "")
10
+ .join("\n");
11
+ }
12
+ return "";
13
+ }
14
+
15
+ // Takes [{role, content, timestamp}] from a discuss JSONL session and returns
16
+ // [{isOperator, text, ts}] with protocol headers/footers stripped from user
17
+ // turns and <draft>...</draft> tags stripped from assistant turns.
18
+ export function filterDiscussHistoryMessages(msgs) {
19
+ const toEpochMs = (v) => {
20
+ if (v == null) return null;
21
+ if (typeof v === "number") return Number.isFinite(v) ? v : null;
22
+ const n = Date.parse(String(v));
23
+ return Number.isFinite(n) ? n : null;
24
+ };
25
+ const out = [];
26
+ for (const m of msgs) {
27
+ if (m?.role !== "user" && m?.role !== "assistant") continue;
28
+ let text = stringifyMessageContent(m.content);
29
+ if (m.role === "user") {
30
+ const split = text.split(/\n\n---\n\n/);
31
+ if (split.length >= 2) text = split.slice(1).join("\n\n---\n\n");
32
+ if (/^##/.test(text)) {
33
+ const parts = text.split(/\n\n\n+/);
34
+ if (parts.length >= 2) text = parts[parts.length - 1];
35
+ }
36
+ text = text.replace(/\n*\[discuss-protocol\][\s\S]*$/, "").trim();
37
+ if (text) out.push({ isOperator: true, text, ts: toEpochMs(m.timestamp) });
38
+ } else {
39
+ text = text.replace(/<draft>[\s\S]*?<\/draft>/g, "").trim();
40
+ if (text) out.push({ isOperator: false, text, ts: toEpochMs(m.timestamp) });
41
+ }
42
+ }
43
+ return out;
44
+ }
45
+
46
+ // Given a resolved provider chain and a sync isCooldown predicate, returns the
47
+ // best {provider, model} to use for this turn. Skips the primary if it's in
48
+ // billing cooldown and a healthy fallback is available.
49
+ export function selectDiscussProvider({ primarySpec, chain, isCooldown }) {
50
+ const resolveRef = (ref) => {
51
+ const [p, ...mPts] = (ref ?? "").split("/");
52
+ return { provider: p || null, model: mPts.join("/") };
53
+ };
54
+ const nextHealthy = (skip) => {
55
+ for (const ref of chain) {
56
+ const { provider: p, model: m } = resolveRef(ref);
57
+ if (p !== skip && !isCooldown(p)) return { provider: p, model: m };
58
+ }
59
+ return null;
60
+ };
61
+ if (!chain || chain.length === 0) {
62
+ return resolveRef(primarySpec);
63
+ }
64
+ const primary = resolveRef(chain[0]);
65
+ if (chain.length > 1 && primary.provider && isCooldown(primary.provider)) {
66
+ const healthy = nextHealthy(null);
67
+ if (healthy) return healthy;
68
+ }
69
+ return primary;
70
+ }
71
+
72
+ // ── Discuss handler factory ───────────────────────────────────────────────────
73
+
74
+ export function createDiscussHandler({
75
+ api,
76
+ // The discuss store owns the pending proposal (discuss_state.pending_json).
77
+ discussStore,
78
+ sessions,
79
+ }) {
80
+ async function handleDiscuss(body) {
81
+ const flowId = typeof body.flowId === "string" ? body.flowId : "";
82
+ const session = typeof body.session === "string" ? body.session : "";
83
+ const agentId = typeof body.agentId === "string" ? body.agentId : "";
84
+ const modelOverride = typeof body.modelOverride === "string" && body.modelOverride.trim()
85
+ ? body.modelOverride.trim()
86
+ : null;
87
+ const text = typeof body.text === "string" ? body.text : "";
88
+ if (!flowId || !session || !agentId || !text) {
89
+ return { status: 400, body: { ok: false, code: "invalid_body", error: "flowId, session, agentId, text required" } };
90
+ }
91
+ const agentRuntime = api.runtime?.agent;
92
+ if (!agentRuntime?.runEmbeddedAgent) {
93
+ return { status: 503, body: { ok: false, code: "agent_runtime_unavailable", error: "agent runtime not bound" } };
94
+ }
95
+ const itemIdForDraft = typeof body.itemId === "string" ? body.itemId : null;
96
+ const systemPrompt = typeof body.systemPrompt === "string" ? body.systemPrompt : null;
97
+ const startedAt = Date.now();
98
+ try {
99
+ const workspaceDir = agentRuntime.resolveAgentWorkspaceDir(api.config, agentId)
100
+ ?? agentRuntime.resolveAgentWorkspaceDir(api.config);
101
+ const primarySpec = modelOverride ?? await sessions.resolveAgentEffectiveModelPrimary(api.config, agentId) ?? "";
102
+ const _agentCfg = !modelOverride && (api.config?.agents?.list ?? []).find((a) => a?.id === agentId);
103
+ const _modelCfg = _agentCfg ? (_agentCfg?.model ?? api.config?.agents?.defaults?.model) : null;
104
+ const chain = (_modelCfg && typeof _modelCfg === "object")
105
+ ? [_modelCfg.primary, ...(Array.isArray(_modelCfg.fallbacks) ? _modelCfg.fallbacks : [])]
106
+ .filter((r) => typeof r === "string" && r.length > 0)
107
+ : [];
108
+ const isCooldown = (p) => sessions.isProviderCooldown(agentId, p);
109
+ const { provider: activeProvider, model: activeModel } = selectDiscussProvider({
110
+ primarySpec, chain, isCooldown,
111
+ });
112
+ if (activeProvider !== primarySpec.split("/")[0] && activeProvider) {
113
+ api.logger.info(`manifold discuss: billing cooldown on ${primarySpec.split("/")[0]}, routing to ${activeProvider}/${activeModel}`);
114
+ }
115
+ const _runParams = {
116
+ // Adapter edge: the harness runtime names its own fields `sessionId` /
117
+ // `sessionKey`; core passes its single `session` as both.
118
+ sessionId: session, sessionKey: session, agentId, trigger: "manual", workspaceDir,
119
+ config: api.config, prompt: text, timeoutMs: 300_000,
120
+ ...(systemPrompt ? { extraSystemPrompt: systemPrompt } : {}),
121
+ };
122
+ let result;
123
+ try {
124
+ result = await agentRuntime.runEmbeddedAgent({
125
+ ..._runParams, provider: activeProvider || undefined, model: activeModel || undefined,
126
+ });
127
+ } catch (firstErr) {
128
+ const _errMsg = firstErr?.message ?? "";
129
+ const _isBilling = /billing error|insufficient|out of credits|out of extra usage|no available auth profile|all in cooldown/i.test(_errMsg);
130
+ if (_isBilling && chain.length > 1) {
131
+ const retry = selectDiscussProvider({ primarySpec, chain, isCooldown: (p) => p === activeProvider });
132
+ if (retry.provider && retry.provider !== activeProvider) {
133
+ api.logger.info(`manifold discuss: billing error on ${activeProvider}, retrying with ${retry.provider}/${retry.model}`);
134
+ result = await agentRuntime.runEmbeddedAgent({ ..._runParams, provider: retry.provider, model: retry.model || undefined });
135
+ } else {
136
+ throw firstErr;
137
+ }
138
+ } else {
139
+ throw firstErr;
140
+ }
141
+ }
142
+ // Layer 3: all providers returned empty (context-filter silent rejection)
143
+ {
144
+ const _hasText = (r) => !!(r?.meta?.finalAssistantVisibleText || r?.meta?.finalAssistantRawText
145
+ || (Array.isArray(r?.payloads) && r.payloads.some((p) => p?.text?.trim?.())));
146
+ if (!_hasText(result) && chain.length > 1) {
147
+ const _activeIdx = chain.findIndex((ref) => ref.split("/")[0] === activeProvider);
148
+ const _skipped = _activeIdx > 0 ? chain.slice(0, _activeIdx) : [];
149
+ for (const ref of _skipped) {
150
+ const [_p, ..._mPts] = ref.split("/");
151
+ api.logger.info(`manifold discuss: all providers returned empty (context-filter likely) — retrying with skipped provider ${_p}`);
152
+ try {
153
+ const _l3 = await agentRuntime.runEmbeddedAgent({ ..._runParams, provider: _p, model: _mPts.join("/") || undefined });
154
+ if (_hasText(_l3)) { result = _l3; break; }
155
+ } catch (_l3Err) {
156
+ api.logger.warn(`manifold discuss: layer-3 ${_p} retry failed: ${_l3Err?.message}`);
157
+ }
158
+ }
159
+ }
160
+ }
161
+ // Thread identity is recorded by core before the elev call (session
162
+ // roster); nothing is stamped here and the session id is never parsed.
163
+ let replyText = result?.meta?.finalAssistantVisibleText
164
+ ?? result?.meta?.finalAssistantRawText
165
+ ?? (Array.isArray(result?.payloads)
166
+ ? result.payloads.map((p) => p?.text?.trim?.() ?? "").filter(Boolean).join("\n")
167
+ : "");
168
+ if (!replyText) {
169
+ api.logger.warn(`manifold discuss (elev) [${flowId.slice(0, 8)}]: runEmbeddedAgent returned no assistant text`);
170
+ return { status: 500, body: { ok: false, code: "no_reply_text", error: "agent ran but no assistant text found" } };
171
+ }
172
+ // Core never scans harness transcripts for pipeline tool calls —
173
+ // pending fields and drafts arrive only via explicit tools.
174
+ let proposedDraft = null;
175
+ let proposedMeta = null;
176
+ const currentPending = await discussStore.readPending(flowId, itemIdForDraft);
177
+ if (currentPending) {
178
+ if (typeof currentPending.text === "string" && currentPending.text.length > 0) proposedDraft = currentPending.text;
179
+ if (currentPending.fields && Object.keys(currentPending.fields).length > 0) proposedMeta = currentPending.fields;
180
+ }
181
+ const durationMs = Date.now() - startedAt;
182
+ api.logger.info(
183
+ `manifold discuss (elev) [${flowId.slice(0, 8)}]: ok in ${durationMs}ms (reply=${replyText.length} chars, proposedDraft=${proposedDraft ? proposedDraft.length + " chars" : "none"}, proposedMeta=${proposedMeta ? JSON.stringify(Object.keys(proposedMeta)) : "none"})`
184
+ );
185
+ return { status: 200, body: { ok: true, reply: replyText, durationMs, editDraftUpdated: false, proposedDraft, proposedMeta } };
186
+ } catch (err) {
187
+ api.logger.warn(`manifold discuss (elev) handler error: ${err?.message ?? err}`);
188
+ return { status: 500, body: { ok: false, code: "internal", error: err?.message ?? String(err) } };
189
+ }
190
+ }
191
+
192
+ return { handleDiscuss };
193
+ }
@@ -0,0 +1,32 @@
1
+ // routes/operator-resume.js — in-process resume for budget-gate approvals.
2
+ //
3
+ // resumeFlowFromGate is the single implementation behind two callers: POST
4
+ // /pipeclaw/resume-from-gate (thin validating wrapper) and the budget
5
+ // decide route's in-process call. It re-requests the flow's own admission
6
+ // (released the moment it blocked, state-store.js's setWaiting hook) and
7
+ // resumes, leaving status:"queued" to the admission cycle when the pool is
8
+ // full.
9
+ import { admitAndSetRunning } from "../engine/child-resume-trigger.js";
10
+
11
+ export async function resumeFlowFromGate({
12
+ store, readStore, admissionQueueStore, runStore, executor, logger, api,
13
+ flowId, nodeId, decision,
14
+ }) {
15
+ const flow = (await store.get(flowId)) ?? (await readStore?.get(flowId)) ?? null;
16
+ if (!flow) return { ok: false, code: "flow_not_found" };
17
+ const result = await admitAndSetRunning({
18
+ flowId, expectedRevision: flow.revision, lastStep: flow.lastStep, stateJson: flow.stateJson ?? {},
19
+ parentInvocationId: flow.parentInvocationId, store, admissionQueueStore,
20
+ runStore, resume: executor.resume, logger, api,
21
+ });
22
+ if (!result.applied) return { ok: false, code: `setRunning failed: ${result.code}` };
23
+ if (!result.queued) {
24
+ setImmediate(() => {
25
+ executor.resume(flowId).catch((err) => {
26
+ logger.warn(`manifold resume-from-gate: runFlow [${flowId.slice(0, 8)}] error: ${err?.message ?? err}`);
27
+ });
28
+ });
29
+ }
30
+ logger.info(`manifold: resume-from-gate flow=${flowId.slice(0, 8)} node=${nodeId ?? "?"} decision=${decision ?? "?"}${result.queued ? " (queued for admission)" : ""}`);
31
+ return { ok: true, flowId, queued: result.queued };
32
+ }