@turri-dev/cli 0.4.3-next.620bae9 → 0.4.3-next.8482fed

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 (78) hide show
  1. package/README.md +1 -0
  2. package/dist/background-skills.d.ts +4 -1
  3. package/dist/background-skills.js +9 -1
  4. package/dist/capture/agents.d.ts +361 -0
  5. package/dist/capture/agents.js +332 -0
  6. package/dist/capture/area.d.ts +58 -0
  7. package/dist/capture/area.js +197 -0
  8. package/dist/capture/assemble.d.ts +122 -0
  9. package/dist/capture/assemble.js +452 -0
  10. package/dist/capture/capture.d.ts +116 -0
  11. package/dist/capture/capture.js +1228 -0
  12. package/dist/capture/chat.d.ts +29 -0
  13. package/dist/capture/chat.js +94 -0
  14. package/dist/capture/checks.d.ts +142 -0
  15. package/dist/capture/checks.js +643 -0
  16. package/dist/capture/config.d.ts +13 -0
  17. package/dist/capture/config.js +60 -0
  18. package/dist/capture/interface.d.ts +71 -0
  19. package/dist/capture/interface.js +199 -0
  20. package/dist/capture/map.d.ts +56 -0
  21. package/dist/capture/map.js +530 -0
  22. package/dist/capture/progress.d.ts +108 -0
  23. package/dist/capture/progress.js +234 -0
  24. package/dist/capture/report.d.ts +75 -0
  25. package/dist/capture/report.js +267 -0
  26. package/dist/capture/scripts.d.ts +26 -0
  27. package/dist/capture/scripts.js +33 -0
  28. package/dist/capture/state.d.ts +296 -0
  29. package/dist/capture/state.js +43 -0
  30. package/dist/capture/trial.d.ts +34 -0
  31. package/dist/capture/trial.js +89 -0
  32. package/dist/capture-cli.d.ts +1 -0
  33. package/dist/capture-cli.js +77 -0
  34. package/dist/cli.js +32 -14
  35. package/dist/config-edit.js +1 -0
  36. package/dist/config.d.ts +15 -2
  37. package/dist/config.js +57 -3
  38. package/dist/extension.js +125 -3
  39. package/dist/identity.js +2 -1
  40. package/dist/init-config.js +1 -0
  41. package/dist/loop-cli.js +5 -1
  42. package/dist/loop-tools.js +5 -1
  43. package/dist/new-project.d.ts +5 -0
  44. package/dist/new-project.js +11 -0
  45. package/dist/pi.js +2 -2
  46. package/dist/plain-code-blocks.d.ts +14 -0
  47. package/dist/plain-code-blocks.js +56 -0
  48. package/dist/regenerate/command-check.js +80 -11
  49. package/dist/regenerate/loop.js +9 -1
  50. package/dist/regenerate/test-scripts.d.ts +5 -0
  51. package/dist/regenerate/test-scripts.js +4 -0
  52. package/dist/reopen.d.ts +29 -0
  53. package/dist/reopen.js +47 -0
  54. package/dist/setup.js +9 -1
  55. package/docs/README.md +2 -0
  56. package/docs/capture.md +191 -0
  57. package/docs/config.md +14 -2
  58. package/docs/development.md +4 -1
  59. package/docs/regenerating.md +1 -1
  60. package/docs/sandbox.md +2 -2
  61. package/docs/theming.md +1 -1
  62. package/docs/using.md +5 -1
  63. package/genome/capture/capture.md +26 -0
  64. package/genome/capture/check-conventions.md +5 -0
  65. package/genome/capture/check-reference.md +11 -0
  66. package/genome/capture/concepts.md +3 -0
  67. package/genome/capture/divide.md +9 -0
  68. package/genome/capture/feature.md +45 -0
  69. package/genome/capture/interface.md +9 -0
  70. package/genome/capture/modules.md +23 -0
  71. package/genome/capture/outline.md +11 -0
  72. package/genome/capture/readability.md +12 -0
  73. package/genome/capture/reference.md +10 -0
  74. package/genome/capture/split.md +9 -0
  75. package/genome/capture/survey.md +37 -0
  76. package/genome/capture/trial.md +18 -0
  77. package/genome/capture/verify.md +7 -0
  78. package/package.json +1 -1
