factoryhub 0.0.0-stage → 0.1.1

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 (156) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +16 -0
  3. package/README.md +195 -2
  4. package/factories/README.md +17 -0
  5. package/factories/client-file-readiness/README.md +3 -0
  6. package/factories/client-file-readiness/agents/analyst/agent.md +10 -0
  7. package/factories/client-file-readiness/agents/reviewer/agent.md +10 -0
  8. package/factories/client-file-readiness/agents/writer/agent.md +11 -0
  9. package/factories/client-file-readiness/factory.yaml +12 -0
  10. package/factories/client-file-readiness/flow.yaml +56 -0
  11. package/factories/competitor-teardown/README.md +3 -0
  12. package/factories/competitor-teardown/agents/analyst/agent.md +10 -0
  13. package/factories/competitor-teardown/agents/researcher/agent.md +11 -0
  14. package/factories/competitor-teardown/agents/reviewer/agent.md +10 -0
  15. package/factories/competitor-teardown/agents/writer/agent.md +11 -0
  16. package/factories/competitor-teardown/factory.yaml +11 -0
  17. package/factories/competitor-teardown/flow.yaml +75 -0
  18. package/factories/homepage-audit/README.md +3 -0
  19. package/factories/homepage-audit/agents/analyst/agent.md +10 -0
  20. package/factories/homepage-audit/agents/researcher/agent.md +11 -0
  21. package/factories/homepage-audit/agents/reviewer/agent.md +10 -0
  22. package/factories/homepage-audit/agents/writer/agent.md +11 -0
  23. package/factories/homepage-audit/factory.yaml +11 -0
  24. package/factories/homepage-audit/flow.yaml +77 -0
  25. package/factories/inbox-triage/README.md +3 -0
  26. package/factories/inbox-triage/agents/analyst/agent.md +10 -0
  27. package/factories/inbox-triage/agents/reviewer/agent.md +10 -0
  28. package/factories/inbox-triage/agents/writer/agent.md +11 -0
  29. package/factories/inbox-triage/factory.yaml +11 -0
  30. package/factories/inbox-triage/flow.yaml +57 -0
  31. package/factories/index.json +587 -0
  32. package/factories/launch-kit/README.md +3 -0
  33. package/factories/launch-kit/agents/reviewer/agent.md +10 -0
  34. package/factories/launch-kit/agents/strategist/agent.md +10 -0
  35. package/factories/launch-kit/agents/writer/agent.md +11 -0
  36. package/factories/launch-kit/factory.yaml +12 -0
  37. package/factories/launch-kit/flow.yaml +75 -0
  38. package/factories/meeting-to-actions/CHANGELOG.md +7 -0
  39. package/factories/meeting-to-actions/README.md +15 -0
  40. package/factories/meeting-to-actions/agents/analyst/agent.md +10 -0
  41. package/factories/meeting-to-actions/agents/reviewer/agent.md +10 -0
  42. package/factories/meeting-to-actions/agents/writer/agent.md +11 -0
  43. package/factories/meeting-to-actions/factory.yaml +11 -0
  44. package/factories/meeting-to-actions/flow.yaml +53 -0
  45. package/factories/meeting-to-actions/mindburn.requirements.yaml +8 -0
  46. package/factories/meeting-to-actions/mindburn.tests.yaml +16 -0
  47. package/factories/newsletter-note/README.md +11 -0
  48. package/factories/newsletter-note/agents/reviewer/agent.md +10 -0
  49. package/factories/newsletter-note/agents/writer/agent.md +11 -0
  50. package/factories/newsletter-note/factory.yaml +12 -0
  51. package/factories/newsletter-note/flow.yaml +45 -0
  52. package/factories/newsletter-note/mindburn.tests.yaml +80 -0
  53. package/factories/outreach-pack/README.md +3 -0
  54. package/factories/outreach-pack/agents/reviewer/agent.md +5 -0
  55. package/factories/outreach-pack/agents/writer/agent.md +5 -0
  56. package/factories/outreach-pack/factory.yaml +9 -0
  57. package/factories/outreach-pack/flow.yaml +42 -0
  58. package/factories/prospect-brief/README.md +3 -0
  59. package/factories/prospect-brief/agents/researcher/agent.md +11 -0
  60. package/factories/prospect-brief/agents/reviewer/agent.md +10 -0
  61. package/factories/prospect-brief/agents/strategist/agent.md +10 -0
  62. package/factories/prospect-brief/agents/writer/agent.md +11 -0
  63. package/factories/prospect-brief/factory.yaml +11 -0
  64. package/factories/prospect-brief/flow.yaml +79 -0
  65. package/factories/release-desk/README.md +13 -0
  66. package/factories/release-desk/agents/editor/agent.md +10 -0
  67. package/factories/release-desk/agents/reviewer/agent.md +10 -0
  68. package/factories/release-desk/factory.yaml +13 -0
  69. package/factories/release-desk/flow.yaml +67 -0
  70. package/factories/release-desk/mindburn.tests.yaml +163 -0
  71. package/factories/short-video-cut/README.md +11 -0
  72. package/factories/short-video-cut/agents/reviewer/agent.md +10 -0
  73. package/factories/short-video-cut/agents/writer/agent.md +11 -0
  74. package/factories/short-video-cut/factory.yaml +13 -0
  75. package/factories/short-video-cut/flow.yaml +46 -0
  76. package/factories/short-video-cut/mindburn.tests.yaml +80 -0
  77. package/factories/video-facts/README.md +11 -0
  78. package/factories/video-facts/agents/analyst/agent.md +10 -0
  79. package/factories/video-facts/agents/reviewer/agent.md +10 -0
  80. package/factories/video-facts/factory.yaml +13 -0
  81. package/factories/video-facts/flow.yaml +39 -0
  82. package/factories/video-facts/mindburn.tests.yaml +34 -0
  83. package/factories/video-to-posts/README.md +35 -0
  84. package/factories/video-to-posts/agents/analyst/agent.md +10 -0
  85. package/factories/video-to-posts/agents/reviewer/agent.md +10 -0
  86. package/factories/video-to-posts/agents/writer/agent.md +11 -0
  87. package/factories/video-to-posts/factory.yaml +12 -0
  88. package/factories/video-to-posts/flow.yaml +62 -0
  89. package/factories/video-to-posts/mindburn.tests.yaml +34 -0
  90. package/factories/week-of-posts/README.md +11 -0
  91. package/factories/week-of-posts/agents/reviewer/agent.md +10 -0
  92. package/factories/week-of-posts/agents/writer/agent.md +11 -0
  93. package/factories/week-of-posts/factory.yaml +12 -0
  94. package/factories/week-of-posts/flow.yaml +46 -0
  95. package/factories/week-of-posts/mindburn.tests.yaml +80 -0
  96. package/package.json +92 -4
  97. package/packages/cli/bin/factoryhub.mjs +8 -0
  98. package/packages/cli/package.json +29 -0
  99. package/packages/cli/src/args.mjs +47 -0
  100. package/packages/cli/src/commands/export.mjs +54 -0
  101. package/packages/cli/src/commands/get.mjs +37 -0
  102. package/packages/cli/src/commands/inspect.mjs +65 -0
  103. package/packages/cli/src/commands/list.mjs +24 -0
  104. package/packages/cli/src/commands/login.mjs +161 -0
  105. package/packages/cli/src/commands/logout.mjs +43 -0
  106. package/packages/cli/src/commands/mcp.mjs +25 -0
  107. package/packages/cli/src/commands/new.mjs +147 -0
  108. package/packages/cli/src/commands/pack.mjs +96 -0
  109. package/packages/cli/src/commands/publish.mjs +62 -0
  110. package/packages/cli/src/commands/pull.mjs +59 -0
  111. package/packages/cli/src/commands/push.mjs +115 -0
  112. package/packages/cli/src/commands/resume.mjs +66 -0
  113. package/packages/cli/src/commands/run.mjs +352 -0
  114. package/packages/cli/src/commands/runs.mjs +52 -0
  115. package/packages/cli/src/commands/search.mjs +30 -0
  116. package/packages/cli/src/commands/validate.mjs +79 -0
  117. package/packages/cli/src/commands/whoami.mjs +34 -0
  118. package/packages/cli/src/hosted.mjs +159 -0
  119. package/packages/cli/src/main.mjs +134 -0
  120. package/packages/cli/src/tool-sources.mjs +272 -0
  121. package/packages/cli/src/util.mjs +58 -0
  122. package/packages/engine/lib/catalog.mjs +50 -0
  123. package/packages/engine/lib/credentials.mjs +121 -0
  124. package/packages/engine/lib/hosted.mjs +119 -0
  125. package/packages/engine/lib/hub.mjs +423 -0
  126. package/packages/engine/lib/nango.mjs +157 -0
  127. package/packages/engine/lib/node.mjs +242 -0
  128. package/packages/engine/lib/providers.mjs +57 -0
  129. package/packages/engine/lib/run.mjs +192 -0
  130. package/packages/engine/lib/skill.mjs +229 -0
  131. package/packages/engine/lib/text.mjs +5 -0
  132. package/packages/engine/package.json +45 -0
  133. package/packages/engine/src/author-tests.mjs +78 -0
  134. package/packages/engine/src/compose.mjs +150 -0
  135. package/packages/engine/src/cost.mjs +41 -0
  136. package/packages/engine/src/diagnostics.mjs +21 -0
  137. package/packages/engine/src/factory-engine.mjs +2109 -0
  138. package/packages/engine/src/flow-sources.mjs +135 -0
  139. package/packages/engine/src/index.mjs +9 -0
  140. package/packages/engine/src/markdown.mjs +97 -0
  141. package/packages/engine/src/mcp-client.mjs +429 -0
  142. package/packages/engine/src/package.mjs +116 -0
  143. package/packages/engine/src/run.mjs +308 -0
  144. package/packages/engine/src/tool-sources.mjs +566 -0
  145. package/packages/mcp/bin/factoryhub-mcp.mjs +6 -0
  146. package/packages/mcp/package.json +36 -0
  147. package/packages/mcp/src/server.mjs +310 -0
  148. package/packages/sdk/package.json +28 -0
  149. package/packages/sdk/src/index.d.ts +163 -0
  150. package/packages/sdk/src/index.mjs +266 -0
  151. package/spec/README.md +42 -0
  152. package/spec/factory-format.md +866 -0
  153. package/spec/schema/factory.schema.json +43 -0
  154. package/spec/schema/factory.yaml.json +815 -0
  155. package/spec/schema/flow.schema.json +191 -0
  156. package/spec/skill-export.md +129 -0
