@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/mcp/identity.js DELETED
@@ -1,94 +0,0 @@
1
- // identity.js — harness declared, agent and session stamped per call.
2
- //
3
- // One thing is declared, two things arrive with the work. The server is
4
- // CONSTRUCTED with the harness it serves (MANIFOLD_HARNESS env or ctor
5
- // base); the agent and session of each call are the calling harness's job
6
- // to stamp — via _meta.manifold on harnesses with request-params access,
7
- // else stamped manifold_agent/manifold_session args. Unstamped calls fail;
8
- // nothing defaults, ever.
9
-
10
- function isUsableLayer(v) {
11
- return (
12
- typeof v === "string" &&
13
- v.trim() !== "" &&
14
- !/^(unknown|instance:.*)$/i.test(v.trim())
15
- );
16
- }
17
-
18
- export function assertCleanTriple(id, who = "identity") {
19
- const bad = ["harness", "agent", "session"].filter((k) => !isUsableLayer(id?.[k]));
20
- if (bad.length > 0) {
21
- throw new Error(`manifold: refused ${who} (bad layers: ${bad.join(", ")}). Provide real harness/agent/session values.`);
22
- }
23
- return { harness: id.harness.trim(), agent: id.agent.trim(), session: id.session.trim() };
24
- }
25
-
26
- export function assertDeclaration(base) {
27
- const h = typeof base?.harness === "string" ? base.harness.trim() : "";
28
- if (h === "") {
29
- throw new Error(
30
- "manifold: identity declaration incomplete (missing: harness). " +
31
- "Declare the consumer at construction — MANIFOLD_HARNESS env, " +
32
- "X-Manifold-Harness header (HTTP), or startMcpServer({ base: { harness } }). " +
33
- "Agent and session are never declared: they arrive per call."
34
- );
35
- }
36
- if (/^(unknown|instance:.*)$/i.test(h)) {
37
- throw new Error(
38
- `manifold: refused declaration (reserved: harness). ` +
39
- `"${h}" cannot identify a consumer — declare the real harness name.`
40
- );
41
- }
42
- const pd = typeof base?.pipelinesDir === "string" ? base.pipelinesDir.trim() : "";
43
- return pd ? { harness: h, pipelinesDir: pd } : { harness: h };
44
- }
45
-
46
- export function declaredFromEnv(env = process.env) {
47
- return assertDeclaration({ harness: env.MANIFOLD_HARNESS });
48
- }
49
-
50
- export function resolveIdentity({ meta, args, base }) {
51
- const declared = assertDeclaration(base);
52
- const m = meta?.manifold ?? meta ?? null;
53
- const am = args?._meta?.manifold ?? null;
54
- const usable = (v) => (isUsableLayer(v) ? String(v).trim() : null);
55
- const mAgent = usable(m?.agent), mSession = usable(m?.session);
56
- const amAgent = usable(am?.agent), amSession = usable(am?.session);
57
- const aAgent = usable(args?.manifold_agent), aSession = usable(args?.manifold_session);
58
- const pair = (mAgent && mSession)
59
- ? { agent: mAgent, session: mSession, source: "meta" }
60
- : (amAgent && amSession)
61
- ? { agent: amAgent, session: amSession, source: "args-meta" }
62
- : (aAgent && aSession)
63
- ? { agent: aAgent, session: aSession, source: "args" }
64
- : null;
65
- if (!pair) {
66
- if ((mAgent || amAgent || aAgent) && (mSession || amSession || aSession)) {
67
- throw new Error(
68
- "manifold: refused caller identity (halves in different channels — pairs never splice). " +
69
- "Stamp a whole agent+session in one channel: _meta.manifold or manifold_agent/manifold_session args."
70
- );
71
- }
72
- const bad = [];
73
- if (!mAgent && !amAgent && !aAgent) bad.push("agent");
74
- if (!mSession && !amSession && !aSession) bad.push("session");
75
- throw new Error(
76
- `manifold: refused caller identity (unresolved ${bad.join(" and ")}). ` +
77
- "The calling harness must stamp agent and session on each call. " +
78
- "Unidentified callers fail; they are never given default keys."
79
- );
80
- }
81
- const out = {
82
- harness: declared.harness,
83
- agent: pair.agent,
84
- session: pair.session,
85
- source: { harness: "declared", agent: pair.source, session: pair.source },
86
- };
87
- if (declared.pipelinesDir) out.pipelinesDir = declared.pipelinesDir;
88
- return out;
89
- }
90
-
91
- export function identitySessionKey(id) {
92
- const clean = assertCleanTriple(id, "session key");
93
- return `${clean.harness}:${clean.agent}:${clean.session}`;
94
- }
package/mcp/stdio.js DELETED
@@ -1,80 +0,0 @@
1
- // stdio.js — stdio MCP server exposing the pipeline tools. stdout is the
2
- // JSON-RPC channel: every log line goes to stderr, and nothing else may be
3
- // written to stdout.
4
- //
5
- // Request `_meta` surfaces on the handler's second argument (`extra._meta`,
6
- // the original request's params._meta — see the SDK's RequestHandlerExtra).
7
- // `extra._meta.manifold` is the trusted companion-plugin channel; models
8
- // cannot forge it because the plugin overwrites it unconditionally.
9
-
10
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
11
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
12
- import * as z from "zod/v4-mini";
13
- import { TOOL_DEFS, createManifoldToolHandlers } from "./tools.js";
14
- import { resolveIdentity, identitySessionKey, assertDeclaration } from "./identity.js";
15
-
16
- function fieldFromJson(schema) {
17
- if (!schema || typeof schema !== "object") return z.unknown();
18
- if (schema.enum && Array.isArray(schema.enum)) return z.enum(schema.enum);
19
- if (schema.type === "string") return z.string();
20
- if (schema.type === "boolean") return z.boolean();
21
- if (schema.type === "integer") return z.number();
22
- if (schema.type === "array") return z.array(fieldFromJson(schema.items));
23
- if (schema.type === "object") return z.object(shapeFromJson(schema));
24
- return z.unknown();
25
- }
26
-
27
- function shapeFromJson(schema) {
28
- const shape = {};
29
- const required = new Set(schema.required ?? []);
30
- for (const [key, sub] of Object.entries(schema.properties ?? {})) {
31
- const field = fieldFromJson(sub);
32
- shape[key] = required.has(key) ? field : z.optional(field);
33
- }
34
- shape.manifold_agent = z.optional(z.string());
35
- shape.manifold_session = z.optional(z.string());
36
- shape._meta = z.optional(z.unknown());
37
- return shape;
38
- }
39
-
40
- export function toolErrorResult(err) {
41
- const message = `manifold: tool failed: ${String(err?.message ?? err)}`;
42
- if (process.env.MANIFOLD_MCP_DEBUG) {
43
- console.error(message);
44
- }
45
- return {
46
- content: [{ type: "text", text: JSON.stringify({ error: message }) }],
47
- isError: true,
48
- };
49
- }
50
-
51
- export async function startMcpServer({ ops, base, logger }) {
52
- // Identity is refused, never defaulted, at both layers: an undeclared
53
- // server will not start, and an unstamped, unusable, or mismatched call
54
- // will not run. Harness comes from the ctor arg or MANIFOLD_HARNESS env.
55
- const declared = assertDeclaration(base ?? { harness: process.env.MANIFOLD_HARNESS, pipelinesDir: process.env.MANIFOLD_PIPELINES_DIR });
56
- const { handle } = createManifoldToolHandlers(ops);
57
- const server = new McpServer({ name: "manifold", version: "0.1.0" });
58
-
59
- for (const def of TOOL_DEFS) {
60
- server.registerTool(
61
- def.name,
62
- { description: def.description, inputSchema: z.object(shapeFromJson(def.inputSchema)) },
63
- async (args, extra) => {
64
- try {
65
- const identity = resolveIdentity({ meta: extra?._meta, args, base: declared });
66
- logger?.info?.(`manifold: ${def.name} from ${identitySessionKey(identity)}`);
67
- const res = await handle(def.name, args, identity);
68
- return { content: res.content };
69
- } catch (err) {
70
- return toolErrorResult(err);
71
- }
72
- }
73
- );
74
- }
75
-
76
- const transport = new StdioServerTransport();
77
- await server.connect(transport);
78
- logger?.info?.("manifold: MCP server connected on stdio");
79
- return server;
80
- }
package/mcp/tools.js DELETED
@@ -1,245 +0,0 @@
1
- // tools.js — agent-facing pipeline tools: manifold_start / _status /
2
- // _runs / _approve / _cancel.
3
- //
4
- // `createManifoldToolHandlers(ops)` returns static TOOL_DEFS (name,
5
- // description, JSON-schema inputSchema) plus a `handle(name, args,
6
- // identity)` dispatcher. Ops are injected by the host — stdio/HTTP servers
7
- // pass the real executor/run-store wiring, tests pass stubs:
8
- //
9
- // startRun({ pipelineId, args, triggeredBy }) -> flow record
10
- // runStatus({ flowId }) -> flow record | null
11
- // listRuns({ pipelineId, status, limit }) -> flow record[]
12
- // approveGate({ flowId, itemId, decision, text }) -> { ok, ... }
13
- // cancelFlow({ flowId, reason }) -> { cancelled, ... }
14
- // deliverResult({ session, runId, agent, kind, payload }) -> { ok }
15
- // logger -> { info, warn, error } (optional)
16
- //
17
- // The caller identity is the resolved `identity` — never a tool param —
18
- // so agents cannot start runs or approve gates under another agent's name.
19
-
20
- import { identitySessionKey, assertCleanTriple } from "./identity.js";
21
-
22
- function ok(text, details) {
23
- return { content: [{ type: "text", text }], details };
24
- }
25
-
26
- function err(text, reason, extra = {}) {
27
- return { content: [{ type: "text", text }], details: { status: "rejected", reason, ...extra } };
28
- }
29
-
30
- export const TOOL_DEFS = [
31
- {
32
- name: "manifold_start",
33
- description:
34
- "Start a new run of a pipeline. Returns the flow record (flowId, status, revision). " +
35
- "The caller is attributed by request identity, never by a tool param.",
36
- inputSchema: {
37
- type: "object",
38
- additionalProperties: false,
39
- required: ["pipelineId"],
40
- properties: {
41
- pipelineId: { type: "string", description: "Pipeline id (workspace/.pipelines/ definition)." },
42
- args: { type: "object", description: "JSON args merged into the initial state." },
43
- },
44
- },
45
- },
46
- {
47
- name: "manifold_status",
48
- description:
49
- "Read one flow's status: flowId, pipelineId, status, lastStep, revision. " +
50
- "Read-only; a missing flow is refused as not_found, never defaulted.",
51
- inputSchema: {
52
- type: "object",
53
- additionalProperties: false,
54
- required: ["flowId"],
55
- properties: {
56
- flowId: { type: "string", description: "Flow id returned by manifold_start." },
57
- },
58
- },
59
- },
60
- {
61
- name: "manifold_runs",
62
- description:
63
- "List recent flow runs, optionally filtered by pipeline and status. Read-only.",
64
- inputSchema: {
65
- type: "object",
66
- additionalProperties: false,
67
- properties: {
68
- pipelineId: { type: "string", description: "Only runs of this pipeline." },
69
- status: { type: "string", description: "Only runs in this status." },
70
- limit: { type: "integer", description: "Max rows (default 20)." },
71
- },
72
- },
73
- },
74
- {
75
- name: "manifold_approve",
76
- description:
77
- "Record a human-gate decision: approve, reject, or edit (with text) one pending item. " +
78
- "The decision is attributed to the caller — speaking for another agent is refused.",
79
- inputSchema: {
80
- type: "object",
81
- additionalProperties: false,
82
- required: ["flowId", "itemId", "decision"],
83
- properties: {
84
- flowId: { type: "string", description: "Blocked flow id." },
85
- itemId: { type: "string", description: "Pending gate item id." },
86
- decision: { type: "string", enum: ["approve", "reject", "edit"] },
87
- text: { type: "string", description: "Edited text (only with decision=edit)." },
88
- },
89
- },
90
- },
91
- {
92
- name: "manifold_cancel",
93
- description:
94
- "Cancel a flow run. Terminal flows and missing flows are refused, never silently ok.",
95
- inputSchema: {
96
- type: "object",
97
- additionalProperties: false,
98
- required: ["flowId"],
99
- properties: {
100
- flowId: { type: "string", description: "Flow id to cancel." },
101
- reason: { type: "string", description: "Why the run is cancelled (audit trail)." },
102
- },
103
- },
104
- },
105
- {
106
- name: "manifold_deliver_result",
107
- description:
108
- "Deliver a structured tool result for the calling session: the dispatch " +
109
- "waiting on this session's turn picks it up instead of waiting out the " +
110
- "agent run. The session is identified from the caller's stamped identity, " +
111
- "never from a parameter — a result cannot be filed under another session. " +
112
- "Latest write wins per session; the dispatch consumes and clears it.",
113
- inputSchema: {
114
- type: "object",
115
- additionalProperties: false,
116
- required: ["payload"],
117
- properties: {
118
- payload: { description: "JSON result payload the node's apply() receives as output.toolResult.payload." },
119
- kind: { type: "string", description: "Result kind (e.g. score, draft) — routed opaquely, never interpreted here." },
120
- runId: { type: "string", description: "Agent run id, when known (traceability only)." },
121
- },
122
- },
123
- },
124
- ];
125
-
126
- export function createManifoldToolHandlers(ops = {}) {
127
- const { startRun, runStatus, listRuns, approveGate, cancelFlow, deliverResult, logger } = ops;
128
-
129
- function need(fn, name) {
130
- if (typeof fn !== "function") throw new Error(`manifold: op ${name} is not wired (no ${name} in injected ops)`);
131
- return fn;
132
- }
133
-
134
- const handlers = {
135
- async manifold_start(args, identity) {
136
- const pipelineId = args?.pipelineId;
137
- if (typeof pipelineId !== "string" || pipelineId.trim() === "") {
138
- return err("manifold_start: pipelineId is required", "rejected");
139
- }
140
- try {
141
- const record = await need(startRun, "startRun")({
142
- pipelineId: pipelineId.trim(),
143
- args: args?.args ?? {},
144
- triggeredBy: { kind: "mcp", label: `MCP · ${identitySessionKey(identity)}`, ts: Date.now() },
145
- pipelinesDir: identity?.pipelinesDir ?? null,
146
- });
147
- logger?.info?.(`manifold: ${identitySessionKey(identity)} started ${record.flowId} (${record.pipelineId ?? pipelineId})`);
148
- return ok(JSON.stringify(record), { status: "ok", flowId: record.flowId });
149
- } catch (e) {
150
- return err(`manifold_start failed: ${e?.message ?? e}`, "error");
151
- }
152
- },
153
-
154
- async manifold_status(args, identity) {
155
- const flowId = args?.flowId;
156
- if (typeof flowId !== "string" || flowId.trim() === "") {
157
- return err("manifold_status: flowId is required", "rejected");
158
- }
159
- try {
160
- const flow = await need(runStatus, "runStatus")({ flowId: flowId.trim() });
161
- if (!flow) return err(`manifold_status: not found: ${flowId}`, "not_found", { flowId });
162
- return ok(JSON.stringify(flow), { status: "ok", flowId: flow.flowId ?? flowId });
163
- } catch (e) {
164
- return err(`manifold_status failed: ${e?.message ?? e}`, "error");
165
- }
166
- },
167
-
168
- async manifold_runs(args, identity) {
169
- void identity;
170
- try {
171
- const rows = await need(listRuns, "listRuns")({
172
- pipelineId: args?.pipelineId ?? null,
173
- status: args?.status ?? null,
174
- limit: args?.limit ?? 20,
175
- });
176
- return ok(JSON.stringify(rows), { status: "ok", count: Array.isArray(rows) ? rows.length : 0 });
177
- } catch (e) {
178
- return err(`manifold_runs failed: ${e?.message ?? e}`, "error");
179
- }
180
- },
181
-
182
- async manifold_approve(args, identity) {
183
- const { flowId, itemId, decision } = args ?? {};
184
- if (typeof flowId !== "string" || !flowId) return err("manifold_approve: flowId is required", "rejected");
185
- if (typeof itemId !== "string" || !itemId) return err("manifold_approve: itemId is required", "rejected");
186
- if (!["approve", "reject", "edit"].includes(decision)) {
187
- return err("manifold_approve: decision must be approve|reject|edit", "rejected");
188
- }
189
- if (decision === "edit" && (typeof args.text !== "string" || args.text.trim() === "")) {
190
- return err("manifold_approve: decision=edit requires text", "rejected");
191
- }
192
- try {
193
- const r = await need(approveGate, "approveGate")({
194
- flowId, itemId, decision,
195
- text: args?.text ?? null,
196
- actor: identity.agent,
197
- });
198
- if (!r?.ok) return err(`manifold_approve refused: ${r?.code ?? "unknown"}`, r?.code ?? "rejected", { flowId, itemId });
199
- return ok(JSON.stringify(r), { status: "ok", flowId, itemId, decision });
200
- } catch (e) {
201
- return err(`manifold_approve failed: ${e?.message ?? e}`, "error");
202
- }
203
- },
204
-
205
- async manifold_cancel(args, identity) {
206
- const flowId = typeof args?.flowId === "string" ? args.flowId : null;
207
- if (!flowId) return err("manifold_cancel: flowId is required", "rejected");
208
- try {
209
- const r = await need(cancelFlow, "cancelFlow")({ flowId, reason: args?.reason ?? null });
210
- if (!r?.cancelled) return err(`manifold_cancel refused: ${r?.reason ?? "unknown"}`, "rejected", { flowId });
211
- logger?.info?.(`manifold: ${identitySessionKey(identity)} cancelled ${flowId}`);
212
- return ok(JSON.stringify(r), { status: "ok", flowId });
213
- } catch (e) {
214
- return err(`manifold_cancel failed: ${e?.message ?? e}`, "error", { flowId });
215
- }
216
- },
217
-
218
- async manifold_deliver_result(args, identity) {
219
- if (args?.payload === undefined) {
220
- return err("manifold_deliver_result: payload is required", "rejected");
221
- }
222
- try {
223
- await need(deliverResult, "deliverResult")({
224
- session: identity.session,
225
- runId: typeof args?.runId === "string" ? args.runId : null,
226
- agentId: identity.agent,
227
- kind: typeof args?.kind === "string" ? args.kind : null,
228
- payload: args.payload,
229
- });
230
- return ok("delivered", { status: "ok", session: identity.session });
231
- } catch (e) {
232
- return err(`manifold_deliver_result failed: ${e?.message ?? e}`, "error");
233
- }
234
- },
235
- };
236
-
237
- async function handle(name, args, identity) {
238
- assertCleanTriple(identity, `caller identity for ${name}`);
239
- const fn = handlers[name];
240
- if (!fn) return err(`unknown tool: ${name}`, "unknown_tool");
241
- return fn(args, identity);
242
- }
243
-
244
- return { TOOL_DEFS, handle };
245
- }
package/mcp/wire-ops.js DELETED
@@ -1,178 +0,0 @@
1
- // wire-ops.js — real core ops for the MCP servers.
2
- //
3
- // createRealOps builds the six tool ops from live core pieces: the
4
- // run-store for status/runs/cancel, the executor + gate-resolver for
5
- // start/approve, and the tool-results store for deliver_result.
6
- // Everything is store-backed — no stubs, no fakes.
7
- //
8
- // Standalone note: `serve --mcp` runs outside the gateway, so there is no
9
- // agent runtime. Code/manual/subflow nodes drive fine; an agent-node
10
- // dispatch refuses loudly at dispatch time (the injected runTurn throws),
11
- // naming the missing runtime instead of hanging. Status/runs/cancel always
12
- // work — they are pure store reads/writes.
13
-
14
- import { createRunStore } from "../state/run-store.js";
15
- import { createStateStore } from "../state/state-store.js";
16
- import { getNodeExecutionsStore } from "../state/node-executions.js";
17
- import { createFailureStore } from "../state/failure-store.js";
18
- import { writePendingResult } from "../state/tool-handoff.js";
19
- import { createAdmissionQueueStore } from "../state/admission-queue-store.js";
20
- import { createNodeHealthStore } from "../state/node-health-store.js";
21
- import { createSessionIndex } from "../state/session-index.js";
22
- import { createExecutor } from "../engine/executor.js";
23
- import { createGateResolver } from "../gates/gate-resolver.js";
24
- import { loadPipelines } from "../engine/loader.js";
25
- import { createEmitter } from "../events/emit.js";
26
- import { getGlobalConcurrencyLimit } from "../engine/global-concurrency.js";
27
- import { resolveStorePaths } from "../state/paths.js";
28
-
29
- export async function createRealOps({ dbPath = null, pipelinesDir = null, config = null, logger = null } = {}) {
30
- const paths = resolveStorePaths();
31
- const runtimeDb = dbPath ?? paths.runtimeDb;
32
- const pipesDir = pipelinesDir ?? paths.pipelinesDir;
33
-
34
- const runStore = createRunStore({ logger, dbPath: runtimeDb });
35
- const nodeExecutionsStore = getNodeExecutionsStore(runtimeDb);
36
- const failureStore = createFailureStore({ logger, nodeExecutionsStore });
37
- const admissionQueueStore = createAdmissionQueueStore({ logger, getLimit: getGlobalConcurrencyLimit });
38
- const nodeHealthStore = await createNodeHealthStore({ logger }).catch(() => null);
39
- const sessionIndex = await createSessionIndex({ logger }).catch(() => null);
40
-
41
- const api = {
42
- logger: logger ?? console,
43
- runtime: {
44
- subagent: {
45
- run: async () => {
46
- throw new Error("manifold standalone serve: agent dispatch needs a gateway subagent runtime");
47
- },
48
- },
49
- },
50
- };
51
- // Pipelines cache keyed by dir — the default dir loads at startup;
52
- // per-connection dirs (X-Manifold-Pipelines-Dir) load lazily on first use.
53
- const pipelinesCache = new Map();
54
- const loadPipelinesForDir = async (dir) => {
55
- const key = dir ?? pipesDir;
56
- if (pipelinesCache.has(key)) return pipelinesCache.get(key);
57
- const loaded = await loadPipelines(key, logger);
58
- pipelinesCache.set(key, loaded);
59
- return loaded;
60
- };
61
- const pipelinesRef = { value: await loadPipelinesForDir(pipesDir).catch((err) => {
62
- logger?.warn?.(`manifold: pipelines failed to load (${err?.message ?? err}); manifold_start will refuse unknown pipelines`);
63
- return new Map();
64
- }) };
65
- const ensurePipelinesLoaded = async (dir = null) => {
66
- const key = dir ?? pipesDir;
67
- if (!pipelinesCache.has(key)) {
68
- const loaded = await loadPipelines(key, logger).catch((err) => {
69
- logger?.warn?.(`manifold: pipelines failed to load from ${key} (${err?.message ?? err})`);
70
- return new Map();
71
- });
72
- pipelinesCache.set(key, loaded);
73
- }
74
- if (key === pipesDir) pipelinesRef.value = pipelinesCache.get(key);
75
- return pipelinesCache.get(key);
76
- };
77
-
78
- const store = createStateStore(api, "mcp:standalone", {
79
- runStore,
80
- nodeExecutionsStore,
81
- resumeParentRef: {
82
- resume: async () => {
83
- throw new Error("manifold standalone serve: no parent-resume runtime");
84
- },
85
- },
86
- pipelinesRef,
87
- failureStore,
88
- admissionQueueStore,
89
- logger,
90
- });
91
- const emit = createEmitter({ getBroadcast: () => null, logger });
92
-
93
- const executor = createExecutor({
94
- api,
95
- config: config ?? {},
96
- approvalQueue: null,
97
- pipelinesDir: pipesDir,
98
- store,
99
- pipelinesRef,
100
- ensurePipelinesLoaded,
101
- logger: logger ?? console,
102
- // No agent runtime outside the gateway: an agent-node dispatch refuses
103
- // here, naming the missing runtime instead of hanging.
104
- runTurn: async () => {
105
- throw new Error("manifold standalone serve: agent dispatch needs a gateway agent runtime");
106
- },
107
- failureStore,
108
- nodeHealthStore,
109
- notifyFlowEnteredWaiting: async () => {},
110
- sessionIndex,
111
- nodeExecutionsStore,
112
- runStore,
113
- admissionQueueStore,
114
- emit: emit.emit,
115
- });
116
-
117
- const gateResolver = createGateResolver({
118
- api,
119
- store,
120
- executor,
121
- getBroadcast: () => null,
122
- readStore: runStore,
123
- runStore,
124
- pipelineLookup: (id, dir = null) => {
125
- const cache = pipelinesCache.get(dir ?? pipesDir);
126
- return (cache ?? pipelinesRef.value)?.get(id) ?? null;
127
- },
128
- nodeExecutionsStore,
129
- admissionQueueStore,
130
- });
131
-
132
- return {
133
- async startRun({ pipelineId, args, triggeredBy, pipelinesDir = null }) {
134
- const dir = pipelinesDir || pipesDir;
135
- const loaded = await ensurePipelinesLoaded(dir);
136
- if (loaded && !pipelinesRef.value?.has(pipelineId)) pipelinesRef.value = loaded;
137
- const record = await executor.start(pipelineId, args ?? {}, triggeredBy ?? { kind: "mcp", ts: Date.now() });
138
- setImmediate(() => {
139
- executor.runFlow(record.flowId, "fresh").catch((err) => {
140
- logger?.warn?.(`manifold: detached runFlow ${record.flowId} failed: ${err?.message ?? err}`);
141
- });
142
- });
143
- return store.get(record.flowId).then((f) => f ?? record);
144
- },
145
- async runStatus({ flowId }) {
146
- return runStore.get(flowId);
147
- },
148
- async listRuns({ pipelineId, status, limit }) {
149
- const q = {};
150
- if (pipelineId) q.pipelineId = pipelineId;
151
- if (status) q.status = status;
152
- q.limit = Number.isInteger(limit) && limit > 0 ? limit : 20;
153
- try {
154
- return await runStore.listRunsPage(q);
155
- } catch {
156
- const all = await runStore.list();
157
- return all.slice(0, q.limit);
158
- }
159
- },
160
- async approveGate({ flowId, itemId, decision, text, actor }) {
161
- return gateResolver.recordItemDecision({
162
- flowId, itemId, decision,
163
- source: "mcp",
164
- editedText: text ?? null,
165
- reason: actor ? `mcp approval by ${actor}` : "mcp approval",
166
- awaitCompletion: false,
167
- });
168
- },
169
- async cancelFlow({ flowId, reason }) {
170
- return runStore.cancelFlow(flowId, reason);
171
- },
172
- async deliverResult({ session, runId, agentId, kind, payload }) {
173
- await writePendingResult({ session, runId, agentId, kind, payload });
174
- return { ok: true, session };
175
- },
176
- logger,
177
- };
178
- }
@@ -1,57 +0,0 @@
1
- // routes/bearer-auth.js — winch-style bearer guard for manifold HTTP routes.
2
- //
3
- // One shared secret, no pairing, no device tokens: `Authorization: Bearer
4
- // <MANIFOLD_BEARER>` — the same env the MCP HTTP server requires before it
5
- // starts. Timing-safe compare; TLS terminates in front (reverse proxy or
6
- // ingress). An unset/empty secret fails every check (fail-closed); the
7
- // first rejection logs once so a missing env is loud instead of mysterious.
8
- //
9
- // The harness declares itself per call with X-Manifold-Harness where
10
- // identity matters (MCP sessions); these operator routes authenticate the
11
- // caller, not the harness.
12
- import { timingSafeEqual } from "node:crypto";
13
-
14
- let warnedNoSecret = false;
15
-
16
- function tokensEqual(a, b) {
17
- const ab = Buffer.from(a, "utf8");
18
- const bb = Buffer.from(b, "utf8");
19
- if (ab.length !== bb.length) {
20
- timingSafeEqual(ab, ab); // burn the cycles to keep timing flat
21
- return false;
22
- }
23
- return timingSafeEqual(ab, bb);
24
- }
25
-
26
- /**
27
- * Returns {ok: true} or {ok: false, reason}. Reasons: "no-bearer"
28
- * (missing/non-Bearer scheme), "empty-token", "no-secret" (MANIFOLD_BEARER
29
- * unset — fail-closed), "no-match".
30
- */
31
- export function authorizeBearerRequest(req, { logger = null, secret: secretOverride = null } = {}) {
32
- const raw = req?.headers?.authorization ?? "";
33
- if (typeof raw !== "string" || !raw.toLowerCase().startsWith("bearer ")) {
34
- return { ok: false, reason: "no-bearer" };
35
- }
36
- const token = raw.slice(7).trim();
37
- if (!token) return { ok: false, reason: "empty-token" };
38
- // A caller may pin its own secret (the telemetry ingest token the core
39
- // mints for its adapter) without touching the operator-wide bearer.
40
- const secret = secretOverride ?? process.env.MANIFOLD_BEARER ?? "";
41
- if (!secret) {
42
- if (!warnedNoSecret) {
43
- warnedNoSecret = true;
44
- try { logger?.warn?.("manifold: MANIFOLD_BEARER is unset — every bearer check fails closed"); } catch {}
45
- }
46
- return { ok: false, reason: "no-secret" };
47
- }
48
- if (!tokensEqual(token, secret)) return { ok: false, reason: "no-match" };
49
- return { ok: true };
50
- }
51
-
52
- /** Standard 401 for a bearer-rejected request. */
53
- export function sendUnauthorized(res, reason) {
54
- res.statusCode = 401;
55
- res.setHeader("Content-Type", "application/json");
56
- res.end(JSON.stringify({ error: "unauthorized", reason: reason ?? "unauthorized" }));
57
- }