package/dist/config.d.ts CHANGED
@@ -143,7 +143,7 @@ export interface ModelChoice {
143
143
  * The code fixer of a conformance run and the repair agent are coding agents; the unit-test and conformance arbiters
144
144
  * are both `arbiter`.
145
145
  */
146
- export declare const AGENT_ROLES: readonly ["chat", "sentinel", "planner", "diagnosis", "launch", "coding", "conformance", "explorer", "reviewer", "test-reviewer", "judge", "arbiter", "debugger"];
146
+ export declare const AGENT_ROLES: readonly ["chat", "sentinel", "planner", "capture", "diagnosis", "launch", "coding", "conformance", "explorer", "reviewer", "test-reviewer", "judge", "arbiter", "debugger"];
147
147
  export type AgentRole = (typeof AGENT_ROLES)[number];
148
148
  /**
149
149
  * How hard each role thinks when nothing names a level - not the config's `models:`, nor a `:level` on the model it is
@@ -399,7 +399,7 @@ export declare function unknownConfigKeys(root: string): Array<{
399
399
  * a key turri renamed in the file - information, nothing to do; `old-beside-new`, an old name left beside its new one,
400
400
  * doing nothing - take it out; `unknown`, keys turri does not read - take them out, or fix their spelling.
401
401
  */
402
- export type ConfigLineKind = "renamed" | "old-beside-new" | "unknown";
402
+ export type ConfigLineKind = "broken" | "renamed" | "old-beside-new" | "unknown";
403
403
  export interface ConfigLine {
404
404
  kind: ConfigLineKind;
405
405
  /** The file, from the project: `config.turri.yaml`, `config.turri.<module>.yaml`. */
@@ -412,4 +412,17 @@ export interface ConfigLine {
412
412
  * beside its new one - doing nothing - and each file with keys turri does not read.
413
413
  */
414
414
  export declare function configLines(root: string): ConfigLine[];
415
+ /**
416
+ * Why a config file does not parse - its line and what YAML says, a key set twice among them - or undefined when it
417
+ * parses or is not there. turri reads a config that does not parse as empty, every setting at its default, the models
418
+ * pi's own: said, never silently.
419
+ */
420
+ export declare function configFileProblem(path: string): string | undefined;
421
+ /** The config files of a project folder that do not parse - config.turri.yaml and each module's own - each with why. */
422
+ export declare function configProblems(root: string): Array<{
423
+ file: string;
424
+ text: string;
425
+ }>;
426
+ /** Why a project's config does not parse, in a sentence for a refusal - undefined when every file of it parses. */
427
+ export declare function brokenConfig(root: string): string | undefined;
415
428
  export {};
package/dist/config.js CHANGED
@@ -303,7 +303,7 @@ export const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhig
303
303
  * The code fixer of a conformance run and the repair agent are coding agents; the unit-test and conformance arbiters
304
304
  * are both `arbiter`.
305
305
  */
306
- export const AGENT_ROLES = ["chat", "sentinel", "planner", "diagnosis", "launch", "coding", "conformance", "explorer", "reviewer", "test-reviewer", "judge", "arbiter", "debugger"];
306
+ export const AGENT_ROLES = ["chat", "sentinel", "planner", "capture", "diagnosis", "launch", "coding", "conformance", "explorer", "reviewer", "test-reviewer", "judge", "arbiter", "debugger"];
307
307
  /**
308
308
  * How hard each role thinks when nothing names a level - not the config's `models:`, nor a `:level` on the model it is
309
309
  * given. The agents that do the work - write the code and the tests, explore, launch - think little: they work from a
@@ -321,12 +321,14 @@ export const ROLE_THINKING = {
321
321
  arbiter: "medium",
322
322
  debugger: "medium",
323
323
  planner: "medium",
324
+ capture: "medium",
324
325
  diagnosis: "medium",
325
326
  };
326
327
  /** The roles on the conversation's side: without their own entry they take the chat's model, not `default`. */
327
328
  // The launch is not: it follows steps - a script, a start command - and runs on the coding model, thinking low. Nor
328
329
  // is the diagnosis: a post-mortem of a job that failed, read by the person - it runs on the coding model, thinking medium.
329
- const CHAT_SIDE = ["chat", "sentinel", "planner"];
330
+ // Capture is too: it writes ***plain, as the chat does.
331
+ const CHAT_SIDE = ["chat", "sentinel", "planner", "capture"];
330
332
  function isThinkingLevel(value) {
331
333
  return typeof value === "string" && THINKING_LEVELS.includes(value);
332
334
  }
@@ -731,6 +733,7 @@ export function unknownConfigKeys(root) {
731
733
  * beside its new one - doing nothing - and each file with keys turri does not read.
732
734
  */
733
735
  export function configLines(root) {
736
+ const broken = configProblems(root).map((problem) => ({ kind: "broken", file: problem.file, text: `${problem.text} - so none of ${problem.file} applies: turri runs on its defaults and pi's, the models among them. Set each key once.` }));
734
737
  const renamed = renameOldKeys(root).map(({ file, from, to }) => ({ kind: "renamed", file, text: `${file}: ${from} is called ${to} now - turri renamed it there, its value kept.` }));
735
738
  const left = [];
736
739
  for (const file of namesIn(root).filter((name) => /^config\.turri(\.[^.]+)?\.yaml$/.test(name)).sort()) {
@@ -753,5 +756,56 @@ export function configLines(root) {
753
756
  file,
754
757
  text: `${file} has ${keys.length === 1 ? "a key" : "keys"} turri does not read - ${keys.join(", ")}: no setting turri has, so ${keys.length === 1 ? "it does" : "they do"} nothing. Take ${keys.length === 1 ? "it" : "them"} out, or see docs/config.md for the spelling.`,
755
758
  }));
756
- return [...renamed, ...left, ...unknown];
759
+ return [...broken, ...renamed, ...left, ...unknown];
760
+ }
761
+ /**
762
+ * Why a config file does not parse - its line and what YAML says, a key set twice among them - or undefined when it
763
+ * parses or is not there. turri reads a config that does not parse as empty, every setting at its default, the models
764
+ * pi's own: said, never silently.
765
+ */
766
+ export function configFileProblem(path) {
767
+ let text;
768
+ try {
769
+ if (!statSync(path).isFile())
770
+ return undefined;
771
+ text = readFileSync(path, "utf8");
772
+ }
773
+ catch {
774
+ return undefined;
775
+ }
776
+ const file = basename(path);
777
+ try {
778
+ const parsed = loadYaml(text);
779
+ if (parsed !== null && parsed !== undefined && (typeof parsed !== "object" || Array.isArray(parsed)))
780
+ return `${file} is not a list of settings, a key and its value a line`;
781
+ return undefined;
782
+ }
783
+ catch (error) {
784
+ const reason = error.reason;
785
+ const line = error.mark?.line;
786
+ const at = typeof line === "number" ? `, line ${line + 1}` : "";
787
+ const key = typeof line === "number" ? /^\s*([\w.-]+)\s*:/.exec(text.split("\n")[line] ?? "")?.[1] : undefined;
788
+ if (reason === "duplicated mapping key")
789
+ return `${file}${at}: ${key !== undefined ? `${key} is` : "a key is"} set twice`;
790
+ return `${file}${at} does not parse: ${typeof reason === "string" ? reason : error instanceof Error ? error.message.split("\n")[0] : String(error)}`;
791
+ }
792
+ }
793
+ /** The config files of a project folder that do not parse - config.turri.yaml and each module's own - each with why. */
794
+ export function configProblems(root) {
795
+ return namesIn(root)
796
+ // config.yaml only while turri reads it: until it writes config.turri.yaml, it may be another tool's.
797
+ .filter((name) => /^config\.turri(\.[^.]+)?\.yaml$/.test(name) || (name === LEGACY_CONFIG_FILE && usesLegacyConfig(root)))
798
+ .sort()
799
+ .flatMap((file) => {
800
+ const text = configFileProblem(join(root, file));
801
+ return text === undefined ? [] : [{ file, text }];
802
+ });
803
+ }
804
+ /** Why a project's config does not parse, in a sentence for a refusal - undefined when every file of it parses. */
805
+ export function brokenConfig(root) {
806
+ const problems = configProblems(root);
807
+ if (problems.length === 0)
808
+ return undefined;
809
+ return (`${problems.map((problem) => problem.text).join("; ")}. A config that does not parse is read as empty: none of it would apply - ` +
810
+ `not the models, not conformance tests, no other setting - and turri would run on its defaults and pi's. Fix it - each key set once - then ask again.`);
757
811
  }
package/dist/extension.js CHANGED
@@ -20,6 +20,12 @@ import { applyBedrockRegion } from "./bedrock-region.js";
20
20
  import { bannerWarnings } from "./turri-versions.js";
21
21
  import { CONFORMANCE_OFF_REFUSAL, conformanceBlock, conformanceTestsOn, conformanceTestsOnIn, turnOnConformanceTests } from "./conformance-switch.js";
22
22
  import { BACKGROUND_NOTE, doneLine, failedTask, ownChanges, runDetails, skillRunDelivery, startedText } from "./background-skills.js";
23
+ import { runCapture } from "./capture/capture.js";
24
+ import { captureEnded, captureFailed, captureGoesOn, captureOpenQuestion, captureRefusal, captureStartedText, readReopenedAfterCapture, reopenedAfterCapture } from "./capture/chat.js";
25
+ import { reportFile as captureReportFile } from "./capture/state.js";
26
+ import { canReopen, REOPENED_AFTER_CAPTURE, reopenIn } from "./reopen.js";
27
+ import { captureStatusLines } from "./capture/progress.js";
28
+ import { highlightPlainCodeBlocks } from "./plain-code-blocks.js";
23
29
  import { createAskUserTool } from "./tools.js";
24
30
  import { asksFromScratch, asksWholeChain, driftTool, endWait, fromWorkingDir, haltLaunched, haltTool, loopReply, startWait, toldByWaitingCall, MODEL_PARAM, regenerateTool, stopJob, WAIT_PARAM, whenBuildable, WORKING_DIR_PARAM } from "./loop-tools.js";
25
31
  import { createWebTools } from "./regenerate/web.js";
@@ -32,7 +38,7 @@ import { createSessionLaunches, launchedDir, launchedNote, replacedNote } from "
32
38
  import { describeLaunchLine, launchText } from "./launch-track.js";
33
39
  import { checkedSpecs } from "./sentinel-check.js";
34
40
  import { askedForCommandLine, refusal, selfInvocation, TOOLS_NOT_CLI } from "./self-invocation.js";
35
- import { NEW_PROJECT } from "./new-project.js";
41
+ import { CAPTURE_HINT, NEW_PROJECT } from "./new-project.js";
36
42
  import { describeResolution, resolveModel } from "./regenerate/model-names.js";
37
43
  import { checkPlainFile, formatCheckResults } from "./plain/check.js";
38
44
  import { checkPlainTool } from "./parse-tool.js";
@@ -618,6 +624,7 @@ function turriExtension(api, session, link) {
618
624
  systemPrompt: conversationSystemPrompt(event.systemPrompt, host, [
619
625
  TOOLS_NOT_CLI,
620
626
  NEW_PROJECT,
627
+ CAPTURE_HINT,
621
628
  pulseEndsBlock(session.sentinelOn()),
622
629
  // Conformance tests - what they are, whether they are on here, and how they are turned on: every turn, read afresh.
623
630
  conformanceBlock(conformanceTestsOnIn(cwd)),
@@ -781,6 +788,8 @@ function turriExtension(api, session, link) {
781
788
  for (const controller of backgroundSkillRuns.values())
782
789
  controller.abort();
783
790
  });
791
+ // An existing codebase captured into ***plain, in the background: the person starts it, never the chat's agent.
792
+ registerCapture(pi, cwd, skillRunEnds);
784
793
  const startInBackground = (skill, params, plainFile, ctx) => {
785
794
  const key = `${cwd}\0${skill.name}`;
786
795
  const kind = scriptKindOfSkill(skill.name);
@@ -2669,6 +2678,117 @@ function registerCheckPlain(pi, cwd, dialogs, afterAnswer) {
2669
2678
  const SIDE_ENTRY = "turri_btw";
2670
2679
  /** A message the person sent while a skill ran in the chat, read by the skill's agent: drawn as the message it is. */
2671
2680
  const SKILL_MESSAGE_ENTRY = "turri_skill_message";
2681
+ /** The capture's lines above the input while it runs. */
2682
+ const CAPTURE_WIDGET = "turri-capture";
2683
+ /**
2684
+ * /capture [path]: the codebase at path - the chat's folder by default - captured into ***plain in <path>/plain, in the
2685
+ * background and offline (docs/capture.md). A command alone: capture turns conformance tests on in the project it writes,
2686
+ * which the person alone does. One at a time; its end comes back to this chat as a background skill's does, its report
2687
+ * for the chat's agent to pass on.
2688
+ */
2689
+ function registerCapture(pi, cwd, ends) {
2690
+ let running;
2691
+ pi.on("session_shutdown", (event) => {
2692
+ if (event.reason === "quit")
2693
+ running?.controller.abort();
2694
+ });
2695
+ // turri opened again here, in the project a capture wrote: its report told in the first chat, once.
2696
+ pi.on("session_start", () => {
2697
+ const told = readReopenedAfterCapture(process.env[REOPENED_AFTER_CAPTURE]);
2698
+ delete process.env[REOPENED_AFTER_CAPTURE];
2699
+ if (told !== undefined)
2700
+ ends.put(captureEnded(cwd, { plainDir: cwd, reportFile: captureReportFile(cwd), summary: told.summary }));
2701
+ });
2702
+ pi.registerCommand("capture", {
2703
+ description: "Capture an existing codebase into ***plain, in the background - nothing is asked, and its report comes back here; a stopped one goes on: /capture [path] (this folder by default - the ***plain goes into <path>/plain)",
2704
+ handler: async (args, ctx) => {
2705
+ const command = `/capture ${args.trim()}`.trim();
2706
+ await echoCommand(pi, command);
2707
+ const refuse = (text) => shownAfterCommand(pi, ctx, command, text, "error", true);
2708
+ if (running !== undefined)
2709
+ return refuse(`A capture of ${running.root} is running already: its report comes back here when it ends. Nothing new was started.`);
2710
+ const root = resolve(cwd, args.trim() || ".");
2711
+ const refusal = captureRefusal(root);
2712
+ if (refusal !== undefined)
2713
+ return refuse(refusal);
2714
+ const controller = new AbortController();
2715
+ running = { root, controller };
2716
+ const model = conversationModel(ctx);
2717
+ shownAfterCommand(pi, ctx, command, captureStartedText(root, model, captureGoesOn(root)), "info", true);
2718
+ // Above the input while it runs: where it is, each agent at work and what it did last - a capture at work
2719
+ // is told from one that hangs.
2720
+ let status;
2721
+ let redrawNow;
2722
+ if (ctx.hasUI) {
2723
+ ctx.ui.setWidget(CAPTURE_WIDGET, (tui, theme) => {
2724
+ // The spinner and the clocks move.
2725
+ const redraw = setInterval(() => tui.requestRender(), 1000);
2726
+ redraw.unref?.();
2727
+ redrawNow = () => tui.requestRender();
2728
+ const style = {
2729
+ heading: (text) => theme.bold(theme.fg("accent", text)),
2730
+ done: (text) => theme.fg("success", text),
2731
+ now: (text) => theme.bold(theme.fg("accent", text)),
2732
+ muted: (text) => theme.fg("muted", text),
2733
+ };
2734
+ return {
2735
+ render: (width) => (status === undefined ? [] : captureStatusLines(status, { frame: spinner(Date.now()), now: Date.now(), width }, style)),
2736
+ invalidate: () => { },
2737
+ dispose: () => {
2738
+ clearInterval(redraw);
2739
+ redrawNow = undefined;
2740
+ },
2741
+ };
2742
+ });
2743
+ }
2744
+ const watch = (next) => {
2745
+ status = next;
2746
+ redrawNow?.();
2747
+ };
2748
+ // The captured project starts as the config in use here, with the chat's model and thinking of the moment, and the
2749
+ // coding model turri was started with, where it says otherwise.
2750
+ const codingModel = process.env[CODING_MODEL_ENV];
2751
+ const configured = {
2752
+ configFrom: cwd,
2753
+ ...(model !== undefined ? { model, harnessModel: `${model}:${pi.getThinkingLevel()}` } : {}),
2754
+ ...(codingModel !== undefined && codingModel !== "" ? { codingModel } : {}),
2755
+ };
2756
+ void captureConsole(() => runCapture({ root, signal: controller.signal, watch, ...configured }))
2757
+ .then(async ({ result }) => {
2758
+ if (ctx.hasUI)
2759
+ ctx.ui.setWidget(CAPTURE_WIDGET, undefined);
2760
+ // A chat works on the project of its own folder, and the capture wrote one of its own: turri in a terminal
2761
+ // can open again there, on the chat's model, the report told there.
2762
+ if (ctx.hasUI && canReopen()) {
2763
+ const question = captureOpenQuestion(cwd, result);
2764
+ const chatModel = conversationModel(ctx);
2765
+ const codingModel = process.env[CODING_MODEL_ENV];
2766
+ const args = [
2767
+ ...(chatModel !== undefined ? ["--model", chatModel] : []),
2768
+ "--thinking",
2769
+ pi.getThinkingLevel(),
2770
+ ...(codingModel !== undefined && codingModel !== "" ? ["--coding-model", codingModel] : []),
2771
+ ];
2772
+ if ((await ctx.ui.confirm(question.title, question.message)) && reopenIn(result.plainDir, { args, env: { [REOPENED_AFTER_CAPTURE]: reopenedAfterCapture(result.summary) } })) {
2773
+ ctx.shutdown();
2774
+ return;
2775
+ }
2776
+ }
2777
+ ends.put(captureEnded(cwd, result));
2778
+ })
2779
+ .catch((error) => {
2780
+ // Stopped as turri quits: nobody is left to tell.
2781
+ if (!controller.signal.aborted)
2782
+ ends.put(captureFailed(error));
2783
+ })
2784
+ .finally(() => {
2785
+ running = undefined;
2786
+ if (ctx.hasUI)
2787
+ ctx.ui.setWidget(CAPTURE_WIDGET, undefined);
2788
+ });
2789
+ },
2790
+ });
2791
+ }
2672
2792
  /**
2673
2793
  * /btw, a question on the side (btw.ts): answered at once, even while a skill runs - pi runs a command mid-turn - and
2674
2794
  * shown in the transcript, never in a model's context.
@@ -2989,8 +3109,8 @@ function registerBranding(pi, skills) {
2989
3109
  (data.commit !== undefined ? theme.fg("dim", ` from a clone, ${data.commit}${data.changed ? " with changes" : ""}`) : ""),
2990
3110
  // A newer turri out, or one installed and hidden behind this one: said first, under the version it is about.
2991
3111
  ...(data.versions ?? []).map((line) => theme.fg("warning", line)),
2992
- // A key renamed is information; the rest are the person's to take out.
2993
- ...(data.config ?? []).map((line) => theme.fg(line.kind === "renamed" ? "muted" : "warning", line.text)),
3112
+ // A key renamed is information; one that does not parse stops everything that reads it; the rest are the person's to take out.
3113
+ ...(data.config ?? []).map((line) => theme.fg(line.kind === "renamed" ? "muted" : line.kind === "broken" ? "error" : "warning", line.text)),
2994
3114
  `${theme.fg("text", "the first coding agent with the power of ")}${brandPink(theme)("regenerative software")}`,
2995
3115
  // Where the settings are changed, without leaving the chat.
2996
3116
  theme.fg("muted", "configure with /settings"),
@@ -3016,6 +3136,8 @@ function registerBranding(pi, skills) {
3016
3136
  if (ctx.hasUI) {
3017
3137
  padTheScreen(ctx);
3018
3138
  animateJellyfish(ctx);
3139
+ // ***plain an agent shows in the chat, highlighted in the theme of the moment.
3140
+ highlightPlainCodeBlocks(() => ctx.ui.theme);
3019
3141
  }
3020
3142
  // Once a chat: it starts again each time it is shown.
3021
3143
  if (bannered)
package/dist/identity.js CHANGED
@@ -42,7 +42,8 @@ const IDENTITY_BEFORE = [
42
42
  "regenerative software - you write ***plain with them and regenerate the code from it. Never say they write the",
43
43
  "***plain and you help: you write it, together. Not an assistant, and not a helper with specifications: ***plain is",
44
44
  "the language the software is written in, and naming it is the point. Your replies are Markdown, where",
45
- "three asterisks start bold italics: write the name escaped, \\*\\*\\*plain, so it shows as ***plain.",
45
+ "three asterisks start bold italics: write the name escaped, \\*\\*\\*plain, so it shows as ***plain. ***plain you",
46
+ "show is fenced as ```plain, which highlights it.",
46
47
  "",
47
48
  "Speak as turri, in the first person - I, my pulses, my agents - to the person, in whole sentences. Never speak of",
48
49
  "turri in the third person, as if it were someone else, and never tell the person to tell or ask turri something:",
@@ -350,6 +350,7 @@ export function quickStartConfig(vendor = "other", bedrock, models) {
350
350
  `${column(`# chat: ${harness}`, 72)}# the conversation - as harness-model, which it wins over`,
351
351
  `${column(`# sentinel: ${harness}`, 72)}# the sentinel: checks every finished pulse and tests what is launched`,
352
352
  role("planner", harness, "cuts the work into pulses"),
353
+ role("capture", harness, "captures an existing codebase into ***plain"),
353
354
  role("diagnosis", harness, "looks into a pulse that failed for good"),
354
355
  role("launch", coding, "the launch agent: turri launch's, the chat's and launch-after-pulse's"),
355
356
  `${column(`# coding: { model: ${coding}, thinking: ${ROLE_THINKING.coding}, turn-limit: 180 }`, 72)}# as coding-model, which it wins over`,
package/dist/loop-cli.js CHANGED
@@ -2,7 +2,7 @@ import { sweepOrphanedGroups } from "./regenerate/shell.js";
2
2
  import { refuseTestPlainFile } from "./test-plain-files.js";
3
3
  import { createInterface } from "node:readline/promises";
4
4
  import { resolve, sep } from "node:path";
5
- import { configForSpec, inheritModel, modelOnly, modelSpec, projectModels, readProjectConfig, roleModel, ROLE_THINKING, splitModelSpec, } from "./config.js";
5
+ import { brokenConfig, configForSpec, inheritModel, modelOnly, modelSpec, projectModels, readProjectConfig, roleModel, ROLE_THINKING, splitModelSpec, } from "./config.js";
6
6
  import { PACKAGE_ROOT } from "./environment.js";
7
7
  import { c } from "./module-report.js";
8
8
  import { describeTurnIncident, onModelEvent } from "./regenerate/activity.js";
@@ -26,6 +26,10 @@ import { configKeyOptions, optionValue } from "./cli-options.js";
26
26
  export async function runLoop(options) {
27
27
  const plainFile = resolve(options.plainFile);
28
28
  refuseTestPlainFile(plainFile);
29
+ // A config that does not parse is read as empty: refused, rather than every pulse run on defaults - pi's model among them.
30
+ const broken = brokenConfig(projectDirOf(plainFile));
31
+ if (broken !== undefined)
32
+ throw new Error(`Nothing was started: ${broken}`);
29
33
  // What a turri that was killed left running - commands' process groups - stopped before anything starts.
30
34
  const orphans = sweepOrphanedGroups();
31
35
  if (orphans > 0)
@@ -3,7 +3,7 @@ import { refuseTestPlainFile } from "./test-plain-files.js";
3
3
  import { basename, relative, resolve } from "node:path";
4
4
  import { defineTool } from "@earendil-works/pi-coding-agent";
5
5
  import { Type } from "typebox";
6
- import { CONFIG_FILE, readProjectConfig, moduleConfigFile, configModuleFor, moduleConfigsOf, withConfigModule } from "./config.js";
6
+ import { brokenConfig, CONFIG_FILE, readProjectConfig, moduleConfigFile, configModuleFor, moduleConfigsOf, withConfigModule } from "./config.js";
7
7
  import { checkPlainFile, formatCheckResults } from "./plain/check.js";
8
8
  import { describeDrift, describeModules } from "./regenerate/loop.js";
9
9
  import { describeJob, pulseName } from "./regenerate/jobs.js";
@@ -34,6 +34,10 @@ export const MODEL_PARAM = Type.Optional(Type.String({
34
34
  */
35
35
  export function unbuildableConfig(plainFile) {
36
36
  const root = projectDirOf(plainFile);
37
+ // A config that does not parse is read as empty: built with it, every pulse would run on defaults - pi's model among them.
38
+ const broken = brokenConfig(root);
39
+ if (broken !== undefined)
40
+ return broken;
37
41
  let own;
38
42
  try {
39
43
  own = configModuleFor(plainFile);
@@ -3,3 +3,8 @@
3
3
  * Spring Boot" - and the chat writes the ***plain itself, here, with no skill, regenerating from the first functional spec.
4
4
  */
5
5
  export declare const NEW_PROJECT: string;
6
+ /**
7
+ * Bringing an existing codebase under ***plain: the person starts /capture, never the chat - it runs a while, and turns
8
+ * conformance tests on in the project it writes.
9
+ */
10
+ export declare const CAPTURE_HINT: string;
@@ -29,3 +29,14 @@ export const NEW_PROJECT = [
29
29
  "go on, or what to change, and every change after is ***plain you write and regenerate.",
30
30
  "</new-project>",
31
31
  ].join("\n");
32
+ /**
33
+ * Bringing an existing codebase under ***plain: the person starts /capture, never the chat - it runs a while, and turns
34
+ * conformance tests on in the project it writes.
35
+ */
36
+ export const CAPTURE_HINT = [
37
+ "<capture>",
38
+ "When the person wants an existing codebase brought under ***plain - written down as ***plain, to work on from then on",
39
+ "instead of the code - tell them /capture [path] does it: in the background, asking nothing, into <path>/plain, with a",
40
+ "report of what it decided. Only they start it; you cannot.",
41
+ "</capture>",
42
+ ].join("\n");
package/dist/pi.js CHANGED
@@ -237,8 +237,8 @@ export function providerRetryDelay(attempt, random = Math.random) {
237
237
  }
238
238
  /** How long a request to the model may go without anything coming back before the provider is said to be stalling; 0 never. */
239
239
  export const PROVIDER_STALL_MS = Number(process.env.TURRI_PROVIDER_STALL ?? 120) * 1000;
240
- /** A provider error that passes: overloaded, rate limited, unreachable, timed out. */
241
- const TRANSIENT_PROVIDER_ERROR = /\b(429|500|502|503|504|529)\b|overloaded|high demand|rate.?limit|too many requests|unavailable|fetch failed|network|connection|timed? ?out|ECONNRESET|socket|terminated/i;
240
+ /** A provider error that passes: overloaded, rate limited, unreachable, timed out, its stream cut off part-way. */
241
+ const TRANSIENT_PROVIDER_ERROR = /\b(429|500|502|503|504|529)\b|overloaded|high demand|rate.?limit|too many requests|unavailable|fetch failed|network|connection|timed? ?out|ECONNRESET|socket|terminated|truncated|stream ended/i;
242
242
  /** Wait, unless the job is stopped first. */
243
243
  async function waitOrStop(ms) {
244
244
  const stop = currentStopSignal();
@@ -0,0 +1,14 @@
1
+ import { type PlainRole } from "./plain/highlight.ts";
2
+ export declare function isPlainLanguage(lang: string | undefined): boolean;
3
+ /** Whether a fenced block is ***plain: fenced as plain, or fenced with no language around a section's header. */
4
+ export declare function isPlainBlock(lang: string | undefined, text: string): boolean;
5
+ /** Lines of ***plain, each piece painted by its role; the text around them in `rest`. */
6
+ export declare function highlightPlain(code: string, paint: (role: PlainRole, text: string) => string, rest?: (text: string) => string): string[];
7
+ /** What a theme says of itself that the palette needs: dark or light, and how many colours the terminal has. */
8
+ type ThemeLike = {
9
+ appearance?: "dark" | "light";
10
+ getColorMode?(): string;
11
+ };
12
+ /** From now on, a ***plain block in the chat is highlighted - in the colours of the theme `theme` gives at the time. */
13
+ export declare function highlightPlainCodeBlocks(theme: () => ThemeLike | undefined): void;
14
+ export {};
@@ -0,0 +1,56 @@
1
+ import { Markdown } from "@earendil-works/pi-tui";
2
+ import { highlightLines, roleOf } from "./plain/highlight.js";
3
+ import { plainPaint } from "./regenerate/plain-palette.js";
4
+ /**
5
+ * A fenced block of ***plain in the chat - ```plain, as an agent shows a module, or a fence with no language around
6
+ * a section's header - highlighted as turri highlights ***plain everywhere else: by its own grammar
7
+ * (plain/highlight.ts), in the colours of a ***plain diff (plain-palette.ts). pi highlights a code block through highlight.js, which knows no ***plain, and has no hook for
8
+ * a language of an extension's: so pi-tui's Markdown is patched, as chat-terminal.ts patches pi's screen - a ***plain
9
+ * block drawn with a highlighter of turri's in place of the theme's, every other block as pi draws it.
10
+ */
11
+ /** The fence's languages that are ***plain. */
12
+ const PLAIN_LANGUAGES = new Set(["plain", "***plain"]);
13
+ export function isPlainLanguage(lang) {
14
+ return lang !== undefined && PLAIN_LANGUAGES.has(lang.trim().toLowerCase());
15
+ }
16
+ /** A section's header on a line of its own - `***functional specs***` - which nothing but ***plain writes. */
17
+ const SECTION_HEADER = /^\*\*\*[a-z][a-z ]*\*\*\*[ \t]*$/m;
18
+ /** Whether a fenced block is ***plain: fenced as plain, or fenced with no language around a section's header. */
19
+ export function isPlainBlock(lang, text) {
20
+ return isPlainLanguage(lang) || ((lang ?? "").trim() === "" && SECTION_HEADER.test(text));
21
+ }
22
+ /** Lines of ***plain, each piece painted by its role; the text around them in `rest`. */
23
+ export function highlightPlain(code, paint, rest = (text) => text) {
24
+ return highlightLines(code.split("\n")).map((tokens) => tokens
25
+ .map((token) => {
26
+ const role = roleOf(token.scopes);
27
+ return role !== undefined ? paint(role, token.text) : rest(token.text);
28
+ })
29
+ .join(""));
30
+ }
31
+ let themeNow = () => undefined;
32
+ let patched = false;
33
+ /** From now on, a ***plain block in the chat is highlighted - in the colours of the theme `theme` gives at the time. */
34
+ export function highlightPlainCodeBlocks(theme) {
35
+ themeNow = theme;
36
+ if (patched)
37
+ return;
38
+ patched = true;
39
+ const prototype = Markdown.prototype;
40
+ const renderToken = prototype.renderToken;
41
+ prototype.renderToken = function (token, ...rest) {
42
+ const theme = this.theme;
43
+ const current = themeNow();
44
+ if (token.type !== "code" || !isPlainBlock(token.lang, token.text ?? "") || current === undefined)
45
+ return renderToken.call(this, token, ...rest);
46
+ const paint = plainPaint(current);
47
+ // Drawn by pi, with turri's highlighter in the theme's place for this block alone.
48
+ this.theme = { ...theme, highlightCode: (code) => highlightPlain(code, paint.syntax, theme.codeBlock) };
49
+ try {
50
+ return renderToken.call(this, token, ...rest);
51
+ }
52
+ finally {
53
+ this.theme = theme;
54
+ }
55
+ };
56
+ }
@@ -54,12 +54,50 @@ const INSTALLER_FILE = /\.(run|pkg|msi|dmg)$/i;
54
54
  function words(segment) {
55
55
  return (segment.match(/"[^"]*"|'[^']*'|[^\s"']+(?:(?:"[^"]*"|'[^']*')[^\s"']*)*/g) ?? []).map((word) => word.replace(/"([^"]*)"|'([^']*)'/g, "$1$2"));
56
56
  }
57
- /** The simple commands a command line is made of, in order: split on `;`, `&&`, `||`, `|`, `&`, newlines and subshells. */
57
+ /**
58
+ * The simple commands a command line is made of, in order: split on `;`, `&&`, `||`, `|`, `&`, newlines and subshells
59
+ * where the shell reads them - not in a string, so `grep "a\|b.run"` is one command - each cut from the command itself.
60
+ * A here-document's body that is a file's text is none.
61
+ */
58
62
  function segments(command) {
59
- return command
60
- .split(/&&|\|\||[;|&\n()`]|\$\(/)
61
- .map((part) => part.trim())
62
- .filter((part) => part !== "");
63
+ const code = shellCode(command);
64
+ const found = [];
65
+ let start = 0;
66
+ const cut = (end) => {
67
+ if (code.slice(start, end).trim() !== "")
68
+ found.push(command.slice(start, end).trim());
69
+ };
70
+ for (const match of code.matchAll(/&&|\|\||[;|&\n()`]|\$\(/g)) {
71
+ cut(match.index);
72
+ start = match.index + match[0].length;
73
+ }
74
+ cut(code.length);
75
+ return found;
76
+ }
77
+ /**
78
+ * The simple commands a command line runs: its own, and those of each script it hands a shell as a word - `bash -c
79
+ * "cd app; pip install --user x"`, `eval "..."` - which a string hides from the shell reading the line.
80
+ */
81
+ function simpleCommands(command, depth = 0) {
82
+ const own = segments(command);
83
+ if (depth >= 3)
84
+ return own;
85
+ return own.flatMap((segment) => {
86
+ const script = scriptOf(segment);
87
+ return script === undefined ? [segment] : [segment, ...simpleCommands(script, depth + 1)];
88
+ });
89
+ }
90
+ /** The script a simple command hands a shell to run: `sh -c '<script>'`, `bash -lc "<script>"`, `eval <script>`. */
91
+ function scriptOf(segment) {
92
+ const found = programOf(segment);
93
+ if (found === undefined)
94
+ return undefined;
95
+ if (found.program === "eval")
96
+ return found.args.length > 0 ? found.args.join(" ") : undefined;
97
+ if (!/^(ba|z|da|k)?sh$/.test(found.program))
98
+ return undefined;
99
+ const at = found.args.findIndex((arg) => /^-[a-zA-Z]*c[a-zA-Z]*$/.test(arg));
100
+ return at === -1 ? undefined : found.args[at + 1];
63
101
  }
64
102
  /** A simple command's program and arguments, past assignments, wrappers and their own options. */
65
103
  function programOf(segment) {
@@ -169,9 +207,9 @@ function systemSettingIn(segment) {
169
207
  * an agent, not the chat, not a launch - what the machine lacks is the person's to install, in their own words.
170
208
  */
171
209
  export function machineChange(command) {
172
- if (PIPED_DOWNLOAD.test(command) || RUN_DOWNLOAD.test(command))
210
+ if (runsDownload(command))
173
211
  return "it runs a script downloaded from the web";
174
- for (const segment of segments(command)) {
212
+ for (const segment of simpleCommands(command)) {
175
213
  const why = installIn(segment) ?? systemSettingIn(segment);
176
214
  if (why !== undefined)
177
215
  return why;
@@ -241,9 +279,40 @@ export function machineChangeReason(why) {
241
279
  "the same tool (python for python3), a version manager's folder - and use it, or give the person the exact command to " +
242
280
  "run themselves, and go on once they say it is done.");
243
281
  }
244
- /** Downloads run as programs: a script piped to a shell, or run from a download. */
245
- const PIPED_DOWNLOAD = /\b(curl|wget)\b[^|;&\n]*\|\s*(sudo\s+(-\S+\s+)*)?((ba|z|da|k)?sh|python\d*|perl|ruby|node)\b/;
282
+ /** Downloads run as programs: a script piped to a shell or an interpreter, or run from a download. */
283
+ const PIPED_DOWNLOAD = /\b(?:curl|wget)\b[^|;&\n]*\|\s*(?:sudo\s+(?:-\S+\s+)*)?((?:ba|z|da|k)?sh|python[\d.]*|perl|ruby|node)\b([^|;&\n]*)/g;
246
284
  const RUN_DOWNLOAD = /\b(ba|z|da|k)?sh\s+(-\w+\s+)*["']?\$\(\s*(curl|wget)\b|<\(\s*(curl|wget)\b/;
285
+ /**
286
+ * The option that gives an interpreter its code on the command line, so what is piped to it is data it reads - `curl
287
+ * localhost:8000/links | python3 -c 'import json, sys; ...'`, `| python3 -m json.tool`, `| node -e`, `| perl -ne`.
288
+ */
289
+ const CODE_OPTIONS = [
290
+ [/^(ba|z|da|k)?sh$/, /^-[a-zA-Z]*c[a-zA-Z]*$/],
291
+ [/^python/, /^-[a-zA-Z]*[cm]$/],
292
+ [/^node$/, /^(-[a-zA-Z]*[ep][a-zA-Z]*|--eval|--print)$/],
293
+ [/^(perl|ruby)$/, /^-[a-zA-Z]*[eE][a-zA-Z]*$/],
294
+ ];
295
+ /** Whether a command line runs what it downloads: piped to a shell or an interpreter that runs it, or run from it. */
296
+ function runsDownload(command) {
297
+ if (RUN_DOWNLOAD.test(command))
298
+ return true;
299
+ for (const match of shellCode(command).matchAll(PIPED_DOWNLOAD)) {
300
+ const interpreter = match[1];
301
+ const options = [];
302
+ for (const word of words(match[2])) {
303
+ if (!word.startsWith("-") || word === "-")
304
+ break;
305
+ options.push(word);
306
+ }
307
+ const code = CODE_OPTIONS.find(([program]) => program.test(interpreter))?.[1];
308
+ if (code === undefined || !options.some((option) => code.test(option)))
309
+ return true;
310
+ }
311
+ return simpleCommands(command).some((segment) => {
312
+ const script = scriptOf(segment);
313
+ return script !== undefined && script !== command && runsDownload(script);
314
+ });
315
+ }
247
316
  /** Killing by name, or by what holds a port. */
248
317
  const KILL_BY_LOOKUP = /\bkill\b[^;&|\n]*(\$\(|`)\s*(lsof|fuser|pgrep|pidof|ss|netstat)\b/;
249
318
  const LOOKUP_TO_KILL = /\b(lsof|pgrep|pidof|fuser|ss|netstat)\b[^;&\n]*\|\s*xargs\s+(-\S+\s+)*kill\b/;
@@ -452,11 +521,11 @@ export function checkCommand(command, fence) {
452
521
  return refusal("record", `${RECORD_FILE} is the harness's record of what the code is built from: no agent reads or writes it, and nothing in it is yours to go by.`);
453
522
  }
454
523
  // Installs and kills, a simple command at a time; downloads run as programs, on the whole line.
455
- if (PIPED_DOWNLOAD.test(command) || RUN_DOWNLOAD.test(command))
524
+ if (runsDownload(command))
456
525
  return refusal("install", installReason("it runs a script downloaded from the web"));
457
526
  if (KILL_BY_LOOKUP.test(command) || LOOKUP_TO_KILL.test(command))
458
527
  return refusal("kill", killReason());
459
- for (const segment of segments(command)) {
528
+ for (const segment of simpleCommands(command)) {
460
529
  const why = installIn(segment);
461
530
  if (why !== undefined)
462
531
  return refusal("install", installReason(why));
@@ -1151,7 +1151,8 @@ export function createWorkLoop(options) {
1151
1151
  const own = (jobs) => (jobs ?? []).filter((job) => job !== running);
1152
1152
  // A track being planned again shows as that, not as its plan before - and a module asked for, from that moment, as
1153
1153
  // its code being planned: its code deleted, what is left worked out, before the planner runs.
1154
- const planningTrack = state.running === undefined ? (state.planning ?? (preparing.has(tipEntry(state).moduleName) ? "code" : undefined)) : undefined;
1154
+ // One waiting for a module below it is shown waiting, asked for or not: nothing plans it until that one is built.
1155
+ const planningTrack = state.running === undefined ? (state.planning ?? (preparing.has(tipEntry(state).moduleName) && state.waitsFor === undefined ? "code" : undefined)) : undefined;
1155
1156
  const replanning = planningTrack;
1156
1157
  const jobs = [
1157
1158
  ...(running !== undefined ? [running] : []),
@@ -1267,6 +1268,13 @@ export function createWorkLoop(options) {
1267
1268
  state.lookedAhead = undefined;
1268
1269
  // Asked for again: its conformance tests are written for every functional spec with scenarios, not only those conform named.
1269
1270
  state.conformanceOnly = undefined;
1271
+ // A module below it not built at all: it waits for that one, said at once - the looks go bottom first, each the
1272
+ // planner's time, and until its own it would show as being planned. Its look says it again, or moves it on.
1273
+ const below = state.running === undefined ? state.chain.slice(0, -1).find((entry) => modules.has(entry.buildDir) && !started(entry)) : undefined;
1274
+ if (below !== undefined && state.waitsFor === undefined) {
1275
+ state.waitsFor = below.moduleName;
1276
+ state.why = `waiting for ${below.moduleName}: the code it is built on is not built yet`;
1277
+ }
1270
1278
  }
1271
1279
  await tick();
1272
1280
  return [...new Set(states)].map(statusOf);
@@ -88,6 +88,11 @@ export declare function staticChecksOnly(run: {
88
88
  exitCode: number;
89
89
  timedOut?: boolean;
90
90
  }): boolean;
91
+ /** The skill that writes a testing script of a kind, and what the script is called in words. */
92
+ export declare function testingScriptSkill(kind: ScriptKind): {
93
+ skill: string;
94
+ what: string;
95
+ };
91
96
  /** The kind of testing script a skill writes, by its name - one that writes none, undefined. */
92
97
  export declare function scriptKindOfSkill(skill: string): ScriptKind | undefined;
93
98
  /** Raised before a build starts when the script that would decide it is done is missing. */