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,429 @@
1
+ // Experimental: a client for remote MCP servers over Streamable HTTP.
2
+ // Only runs that opt in to experimental tool sources use it (see
3
+ // tool-sources.mjs); a default run never reaches this code. It will change
4
+ // with the RFC on tool sources.
5
+ //
6
+ // No dependencies and no Node.js-only APIs: fetch, TextDecoder and
7
+ // AbortSignal work in Node.js, browsers and workers alike.
8
+ // SPDX-License-Identifier: Apache-2.0
9
+
10
+ /** The protocol revision this client asks for. It accepts the one the server answers with. */
11
+ export const MCP_PROTOCOL_VERSION = '2025-06-18';
12
+ /** How long one request may take. Remote tools often call other services. */
13
+ export const MCP_TIMEOUT_MS = 90000;
14
+ const MAX_PAGES = 20;
15
+ const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
16
+ const MAX_ERROR_BYTES = 64 * 1024;
17
+ const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]']);
18
+ /** A shorter token could not be found again reliably in what a server sends back. */
19
+ export const MIN_TOKEN_LENGTH = 16;
20
+ const PROTOCOL_VERSION = /^\d{4}-\d{2}-\d{2}$/;
21
+ const SERVER_NAME = /^[A-Za-z0-9][A-Za-z0-9 ._@/+-]{0,99}$/;
22
+ const SERVER_VERSION = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,39}$/;
23
+ const DELETE_TIMEOUT_MS = 3000;
24
+
25
+ /**
26
+ * A failed request. `retryable` says whether trying again later may work;
27
+ * `kind` names the class of failure: timeout, network, auth, http, rpc,
28
+ * redirect, too_large, input_required, closed or protocol. A message is
29
+ * always this client's own sentence: no text a server sent is in it.
30
+ */
31
+ export class McpError extends Error {
32
+ constructor(message, { retryable = false, status, rpcCode, kind = 'protocol' } = {}) {
33
+ super(message);
34
+ this.name = 'McpError';
35
+ this.kind = kind;
36
+ this.retryable = retryable;
37
+ if (status) this.status = status;
38
+ if (rpcCode !== undefined) this.rpcCode = rpcCode;
39
+ if (kind === 'input_required') this.inputRequired = true;
40
+ }
41
+ }
42
+
43
+ const tooLarge = () => new McpError('The server sent more than 8 MB for one request.', { kind: 'too_large' });
44
+ const isTimeout = (error) => error?.name === 'TimeoutError' || error?.name === 'AbortError';
45
+
46
+ // The body, chunk by chunk, so nothing has to be read whole.
47
+ async function* chunks(response) {
48
+ const reader = response.body?.getReader?.();
49
+ if (!reader) {
50
+ const text = await response.text();
51
+ if (text) yield new TextEncoder().encode(text);
52
+ return;
53
+ }
54
+ try {
55
+ for (;;) {
56
+ const { value, done } = await reader.read();
57
+ if (done) return;
58
+ if (value?.byteLength) yield value;
59
+ }
60
+ } finally {
61
+ reader.cancel().catch(() => {});
62
+ }
63
+ }
64
+
65
+ // At most `limit` bytes of text: past it, an error, or with `cut` the text so far.
66
+ async function readText(response, limit, { cut = false } = {}) {
67
+ const decoder = new TextDecoder();
68
+ let text = '';
69
+ let total = 0;
70
+ for await (const chunk of chunks(response)) {
71
+ total += chunk.byteLength;
72
+ if (total > limit) {
73
+ if (cut) return text;
74
+ throw tooLarge();
75
+ }
76
+ text += decoder.decode(chunk, { stream: true });
77
+ }
78
+ return text + decoder.decode();
79
+ }
80
+
81
+ // Server-sent events, one `data` payload at a time, read as they arrive, so
82
+ // a server that keeps its stream open after answering is fine.
83
+ async function* sseData(response) {
84
+ const decoder = new TextDecoder();
85
+ let buffer = '';
86
+ let data = [];
87
+ let total = 0;
88
+ const lines = function* (final) {
89
+ for (;;) {
90
+ const at = buffer.search(/\r|\n/);
91
+ if (at < 0 || (buffer[at] === '\r' && at === buffer.length - 1 && !final)) return;
92
+ const line = buffer.slice(0, at);
93
+ buffer = buffer.slice(at + (buffer[at] === '\r' && buffer[at + 1] === '\n' ? 2 : 1));
94
+ yield line;
95
+ }
96
+ };
97
+ const event = function* (line) {
98
+ if (line === '') { if (data.length) yield data.join('\n'); data = []; return; }
99
+ if (line.startsWith(':')) return;
100
+ const colon = line.indexOf(':');
101
+ const field = colon < 0 ? line : line.slice(0, colon);
102
+ const value = colon < 0 ? '' : line.slice(colon + 1).replace(/^ /, '');
103
+ if (field === 'data') data.push(value);
104
+ };
105
+ for await (const chunk of chunks(response)) {
106
+ total += chunk.byteLength;
107
+ if (total > MAX_RESPONSE_BYTES) throw tooLarge();
108
+ buffer += decoder.decode(chunk, { stream: true });
109
+ for (const line of lines(false)) yield* event(line);
110
+ }
111
+ buffer += decoder.decode();
112
+ for (const line of lines(true)) yield* event(line);
113
+ if (buffer) yield* event(buffer);
114
+ if (data.length) yield data.join('\n');
115
+ }
116
+
117
+ // A value that reads like a credential: long, letters and digits, varied,
118
+ // and not a date. Words, tool names and dates never are.
119
+ function credentialLike(value) {
120
+ if (value.length < 16 || !/[A-Za-z]/.test(value) || !/\d/.test(value) || /^\d{4}-\d{2}-\d{2}/.test(value)) return false;
121
+ const counts = new Map();
122
+ for (const char of value) counts.set(char, (counts.get(char) || 0) + 1);
123
+ let entropy = 0;
124
+ for (const count of counts.values()) { const share = count / value.length; entropy -= share * Math.log2(share); }
125
+ return entropy >= 3;
126
+ }
127
+ const CREDENTIAL_NAME = /key|token|secret|passw|auth|sig|credential|session|code/i;
128
+
129
+ // The secrets an address carries: query values named like a credential (8
130
+ // characters or more) or reading like one, and path segments reading like one.
131
+ function addressSecrets(endpoint) {
132
+ const found = [];
133
+ for (const [name, value] of endpoint.searchParams) if (value.length >= 8 && (CREDENTIAL_NAME.test(name) || credentialLike(value))) found.push(value);
134
+ for (const segment of endpoint.pathname.split('/')) {
135
+ let value = segment;
136
+ try { value = decodeURIComponent(segment); } catch { /* kept as written */ }
137
+ if (credentialLike(value)) found.push(value);
138
+ }
139
+ return found;
140
+ }
141
+
142
+ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');
143
+ const hexOf = (bytes) => [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join('');
144
+
145
+ // The forms of a token this client removes from what a server sends: as
146
+ // written and percent-encoded (any case), hex (any case), and base64 and
147
+ // base64url with or without padding, also where the token starts at any
148
+ // byte offset inside a longer encoded text.
149
+ function secretPatterns(secrets) {
150
+ const anyCase = new Set();
151
+ const exact = new Set();
152
+ for (const token of secrets) addPatterns(token, anyCase, exact);
153
+ const alternation = (set) => [...set].filter(Boolean).sort((a, b) => b.length - a.length).map(escapeRegExp).join('|');
154
+ return [new RegExp(alternation(anyCase), 'gi'), new RegExp(alternation(exact), 'g')];
155
+ }
156
+
157
+ function addPatterns(token, anyCase, exact) {
158
+ const raw = new TextEncoder().encode(token);
159
+ for (const form of [token, encodeURIComponent(token), [...raw].map((byte) => `%${byte.toString(16).padStart(2, '0')}`).join(''), hexOf(raw)]) anyCase.add(form);
160
+ const encode = (bytes) => btoa(String.fromCharCode(...bytes));
161
+ const url = (text) => text.replace(/\+/g, '-').replace(/\//g, '_');
162
+ const full = encode(raw);
163
+ for (const form of [full, full.replace(/=+$/, '')]) { exact.add(form); exact.add(url(form)); }
164
+ for (let offset = 0; offset < 3; offset += 1) {
165
+ const shifted = new Uint8Array(offset + raw.length);
166
+ shifted.set(raw, offset);
167
+ // The characters that depend on the token's bytes alone.
168
+ const middle = encode(shifted).slice(Math.ceil((8 * offset) / 6), Math.floor((8 * (offset + raw.length)) / 6));
169
+ exact.add(middle);
170
+ exact.add(url(middle));
171
+ }
172
+ }
173
+
174
+ /**
175
+ * A client for one remote MCP server over Streamable HTTP.
176
+ *
177
+ * - `url`: the server's MCP endpoint: https, or http on this machine only.
178
+ * - `token`: sent as `Authorization: Bearer <token>` when given, at least
179
+ * 16 characters. It never appears in an error message. It is removed,
180
+ * with the encodings secretPatterns lists, from everything the server
181
+ * sends back; `mentionsSecret` finds a piece of it in text. A hostile
182
+ * server holding the token can still pass it on by a channel this client
183
+ * cannot see.
184
+ * - `fetchImpl`, `timeoutMs`, `clientInfo`: as named.
185
+ *
186
+ * Works with servers that keep a session (`Mcp-Session-Id`) and with
187
+ * stateless ones that need none. Answers may come as plain JSON or as
188
+ * server-sent events.
189
+ */
190
+ export function createMcpClient({ url, token = '', fetchImpl = fetch, timeoutMs = MCP_TIMEOUT_MS, clientInfo = { name: 'factoryhub', version: 'experimental' } }) {
191
+ let endpoint;
192
+ try { endpoint = new URL(url); } catch { throw new McpError('The MCP server address is not a valid URL.'); }
193
+ if (endpoint.protocol !== 'https:' && !(endpoint.protocol === 'http:' && LOOPBACK.has(endpoint.hostname))) throw new McpError('The MCP server address must start with https:// (http:// only for this machine).');
194
+ if (endpoint.username || endpoint.password) throw new McpError('The MCP server address must not hold credentials: pass a token instead.');
195
+ if (token && String(token).length < MIN_TOKEN_LENGTH) throw new McpError(`A token must be at least ${MIN_TOKEN_LENGTH} characters long, so it can be found again in what a server sends back.`);
196
+ // Named in messages without its path or query, which can carry identifiers.
197
+ const origin = endpoint.origin;
198
+ // Secrets to remove: the token, and what in the address reads as a
199
+ // credential (a key put in the query or the path instead of in a token).
200
+ const secrets = [...new Set([...(token ? [String(token)] : []), ...addressSecrets(endpoint)])];
201
+ const patterns = secrets.length ? secretPatterns(secrets) : [];
202
+ const redact = (text) => patterns.reduce((out, pattern) => out.replace(pattern, '[redacted]'), String(text));
203
+ // Any piece of the token at least half its length, in text with spaces,
204
+ // invisible and control characters and case taken out, numeric HTML
205
+ // entities read, forwards or backwards: a split, spaced or reversed echo.
206
+ const span = Math.max(8, Math.ceil(String(token).length / 2));
207
+ const pieces = token ? Array.from({ length: String(token).length - span + 1 }, (_, at) => String(token).slice(at, at + span).toLowerCase()) : [];
208
+ const mentionsSecret = (text) => {
209
+ if (!pieces.length) return false;
210
+ const squashed = String(text)
211
+ .replace(/&#x([0-9a-f]{1,6});/gi, (_, code) => String.fromCodePoint(Math.min(parseInt(code, 16), 0x10ffff)))
212
+ .replace(/&#(\d{1,7});/g, (_, code) => String.fromCodePoint(Math.min(Number(code), 0x10ffff)))
213
+ .normalize('NFKC').replace(/[\s\p{Cf}\p{Cc}]/gu, '').toLowerCase();
214
+ const backwards = [...squashed].reverse().join('');
215
+ return pieces.some((piece) => squashed.includes(piece) || backwards.includes(piece));
216
+ };
217
+ const scrub = (value) => {
218
+ if (typeof value === 'string') return redact(value);
219
+ if (Array.isArray(value)) return value.map(scrub);
220
+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, item]) => [redact(key), scrub(item)]));
221
+ return value;
222
+ };
223
+ let nextId = 1;
224
+ let sessionId = null;
225
+ let protocolVersion = null;
226
+ let server = null;
227
+ let initialized = false;
228
+ let initializing = null;
229
+ let closed = false;
230
+ // Aborts every request in flight when the client is closed.
231
+ const closing = new AbortController();
232
+ const signalFor = () => (AbortSignal.any ? AbortSignal.any([AbortSignal.timeout(timeoutMs), closing.signal]) : AbortSignal.timeout(timeoutMs));
233
+ const closedError = () => new McpError('The connection to the tool source was closed.', { kind: 'closed' });
234
+
235
+ const headersFor = (method) => {
236
+ const headers = { 'content-type': 'application/json', accept: 'application/json, text/event-stream' };
237
+ if (token) headers.authorization = `Bearer ${token}`;
238
+ if (protocolVersion && method !== 'initialize') headers['mcp-protocol-version'] = protocolVersion;
239
+ if (sessionId) headers['mcp-session-id'] = sessionId;
240
+ return headers;
241
+ };
242
+ const timedOut = () => new McpError(`${origin} did not answer within ${Math.round(timeoutMs / 1000)} seconds.`, { retryable: true, kind: 'timeout' });
243
+
244
+ async function post(message) {
245
+ if (closed) throw closedError();
246
+ let response;
247
+ try {
248
+ // Redirects are not followed, so the token only ever goes to this address.
249
+ response = await fetchImpl(endpoint.href, { method: 'POST', headers: headersFor(message.method), body: JSON.stringify(message), redirect: 'manual', signal: signalFor() });
250
+ } catch (error) {
251
+ if (closed) throw closedError();
252
+ if (isTimeout(error)) throw timedOut();
253
+ throw new McpError(`The connection to ${origin} failed.`, { retryable: true, kind: 'network' });
254
+ }
255
+ if (response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400)) {
256
+ await response.body?.cancel?.().catch?.(() => {});
257
+ throw new McpError(`${origin} answered with a redirect, which this client does not follow. Give the server's final address.`, { kind: 'redirect' });
258
+ }
259
+ return response;
260
+ }
261
+
262
+ // The class and status of a failed answer. What the server wrote is read
263
+ // (at most 64 KB, to free the connection) and never put in the message.
264
+ async function failureOf(response, method) {
265
+ try { await readText(response, MAX_ERROR_BYTES, { cut: true }); } catch { /* nothing to keep */ }
266
+ const status = response.status;
267
+ if (status === 401 || status === 403) return new McpError(`${origin} refused the credentials for ${method} (HTTP ${status}).`, { status, kind: 'auth' });
268
+ const retryable = status === 408 || status === 429 || status >= 500;
269
+ return new McpError(`${origin} answered ${method} with HTTP ${status}.`, { status, retryable, kind: 'http' });
270
+ }
271
+
272
+ // Answers a ping the server sends while it works on a request. Never throws.
273
+ async function pong(requestId) {
274
+ try {
275
+ const response = await post({ jsonrpc: '2.0', id: requestId, result: {} });
276
+ await response.body?.cancel?.().catch?.(() => {});
277
+ } catch { /* the server goes on or gives up */ }
278
+ }
279
+
280
+ // Sends one request and returns its result, or throws an McpError.
281
+ async function request(method, params, retried = false) {
282
+ const id = nextId;
283
+ nextId += 1;
284
+ const used = sessionId;
285
+ const response = await post({ jsonrpc: '2.0', id, method, ...(params !== undefined ? { params } : {}) });
286
+ // An expired session: one new session, shared by every request that saw it expire.
287
+ if (response.status === 404 && used && method !== 'initialize' && !retried) {
288
+ await response.body?.cancel?.().catch?.(() => {});
289
+ if (sessionId === used) { sessionId = null; initialized = false; }
290
+ await ready();
291
+ return request(method, params, true);
292
+ }
293
+ if (!response.ok) throw await failureOf(response, method);
294
+ if (method === 'initialize') {
295
+ const given = response.headers.get('mcp-session-id');
296
+ if (given && /^[\x21-\x7e]{1,512}$/.test(given)) sessionId = given;
297
+ }
298
+ const type = (response.headers.get('content-type') || '').toLowerCase();
299
+ const answer = async (messages) => {
300
+ for (const raw of [].concat(messages)) {
301
+ const message = scrub(raw);
302
+ if (!message || typeof message !== 'object') continue;
303
+ if (message.id === id && (Object.hasOwn(message, 'result') || Object.hasOwn(message, 'error'))) return { done: true, message };
304
+ if (typeof message.method === 'string' && message.id !== undefined && message.id !== null) {
305
+ if (message.method === 'ping') { await pong(message.id); continue; }
306
+ // The server asks the client something (elicitation, sampling,
307
+ // roots) before it answers: this client cannot take part yet.
308
+ return { done: true, asks: message.method };
309
+ }
310
+ }
311
+ return { done: false };
312
+ };
313
+ let found = { done: false };
314
+ try {
315
+ if (type.includes('text/event-stream')) {
316
+ for await (const data of sseData(response)) {
317
+ let parsed;
318
+ try { parsed = JSON.parse(data); } catch { throw new McpError('The server sent an event that is not JSON.'); }
319
+ found = await answer(parsed);
320
+ if (found.done) break;
321
+ }
322
+ } else if (type.includes('application/json')) {
323
+ let parsed;
324
+ const text = await readText(response, MAX_RESPONSE_BYTES);
325
+ try { parsed = JSON.parse(text); } catch { throw new McpError('The server answered with invalid JSON.'); }
326
+ found = await answer(parsed);
327
+ } else {
328
+ await response.body?.cancel?.().catch?.(() => {});
329
+ throw new McpError(`${origin} answered ${method} with an unexpected content type.`);
330
+ }
331
+ } catch (error) {
332
+ if (closed) throw closedError();
333
+ if (error instanceof McpError) throw error;
334
+ if (isTimeout(error)) throw timedOut();
335
+ throw new McpError(`The connection to ${origin} broke while the answer was read.`, { retryable: true, kind: 'network' });
336
+ }
337
+ if (found.asks) throw new McpError('The server asked for input before answering, which this experimental mode does not support yet.', { kind: 'input_required' });
338
+ if (!found.done) throw new McpError(`${origin} closed the answer to ${method} without a result.`, { retryable: true });
339
+ const { message } = found;
340
+ if (message.error) {
341
+ const code = Number.isSafeInteger(message.error.code) ? message.error.code : undefined;
342
+ throw new McpError(`${origin} answered ${method} with JSON-RPC error ${code ?? 'without a code'}.`, { rpcCode: code, retryable: code === -32603, kind: 'rpc' });
343
+ }
344
+ return message.result;
345
+ }
346
+
347
+ async function notify(method, params) {
348
+ const response = await post({ jsonrpc: '2.0', method, ...(params !== undefined ? { params } : {}) });
349
+ await response.body?.cancel?.().catch?.(() => {});
350
+ if (response.status === 401 || response.status === 403) throw new McpError(`${origin} refused the credentials (HTTP ${response.status}).`, { status: response.status, kind: 'auth' });
351
+ }
352
+
353
+ // One handshake at a time: requests that need one while it runs wait for it.
354
+ function initialize() {
355
+ initializing ||= (async () => {
356
+ const result = await request('initialize', { protocolVersion: MCP_PROTOCOL_VERSION, capabilities: {}, clientInfo });
357
+ // A revision is a date. Anything else is refused: this value goes back
358
+ // to the server in a header and into every receipt entry.
359
+ if (!result || typeof result.protocolVersion !== 'string' || !PROTOCOL_VERSION.test(result.protocolVersion)) throw new McpError(`${origin} answered initialize with a protocol version that is not a date.`, { kind: 'protocol' });
360
+ protocolVersion = result.protocolVersion;
361
+ // The server's name and version, only when they read as a plain name and version.
362
+ const plain = (value, pattern) => (typeof value === 'string' && pattern.test(value) && !mentionsSecret(value) ? value : null);
363
+ server = { name: plain(result.serverInfo?.name, SERVER_NAME), version: plain(result.serverInfo?.version, SERVER_VERSION) };
364
+ await notify('notifications/initialized');
365
+ initialized = true;
366
+ return { protocolVersion, server };
367
+ })().finally(() => { initializing = null; });
368
+ return initializing;
369
+ }
370
+
371
+ async function ready() { if (!initialized) await initialize(); }
372
+
373
+ return {
374
+ origin,
375
+ get protocolVersion() { return protocolVersion; },
376
+ get server() { return server; },
377
+ get sessionId() { return sessionId; },
378
+ /** Removes the token, and the encodings of it this client knows, from text. */
379
+ redact,
380
+ /** True when text holds a piece of the token, however spaced, split or cased. */
381
+ mentionsSecret,
382
+ initialize,
383
+ /** Every tool the server lists, following `nextCursor` page by page. */
384
+ async listTools() {
385
+ await ready();
386
+ const tools = [];
387
+ const seen = new Set();
388
+ let cursor;
389
+ for (let page = 0; page < MAX_PAGES; page += 1) {
390
+ const result = await request('tools/list', cursor === undefined ? {} : { cursor });
391
+ if (!result || !Array.isArray(result.tools)) throw new McpError('The server answered tools/list without a list of tools.');
392
+ tools.push(...result.tools);
393
+ cursor = result.nextCursor;
394
+ if (cursor === undefined || cursor === null || cursor === '') return tools;
395
+ if (typeof cursor !== 'string' || seen.has(cursor)) throw new McpError('The server sent a tools/list page cursor that repeats or is not text.');
396
+ seen.add(cursor);
397
+ }
398
+ throw new McpError(`The server listed more than ${MAX_PAGES} pages of tools.`);
399
+ },
400
+ /** The raw `tools/call` result. Errors are thrown as McpError. */
401
+ async callTool(name, args) {
402
+ await ready();
403
+ return request('tools/call', { name, arguments: args });
404
+ },
405
+ /**
406
+ * Ends the server's session, when it gave one, and refuses new requests.
407
+ * During a handshake, the session it opens is ended once it settles;
408
+ * this waits for that at most a few seconds. Never throws.
409
+ */
410
+ async close() {
411
+ closed = true;
412
+ closing.abort();
413
+ const end = async () => {
414
+ if (!sessionId) return;
415
+ const ending = sessionId;
416
+ sessionId = null;
417
+ try {
418
+ const headers = { ...headersFor('close'), 'mcp-session-id': ending };
419
+ const response = await fetchImpl(endpoint.href, { method: 'DELETE', headers, redirect: 'manual', signal: AbortSignal.timeout(DELETE_TIMEOUT_MS) });
420
+ await response.body?.cancel?.().catch?.(() => {});
421
+ } catch { /* the session expires on its own */ }
422
+ };
423
+ const settled = initializing ? initializing.catch(() => {}).then(end) : end();
424
+ let timer;
425
+ await Promise.race([settled, new Promise((resolve) => { timer = setTimeout(resolve, DELETE_TIMEOUT_MS + 1000); })]);
426
+ clearTimeout(timer);
427
+ },
428
+ };
429
+ }
@@ -0,0 +1,116 @@
1
+ // Portable package metadata and ZIP downloads, derived from the executable source.
2
+ import { parseBundle, parseYaml, inputSchema, bundleHash } from './factory-engine.mjs';
3
+ import { readAuthorTests, authorTestSummary, AUTHOR_TEST_VERSION } from './author-tests.mjs';
4
+
5
+ // Requirements are author declarations, never proof of compatibility or cost.
6
+ // An invalid companion remains in the source archive, with visible diagnostics.
7
+ export function packageDetails(files) {
8
+ const parsed = parseBundle(files);
9
+ const { factory } = parsed;
10
+ const warnings = [];
11
+ let declared = {};
12
+ if (files['mindburn.requirements.yaml']) {
13
+ try {
14
+ declared = parseYaml(files['mindburn.requirements.yaml']);
15
+ if (!declared || typeof declared !== 'object' || Array.isArray(declared)) throw new Error('Use a mapping.');
16
+ } catch {
17
+ warnings.push('Model and cost requirements could not be read. Check mindburn.requirements.yaml.');
18
+ declared = {};
19
+ }
20
+ }
21
+ const model = (value, label) => {
22
+ if (value === undefined) return null;
23
+ if (typeof value !== 'string' || !value.trim() || value.length > 160) {
24
+ warnings.push(`${label} must name a model in at most 160 characters.`);
25
+ return null;
26
+ }
27
+ return value.trim();
28
+ };
29
+ const minimum = model(declared.models?.minimum, 'Minimum model');
30
+ if (declared.models !== undefined && (!declared.models || typeof declared.models !== 'object' || Array.isArray(declared.models))) warnings.push('Model requirements must contain named minimum and recommended fields.');
31
+ const recommended = model(declared.models?.recommended, 'Recommended model') || model(factory.harness?.model, 'Default model');
32
+ let expectedCost = null;
33
+ const cost = declared.expected_cost;
34
+ if (cost !== undefined) {
35
+ if (cost && typeof cost === 'object' && cost.currency === 'USD'
36
+ && Number.isFinite(cost.min) && Number.isFinite(cost.max) && cost.min >= 0 && cost.max >= cost.min
37
+ && typeof cost.model === 'string' && cost.model.trim() && cost.model.length <= 160
38
+ && typeof cost.basis === 'string' && cost.basis.trim() && cost.basis.length <= 1000) {
39
+ expectedCost = { currency: 'USD', min: cost.min, max: cost.max, model: cost.model.trim(), basis: cost.basis.trim(), provenance: 'author-estimate' };
40
+ } else warnings.push('Expected cost needs USD, non-negative min/max, a model and the basis of the estimate.');
41
+ }
42
+ return {
43
+ format: 'mindburn-factory-package/v1',
44
+ name: factory.name, title: factory.title, version: factory.version,
45
+ inputs: inputSchema(factory),
46
+ requirements: {
47
+ runtime: 'Node.js 20 or newer for the included runner',
48
+ models: { minimum, recommended, provenance: 'author-declared', verified: false },
49
+ tools: [...new Set(factory.steps.flatMap((step) => [...step.tools, ...step.missing]))].sort(),
50
+ unsupported: factory.unsupportedRequirements,
51
+ expectedCost,
52
+ },
53
+ validation: { runnable: parsed.ok && factory.runnable, errors: parsed.errors, blockers: factory.blockers, warnings: [...parsed.warnings, ...warnings] },
54
+ // Structural validation is deliberately separate from effectiveness tests.
55
+ authorTests: authorTestSummary(readAuthorTests(files)),
56
+ securityScan: { status: 'not-scanned' },
57
+ changelog: Object.keys(files).find((path) => /^CHANGELOG(?:\.(?:md|txt))?$/.test(path)) || null,
58
+ };
59
+ }
60
+
61
+ export async function packageManifest(files, scan = null, tests = null) {
62
+ const sourceSha256 = await bundleHash(files);
63
+ const manifest = { ...packageDetails(files), sourceSha256 };
64
+ if (scan?.sourceSha256 === sourceSha256 && scan.version === 1) manifest.securityScan = scan;
65
+ if (tests?.sourceSha256 === sourceSha256 && tests.version === AUTHOR_TEST_VERSION) manifest.authorTests = tests;
66
+ return manifest;
67
+ }
68
+
69
+ // ---------------------------------------------------------------- bundle ----
70
+
71
+ const CRC_TABLE = (() => {
72
+ const table = new Uint32Array(256);
73
+ for (let n = 0; n < 256; n += 1) {
74
+ let c = n;
75
+ for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
76
+ table[n] = c >>> 0;
77
+ }
78
+ return table;
79
+ })();
80
+
81
+ function crc32(bytes) {
82
+ let crc = 0xffffffff;
83
+ for (const byte of bytes) crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8);
84
+ return (crc ^ 0xffffffff) >>> 0;
85
+ }
86
+
87
+ // A plain (stored, uncompressed) zip: enough for a handful of text files.
88
+ export function zip(files) {
89
+ const encoder = new TextEncoder();
90
+ const parts = [];
91
+ const central = [];
92
+ let offset = 0;
93
+ for (const [name, text] of Object.entries(files)) {
94
+ const nameBytes = encoder.encode(name);
95
+ const data = encoder.encode(text);
96
+ const crc = crc32(data);
97
+ const local = new DataView(new ArrayBuffer(30));
98
+ local.setUint32(0, 0x04034b50, true); local.setUint16(4, 20, true); local.setUint16(6, 0x0800, true);
99
+ local.setUint16(8, 0, true); local.setUint16(10, 0, true); local.setUint16(12, 0x21, true);
100
+ local.setUint32(14, crc, true); local.setUint32(18, data.length, true); local.setUint32(22, data.length, true);
101
+ local.setUint16(26, nameBytes.length, true); local.setUint16(28, 0, true);
102
+ parts.push(new Uint8Array(local.buffer), nameBytes, data);
103
+ const entry = new DataView(new ArrayBuffer(46));
104
+ entry.setUint32(0, 0x02014b50, true); entry.setUint16(4, 20, true); entry.setUint16(6, 20, true); entry.setUint16(8, 0x0800, true);
105
+ entry.setUint16(10, 0, true); entry.setUint16(12, 0, true); entry.setUint16(14, 0x21, true);
106
+ entry.setUint32(16, crc, true); entry.setUint32(20, data.length, true); entry.setUint32(24, data.length, true);
107
+ entry.setUint16(28, nameBytes.length, true); entry.setUint32(42, offset, true);
108
+ central.push(new Uint8Array(entry.buffer), nameBytes);
109
+ offset += 30 + nameBytes.length + data.length;
110
+ }
111
+ const centralSize = central.reduce((sum, part) => sum + part.length, 0);
112
+ const end = new DataView(new ArrayBuffer(22));
113
+ end.setUint32(0, 0x06054b50, true); end.setUint16(8, Object.keys(files).length, true); end.setUint16(10, Object.keys(files).length, true);
114
+ end.setUint32(12, centralSize, true); end.setUint32(16, offset, true);
115
+ return new Blob([...parts, ...central, new Uint8Array(end.buffer)], { type: 'application/zip' });
116
+ }