@turri-dev/cli 0.1.4-next.246fd84 → 0.1.4-next.5a94e68

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.
package/dist/ask.js CHANGED
@@ -9,6 +9,9 @@ import { PANEL_KEY } from "./regenerate/job-panel.js";
9
9
  export const OTHER_OPTION = "Something else…";
10
10
  export const CHAT_OPTION = "Chat about this";
11
11
  export const DONE_OPTION = "Done — that's all of them";
12
+ /** An option's box in a question of several, ticked and not. */
13
+ export const TICKED = "☑";
14
+ export const UNTICKED = "☐";
12
15
  export const DISMISSED = "The user dismissed the question without answering.";
13
16
  /** How an answer that is no answer starts: the person chose to talk about the question first. */
14
17
  export const CHAT_PREFIX = "The user has not answered this question yet: they chose to talk about it first.";
@@ -107,32 +110,48 @@ export async function runAsk(asked, io) {
107
110
  return choice;
108
111
  }
109
112
  }
110
- // Pick several: keep offering what is left until they say they are done.
111
- const chosen = [];
112
- let remaining = [...options];
113
- while (remaining.length > 0) {
114
- const title = chosen.length === 0 ? request.question : `${request.question} [so far: ${chosen.join(", ")}]`;
115
- const choice = await io.select(title, [...remaining, ...extras, DONE_OPTION], context);
116
- if (choice === undefined)
117
- break;
118
- if (choice === DONE_OPTION)
113
+ // Pick several: every option a box, ticked and unticked as it is chosen, until they say they are done. What they type
114
+ // is one more box, ticked - and can be unticked too. Something else, Chat about this and Done are no boxes.
115
+ const listed = [...options];
116
+ const ticked = new Set();
117
+ const picked = () => listed.filter((option) => ticked.has(option));
118
+ let at = 0;
119
+ for (;;) {
120
+ const rows = listed.map((option) => `${ticked.has(option) ? TICKED : UNTICKED} ${option}`);
121
+ const choice = await io.select(request.question, [...rows, ...extras, DONE_OPTION], context, at);
122
+ if (choice === undefined || choice === DONE_OPTION)
119
123
  break;
120
124
  if (choice === OTHER_OPTION) {
125
+ at = listed.length;
121
126
  const typed = await typeInstead();
122
- if (!typedNothing(typed))
123
- chosen.push(typed.trim());
127
+ if (typedNothing(typed))
128
+ continue;
129
+ const option = typed.trim();
130
+ if (!listed.includes(option))
131
+ listed.push(option);
132
+ ticked.add(option);
133
+ at = listed.indexOf(option);
124
134
  continue;
125
135
  }
126
136
  if (choice === CHAT_OPTION) {
137
+ at = listed.length + extras.indexOf(CHAT_OPTION);
127
138
  const said = await chatAbout();
128
139
  if (typedNothing(said))
129
140
  continue;
130
- return chatAnswer(said, chosen);
141
+ return chatAnswer(said, picked());
131
142
  }
132
- chosen.push(choice);
133
- remaining = remaining.filter((option) => option !== choice);
143
+ // A row, or - where the answer is typed, on the command line - an option by its text, or one more of their own.
144
+ const row = rows.indexOf(choice);
145
+ const option = row !== -1 ? listed[row] : choice.trim();
146
+ if (!listed.includes(option))
147
+ listed.push(option);
148
+ if (ticked.has(option))
149
+ ticked.delete(option);
150
+ else
151
+ ticked.add(option);
152
+ at = listed.indexOf(option);
134
153
  }
135
- return chosen.length > 0 ? chosen.join(", ") : DISMISSED;
154
+ return ticked.size > 0 ? picked().join(", ") : DISMISSED;
136
155
  }
137
156
  /**
138
157
  * While a question is open, what catches ctrl+h on the terminal's input: pi gives an extension's shortcut only the keys
@@ -1,4 +1,4 @@
1
- import { conformanceOption, overrideConfig, reviewOption, splitModelSpec } from "./config.js";
1
+ import { booleanOption, conformanceOption, overrideConfig, splitModelSpec } from "./config.js";
2
2
  /**
3
3
  * The command line of turri's commands: their words, and the options that stand for the config's own keys - kept apart
4
4
  * from the commands that use them, so a light one (doctor) reads them as a regenerate does without loading it.
@@ -51,19 +51,24 @@ export function optionValue(options, name) {
51
51
  }
52
52
  /**
53
53
  * The options that stand for the config's own keys - `--harness-model`, `--coding-model` (`--model`), `--judge-model`
54
- * and, as asked, `--review` and `--conformance-tests` - read as if config.turri.yaml had them, in their place in the
54
+ * and, as asked, `--review`, `--mutation-testing` and `--conformance-tests` - read as if config.turri.yaml had them, in their place in the
55
55
  * order the config resolves them in (overrideConfig): a run, or doctor, with them is the same as one with them in the
56
56
  * file. Exits on a value it cannot read.
57
57
  */
