@rotifer/playground 0.34.0 → 0.35.0

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.
@@ -33,11 +33,12 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.helloCommand = void 0;
36
+ exports.helloCommand = exports.TEMPLATES = void 0;
37
37
  exports.executeGenomePipeline = executeGenomePipeline;
38
38
  const commander_1 = require("commander");
39
39
  const node_fs_1 = require("node:fs");
40
40
  const node_path_1 = require("node:path");
41
+ const node_os_1 = require("node:os");
41
42
  const node_url_1 = require("node:url");
42
43
  const display = __importStar(require("../utils/display.js"));
43
44
  const palette_js_1 = require("../utils/palette.js");
@@ -48,7 +49,9 @@ const agent_run_js_1 = require("./agent-run.js");
48
49
  const binding_js_1 = require("../utils/binding.js");
49
50
  const l0_gate_js_1 = require("../utils/l0-gate.js");
50
51
  const network_gateway_js_1 = require("../runtime/network-gateway.js");
51
- const TEMPLATES = [
52
+ const gate_js_1 = require("../testsuite/gate.js");
53
+ const gene_availability_js_1 = require("../cloud/gene-availability.js");
54
+ exports.TEMPLATES = [
52
55
  {
53
56
  id: "quality-advisor",
54
57
  name: "Gene Quality Advisor",
@@ -58,6 +61,7 @@ const TEMPLATES = [
58
61
  composition: "Seq",
59
62
  exampleInput: { verbose: false },
60
63
  section: "quick",
64
+ availability: "bundled",
61
65
  dirMapping: { mapTo: "genesDir" },
62
66
  },
63
67
  {
@@ -66,6 +70,7 @@ const TEMPLATES = [
66
70
  description: "Stop your UI from looking AI-generated",
67
71
  genes: ["uiux-analyzer", "uiux-reporter"],
68
72
  fallbackGenes: ["genesis-web-search"],
73
+ availability: "cloud",
69
74
  composition: "Seq",
70
75
  exampleInput: { html: "<html><body><img src='logo.png'><div style='color:red'><div style='font-size:10px'><input type='text'></div></div></body></html>", css: "body { color: white; background: #eee; } .btn { z-index: 999; } .card { z-index: 100; } .modal { z-index: 50; } .nav { z-index: 200; } .popup { z-index: 300; } .overlay { z-index: 400; }" },
71
76
  section: "quick",
@@ -77,6 +82,7 @@ const TEMPLATES = [
77
82
  description: "Write articles that actually go viral",
78
83
  genes: ["content-quality-analyzer", "content-optimizer"],
79
84
  fallbackGenes: ["genesis-web-search"],
85
+ availability: "cloud",
80
86
  composition: "Seq",
81
87
  exampleInput: { text: "# How to Build Your First AI Agent in 5 Minutes\n\nHave you ever wanted to create an AI agent but felt overwhelmed? In this guide, I'll show you exactly how to do it.\n\n## Step 1: Install Rotifer\n\n```bash\nnpm install -g @rotifer/playground\n```\n\n## Step 2: Initialize\n\nRun `rotifer init my-agent` and you're ready to go!\n\nThis amazing framework makes it incredibly easy to get started.", platform: "dev.to" },
82
88
  section: "quick",
@@ -92,6 +98,7 @@ const TEMPLATES = [
92
98
  // returned an EISDIR error that ended as "Execution complete" (#454).
93
99
  // Without security-scanner the template says so and stops.
94
100
  fallbackGenes: [],
101
+ availability: "unavailable",
95
102
  composition: "Seq",
96
103
  exampleInput: { path: "./genes", includeTests: false },
97
104
  section: "quick",
@@ -103,6 +110,7 @@ const TEMPLATES = [
103
110
  description: "Ask your docs, get cited answers",
104
111
  genes: ["doc-retrieval", "answer-synthesizer"],
105
112
  fallbackGenes: ["genesis-file-read", "genesis-web-search"],
113
+ availability: "unavailable",
106
114
  composition: "Seq",
107
115
  exampleInput: { question: "What is the Rotifer Protocol?", topK: 3 },
108
116
  section: "power",
@@ -114,6 +122,7 @@ const TEMPLATES = [
114
122
  description: "Contract audit + chain data",
115
123
  genes: ["solidity-parser", "vuln-detector", "audit-reporter"],
116
124
  fallbackGenes: ["genesis-code-format", "genesis-file-read"],
125
+ availability: "cloud",
117
126
  composition: "Seq",
118
127
  exampleInput: { source: "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ncontract SimpleToken {\n mapping(address => uint256) public balances;\n\n function deposit() public payable {\n balances[msg.sender] += msg.value;\n }\n\n function withdraw(uint256 amount) public {\n require(balances[msg.sender] >= amount);\n (bool success, ) = msg.sender.call{value: amount}(\"\");\n require(success);\n balances[msg.sender] -= amount;\n }\n}" },
119
128
  section: "power",
@@ -128,36 +137,52 @@ exports.helloCommand = new commander_1.Command("hello")
128
137
  .option("--file <path>", "read input from a local file")
129
138
  .option("--dir <path>", "scan a directory as input")
130
139
  .option("--verbose", "show detailed output (L2)", false)
131
- .option("--json", "output raw JSON (L3)", false)
132
- .option("--list-templates", "list available templates and exit")
133
- .action(async (options) => {
134
- const root = (0, project_root_js_1.requireProjectRoot)();
140
+ .option("--json", "write only JSON to stdout: the output, or {ok:false,code,...} on failure; progress goes to stderr", false)
141
+ .option("--list-templates", "list templates and whether each can run in this workspace, then exit")
142
+ .addHelpText("after", "\nA template whose genes are missing exits 1 and says, gene by gene, what is possible:\n" +
143
+ "the install command, or that the gene is not available. hello asks Rotifer Cloud\n" +
144
+ "(read-only, 5 s limit) but never downloads or installs anything itself.\n")
145
+ .action(reportingFailures(async (options) => {
146
+ // The program declares --json too, and takes the flag before this command
147
+ // sees it, so the program-level hook's output mode is the one to read.
148
+ options.json = options.json || display.isJsonMode();
149
+ const root = options.json ? workspaceRootOrFailure() : (0, project_root_js_1.requireProjectRoot)();
135
150
  const config = (0, config_js_1.loadConfig)(root);
136
151
  const genesDir = (0, node_path_1.join)(root, config.genes_dir);
137
152
  if (options.listTemplates) {
138
- printTemplateList();
153
+ printTemplateList(genesDir);
139
154
  return;
140
155
  }
141
156
  if (options.json) {
142
157
  display.setOutputMode("json");
158
+ // Everything meant for a person, a gene's own logging included, leaves
159
+ // stdout free for the one JSON document a caller parses.
160
+ console.log = console.error;
143
161
  }
144
162
  display.header("Rotifer Hello");
145
163
  display.info("Create and run an agent in seconds\n");
146
164
  let selected;
147
165
  if (options.template) {
148
- const found = TEMPLATES.find((t) => t.id === options.template);
166
+ const found = exports.TEMPLATES.find((t) => t.id === options.template);
149
167
  if (!found) {
150
168
  display.error(`Template '${options.template}' not found`);
151
169
  display.hint("Use --list-templates to see available options");
170
+ if (options.json) {
171
+ await exitWithJson({ ok: false, code: "template_not_found", template: options.template });
172
+ }
152
173
  process.exit(1);
153
174
  }
154
175
  selected = found;
155
176
  }
177
+ else if (options.json) {
178
+ throw new HelloFailure("template_required", "--json needs --template <id>: there is no one to answer the picker");
179
+ }
156
180
  else {
157
- selected = await promptTemplateSelection();
181
+ selected = await promptTemplateSelection(genesDir);
158
182
  }
159
183
  const resolution = resolveAvailableGenes(selected, genesDir);
160
184
  const availableGenes = resolution.genome;
185
+ const withoutCode = availableGenes.filter((g) => !hasRunnableCode((0, node_path_1.join)(genesDir, g)));
161
186
  if (availableGenes.length === 0) {
162
187
  display.error("None of the required genes are available in this project");
163
188
  if (resolution.missingPrimary.length > 0) {
@@ -167,8 +192,13 @@ exports.helloCommand = new commander_1.Command("hello")
167
192
  resolution.fallbackCompatible.length === 0) {
168
193
  display.hint(`Fallback genes found but incompatible with template input contract: ${resolution.fallbackAvailable.join(", ")}`);
169
194
  }
170
- display.hint("Install/import the required genes, or choose another template");
171
- process.exit(1);
195
+ const genes = await Promise.all(resolution.missingPrimary.map((g) => (0, gene_availability_js_1.diagnoseRegistryGene)(g)));
196
+ await reportUnavailableGenes(selected, genes, options);
197
+ }
198
+ if (withoutCode.length > 0) {
199
+ display.error(`Template '${selected.id}' cannot run: ${withoutCode.length} of its genes have no runnable code`);
200
+ const genes = withoutCode.map((g) => (0, gene_availability_js_1.diagnoseLocalGene)(g, readFidelity((0, node_path_1.join)(genesDir, g))));
201
+ await reportUnavailableGenes(selected, genes, options);
172
202
  }
173
203
  const agentName = `hello-${selected.id}`;
174
204
  const input = await resolveInput(selected, options, genesDir);
@@ -190,8 +220,7 @@ exports.helloCommand = new commander_1.Command("hello")
190
220
  display.success(`Agent '${agentName}' created`);
191
221
  }
192
222
  catch (err) {
193
- display.error(`Failed to create agent: ${err.message}`);
194
- process.exit(1);
223
+ throw new HelloFailure("agent_create_failed", `Failed to create agent: ${forOutput(err.message)}`);
195
224
  }
196
225
  }
197
226
  const separator = selected.composition === "Par" ? " ∥ " : " → ";
@@ -204,9 +233,25 @@ exports.helloCommand = new commander_1.Command("hello")
204
233
  const elapsed = performance.now() - startTime;
205
234
  console.log();
206
235
  if (pipeline.failed) {
207
- display.error(`Execution failed at ${pipeline.failedGene ?? "unknown gene"}: ${pipeline.error ?? "unknown error"}`);
236
+ // A scan that found nothing reaches the first gene as an empty input, and
237
+ // "missing required field" does not tell anyone what to point --dir at.
238
+ const nextStep = options.dir && selected.fileMapping && !hasMeaningfulHelloInput(input)
239
+ ? `No ${Object.keys(selected.fileMapping).join(", ")} files in ${options.dir}. ` +
240
+ "Point --dir at a directory that has them, or pass one with --file <path>."
241
+ : undefined;
242
+ display.error(`Execution failed at ${pipeline.failedGene ?? "unknown gene"}: ${pipeline.error ?? "unknown error"}`, nextStep);
208
243
  display.keyValue("Duration", `${elapsed.toFixed(0)}ms`);
209
244
  display.hint("Fix the failing gene or input, then re-run this template.");
245
+ if (options.json) {
246
+ await exitWithJson({
247
+ ok: false,
248
+ code: "execution_failed",
249
+ template: selected.id,
250
+ failed_gene: pipeline.failedGene ?? null,
251
+ error: pipeline.error ?? "unknown error",
252
+ ...(nextStep ? { next_step: nextStep } : {}),
253
+ });
254
+ }
210
255
  process.exit(1);
211
256
  }
212
257
  display.success("Execution complete");
@@ -221,18 +266,109 @@ exports.helloCommand = new commander_1.Command("hello")
221
266
  display.hint(" → Customize your agent: rotifer agent create my-agent --genes <g1> <g2>");
222
267
  display.hint(" → Browse more genes: rotifer search <keyword>");
223
268
  display.hint(" → Compete in Arena: rotifer arena submit <gene>");
224
- });
225
- async function resolveInput(template, options, genesDir) {
226
- if (options.json && options.input) {
227
- return JSON.parse(options.input);
269
+ }));
270
+ /** A reason `hello` stops that the person or program calling it can act on. */
271
+ class HelloFailure extends Error {
272
+ code;
273
+ constructor(code, message) {
274
+ super(message);
275
+ this.code = code;
276
+ this.name = "HelloFailure";
277
+ }
278
+ }
279
+ /**
280
+ * Text that came from somewhere else (a gene's error, a Node error) can name
281
+ * paths on this machine. A JSON failure is handed to programs and logs, so it
282
+ * carries the reason without them.
283
+ */
284
+ function withoutLocalPaths(text) {
285
+ let out = text;
286
+ for (const known of [process.cwd(), (0, node_os_1.homedir)()]) {
287
+ if (known.length > 1)
288
+ out = out.split(known).join("<path>");
289
+ }
290
+ return out.replace(/(?:file:\/\/)?(?<![\w.:/])(?:[A-Za-z]:\\|\/)[^\s'"`:,)]+[\\/][^\s'"`:,)]*/g, "<path>");
291
+ }
292
+ function forOutput(text) {
293
+ return display.isJsonMode() ? withoutLocalPaths(text) : text;
294
+ }
295
+ function workspaceRootOrFailure() {
296
+ try {
297
+ return (0, config_js_1.getProjectRoot)();
298
+ }
299
+ catch {
300
+ throw new HelloFailure("not_in_workspace", "Not in a Rotifer Agent workspace. Run 'rotifer init' first.");
301
+ }
302
+ }
303
+ /**
304
+ * Every way out of `hello` under --json is a document on stdout, including an
305
+ * error nobody planned for; without --json a planned failure prints as it
306
+ * always did.
307
+ */
308
+ function reportingFailures(action) {
309
+ return async (options) => {
310
+ try {
311
+ await action(options);
312
+ }
313
+ catch (err) {
314
+ const isJson = options.json || display.isJsonMode();
315
+ if (err instanceof HelloFailure) {
316
+ display.error(err.message);
317
+ if (isJson)
318
+ await exitWithJson({ ok: false, code: err.code, error: err.message });
319
+ process.exit(1);
320
+ }
321
+ if (!isJson)
322
+ throw err;
323
+ const error = withoutLocalPaths(err instanceof Error ? err.message : String(err));
324
+ display.error(error);
325
+ await exitWithJson({ ok: false, code: "internal_error", error });
326
+ }
327
+ };
328
+ }
329
+ /** Writes a failure document and exits 1, after stdout has taken all of it. */
330
+ function exitWithJson(report) {
331
+ return new Promise(() => {
332
+ process.stdout.write(JSON.stringify(report) + "\n", () => process.exit(1));
333
+ });
334
+ }
335
+ /**
336
+ * Says gene by gene what can be done about a template that cannot run, then
337
+ * exits 1. Never installs: `hello` does not fetch and run remote code on its
338
+ * own, and an unattended caller gets the same answer with nothing to confirm.
339
+ */
340
+ async function reportUnavailableGenes(template, genes, options) {
341
+ for (const gene of genes) {
342
+ display.hint(` ${gene.name}: ${gene.detail}`);
343
+ }
344
+ const hasUnchecked = genes.some((g) => g.status === "unknown");
345
+ const isBlocked = genes.some((g) => g.status === "not_published" || g.status === "metadata_only");
346
+ let nextStep;
347
+ if (template.availability === "bundled") {
348
+ nextStep = "These genes come with 'rotifer init': create a new workspace with it to get them.";
349
+ }
350
+ else if (isBlocked) {
351
+ nextStep = "This template cannot run yet. See what can: rotifer hello --list-templates";
352
+ }
353
+ else if (hasUnchecked) {
354
+ nextStep = "Check your network connection, or retry when Rotifer Cloud is reachable.";
228
355
  }
356
+ else {
357
+ nextStep = `Run the commands above, then: rotifer hello --template ${template.id}`;
358
+ }
359
+ display.hint(nextStep);
360
+ if (options.json) {
361
+ await exitWithJson({ ok: false, code: "genes_unavailable", template: template.id, genes, next_step: nextStep });
362
+ }
363
+ process.exit(1);
364
+ }
365
+ async function resolveInput(template, options, genesDir) {
229
366
  if (options.input) {
230
367
  try {
231
368
  return JSON.parse(options.input);
232
369
  }
233
370
  catch {
234
- display.error("Invalid --input JSON: " + options.input);
235
- process.exit(1);
371
+ throw new HelloFailure("invalid_input", "Invalid --input JSON: " + options.input);
236
372
  }
237
373
  }
238
374
  if (options.file) {
@@ -261,10 +397,16 @@ async function resolveInput(template, options, genesDir) {
261
397
  function readFileInput(filePath, template) {
262
398
  const absPath = (0, node_path_1.resolve)(filePath);
263
399
  if (!(0, node_fs_1.existsSync)(absPath)) {
264
- display.error(`File not found: ${filePath}`);
265
- process.exit(1);
400
+ throw new HelloFailure("input_not_found", `File not found: ${filePath}`);
401
+ }
402
+ let content;
403
+ try {
404
+ content = (0, node_fs_1.readFileSync)(absPath, "utf-8");
405
+ }
406
+ catch (err) {
407
+ const reason = err.code ?? "read failed";
408
+ throw new HelloFailure("input_unreadable", `Cannot read file: ${filePath} (${reason})`);
266
409
  }
267
- const content = (0, node_fs_1.readFileSync)(absPath, "utf-8");
268
410
  const ext = (0, node_path_1.extname)(absPath).toLowerCase();
269
411
  if (template.fileMapping && template.fileMapping[ext]) {
270
412
  return { [template.fileMapping[ext]]: content };
@@ -279,8 +421,7 @@ function readFileInput(filePath, template) {
279
421
  function readDirInput(dirPath, template) {
280
422
  const absPath = (0, node_path_1.resolve)(dirPath);
281
423
  if (!(0, node_fs_1.existsSync)(absPath) || !(0, node_fs_1.statSync)(absPath).isDirectory()) {
282
- display.error(`Directory not found: ${dirPath}`);
283
- process.exit(1);
424
+ throw new HelloFailure("input_not_found", `Directory not found: ${dirPath}`);
284
425
  }
285
426
  if (template.dirMapping) {
286
427
  return { [template.dirMapping.mapTo]: absPath };
@@ -335,7 +476,7 @@ async function readStdin() {
335
476
  }
336
477
  async function renderOutput(result, genome, genesDir, options) {
337
478
  if (options.json) {
338
- console.log(JSON.stringify(result, null, 2));
479
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
339
480
  return;
340
481
  }
341
482
  const lastGene = genome[genome.length - 1];
@@ -384,37 +525,64 @@ function hasMeaningfulHelloInput(input) {
384
525
  return Object.keys(input).length > 0;
385
526
  return true;
386
527
  }
387
- function printTemplateList() {
528
+ function isReadyHere(template, genesDir) {
529
+ return template.genes.every((g) => {
530
+ const geneDir = (0, node_path_1.join)(genesDir, g);
531
+ return (0, node_fs_1.existsSync)((0, node_path_1.join)(geneDir, "phenotype.json")) && hasRunnableCode(geneDir);
532
+ });
533
+ }
534
+ function needsGenesReason(template) {
535
+ switch (template.availability) {
536
+ case "bundled":
537
+ return "comes with rotifer init";
538
+ case "cloud":
539
+ return "install from Rotifer Cloud";
540
+ case "unavailable":
541
+ return "not available yet";
542
+ }
543
+ }
544
+ function printTemplateList(genesDir) {
388
545
  display.header("Available Templates");
389
546
  console.log();
390
- const quickStart = TEMPLATES.filter((t) => t.section === "quick");
391
- const power = TEMPLATES.filter((t) => t.section === "power");
392
- display.info(palette_js_1.c.accent.bold("Quick Start") + palette_js_1.c.muted(" (works instantly, no setup)"));
393
- for (const t of quickStart) {
394
- console.log(` ${palette_js_1.c.brand(t.id.padEnd(24))} ${t.description}`);
547
+ const ready = exports.TEMPLATES.filter((t) => isReadyHere(t, genesDir));
548
+ const quickStart = ready.filter((t) => t.section === "quick");
549
+ const power = ready.filter((t) => t.section === "power");
550
+ const needsGenes = exports.TEMPLATES.filter((t) => !ready.includes(t));
551
+ const row = (t, suffix) => console.log(` ${palette_js_1.c.brand(t.id.padEnd(24))} ${t.description}${suffix}`);
552
+ if (quickStart.length > 0) {
553
+ display.info(palette_js_1.c.accent.bold("Quick Start") + palette_js_1.c.muted(" (ready to run here)"));
554
+ for (const t of quickStart)
555
+ row(t, "");
556
+ console.log();
395
557
  }
396
- console.log();
397
- display.info(palette_js_1.c.accent.bold("Power Templates") + palette_js_1.c.muted(" (may need API key or domain knowledge)"));
398
- for (const t of power) {
399
- const badge = t.badge ? palette_js_1.c.warn(` [${t.badge}]`) : "";
400
- console.log(` ${palette_js_1.c.brand(t.id.padEnd(24))} ${t.description}${badge}`);
558
+ if (power.length > 0) {
559
+ display.info(palette_js_1.c.accent.bold("Power Templates") + palette_js_1.c.muted(" (may need API key or domain knowledge)"));
560
+ for (const t of power)
561
+ row(t, t.badge ? palette_js_1.c.warn(` [${t.badge}]`) : "");
562
+ console.log();
563
+ }
564
+ if (needsGenes.length > 0) {
565
+ display.info(palette_js_1.c.accent.bold("Needs genes first") + palette_js_1.c.muted(" (run one to see exactly what it needs)"));
566
+ for (const t of needsGenes)
567
+ row(t, palette_js_1.c.warn(` [${needsGenesReason(t)}]`));
568
+ console.log();
401
569
  }
402
- console.log();
403
570
  display.hint("Usage: rotifer hello --template <id>");
404
571
  display.hint(" rotifer hello --template <id> --file <path>");
405
- display.hint(" cat file.md | rotifer hello --template content-analysis");
572
+ display.hint(" cat file.md | rotifer hello --template <id>");
406
573
  }
407
- async function promptTemplateSelection() {
574
+ async function promptTemplateSelection(genesDir) {
408
575
  const clack = await import("@clack/prompts");
409
- const quickOptions = TEMPLATES.filter((t) => t.section === "quick").map((t) => ({
576
+ const readiness = (t) => (isReadyHere(t, genesDir) ? "" : " [needs genes]");
577
+ const quickOptions = exports.TEMPLATES.filter((t) => t.section === "quick").map((t) => ({
410
578
  value: t.id,
411
579
  label: t.name,
412
- hint: t.description,
580
+ hint: `${t.description}${readiness(t)}`,
413
581
  }));
414
- const powerOptions = TEMPLATES.filter((t) => t.section === "power").map((t) => ({
582
+ const powerOptions = exports.TEMPLATES.filter((t) => t.section === "power").map((t) => ({
415
583
  value: t.id,
416
584
  label: t.name,
417
- hint: `${t.description}${t.badge ? ` [${t.badge}]` : ""}`,
585
+ hint: `${t.description}${t.badge ? ` [${t.badge}]` : ""}${readiness(t)}`,
418
586
  }));
419
587
  const customOption = {
420
588
  value: "__custom__",
@@ -443,7 +611,7 @@ async function promptTemplateSelection() {
443
611
  display.hint(" → Use Cloud search: rotifer.ai (semantic gene discovery)");
444
612
  process.exit(0);
445
613
  }
446
- const selected = TEMPLATES.find((t) => t.id === choice);
614
+ const selected = exports.TEMPLATES.find((t) => t.id === choice);
447
615
  if (!selected) {
448
616
  display.error("Template not found");
449
617
  process.exit(1);
@@ -599,16 +767,23 @@ async function executeGenomePipeline(genome, genesDir, input) {
599
767
  continue;
600
768
  }
601
769
  const srcFile = findGeneSource(geneDir);
602
- if (!srcFile) {
603
- display.warn(`${step} Gene '${geneName}' has no executable source — passing through`);
604
- continue;
605
- }
606
- // 门控放在 import 之前:import 会执行模块顶层代码,等到 express() 就晚了。
770
+ const irWasmPath = (0, node_path_1.join)(geneDir, "gene.ir.wasm");
607
771
  const phenotypePath = (0, node_path_1.join)(geneDir, "phenotype.json");
608
772
  const phenotype = (0, node_fs_1.existsSync)(phenotypePath)
609
773
  ? JSON.parse((0, node_fs_1.readFileSync)(phenotypePath, "utf-8"))
610
774
  : {};
611
- const l0 = (0, l0_gate_js_1.evaluateL0)((0, binding_js_1.tryLoadBinding)(), phenotype);
775
+ // Nothing to run is a failure. This used to carry the input forward and
776
+ // end in "Execution complete", over output equal to the input.
777
+ if (!srcFile && !(0, node_fs_1.existsSync)(irWasmPath)) {
778
+ hasFailed = true;
779
+ failedGene = geneName;
780
+ error = `Gene '${geneName}' has no runnable code (declares ${phenotype.fidelity ?? "no fidelity"})`;
781
+ display.error(`${step} ${error}`);
782
+ break;
783
+ }
784
+ // 门控放在 import 之前:import 会执行模块顶层代码,等到 express() 就晚了。
785
+ const binding = (0, binding_js_1.tryLoadBinding)();
786
+ const l0 = (0, l0_gate_js_1.evaluateL0)(binding, phenotype);
612
787
  const blocked = l0.kind === "violation"
613
788
  ? l0.detail
614
789
  : l0.kind === "unavailable" && (0, l0_gate_js_1.isExternallySourced)(geneDir)
@@ -618,35 +793,75 @@ async function executeGenomePipeline(genome, genesDir, input) {
618
793
  display.warn(`${step} L0 gate could not run (${l0.detail}) — running this local gene unchecked.`);
619
794
  }
620
795
  if (blocked) {
621
- display.error(`${step} L0 gate blocked '${geneName}': ${blocked}`);
796
+ display.error(`${step} L0 gate blocked '${geneName}': ${forOutput(blocked)}`);
622
797
  hasFailed = true;
623
798
  failedGene = geneName;
624
- error = `L0 gate blocked: ${blocked}`;
799
+ error = `L0 gate blocked: ${forOutput(blocked)}`;
625
800
  break;
626
801
  }
802
+ // An installed Native gene is WASM with no source. It runs the way
803
+ // `agent run` runs it: the same executor, the phenotype's own declarations.
804
+ if (!srcFile) {
805
+ if (!binding) {
806
+ hasFailed = true;
807
+ failedGene = geneName;
808
+ error = `Gene '${geneName}' is compiled WASM, and the native sandbox that runs it did not load on this machine`;
809
+ display.error(`${step} ${error}`);
810
+ break;
811
+ }
812
+ const execute = await (0, agent_run_js_1.buildGeneExecutor)(geneName, geneDir, irWasmPath, true, phenotype, binding, binding, false);
813
+ const outcome = await execute(current);
814
+ if (outcome.success) {
815
+ current = outcome.output;
816
+ display.success(`${step} ${geneName} completed`);
817
+ }
818
+ else {
819
+ hasFailed = true;
820
+ failedGene = geneName;
821
+ error = forOutput(outcome.error ?? "unknown error");
822
+ display.error(`${step} ${geneName} failed: ${error}`);
823
+ }
824
+ continue;
825
+ }
627
826
  try {
628
827
  const absPath = (0, node_path_1.resolve)(geneDir, srcFile);
629
828
  const mod = await import((0, node_url_1.pathToFileURL)(absPath).href);
630
829
  if (typeof mod.express !== "function") {
631
- display.warn(`${step} Gene '${geneName}' does not export express() — passing through`);
632
- continue;
830
+ hasFailed = true;
831
+ failedGene = geneName;
832
+ error = `Gene '${geneName}' does not export express()`;
833
+ display.error(`${step} ${error}`);
834
+ break;
633
835
  }
634
836
  // A Hybrid gene reaches the network only through the gateway on its
635
837
  // second argument, as `run`, `test` and `agent run` give it (#444).
838
+ let output;
636
839
  if (phenotype.fidelity === "Hybrid" && phenotype.network) {
637
840
  const { gatewayFetch } = (0, network_gateway_js_1.createGatewayFetch)(phenotype.network);
638
- current = await mod.express(current, { gatewayFetch });
841
+ output = await mod.express(current, { gatewayFetch });
639
842
  }
640
843
  else {
641
- current = await mod.express(current);
844
+ output = await mod.express(current);
845
+ }
846
+ // A lone __rotifer_error is the gene refusing (ADR-334). The sandbox
847
+ // reports it as INVALID_INPUT; read it the same way here, rather than
848
+ // as a result to pass on.
849
+ const refusal = (0, gate_js_1.readErrorEnvelope)(output);
850
+ if (refusal) {
851
+ hasFailed = true;
852
+ failedGene = geneName;
853
+ error = forOutput(refusal);
854
+ display.error(`${step} ${geneName} failed: ${error}`);
855
+ continue;
642
856
  }
857
+ current = output;
643
858
  display.success(`${step} ${geneName} completed`);
644
859
  }
645
860
  catch (err) {
646
- display.error(`${step} ${geneName} failed: ${err.message}`);
861
+ error = forOutput(err.message);
862
+ display.error(`${step} ${geneName} failed: ${error}`);
647
863
  hasFailed = true;
648
864
  failedGene = geneName;
649
- error = err.message;
650
865
  }
651
866
  }
652
867
  return { result: current, failed: hasFailed, failedGene, error };
@@ -658,4 +873,16 @@ function findGeneSource(geneDir) {
658
873
  }
659
874
  return null;
660
875
  }
876
+ function hasRunnableCode(geneDir) {
877
+ return findGeneSource(geneDir) !== null || (0, node_fs_1.existsSync)((0, node_path_1.join)(geneDir, "gene.ir.wasm"));
878
+ }
879
+ function readFidelity(geneDir) {
880
+ try {
881
+ const phenotype = JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(geneDir, "phenotype.json"), "utf-8"));
882
+ return typeof phenotype?.fidelity === "string" ? phenotype.fidelity : null;
883
+ }
884
+ catch {
885
+ return null;
886
+ }
887
+ }
661
888
  //# sourceMappingURL=hello.js.map