@turri-dev/cli 0.4.2 → 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 (99) 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/chat-commands.d.ts +2 -10
  35. package/dist/chat-commands.js +3 -57
  36. package/dist/chat-tab-header.d.ts +15 -0
  37. package/dist/chat-tab-header.js +78 -0
  38. package/dist/chat-tabs.d.ts +20 -0
  39. package/dist/chat-tabs.js +96 -0
  40. package/dist/chat-terminal.js +54 -8
  41. package/dist/chat-waiting.d.ts +4 -1
  42. package/dist/chat-waiting.js +7 -4
  43. package/dist/chats.d.ts +2 -0
  44. package/dist/cli.js +32 -14
  45. package/dist/config-edit.js +1 -0
  46. package/dist/config.d.ts +15 -2
  47. package/dist/config.js +57 -3
  48. package/dist/extension.js +140 -7
  49. package/dist/identity.js +2 -1
  50. package/dist/init-config.js +1 -0
  51. package/dist/loop-cli.js +5 -1
  52. package/dist/loop-tools.js +5 -1
  53. package/dist/new-project.d.ts +5 -0
  54. package/dist/new-project.js +11 -0
  55. package/dist/pi.js +2 -2
  56. package/dist/plain-code-blocks.d.ts +14 -0
  57. package/dist/plain-code-blocks.js +56 -0
  58. package/dist/pointer-hover.d.ts +12 -0
  59. package/dist/pointer-hover.js +44 -0
  60. package/dist/regenerate/command-check.js +80 -11
  61. package/dist/regenerate/jobs-tree.d.ts +1 -0
  62. package/dist/regenerate/jobs-tree.js +5 -1
  63. package/dist/regenerate/loop.js +9 -1
  64. package/dist/regenerate/side-panel.d.ts +4 -1
  65. package/dist/regenerate/side-panel.js +131 -22
  66. package/dist/regenerate/spec-map-view.d.ts +9 -1
  67. package/dist/regenerate/spec-map-view.js +22 -2
  68. package/dist/regenerate/test-scripts.d.ts +5 -0
  69. package/dist/regenerate/test-scripts.js +4 -0
  70. package/dist/reopen.d.ts +29 -0
  71. package/dist/reopen.js +47 -0
  72. package/dist/resume-line.d.ts +4 -1
  73. package/dist/resume-line.js +5 -2
  74. package/dist/setup.js +9 -1
  75. package/docs/README.md +2 -0
  76. package/docs/capture.md +191 -0
  77. package/docs/chats.md +6 -5
  78. package/docs/config.md +14 -2
  79. package/docs/development.md +4 -1
  80. package/docs/regenerating.md +1 -1
  81. package/docs/sandbox.md +2 -2
  82. package/docs/theming.md +2 -2
  83. package/docs/using.md +9 -1
  84. package/genome/capture/capture.md +26 -0
  85. package/genome/capture/check-conventions.md +5 -0
  86. package/genome/capture/check-reference.md +11 -0
  87. package/genome/capture/concepts.md +3 -0
  88. package/genome/capture/divide.md +9 -0
  89. package/genome/capture/feature.md +45 -0
  90. package/genome/capture/interface.md +9 -0
  91. package/genome/capture/modules.md +23 -0
  92. package/genome/capture/outline.md +11 -0
  93. package/genome/capture/readability.md +12 -0
  94. package/genome/capture/reference.md +10 -0
  95. package/genome/capture/split.md +9 -0
  96. package/genome/capture/survey.md +37 -0
  97. package/genome/capture/trial.md +18 -0
  98. package/genome/capture/verify.md +7 -0
  99. package/package.json +3 -3
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";
@@ -78,6 +84,7 @@ import { ignoredGuidance, keepGuidance, landedNote, pulseEndsBlock, SENTINEL, SE
78
84
  import { noticeDialogs, registerSentinel } from "./sentinel-chat.js";
79
85
  import { currentChat } from "./chat-scope.js";
80
86
  import { registerChats } from "./chat-commands.js";
87
+ import { buttonLabel, terminalPointer } from "./pointer-hover.js";
81
88
  import { turriIdentity } from "./environment.js";
82
89
  import { answerSideQuestion, askWithAsides, BTW_HOW, runningSkill, skillRunStarted, skillSessionText, transcriptOf } from "./btw.js";
83
90
  import { createJobRegistry, defaultParallelJobs, describeJob, formatDuration, pulseName, shouldWait, STOPPED_ON_REQUEST, } from "./regenerate/jobs.js";
@@ -548,6 +555,11 @@ function turriExtension(api, session, link) {
548
555
  };
549
556
  const notices = noticeDialogs(pi, session, link, contextNow);
550
557
  link.live({
558
+ openPlainPanel: () => {
559
+ const ctx = contextNow();
560
+ if (ctx?.hasUI)
561
+ sidePanelOf(jobs, cwd).open(ctx, "map", "beside");
562
+ },
551
563
  announce,
552
564
  landed,
553
565
  brief,
@@ -612,6 +624,7 @@ function turriExtension(api, session, link) {
612
624
  systemPrompt: conversationSystemPrompt(event.systemPrompt, host, [
613
625
  TOOLS_NOT_CLI,
614
626
  NEW_PROJECT,
627
+ CAPTURE_HINT,
615
628
  pulseEndsBlock(session.sentinelOn()),
616
629
  // Conformance tests - what they are, whether they are on here, and how they are turned on: every turn, read afresh.
617
630
  conformanceBlock(conformanceTestsOnIn(cwd)),
@@ -775,6 +788,8 @@ function turriExtension(api, session, link) {
775
788
  for (const controller of backgroundSkillRuns.values())
776
789
  controller.abort();
777
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);
778
793
  const startInBackground = (skill, params, plainFile, ctx) => {
779
794
  const key = `${cwd}\0${skill.name}`;
780
795
  const kind = scriptKindOfSkill(skill.name);
@@ -2286,7 +2301,7 @@ function sidePanelOf(jobs, cwd) {
2286
2301
  if (known !== undefined)
2287
2302
  return known;
2288
2303
  const self = {
2289
- open: (ctx, view) => openPanel(ctx, view),
2304
+ open: (ctx, view, placement) => openPanel(ctx, view, placement),
2290
2305
  shown: () => panel !== undefined && panel.keys,
2291
2306
  };
2292
2307
  sidePanels.set(jobs, self);
@@ -2324,7 +2339,7 @@ function sidePanelOf(jobs, cwd) {
2324
2339
  plan: () => workLoops.get(jobs)?.loop.mapPlan() ?? { files: [], codebases: [] },
2325
2340
  });
2326
2341
  /** Open the side panel - on the view named, or as it was left. */
2327
- const openPanel = (ctx, view) => {
2342
+ const openPanel = (ctx, view, placement) => {
2328
2343
  // Found: ctrl+h under the job panel stops breathing.
2329
2344
  keyPressed("peek");
2330
2345
  if (view !== undefined)
@@ -2337,7 +2352,10 @@ function sidePanelOf(jobs, cwd) {
2337
2352
  mapState.view = "pulses";
2338
2353
  }
2339
2354
  needsLooking.delete(jobs);
2355
+ if (placement === "beside")
2356
+ panelDocked = true;
2340
2357
  if (panel !== undefined) {
2358
+ panel.layOut();
2341
2359
  panel.keepChatFocus();
2342
2360
  panel.handle?.setHidden(false);
2343
2361
  panel.keys = true;
@@ -2406,6 +2424,8 @@ function sidePanelOf(jobs, cwd) {
2406
2424
  // Opened, it reads the files again at once: they may have changed while it was closed.
2407
2425
  specMap.refresh();
2408
2426
  const view = createSidePanel({
2427
+ pointer: terminalPointer(tui.terminal),
2428
+ tabLabel: (text, active, hovered, role) => buttonLabel(theme, text, active, hovered, role),
2409
2429
  jobs: () => shownJobs(jobs),
2410
2430
  earlier: earlierJobs,
2411
2431
  tree: jobsTree,
@@ -2451,7 +2471,7 @@ function sidePanelOf(jobs, cwd) {
2451
2471
  return focused !== null && focused !== component;
2452
2472
  },
2453
2473
  });
2454
- const entry = { view, close, keepChatFocus, keys: true };
2474
+ const entry = { view, close, keepChatFocus, layOut, keys: true };
2455
2475
  panel = entry;
2456
2476
  layOut();
2457
2477
  // Every key goes to the panel while it shows, whatever has the focus: a question the chat model asks in the
@@ -2529,7 +2549,7 @@ function sidePanelOf(jobs, cwd) {
2529
2549
  view.handleInput(data);
2530
2550
  tui.requestRender();
2531
2551
  },
2532
- handleMouse: (event) => view.handleMouse(event),
2552
+ handleMouse: (event) => view.handleMouse(panelBeside() > 0 ? { ...event, x: event.x - 2, width: event.width - 2 } : event),
2533
2553
  invalidate: () => view.invalidate(),
2534
2554
  dispose: () => {
2535
2555
  unlisten();
@@ -2658,6 +2678,117 @@ function registerCheckPlain(pi, cwd, dialogs, afterAnswer) {
2658
2678
  const SIDE_ENTRY = "turri_btw";
2659
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. */
2660
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
+ }
2661
2792
  /**
2662
2793
  * /btw, a question on the side (btw.ts): answered at once, even while a skill runs - pi runs a command mid-turn - and
2663
2794
  * shown in the transcript, never in a model's context.
@@ -2978,8 +3109,8 @@ function registerBranding(pi, skills) {
2978
3109
  (data.commit !== undefined ? theme.fg("dim", ` from a clone, ${data.commit}${data.changed ? " with changes" : ""}`) : ""),
2979
3110
  // A newer turri out, or one installed and hidden behind this one: said first, under the version it is about.
2980
3111
  ...(data.versions ?? []).map((line) => theme.fg("warning", line)),
2981
- // A key renamed is information; the rest are the person's to take out.
2982
- ...(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)),
2983
3114
  `${theme.fg("text", "the first coding agent with the power of ")}${brandPink(theme)("regenerative software")}`,
2984
3115
  // Where the settings are changed, without leaving the chat.
2985
3116
  theme.fg("muted", "configure with /settings"),
@@ -3005,6 +3136,8 @@ function registerBranding(pi, skills) {
3005
3136
  if (ctx.hasUI) {
3006
3137
  padTheScreen(ctx);
3007
3138
  animateJellyfish(ctx);
3139
+ // ***plain an agent shows in the chat, highlighted in the theme of the moment.
3140
+ highlightPlainCodeBlocks(() => ctx.ui.theme);
3008
3141
  }
3009
3142
  // Once a chat: it starts again each time it is shown.
3010
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
+ }
@@ -0,0 +1,12 @@
1
+ import type { Theme } from "@earendil-works/pi-coding-agent";
2
+ export type ButtonRole = "tab" | "new" | "close" | "panel";
3
+ export type ButtonPaint = (text: string, active: boolean, hovered: boolean, role: ButtonRole) => string;
4
+ /** The layout owns the padding, so the entire coloured surface is also the click target. */
5
+ export declare function buttonLabel(theme: Theme, text: string, active: boolean, hovered: boolean, role: ButtonRole): string;
6
+ /** pi sends moves to the component under the pointer but has no leave event. Share one hover target across the
7
+ * screen: if the next input is dispatched elsewhere the old highlight goes away. Redraw only on a change. */
8
+ export declare class PointerHover {
9
+ target: string | undefined;
10
+ dispatch<T>(dispatch: () => T, redraw: () => void): T;
11
+ }
12
+ export declare function terminalPointer(terminal: object): PointerHover;
@@ -0,0 +1,44 @@
1
+ import { colorToRgb, parseColor } from "@earendil-works/pi-tui";
2
+ const abyss = parseColor("#0a0f1a");
3
+ const white = parseColor("#f4f7f9");
4
+ const linear = (byte) => byte <= 10 ? byte / 3294.6 : ((byte / 255 + 0.055) / 1.055) ** 2.4;
5
+ function luminance(color) {
6
+ const { r, g, b } = colorToRgb(color);
7
+ return 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);
8
+ }
9
+ // The point at which white and abyss have equal contrast on a fill. Paint both sides explicitly: the
10
+ // terminal's own background can still be dark when the person picks the light theme (and vice versa).
11
+ const inkSwitch = Math.sqrt((luminance(abyss) + 0.05) * (luminance(white) + 0.05)) - 0.05;
12
+ /** The layout owns the padding, so the entire coloured surface is also the click target. */
13
+ export function buttonLabel(theme, text, active, hovered, role) {
14
+ if (role === "new" || active || hovered) {
15
+ const fill = theme.colors[role === "new" ? "success" : role === "close" && hovered ? "error" : "accent"];
16
+ return theme.style(text, { bg: fill, fg: luminance(fill) > inkSwitch ? abyss : white, bold: true, underline: hovered });
17
+ }
18
+ return theme.style(text, { bg: "selectedBg", fg: role === "panel" ? "accent" : "text", bold: role === "panel" });
19
+ }
20
+ /** pi sends moves to the component under the pointer but has no leave event. Share one hover target across the
21
+ * screen: if the next input is dispatched elsewhere the old highlight goes away. Redraw only on a change. */
22
+ export class PointerHover {
23
+ target;
24
+ dispatch(dispatch, redraw) {
25
+ const before = this.target;
26
+ this.target = undefined;
27
+ try {
28
+ return dispatch();
29
+ }
30
+ finally {
31
+ if (before !== this.target)
32
+ redraw();
33
+ }
34
+ }
35
+ }
36
+ const pointers = new WeakMap();
37
+ export function terminalPointer(terminal) {
38
+ let pointer = pointers.get(terminal);
39
+ if (pointer === undefined) {
40
+ pointer = new PointerHover();
41
+ pointers.set(terminal, pointer);
42
+ }
43
+ return pointer;
44
+ }
@@ -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));
@@ -54,6 +54,7 @@ export declare function jobsTreeRows(jobs: Job[], state: JobsTreeState): TreeRow
54
54
  export declare function jobsTreeLines(jobs: Job[], state: JobsTreeState, width: number, style: TranscriptStyle): {
55
55
  lines: string[];
56
56
  rowStarts: number[];
57
+ labelHeights: number[];
57
58
  rows: TreeRow[];
58
59
  };
59
60
  /** Keep the cursor's row in sight: scroll only as far as that takes. */