58
58
  export function configKeyOptions(options, take = {}) {
59
+ const flag = (name) => {
60
+ const given = take.review === true ? optionValue(options, name) : undefined;
61
+ const value = given !== undefined ? booleanOption(given) : undefined;
62
+ if (given !== undefined && value === undefined)
63
+ failOption(`--${name} takes true or false, not ${given}`);
64
+ return value;
65
+ };
59
66
  const tests = take.conformance === true ? optionValue(options, "conformance-tests") : undefined;
60
67
  const setting = tests !== undefined ? conformanceOption(tests) : undefined;
61
68
  if (tests !== undefined && setting === undefined)
62
69
  failOption(`--conformance-tests takes all, chosen, module or false, not ${tests}`);
63
- const reviewed = take.review === true ? optionValue(options, "review") : undefined;
64
- const review = reviewed !== undefined ? reviewOption(reviewed) : undefined;
65
- if (reviewed !== undefined && review === undefined)
66
- failOption(`--review takes true or false, not ${reviewed}`);
70
+ const review = flag("review");
71
+ const mutationTesting = flag("mutation-testing");
67
72
  const model = (name, key) => {
68
73
  const spec = optionValue(options, name);
69
74
  return spec !== undefined ? { [key]: splitModelSpec(spec) } : {};
@@ -74,6 +79,7 @@ export function configKeyOptions(options, take = {}) {
74
79
  ...model("judge-model", "judgeModel"),
75
80
  ...(setting !== undefined ? { conformanceTests: setting } : {}),
76
81
  ...(review !== undefined ? { review } : {}),
82
+ ...(mutationTesting !== undefined ? { mutationTesting } : {}),
77
83
  });
78
84
  }
