mimetic-cli 0.1.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.
Files changed (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +132 -0
  3. package/dist/argv.d.ts +1 -0
  4. package/dist/argv.js +8 -0
  5. package/dist/argv.js.map +1 -0
  6. package/dist/cli.d.ts +2 -0
  7. package/dist/cli.js +5 -0
  8. package/dist/cli.js.map +1 -0
  9. package/dist/feedback.d.ts +48 -0
  10. package/dist/feedback.js +243 -0
  11. package/dist/feedback.js.map +1 -0
  12. package/dist/index.d.ts +15 -0
  13. package/dist/index.js +9 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/init-templates.d.ts +12 -0
  16. package/dist/init-templates.js +251 -0
  17. package/dist/init-templates.js.map +1 -0
  18. package/dist/init.d.ts +26 -0
  19. package/dist/init.js +343 -0
  20. package/dist/init.js.map +1 -0
  21. package/dist/observer-assets.d.ts +2 -0
  22. package/dist/observer-assets.js +2322 -0
  23. package/dist/observer-assets.js.map +1 -0
  24. package/dist/observer-data.d.ts +53 -0
  25. package/dist/observer-data.js +123 -0
  26. package/dist/observer-data.js.map +1 -0
  27. package/dist/observer.d.ts +36 -0
  28. package/dist/observer.js +360 -0
  29. package/dist/observer.js.map +1 -0
  30. package/dist/oss-lab.d.ts +50 -0
  31. package/dist/oss-lab.js +298 -0
  32. package/dist/oss-lab.js.map +1 -0
  33. package/dist/oss-meta-lab.d.ts +43 -0
  34. package/dist/oss-meta-lab.js +901 -0
  35. package/dist/oss-meta-lab.js.map +1 -0
  36. package/dist/program.d.ts +36 -0
  37. package/dist/program.js +825 -0
  38. package/dist/program.js.map +1 -0
  39. package/dist/run.d.ts +206 -0
  40. package/dist/run.js +688 -0
  41. package/dist/run.js.map +1 -0
  42. package/package.json +78 -0
  43. package/skills/mimetic-cli/SKILL.md +92 -0
  44. package/skills/mimetic-cli/agents/openai.yaml +7 -0
@@ -0,0 +1,901 @@
1
+ import { execFile } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { promisify } from "node:util";
6
+ import { fileURLToPath } from "node:url";
7
+ import { renderObserver } from "./observer.js";
8
+ import { DEFAULT_OSS_REPOS, normalizeOssRepoSlugs, validateOssRepoSlug } from "./oss-lab.js";
9
+ import { REVIEW_SCHEMA, RUN_BUNDLE_SCHEMA, runDryRun } from "./run.js";
10
+ export const OSS_META_LAB_SCHEMA = "mimetic.oss-meta-lab-result.v1";
11
+ const execFileAsync = promisify(execFile);
12
+ const moduleRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
13
+ export function buildOssRepoAssignments(repos, count) {
14
+ return Array.from({ length: count }, (_, index) => {
15
+ const repo = repos[index % repos.length];
16
+ if (!repo) {
17
+ throw new Error("At least one OSS repo is required.");
18
+ }
19
+ return {
20
+ index: index + 1,
21
+ repo,
22
+ scenarioId: `oss-meta-${repoSlugToken(repo)}`,
23
+ simId: `oss-${String(index + 1).padStart(2, "0")}`,
24
+ streamId: `oss-${String(index + 1).padStart(2, "0")}-desktop`
25
+ };
26
+ });
27
+ }
28
+ export async function runOssMetaLab(options) {
29
+ const cwd = path.resolve(options.cwd);
30
+ const dryRun = options.dryRun === true;
31
+ const liveRequested = !dryRun;
32
+ const warnings = [];
33
+ const repos = normalizeOssRepoSlugs(options.repos);
34
+ const count = options.count ?? DEFAULT_OSS_REPOS.length;
35
+ if (!Number.isInteger(count) || count < 1 || count > 16) {
36
+ return {
37
+ schema: OSS_META_LAB_SCHEMA,
38
+ ok: false,
39
+ assignments: [],
40
+ cwd,
41
+ dryRun,
42
+ error: {
43
+ code: "MIMETIC_INVALID_OSS_COUNT",
44
+ message: "--count must be an integer between 1 and 16."
45
+ },
46
+ liveRequested,
47
+ repos,
48
+ sandboxes: [],
49
+ warnings
50
+ };
51
+ }
52
+ const invalid = repos.find((repo) => !validateOssRepoSlug(repo));
53
+ if (invalid) {
54
+ return {
55
+ schema: OSS_META_LAB_SCHEMA,
56
+ ok: false,
57
+ assignments: [],
58
+ count,
59
+ cwd,
60
+ dryRun,
61
+ error: {
62
+ code: "MIMETIC_INVALID_OSS_REPO",
63
+ message: `Only public GitHub owner/repo slugs are supported: ${invalid}`
64
+ },
65
+ liveRequested,
66
+ repos,
67
+ sandboxes: [],
68
+ warnings
69
+ };
70
+ }
71
+ const missingKeys = missingLiveKeys(process.env);
72
+ if (liveRequested && missingKeys.length > 0) {
73
+ warnings.push(`Live E2B/Codex launch is waiting on env vars: ${missingKeys.join(", ")}.`);
74
+ warnings.push("Observer lanes stay in the live waiting state until keys are present.");
75
+ }
76
+ const assignments = buildOssRepoAssignments(repos, count);
77
+ const runId = options.runId ?? makeMetaRunId();
78
+ let localPackage;
79
+ if (liveRequested && missingKeys.length === 0) {
80
+ try {
81
+ localPackage = await packLocalMimeticPackage(cwd, runId);
82
+ warnings.push(`Packed local mimetic-cli package for sandbox install (${localPackage.fileName}).`);
83
+ }
84
+ catch (error) {
85
+ warnings.push(`Local mimetic-cli package pack failed; sandbox bootstrap will try public npm fallback. ${compactError(error)}`);
86
+ }
87
+ }
88
+ const liveDesktops = liveRequested && missingKeys.length === 0
89
+ ? await launchLiveDesktops(assignments, localPackage ? { localPackage } : {})
90
+ : [];
91
+ const liveDesktopCount = liveDesktops.filter((desktop) => desktop.url).length;
92
+ const failedLiveDesktopCount = liveDesktops.filter((desktop) => desktop.error).length;
93
+ const startedBootstrapCount = liveDesktops.filter((desktop) => desktop.bootstrap?.status === "started").length;
94
+ if (liveDesktops.length > 0) {
95
+ warnings.push(`Launched ${liveDesktopCount}/${liveDesktops.length} live E2B desktop stream${liveDesktops.length === 1 ? "" : "s"}.`);
96
+ if (startedBootstrapCount > 0) {
97
+ warnings.push(`Started ${startedBootstrapCount}/${liveDesktops.length} visible bootstrap terminal${liveDesktops.length === 1 ? "" : "s"} for Codex TUI attempt and nested Mimetic setup.`);
98
+ }
99
+ else {
100
+ warnings.push("Codex TUI injection and nested Mimetic execution remain the next substrate slice behind these live desktops.");
101
+ }
102
+ }
103
+ if (failedLiveDesktopCount > 0) {
104
+ warnings.push(`${failedLiveDesktopCount} E2B desktop launch${failedLiveDesktopCount === 1 ? "" : "es"} failed; see stream events in the Observer.`);
105
+ }
106
+ const runResult = await runDryRun({
107
+ cwd,
108
+ dryRun: true,
109
+ runId,
110
+ simCount: count
111
+ });
112
+ if (!runResult.ok || !runResult.runId) {
113
+ return {
114
+ schema: OSS_META_LAB_SCHEMA,
115
+ ok: false,
116
+ assignments,
117
+ count,
118
+ cwd,
119
+ dryRun,
120
+ error: {
121
+ code: "MIMETIC_META_RUN_FAILED",
122
+ message: runResult.error?.message ?? "Failed to create OSS meta-lab run bundle."
123
+ },
124
+ liveRequested,
125
+ repos,
126
+ sandboxes: liveDesktops.map(formatLiveDesktopForResult),
127
+ warnings: [...warnings, ...runResult.warnings]
128
+ };
129
+ }
130
+ const artifactRoot = path.join(cwd, ".mimetic", "runs", runId);
131
+ const bundlePath = path.join(artifactRoot, "run.json");
132
+ const createdAt = new Date().toISOString();
133
+ const bundle = buildMetaBundle({
134
+ assignments,
135
+ createdAt,
136
+ cwd,
137
+ dryRun,
138
+ liveDesktops,
139
+ liveRequested,
140
+ missingKeys,
141
+ runId
142
+ });
143
+ await mkdir(artifactRoot, { recursive: true });
144
+ await writeJson(bundlePath, bundle);
145
+ await writeJson(path.join(artifactRoot, "review.json"), bundle.review);
146
+ await writeFile(path.join(artifactRoot, "review.md"), renderMetaReviewMarkdown(bundle), "utf8");
147
+ await writeFile(path.join(artifactRoot, "events.ndjson"), `${bundle.events.map((event) => JSON.stringify(event)).join("\n")}\n`, "utf8");
148
+ const observer = await renderObserver(cwd, runId, { open: options.open === true });
149
+ return {
150
+ schema: OSS_META_LAB_SCHEMA,
151
+ ok: observer.ok,
152
+ assignments,
153
+ count,
154
+ cwd,
155
+ dryRun,
156
+ liveRequested,
157
+ observer,
158
+ repos,
159
+ runId,
160
+ sandboxes: liveDesktops.map(formatLiveDesktopForResult),
161
+ warnings: [...warnings, ...observer.warnings]
162
+ };
163
+ }
164
+ function buildMetaBundle(args) {
165
+ const simulations = [];
166
+ const streams = [];
167
+ const events = [
168
+ {
169
+ id: "event-000",
170
+ at: args.createdAt,
171
+ level: "info",
172
+ type: "oss-meta.contract.created",
173
+ message: "Created public-safe OSS meta-lab Observer-of-Observers contract."
174
+ }
175
+ ];
176
+ for (const assignment of args.assignments) {
177
+ const prompt = buildCodexBootstrapPrompt(assignment);
178
+ const liveDesktop = args.liveDesktops.find((desktop) => desktop.streamId === assignment.streamId);
179
+ const status = statusForMeta(args, liveDesktop);
180
+ simulations.push({
181
+ id: assignment.simId,
182
+ index: assignment.index,
183
+ personaId: `codex-oss-operator-${String(assignment.index).padStart(2, "0")}`,
184
+ scenarioId: assignment.scenarioId,
185
+ status,
186
+ streamKind: "browser",
187
+ mode: "ui-sim",
188
+ progress: progressForMeta(status, liveDesktop),
189
+ currentStep: currentStepForMeta(args, assignment),
190
+ summary: liveDesktop?.bootstrap?.status === "started"
191
+ ? `Headed E2B desktop lane assigned to ${assignment.repo}; bootstrap terminal launched to set up Mimetic and open the nested Observer.`
192
+ : `Headed E2B desktop lane assigned to ${assignment.repo}; nested Codex TUI should set up Mimetic and open a nested Observer inside that desktop.`,
193
+ streamIds: [assignment.streamId],
194
+ startedAt: args.createdAt,
195
+ updatedAt: args.createdAt
196
+ });
197
+ streams.push({
198
+ id: assignment.streamId,
199
+ simId: assignment.simId,
200
+ kind: "browser",
201
+ label: `E2B desktop - ${assignment.repo}`,
202
+ status,
203
+ transport: liveDesktop?.url ? "sse" : status === "contract_proof_only" ? "snapshot" : "sse",
204
+ updatedAt: args.createdAt,
205
+ ...(liveDesktop?.url ? { url: liveDesktop.url } : {}),
206
+ embed: {
207
+ kind: liveDesktop?.url ? "iframe" : "placeholder",
208
+ ...(liveDesktop?.url ? { url: liveDesktop.url } : {}),
209
+ title: `E2B desktop ${assignment.index}`
210
+ },
211
+ viewport: {
212
+ width: 1440,
213
+ height: 960,
214
+ deviceScaleFactor: 1
215
+ },
216
+ terminal: {
217
+ title: `Codex TUI bootstrap - ${assignment.repo}`,
218
+ format: "plain",
219
+ stdin: liveDesktop?.bootstrap ? "sent" : "planned",
220
+ tail: liveDesktop?.bootstrap?.tail ?? prompt
221
+ },
222
+ ui: {
223
+ route: `e2b://desktop/${assignment.repo}`,
224
+ intent: "Watch the headed desktop where Codex clones the repo, sets up Mimetic, and opens the nested Observer.",
225
+ state: liveDesktop?.bootstrap?.status === "started"
226
+ ? "bootstrap terminal launched"
227
+ : liveDesktop?.url ? "live E2B desktop" : args.dryRun ? "contract desktop" : "headed E2B desktop"
228
+ },
229
+ artifacts: [
230
+ { label: "run bundle", path: "run.json", kind: "bundle" },
231
+ { label: "review", path: "review.md", kind: "review" },
232
+ { label: "events", path: "events.ndjson", kind: "events" },
233
+ ...(liveDesktop?.bootstrap?.logPath ? [{ label: "remote bootstrap log", path: liveDesktop.bootstrap.logPath, kind: "log" }] : []),
234
+ ...(liveDesktop?.bootstrap?.nestedObserverPath ? [{ label: "nested observer path", path: liveDesktop.bootstrap.nestedObserverPath, kind: "observer" }] : [])
235
+ ]
236
+ });
237
+ events.push({
238
+ id: `event-${String(assignment.index).padStart(3, "0")}-assigned`,
239
+ at: args.createdAt,
240
+ level: "info",
241
+ type: "oss-meta.repo.assigned",
242
+ message: `Assigned ${assignment.repo} to Codex desktop lane ${assignment.index}.`,
243
+ simId: assignment.simId,
244
+ streamId: assignment.streamId
245
+ }, {
246
+ id: `event-${String(assignment.index).padStart(3, "0")}-prompt`,
247
+ at: args.createdAt,
248
+ level: "info",
249
+ type: "oss-meta.codex.prompt.ready",
250
+ message: "Codex TUI bootstrap prompt is available in the stream logs tab.",
251
+ simId: assignment.simId,
252
+ streamId: assignment.streamId
253
+ });
254
+ if (liveDesktop?.url) {
255
+ events.push({
256
+ id: `event-${String(assignment.index).padStart(3, "0")}-stream`,
257
+ at: args.createdAt,
258
+ level: "info",
259
+ type: "oss-meta.e2b.stream.started",
260
+ message: `Live E2B desktop stream started for ${assignment.repo}.`,
261
+ simId: assignment.simId,
262
+ streamId: assignment.streamId
263
+ });
264
+ if (liveDesktop.bootstrap?.status === "started") {
265
+ events.push({
266
+ id: `event-${String(assignment.index).padStart(3, "0")}-bootstrap-started`,
267
+ at: args.createdAt,
268
+ level: "info",
269
+ type: "oss-meta.bootstrap.started",
270
+ message: `Visible bootstrap terminal launched for ${assignment.repo}.`,
271
+ simId: assignment.simId,
272
+ streamId: assignment.streamId
273
+ });
274
+ }
275
+ else if (liveDesktop.bootstrap?.status === "failed") {
276
+ events.push({
277
+ id: `event-${String(assignment.index).padStart(3, "0")}-bootstrap-failed`,
278
+ at: args.createdAt,
279
+ level: "error",
280
+ type: "oss-meta.bootstrap.failed",
281
+ message: `Bootstrap launcher failed for ${assignment.repo}.`,
282
+ simId: assignment.simId,
283
+ streamId: assignment.streamId
284
+ });
285
+ }
286
+ }
287
+ else if (liveDesktop?.error) {
288
+ events.push({
289
+ id: `event-${String(assignment.index).padStart(3, "0")}-stream-error`,
290
+ at: args.createdAt,
291
+ level: "error",
292
+ type: "oss-meta.e2b.stream.failed",
293
+ message: `E2B desktop stream failed for ${assignment.repo}: ${liveDesktop.error}`,
294
+ simId: assignment.simId,
295
+ streamId: assignment.streamId
296
+ });
297
+ }
298
+ }
299
+ if (args.liveRequested && args.missingKeys.length > 0) {
300
+ events.push({
301
+ id: "event-live-keys-blocked",
302
+ at: args.createdAt,
303
+ level: "warn",
304
+ type: "oss-meta.live.keys_missing",
305
+ message: `Live launch is blocked until ${args.missingKeys.join(", ")} are present.`
306
+ });
307
+ }
308
+ if (args.liveRequested && args.liveDesktops.length === 0) {
309
+ events.push({
310
+ id: "event-live-substrate-planned",
311
+ at: args.createdAt,
312
+ level: "warn",
313
+ type: "oss-meta.live.substrate_planned",
314
+ message: args.missingKeys.length > 0
315
+ ? "E2B desktop launch is waiting on required environment variables."
316
+ : "Codex TUI injection and nested Mimetic execution are planned behind this Observer contract."
317
+ });
318
+ }
319
+ if (args.liveDesktops.some((desktop) => desktop.url)) {
320
+ events.push({
321
+ id: "event-live-substrate-started",
322
+ at: args.createdAt,
323
+ level: "info",
324
+ type: "oss-meta.live.substrate_started",
325
+ message: args.liveDesktops.some((desktop) => desktop.bootstrap?.status === "started")
326
+ ? "E2B desktop streams are connected and bootstrap terminals are launched."
327
+ : "E2B desktop streams are connected; Codex TUI injection is still pending."
328
+ });
329
+ }
330
+ const review = createMetaReview(args);
331
+ return {
332
+ schema: RUN_BUNDLE_SCHEMA,
333
+ runId: args.runId,
334
+ mode: "dry-run",
335
+ simCount: args.assignments.length,
336
+ createdAt: args.createdAt,
337
+ cwd: args.cwd,
338
+ artifactRoot: path.join(".mimetic", "runs", args.runId),
339
+ source: {
340
+ packageName: "mimetic-cli",
341
+ mimeticSource: "present",
342
+ git: {
343
+ status: "not_captured",
344
+ note: "OSS meta-lab does not capture host git state in this slice."
345
+ }
346
+ },
347
+ persona: {
348
+ id: "oss-meta-codex-tui-operators",
349
+ name: "Codex TUI OSS Setup Operators",
350
+ source: "lab:oss:meta",
351
+ sourceDigest: "public-safe"
352
+ },
353
+ scenario: {
354
+ id: "oss-meta-observer-of-observers",
355
+ title: "OSS Observer-of-Observers Meta-Lab",
356
+ goal: "Launch headed E2B desktops where Codex agents clone public OSS repos, set up Mimetic, run nested Mimetic proof commands, attempt Codex TUI, and keep each nested Observer visible.",
357
+ source: "lab:oss:meta",
358
+ sourceDigest: "public-safe"
359
+ },
360
+ lifecycle: [
361
+ {
362
+ at: args.createdAt,
363
+ event: "oss-meta.run.created",
364
+ message: `Created OSS meta-lab run with ${args.assignments.length} headed desktop lane${args.assignments.length === 1 ? "" : "s"}.`
365
+ },
366
+ {
367
+ at: args.createdAt,
368
+ event: "oss-meta.repos.assigned",
369
+ message: `Assigned repos: ${args.assignments.map((assignment) => assignment.repo).join(", ")}.`
370
+ },
371
+ {
372
+ at: args.createdAt,
373
+ event: "oss-meta.observer.ready",
374
+ message: "Top-level Observer is ready to watch nested Mimetic Observers."
375
+ }
376
+ ],
377
+ simulations,
378
+ streams,
379
+ events,
380
+ redaction: {
381
+ status: "passed",
382
+ notes: "OSS meta-lab artifacts contain public GitHub slugs and synthetic bootstrap prompts only."
383
+ },
384
+ artifacts: {
385
+ run: "run.json",
386
+ reviewJson: "review.json",
387
+ reviewMarkdown: "review.md",
388
+ observerData: "observer/observer-data.json",
389
+ events: "events.ndjson"
390
+ },
391
+ review,
392
+ feedbackCandidates: []
393
+ };
394
+ }
395
+ function statusForMeta(args, liveDesktop) {
396
+ if (args.dryRun)
397
+ return "contract_proof_only";
398
+ if (liveDesktop?.bootstrap?.status === "failed")
399
+ return "failed";
400
+ if (liveDesktop?.url)
401
+ return "running";
402
+ if (liveDesktop?.error)
403
+ return "failed";
404
+ if (args.missingKeys.length > 0)
405
+ return "blocked";
406
+ return "preparing";
407
+ }
408
+ function progressForMeta(status, liveDesktop) {
409
+ if (status === "contract_proof_only")
410
+ return 100;
411
+ if (status === "blocked")
412
+ return 18;
413
+ if (status === "failed")
414
+ return 8;
415
+ if (liveDesktop?.bootstrap?.status === "started")
416
+ return 74;
417
+ if (liveDesktop?.url)
418
+ return 58;
419
+ return 34;
420
+ }
421
+ function currentStepForMeta(args, assignment) {
422
+ const liveDesktop = args.liveDesktops.find((desktop) => desktop.streamId === assignment.streamId);
423
+ if (args.dryRun) {
424
+ return `Contract ready for ${assignment.repo}; no E2B desktop launched.`;
425
+ }
426
+ if (liveDesktop?.bootstrap?.status === "started") {
427
+ return `Bootstrap terminal launched for ${assignment.repo}; Codex TUI attempt, Mimetic setup, and nested Observer run inside the desktop.`;
428
+ }
429
+ if (liveDesktop?.bootstrap?.status === "failed") {
430
+ return `Bootstrap launcher failed for ${assignment.repo}.`;
431
+ }
432
+ if (liveDesktop?.url) {
433
+ return `Live E2B desktop connected for ${assignment.repo}; Codex TUI injection pending.`;
434
+ }
435
+ if (liveDesktop?.error) {
436
+ return `E2B desktop launch failed for ${assignment.repo}.`;
437
+ }
438
+ if (args.missingKeys.length > 0) {
439
+ return `Waiting for ${args.missingKeys.join(", ")} before launching ${assignment.repo}.`;
440
+ }
441
+ return `Ready to launch E2B desktop and inject Codex TUI for ${assignment.repo}.`;
442
+ }
443
+ function createMetaReview(args) {
444
+ const gaps = [
445
+ args.liveDesktops.some((desktop) => desktop.bootstrap?.status === "started")
446
+ ? "Visible E2B bootstrap terminals are launched and run nested Mimetic setup; completion is watched in the desktop stream rather than polled back into the top-level bundle yet."
447
+ : "Nested Mimetic Observer evidence is represented as a lane contract until Codex TUI injection and nested Mimetic execution land.",
448
+ "The top-level run does not clone, modify, commit, push, or file issues in target repos.",
449
+ "Only public GitHub owner/repo slugs are recorded."
450
+ ];
451
+ if (args.liveRequested && args.missingKeys.length > 0) {
452
+ gaps.unshift(`Live launch is blocked until ${args.missingKeys.join(", ")} are available in environment.`);
453
+ }
454
+ if (args.liveDesktops.some((desktop) => desktop.url) && !args.liveDesktops.some((desktop) => desktop.bootstrap?.status === "started")) {
455
+ gaps.unshift("Live E2B desktop streams are connected, but Codex TUI injection and nested Mimetic execution are not yet automated.");
456
+ }
457
+ return {
458
+ schema: REVIEW_SCHEMA,
459
+ verdict: "contract_proof_only",
460
+ summary: args.dryRun
461
+ ? "OSS meta-lab dry-run rendered the Observer-of-Observers contract without provider spend."
462
+ : args.liveDesktops.some((desktop) => desktop.bootstrap?.status === "started")
463
+ ? "OSS meta-lab launched live E2B desktop streams, injected visible bootstrap terminals, and started nested Mimetic setup inside each desktop."
464
+ : args.liveDesktops.some((desktop) => desktop.url)
465
+ ? "OSS meta-lab launched live E2B desktop streams and rendered them in the top-level Observer."
466
+ : "OSS meta-lab rendered the live headed-desktop control surface and marked the missing substrate truth in-lane.",
467
+ gaps
468
+ };
469
+ }
470
+ function buildCodexBootstrapPrompt(assignment) {
471
+ return [
472
+ `# Mimetic OSS Meta-Lab Actor ${assignment.index}`,
473
+ "",
474
+ "You are running inside a disposable headed E2B desktop with a visible terminal and browser.",
475
+ "Public-safety hard rails: use only public repo contents; never print keys; never commit, push, file issues, or preserve private artifacts.",
476
+ "",
477
+ `Target repo: https://github.com/${assignment.repo}.git`,
478
+ "",
479
+ "Mission:",
480
+ "1. Clone the target repo into a clean disposable workspace.",
481
+ "2. Inspect the package manager, dev scripts, README, and app shape.",
482
+ "3. Get the repo into a local runnable dev mode if feasible.",
483
+ "4. Install Mimetic as a dev dependency with the package manager the repo already uses.",
484
+ "5. Run `npx mimetic init --yes` or the package-manager equivalent.",
485
+ "6. Author plausible public-safe Mimetic personas and scenarios for this repo.",
486
+ "7. Run the strongest Mimetic proof path the installed package supports, using provided OPENAI_API_KEY and E2B_API_KEY where live substrate is implemented.",
487
+ "8. Open the nested Mimetic Observer in the E2B browser and keep it visible.",
488
+ "9. Record public-safe blockers and evidence paths only.",
489
+ "",
490
+ "Expected nested outcome: the top-level Mimetic Observer shows this desktop, and this desktop shows its own nested Mimetic Observer."
491
+ ].join("\n");
492
+ }
493
+ function renderMetaReviewMarkdown(bundle) {
494
+ return `# Mimetic OSS Meta-Lab Review
495
+
496
+ Run: ${bundle.runId}
497
+
498
+ Verdict: ${bundle.review.verdict}
499
+
500
+ ${bundle.review.summary}
501
+
502
+ ## Public-Safety
503
+
504
+ - Redaction: ${bundle.redaction.status}
505
+ - Notes: ${bundle.redaction.notes}
506
+
507
+ ## Assigned Repos
508
+
509
+ ${bundle.streams.map((stream) => `- ${stream.label}: ${stream.simId}`).join("\n")}
510
+
511
+ ## Gaps
512
+
513
+ ${bundle.review.gaps.map((gap) => `- ${gap}`).join("\n")}
514
+ `;
515
+ }
516
+ async function launchLiveDesktops(assignments, options = {}) {
517
+ const e2bApiKey = process.env.E2B_API_KEY;
518
+ const openaiApiKey = process.env.OPENAI_API_KEY;
519
+ if (!e2bApiKey || !openaiApiKey) {
520
+ return [];
521
+ }
522
+ const desktopPackage = "@e2b/desktop";
523
+ const desktopModule = await import(desktopPackage);
524
+ const timeoutMs = readPositiveInt(process.env.MIMETIC_E2B_TIMEOUT_MS, 60 * 60 * 1000);
525
+ const requestTimeoutMs = readPositiveInt(process.env.MIMETIC_E2B_REQUEST_TIMEOUT_MS, 60_000);
526
+ return Promise.all(assignments.map(async (assignment) => {
527
+ try {
528
+ const desktop = await desktopModule.Sandbox.create({
529
+ apiKey: e2bApiKey,
530
+ requestTimeoutMs,
531
+ timeoutMs,
532
+ metadata: {
533
+ tool: "mimetic-cli",
534
+ mode: "oss-meta-lab",
535
+ repo: assignment.repo,
536
+ simId: assignment.simId
537
+ },
538
+ envs: {
539
+ E2B_API_KEY: e2bApiKey,
540
+ OPENAI_API_KEY: openaiApiKey
541
+ },
542
+ resolution: [1440, 960],
543
+ dpi: 96,
544
+ lifecycle: {
545
+ onTimeout: "kill"
546
+ }
547
+ });
548
+ const bootstrap = await startOssBootstrap(desktop, assignment, options.localPackage, requestTimeoutMs);
549
+ await desktop.wait(750).catch(() => undefined);
550
+ await desktop.stream.start({ requireAuth: true });
551
+ const authKey = desktop.stream.getAuthKey();
552
+ const url = desktop.stream.getUrl({
553
+ authKey,
554
+ autoConnect: true,
555
+ viewOnly: true,
556
+ resize: "scale"
557
+ });
558
+ return {
559
+ bootstrap,
560
+ repo: assignment.repo,
561
+ sandboxId: desktop.sandboxId,
562
+ simId: assignment.simId,
563
+ streamId: assignment.streamId,
564
+ url
565
+ };
566
+ }
567
+ catch (error) {
568
+ return {
569
+ error: compactError(error),
570
+ repo: assignment.repo,
571
+ simId: assignment.simId,
572
+ streamId: assignment.streamId
573
+ };
574
+ }
575
+ }));
576
+ }
577
+ async function startOssBootstrap(desktop, assignment, localPackage, requestTimeoutMs) {
578
+ const token = repoSlugToken(assignment.repo);
579
+ const rootDir = `/home/user/mimetic-oss-lab/${token}`;
580
+ const remotePackagePath = `/tmp/${localPackage?.fileName ?? "mimetic-cli.tgz"}`;
581
+ const bootstrapPath = `${rootDir}/bootstrap.sh`;
582
+ const launcherPath = `${rootDir}/launch-terminal.sh`;
583
+ const logPath = `${rootDir}/bootstrap.log`;
584
+ const nestedObserverPath = `${rootDir}/repo/.mimetic/runs/nested-${token}/observer/index.html`;
585
+ const title = `Mimetic ${assignment.index} ${assignment.repo}`;
586
+ const baseTail = [
587
+ `repo: ${assignment.repo}`,
588
+ `sandbox: ${desktop.sandboxId}`,
589
+ `remote package: ${localPackage ? remotePackagePath : "npm:mimetic-cli fallback"}`,
590
+ `bootstrap: ${bootstrapPath}`,
591
+ `log: ${logPath}`,
592
+ `nested observer: ${nestedObserverPath}`
593
+ ].join("\n");
594
+ try {
595
+ await runDesktopCommand(desktop, `mkdir -p ${shellQuote(rootDir)}`, {
596
+ requestTimeoutMs,
597
+ timeoutMs: 30_000
598
+ });
599
+ if (localPackage) {
600
+ const packageBytes = await readFile(localPackage.path);
601
+ await desktop.files.write(remotePackagePath, toArrayBuffer(packageBytes), {
602
+ requestTimeoutMs,
603
+ useOctetStream: true
604
+ });
605
+ }
606
+ const bootstrapScript = buildRemoteBootstrapScript({
607
+ assignment,
608
+ logPath,
609
+ nestedObserverPath,
610
+ rootDir,
611
+ token,
612
+ ...(localPackage ? { remotePackagePath } : {})
613
+ });
614
+ const launcherScript = buildRemoteLauncherScript({
615
+ bootstrapPath,
616
+ launcherPath,
617
+ logPath,
618
+ title
619
+ });
620
+ await desktop.files.write(bootstrapPath, bootstrapScript, { requestTimeoutMs });
621
+ await desktop.files.write(launcherPath, launcherScript, { requestTimeoutMs });
622
+ await runDesktopCommand(desktop, `chmod +x ${shellQuote(bootstrapPath)} ${shellQuote(launcherPath)}`, {
623
+ requestTimeoutMs,
624
+ timeoutMs: 30_000
625
+ });
626
+ await runDesktopCommand(desktop, `bash ${shellQuote(launcherPath)}`, {
627
+ requestTimeoutMs,
628
+ timeoutMs: 30_000
629
+ });
630
+ await desktop.wait(1200).catch(() => undefined);
631
+ await runDesktopCommand(desktop, buildRemoteFocusCommand(title), {
632
+ requestTimeoutMs,
633
+ timeoutMs: 10_000
634
+ }).catch(() => undefined);
635
+ return {
636
+ codexMode: "tui-attempted",
637
+ launcherPath,
638
+ logPath,
639
+ mimeticPackageUploaded: Boolean(localPackage),
640
+ nestedObserverPath,
641
+ status: "started",
642
+ tail: [
643
+ "Visible E2B bootstrap terminal launched.",
644
+ "The terminal clones the public repo, installs this local mimetic-cli package tarball when available, runs nested Mimetic proof commands, attempts Codex TUI, then opens the nested Observer in Chrome.",
645
+ baseTail
646
+ ].join("\n")
647
+ };
648
+ }
649
+ catch (error) {
650
+ return {
651
+ codexMode: "tui-attempted",
652
+ launcherPath,
653
+ logPath,
654
+ mimeticPackageUploaded: Boolean(localPackage),
655
+ nestedObserverPath,
656
+ status: "failed",
657
+ tail: [
658
+ "Bootstrap launcher failed before the remote terminal could start.",
659
+ baseTail,
660
+ `error: ${compactError(error)}`
661
+ ].join("\n")
662
+ };
663
+ }
664
+ }
665
+ function buildRemoteBootstrapScript(args) {
666
+ const repoUrl = `https://github.com/${args.assignment.repo}.git`;
667
+ const runId = `nested-${args.token}`;
668
+ return `#!/usr/bin/env bash
669
+ set -Eeuo pipefail
670
+ export TERM=xterm-256color
671
+ export MIMETIC_PUBLIC_SAFE=1
672
+ ROOT_DIR=${shellQuote(args.rootDir)}
673
+ APP_DIR="$ROOT_DIR/repo"
674
+ LOG_PATH=${shellQuote(args.logPath)}
675
+ NESTED_OBSERVER=${shellQuote(args.nestedObserverPath)}
676
+ REMOTE_PACKAGE=${args.remotePackagePath ? shellQuote(args.remotePackagePath) : "''"}
677
+ mkdir -p "$ROOT_DIR"
678
+ touch "$LOG_PATH"
679
+ exec > >(tee -a "$LOG_PATH") 2>&1
680
+
681
+ echo "== mimetic oss meta-lab bootstrap =="
682
+ echo "repo=${args.assignment.repo}"
683
+ echo "public_safe=1"
684
+ echo "E2B_API_KEY=$([[ -n "\${E2B_API_KEY:-}" ]] && echo present || echo missing)"
685
+ echo "OPENAI_API_KEY=$([[ -n "\${OPENAI_API_KEY:-}" ]] && echo present || echo missing)"
686
+ echo
687
+
688
+ need() {
689
+ if ! command -v "$1" >/dev/null 2>&1; then
690
+ echo "missing command: $1"
691
+ return 1
692
+ fi
693
+ }
694
+
695
+ ensure_node() {
696
+ local major=0
697
+ if command -v node >/dev/null 2>&1; then
698
+ major="$(node -e 'console.log(Number(process.versions.node.split(".")[0]))' 2>/dev/null || echo 0)"
699
+ fi
700
+
701
+ if command -v node >/dev/null 2>&1 && command -v npm >/dev/null 2>&1 && [[ "$major" -ge 20 ]]; then
702
+ return 0
703
+ fi
704
+
705
+ echo "node_or_npm=missing_or_too_old"
706
+ if command -v apt-get >/dev/null 2>&1 && command -v sudo >/dev/null 2>&1; then
707
+ echo "installing nodejs/npm via nodesource"
708
+ sudo -n apt-get update
709
+ sudo -n apt-get install -y ca-certificates curl gnupg
710
+ curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
711
+ sudo -n apt-get install -y nodejs
712
+ fi
713
+ }
714
+
715
+ need git
716
+ ensure_node
717
+ need node
718
+ need npm
719
+
720
+ run_tui() {
721
+ local status=0
722
+ if [[ -r /dev/tty && -w /dev/tty ]]; then
723
+ timeout 90s "$@" </dev/tty >/dev/tty 2>&1 || status=$?
724
+ else
725
+ timeout 90s "$@" || status=$?
726
+ fi
727
+ echo "codex_tui_exit=$status"
728
+ return 0
729
+ }
730
+
731
+ rm -rf "$APP_DIR"
732
+ git clone --depth=1 ${shellQuote(repoUrl)} "$APP_DIR"
733
+ cd "$APP_DIR"
734
+ echo
735
+ echo "== repo fingerprint =="
736
+ git rev-parse --short HEAD || true
737
+ node --version || true
738
+ npm --version || true
739
+
740
+ echo
741
+ echo "== installing mimetic-cli =="
742
+ if [[ -n "$REMOTE_PACKAGE" && -f "$REMOTE_PACKAGE" ]]; then
743
+ npm i -D "$REMOTE_PACKAGE" --ignore-scripts --no-audit --no-fund
744
+ else
745
+ npm i -D mimetic-cli --ignore-scripts --no-audit --no-fund
746
+ fi
747
+
748
+ echo
749
+ echo "== mimetic init =="
750
+ npx mimetic init --yes
751
+
752
+ echo
753
+ echo "== nested mimetic proof =="
754
+ npx mimetic run --dry-run --run-id ${shellQuote(runId)}
755
+ npx mimetic verify --run latest
756
+ npx mimetic watch --run latest --detach --no-open
757
+
758
+ echo
759
+ echo "== optional codex tui attempt =="
760
+ if command -v codex >/dev/null 2>&1; then
761
+ run_tui codex --no-alt-screen -C "$APP_DIR" --sandbox danger-full-access --ask-for-approval never "You are a Mimetic OSS meta-lab actor. Inspect this public repo, inspect the Mimetic artifacts already generated here, and explain the best next persona/scenario work. Do not print secrets, do not commit, do not push, and do not file issues."
762
+ else
763
+ run_tui npx -y @openai/codex@latest --no-alt-screen -C "$APP_DIR" --sandbox danger-full-access --ask-for-approval never "You are a Mimetic OSS meta-lab actor. Inspect this public repo, inspect the Mimetic artifacts already generated here, and explain the best next persona/scenario work. Do not print secrets, do not commit, do not push, and do not file issues."
764
+ fi
765
+
766
+ echo
767
+ echo "== opening nested observer =="
768
+ if [[ -f "$NESTED_OBSERVER" ]]; then
769
+ if command -v google-chrome >/dev/null 2>&1; then
770
+ nohup google-chrome --no-first-run --no-default-browser-check --disable-default-apps --user-data-dir="$ROOT_DIR/chrome-profile" "file://$NESTED_OBSERVER" >/dev/null 2>&1 &
771
+ elif command -v firefox >/dev/null 2>&1; then
772
+ nohup firefox "file://$NESTED_OBSERVER" >/dev/null 2>&1 &
773
+ else
774
+ echo "No browser command found. Nested observer is at: $NESTED_OBSERVER"
775
+ fi
776
+ else
777
+ echo "Nested observer missing: $NESTED_OBSERVER"
778
+ fi
779
+
780
+ echo
781
+ echo "== bootstrap complete =="
782
+ echo "nested_observer=$NESTED_OBSERVER"
783
+ `;
784
+ }
785
+ function buildRemoteLauncherScript(args) {
786
+ const terminalCommand = `bash -lc ${shellQuote(`${args.bootstrapPath}; echo; echo 'Mimetic bootstrap finished. Leave this terminal open for review.'; exec bash`)}`;
787
+ return `#!/usr/bin/env bash
788
+ set -u
789
+ BOOTSTRAP=${shellQuote(args.bootstrapPath)}
790
+ LOG_PATH=${shellQuote(args.logPath)}
791
+ TITLE=${shellQuote(args.title)}
792
+ echo "launching visible terminal for $BOOTSTRAP" >> "$LOG_PATH"
793
+ if command -v xfce4-terminal >/dev/null 2>&1; then
794
+ nohup xfce4-terminal --hold --title "$TITLE" --command ${shellQuote(terminalCommand)} >> "$LOG_PATH" 2>&1 &
795
+ elif command -v xterm >/dev/null 2>&1; then
796
+ nohup xterm -T "$TITLE" -e ${shellQuote(terminalCommand)} >> "$LOG_PATH" 2>&1 &
797
+ else
798
+ echo "No GUI terminal found; running bootstrap headless." >> "$LOG_PATH"
799
+ nohup bash "$BOOTSTRAP" >> "$LOG_PATH" 2>&1 &
800
+ fi
801
+ `;
802
+ }
803
+ function buildRemoteFocusCommand(title) {
804
+ return `TITLE=${shellQuote(title)}
805
+ for attempt in $(seq 1 20); do
806
+ if command -v wmctrl >/dev/null 2>&1; then
807
+ wmctrl -a "$TITLE" >/dev/null 2>&1 && exit 0
808
+ fi
809
+ if command -v xdotool >/dev/null 2>&1; then
810
+ WIN="$(xdotool search --name "$TITLE" 2>/dev/null | head -n 1 || true)"
811
+ if [[ -n "$WIN" ]]; then
812
+ xdotool windowactivate "$WIN" >/dev/null 2>&1 && exit 0
813
+ fi
814
+ fi
815
+ sleep 0.25
816
+ done
817
+ exit 0`;
818
+ }
819
+ async function runDesktopCommand(desktop, command, options) {
820
+ const result = await desktop.commands.run(`bash -lc ${shellQuote(command)}`, options);
821
+ if (result.exitCode && result.exitCode !== 0) {
822
+ throw new Error([
823
+ `Remote command failed with exit code ${result.exitCode}.`,
824
+ `stdout=${result.stdout ?? ""}`,
825
+ `stderr=${result.stderr ?? ""}`
826
+ ].join("\n"));
827
+ }
828
+ return result;
829
+ }
830
+ async function packLocalMimeticPackage(cwd, runId) {
831
+ const packageRoot = moduleRoot;
832
+ const packDir = path.join(cwd, ".mimetic", "tmp", "oss-meta", runId, "package");
833
+ await mkdir(packDir, { recursive: true });
834
+ await execFileAsync("pnpm", ["build"], {
835
+ cwd: packageRoot,
836
+ env: process.env,
837
+ maxBuffer: 10 * 1024 * 1024
838
+ });
839
+ await execFileAsync("npm", ["pack", "--pack-destination", packDir], {
840
+ cwd: packageRoot,
841
+ env: process.env,
842
+ maxBuffer: 10 * 1024 * 1024
843
+ });
844
+ const files = await readdir(packDir);
845
+ const fileName = files.find((file) => /^mimetic-cli-.*\.tgz$/.test(file));
846
+ if (!fileName) {
847
+ throw new Error("npm pack did not produce a mimetic-cli tarball.");
848
+ }
849
+ const archivePath = path.join(packDir, fileName);
850
+ const archiveStat = await stat(archivePath);
851
+ return {
852
+ fileName,
853
+ path: archivePath,
854
+ sizeBytes: archiveStat.size
855
+ };
856
+ }
857
+ function toArrayBuffer(buffer) {
858
+ const copy = new ArrayBuffer(buffer.byteLength);
859
+ new Uint8Array(copy).set(buffer);
860
+ return copy;
861
+ }
862
+ function shellQuote(value) {
863
+ if (value.length === 0) {
864
+ return "''";
865
+ }
866
+ return `'${value.replaceAll("'", "'\"'\"'")}'`;
867
+ }
868
+ function formatLiveDesktopForResult(desktop) {
869
+ return {
870
+ ...(desktop.bootstrap ? { bootstrapStatus: desktop.bootstrap.status } : {}),
871
+ repo: desktop.repo,
872
+ ...(desktop.sandboxId ? { sandboxId: desktop.sandboxId } : {}),
873
+ streamId: desktop.streamId,
874
+ urlPresent: Boolean(desktop.url)
875
+ };
876
+ }
877
+ function missingLiveKeys(env) {
878
+ return ["E2B_API_KEY", "OPENAI_API_KEY"].filter((name) => !env[name]?.trim());
879
+ }
880
+ function readPositiveInt(value, fallback) {
881
+ if (!value || !/^\d+$/.test(value)) {
882
+ return fallback;
883
+ }
884
+ const parsed = Number.parseInt(value, 10);
885
+ return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : fallback;
886
+ }
887
+ function compactError(error) {
888
+ const message = error instanceof Error ? error.message : String(error);
889
+ return message.replace(/\s+/g, " ").slice(0, 240);
890
+ }
891
+ function makeMetaRunId() {
892
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
893
+ return `oss-meta-${stamp}-${randomBytes(4).toString("hex")}`;
894
+ }
895
+ function repoSlugToken(repo) {
896
+ return repo.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
897
+ }
898
+ async function writeJson(filePath, value) {
899
+ await writeFile(filePath, `${JSON.stringify(value, null, 2)}\n`, "utf8");
900
+ }
901
+ //# sourceMappingURL=oss-meta-lab.js.map