ceulen 0.17.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/extensions/modules/a2a/lib/client.ts +2 -1
  3. package/extensions/modules/advisor/commands/advisor.ts +22 -12
  4. package/extensions/modules/advisor/test/module.test.ts +26 -0
  5. package/extensions/modules/plan/index.ts +64 -0
  6. package/extensions/modules/plan/test/module.test.ts +112 -0
  7. package/extensions/modules/steering/index.ts +25 -6
  8. package/extensions/modules/steering/test/anchor-regressions.test.ts +38 -0
  9. package/package.json +3 -3
  10. package/scripts/validate-themes.mjs +31 -3
  11. package/themes/alabaster.json +2 -17
  12. package/themes/amethyst.json +2 -19
  13. package/themes/anthracite.json +2 -22
  14. package/themes/basalt.json +3 -31
  15. package/themes/birch.json +2 -19
  16. package/themes/catppuccin-mocha.json +1 -7
  17. package/themes/dark-abyss.json +2 -17
  18. package/themes/dark-arctic.json +2 -23
  19. package/themes/dark-aurora.json +2 -18
  20. package/themes/dark-catppuccin.json +2 -25
  21. package/themes/dark-cavern.json +2 -18
  22. package/themes/dark-celestial.json +2 -18
  23. package/themes/dark-copper.json +2 -18
  24. package/themes/dark-cosmos.json +2 -17
  25. package/themes/dark-cyberpunk.json +2 -21
  26. package/themes/dark-dracula.json +2 -20
  27. package/themes/dark-eclipse.json +2 -18
  28. package/themes/dark-ember.json +2 -18
  29. package/themes/dark-equinox.json +2 -17
  30. package/themes/dark-forest.json +2 -21
  31. package/themes/dark-github.json +2 -24
  32. package/themes/dark-gruvbox.json +2 -30
  33. package/themes/dark-lavender.json +2 -18
  34. package/themes/dark-lunar.json +2 -17
  35. package/themes/dark-midnight.json +2 -18
  36. package/themes/dark-monochrome.json +2 -19
  37. package/themes/dark-monokai.json +2 -21
  38. package/themes/dark-nebula.json +2 -18
  39. package/themes/dark-neon-noir.json +2 -21
  40. package/themes/dark-nord.json +2 -21
  41. package/themes/dark-ocean.json +2 -22
  42. package/themes/dark-one.json +2 -21
  43. package/themes/dark-poimandres.json +4 -41
  44. package/themes/dark-rainforest.json +2 -17
  45. package/themes/dark-reef.json +2 -18
  46. package/themes/dark-retro.json +2 -18
  47. package/themes/dark-rose-pine.json +3 -21
  48. package/themes/dark-sakura.json +2 -18
  49. package/themes/dark-slate.json +2 -18
  50. package/themes/dark-solarized.json +2 -23
  51. package/themes/dark-solstice.json +2 -17
  52. package/themes/dark-starfall.json +2 -17
  53. package/themes/dark-sunset.json +2 -23
  54. package/themes/dark-swamp.json +2 -18
  55. package/themes/dark-synthwave.json +2 -25
  56. package/themes/dark-taiga.json +2 -17
  57. package/themes/dark-terminal.json +2 -18
  58. package/themes/dark-tokyo-night.json +2 -23
  59. package/themes/dark-tundra.json +2 -18
  60. package/themes/dark-twilight.json +2 -17
  61. package/themes/dark-volcanic.json +2 -17
  62. package/themes/dark.json +2 -6
  63. package/themes/graphite.json +2 -21
  64. package/themes/light-arctic.json +2 -27
  65. package/themes/light-aurora-day.json +2 -18
  66. package/themes/light-canyon.json +2 -17
  67. package/themes/light-catppuccin.json +3 -24
  68. package/themes/light-cirrus.json +2 -18
  69. package/themes/light-coral.json +2 -18
  70. package/themes/light-cyberpunk.json +2 -19
  71. package/themes/light-dawn.json +2 -17
  72. package/themes/light-dunes.json +2 -17
  73. package/themes/light-eucalyptus.json +2 -18
  74. package/themes/light-forest.json +3 -24
  75. package/themes/light-frost.json +2 -18
  76. package/themes/light-github.json +3 -39
  77. package/themes/light-glacier.json +2 -17
  78. package/themes/light-gruvbox.json +3 -30
  79. package/themes/light-haze.json +2 -18
  80. package/themes/light-honeycomb.json +2 -18
  81. package/themes/light-lagoon.json +2 -17
  82. package/themes/light-lavender.json +2 -18
  83. package/themes/light-meadow.json +2 -17
  84. package/themes/light-mint.json +2 -18
  85. package/themes/light-monochrome.json +2 -21
  86. package/themes/light-ocean.json +2 -20
  87. package/themes/light-one.json +2 -20
  88. package/themes/light-opal.json +2 -18
  89. package/themes/light-orchard.json +2 -18
  90. package/themes/light-paper.json +2 -18
  91. package/themes/light-poimandres.json +4 -41
  92. package/themes/light-prism.json +2 -19
  93. package/themes/light-retro.json +3 -21
  94. package/themes/light-sand.json +2 -18
  95. package/themes/light-savanna.json +2 -17
  96. package/themes/light-solarized.json +2 -22
  97. package/themes/light-soleil.json +2 -18
  98. package/themes/light-sunset.json +2 -22
  99. package/themes/light-synthwave.json +2 -22
  100. package/themes/light-tokyo-night.json +3 -28
  101. package/themes/light-wetland.json +2 -17
  102. package/themes/light-zenith.json +2 -18
  103. package/themes/light.json +2 -6
  104. package/themes/limestone.json +2 -19
  105. package/themes/mahogany.json +2 -19
  106. package/themes/marble.json +2 -19
  107. package/themes/mirage.json +2 -6
  108. package/themes/obsidian.json +2 -19
  109. package/themes/onyx.json +2 -17
  110. package/themes/pearl.json +2 -21
  111. package/themes/porcelain.json +2 -17
  112. package/themes/quartz.json +2 -19
  113. package/themes/sandstone.json +2 -20
  114. package/themes/titanium.json +2 -17