79
85
  function failOption(message) {
@@ -59,6 +59,7 @@ export function settings(rules = []) {
59
59
  { key: "conformance-tests", about: "which functional specs get conformance tests", kind: "choice", options: ["all", "chosen", "module", "false"], unset: "all, where a module has test reqs", effect: "next-plan" },
60
60
  { key: "conformance-budget", about: "under conformance-tests: chosen or module, how many may be chosen - a count or a share", kind: "budget", options: ["10%", "30%", "50%", "5", "10"], unset: "no limit", effect: "next-plan" },
61
61
  { key: "review", about: "whether the code and its tests are reviewed once they pass", kind: "boolean", unset: "true", effect: "next-pulse" },
62
+ { key: "mutation-testing", about: "whether the coding agent and the reviewer can put a bug in the code for one test run (can_it_fail)", kind: "boolean", unset: "true", effect: "next-pulse" },
62
63
  { key: "allow-to-stop-jobs", about: "whether turri stops a running pulse the spec has moved on from", kind: "boolean", unset: "true", effect: "now" },
63
64
  { key: "release-after-pulse", about: "whether every pulse that lands code releases it", kind: "boolean", unset: "false", effect: "next-landing" },
64
65
  { key: "unittests-script", about: "the unit testing script, by path from the project root", kind: "path", unset: "the one run_unittests*.sh found", effect: "next-test-run" },
package/dist/config.js CHANGED
@@ -21,6 +21,7 @@ import { projectDirOf } from "./regenerate/paths.js";
21
21
  * conformance-tests: chosen # all, chosen (those with acceptance tests, and those the chooser picks after each pulse), module (the chooser picks, and plans, once the module is regenerated) or false (default: false)
22
22
  * conformance-budget: 30% # under chosen or module: how many functional specs a module may have chosen, beside those with acceptance tests - a count or a share (default: no limit)
23
23
  * review: false # review the code and its tests once they pass (default: true)
24
+ * mutation-testing: false # give the coding agent and the reviewer can_it_fail (default: true)
24
25
  * allow-to-stop-jobs: false # stop a running job the spec moved on from (default: true)
25
26
  * release-after-pulse: true # release what each pulse lands, as its last stage, before the next pulse (default: false)
26
27
  * rules-off: [integrations] # ***plain rules to leave out of the prompts, by name (default: none)
@@ -331,6 +332,7 @@ export const CONFIG_KEYS = {
331
332
  conformanceTests: "conformance-tests",
332
333
  conformanceBudget: "conformance-budget",
333
334
  review: "review",
335
+ mutationTesting: "mutation-testing",
334
336
  allowToStopJobs: "allow-to-stop-jobs",
335
337
  releaseAfterPulse: "release-after-pulse",
336
338
  unittestsScript: "unittests-script",
@@ -416,8 +418,8 @@ export function overrideConfig(overrides) {
416
418
  export function conformanceOption(value) {
417
419
  return conformanceSetting(value);
418
420
  }
419
- /** `--review <value>`: the config's own, true or false. Undefined for anything else. */
420
- export function reviewOption(value) {
421
+ /** `--review <value>`, `--mutation-testing <value>`: the config's own, true or false. Undefined for anything else. */
422
+ export function booleanOption(value) {
421
423
  const word = value.trim().toLowerCase();
422
424
  return word === "true" ? true : word === "false" ? false : undefined;
423
425
  }
@@ -487,6 +489,7 @@ function readConfigFile(path) {
487
489
  conformanceTests: conformanceSetting(conformance),
488
490
  conformanceBudget: budgetSetting(raw[CONFIG_KEYS.conformanceBudget]),
489
491
  review: typeof raw[CONFIG_KEYS.review] === "boolean" ? raw[CONFIG_KEYS.review] : undefined,
492
+ mutationTesting: typeof raw[CONFIG_KEYS.mutationTesting] === "boolean" ? raw[CONFIG_KEYS.mutationTesting] : undefined,
490
493
  allowToStopJobs: typeof raw[CONFIG_KEYS.allowToStopJobs] === "boolean" ? raw[CONFIG_KEYS.allowToStopJobs] : undefined,
491
494
  releaseAfterPulse: typeof raw[CONFIG_KEYS.releaseAfterPulse] === "boolean" ? raw[CONFIG_KEYS.releaseAfterPulse] : undefined,
492
495
  unittestsScript: text(raw[CONFIG_KEYS.unittestsScript]),
package/dist/extension.js CHANGED
@@ -16,7 +16,7 @@ import { readScript, scriptAgainstMachine, stackOnMachine, toolchainsBlock } fro
16
16
  import { sandboxAvailable, sandboxSummary } from "./regenerate/os-sandbox.js";
17
17
  import { findTestScripts } from "./regenerate/test-scripts.js";
18
18
  import { createAskUserTool } from "./tools.js";
19
- import { asksFromScratch, driftTool, fromWorkingDir, haltTool, loopReply, MODEL_PARAM, regenerateTool, stopJob, WAIT_PARAM, WORKING_DIR_PARAM } from "./loop-tools.js";
19
+ import { asksFromScratch, asksWholeChain, driftTool, fromWorkingDir, haltTool, loopReply, MODEL_PARAM, regenerateTool, stopJob, WAIT_PARAM, WORKING_DIR_PARAM } from "./loop-tools.js";
20
20
  import { createWebTools } from "./regenerate/web.js";
21
21
  import { describeGates, interruptedRun, runSkill } from "./genome.js";
22
22
  import { skillStatus } from "./skill.js";
@@ -41,7 +41,7 @@ import { createJobsTreeState, selectJob } from "./regenerate/jobs-tree.js";
41
41
  import { describeDiagnosis, diagnoseFailure } from "./regenerate/diagnose.js";
42
42
  import { HISTORY_DIR, historyLog, historyShow } from "./regenerate/lineage.js";
43
43
  import { defaultBuildDir } from "./regenerate/paths.js";
44
- import { describeUsage } from "./regenerate/activity.js";
44
+ import { describeTurnIncident, describeUsage, onModelEvent } from "./regenerate/activity.js";
45
45
  import { describeSpecConflict } from "./regenerate/stop-report.js";
46
46
  import { inheritProviders, inheritThinkingLevel } from "./pi.js";
47
47
  import { beginCapture, captureConsole, describeCaptured, dropNoise } from "./quiet.js";
@@ -90,11 +90,12 @@ aside) {
90
90
  // The question, with what the asker gives to read for it - a brief to confirm - above it; what it said of its work
91
91
  // before asking is kept in its record, never put in the dialog.
92
92
  // A dialog of turri's own: a long brief scrolls above the question, and the options always show (question-dialog.ts).
93
- const dialog = (question, context, options) => ctx.ui.custom((tui, theme, _keybindings, done) => {
93
+ const dialog = (question, context, options, selected) => ctx.ui.custom((tui, theme, _keybindings, done) => {
94
94
  const shown = new QuestionDialog({
95
95
  question,
96
96
  ...(context !== undefined ? { context } : {}),
97
97
  ...(options !== undefined ? { options } : {}),
98
+ ...(selected !== undefined ? { selected } : {}),
98
99
  rows: () => tui.terminal.rows,
99
100
  style: { accent: (text) => theme.fg("accent", text), muted: (text) => theme.fg("muted", text), bold: (text) => theme.bold(text) },
100
101
  done: (answer) => {
@@ -108,7 +109,7 @@ aside) {
108
109
  return shown;
109
110
  });
110
111
  const asking = (asked) => runAsk(asked, {
111
- select: (title, options, context) => dialog(title, context, options),
112
+ select: (title, options, context, at) => dialog(title, context, options, at),
112
113
  input: (title, context) => dialog(title, context),
113
114
  });
114
115
  const bare = { ...request, said: undefined };
@@ -327,6 +328,19 @@ export default function (pi) {
327
328
  };
328
329
  pi.on("agent_end", endTurnCapture);
329
330
  pi.on("agent_settled", endTurnCapture);
331
+ // A pulse's provider failing and waited out, or a turn turri ended itself: said in the chat as it happens - the job
332
+ // panel's activity holds it too, but scrolls by.
333
+ let stopTurnIncidents;
334
+ pi.on("session_start", (_event, ctx) => {
335
+ stopTurnIncidents?.();
336
+ if (!ctx.hasUI)
337
+ return;
338
+ stopTurnIncidents = onModelEvent((event) => {
339
+ const line = describeTurnIncident(event);
340
+ if (line !== undefined)
341
+ ctx.ui.notify(event.job !== undefined ? `${event.job}: ${line}` : line, "warning");
342
+ });
343
+ });
330
344
  // What a turri that was killed left running - its commands' process groups - stopped as this one starts.
331
345
  const orphans = sweepOrphanedGroups();
332
346
  let orphansSaid = orphans === 0;
@@ -610,7 +624,7 @@ function registerRegenerate(pi, cwd, jobs) {
610
624
  // by the planner: one functional spec at a time, a few together or the whole module in one, as it judges. What
611
625
  // follows the module is guidance for that plan, in the person's words.
612
626
  pi.registerCommand("regenerate", {
613
- description: "Regenerate a module from its spec as it is now, in pulses the planner cuts - named functionalities though they did not change, or all of it from scratch: /regenerate [module | file.plain] [functionality ...] [from scratch] [how to cut the work]",
627
+ description: "Regenerate a module from its spec as it is now, in pulses the planner cuts - named functionalities though they did not change, or all of it from scratch, its whole chain too when asked: /regenerate [module | file.plain] [functionality ...] [from scratch [whole chain]] [how to cut the work]",
614
628
  handler: async (args, ctx) => {
615
629
  const command = `/regenerate ${args.trim()}`.trim();
616
630
  await echoCommand(pi, command);
@@ -652,13 +666,17 @@ function registerRegenerate(pi, cwd, jobs) {
652
666
  }
653
667
  // From scratch - started over, its code deleted - asked in the person's words: confirmed first, as it deletes.
654
668
  const scratch = asksFromScratch(guidance);
669
+ // The whole chain with it - "from scratch, the whole chain" - every module it requires built again from the bottom.
670
+ const chain = scratch && asksWholeChain(guidance);
655
671
  const module = basename(plainFile).replace(/\.plain$/, "");
656
672
  if (scratch && again.length > 0) {
657
673
  say("Name functionalities or ask for it from scratch, not both: from scratch regenerates every one of them.", "warning");
658
674
  return;
659
675
  }
660
676
  if (scratch && ctx.hasUI) {
661
- const agreed = await ctx.ui.confirm(`Regenerate ${module} from scratch?`, `Its code and conformance tests are deleted - committed first, so /lineage ${module} keeps them - and the whole module is regenerated from its spec.`);
677
+ const agreed = await ctx.ui.confirm(chain ? `Regenerate ${module} and its whole chain from scratch?` : `Regenerate ${module} from scratch?`, chain
678
+ ? `The code and conformance tests of ${module} and of every module it requires are deleted - committed first, so /lineage keeps them - and the whole chain is regenerated from its spec, from the bottom.`
679
+ : `Its code and conformance tests are deleted - committed first, so /lineage ${module} keeps them - and the whole module is regenerated from its spec.`);
662
680
  if (!agreed)
663
681
  return;
664
682
  }
@@ -668,14 +686,14 @@ function registerRegenerate(pi, cwd, jobs) {
668
686
  // Said at once, and kept in the chat: what follows takes a while - the planner is an agent - and the person sees it
669
687
  // began, not a chat that stays empty until the first pulse starts. The plan is said under it once it is made.
670
688
  say(scratch
671
- ? `Deleting ${module}'s code, then planning all of it again…`
689
+ ? `Deleting ${module}'s code${chain ? " and its whole chain's" : ""}, then planning all of it again…`
672
690
  : again.length > 0
673
691
  ? `Planning ${module}'s functionalit${again.length === 1 ? "y" : "ies"} ${again.join(", ")} again…`
674
692
  : `Planning ${module}'s pulses…`, "info");
675
693
  await nextFrame();
676
694
  try {
677
695
  const statuses = scratch
678
- ? await loop.fromScratch(plainFile, request)
696
+ ? await loop.fromScratch(plainFile, { ...request, chain })
679
697
  : again.length > 0
680
698
  ? await loop.regenerateAgain(plainFile, again, request)
681
699
  : await loop.bringUp(plainFile, request);
@@ -110,6 +110,7 @@ export function withModels(text, lines) {
110
110
  export const DEFAULTS = {
111
111
  conformanceTests: false,
112
112
  review: false,
113
+ mutationTesting: true,
113
114
  allowToStopJobs: true,
114
115
  releaseAfterPulse: false,
115
116
  testingScriptsRunOn: "in-place",
@@ -143,6 +144,10 @@ export function quickStartConfig(vendor = "other", bedrock) {
143
144
  "# Whether the code and its tests are reviewed once they pass - two reviews at most, the second weighed by the arbiter.",
144
145
  `review: ${DEFAULTS.review}`,
145
146
  "",
147
+ "# Whether the coding agent and the reviewer can put a bug in the code for one run of the unit tests (can_it_fail),",
148
+ "# to see that a test catches it - on a copy of the code, or in place and put back after.",
149
+ `mutation-testing: ${DEFAULTS.mutationTesting}`,
150
+ "",
146
151
  "# Whether turri stops a running pulse the spec has moved on from. false: it lands, the change regenerated on top.",
147
152
  `allow-to-stop-jobs: ${DEFAULTS.allowToStopJobs}`,
148
153
  "",
package/dist/loop-cli.js CHANGED
@@ -4,6 +4,7 @@ import { resolve, sep } from "node:path";
4
4
  import { configForSpec, inheritModel, modelOnly, modelSpec, projectModels, readProjectConfig, roleModel, ROLE_THINKING, splitModelSpec, } from "./config.js";
5
5
  import { PACKAGE_ROOT } from "./environment.js";
6
6
  import { c } from "./module-report.js";
7
+ import { describeTurnIncident, onModelEvent } from "./regenerate/activity.js";
7
8
  import { tryItCommand } from "./regenerate/delivery.js";
8
9
  import { describeDiagnosis, diagnoseFailure } from "./regenerate/diagnose.js";
9
10
  import { createJobRegistry, pulseName } from "./regenerate/jobs.js";
@@ -51,6 +52,7 @@ export async function runLoop(options) {
51
52
  ...(buildDir !== undefined ? { buildDir } : {}),
52
53
  conformanceTests: conformanceLabel(project.conformanceTests),
53
54
  review: project.review === true,
55
+ mutationTesting: project.mutationTesting !== false,
54
56
  models: reportModels(project, model),
55
57
  })
56
58
  : undefined;
@@ -85,9 +87,19 @@ async function runLoopReporting(options) {
85
87
  console.log(`${mark} ${job.id} ${pulseName(job)} - ${job.status}`);
86
88
  if (job.status !== "succeeded")
87
89
  console.log(c.dim((job.announce ?? job.report ?? job.error ?? "").trim()));
90
+ // Its report is not printed when it succeeds, and nobody is asked here: the spec gaps its agents met are said.
91
+ else
92
+ for (const gap of job.details?.specGaps ?? [])
93
+ console.log(c.yellow(` spec gap: ${gap.question}`), c.dim(`Meanwhile: ${gap.assumption}`));
88
94
  report?.write();
89
95
  },
90
96
  });
97
+ // A provider failing and waited out, a turn turri ended itself: said as they happen, not left in the job logs alone.
98
+ onModelEvent((event) => {
99
+ const line = describeTurnIncident(event);
100
+ if (line !== undefined)
101
+ console.log(c.yellow(` ${event.job !== undefined ? `${event.job}: ` : ""}${line}`));
102
+ });
91
103
  const planner = modelSpec(projectModels(project).harness);
92
104
  const loop = createWorkLoop({
93
105
  registry,
@@ -236,7 +248,7 @@ function reportModels(project, model) {
236
248
  }
237
249
  /**
238
250
  * The options every command that regenerates takes for a headless run: `--report` and `--build-dir`, and the config's
239
- * own keys (configKeyOptions) - `--harness-model`, `--coding-model` (`--model`), `--judge-model`, `--review` and, where
251
+ * own keys (configKeyOptions) - `--harness-model`, `--coding-model` (`--model`), `--judge-model`, `--review`, `--mutation-testing` and, where
240
252
  * `conformance` is true, `--conformance-tests` - read as if config.turri.yaml had them. Exits on a value it cannot read.
241
253
  */
242
254
  export function headlessOptions(options, conformance) {
@@ -110,6 +110,10 @@ function plainFileOf(cwd, given, what) {
110
110
  export function asksFromScratch(words) {
111
111
  return FROM_SCRATCH.test(words);
112
112
  }
113
+ /** Whether a /regenerate asking for its module from scratch asks for its whole requires chain with it. */
114
+ export function asksWholeChain(words) {
115
+ return /\bchain\b|\bevery module\b|\ball (the )?modules\b/i.test(words);
116
+ }
113
117
  const FROM_SCRATCH = /\b(from (scratch|nothing|zero|the (start|beginning|ground up))|start(ing)? (it )?(over|afresh)|afresh|anew|clean slate|(delete|wipe|remove|drop|throw away)\b.{0,30}\b(module|code|codebase|everything|all of it))/i;
114
118
  /** regenerate: regenerate a module's code up to its spec as it is now. */
115
119
  export function regenerateTool(options) {
@@ -131,6 +135,7 @@ export function regenerateTool(options) {
131
135
  "A change to a file the spec links - an API surface, a mapping document - is a change to the spec: regenerate sees it by itself, and regenerates every functional spec that uses what links it.",
132
136
  "Never stop pulses and start them again yourself to follow a spec change: regenerate does it.",
133
137
  "Set from_scratch only when the user asks for the module to be regenerated from scratch - started over, its code deleted - in this conversation, or agrees to it when a module's status says it has to start over: never to fix a pulse that did not land.",
138
+ 'from_scratch "module" takes out the code where the module is built; the modules below keep theirs, and the module starts from a copy of the code below it. "chain" takes out every codebase of its requires chain, the base\'s too, and builds all of it again from the bottom: use it after modules were split, merged or moved (refactor-module), or when the user asks for the whole chain.',
134
139
  ],
135
140
  parameters: Type.Object({
136
141
  plain_file: Type.Optional(Type.String({ description: "Path to the .plain file. Omitted: the module the project's config.turri.yaml names" })),
@@ -139,8 +144,9 @@ export function regenerateTool(options) {
139
144
  functionalities: Type.Optional(Type.Array(Type.String(), {
140
145
  description: "Functional specs already built, by id, to regenerate though their spec did not change. Omitted: what the spec now differs from the code in",
141
146
  })),
142
- from_scratch: Type.Optional(Type.Boolean({
143
- description: "Only when the user asks for it: the module's code and conformance tests deleted - committed first, so its lineage keeps them - and the whole module regenerated from its spec",
147
+ from_scratch: Type.Optional(Type.Union([Type.Literal("module"), Type.Literal("chain")], {
148
+ description: "Only when the user asks for it: the module's code and conformance tests deleted - committed first, so its lineage keeps them - and the whole module regenerated from its spec. " +
149
+ '"chain": every module of its requires chain too, built again from the bottom',
144
150
  })),
145
151
  model: MODEL_PARAM,
146
152
  wait: WAIT_PARAM,
@@ -151,15 +157,15 @@ export function regenerateTool(options) {
151
157
  if (!check.ok)
152
158
  throw new Error(`${relative(options.cwd, plainFile) || plainFile} does not parse, so nothing can be regenerated from it yet: ${check.error}`);
153
159
  const again = given.functionalities ?? [];
154
- if (again.length > 0 && given.from_scratch === true)
160
+ if (again.length > 0 && given.from_scratch !== undefined)
155
161
  throw new Error("Name functionalities or set from_scratch, not both: from scratch regenerates every one of them.");
156
162
  // Named functionalities are work on functionalities, as engine chooses a model for it; the rest, spec changes.
157
163
  const work = again.length > 0 ? "functionalities" : "spec_changes";
158
164
  const model = options.model !== undefined ? options.model(ctx, plainFile, given.model, work) : given.model;
159
165
  const loop = options.loop(ctx);
160
166
  const request = { ...(model !== undefined ? { model } : {}), ...(given.guidance !== undefined ? { guidance: given.guidance } : {}) };
161
- const statuses = given.from_scratch === true
162
- ? await loop.fromScratch(plainFile, request)
167
+ const statuses = given.from_scratch !== undefined
168
+ ? await loop.fromScratch(plainFile, { ...request, chain: given.from_scratch === "chain" })
163
169
  : again.length > 0
164
170
  ? await loop.regenerateAgain(plainFile, again, request)
165
171
  : await loop.bringUp(plainFile, request);
package/dist/pi.js CHANGED
@@ -4,6 +4,7 @@ import { createAgentSession, DefaultResourceLoader, getAgentDir, ModelRegistry,
4
4
  import { loadRules, renderRulesBlock } from "./rules.js";
5
5
  import { inheritModel, stackOf, readProjectConfig, ROLE_THINKING, roleModel, roleTurnLimitMs, splitModelSpec } from "./config.js";
6
6
  import { maskToolResults } from "./regenerate/masking.js";
7
+ import { withListArguments } from "./regenerate/list-arguments.js";
7
8
  import { checkAgainstScript, ENVIRONMENT_ERROR_TOOL, EnvironmentError, environmentErrorTool, sandboxGapOf } from "./regenerate/environment-error.js";
8
9
  import { MODULES_DIR, projectRootOf, sessionsDir } from "./regenerate/paths.js";
9
10
  import { currentStopSignal, describeToolCall, describeToolResult, JobStoppedError, shownName, reportActivity, reportNow, reportAgent, reportTranscript, reportModelEvent, reportUsage, } from "./regenerate/activity.js";
@@ -146,6 +147,19 @@ export class ProviderError extends Error {
146
147
  this.name = "ProviderError";
147
148
  }
148
149
  }
150
+ /** Why turri itself ended a session's turn under way: the abort that comes back is its own, not the provider failing. */
151
+ const harnessStops = new WeakMap();
152
+ /**
153
+ * End the agent's turn, turri's own doing - it is going round in a circle, its time is up. The turn ends as any turn
154
+ * does: what the agent said stands, and the harness goes on from there. Never a provider error.
155
+ */
156
+ export function stopTurn(session, reason) {
157
+ if (session === undefined || harnessStops.has(session))
158
+ return;
159
+ harnessStops.set(session, reason);
160
+ reportModelEvent({ kind: "stopped", ...modelEventOf(session), reason });
161
+ void session.abort();
162
+ }
149
163
  /**
150
164
  * Run one turn and return the assistant's text, streaming deltas to `onDelta`.
151
165
  *
@@ -212,17 +226,32 @@ async function askUnrestricted(session, text, onDelta) {
212
226
  catch (error) {
213
227
  if (!(error instanceof ProviderError) || !TRANSIENT_PROVIDER_ERROR.test(error.message) || attempt >= PROVIDER_RETRIES)
214
228
  throw error;
215
- const wait = PROVIDER_RETRY_DELAY_MS * 2 ** attempt;
216
- reportActivity(` the model provider is failing for now - trying again in ${Math.round(wait / 1000)}s (${attempt + 1} of ${PROVIDER_RETRIES})`);
217
- debugLogOf(session)?.note(`provider failing - trying again in ${Math.round(wait / 1000)}s: ${error.message.slice(0, 200)}`);
229
+ const wait = providerRetryDelay(attempt);
230
+ const shown = `${Math.round(wait / 1000)}s (${attempt + 1} of ${PROVIDER_RETRIES})`;
231
+ reportActivity(` the model provider is failing for now - trying again in ${shown}`);
232
+ reportNow(`the model provider is failing - trying again in ${shown}`);
233
+ reportModelEvent({ kind: "provider_retry", ...modelEventOf(session), error: error.message, attempt: attempt + 1, of: PROVIDER_RETRIES, waitMs: wait });
234
+ debugLogOf(session)?.note(`provider failing - trying again in ${shown}: ${error.message.slice(0, 200)}`);
218
235
  await waitOrStop(wait);
236
+ reportNow(undefined);
219
237
  prompt = "Carry on where you were: the model provider failed part-way through your last turn.";
220
238
  }
221
239
  }
222
240
  }
223
- /** How many times, after pi's own retries, a turn whose provider failed for a moment is tried again - and the first wait, doubled each time. */
224
- export const PROVIDER_RETRIES = 3;
241
+ /**
242
+ * How many times, after pi's own retries, a turn whose provider failed for a moment is tried again; the first wait,
243
+ * doubled each time up to the longest - 15s, 30s, 1m, 2m, 4m, 5m: an outage of about 13 minutes is waited out.
244
+ */
245
+ export const PROVIDER_RETRIES = 6;
225
246
  export const PROVIDER_RETRY_DELAY_MS = Number(process.env.TURRI_PROVIDER_RETRY_DELAY ?? 15) * 1000;
247
+ export const PROVIDER_RETRY_MAX_DELAY_MS = 20 * PROVIDER_RETRY_DELAY_MS;
248
+ /** The wait before try `attempt + 1`: doubled each time, up to the longest, with a tenth either way so parallel jobs do not all come back at once. */
249
+ export function providerRetryDelay(attempt, random = Math.random) {
250
+ const base = Math.min(PROVIDER_RETRY_DELAY_MS * 2 ** attempt, PROVIDER_RETRY_MAX_DELAY_MS);
251
+ return Math.round(base * (0.9 + 0.2 * random()));
252
+ }
253
+ /** How long a request to the model may go without anything coming back before the provider is said to be stalling; 0 never. */
254
+ export const PROVIDER_STALL_MS = Number(process.env.TURRI_PROVIDER_STALL ?? 120) * 1000;
226
255
  /** A provider error that passes: overloaded, rate limited, unreachable, timed out. */
227
256
  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;
228
257
  /** Wait, unless the job is stopped first. */
@@ -251,7 +280,7 @@ async function askOnce(session, text, onDelta) {
251
280
  // Calls to one tool failing one after another - arguments it refuses, or errors - with nothing going through.
252
281
  let failing = 0;
253
282
  let failingTool;
254
- let stoppedFailing = false;
283
+ harnessStops.delete(session);
255
284
  reportNow("waiting for the model");
256
285
  // Every entry says which agent it is from, and what it runs on - for reading one agent at a time.
257
286
  const agent = agentOf(session);
@@ -263,7 +292,30 @@ async function askOnce(session, text, onDelta) {
263
292
  if (agent !== undefined)
264
293
  reportAgent({ label: agent.label, ...(agent.model !== undefined ? { model: agent.model } : {}), turns: 1 });
265
294
  reportModelEvent({ kind: "turn", ...modelEventOf(session) });
295
+ // The provider stalling: a request to the model that nothing has come back on - not a token, not an error - for
296
+ // long. Said once for each silence; the turn goes on waiting, its own time limit ending it if it must.
297
+ let toolsRunning = 0;
298
+ let stall;
299
+ const watchForStall = (afterMs = PROVIDER_STALL_MS) => {
300
+ if (stall !== undefined)
301
+ clearTimeout(stall);
302
+ stall = toolsRunning > 0 || PROVIDER_STALL_MS <= 0 ? undefined : setTimeout(() => {
303
+ reportModelEvent({ kind: "provider_stall", ...modelEventOf(session), waitMs: PROVIDER_STALL_MS });
304
+ debugLogOf(session)?.note(`the provider has sent nothing back for ${seconds(PROVIDER_STALL_MS)}`);
305
+ }, afterMs);
306
+ };
266
307
  const unsubscribe = session.subscribe((event) => {
308
+ if (event.type === "tool_execution_start")
309
+ toolsRunning += 1;
310
+ if (event.type === "tool_execution_end")
311
+ toolsRunning = Math.max(0, toolsRunning - 1);
312
+ // pi tries a failed request again itself first: the provider failing is said then, not only once pi gives up.
313
+ if (event.type === "auto_retry_start") {
314
+ reportModelEvent({ kind: "provider_retry", ...modelEventOf(session), error: event.errorMessage, attempt: event.attempt, of: event.maxAttempts, waitMs: event.delayMs });
315
+ watchForStall(event.delayMs + PROVIDER_STALL_MS);
316
+ }
317
+ else
318
+ watchForStall();
267
319
  if (event.type === "message_update") {
268
320
  const update = event.assistantMessageEvent;
269
321
  if (update.type === "text_delta") {
@@ -308,14 +360,13 @@ async function askOnce(session, text, onDelta) {
308
360
  if (event.type === "tool_execution_end") {
309
361
  failing = event.isError ? (event.toolName === failingTool ? failing + 1 : 1) : 0;
310
362
  failingTool = event.isError ? event.toolName : undefined;
311
- if (failing >= FAILURES_BEFORE_STOP && !stoppedFailing) {
363
+ if (failing >= FAILURES_BEFORE_STOP && !harnessStops.has(session)) {
312
364
  // A call its tool refuses never reaches the tool, so no guard on the tools sees it: an agent can
313
365
  // make the same bad call, worded a little differently, thousands of times. Its turn ends here, and
314
366
  // the harness goes on from there, as after any turn.
315
- stoppedFailing = true;
316
367
  reportActivity(` stopped the agent's turn: ${failing} ${shownName(event.toolName)} calls failed in a row`);
317
368
  debugLogOf(session)?.note(`turn stopped: ${failing} ${event.toolName} calls failed in a row`);
318
- void session.abort();
369
+ stopTurn(session, `${failing} ${shownName(event.toolName)} calls failed in a row`);
319
370
  }
320
371
  const output = resultText(event.result);
321
372
  transcript({ kind: "result", text: clipText(output, MAX_TOOL_RESULT), error: event.isError, full: output });
@@ -376,7 +427,7 @@ async function askOnce(session, text, onDelta) {
376
427
  stopped = true;
377
428
  reportActivity(` stopped the agent's turn: its ${formatLimit(limitMs)} are up`);
378
429
  debug?.note(`turn stopped: its ${formatLimit(limitMs)} are up${how}`);
379
- void session.abort();
430
+ stopTurn(session, `its ${formatLimit(limitMs)} were up`);
380
431
  };
381
432
  const atNextRequest = timed
382
433
  ? session.subscribe((event) => {
@@ -392,6 +443,7 @@ async function askOnce(session, text, onDelta) {
392
443
  }
393
444
  // What the model is sent, and only that: its task is its system prompt, which the log already holds whole.
394
445
  debug?.prompt(text);
446
+ watchForStall();
395
447
  try {
396
448
  // Its images, when its conversation does not hold them: the first turn, and the first after a compaction.
397
449
  const images = sessionImages.get(session);
@@ -412,19 +464,24 @@ async function askOnce(session, text, onDelta) {
412
464
  clearTimeout(timer);
413
465
  if (backstop !== undefined)
414
466
  clearTimeout(backstop);
467
+ if (stall !== undefined)
468
+ clearTimeout(stall);
415
469
  atNextRequest?.();
416
470
  unsubscribe();
417
471
  stop?.removeEventListener("abort", onStop);
418
472
  reportNow(undefined);
419
473
  }
420
- if (stopped)
421
- out = `${out.trim()}\n\n[the turn was stopped: its ${formatLimit(limitMs)} were up]`.trim();
474
+ // turri ended the turn itself - its time was up, the agent went round in a circle: the abort that ended it is its own.
475
+ const stoppedFor = harnessStops.get(session);
476
+ harnessStops.delete(session);
477
+ if (stoppedFor !== undefined)
478
+ out = `${out.trim()}\n\n[the turn was stopped: ${stoppedFor}]`.trim();
422
479
  if (stop?.aborted) {
423
480
  debug?.note(`turn stopped on request after ${seconds(Date.now() - turnStarted)}`);
424
481
  throw new JobStoppedError();
425
482
  }
426
- // A turn ended for its time is ended, whatever the provider was doing then.
427
- if (providerError !== undefined && !stopped) {
483
+ // A turn turri ended is ended, whatever the provider was doing then: what comes back of the abort is not the provider failing.
484
+ if (providerError !== undefined && stoppedFor === undefined) {
428
485
  debug?.note(`turn ended with a provider error after ${seconds(Date.now() - turnStarted)}: ${providerError}`);
429
486
  throw new ProviderError(`${session.model?.id ?? "model"}: ${providerError}`);
430
487
  }
@@ -614,7 +671,7 @@ export function guardRepeats(tools, session, budget) {
614
671
  refused += 1;
615
672
  if (refused > REFUSED_BEFORE_STOP) {
616
673
  reportActivity(` stopped the agent's turn: ${refused} calls to tools this turn does not have`);
617
- void current?.abort();
674
+ stopTurn(current, `${refused} calls to tools this turn does not have`);
618
675
  throw new Error(`Stopped: ${refused} calls to tools this turn does not have.`);
619
676
  }
620
677
  throw new Error(`Not run: your work is done and checked - this turn is for ${[...only].join(" and ")} alone, and nothing else is ` +
@@ -624,7 +681,7 @@ export function guardRepeats(tools, session, budget) {
624
681
  if (budget !== undefined && !budget.finish.includes(tool.name) && calls > budget.calls) {
625
682
  if (calls > budget.calls * 2) {
626
683
  reportActivity(` stopped the agent's turn: ${calls} tool calls, past its budget of ${budget.calls}`);
627
- void session()?.abort();
684
+ stopTurn(session(), `${calls} tool calls, past its budget of ${budget.calls}`);
628
685
  throw new Error(`Stopped: ${calls} tool calls, past the budget of ${budget.calls}.`);
629
686
  }
630
687
  throw new Error(`Not run: you have made ${budget.calls} tool calls, which is all you have. Decide now with what you know: call ` +
@@ -652,7 +709,7 @@ export function guardRepeats(tools, session, budget) {
652
709
  }
653
710
  if (repeats > REPEATS_BEFORE_STOP) {
654
711
  reportActivity(` stopped the agent's turn: it made the same ${tool.name} call ${repeats} times with nothing changed`);
655
- void session()?.abort();
712
+ stopTurn(session(), `the same ${tool.name} call ${repeats} times with nothing changed`);
656
713
  throw new Error(`Stopped: the same ${tool.name} call ${repeats} times with nothing changed.`);
657
714
  }
658
715
  if (repeats > REPEATS_ALLOWED) {
@@ -695,7 +752,7 @@ export async function createExecutor(opts) {
695
752
  modelRuntime: await subAgentModelRuntime(),
696
753
  tools: hasShell ? [...opts.tools, ENVIRONMENT_ERROR_TOOL] : opts.tools,
697
754
  // What an agent is shown never holds a credential the project passed: each value is its name (masking.ts).
698
- customTools: guardRepeats(maskToolResults(withEnvironmentErrors), () => session, opts.budget),
755
+ customTools: guardRepeats(maskToolResults(withListArguments(withEnvironmentErrors)), () => session, opts.budget),
699
756
  sessionManager,
700
757
  resourceLoader: await subAgentResources(opts.cwd, opts.rules === true, [opts.system, opts.task].filter((part) => part !== undefined && part !== "").join("\n\n") || undefined),
701
758
  });
@@ -814,7 +871,7 @@ export async function createJudge(opts) {
814
871
  model,
815
872
  modelRuntime,
816
873
  tools: [...(opts.extraTools ?? []), "submit_verdict"],
817
- customTools: [opts.verdictTool],
874
+ customTools: withListArguments([opts.verdictTool]),
818
875
  sessionManager: SessionManager.inMemory(opts.cwd),
819
876
  // Judges assess specs against the rules, so they have them too.
820
877
  resourceLoader: await subAgentResources(opts.cwd, true, opts.task),
@@ -25,6 +25,7 @@ export class QuestionDialog {
25
25
  }
26
26
  else {
27
27
  this.input = undefined;
28
+ this.selected = Math.min(Math.max(0, options.selected ?? 0), options.options.length - 1);
28
29
  }
29
30
  }
30
31
  get focused() {