@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
@@ -1,104 +0,0 @@
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
- }
package/routes/graphql.js DELETED
@@ -1,61 +0,0 @@
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
- }
package/routes/health.js DELETED
@@ -1,54 +0,0 @@
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
- }
@@ -1,193 +0,0 @@
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
- }
@@ -1,32 +0,0 @@
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
- }