@@ -0,0 +1,310 @@
1
+ // The factoryhub MCP server: find, read, validate, export and run AI
2
+ // factories from any MCP client. It runs locally over stdio. Runs use the
3
+ // model key in this process's environment, never one of ours, and stop at
4
+ // every human decision: the client must ask the person and call resume_run.
5
+ import * as fsp from 'node:fs/promises';
6
+ import { readFile, writeFile, mkdir, rm } from 'node:fs/promises';
7
+ import { existsSync, readFileSync } from 'node:fs';
8
+ import { join, resolve, delimiter } from 'node:path';
9
+ import { homedir } from 'node:os';
10
+ import { randomBytes } from 'node:crypto';
11
+ import { McpServer, ResourceTemplate } from '@modelcontextprotocol/server';
12
+ import { z } from 'zod';
13
+ import { parseBundle, toEnvelope, sha256 } from '../../engine/src/factory-engine.mjs';
14
+ import { readFactory, readFolder, listFactoryDirs, writeFiles, HOUSE_FACTORIES } from '../../engine/lib/node.mjs';
15
+ import { summarize, matches, canonicalFiles } from '../../engine/lib/catalog.mjs';
16
+ import { exportSkill, checkSkill } from '../../engine/lib/skill.mjs';
17
+ import { hubClient } from '../../engine/lib/hub.mjs';
18
+ import { chooseProvider } from '../../engine/lib/providers.mjs';
19
+ import { nodeHost, prepareRun, continueRun, pendingDecision, decide, restoreRun } from '../../engine/lib/run.mjs';
20
+
21
+ export const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
22
+ export const SPEC_PATH = new URL('../../../spec/factory-format.md', import.meta.url);
23
+ export const TOOL_NAMES = ['list_factories', 'get_factory', 'validate_factory', 'export_skill', 'run_factory', 'resume_run'];
24
+
25
+ const INSTRUCTIONS = `factoryhub serves AI factories: small teams of AI agents written as plain files (factory.yaml, flow.yaml, agents/<name>/agent.md).
26
+ - list_factories and get_factory find and read factories; validate_factory checks one; export_skill turns one into an Agent Skill folder.
27
+ - run_factory runs one with the model key configured for this server. It returns when the run finishes or reaches a human decision.
28
+ - At a decision, show the person the full text, ask them to approve, reject, or say what to change, and call resume_run with their answer. Never decide for them.
29
+ - The prompt "factory_format" holds the format specification for writing a new factory.`;
30
+
31
+ const ID = z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/).max(64);
32
+
33
+ function text(value) {
34
+ return typeof value === 'string' ? value : JSON.stringify(value, null, 2);
35
+ }
36
+
37
+ function result(value, summary) {
38
+ return { structuredContent: value, content: [{ type: 'text', text: summary ? `${summary}\n\n${text(value)}` : text(value) }] };
39
+ }
40
+
41
+ function failure(error) {
42
+ return { isError: true, content: [{ type: 'text', text: String(error?.message || error) }] };
43
+ }
44
+
45
+ /**
46
+ * Creates the server. Options exist for tests and embedding:
47
+ * env (keys, FACTORYHUB_FACTORIES, FACTORYHUB_RUNS_DIR), fetchImpl, factoryDirs, runsDir,
48
+ * fs (the file system calls local factories are read with).
49
+ */
50
+ export function createServer({ env = process.env, fetchImpl = fetch, factoryDirs, runsDir, fs = fsp } = {}) {
51
+ const dirs = factoryDirs || [HOUSE_FACTORIES, ...String(env.FACTORYHUB_FACTORIES || '').split(delimiter).filter(Boolean).map((dir) => resolve(dir))];
52
+ const runs = new Map();
53
+ const runFolder = runsDir || env.FACTORYHUB_RUNS_DIR || join(homedir(), '.factoryhub', 'runs');
54
+
55
+ async function localIds() {
56
+ const seen = new Map();
57
+ const lists = await Promise.all(dirs.map((dir) => listFactoryDirs(dir)));
58
+ dirs.forEach((dir, index) => { for (const id of lists[index]) if (!seen.has(id)) seen.set(id, join(dir, id)); });
59
+ return seen;
60
+ }
61
+
62
+ // The folder of a local factory id, as localIds() would map it: the first
63
+ // factory directory with an entry of exactly that name that is a folder
64
+ // holding a factory.yaml. Only that entry is checked, not every folder, and
65
+ // an id that is not an entry name (such as "../x") is never joined to a path.
66
+ async function localLocation(id) {
67
+ for (const dir of dirs) {
68
+ const names = await fs.readdir(dir).catch(() => []);
69
+ if (!names.includes(id)) continue;
70
+ const location = join(dir, id);
71
+ const folder = await fs.lstat(location).then((stats) => stats.isDirectory(), () => false);
72
+ if (folder && existsSync(join(location, 'factory.yaml'))) return location;
73
+ }
74
+ return null;
75
+ }
76
+
77
+ // Local factories are read and summarized again only when one of their
78
+ // files changed. A folder's signature is the time and size of every file
79
+ // readFolder would read, found by the same walk with a stat in place of
80
+ // each read; an edit, an added or a removed file changes it.
81
+ const cache = new Map();
82
+ const statFs = { readdir: fs.readdir, readFile: async (path) => { const stats = await fs.stat(path); return `${stats.mtimeMs}:${stats.size}`; } };
83
+ async function readLocal(id, location) {
84
+ const signature = JSON.stringify((await readFolder(location, { fs: statFs })).files);
85
+ const cached = cache.get(location);
86
+ if (cached?.signature === signature) return cached;
87
+ const { files, skipped } = await readFolder(location, { fs });
88
+ const entry = { signature, files, skipped, summary: await summarize(files, { id }) };
89
+ cache.set(location, entry);
90
+ return entry;
91
+ }
92
+
93
+ async function resolveFactory({ id, path, source = 'local' }) {
94
+ if (path) {
95
+ const read = await readFactory(path, { fetchImpl });
96
+ return { id: read.source.id, files: read.files, location: read.source.location, leftOut: read.leftOut };
97
+ }
98
+ if (!id) throw new Error('Give a factory id, or a path to a factory folder or bundle.');
99
+ if (source === 'hub') {
100
+ const got = await hubClient({ env, fetchImpl }).get(id);
101
+ return { id, files: got.files, location: got.source, leftOut: got.leftOut };
102
+ }
103
+ const location = await localLocation(id);
104
+ if (!location) throw new Error(`No local factory "${id}". Call list_factories to see the ids, or pass source "hub" or a path.`);
105
+ const { files, skipped, summary } = await readLocal(id, location);
106
+ return { id, files, location, leftOut: skipped, summary };
107
+ }
108
+
109
+ async function saveRun(state) {
110
+ await mkdir(runFolder, { recursive: true });
111
+ const file = join(runFolder, `${state.id}.json`);
112
+ await writeFile(file, `${JSON.stringify(state)}\n`);
113
+ return file;
114
+ }
115
+
116
+ async function loadRun(runId) {
117
+ if (runs.has(runId)) return runs.get(runId);
118
+ const file = join(runFolder, `${runId}.json`);
119
+ if (!/^[A-Za-z0-9_-]{1,80}$/.test(runId) || !existsSync(file)) throw new Error(`No saved run "${runId}".`);
120
+ const state = restoreRun(JSON.parse(await readFile(file, 'utf8')));
121
+ runs.set(runId, state);
122
+ return state;
123
+ }
124
+
125
+ function progress(ctx) {
126
+ const token = ctx?.mcpReq?._meta?.progressToken;
127
+ let count = 0;
128
+ return (event) => {
129
+ if (token === undefined || !['step_started', 'step_done', 'check', 'approval_needed', 'run_failed'].includes(event.type)) return;
130
+ count += 1;
131
+ const message = event.type === 'step_started' ? `Started: ${event.title}` : event.type === 'step_done' ? `Finished step ${event.step}` : event.type === 'check' ? `Check ${event.step}: ${event.status}` : event.type === 'approval_needed' ? `Waiting for a decision at ${event.step}` : `Stopped: ${event.error}`;
132
+ ctx.mcpReq.notify({ method: 'notifications/progress', params: { progressToken: token, progress: count, message } }).catch(() => {});
133
+ };
134
+ }
135
+
136
+ async function report(state) {
137
+ runs.set(state.id, state);
138
+ const stateFile = await saveRun(state);
139
+ if (state.status === 'waiting') {
140
+ const decision = await pendingDecision(state);
141
+ return result({
142
+ run_id: state.id, status: 'waiting', decision, state_file: stateFile,
143
+ next: 'Show the person the full decision text and ask them to approve, reject, or say what to change. Then call resume_run with run_id, their decision, seen_sha256 and approval_id. Never decide for them.',
144
+ }, `The run is waiting for the person to decide at "${decision.title}".`);
145
+ }
146
+ if (state.status === 'done') {
147
+ const deliverableFile = join(runFolder, `${state.id}.md`);
148
+ await writeFile(deliverableFile, state.deliverable);
149
+ await writeFile(join(runFolder, `${state.id}.receipt.json`), `${JSON.stringify(state.receipt, null, 2)}\n`);
150
+ return result({ run_id: state.id, status: 'done', deliverable: state.deliverable, review: state.receipt.deliverable_review.status, flags: state.receipt.flags, deliverable_file: deliverableFile, receipt_file: join(runFolder, `${state.id}.receipt.json`), usage: { calls: state.usage.llmCalls, input_tokens: state.usage.input, output_tokens: state.usage.output } }, 'The run is done.');
151
+ }
152
+ if (state.status === 'stopped') return result({ run_id: state.id, status: 'stopped', step: state.stopped.step, note: state.stopped.note || '' }, 'The person rejected the result, so the run stopped with no deliverable.');
153
+ return result({ run_id: state.id, status: state.status, error: state.error, failure: state.failure || null }, 'The run did not finish.');
154
+ }
155
+
156
+ const server = new McpServer({ name: 'factoryhub', version: VERSION }, { capabilities: { tools: {}, resources: {}, prompts: {} }, instructions: INSTRUCTIONS });
157
+
158
+ server.registerTool('list_factories', {
159
+ title: 'List factories',
160
+ description: 'Lists AI factories: the house factories and folders named in FACTORYHUB_FACTORIES (source "local"), or the published catalogue on factoryhub (source "hub", which needs FACTORYHUB_ACCESS_KEY while the site is in private preview). Filters by words in the id, title, description or tags.',
161
+ inputSchema: z.object({ query: z.string().max(200).optional(), source: z.enum(['local', 'hub']).optional() }),
162
+ annotations: { readOnlyHint: true, openWorldHint: true },
163
+ }, async ({ query, source = 'local' }) => {
164
+ try {
165
+ let entries;
166
+ if (source === 'hub') entries = (await hubClient({ env, fetchImpl }).search(query || '')).map((entry) => ({ id: entry.id, title: entry.title, description: entry.description, version: entry.version, tags: entry.tags || [], runnable: entry.runnable, source: 'hub' }));
167
+ else {
168
+ const found = await Promise.all([...await localIds()].map(async ([id, location]) => ({ id, location, summary: (await readLocal(id, location)).summary })));
169
+ entries = found.filter(({ summary }) => matches(summary, query)).map(({ id, location, summary }) => ({ id, title: summary.title, description: summary.description, version: summary.version, tags: summary.tags, runnable: summary.runnable, inputs: summary.inputs.map((input) => input.key), steps: summary.steps.length, source: 'local', path: location }));
170
+ }
171
+ return result({ factories: entries }, `${entries.length} ${entries.length === 1 ? 'factory' : 'factories'}.`);
172
+ } catch (error) { return failure(error); }
173
+ });
174
+
175
+ server.registerTool('get_factory', {
176
+ title: 'Get a factory',
177
+ description: 'Reads one factory: its summary (inputs, steps in order, agents, tools, checks), its bundle SHA-256, and the full text of every file. Give an id (local or, with source "hub", published) or a path to a folder or bundle .json.',
178
+ inputSchema: z.object({ id: ID.optional(), path: z.string().max(1000).optional(), source: z.enum(['local', 'hub']).optional() }),
179
+ annotations: { readOnlyHint: true, openWorldHint: true },
180
+ }, async (args) => {
181
+ try {
182
+ const found = await resolveFactory(args);
183
+ const summary = found.summary || await summarize(found.files, { id: found.id });
184
+ return result({ summary, files: canonicalFiles(found.files), location: found.location, left_out: found.leftOut }, `${summary.title} v${summary.version}.`);
185
+ } catch (error) { return failure(error); }
186
+ });
187
+
188
+ server.registerTool('validate_factory', {
189
+ title: 'Validate a factory',
190
+ description: 'Checks a factory with the engine\'s parser, without a key or a model: every problem, every tool this runner lacks, and whether it runs here. Give a path to a folder or bundle .json, an id, or the files themselves as a map of path to text.',
191
+ inputSchema: z.object({ path: z.string().max(1000).optional(), id: ID.optional(), files: z.record(z.string().max(200), z.string().max(400000)).optional() }),
192
+ annotations: { readOnlyHint: true, openWorldHint: true },
193
+ }, async ({ path, id, files }) => {
194
+ try {
195
+ const source = files || (await resolveFactory({ id, path })).files;
196
+ const { ok, errors, warnings, factory } = parseBundle(source);
197
+ const value = { valid: ok, runnable: ok && factory.runnable, name: factory.name, title: factory.title, version: factory.version, errors, blockers: factory.blockers, warnings: warnings.filter((warning) => !factory.blockers.includes(warning)) };
198
+ return result(value, !ok ? `Not valid: ${errors.length} problem${errors.length === 1 ? '' : 's'}.` : factory.runnable ? 'Valid, and it runs here.' : 'Valid, but it cannot run here.');
199
+ } catch (error) { return failure(error); }
200
+ });
201
+
202
+ server.registerTool('export_skill', {
203
+ title: 'Export as an Agent Skill',
204
+ description: 'Turns a factory into an Agent Skill folder: <id>/SKILL.md (what it produces, inputs to collect, every step and who does it, where to stop and ask the person to approve) and <id>/factory/ (the files unchanged, plus a foreman written from the flow when the author wrote none). With out_dir, writes the folder there; without, returns SKILL.md and the file list.',
205
+ inputSchema: z.object({ id: ID.optional(), path: z.string().max(1000).optional(), source: z.enum(['local', 'hub']).optional(), out_dir: z.string().max(1000).optional(), overwrite: z.boolean().optional() }),
206
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
207
+ }, async ({ out_dir: outDir, overwrite = false, ...args }) => {
208
+ try {
209
+ const found = await resolveFactory(args);
210
+ const skill = await exportSkill(found.files, { id: found.id });
211
+ const problems = await checkSkill(skill.files, { folder: skill.id });
212
+ let folder = null;
213
+ if (outDir) {
214
+ folder = resolve(outDir, skill.id);
215
+ if (existsSync(folder)) {
216
+ if (!overwrite) throw new Error(`${folder} already exists. Pass overwrite: true to replace it.`);
217
+ if (!existsSync(join(folder, 'SKILL.md'))) throw new Error(`${folder} is not an earlier skill export, so it was left alone.`);
218
+ await rm(folder, { recursive: true, force: true });
219
+ }
220
+ await writeFiles(folder, skill.files, { allow: (file) => file === 'SKILL.md' || file.startsWith('factory/') });
221
+ }
222
+ return result({ id: skill.id, sha256: skill.sha256, folder, files: Object.keys(skill.files), problems, skill_md: skill.files['SKILL.md'] }, folder ? `Wrote ${folder}.` : 'SKILL.md is below; pass out_dir to write the folder.');
223
+ } catch (error) { return failure(error); }
224
+ });
225
+
226
+ server.registerTool('run_factory', {
227
+ title: 'Run a factory',
228
+ description: 'Runs a factory on this machine with the model key set in this server\'s environment (ANTHROPIC_API_KEY, OPENAI_API_KEY or OPENROUTER_API_KEY), or a local OpenAI-compatible server (provider "ollama" or base_url, with model). It can take minutes. It returns when the run is done, fails, or reaches a human decision: then it returns run_id, the text to show, seen_sha256 and approval_id. Show the person the text, get their decision, and call resume_run. Never decide for them.',
229
+ inputSchema: z.object({
230
+ id: ID.optional(), path: z.string().max(1000).optional(), source: z.enum(['local', 'hub']).optional(),
231
+ inputs: z.record(z.string().max(64), z.string().max(40000)).optional(),
232
+ provider: z.enum(['anthropic', 'openai', 'openrouter', 'ollama', 'openai-compatible']).optional(),
233
+ model: z.string().max(160).optional(), base_url: z.string().max(2000).optional(),
234
+ }),
235
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
236
+ }, async ({ inputs = {}, provider: kind, model, base_url: baseUrl, ...args }, ctx) => {
237
+ try {
238
+ const found = await resolveFactory(args);
239
+ const provider = chooseProvider({ provider: kind, model, baseUrl, env, fetchImpl });
240
+ const id = `mcp-${Date.now().toString(36)}-${randomBytes(4).toString('hex')}`;
241
+ const prepared = prepareRun({ files: found.files, inputs, id, runner: { mode: 'mcp', provider: provider.name, model: provider.model } });
242
+ if (!prepared.ok) throw new Error(prepared.problems.join('\n'));
243
+ const state = prepared.state;
244
+ state.mcp = { provider: kind || null, model: provider.model, baseUrl: baseUrl || null };
245
+ await continueRun(state, nodeHost({ provider, fetchImpl, emit: progress(ctx) }));
246
+ return await report(state);
247
+ } catch (error) { return failure(error); }
248
+ });
249
+
250
+ server.registerTool('resume_run', {
251
+ title: 'Resume a run with the person\'s decision',
252
+ description: 'Continues a run that is waiting at a human decision. Call it only with the person\'s own answer: approve, reject (ends the run with no result), or revise with a note saying what to change. Pass the seen_sha256 and approval_id from the waiting result, so the decision applies to the exact text the person saw. Returns at the next decision or when the run ends.',
253
+ inputSchema: z.object({
254
+ run_id: z.string().regex(/^[A-Za-z0-9_-]{1,80}$/),
255
+ decision: z.enum(['approve', 'revise', 'reject']),
256
+ note: z.string().max(4000).optional(),
257
+ seen_sha256: z.string().regex(/^[a-f0-9]{64}$/),
258
+ approval_id: z.string().regex(/^[a-f0-9]{64}$/),
259
+ }),
260
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
261
+ }, async ({ run_id: runId, decision, note, seen_sha256: seen, approval_id: approvalId }, ctx) => {
262
+ try {
263
+ const state = await loadRun(runId);
264
+ if (decision === 'revise' && !String(note || '').trim()) throw new Error('A revise decision needs a note saying what to change.');
265
+ const why = decide(state, { action: decision, note, seen, approvalId });
266
+ if (why) {
267
+ const reasons = { not_waiting: 'This run is not waiting for a decision.', bad_action: 'The decision must be approve, revise or reject.', unseen: 'Pass seen_sha256 from the waiting result.', stale: 'seen_sha256 or approval_id does not match the text the run is waiting on. Read the current decision again and show it to the person.', no_revisions: 'This step has been sent back as often as the factory allows: approve or reject it.' };
268
+ throw new Error(reasons[why] || why);
269
+ }
270
+ const settings = state.mcp || {};
271
+ const provider = chooseProvider({ provider: settings.provider || undefined, model: settings.model, baseUrl: settings.baseUrl || undefined, env, fetchImpl });
272
+ await continueRun(state, nodeHost({ provider, fetchImpl, emit: progress(ctx) }));
273
+ return await report(state);
274
+ } catch (error) { return failure(error); }
275
+ });
276
+
277
+ server.registerResource('factory', new ResourceTemplate('factoryhub://factories/{id}', {
278
+ list: async () => {
279
+ const resources = await Promise.all([...await localIds()].map(async ([id, location]) => {
280
+ const { summary } = await readLocal(id, location);
281
+ return { uri: `factoryhub://factories/${id}`, name: id, title: summary.title, description: summary.description, mimeType: 'application/json' };
282
+ }));
283
+ return { resources };
284
+ },
285
+ }), { title: 'Factory bundle', description: 'A local factory as a transfer bundle: every file with its SHA-256.', mimeType: 'application/json' }, async (uri, { id }) => {
286
+ const found = await resolveFactory({ id: String(id) });
287
+ const files = canonicalFiles(found.files);
288
+ const envelope = toEnvelope(files, { project: found.id });
289
+ for (const entry of envelope.files) entry.sha256 = await sha256(entry.content);
290
+ return { contents: [{ uri: uri.href, mimeType: 'application/json', text: JSON.stringify(envelope, null, 2) }] };
291
+ });
292
+
293
+ server.registerResource('factory-format', 'factoryhub://spec/factory-format', { title: 'The factory format', description: 'The specification of the factory format, v1alpha1.', mimeType: 'text/markdown' }, async (uri) => ({
294
+ contents: [{ uri: uri.href, mimeType: 'text/markdown', text: await readFile(SPEC_PATH, 'utf8') }],
295
+ }));
296
+
297
+ server.registerPrompt('factory_format', {
298
+ title: 'Write a factory',
299
+ description: 'The factory format specification, to read or to write a new factory from. With a goal, asks for a factory that reaches it.',
300
+ argsSchema: z.object({ goal: z.string().max(2000).optional() }),
301
+ }, async ({ goal }) => {
302
+ const spec = await readFile(SPEC_PATH, 'utf8');
303
+ const ask = goal
304
+ ? `Write a factory for this goal, in the format above: ${goal}\n\nOutput every file in full: factory.yaml, flow.yaml and agents/<name>/agent.md for every agent a step names. Then check the files with the validate_factory tool and fix every problem it reports.`
305
+ : 'Use this specification to read, explain or write factories. Check any factory you write with the validate_factory tool.';
306
+ return { messages: [{ role: 'user', content: { type: 'text', text: `${spec}\n\n---\n\n${ask}` } }] };
307
+ });
308
+
309
+ return server;
310
+ }
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@factoryhub/sdk",
3
+ "version": "0.1.1",
4
+ "description": "The factoryhub SDK for JavaScript: log in, push, pull, publish and run factories on factoryhub, and verify run receipts. Published as the main export of the factoryhub package.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "private": true,
8
+ "engines": {
9
+ "node": ">=22"
10
+ },
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/Mindburn-Labs/factoryhub.git",
14
+ "directory": "packages/sdk"
15
+ },
16
+ "exports": {
17
+ ".": {
18
+ "types": "./src/index.d.ts",
19
+ "default": "./src/index.mjs"
20
+ }
21
+ },
22
+ "files": [
23
+ "src"
24
+ ],
25
+ "scripts": {
26
+ "test": "node --test \"test/*.test.mjs\""
27
+ }
28
+ }
@@ -0,0 +1,163 @@
1
+ // Types for the factoryhub SDK (packages/sdk/src/index.mjs).
2
+
3
+ export type Scope = 'factories:read' | 'factories:write' | 'runs:start' | 'runs:read' | 'factories:publish' | 'runs:decide';
4
+ export const SCOPES: Scope[];
5
+ export const OPT_IN_SCOPES: Scope[];
6
+ export const DEFAULT_HUB: string;
7
+
8
+ export interface ConnectionOptions {
9
+ /** The hub address. Default: FACTORYHUB_BASE_URL or https://factory.mindburn.org. */
10
+ baseUrl?: string;
11
+ /** A personal access token. Default: FACTORYHUB_TOKEN, then the saved login. */
12
+ token?: string;
13
+ /** The private-preview key. Default: FACTORYHUB_ACCESS_KEY. */
14
+ accessKey?: string;
15
+ fetch?: typeof fetch;
16
+ env?: Record<string, string | undefined>;
17
+ }
18
+
19
+ export class HubError extends Error {
20
+ status?: number;
21
+ code: string | null;
22
+ preview: boolean;
23
+ scope: string[] | null;
24
+ retryAfter: number | null;
25
+ details: Record<string, unknown> | null;
26
+ }
27
+
28
+ export interface Account { id: string; handle: string; name: string | null; email?: string }
29
+ export interface TokenInfo { id: string; name: string; prefix: string; scopes: Scope[]; expires: string | null }
30
+ export interface DeviceCode { userCode: string; verificationUri: string; verificationUriComplete: string | null; expiresIn: number; scope: string | null }
31
+
32
+ export interface LoginOptions extends ConnectionOptions {
33
+ scopes?: Scope[];
34
+ name?: string;
35
+ days?: number;
36
+ /** Show the person the code and the page. Required for a device login. */
37
+ onCode?: (code: DeviceCode) => void | Promise<void>;
38
+ /** Store the token where the CLI finds it too. Default true. */
39
+ save?: boolean;
40
+ sleep?: (ms: number) => Promise<void>;
41
+ }
42
+ export interface LoginResult {
43
+ account: Account;
44
+ token: TokenInfo;
45
+ saved: string | null;
46
+ /** What happened to the token saved before: a device-login token is revoked, a passed-in one is kept. */
47
+ replaced: 'revoked' | 'not_revoked' | 'kept' | null;
48
+ }
49
+
50
+ export interface PushResult {
51
+ factory: { id: string; url: string; title: string; visibility: string; mine: boolean; sha256: string };
52
+ parent: string | null;
53
+ unchanged: boolean;
54
+ }
55
+ export interface PullResult {
56
+ id: string;
57
+ files: Record<string, string>;
58
+ sha256: string;
59
+ source: string;
60
+ leftOut: string[];
61
+ /** True when `partial` let through a bundle that could not be checked whole. */
62
+ partial: boolean;
63
+ /** Why the bundle could not be checked whole, when `partial`. */
64
+ unchecked: string[];
65
+ dir: string | null;
66
+ /** Files an earlier pull wrote that `force` removed. */
67
+ removed: string[];
68
+ }
69
+ export interface PullOptions {
70
+ dir?: string;
71
+ /** Replace an earlier pull: only files that pull recorded are removed. */
72
+ force?: boolean;
73
+ /** Accept a bundle that cannot be checked whole (no bundle hash, or files left out). */
74
+ partial?: boolean;
75
+ }
76
+ export interface PublishResult { factory: { id: string; visibility: string }; already: boolean; message: string }
77
+ export interface RunSummary { id: string; title: string; factoryId: string; started: string; status: string; url: string }
78
+
79
+ export interface RunEvent { i: number; at: string; type: string; step: string | null; status?: string; error?: string }
80
+ export interface Waiting {
81
+ approval_id: string;
82
+ step: string;
83
+ title: string;
84
+ ask: string;
85
+ artifact: string;
86
+ artifact_sha256: string;
87
+ revisionsLeft: number;
88
+ text: string;
89
+ complete: boolean;
90
+ totalChars: number;
91
+ }
92
+ export interface Decision { decision: 'approve' | 'revise' | 'reject'; note?: string }
93
+
94
+ export interface Verification {
95
+ /** The signature is valid, the deliverable (when given) matches, and the issuer is the hub (when checked against a hub). */
96
+ valid: boolean;
97
+ signed: boolean;
98
+ signatureValid: boolean;
99
+ deliverableMatches: boolean | null;
100
+ keyId: string | null;
101
+ problems: string[];
102
+ /** "pinned": a production key pinned in this package; "published": keys the hub at `host` publishes; "given": the keys passed in. */
103
+ trust: 'pinned' | 'published' | 'given' | null;
104
+ host?: string;
105
+ issuer?: string | null;
106
+ issuerMatches?: boolean;
107
+ }
108
+ export interface HostedVerification extends Omit<Verification, 'valid'> {
109
+ /** The one answer to act on: signature, deliverable and issuer all check out. */
110
+ verified: boolean;
111
+ host: string;
112
+ issuer: string | null;
113
+ issuerMatches: boolean;
114
+ }
115
+ export interface RunResult {
116
+ text: string;
117
+ receipt: Record<string, unknown> | null;
118
+ verification: HostedVerification;
119
+ review: string;
120
+ sha256: string | null;
121
+ }
122
+ export type RunOutcome =
123
+ | { status: 'done'; run: string; url: string; result: RunResult | null }
124
+ | { status: 'waiting'; run: string; url: string; waiting: Waiting }
125
+ | { status: string; run: string; url: string; error: string | null; stopped: { step: string; title: string; note: string } | null };
126
+
127
+ export interface RunOptions extends ConnectionOptions {
128
+ inputs?: Record<string, string>;
129
+ onEvent?: (event: RunEvent) => void | Promise<void>;
130
+ /** Return the person's own decision, or null to leave the run waiting. Needs runs:decide. An approval of a step whose text was not sent whole (`complete: false`) is refused. */
131
+ onDecision?: (waiting: Waiting) => Decision | null | Promise<Decision | null>;
132
+ idempotencyKey?: string;
133
+ every?: number;
134
+ sleep?: (ms: number) => Promise<void>;
135
+ }
136
+
137
+ export interface ReceiptKey { key_id: string; public_key: string; alg?: string }
138
+
139
+ export class Hub {
140
+ constructor(options?: ConnectionOptions);
141
+ readonly baseUrl: string;
142
+ login(options?: LoginOptions & { token?: string }): Promise<LoginResult>;
143
+ logout(): Promise<boolean>;
144
+ whoami(): Promise<{ account: Account; token: TokenInfo }>;
145
+ push(source: string | Record<string, string>, options?: { parent?: string }): Promise<PushResult>;
146
+ pull(id: string, options?: PullOptions): Promise<PullResult>;
147
+ publish(id: string, options?: { note?: string }): Promise<PublishResult>;
148
+ runs(options?: { limit?: number }): Promise<RunSummary[]>;
149
+ run(id: string, options?: RunOptions): Promise<RunOutcome>;
150
+ keys(): Promise<ReceiptKey[]>;
151
+ }
152
+
153
+ export function login(options?: LoginOptions & { token?: string }): Promise<LoginResult>;
154
+ export function logout(options?: ConnectionOptions): Promise<boolean>;
155
+ export function whoami(options?: ConnectionOptions): Promise<{ account: Account; token: TokenInfo }>;
156
+ export function push(source: string | Record<string, string>, options?: ConnectionOptions & { parent?: string }): Promise<PushResult>;
157
+ export function pull(id: string, options?: ConnectionOptions & PullOptions): Promise<PullResult>;
158
+ export function publish(id: string, options?: ConnectionOptions & { note?: string }): Promise<PublishResult>;
159
+ export function run(id: string, options?: RunOptions): Promise<RunOutcome>;
160
+ export function runs(options?: ConnectionOptions & { limit?: number }): Promise<RunSummary[]>;
161
+ export function verifyReceipt(receipt: Record<string, unknown> | string, options?: ConnectionOptions & { keys?: ReceiptKey[]; deliverable?: string }): Promise<Verification>;
162
+ export function saveResult(result: RunResult, file: string): Promise<{ file: string; receipt: string | null }>;
163
+ export function credentialsPath(env?: Record<string, string | undefined>): string;