package/CHANGELOG.md CHANGED
@@ -1,5 +1,57 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.18.0 — 2026-10-14
4
+
5
+ pi 1.2.0 compatibility + the ask_user_question confirmation loop (incident
6
+ report 2026-10-14, session 01a12a6c: six consecutive permission dialogs, each
7
+ answered, with the dispatch they were asking about never sent):
8
+
9
+ - **Themes broke on pi 1.2.0 — all 104 shipped themes failed to load**
10
+ (`Error: Failed to load theme "titanium": Theme not found: titanium` →
11
+ system fallback). pi 1.2.0 validates themes at startup against a schema with
12
+ `additionalProperties: false` at both the root object and `colors`; 100 of
13
+ the 104 themes carried non-schema keys inherited from the pi-themes port
14
+ (`statusLine*` ×14, `pythonMode`, `link`, `toolText`) that pi and ceulen both
15
+ ignore. Validation threw, the resource loader swallowed it as a diagnostic,
16
+ and the theme silently vanished. All 104 themes are now schema-clean (their
17
+ 255 orphaned `vars` pruned, `$schema` repointed to
18
+ `https://pi.dev/schemas/theme.schema.json`), and `scripts/validate-themes.mjs`
19
+ — which runs in `npm test` — gained ALLOWED/ROOT/EXPORT gates mirroring pi's
20
+ closed schema, so a stray key fails the suite instead of vanishing at boot.
21
+ Verified against pi 1.2.0's own validator: 4/104 → 104/104, all 104 also
22
+ build a Theme instance.
23
+ - **Peer deps widened** to `>=0.99.1 <1.3.0` for both `@earendil-works/pi-coding-agent`
24
+ and `@earendil-works/pi-tui` — the old range excluded 1.2.0 semver-wise. Dev
25
+ lockfile refreshed; typecheck + full suite now run against 1.2.0 types.
26
+ - **steering**: pi 1.2.0 made `BeforeAgentStartEvent` a union on `messageType`
27
+ (`prompt`/`images` only on the `"user"` variant) and now fires
28
+ `before_agent_start` for `sendMessage({triggerTurn:true})` runs too (cron
29
+ fires, repair auto-bg follow-ups, subagent receipts). The first-tool hints
30
+ read `event.prompt` (3 type errors) and the ds-anchor bootstrap could be
31
+ consumed by a machine-initiated run — running a cron task under the DSH
32
+ minimal prompt with bash/str_replace_editor only. Custom runs now skip the
33
+ bootstrap and the prompt-derived hints; the bootstrap stays pending for the
34
+ next user turn. Tested as "not custom" (not `=== "user"`), since pi ≤1.1.0
35
+ sends no `messageType`. 2 new tests.
36
+ - **plan**: `ask_user_question` gains a two-arm loop dampener. Either arm alone
37
+ has a hole: an identical-args guard misses the incident's reworded repeats
38
+ ("Ready to execute…dispatch…peer now?" → "Execute: dispatch to peer now?" →
39
+ "Dispatch now?" → "Dispatch?"). Arm A refuses a near-duplicate of an
40
+ already-answered question (stopword-filtered content-word containment, cut at
41
+ 0.8 — the incident's rewording scores 1.00 every time, the closest distinct
42
+ pair 0.67; replaying the incident it fires at ask #2). Arm B is the
43
+ wording-blind backstop: a 4th ask with no other tool call in between. The
44
+ guard returns the earlier question + answer and an instruction to act instead
45
+ of opening another dialog; any other tool call or a new session clears it.
46
+ 8 new tests.
47
+ - **advisor**: a whole-chain consult failure now wraps the raw provider error
48
+ (`400 insufficient credits` is what spun the model into asking) with what it
49
+ means and what to do — continue without guidance, do not stall the user.
50
+ 1 new test.
51
+ - **a2a**: the reply-timeout error now points at `a2a_status` and
52
+ `async_dispatch: true` before re-sending, and notes a duplicate synchronous
53
+ send can double-deliver.
54
+
3
55
  ## 0.17.0 — 2026-10-13
4
56
 
5
57
  - **Munin loop fixed** (incident report 2026-10-12; two sessions on
@@ -224,7 +224,8 @@ async function postJsonRpc(
224
224
  } catch (e: any) {
225
225
  if (ctrl.signal.aborted) {
226
226
  throw new Error(
227
- `reply timed out after ${timeoutMs}ms; delivery status unknown (requestId=${String(body.id)})`,
227
+ `reply timed out after ${timeoutMs}ms; delivery status unknown (requestId=${String(body.id)}). ` +
228
+ `The peer may still be working: check a2a_status before re-sending, and use async_dispatch: true for a peer that is routinely slow — a second synchronous send can double-deliver the work.`,
228
229
  );
229
230
  }
230
231
  throw new Error(`connection failed — ${e?.message || String(e)}`);
@@ -119,18 +119,28 @@ export function registerAdvisor(pi: ExtensionAPI, state: AdvisorState): AdvisorH
119
119
  // must not leave its partial output above the next candidate's response.
120
120
  let output = "";
121
121
  let attempt = 0;
122
- const result = await runIsolatedChain(ctx, models, {
123
- systemPrompt: `${SYSTEM}\n\nPRIMARY AGENT SYSTEM PROMPT:\n${ctx.getSystemPrompt()}`,
124
- messages: [{
125
- role: "user",
126
- content: [{ type: "text", text: `<transcript>${transcriptEvidence}</transcript>\n\nProvide strategic guidance for the executor.` }],
127
- timestamp: Date.now(),
128
- }],
129
- }, (delta, forAttempt) => {
130
- if (forAttempt !== attempt) { attempt = forAttempt; output = ""; }
131
- output += delta;
132
- onUpdate?.({ content: [{ type: "text", text: output }], details: { models } });
133
- }, signal);
122
+ let result;
123
+ try {
124
+ result = await runIsolatedChain(ctx, models, {
125
+ systemPrompt: `${SYSTEM}\n\nPRIMARY AGENT SYSTEM PROMPT:\n${ctx.getSystemPrompt()}`,
126
+ messages: [{
127
+ role: "user",
128
+ content: [{ type: "text", text: `<transcript>${transcriptEvidence}</transcript>\n\nProvide strategic guidance for the executor.` }],
129
+ timestamp: Date.now(),
130
+ }],
131
+ }, (delta, forAttempt) => {
132
+ if (forAttempt !== attempt) { attempt = forAttempt; output = ""; }
133
+ output += delta;
134
+ onUpdate?.({ content: [{ type: "text", text: output }], details: { models } });
135
+ }, signal);
136
+ } catch (error) {
137
+ // The whole chain failed (provider/key/quota — e.g. a 400 "insufficient
138
+ // credits"). A bare provider string reads to weak models as "the session
139
+ // is broken, so stall and ask the user" — the 2026-10-14 ask-loop
140
+ // incident started exactly here. Say what it means and what to do.
141
+ const reason = error instanceof Error ? error.message : String(error);
142
+ throw new Error(`Advisor unavailable (chain ${chain}): ${reason}\nContinue the task without advisor guidance. Do not tell the user the advisor failed and do not ask them to retry it — it is an optional second opinion, not a gate.`);
143
+ }
134
144
  return {
135
145
  content: [{ type: "text", text: `Advice from ${result.model}:\n${result.text}\n\nAdvisor usage: ${usageLine(result.usage.input, result.usage.output, result.usage.cost)}` }],
136
146
  details: { models, served: result.model },
@@ -683,3 +683,29 @@ describe("writeAdvisorSettings integration", () => {
683
683
  function cmdStatus(state: any, ctx: any): void {
684
684
  state.commands.get("advisor").handler("status", ctx);
685
685
  }
686
+
687
+ describe("consult tool — chain exhaustion message", () => {
688
+ it("wraps a raw provider failure with what it means and what to do", async () => {
689
+ writeSettings({ advisor: { enabled: true, models: [MODEL] } });
690
+ const { pi, state } = createFakePi();
691
+ advisorModule(pi);
692
+ const ctx = available(fakeCtx([]));
693
+ await fire(pi, state, "session_start", ctx);
694
+ const tool = state.tools.get("advisor");
695
+ assert.ok(tool, "consult tool registered");
696
+ // The provider rejects the call (the 400 "insufficient credits" shape).
697
+ ctx.modelRegistry.streamSimple = () => {
698
+ throw new Error('400: {"message":"You have insufficient credits to make this request."}');
699
+ };
700
+ await assert.rejects(
701
+ () => tool.execute("tc1", {}, undefined, undefined, ctx),
702
+ (err: Error) => {
703
+ assert.match(err.message, /Advisor unavailable \(chain /, "names the failed chain");
704
+ assert.match(err.message, /insufficient credits/, "keeps the provider reason");
705
+ assert.match(err.message, /Continue the task without advisor guidance/, "tells the model to proceed");
706
+ assert.match(err.message, /Do not tell the user the advisor failed/, "forbids the stall-and-ask loop");
707
+ return true;
708
+ },
709
+ );
710
+ });
711
+ });
@@ -519,10 +519,64 @@ export default function planModule(pi: ExtensionAPI): void {
519
519
  // ponytail: ctx.ui.select is not reentrant — serialize concurrent dialogs.
520
520
  let askQuestionQueue: Promise<unknown> = Promise.resolve();
521
521
 
522
+ // Ask-loop dampener (2026-10-14 incident, session 01a12a6c): a glm-5.3-flash
523
+ // run asked permission 6 times in a row — each answered "Send it" — without
524
+ // ever emitting the a2a_call it was asking about. The wording drifted each
525
+ // time ("Ready to execute…dispatch now?" → "Execute: dispatch to peer now?" →
526
+ // "Dispatch now?" → "Dispatch?"), so an identical-args guard catches nothing.
527
+ // TWO independent arms, because either alone leaves a hole:
528
+ // A. near-duplicate — catches the incident's reworded repeats immediately.
529
+ // B. consecutive count — wording-independent backstop for a loop that drifts
530
+ // past the similarity cut (a 4th ask with NO tool call in between is a
531
+ // loop whatever it says; three distinct questions is a legitimate flow).
532
+ // ANY other tool call (see the tool_call hook) or a new session clears both.
533
+ let asksSinceToolCall = 0;
534
+ const ASK_RUN_LIMIT = 4;
535
+ let answeredAsks: { question: string; tokens: Set<string>; answer: string }[] = [];
536
+ // Filler words carry no intent and are removed first: without this "Should I
537
+ // dispatch the diagnosis to the peer now?" and "Should I revert the config
538
+ // now?" overlap on should/i/the/now and read as the same question.
539
+ const ASK_STOPWORDS = new Set([
540
+ "a", "an", "and", "are", "be", "before", "can", "do", "does", "for", "from", "go", "i", "if",
541
+ "in", "is", "it", "its", "me", "my", "now", "of", "on", "or", "please", "ready", "should",
542
+ "so", "that", "the", "then", "this", "to", "up", "use", "we", "what", "when", "which", "with",
543
+ "you", "your",
544
+ ]);
545
+ const askTokens = (q: string): Set<string> =>
546
+ new Set((q.toLowerCase().match(/[a-z0-9]+/g) ?? []).filter((t) => !ASK_STOPWORDS.has(t) && t.length > 1));
547
+ // 0.8 keeps the recall we need without tripping on same-verb/different-object
548
+ // questions. Measured on the incident's real wording drift (identical intent):
549
+ // "Ready to execute…dispatch…peer now?" vs "Execute: dispatch to peer now?" /
550
+ // "Dispatch now?" / "Dispatch?" all score 1.00, while the closest DISTINCT pair
551
+ // ("Should I restart the radius unit?" vs "…nginx unit?") scores 0.67.
552
+ /** Content words the shorter question shares with the longer, ≥0.8 → "same intent". */
553
+ const isNearDuplicate = (a: Set<string>, b: Set<string>): boolean => {
554
+ if (a.size === 0 || b.size === 0) return false;
555
+ const [small, big] = a.size <= b.size ? [a, b] : [b, a];
556
+ let shared = 0;
557
+ for (const token of small) if (big.has(token)) shared += 1;
558
+ return shared / small.size >= 0.8;
559
+ };
560
+
522
561
  async function executeAskQuestion(_toolCallId: string, params: unknown, _signal: unknown, _onUpdate: unknown, ctx: ExtensionToolContext) {
523
562
  const typedParams = params as PlanQuestionParams;
524
563
  const { options, recommendedIndex } = validateQuestionParams(typedParams);
525
564
  const textBlock = (text: string) => ({ type: "text" as const, text });
565
+ const tokens = askTokens(typedParams.question);
566
+ const repeat = answeredAsks.find((entry) => isNearDuplicate(tokens, entry.tokens));
567
+ asksSinceToolCall += 1;
568
+ const prior = repeat ?? answeredAsks[answeredAsks.length - 1];
569
+ if (repeat || (asksSinceToolCall >= ASK_RUN_LIMIT && prior)) {
570
+ return {
571
+ content: [textBlock(
572
+ `Loop guard: ${repeat
573
+ ? `you already asked this and the user answered — "${repeat.question}" → "${repeat.answer}".`
574
+ : `this is ask_user_question call #${asksSinceToolCall} in a row with no other tool call in between; the last answer was "${prior.question}" → "${prior.answer}".`} ` +
575
+ `Act on that answer now instead of asking again. If something genuinely blocks you, do the work that resolves it or say what the blocker is in plain text (a further question is allowed after any other tool call).`,
576
+ )],
577
+ details: { question: typedParams.question, options, answer: prior.answer, cancelled: false, loopGuard: true },
578
+ };
579
+ }
526
580
  const cancelled = {
527
581
  content: [textBlock("User cancelled the question.")],
528
582
  details: { question: typedParams.question, options, answer: null, cancelled: true, wasCustom: false },
@@ -546,6 +600,8 @@ export default function planModule(pi: ExtensionAPI): void {
546
600
  if (choice === otherLabel) {
547
601
  const answer = (await ctx.ui.editor("Your answer", ""))?.trim();
548
602
  if (!answer) return cancelled;
603
+ answeredAsks.push({ question: typedParams.question, tokens, answer });
604
+ if (answeredAsks.length > 8) answeredAsks.shift();
549
605
  return {
550
606
  content: [textBlock(`User wrote: ${answer}`)],
551
607
  details: { question: typedParams.question, options, answer, wasCustom: true, cancelled: false },
@@ -553,6 +609,8 @@ export default function planModule(pi: ExtensionAPI): void {
553
609
  }
554
610
  const selectedIndex = displayLabels.indexOf(choice);
555
611
  const answer = options[selectedIndex]?.label ?? choice;
612
+ answeredAsks.push({ question: typedParams.question, tokens, answer });
613
+ if (answeredAsks.length > 8) answeredAsks.shift();
556
614
  return {
557
615
  content: [textBlock(`User selected: ${answer}`)],
558
616
  details: { question: typedParams.question, options, answer, selectedIndex, wasCustom: false, cancelled: false },
@@ -871,6 +929,8 @@ export default function planModule(pi: ExtensionAPI): void {
871
929
 
872
930
  pi.on("session_start", async (event, ctx) => {
873
931
  sessionAllows.clear();
932
+ answeredAsks = [];
933
+ asksSinceToolCall = 0;
874
934
  refreshSettings(ctx);
875
935
  setPlanRegistry(ctx.modelRegistry);
876
936
  void probeDiffDrivers(ctx.cwd); // best-effort: textconv-aware bash gating
@@ -923,6 +983,10 @@ export default function planModule(pi: ExtensionAPI): void {
923
983
  * blocked mutators → hard error; bash writers → hard-block; bash reads →
924
984
  * auto-allow; unknown executables + non-read tools → confirm tier. */
925
985
  pi.on("tool_call", async (event, ctx) => {
986
+ // Ask-loop dampener: any tool call other than the question itself breaks the
987
+ // run (munin dampener contract). Deliberately above the
988
+ // plan-mode early return — the loop it guards is not plan-specific.
989
+ if (event.toolName !== ASK_USER_QUESTION_TOOL) { answeredAsks = []; asksSinceToolCall = 0; }
926
990
  if (!planModeEnabled) return;
927
991
  if (BLOCKED_TOOLS.has(event.toolName)) {
928
992
  return { block: true, reason: `plan mode: ${event.toolName} is not available while planning. Use ${PLAN_TOOL} to write the plan file.` };
@@ -410,6 +410,118 @@ describe("plan mode — branch restore", () => {
410
410
  });
411
411
  });
412
412
 
413
+ describe("ask_user_question ask-loop dampener", () => {
414
+ /** ctx whose ui.select answers `answers` in order and counts dialogs shown. */
415
+ function askingCtx(h: ReturnType<typeof createFakePi>, answers: string[]) {
416
+ const shown: string[] = [];
417
+ let i = 0;
418
+ const ctx = h.ctx({
419
+ ui: {
420
+ notify: () => {},
421
+ select: async (question: string) => { shown.push(question); return answers[i++]; },
422
+ editor: async () => undefined,
423
+ setStatus: () => {},
424
+ setEditorText: () => {},
425
+ theme: { fg: (_c: string, t: string) => t },
426
+ },
427
+ });
428
+ return { ctx, shown };
429
+ }
430
+ const ask = (h: ReturnType<typeof createFakePi>, ctx: any, question: string) =>
431
+ h.tools.ask_user_question.execute(`tc-${question}`, { question, options: [{ label: "Send it" }, { label: "Stop" }] }, undefined, undefined, ctx);
432
+ const text = (r: any) => String(r?.content?.[0]?.text ?? "");
433
+
434
+ it("refuses a near-duplicate of an already-answered question", async () => {
435
+ const h = await start();
436
+ const { ctx, shown } = askingCtx(h, ["Send it"]);
437
+ const first = await ask(h, ctx, "Ready to execute the confirmed plan — dispatch the NAK diagnosis to the peer now?");
438
+ assert.equal(text(first), "User selected: Send it", "1st ask shows the dialog");
439
+ // The incident's exact drift: same intent, reworded, shrinking.
440
+ const second = await ask(h, ctx, "Execute: dispatch to peer now?");
441
+ assert.match(text(second), /Loop guard/, "reworded repeat is refused");
442
+ assert.match(text(second), /already asked this and the user answered/, "guard explains why");
443
+ assert.match(text(second), /"Send it"/, "guard hands back the earlier answer");
444
+ assert.equal(shown.length, 1, "the repeat NEVER opened a second dialog");
445
+ assert.equal(second.details.loopGuard, true, "details mark the loop guard");
446
+ });
447
+
448
+ it("genuinely different questions are NOT blocked", async () => {
449
+ const h = await start();
450
+ const { ctx, shown } = askingCtx(h, ["Send it", "Send it", "Send it"]);
451
+ await ask(h, ctx, "Which port profile should the uplink use?");
452
+ await ask(h, ctx, "Which RADIUS secret belongs on the controller?");
453
+ const third = await ask(h, ctx, "How long should the capture run stay armed?");
454
+ assert.equal(text(third), "User selected: Send it", "a distinct question still opens");
455
+ assert.equal(shown.length, 3, "all three dialogs shown");
456
+ });
457
+
458
+ it("same verb, different object is NOT a duplicate (measured at 0.67)", async () => {
459
+ const h = await start();
460
+ const { ctx } = askingCtx(h, ["Go", "Go"]);
461
+ await ask(h, ctx, "Should I restart the radius unit?");
462
+ const second = await ask(h, ctx, "Should I restart the nginx unit?");
463
+ assert.equal(text(second), "User selected: Go", "different target still asks");
464
+ });
465
+
466
+ it("an explicit answer stays reusable while the loop guard holds", async () => {
467
+ const h = await start();
468
+ const { ctx, shown } = askingCtx(h, ["Dispatch now, store memories"]);
469
+ await ask(h, ctx, "Ready to execute — dispatch the NAK diagnosis to the peer now?");
470
+ const again = await ask(h, ctx, "Execute: dispatch to peer now?");
471
+ assert.match(text(again), /Dispatch now, store memories/, "guard hands the exact earlier choice back");
472
+ assert.equal(shown.length, 1, "user is not asked twice");
473
+ });
474
+
475
+ it("the count backstop catches wording drift the similarity arm misses", async () => {
476
+ const h = await start();
477
+ // Four asks that are all DIFFERENT enough to beat the similarity arm, yet a
478
+ // loop by the only wording-independent signal: no tool call in between.
479
+ const { ctx, shown } = askingCtx(h, ["A", "B", "C", "D"]);
480
+ await ask(h, ctx, "Which port profile?");
481
+ await ask(h, ctx, "Which RADIUS secret?");
482
+ await ask(h, ctx, "How long is the capture?");
483
+ assert.equal(shown.length, 3, "three distinct questions are a legitimate flow");
484
+ const fourth = await ask(h, ctx, "Pick a colour for the dashboard?");
485
+ assert.match(text(fourth), /Loop guard/, "4th consecutive ask with no tool call is refused");
486
+ assert.match(text(fourth), /call #4 in a row/, "guard names the run length");
487
+ assert.equal(shown.length, 3, "the 4th ask never opened a dialog");
488
+ });
489
+
490
+ it("any other tool call re-arms the dampener", async () => {
491
+ const h = await start();
492
+ const { ctx, shown } = askingCtx(h, ["Send it", "Send it"]);
493
+ await ask(h, ctx, "Dispatch now?");
494
+ // The model finally does the work instead of asking again.
495
+ await h.fire("tool_call", { toolName: "bash", input: { command: "ls" } }, ctx);
496
+ const after = await ask(h, ctx, "Dispatch now?");
497
+ assert.equal(text(after), "User selected: Send it", "re-armed after another tool call");
498
+ assert.equal(shown.length, 2, "the dialog opened again");
499
+ });
500
+
501
+ it("a fresh session re-arms the dampener", async () => {
502
+ const h = await start();
503
+ const { ctx } = askingCtx(h, ["Send it"]);
504
+ await ask(h, ctx, "Dispatch now?");
505
+ await start(h); // session_start clears the run
506
+ const { ctx: ctx2, shown } = askingCtx(h, ["Send it"]);
507
+ const after = await ask(h, ctx2, "Dispatch now?");
508
+ assert.equal(text(after), "User selected: Send it", "new session asks normally");
509
+ assert.equal(shown.length, 1, "dialog shown in the new session");
510
+ });
511
+
512
+ it("cancelled asks do not count as an answer to reuse", async () => {
513
+ const h = await start();
514
+ // ctx.ui.select returning undefined = user cancelled.
515
+ const cancelledCtx = h.ctx({ ui: { notify: () => {}, select: async () => undefined, editor: async () => undefined, setStatus: () => {}, setEditorText: () => {}, theme: { fg: (_c: string, t: string) => t } } });
516
+ await ask(h, cancelledCtx, "Dispatch now?");
517
+ const { ctx, shown } = askingCtx(h, ["Send it"]);
518
+ const repeat = await ask(h, ctx, "Dispatch now?");
519
+ assert.equal(text(repeat), "User selected: Send it", "no stale answer to hand back — dialog opens");
520
+ assert.equal(shown.length, 1);
521
+ });
522
+ });
523
+
524
+
413
525
  /** Recursively collect file names under dir ([] when missing). */
414
526
  function readSyncRecursive(dir: string, prefix = ""): string[] {
415
527
  if (!existsSync(dir)) return [];
@@ -341,12 +341,28 @@ export default function steeringModule(pi: ExtensionAPI): void {
341
341
  settings = readSteeringSettings(ctx); // read per turn — /config saves apply live
342
342
  activeFamily = family(ctx.model);
343
343
 
344
+ // pi 1.2.0 fires before_agent_start for sendMessage(..., { triggerTurn: true })
345
+ // runs too (cron fires, repair auto-bg follow-ups, subagent receipts) and
346
+ // splits the event on `messageType` — `prompt`/`images` exist only on the
347
+ // "user" variant. Older pi has no messageType and fires ONLY for user
348
+ // prompts, so "not custom" is the correct test on every supported version.
349
+ const messageType = (event as { messageType?: string }).messageType;
350
+ const isCustomRun = messageType === "custom";
351
+
344
352
  // ds-anchor bootstrap: request #1 gets the byte-identical Minimal prompt
345
353
  // and NO guidance (Super Power, selection guidance, hints all suppressed).
346
354
  // This handler is LAST in ceulen's chain, so the returned systemPrompt
347
355
  // REPLACES everything ponytail/subagent/advisor composed — deliberate, and
348
356
  // the only place this module clobbers rather than composes.
349
- if (anchorBootstrapping(ctx.model)) {
357
+ //
358
+ // A machine-initiated run must NOT consume the bootstrap: the minimal prompt
359
+ // plus bash/str_replace_editor-only tools would run a cron/background task
360
+ // under DSH minimal mode. The bootstrap stays pending for the next user turn.
361
+ if (isCustomRun && anchorTarget(ctx.model)) {
362
+ // Machine-initiated: never engage the bootstrap (trace once, then the
363
+ // normal composition path below).
364
+ anchorTracePush(`bootstrap skipped: custom-triggered run (promoted=${anchorPromoted})`);
365
+ } else if (anchorBootstrapping(ctx.model)) {
350
366
  scanAnchorEntries(ctx);
351
367
  if (!anchorPromoted) {
352
368
  anchorRunActive = true;
@@ -389,14 +405,17 @@ export default function steeringModule(pi: ExtensionAPI): void {
389
405
  // byte-identical — a per-turn source switch would invalidate the cache head.
390
406
  const selected = event.systemPromptOptions?.selectedTools;
391
407
  const activeForHint: readonly string[] = Array.isArray(selected) && selected.length > 0 ? selected : pi.getActiveTools();
392
- if (settings.firstToolHints && activeForHint.includes("bash")) {
393
- const runHint = runTaskFirstToolHint(event.prompt || "");
408
+ // Hints heuristically read the USER's task text: a custom-triggered run has
409
+ // no prompt, and hinting off a machine message would be noise.
410
+ const runPrompt = !isCustomRun && "prompt" in event ? event.prompt : "";
411
+ if (settings.firstToolHints && !isCustomRun && activeForHint.includes("bash")) {
412
+ const runHint = runTaskFirstToolHint(runPrompt);
394
413
  if (runHint) dynamicParts.push(runHint);
395
- const ghHint = githubCloneFirstToolHint(event.prompt || "");
414
+ const ghHint = githubCloneFirstToolHint(runPrompt);
396
415
  if (ghHint) dynamicParts.push(ghHint);
397
416
  }
398
- if (settings.firstToolHints && activeForHint.includes("find")) {
399
- const readHint = readUncertainPathHint(event.prompt || "");
417
+ if (settings.firstToolHints && !isCustomRun && activeForHint.includes("find")) {
418
+ const readHint = readUncertainPathHint(runPrompt);
400
419
  if (readHint) dynamicParts.push(readHint);
401
420
  }
402
421
 
@@ -90,4 +90,42 @@ describe("ds-anchor regressions", () => {
90
90
  assert.equal(out.max_completion_tokens, 256000, "budget pinned on the field the payload already carries");
91
91
  assert.equal(out.max_tokens, undefined, "conflicting max_tokens dropped");
92
92
  });
93
+
94
+ // pi 1.2.0: before_agent_start also fires for sendMessage({triggerTurn: true})
95
+ // runs (cron fires, auto-bg receipts) with messageType "custom" and NO prompt.
96
+ it("a custom-triggered run does NOT consume the bootstrap; the next user turn still gets it", () => {
97
+ const h = createFakePi();
98
+ h.setEntries([]);
99
+ h.fire("session_start", {}, h.ctx("deepseek-v4-pro"));
100
+ // cron-style custom run (no `prompt` field — pi's custom variant)
101
+ const custom = h.fire("before_agent_start", {
102
+ messageType: "custom", message: { customType: "ceulen-cron-fire", content: "job fired" },
103
+ systemPrompt: "FULL PI PROMPT", systemPromptOptions: {},
104
+ }, h.ctx("deepseek-v4-pro"));
105
+ assert.notEqual(custom?.systemPrompt, MINIMAL, "custom run must not get the minimal prompt");
106
+ const out = h.fire("before_provider_request", { payload: { tools: [{ name: "bash" }, { name: "str_replace_editor" }, { name: "edit" }] } }, h.ctx("deepseek-v4-pro"));
107
+ assert.equal(out?.tools, undefined, "custom run keeps the full tool catalog");
108
+ assert.equal(out?.max_tokens, undefined, "custom run gets no budget pin");
109
+ // the bootstrap stayed pending for the next user turn
110
+ const user = h.fire("before_agent_start", { messageType: "user", prompt: "do a task", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx("deepseek-v4-pro"));
111
+ assert.equal(user?.systemPrompt, MINIMAL, "the next USER turn still bootstraps");
112
+ });
113
+
114
+ it("a custom-triggered run gets no first-tool hints (no prompt to read)", () => {
115
+ const h = createFakePi(["bash", "read", "edit", "grep"]);
116
+ h.setEntries([]);
117
+ h.fire("session_start", {}, h.ctx("deepseek-v4-flash"));
118
+ const custom = h.fire("before_agent_start", {
119
+ messageType: "custom", message: { customType: "ceulen-cron-fire", content: "run the task" },
120
+ systemPrompt: "FULL", systemPromptOptions: {},
121
+ }, h.ctx("deepseek-v4-flash"));
122
+ // The static family guidance still composes; what must NOT appear is the
123
+ // prompt-derived dynamic hint (recognisable by its "Do NOT spawn a task
124
+ // agent" / task-shaped preamble). A user turn with the same text DOES add it.
125
+ const customDynamic = (custom?.systemPrompt ?? "").length;
126
+ const user = h.fire("before_agent_start", { messageType: "user", prompt: "refactor everything in the repo", systemPrompt: "FULL", systemPromptOptions: {} }, h.ctx("deepseek-v4-flash"));
127
+ assert.equal(user?.systemPrompt, custom?.systemPrompt, "a custom run adds no dynamic hint");
128
+ assert.ok(String(custom?.systemPrompt ?? "").startsWith("DeepSeek V4"), "static family guidance still composes on custom runs");
129
+ assert.ok(customDynamic > "FULL".length, "static guidance present");
130
+ });
93
131
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ceulen",
3
- "version": "0.17.0",
3
+ "version": "0.18.0",
4
4
  "description": "Ceulen — the Pi coding agent, fully dressed: one bundle extension carrying the full toolkit with a single /ceulen config command.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -52,8 +52,8 @@
52
52
  ]
53
53
  },
54
54
  "peerDependencies": {
55
- "@earendil-works/pi-coding-agent": ">=0.99.1 <1.2.0",
56
- "@earendil-works/pi-tui": ">=0.99.1 <1.2.0",
55
+ "@earendil-works/pi-coding-agent": ">=0.99.1 <1.3.0",
56
+ "@earendil-works/pi-tui": ">=0.99.1 <1.3.0",
57
57
  "typebox": "*"
58
58
  },
59
59
  "devDependencies": {
@@ -1,7 +1,13 @@
1
1
  // Validates every themes/*.json loads as a pi theme: name present + unique,
2
2
  // not colliding with pi's builtin names (dark/light/system are preloaded and
3
- // win dedupe), full pi-required color token set (from pi's theme-json schema),
4
- // and every value resolving to a var ref, #RRGGBB, 256-color index, or "".
3
+ // win dedupe), full pi-required color token set, every value resolving to a var
4
+ // ref, #RRGGBB, 256-color index, or "", and NO unknown keys anywhere.
5
+ //
6
+ // pi 1.2.0 (dist/modes/interactive/theme/theme-schema.js) validates themes
7
+ // loaded at startup with `additionalProperties: false` at BOTH the root and
8
+ // `colors` — an unknown key throws, the loader swallows it as a diagnostic, and
9
+ // the theme silently vanishes ("Theme not found: <name>" + system fallback).
10
+ // The ALLOWED/ROOT_KEYS gates below mirror that so `npm test` catches it here.
5
11
  // ponytail: adapted from @bacnh85/pi-themes scripts/validate-themes.mjs (MIT).
6
12
  // Usage: node scripts/validate-themes.mjs [dir] (dir defaults to ./themes)
7
13
  import { readFileSync, readdirSync } from "node:fs";
@@ -30,6 +36,21 @@ const REQUIRED = [
30
36
  "syntaxPunctuation", "thinkingOff", "thinkingMinimal", "thinkingLow",
31
37
  "thinkingMedium", "thinkingHigh", "thinkingXhigh", "bashMode",
32
38
  ];
39
+ // pi 1.2.0's full colors token set (THEME_TOKENS): REQUIRED plus the tokens
40
+ // that are optional because they carry a fallback.
41
+ // Source of truth: node_modules/@earendil-works/pi-coding-agent/dist/modes/
42
+ // interactive/theme/theme-tokens.js (not importable — the package `exports` map
43
+ // blocks deep subpaths). Re-derive on every pi minor bump:
44
+ // node -p "Object.keys(require('<pi>/dist/modes/interactive/theme/theme-tokens.js').THEME_TOKENS)"
45
+ // A token pi ADDS is not a break (an unknown key only fails when we SHIP one);
46
+ // a token pi REMOVES is — this file would then allow a key pi rejects.
47
+ const ALLOWED_COLORS = new Set([
48
+ ...REQUIRED,
49
+ "scrollbarTrack", "scrollbarThumb", "searchMatchBg", "searchMatchText", "thinkingMax",
50
+ ]);
51
+ // pi 1.2.0's root object (additionalProperties: false).
52
+ const ROOT_KEYS = new Set(["$schema", "name", "appearance", "vars", "colors", "export"]);
53
+ const EXPORT_KEYS = new Set(["pageBg", "cardBg", "infoBg"]);
33
54
  const BUILTIN = new Set(["dark", "light", "system"]);
34
55
 
35
56
  let failed = false;
@@ -63,9 +84,16 @@ for (const file of files) {
63
84
  const missing = REQUIRED.filter((k) => !(k in colors));
64
85
  if (missing.length) fail(`missing required tokens: ${missing.join(", ")}`);
65
86
 
87
+ const unknownRoot = Object.keys(theme).filter((k) => !ROOT_KEYS.has(k));
88
+ if (unknownRoot.length) fail(`unknown root keys: ${unknownRoot.join(", ")}`);
89
+ const unknownColors = Object.keys(colors).filter((k) => !ALLOWED_COLORS.has(k));
90
+ if (unknownColors.length) fail(`unknown color tokens: ${unknownColors.join(", ")}`);
91
+ const unknownExport = Object.keys(theme.export ?? {}).filter((k) => !EXPORT_KEYS.has(k));
92
+ if (unknownExport.length) fail(`unknown export keys: ${unknownExport.join(", ")}`);
93
+
66
94
  const vars = new Set(Object.keys(theme.vars ?? {}));
67
95
  const bad = [];
68
- for (const [k, v] of Object.entries({ ...vars.entries && theme.vars, ...colors })) {
96
+ for (const [k, v] of Object.entries({ ...theme.vars, ...colors })) {
69
97
  if (!isColorValue(v, vars)) bad.push(`${k}=${JSON.stringify(v)}`);
70
98
  }
71
99
  if (bad.length) fail(`unresolvable values: ${bad.join(", ")}`);
@@ -1,5 +1,5 @@
1
1
  {
2
- "$schema": "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json",
2
+ "$schema": "https://pi.dev/schemas/theme.schema.json",
3
3
  "name": "alabaster",
4
4
  "vars": {
5
5
  "alabaster": "#fdfcfb",
@@ -68,22 +68,7 @@
68
68
  "thinkingMedium": "#606870",
69
69
  "thinkingHigh": "#505860",
70
70
  "thinkingXhigh": "#303840",
71
- "bashMode": "#405840",
72
- "statusLineBg": "#ececf0",
73
- "statusLineSep": "#a0a0a8",
74
- "statusLineModel": "#505860",
75
- "statusLinePath": "#404850",
76
- "statusLineGitClean": "#305030",
77
- "statusLineGitDirty": "#806030",
78
- "statusLineContext": "#404860",
79
- "statusLineSpend": "#405050",
80
- "statusLineStaged": 28,
81
- "statusLineDirty": 136,
82
- "statusLineUntracked": 31,
83
- "statusLineOutput": 133,
84
- "statusLineCost": 133,
85
- "statusLineSubagents": "shadowGray",
86
- "pythonMode": "#f0c040"
71
+ "bashMode": "#405840"
87
72
  },
88
73
  "export": {
89
74
  "pageBg": "#fdfcfb",
@@ -1,5 +1,5 @@
1
1
  {
2
- "$schema": "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json",
2
+ "$schema": "https://pi.dev/schemas/theme.schema.json",
3
3
  "name": "amethyst",
4
4
  "vars": {
5
5
  "amethyst": "#b48eff",
@@ -11,7 +11,6 @@
11
11
  "lavender": "#c8a8e9",
12
12
  "crystalFacet": "#2a2435",
13
13
  "caveDark": "#140f18",
14
- "caveDeep": "#0f0b13",
15
14
  "selectedBg": "#221b28",
16
15
  "userMsgBg": "#1a1420",
17
16
  "toolPendingBg": "#1b1624",
@@ -55,7 +54,6 @@
55
54
  "toolDiffAdded": "#8eb897",
56
55
  "toolDiffRemoved": "#d96c75",
57
56
  "toolDiffContext": "#8b7a99",
58
- "link": "violet",
59
57
  "syntaxComment": "#7a6b88",
60
58
  "syntaxKeyword": "amethyst",
61
59
  "syntaxFunction": "gold",
@@ -71,22 +69,7 @@
71
69
  "thinkingMedium": "violet",
72
70
  "thinkingHigh": "amethyst",
73
71
  "thinkingXhigh": "lavender",
74
- "bashMode": "amethyst",
75
- "statusLineBg": "caveDeep",
76
- "statusLineSep": 240,
77
- "statusLineModel": "roseQuartz",
78
- "statusLinePath": "violet",
79
- "statusLineGitClean": "#8eb897",
80
- "statusLineGitDirty": "gold",
81
- "statusLineContext": "lavender",
82
- "statusLineSpend": "deepPurple",
83
- "statusLineStaged": 141,
84
- "statusLineDirty": 179,
85
- "statusLineUntracked": 183,
86
- "statusLineOutput": 213,
87
- "statusLineCost": 213,
88
- "statusLineSubagents": "amethyst",
89
- "pythonMode": "gold"
72
+ "bashMode": "amethyst"
90
73
  },
91
74
  "export": {
92
75
  "pageBg": "caveDark",