@akanjs/cli 3.2.0-rc.2 → 3.2.0-rc.21

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 (132) hide show
  1. package/.build-stamp +2 -1
  2. package/CodeAgent-faqv7t4g.js +11 -0
  3. package/{CodeTui-zyc7zaq6.js → CodeTui-vqck9tet.js} +822 -666
  4. package/README.ko.md +26 -1
  5. package/README.md +26 -1
  6. package/TunnelShare-bwe3ddv7.js +18 -0
  7. package/agent.command-p75jvgrd.js +56 -0
  8. package/akanCode.js +12 -12
  9. package/appExecutor-020cyesq.js +11 -0
  10. package/{application.command-vb278qnq.js → application.command-ta2knqxm.js} +72 -34
  11. package/{applicationBuildRunner-bqbyeg84.js → applicationBuildRunner-gkh82j2b.js} +18 -13
  12. package/buildBatch.proc.js +26 -11
  13. package/{cloud.command-ca777ee2.js → cloud.command-v3jhfvm5.js} +31 -28
  14. package/cloud.script-be9s1432.js +35 -0
  15. package/{code.command-j08txqcd.js → code.command-mh7dh1st.js} +14 -9
  16. package/{context.command-2fa6egp9.js → context.command-1ycfjkdd.js} +28 -23
  17. package/context.runner-333jkz86.js +34 -0
  18. package/{dependencyScanner-78sq8m4q.js → dependencyScanner-ge10gb52.js} +2 -2
  19. package/{devTui-w38ch13a.js → devTui-rf374y2w.js} +1 -1
  20. package/{fileSys-zpvt5gtf.js → fileSys-q22646yc.js} +1 -1
  21. package/{guideline.command-w6yqpdec.js → guideline.command-w1grfwh7.js} +9 -4
  22. package/guidelines/agentRule/agentRule.instruction.md +17 -5
  23. package/guidelines/akanApi/akanApi.instruction.md +5 -3
  24. package/guidelines/conventions/core.md +23 -5
  25. package/guidelines/conventions/rules/app.md +4 -1
  26. package/guidelines/conventions/rules/page.md +5 -0
  27. package/guidelines/errorCodes/errorCodes.instruction.md +158 -0
  28. package/guidelines/fieldRule/fieldRule.instruction.md +2 -1
  29. package/guidelines/mcpRule/mcpRule.instruction.md +86 -2
  30. package/guidelines/pageRule/pageRule.instruction.md +11 -1
  31. package/guidelines/runtimeRule/runtimeRule.instruction.md +7 -2
  32. package/guidelines/transportRule/transportRule.instruction.md +8 -1
  33. package/incrementalBuilder.proc.js +574 -410
  34. package/{index-c5ymqb05.js → index-013n6z7m.js} +12 -12
  35. package/{index-w15mg3km.js → index-0dm25wvf.js} +1 -1
  36. package/{index-8nbx607g.js → index-0hj82f9w.js} +136 -48
  37. package/{index-ebwkh7bt.js → index-1c0mjc2b.js} +25 -7
  38. package/{index-6h775rv3.js → index-1jk52ffq.js} +53 -12
  39. package/{index-hj6w4ka1.js → index-1p81ecbz.js} +1 -1
  40. package/{index-ygrdw6jw.js → index-1pjwsh2g.js} +65 -8
  41. package/{index-cbcwxp5v.js → index-22g3jq43.js} +9 -7
  42. package/{index-466z5931.js → index-2d9nm03s.js} +580 -364
  43. package/{index-0fj9ra3q.js → index-2k6mve6a.js} +18 -11
  44. package/{index-qd7xn2bk.js → index-2ny1e95c.js} +2 -2
  45. package/{index-j7p0jgaq.js → index-52w4jb87.js} +6 -6
  46. package/{index-e22zedc2.js → index-5h888r6j.js} +3 -3
  47. package/{index-7kmbqp0b.js → index-6pxmcaq8.js} +1 -1
  48. package/{index-xa0289eg.js → index-6zb17wcm.js} +16 -9
  49. package/{index-qgazn58x.js → index-7a07tdap.js} +50 -38
  50. package/{index-m5sg5spm.js → index-7ehdht84.js} +565 -187
  51. package/{index-y725zb1a.js → index-7v7tvgt7.js} +196 -168
  52. package/{index-pq5rjkch.js → index-88s746ns.js} +7 -2
  53. package/{index-r0a604h4.js → index-99kjwyma.js} +1 -1
  54. package/{index-2mrn1mrg.js → index-9f3reh2y.js} +1 -1
  55. package/{index-386canwe.js → index-9rv2zt48.js} +186 -121
  56. package/{index-wr9magsr.js → index-9zswcze5.js} +3 -3
  57. package/{index-xq97me1h.js → index-a41vv4cy.js} +811 -697
  58. package/{index-yf9wc28h.js → index-bejy9zyc.js} +1 -1
  59. package/{index-bdmgqzb5.js → index-bket1068.js} +58 -29
  60. package/{index-bns3wcpc.js → index-by2tvsq6.js} +1 -1
  61. package/{index-1cb9apzn.js → index-czf94w8c.js} +2 -2
  62. package/{index-65b6ms4c.js → index-d3178asw.js} +15 -11
  63. package/index-dss3ds74.js +127 -0
  64. package/{index-annxfpgz.js → index-eyfty8kk.js} +9 -9
  65. package/{index-ny2k80mv.js → index-ffa52fwf.js} +1 -1
  66. package/{index-8jpc5fqv.js → index-g7jgd4xs.js} +2 -2
  67. package/{index-abfbf01s.js → index-gwsesvqc.js} +2 -2
  68. package/{index-kcpk2d20.js → index-h1w4wqgd.js} +1474 -1139
  69. package/{index-j1hjb477.js → index-hp2c7xc2.js} +1 -1
  70. package/index-j4yvgfhr.js +70 -0
  71. package/{index-84c2pgak.js → index-jx2jcw1r.js} +89 -78
  72. package/{index-j6eeh5d7.js → index-knpm8sdm.js} +5 -5
  73. package/{index-2gees180.js → index-mpp4aas6.js} +62 -33
  74. package/index-na8r4a27.js +30 -0
  75. package/{index-0mqga3h9.js → index-nmxszh6x.js} +525 -440
  76. package/{index-35j83zkd.js → index-p5zh7pmc.js} +2 -2
  77. package/{index-20wvskt8.js → index-pt0agdck.js} +1 -1
  78. package/{index-htxck0pn.js → index-q444k260.js} +15 -10
  79. package/{index-wfmpxke3.js → index-qssq2d41.js} +2775 -3677
  80. package/{index-23860fej.js → index-rwgqba9p.js} +24 -9
  81. package/{index-v50xjbbe.js → index-t4d0ckde.js} +1 -1
  82. package/index-va90m8nd.js +25 -0
  83. package/index-vjbne22r.js +80 -0
  84. package/{index-djc5nxpy.js → index-w23tf30e.js} +6 -6
  85. package/{index-mvwvxgtd.js → index-wa01phm9.js} +289 -210
  86. package/{index-h7hehkw6.js → index-xczjdng6.js} +3 -1
  87. package/{index-vbhx60x5.js → index-xwe7y0gf.js} +2140 -2165
  88. package/index-ze48c0vd.js +788 -0
  89. package/{index-dk4g0x0d.js → index-zttyg7tg.js} +27 -16
  90. package/{index-ygdbn9jn.js → index-zyb0ebm4.js} +1 -1
  91. package/index.js +29 -24
  92. package/libExecutor-tq994592.js +10 -0
  93. package/{library.command-8d03a0pq.js → library.command-x219mhcx.js} +9 -4
  94. package/{localRegistry.command-vyv5k6t0.js → localRegistry.command-4p17wa9t.js} +30 -24
  95. package/{module.command-vy3kg965.js → module.command-tjthnvvr.js} +17 -8
  96. package/{package.command-qjh13rs9.js → package.command-c6df2hxx.js} +13 -8
  97. package/package.json +2 -2
  98. package/{page.command-t0nx1jat.js → page.command-gf06paq2.js} +9 -4
  99. package/{pipeline.command-2yjeas7m.js → pipeline.command-y07dgj9b.js} +14 -8
  100. package/pkgExecutor-stde3yc3.js +10 -0
  101. package/{primitive.command-8vm49279.js → primitive.command-0enfygxn.js} +13 -8
  102. package/{projectTypecheck-s9hhe5sa.js → projectTypecheck-mk8wefvd.js} +2 -1
  103. package/{prompter-qrwx1p17.js → prompter-qyggfhqd.js} +2 -2
  104. package/{quality.command-v76fev72.js → quality.command-dkbdztad.js} +23 -16
  105. package/{recipeScanner-4b69ybe0.js → recipeScanner-rrx69awy.js} +1 -1
  106. package/{repair.command-fp4m3w03.js → repair.command-g5vd95ax.js} +13 -8
  107. package/{routeSourceValidator-4h947v7c.js → routeSourceValidator-8n6j1vn7.js} +4 -2
  108. package/{scalar.command-hxe6try8.js → scalar.command-7909pg0d.js} +11 -6
  109. package/skills/akan-debug/SKILL.md +10 -3
  110. package/skills/akan-err/SKILL.md +7 -0
  111. package/skills/akan-mcp/SKILL.md +13 -2
  112. package/skills/akan-scaffold/SKILL.md +2 -2
  113. package/skills/akan-transport/SKILL.md +2 -0
  114. package/skills/akan-validate/SKILL.md +1 -0
  115. package/{subspace.command-q42n1844.js → subspace.command-at4jt1fb.js} +29 -23
  116. package/templates/biomeForm.ts +1 -1
  117. package/templates/env/_env.server.type.ts +1 -1
  118. package/templates/facetIndex/index.ts +2 -37
  119. package/templates/lib/sig.ts +0 -4
  120. package/templates/lib/useClient.ts +1 -1
  121. package/templates/workspaceRoot/AGENTS.md.template +2 -1
  122. package/{tunnel.command-22g11n0x.js → tunnel.command-91h92dwr.js} +17 -12
  123. package/{typeChecker-s640r6c0.js → typeChecker-bfrd1n9n.js} +1 -1
  124. package/typecheck.proc.js +6 -3
  125. package/{verify.command-rx43bha1.js → verify.command-pzky05ts.js} +26 -20
  126. package/{workflow.command-yg0d8mmq.js → workflow.command-mqqe4n12.js} +37 -19
  127. package/{workspace.command-fcfztvn5.js → workspace.command-y4rznvhx.js} +64 -53
  128. package/CodeAgent-6cpjtj25.js +0 -11
  129. package/TunnelShare-zkfkrw8w.js +0 -14
  130. package/agent.command-kf1g3nh4.js +0 -51
  131. package/cloud.script-agpxzq6j.js +0 -30
  132. package/context.runner-ftv8373t.js +0 -29
@@ -4,32 +4,29 @@ import {
4
4
  McpTokenStore,
5
5
  McpSignIn,
6
6
  AkanCodeCompaction2
7
- } from "./index-abfbf01s.js";
8
- import"./index-bns3wcpc.js";
9
- import"./index-35j83zkd.js";
7
+ } from "./index-gwsesvqc.js";
8
+ import"./index-by2tvsq6.js";
9
+ import"./index-p5zh7pmc.js";
10
10
  import {
11
11
  McpServerConfig,
12
12
  WorkspaceTrust
13
- } from "./index-w15mg3km.js";
13
+ } from "./index-0dm25wvf.js";
14
14
  import {
15
- CodeTuiLines2,
16
- CodeTuiAgents2,
17
- CodeTuiClipboard2,
18
15
  CodeTuiCommands2,
16
+ CodeTuiLines2,
19
17
  CodeTuiEditor2,
20
- CodeTuiFiles2,
18
+ CodeTuiAgents2,
21
19
  CodeTuiMarkdown2,
22
- CodeTuiParts2
23
- } from "./index-2mrn1mrg.js";
20
+ CodeTuiParts2,
21
+ CodeTuiClipboard2,
22
+ CodeTuiFiles2
23
+ } from "./index-9f3reh2y.js";
24
24
  import {
25
25
  openBrowser
26
26
  } from "./index-9dp031by.js";
27
27
 
28
28
  // pkgs/@akanjs/cli/code/CodeTui.tsx
29
- import {
30
- CodeTranscript,
31
- codeAgentClip
32
- } from "akanjs/common";
29
+ import { CodeTranscript } from "akanjs/common";
33
30
  import { render } from "ink";
34
31
 
35
32
  // pkgs/@akanjs/cli/ui/CodeTuiApp.tsx
@@ -550,234 +547,235 @@ class CodeTuiModels {
550
547
  }
551
548
  }
552
549
 
553
- // pkgs/@akanjs/cli/code/CodeTui.tsx
554
- import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
550
+ // pkgs/@akanjs/cli/code/CodeTuiCommandRunner.ts
551
+ class CodeTuiCommandRunner {
552
+ #agent;
553
+ #transcript;
554
+ #overlay;
555
+ #host;
556
+ constructor(agent, transcript, overlay, host) {
557
+ this.#agent = agent;
558
+ this.#transcript = transcript;
559
+ this.#overlay = overlay;
560
+ this.#host = host;
561
+ }
562
+ fork(argument) {
563
+ if (!this.#transcript.parts.some((part) => part.kind === "user"))
564
+ return this.#overlay.open("fork", "Nothing has been said in this session yet, so a fork of it is a new session.");
565
+ const from = this.#transcript.info?.sessionId ?? "";
566
+ try {
567
+ const forked = this.#agent.fork(argument.trim() || undefined);
568
+ this.#host.leave({ id: forked.id, notice: `forked \u2014 the original is akan code --resume ${from}` });
569
+ } catch (error) {
570
+ this.#host.fail(error);
571
+ }
572
+ }
573
+ agentList() {
574
+ const budget = this.#agent.profile.tools.subagent;
575
+ if (!budget)
576
+ return "Sub-agents are off in this profile.";
577
+ const column = Math.max(...Object.keys(SubagentPool2.kinds).map((kind) => kind.length)) + 2;
578
+ const kinds = Object.entries(SubagentPool2.kinds).map(([kind, spec]) => `${kind.padEnd(column)}${spec.desc}`);
579
+ return [
580
+ ...kinds,
581
+ "",
582
+ `At most ${budget.maxConcurrent} at once, ${budget.maxDepth} deep, ${budget.budget} tokens for the whole tree.`,
583
+ "",
584
+ "Ask for one in a sentence \u2014 the model calls the tool. Its reading never enters this conversation."
585
+ ].join(`
586
+ `);
587
+ }
588
+ mcp(argument) {
589
+ const words = argument.split(" ").filter(Boolean);
590
+ const local = words.includes("--local");
591
+ const [verb, name, ...rest] = words.filter((word) => word !== "--local");
592
+ const root = this.#agent.workspaceRoot;
593
+ if (!verb)
594
+ return this.#overlay.open("mcp", CodeTuiMcp.list(this.#mcpView()));
595
+ if (verb === "reload")
596
+ return this.#reload("reconnected the MCP servers");
597
+ if (verb === "login" || verb === "logout")
598
+ return this.#mcpAuth(verb, name);
599
+ if (verb !== "add" && verb !== "remove") {
600
+ const status = this.#agent.mcpServers().find((entry) => entry.name === verb);
601
+ if (status)
602
+ return this.#overlay.open(`mcp \xB7 ${verb}`, CodeTuiMcp.tools(status));
603
+ return this.#overlay.open("mcp", [`There is no /mcp ${verb}.`, "", ...CodeTuiMcp.usage].join(`
604
+ `));
605
+ }
606
+ if (!name)
607
+ return this.#overlay.open("mcp", [`Usage:`, "", ...CodeTuiMcp.usage].join(`
608
+ `));
609
+ if (!CodeTuiMcp.namePattern.test(name))
610
+ return this.#overlay.open("mcp", `"${name}" cannot name a server: letters, digits, dash and underscore only.`);
611
+ try {
612
+ if (verb === "remove") {
613
+ const scope = WorkspaceTrust.carry(root, "mcp", () => McpServerConfig.remove(root, name, local ? "workspace" : undefined));
614
+ const remaining = McpServerConfig.declared(root).find((entry) => entry.ref.name === name);
615
+ if (!scope)
616
+ return this.#overlay.open("mcp", remaining ? `"${name}" is not declared in this repo's file; the ${remaining.scope} file declares it \u2014 /mcp remove ${name} removes it there.` : `No server named "${name}" is declared.`);
617
+ if (!remaining)
618
+ return this.#reload(`removed ${name} from the ${scope} file`);
619
+ return this.#reload(`removed ${name} from the ${scope} file \u2014 the ${remaining.scope} file still declares it, so it still applies; /mcp remove ${name} again to remove it there`);
620
+ }
621
+ const scope = local ? "workspace" : "global";
622
+ const ref = WorkspaceTrust.carry(root, "mcp", () => McpServerConfig.add(root, name, rest, scope));
623
+ const where = scope === "global" ? "every repo" : "this repo";
624
+ return this.#reload(`added ${name} \xB7 ${McpServerConfig.targetOf(ref)} \xB7 ${where}`);
625
+ } catch (error) {
626
+ this.#host.fail(error);
627
+ }
628
+ }
629
+ #mcpAuth(verb, name) {
630
+ const root = this.#agent.workspaceRoot;
631
+ if (!name)
632
+ return this.#overlay.open("mcp", [`Usage: /mcp ${verb} <name>`, "", ...CodeTuiMcp.usage].join(`
633
+ `));
634
+ const ref = McpServerConfig.read(root).find((entry) => entry.name === name);
635
+ if (verb === "logout") {
636
+ if (!McpTokenStore.clear(ref ?? { name }))
637
+ return this.#overlay.open("mcp", `"${name}" is not signed in.`);
638
+ return this.#reload(`signed out of ${name}`);
639
+ }
640
+ if (!ref)
641
+ return this.#overlay.open("mcp", `No server named "${name}" is declared.`);
642
+ this.#host.say(`signing in to ${name} \u2014 finish in the browser`);
643
+ McpSignIn.run(ref, { open: (url) => void openBrowser(url), onNotice: (message) => this.#host.say(message) }).then(() => this.#reload(`signed in to ${name}`)).catch((error) => this.#host.fail(error));
644
+ }
645
+ #mcpView() {
646
+ const root = this.#agent.workspaceRoot;
647
+ const problem = McpServerConfig.problem(root);
648
+ return {
649
+ status: this.#agent.mcpServers(),
650
+ declared: McpServerConfig.declared(root),
651
+ files: McpServerConfig.files(root),
652
+ workspaceApproved: WorkspaceTrust.isTrusted(root, "mcp"),
653
+ ...problem ? { problem } : {}
654
+ };
655
+ }
656
+ #reload(notice) {
657
+ const id = this.#transcript.info?.sessionId;
658
+ if (!id || !this.#agent.sessions().some((entry) => entry.id === id))
659
+ return this.#overlay.open("mcp", "This session is not on disk yet, so there is nothing to reopen. Say something first, or start a new `akan code`.");
660
+ this.#host.leave({ id, notice });
661
+ }
662
+ static peerList(peers) {
663
+ if (!peers.length)
664
+ return "No other akan code session is running in this workspace.";
665
+ const column = Math.max(...peers.map((peer) => peer.name.length)) + 2;
666
+ const rows = peers.map((peer) => `${peer.name.padEnd(column)}${peer.id.slice(0, 8)} ${peer.cwd}`);
667
+ return [...rows, "", "/msg <peer> <text> hands one of them a message."].join(`
668
+ `);
669
+ }
670
+ message(argument) {
671
+ const [target, ...rest] = argument.split(" ");
672
+ const text = rest.join(" ").trim();
673
+ if (!target || !text)
674
+ return this.#overlay.open("msg", `Usage: /msg <peer> <text>
555
675
 
556
- class CodeTui {
557
- static frameMs = 34;
558
- static clipboardMs = 2000;
559
- static noticeMs = 4000;
676
+ ${CodeTuiCommandRunner.peerList(this.#agent.peers())}`);
677
+ try {
678
+ const peer = this.#agent.send(target, text);
679
+ this.#host.say(`sent to ${peer.name}`);
680
+ } catch (error) {
681
+ this.#host.fail(error);
682
+ }
683
+ }
684
+ setEffort(argument) {
685
+ const levels = this.#agent.efforts();
686
+ if (!levels.length)
687
+ return this.#overlay.open("effort", "This model does no reasoning, so it has no effort to set.");
688
+ const wanted = argument.trim().toLowerCase();
689
+ if (!levels.includes(wanted))
690
+ return this.#overlay.open("effort", `Usage: /effort <level>
691
+
692
+ now: ${this.#transcript.info?.effort ?? "unknown"}
693
+ ${levels.join(" \xB7 ")}`);
694
+ try {
695
+ this.#agent.setEffort(wanted);
696
+ this.#host.say(`effort ${this.#transcript.info?.effort ?? wanted}`);
697
+ } catch (error) {
698
+ this.#host.fail(error);
699
+ }
700
+ }
701
+ setAutoCompact(argument) {
702
+ const percent = CodeTuiAutoCompact.parse(argument);
703
+ if (percent === undefined)
704
+ return this.#overlay.open("autocompact", CodeTuiAutoCompact.usage(this.#transcript.info));
705
+ try {
706
+ this.#agent.setAutoCompactAt(percent);
707
+ this.#host.say(CodeTuiAutoCompact.describe(this.#transcript.info));
708
+ } catch (error) {
709
+ this.#host.fail(error);
710
+ }
711
+ }
712
+ setModel(argument) {
713
+ const wanted = argument.trim();
714
+ const [provider, ...rest] = wanted.split("/");
715
+ if (provider && rest.length)
716
+ return void this.#agent.setModel({ provider, id: rest.join("/") }).catch((error) => this.#host.fail(error));
717
+ const catalogue = this.#agent.catalogue();
718
+ if (wanted === "providers")
719
+ return this.#overlay.open("model \xB7 providers", CodeTuiModels.providers(catalogue));
720
+ if (!provider)
721
+ return this.#overlay.open("model", CodeTuiModels.list(catalogue));
722
+ const listing = CodeTuiModels.ofProvider(catalogue, provider);
723
+ if (listing)
724
+ return this.#overlay.open(`model \xB7 ${provider}`, listing);
725
+ return this.#overlay.open("model", [`There is no provider called "${provider}".`, "", ...CodeTuiModels.usage].join(`
726
+ `));
727
+ }
728
+ }
729
+
730
+ // pkgs/@akanjs/cli/code/CodeTuiFrame.ts
731
+ import { codeAgentClip } from "akanjs/common";
732
+ class CodeTuiFrame {
560
733
  static chromeRows = 1;
561
734
  static promptRuleRows = 1;
562
735
  static minBodyRows = 3;
563
736
  static maxInputRows = 8;
564
737
  static title = "Akan \u2014 write one line, deploy every stack";
565
- static imageMark = /\[image #(\d+)] ?/g;
566
- static freeTextKey = "__free_text__";
567
- static pasteOn = "\x1B[?2004h";
568
- static pasteOff = "\x1B[?2004l";
569
- #agent;
570
- #transcript = new CodeTranscript;
571
- #editor = new CodeTuiEditor2;
572
- #files;
573
- #listeners = new Set;
574
- #history = [];
575
- #instance;
738
+ #transcript;
576
739
  #stdout;
577
- #historyAt = -1;
578
- #anchor = null;
579
- #selected = 0;
580
- #typing = false;
581
- #menuAt = 0;
582
- #checked = [];
583
- #overlay = null;
584
- #overlayAt = 0;
585
- #picker = null;
586
- #images = [];
587
- #switchTo;
588
- #offered = false;
589
- #clipboardTimer = null;
590
- #notice = "";
591
- #opening;
592
- #warnings;
593
740
  #thinking;
594
- #noticeTimer = null;
595
- #frameTimer = null;
596
- #cached = null;
597
- #unsubscribe;
598
- #exiting = false;
599
- constructor(agent, { thinking = false, notice, warnings = [], ...streams } = {}) {
600
- this.#agent = agent;
741
+ constructor(transcript, stdout, thinking) {
742
+ this.#transcript = transcript;
743
+ this.#stdout = stdout;
601
744
  this.#thinking = thinking;
602
- this.#opening = notice ?? "";
603
- this.#warnings = warnings;
604
- this.#files = new CodeTuiFiles2(agent.profile.paths.root);
605
- this.#stdout = streams.stdout ?? process.stdout;
606
- this.#stdout.on("resize", this.#onResize);
607
- this.#instance = render(/* @__PURE__ */ jsxDEV2(CodeTuiApp, {
608
- actions: {
609
- subscribe: this.#subscribe,
610
- snapshot: this.#snapshot,
611
- type: this.#type,
612
- edit: this.#edit,
613
- submit: this.#submit,
614
- newline: this.#newline,
615
- paste: this.#paste,
616
- pasted: this.#pasted,
617
- complete: this.#complete,
618
- vertical: this.#vertical,
619
- scroll: this.#scroll,
620
- move: this.#move,
621
- toggle: this.#toggle,
622
- answerConfirm: this.#answerConfirm,
623
- cancel: this.#cancel,
624
- interrupt: this.#interrupt
625
- }
626
- }, undefined, false, undefined, this), {
627
- patchConsole: true,
628
- exitOnCtrlC: false,
629
- kittyKeyboard: { mode: "auto" },
630
- ...streams
631
- });
632
745
  }
633
- async run(seed) {
634
- this.#stdout.write(`${CodeTui.pasteOn}${CodeTuiMouse.on}`);
635
- if (this.#opening)
636
- this.#say(this.#opening);
637
- for (const warning of this.#warnings)
638
- this.#transcript.note("warning", warning);
639
- this.#unsubscribe = this.#agent.on((event) => {
640
- this.#transcript.apply(event);
641
- if (event.type === "question")
642
- this.#openQuestion(event.question);
643
- this.#scheduleFrame();
644
- });
645
- this.#agent.announce();
646
- this.#files.load().then(() => this.#renderNow());
647
- this.#watchClipboard();
648
- if (seed?.trim())
649
- this.#send(seed.trim());
650
- await this.#instance.waitUntilExit();
651
- this.#close();
652
- return this.#switchTo;
746
+ static layout(frameRows, askRows, railRows = 0) {
747
+ const room = Math.max(1, frameRows - CodeTuiFrame.minBodyRows - CodeTuiFrame.chromeRows - railRows);
748
+ const ask = Math.max(1, Math.min(askRows, room));
749
+ return {
750
+ ask,
751
+ bodyHeight: Math.max(CodeTuiFrame.minBodyRows, frameRows - ask - CodeTuiFrame.chromeRows - railRows)
752
+ };
653
753
  }
654
- close() {
655
- this.#quit();
754
+ static frameRowsOf(terminalRows) {
755
+ return Math.max(CodeTuiFrame.minBodyRows + CodeTuiFrame.chromeRows + 1, terminalRows - 1);
656
756
  }
657
- #watchClipboard() {
658
- if (!this.#agent.canSeeImages)
659
- return;
660
- this.#clipboardTimer = setInterval(() => {
661
- const offered = CodeTuiClipboard2.has();
662
- if (offered === this.#offered)
663
- return;
664
- this.#offered = offered;
665
- this.#renderNow();
666
- }, CodeTui.clipboardMs);
757
+ toggleThinking() {
758
+ this.#thinking = !this.#thinking;
759
+ return this.#thinking;
667
760
  }
668
- #close() {
669
- if (this.#clipboardTimer)
670
- clearInterval(this.#clipboardTimer);
671
- this.#clipboardTimer = null;
672
- if (this.#frameTimer)
673
- clearTimeout(this.#frameTimer);
674
- if (this.#noticeTimer)
675
- clearTimeout(this.#noticeTimer);
676
- this.#frameTimer = null;
677
- this.#noticeTimer = null;
678
- this.#stdout.off("resize", this.#onResize);
679
- this.#unsubscribe?.();
680
- this.#farewell();
761
+ lines(width) {
762
+ return [
763
+ ...CodeTuiLines2.rows(this.#banner(), width, "banner"),
764
+ ...CodeTuiParts2.lines(this.#transcript.parts, width, { thinking: this.#thinking })
765
+ ];
681
766
  }
682
- #farewell() {
683
- const info = this.#transcript.info;
684
- if (this.#switchTo || !info?.sessionId || !this.#agent.sessions().length)
685
- return;
686
- if (!this.#transcript.parts.some((part) => part.kind === "user"))
687
- return;
688
- const name = info.name ? ` (${info.name})` : "";
689
- this.#stdout.write(`Resume this session${name} with:
690
- akan code --resume ${info.sessionId}
691
- `);
692
- }
693
- #onResize = () => this.#renderNow();
694
- #subscribe = (listener) => {
695
- this.#listeners.add(listener);
696
- return () => this.#listeners.delete(listener);
697
- };
698
- #scheduleFrame() {
699
- if (this.#frameTimer)
700
- return;
701
- this.#frameTimer = setTimeout(() => {
702
- this.#frameTimer = null;
703
- this.#renderNow();
704
- }, CodeTui.frameMs);
705
- }
706
- #renderNow() {
707
- this.#cached = null;
708
- for (const listener of this.#listeners)
709
- listener();
710
- }
711
- static layout(frameRows, askRows, railRows = 0) {
712
- const room = Math.max(1, frameRows - CodeTui.minBodyRows - CodeTui.chromeRows - railRows);
713
- const ask = Math.max(1, Math.min(askRows, room));
714
- return { ask, bodyHeight: Math.max(CodeTui.minBodyRows, frameRows - ask - CodeTui.chromeRows - railRows) };
715
- }
716
- static frameRowsOf(terminalRows) {
717
- return Math.max(CodeTui.minBodyRows + CodeTui.chromeRows + 1, terminalRows - 1);
718
- }
719
- #snapshot = () => {
720
- if (this.#cached)
721
- return this.#cached;
722
- const columns = Math.max(40, this.#stdout.columns || 80);
723
- const frameRows = CodeTui.frameRowsOf(Math.max(10, this.#stdout.rows || 24));
724
- const question = this.#transcript.question;
725
- const approval = this.#transcript.approval;
726
- const mode = this.#typing ? "input" : CodeTui.#modeOf(question, approval);
727
- const subagents = this.#railRows(columns);
728
- const ask = mode === "input" ? this.#inputBlock(columns, frameRows - subagents.length) : this.#askBlock(question, frameRows - subagents.length);
729
- const { bodyHeight } = CodeTui.layout(frameRows, ask.rows, subagents.length);
730
- const width = columns - 2;
731
- const lines = this.#lines(width);
732
- const end = this.#anchor === null ? lines.length : Math.min(lines.length, Math.max(bodyHeight, this.#anchor));
733
- const start = Math.max(0, end - bodyHeight);
734
- const above = start;
735
- const below = lines.length - end;
736
- this.#cached = {
737
- topRule: CodeTui.rule(this.#anchor === null ? "" : `\u25B2${above} \u25BC${below} paused`, this.#transcript.info?.name ?? this.#transcript.info?.sessionId.slice(0, 8) ?? "", columns),
738
- bottomRule: CodeTui.rule(this.#queueLabel(), this.#statusLabel(), columns),
739
- lines: lines.slice(start, end),
740
- above,
741
- below,
742
- following: this.#anchor === null,
743
- overlay: this.#overlayBlock(width, bodyHeight),
744
- status: this.#status(),
745
- subagents,
746
- mode,
747
- placeholder: this.#placeholder(),
748
- offered: this.#offered,
749
- prompt: CodeTui.#promptOf(question, approval),
750
- selected: ask.selected,
751
- checked: this.#checked,
752
- multiSelect: !!question?.multiSelect,
753
- notice: this.#notice,
754
- hint: this.#overlay ? "esc close \xB7 \u2191\u2193 scroll" : this.#hint(mode, !!question?.multiSelect),
755
- columns,
756
- frameRows,
757
- bodyHeight,
758
- cursor: ask.caret ? { x: promptMarkWidth + ask.caret.col, y: bodyHeight + ask.above + ask.caret.row } : null,
759
- ...ask.snapshot
760
- };
761
- return this.#cached;
762
- };
763
- #lines(width) {
764
- return [
765
- ...CodeTuiLines2.rows(this.#banner(), width, "banner"),
766
- ...CodeTuiParts2.lines(this.#transcript.parts, width, { thinking: this.#thinking })
767
- ];
768
- }
769
- #railRows(columns) {
767
+ railRows(columns) {
770
768
  const agents = this.#transcript.subagents;
771
769
  if (!agents.length)
772
770
  return [];
773
771
  const rows = CodeTuiAgents2.rows(agents, this.#transcript.info?.name ?? "main", columns);
774
- const room = CodeTui.frameRowsOf(Math.max(10, this.#stdout.rows || 24)) - CodeTui.minBodyRows - CodeTui.chromeRows - 2 * CodeTui.promptRuleRows - 1;
772
+ const room = CodeTuiFrame.frameRowsOf(Math.max(10, this.#stdout.rows || 24)) - CodeTuiFrame.minBodyRows - CodeTuiFrame.chromeRows - 2 * CodeTuiFrame.promptRuleRows - 1;
775
773
  return rows.length <= room ? rows : [];
776
774
  }
777
775
  #banner() {
778
776
  const cwd = this.#transcript.info?.cwd;
779
777
  return [
780
- { prefix: { text: "\u273B ", color: "cyan" }, spans: [{ text: CodeTui.title, bold: true }] },
778
+ { prefix: { text: "\u273B ", color: "cyan" }, spans: [{ text: CodeTuiFrame.title, bold: true }] },
781
779
  {
782
780
  prefix: { text: " " },
783
781
  spans: [{ text: cwd ? `${cwd} \xB7 /help for commands` : "/help for commands", dim: true }]
@@ -803,7 +801,52 @@ class CodeTui {
803
801
  ] : [{ text: "\u2500", dim: true }]
804
802
  ];
805
803
  }
806
- #overlayBlock(width, height) {
804
+ queueLabel() {
805
+ const queue = this.#transcript.queue;
806
+ const parts = [];
807
+ if (queue.steering || queue.followUp)
808
+ parts.push(`queued ${queue.steering + queue.followUp}`);
809
+ if (this.#transcript.compacting)
810
+ parts.push("compacting");
811
+ return parts.join(" \xB7 ");
812
+ }
813
+ statusLabel() {
814
+ const info = this.#transcript.info;
815
+ if (!info)
816
+ return "starting\u2026";
817
+ const context = this.#transcript.context;
818
+ const window = info.contextTokens ? `${Math.round(info.contextTokens / 1000)}k` : "";
819
+ const used = context?.max ? `${Math.round(context.used / context.max * 100)}% of ${window}` : "";
820
+ const compactsAt = info.autoCompactAt ? `compacts at ${info.autoCompactAt}%` : "";
821
+ return [info.model?.name ?? "no model", used || window && `${window} ctx`, compactsAt, info.profile, info.effort].filter((part) => !!part).join(" \xB7 ");
822
+ }
823
+ status() {
824
+ if (this.#transcript.compacting)
825
+ return "compacting";
826
+ return this.#transcript.streaming ? "working" : "";
827
+ }
828
+ }
829
+
830
+ // pkgs/@akanjs/cli/code/CodeTuiOverlay.ts
831
+ class CodeTuiOverlay {
832
+ #agent;
833
+ #transcript;
834
+ #host;
835
+ #overlay = null;
836
+ #overlayAt = 0;
837
+ #picker = null;
838
+ constructor(agent, transcript, host) {
839
+ this.#agent = agent;
840
+ this.#transcript = transcript;
841
+ this.#host = host;
842
+ }
843
+ get shown() {
844
+ return this.#overlay !== null;
845
+ }
846
+ get picker() {
847
+ return this.#picker;
848
+ }
849
+ block(width, height) {
807
850
  if (this.#picker)
808
851
  return this.#pickerBlock(width, height);
809
852
  const overlay = this.#overlay;
@@ -811,7 +854,7 @@ class CodeTui {
811
854
  return null;
812
855
  const room = Math.max(1, height - 3);
813
856
  const body = Math.max(8, width - 4);
814
- const all = CodeTui.#overlayRows(overlay.text, body);
857
+ const all = CodeTuiOverlay.#overlayRows(overlay.text, body);
815
858
  const first = Math.max(0, Math.min(this.#overlayAt, all.length - room));
816
859
  return {
817
860
  title: overlay.title,
@@ -828,7 +871,7 @@ class CodeTui {
828
871
  const room = Math.max(1, height - 3);
829
872
  const body = Math.max(8, width - 4);
830
873
  const first = Math.max(0, Math.min(picker.at - Math.floor(room / 2), picker.entries.length - room));
831
- const rows = picker.entries.slice(first, first + room).map((entry, at) => CodeTui.#sessionRow(entry, first + at === picker.at));
874
+ const rows = picker.entries.slice(first, first + room).map((entry, at) => CodeTuiOverlay.#sessionRow(entry, first + at === picker.at));
832
875
  return {
833
876
  title: `sessions \xB7 ${picker.entries.length}`,
834
877
  lines: rows.flatMap((row, at) => CodeTuiLines2.rows([row], body, `sessions:${first + at}`).slice(0, 1)),
@@ -843,7 +886,10 @@ class CodeTui {
843
886
  prefix: { text: selected ? "\u276F " : " ", color: "cyan" },
844
887
  spans: [
845
888
  { text: label, bold: selected },
846
- { text: ` ${CodeTui.#ago(entry.updatedAt)} \xB7 ${entry.turns} turn${entry.turns === 1 ? "" : "s"}`, dim: true },
889
+ {
890
+ text: ` ${CodeTuiOverlay.#ago(entry.updatedAt)} \xB7 ${entry.turns} turn${entry.turns === 1 ? "" : "s"}`,
891
+ dim: true
892
+ },
847
893
  ...entry.opening ? [{ text: ` ${entry.opening}`, dim: true }] : []
848
894
  ]
849
895
  };
@@ -856,17 +902,102 @@ class CodeTui {
856
902
  return `${Math.round(minutes / 60)}h ago`;
857
903
  return `${Math.round(minutes / (60 * 24))}d ago`;
858
904
  }
859
- #inputBlock(columns, frameRows) {
905
+ static #overlayRows(text, width) {
906
+ return text.split(`
907
+ `).flatMap((line, at) => CodeTuiLines2.rows(line.trim() ? CodeTuiMarkdown2.rows(line, width) : [{ spans: [{ text: " " }] }], width, `overlay:${at}`));
908
+ }
909
+ openSessions = () => {
910
+ const entries = this.#agent.sessions();
911
+ if (!entries.length)
912
+ return this.#host.say("no stored sessions yet");
913
+ const current = this.#transcript.info?.sessionId;
914
+ this.#picker = {
915
+ entries,
916
+ at: Math.max(0, entries.findIndex((entry) => entry.id === current))
917
+ };
918
+ this.#host.render();
919
+ };
920
+ move(delta) {
921
+ const picker = this.#picker;
922
+ if (!picker)
923
+ return;
924
+ picker.at = Math.max(0, Math.min(picker.entries.length - 1, picker.at + delta));
925
+ this.#host.render();
926
+ }
927
+ scroll(delta) {
928
+ this.#overlayAt = Math.max(0, this.#overlayAt + Math.trunc(delta));
929
+ this.#host.render();
930
+ }
931
+ open(title, text) {
932
+ this.#overlay = { title, text };
933
+ this.#overlayAt = 0;
934
+ this.#host.render();
935
+ }
936
+ dismiss() {
937
+ this.#overlay = null;
938
+ this.#overlayAt = 0;
939
+ this.#picker = null;
940
+ this.#host.render();
941
+ }
942
+ }
943
+
944
+ // pkgs/@akanjs/cli/code/CodeTuiPrompt.ts
945
+ class CodeTuiPrompt {
946
+ static clipboardMs = 2000;
947
+ static imageMark = /\[image #(\d+)] ?/g;
948
+ #agent;
949
+ #transcript;
950
+ #editor;
951
+ #overlay;
952
+ #host;
953
+ #files;
954
+ #history = [];
955
+ #historyAt = -1;
956
+ #menuAt = 0;
957
+ #images = [];
958
+ #offered = false;
959
+ #clipboardTimer = null;
960
+ constructor(agent, transcript, editor, overlay, host) {
961
+ this.#agent = agent;
962
+ this.#transcript = transcript;
963
+ this.#editor = editor;
964
+ this.#overlay = overlay;
965
+ this.#host = host;
966
+ this.#files = new CodeTuiFiles2(agent.profile.paths.root);
967
+ }
968
+ get offered() {
969
+ return this.#offered;
970
+ }
971
+ load() {
972
+ return this.#files.load();
973
+ }
974
+ watchClipboard() {
975
+ if (!this.#agent.canSeeImages)
976
+ return;
977
+ this.#clipboardTimer = setInterval(() => {
978
+ const offered = CodeTuiClipboard2.has();
979
+ if (offered === this.#offered)
980
+ return;
981
+ this.#offered = offered;
982
+ this.#host.render();
983
+ }, CodeTuiPrompt.clipboardMs);
984
+ }
985
+ unwatchClipboard() {
986
+ if (this.#clipboardTimer)
987
+ clearInterval(this.#clipboardTimer);
988
+ this.#clipboardTimer = null;
989
+ }
990
+ block(columns, frameRows) {
860
991
  const all = this.#menu()?.options ?? [];
861
992
  const { rows, row, col } = this.#editor.layout(columns - promptMarkWidth - 1);
862
993
  const offered = this.#offered ? 1 : 0;
863
- const room = frameRows - CodeTui.minBodyRows - CodeTui.chromeRows - 2 * CodeTui.promptRuleRows - offered;
994
+ const room = frameRows - CodeTuiFrame.minBodyRows - CodeTuiFrame.chromeRows - 2 * CodeTuiFrame.promptRuleRows - offered;
864
995
  const menuRows = Math.max(0, Math.min(all.length, room - 1));
865
996
  const menuFrom = Math.max(0, Math.min(this.#menuAt - Math.floor(menuRows / 2), all.length - menuRows));
866
997
  const menu = all.slice(menuFrom, menuFrom + menuRows);
867
- const above = menu.length + CodeTui.promptRuleRows + offered;
868
- const chrome = above + CodeTui.promptRuleRows;
869
- const budget = Math.max(1, Math.min(CodeTui.maxInputRows, room - menu.length));
998
+ const above = menu.length + CodeTuiFrame.promptRuleRows + offered;
999
+ const chrome = above + CodeTuiFrame.promptRuleRows;
1000
+ const budget = Math.max(1, Math.min(CodeTuiFrame.maxInputRows, room - menu.length));
870
1001
  const first = Math.max(0, Math.min(row - budget + 1, rows.length - budget));
871
1002
  const shown = rows.slice(first, first + budget);
872
1003
  return {
@@ -882,25 +1013,6 @@ class CodeTui {
882
1013
  }
883
1014
  };
884
1015
  }
885
- #askBlock(question, frameRows) {
886
- const all = CodeTui.#optionsOf(question);
887
- const chrome = 1 + 2 * CodeTui.promptRuleRows;
888
- const budget = Math.max(1, frameRows - CodeTui.minBodyRows - CodeTui.chromeRows - chrome);
889
- const shown = Math.min(all.length, budget);
890
- const first = Math.max(0, Math.min(this.#selected - Math.floor(shown / 2), all.length - shown));
891
- return {
892
- rows: chrome + shown,
893
- above: CodeTui.promptRuleRows,
894
- selected: this.#selected - first,
895
- caret: undefined,
896
- snapshot: {
897
- input: [],
898
- menu: [],
899
- menuSelected: 0,
900
- options: all.slice(first, first + shown)
901
- }
902
- };
903
- }
904
1016
  #menu() {
905
1017
  const prefix = CodeTuiCommands2.prefixOf(this.#editor.text, this.#editor.caret);
906
1018
  if (prefix !== undefined)
@@ -922,77 +1034,7 @@ class CodeTui {
922
1034
  return null;
923
1035
  return { kind: "file", from: token.from, to: token.to, options };
924
1036
  }
925
- static #overlayRows(text, width) {
926
- return text.split(`
927
- `).flatMap((line, at) => CodeTuiLines2.rows(line.trim() ? CodeTuiMarkdown2.rows(line, width) : [{ spans: [{ text: " " }] }], width, `overlay:${at}`));
928
- }
929
- #queueLabel() {
930
- const queue = this.#transcript.queue;
931
- const parts = [];
932
- if (queue.steering || queue.followUp)
933
- parts.push(`queued ${queue.steering + queue.followUp}`);
934
- if (this.#transcript.compacting)
935
- parts.push("compacting");
936
- return parts.join(" \xB7 ");
937
- }
938
- #statusLabel() {
939
- const info = this.#transcript.info;
940
- if (!info)
941
- return "starting\u2026";
942
- const context = this.#transcript.context;
943
- const window = info.contextTokens ? `${Math.round(info.contextTokens / 1000)}k` : "";
944
- const used = context?.max ? `${Math.round(context.used / context.max * 100)}% of ${window}` : "";
945
- const compactsAt = info.autoCompactAt ? `compacts at ${info.autoCompactAt}%` : "";
946
- return [info.model?.name ?? "no model", used || window && `${window} ctx`, compactsAt, info.profile, info.effort].filter((part) => !!part).join(" \xB7 ");
947
- }
948
- #status() {
949
- if (this.#transcript.compacting)
950
- return "compacting";
951
- return this.#transcript.streaming ? "working" : "";
952
- }
953
- static #modeOf(question, approval) {
954
- if (approval)
955
- return "confirm";
956
- if (!question)
957
- return "input";
958
- if (question.kind === "confirm")
959
- return "confirm";
960
- if (question.kind === "select" && question.options?.length)
961
- return "select";
962
- return "input";
963
- }
964
- static #optionsOf(question) {
965
- const options = (question?.options ?? []).map((option) => ({
966
- key: option.key,
967
- label: option.recommended ? `${option.label} (recommended)` : option.label,
968
- ...option.detail ? { detail: option.detail } : {}
969
- }));
970
- if (!options.length || !question?.freeText)
971
- return options;
972
- return [...options, { key: CodeTui.freeTextKey, label: "Something else\u2026", detail: "answer in your own words" }];
973
- }
974
- static #promptOf(question, approval) {
975
- if (approval)
976
- return `approve? ${approval.summary} [y/n]`;
977
- return question ? `? ${question.prompt}` : "";
978
- }
979
- #hint(mode, multiSelect) {
980
- if (this.#typing)
981
- return "enter answer \xB7 esc back to the choices";
982
- if (mode === "confirm")
983
- return "y yes \xB7 n no \xB7 esc no";
984
- if (mode === "select")
985
- return `\u2191\u2193 choose${multiSelect ? " \xB7 space toggle" : ""} \xB7 enter answer \xB7 esc skip \xB7 pgup/pgdn scroll`;
986
- return "enter send \xB7 shift+enter newline \xB7 \u2191\u2193 move \xB7 esc interrupt \xB7 pgup/pgdn scroll \xB7 ^c quit \xB7 /help";
987
- }
988
- #placeholder() {
989
- if (this.#typing)
990
- return "your answer";
991
- if (this.#transcript.question)
992
- return "type an answer, or esc to skip";
993
- return this.#transcript.streaming ? "type to steer, esc to interrupt" : "ask for something, / for commands";
994
- }
995
- #type = (text) => {
1037
+ type = (text) => {
996
1038
  const pasted = this.#agent.canSeeImages ? CodeTuiClipboard2.imagePathsIn(text) : undefined;
997
1039
  if (pasted?.images.length) {
998
1040
  for (const file of pasted.images)
@@ -1003,19 +1045,19 @@ class CodeTui {
1003
1045
  this.#editor.insert(text);
1004
1046
  this.#menuAt = 0;
1005
1047
  this.#historyAt = -1;
1006
- this.#renderNow();
1048
+ this.#host.render();
1007
1049
  };
1008
- #newline = () => {
1050
+ newline = () => {
1009
1051
  this.#editor.newline();
1010
1052
  this.#historyAt = -1;
1011
- this.#renderNow();
1053
+ this.#host.render();
1012
1054
  };
1013
- #edit = (action) => {
1014
- const width = this.#snapshot().columns - promptMarkWidth - 1;
1055
+ edit = (action) => {
1056
+ const width = this.#host.snapshot().columns - promptMarkWidth - 1;
1015
1057
  const run = {
1016
1058
  backspace: () => this.#editor.backspace(),
1017
1059
  delete: () => this.#editor.deleteForward(),
1018
- left: () => this.#editor.caret ? this.#editor.left() : this.#openSessions(),
1060
+ left: () => this.#editor.caret ? this.#editor.left() : this.#overlay.openSessions(),
1019
1061
  right: () => this.#editor.right(),
1020
1062
  wordLeft: () => this.#editor.wordLeft(),
1021
1063
  wordRight: () => this.#editor.wordRight(),
@@ -1027,25 +1069,21 @@ class CodeTui {
1027
1069
  run[action]();
1028
1070
  if (action.startsWith("delete") || action === "backspace")
1029
1071
  this.#historyAt = -1;
1030
- this.#renderNow();
1072
+ this.#host.render();
1031
1073
  };
1032
- #vertical = (delta) => {
1033
- if (this.#picker)
1034
- return this.#move(delta);
1035
- if (this.#overlay)
1036
- return this.#scroll(delta);
1074
+ vertical(delta) {
1037
1075
  const menu = this.#menu()?.options ?? [];
1038
1076
  if (menu.length) {
1039
1077
  this.#menuAt = (this.#menuAt + delta + menu.length) % menu.length;
1040
- return this.#renderNow();
1078
+ return this.#host.render();
1041
1079
  }
1042
- if (this.#historyAt < 0 && this.#editor.move(delta, this.#snapshot().columns - promptMarkWidth - 1))
1043
- return this.#renderNow();
1080
+ if (this.#historyAt < 0 && this.#editor.move(delta, this.#host.snapshot().columns - promptMarkWidth - 1))
1081
+ return this.#host.render();
1044
1082
  if (delta < 0)
1045
1083
  return this.#historyPrev();
1046
1084
  return this.#historyNext();
1047
- };
1048
- #complete = () => {
1085
+ }
1086
+ complete = () => {
1049
1087
  const menu = this.#menu();
1050
1088
  const chosen = menu?.options[this.#menuAt];
1051
1089
  if (!menu || !chosen)
@@ -1054,14 +1092,14 @@ class CodeTui {
1054
1092
  const text = menu.kind === "command" ? `/${chosen.key}${command?.arg ? " " : ""}` : `@${chosen.key} `;
1055
1093
  this.#editor.replace(menu.from, menu.to, text);
1056
1094
  this.#menuAt = 0;
1057
- this.#renderNow();
1095
+ this.#host.render();
1058
1096
  };
1059
1097
  #historyPrev() {
1060
1098
  if (!this.#history.length)
1061
1099
  return;
1062
1100
  this.#historyAt = this.#historyAt < 0 ? this.#history.length - 1 : Math.max(0, this.#historyAt - 1);
1063
1101
  this.#editor.set(this.#history[this.#historyAt] ?? "");
1064
- this.#renderNow();
1102
+ this.#host.render();
1065
1103
  }
1066
1104
  #historyNext() {
1067
1105
  if (this.#historyAt < 0)
@@ -1072,138 +1110,52 @@ class CodeTui {
1072
1110
  this.#editor.clear();
1073
1111
  } else
1074
1112
  this.#editor.set(this.#history[this.#historyAt] ?? "");
1075
- this.#renderNow();
1113
+ this.#host.render();
1076
1114
  }
1077
- #scroll = (delta) => {
1078
- if (this.#picker)
1079
- return this.#move(Math.sign(delta));
1080
- if (this.#overlay) {
1081
- this.#overlayAt = Math.max(0, this.#overlayAt + Math.trunc(delta));
1082
- return this.#renderNow();
1083
- }
1084
- const snapshot = this.#snapshot();
1085
- const total = snapshot.above + snapshot.lines.length + snapshot.below;
1086
- const rows = Math.max(1, snapshot.lines.length);
1087
- if (total <= rows)
1088
- return;
1089
- const end = this.#anchor === null ? total : this.#anchor;
1090
- const next = Math.min(total, Math.max(rows, end + Math.trunc(delta)));
1091
- this.#anchor = next >= total ? null : next;
1092
- this.#renderNow();
1093
- };
1094
- #move = (delta) => {
1095
- const picker = this.#picker;
1096
- if (picker) {
1097
- picker.at = Math.max(0, Math.min(picker.entries.length - 1, picker.at + delta));
1098
- return this.#renderNow();
1099
- }
1100
- const count = CodeTui.#optionsOf(this.#transcript.question).length;
1101
- if (!count)
1102
- return;
1103
- this.#selected = (this.#selected + delta + count) % count;
1104
- this.#renderNow();
1105
- };
1106
- #toggle = () => {
1107
- const option = CodeTui.#optionsOf(this.#transcript.question)[this.#selected];
1108
- if (!option)
1109
- return;
1110
- this.#checked = this.#checked.includes(option.key) ? this.#checked.filter((key) => key !== option.key) : [...this.#checked, option.key];
1111
- this.#renderNow();
1112
- };
1113
- #answerConfirm = (value) => {
1114
- const approval = this.#transcript.approval;
1115
- if (approval)
1116
- return void this.#agent.approve(approval.approvalId, value);
1117
- const question = this.#transcript.question;
1118
- if (question)
1119
- this.#answer(question.questionId, { text: value ? "yes" : "no" });
1120
- };
1121
- #cancel = () => {
1122
- if (this.#overlay || this.#picker)
1123
- return this.#dismiss();
1124
- if (this.#typing && this.#transcript.question?.options?.length) {
1125
- this.#typing = false;
1126
- this.#editor.clear();
1127
- return this.#renderNow();
1128
- }
1129
- const approval = this.#transcript.approval;
1130
- if (approval)
1131
- return void this.#agent.approve(approval.approvalId, false);
1132
- const question = this.#transcript.question;
1133
- if (question)
1134
- return void this.#answer(question.questionId, {});
1135
- if (this.#transcript.streaming)
1136
- return void this.#agent.abort();
1137
- if (!this.#editor.isEmpty) {
1138
- this.#editor.clear();
1139
- this.#renderNow();
1140
- }
1141
- };
1142
- #interrupt = () => {
1143
- if (this.#transcript.streaming) {
1144
- this.#agent.abort();
1145
- this.#say("interrupted \u2014 ^c again to quit");
1146
- return;
1147
- }
1148
- this.#quit();
1149
- };
1150
- #quit() {
1151
- if (this.#exiting)
1152
- return;
1153
- this.#exiting = true;
1154
- this.#stdout.write(`${CodeTuiMouse.off}${CodeTui.pasteOff}`);
1155
- this.#instance.clear();
1156
- this.#instance.unmount();
1157
- }
1158
- #submit = () => {
1159
- if (this.#picker)
1160
- return this.#resume(this.#picker.entries[this.#picker.at]?.id);
1161
- const question = this.#transcript.question;
1162
- if (question)
1163
- return void this.#answerCurrent(question.questionId);
1164
- const menu = this.#menu();
1165
- if (menu?.kind === "file")
1166
- return this.#complete();
1167
- const chosen = menu?.options[this.#menuAt];
1168
- const raw = chosen ? `/${chosen.key}` : this.#editor.text;
1169
- const pending = this.#pending(raw);
1170
- if (!pending.text && !pending.images.length)
1115
+ submit() {
1116
+ const menu = this.#menu();
1117
+ if (menu?.kind === "file")
1118
+ return this.complete();
1119
+ const chosen = menu?.options[this.#menuAt];
1120
+ const raw = chosen ? `/${chosen.key}` : this.#editor.text;
1121
+ const pending = this.#pending(raw);
1122
+ if (!pending.text && !pending.images.length)
1171
1123
  return;
1172
1124
  this.#editor.clear();
1173
1125
  this.#historyAt = -1;
1174
1126
  if (pending.text)
1175
1127
  this.#history.push(pending.text);
1176
1128
  if (pending.text.startsWith("/"))
1177
- return this.#command(pending.text);
1178
- this.#send(pending.text, pending.images);
1179
- };
1180
- #send(text, images = []) {
1129
+ return this.#host.command(pending.text);
1130
+ this.send(pending.text, pending.images);
1131
+ }
1132
+ send(text, images = []) {
1181
1133
  this.#images = [];
1182
1134
  this.#transcript.echo(text, images.length);
1183
- this.#renderNow();
1184
- this.#agent.prompt(text, images).catch((error) => this.#fail(error));
1135
+ this.#host.render();
1136
+ this.#agent.prompt(text, images).catch((error) => this.#host.fail(error));
1185
1137
  }
1186
- #paste = () => {
1138
+ paste = () => {
1187
1139
  if (!this.#agent.canSeeImages)
1188
- return this.#open("images", CodeTui.#imageHelp(this.#transcript.info?.model));
1189
- CodeTuiClipboard2.image().then((file) => file ? this.#attach(file) : this.#say("nothing on the clipboard we can attach")).catch((error) => this.#fail(error));
1140
+ return this.#overlay.open("images", CodeTuiPrompt.#imageHelp(this.#transcript.info?.model));
1141
+ CodeTuiClipboard2.image().then((file) => file ? this.#attach(file) : this.#host.say("nothing on the clipboard we can attach")).catch((error) => this.#host.fail(error));
1190
1142
  };
1191
- #pasted = (text) => {
1143
+ pasted = (text) => {
1192
1144
  if (text)
1193
- return this.#type(text.replace(/\r\n?/g, `
1145
+ return this.type(text.replace(/\r\n?/g, `
1194
1146
  `));
1195
1147
  if (CodeTuiClipboard2.has())
1196
- this.#paste();
1148
+ this.paste();
1197
1149
  };
1198
1150
  #attach(file) {
1199
1151
  this.#images.push(file);
1200
1152
  this.#editor.insert(`[image #${this.#images.length}] `);
1201
- this.#renderNow();
1153
+ this.#host.render();
1202
1154
  }
1203
1155
  #pending(text) {
1204
- const marks = [...text.matchAll(CodeTui.imageMark)].map((match) => Number(match[1]));
1156
+ const marks = [...text.matchAll(CodeTuiPrompt.imageMark)].map((match) => Number(match[1]));
1205
1157
  const images = marks.map((mark) => this.#images[mark - 1]).filter((file) => !!file).map((path) => ({ path }));
1206
- return { images, text: text.replace(CodeTui.imageMark, "").trim() };
1158
+ return { images, text: text.replace(CodeTuiPrompt.imageMark, "").trim() };
1207
1159
  }
1208
1160
  static #imageHelp(model) {
1209
1161
  const provider = model?.provider ?? "<provider>";
@@ -1217,72 +1169,444 @@ class CodeTui {
1217
1169
  ].join(`
1218
1170
  `);
1219
1171
  }
1220
- #openSessions = () => {
1221
- const entries = this.#agent.sessions();
1222
- if (!entries.length)
1223
- return this.#say("no stored sessions yet");
1224
- const current = this.#transcript.info?.sessionId;
1225
- this.#picker = {
1226
- entries,
1227
- at: Math.max(0, entries.findIndex((entry) => entry.id === current))
1172
+ }
1173
+
1174
+ // pkgs/@akanjs/cli/code/CodeTuiQuestion.ts
1175
+ class CodeTuiQuestion {
1176
+ static freeTextKey = "__free_text__";
1177
+ #agent;
1178
+ #transcript;
1179
+ #editor;
1180
+ #render;
1181
+ #selected = 0;
1182
+ #typing = false;
1183
+ #checked = [];
1184
+ constructor(agent, transcript, editor, render) {
1185
+ this.#agent = agent;
1186
+ this.#transcript = transcript;
1187
+ this.#editor = editor;
1188
+ this.#render = render;
1189
+ }
1190
+ get typing() {
1191
+ return this.#typing;
1192
+ }
1193
+ get checked() {
1194
+ return this.#checked;
1195
+ }
1196
+ block(question, frameRows) {
1197
+ const all = CodeTuiQuestion.optionsOf(question);
1198
+ const chrome = 1 + 2 * CodeTuiFrame.promptRuleRows;
1199
+ const budget = Math.max(1, frameRows - CodeTuiFrame.minBodyRows - CodeTuiFrame.chromeRows - chrome);
1200
+ const shown = Math.min(all.length, budget);
1201
+ const first = Math.max(0, Math.min(this.#selected - Math.floor(shown / 2), all.length - shown));
1202
+ return {
1203
+ rows: chrome + shown,
1204
+ above: CodeTuiFrame.promptRuleRows,
1205
+ selected: this.#selected - first,
1206
+ caret: undefined,
1207
+ snapshot: {
1208
+ input: [],
1209
+ menu: [],
1210
+ menuSelected: 0,
1211
+ options: all.slice(first, first + shown)
1212
+ }
1228
1213
  };
1229
- this.#renderNow();
1230
- };
1231
- #resume(id) {
1232
- if (!id)
1233
- return this.#dismiss();
1234
- if (id === this.#transcript.info?.sessionId)
1235
- return this.#dismiss();
1236
- this.#switchTo = { id };
1237
- this.#quit();
1238
1214
  }
1239
- #fork(argument) {
1240
- if (!this.#transcript.parts.some((part) => part.kind === "user"))
1241
- return this.#open("fork", "Nothing has been said in this session yet, so a fork of it is a new session.");
1242
- const from = this.#transcript.info?.sessionId ?? "";
1243
- try {
1244
- const forked = this.#agent.fork(argument.trim() || undefined);
1245
- this.#switchTo = { id: forked.id, notice: `forked \u2014 the original is akan code --resume ${from}` };
1246
- this.#quit();
1247
- } catch (error) {
1248
- this.#fail(error);
1249
- }
1215
+ static modeOf(question, approval) {
1216
+ if (approval)
1217
+ return "confirm";
1218
+ if (!question)
1219
+ return "input";
1220
+ if (question.kind === "confirm")
1221
+ return "confirm";
1222
+ if (question.kind === "select" && question.options?.length)
1223
+ return "select";
1224
+ return "input";
1250
1225
  }
1251
- #openQuestion(question) {
1226
+ static optionsOf(question) {
1227
+ const options = (question?.options ?? []).map((option) => ({
1228
+ key: option.key,
1229
+ label: option.recommended ? `${option.label} (recommended)` : option.label,
1230
+ ...option.detail ? { detail: option.detail } : {}
1231
+ }));
1232
+ if (!options.length || !question?.freeText)
1233
+ return options;
1234
+ return [
1235
+ ...options,
1236
+ { key: CodeTuiQuestion.freeTextKey, label: "Something else\u2026", detail: "answer in your own words" }
1237
+ ];
1238
+ }
1239
+ static promptOf(question, approval) {
1240
+ if (approval)
1241
+ return `approve? ${approval.summary} [y/n]`;
1242
+ return question ? `? ${question.prompt}` : "";
1243
+ }
1244
+ hint(mode, multiSelect) {
1245
+ if (this.#typing)
1246
+ return "enter answer \xB7 esc back to the choices";
1247
+ if (mode === "confirm")
1248
+ return "y yes \xB7 n no \xB7 esc no";
1249
+ if (mode === "select")
1250
+ return `\u2191\u2193 choose${multiSelect ? " \xB7 space toggle" : ""} \xB7 enter answer \xB7 esc skip \xB7 pgup/pgdn scroll`;
1251
+ return "enter send \xB7 shift+enter newline \xB7 \u2191\u2193 move \xB7 esc interrupt \xB7 pgup/pgdn scroll \xB7 ^c quit \xB7 /help";
1252
+ }
1253
+ placeholder() {
1254
+ if (this.#typing)
1255
+ return "your answer";
1256
+ if (this.#transcript.question)
1257
+ return "type an answer, or esc to skip";
1258
+ return this.#transcript.streaming ? "type to steer, esc to interrupt" : "ask for something, / for commands";
1259
+ }
1260
+ move(delta) {
1261
+ const count = CodeTuiQuestion.optionsOf(this.#transcript.question).length;
1262
+ if (!count)
1263
+ return;
1264
+ this.#selected = (this.#selected + delta + count) % count;
1265
+ this.#render();
1266
+ }
1267
+ toggle = () => {
1268
+ const option = CodeTuiQuestion.optionsOf(this.#transcript.question)[this.#selected];
1269
+ if (!option)
1270
+ return;
1271
+ this.#checked = this.#checked.includes(option.key) ? this.#checked.filter((key) => key !== option.key) : [...this.#checked, option.key];
1272
+ this.#render();
1273
+ };
1274
+ answerConfirm = (value) => {
1275
+ const approval = this.#transcript.approval;
1276
+ if (approval)
1277
+ return void this.#agent.approve(approval.approvalId, value);
1278
+ const question = this.#transcript.question;
1279
+ if (question)
1280
+ this.answer(question.questionId, { text: value ? "yes" : "no" });
1281
+ };
1282
+ open(question) {
1252
1283
  this.#typing = false;
1253
1284
  this.#checked = [];
1254
1285
  this.#selected = Math.max(0, (question.options ?? []).findIndex((option) => option.recommended));
1255
1286
  }
1256
- #answerCurrent(questionId) {
1287
+ answerCurrent(questionId) {
1257
1288
  const question = this.#transcript.question;
1258
- const shown = CodeTui.#optionsOf(question);
1289
+ const shown = CodeTuiQuestion.optionsOf(question);
1259
1290
  if (this.#typing || !shown.length) {
1260
1291
  const text = this.#editor.text.trim();
1261
1292
  this.#editor.clear();
1262
1293
  this.#typing = false;
1263
- return void this.#answer(questionId, { text });
1294
+ return void this.answer(questionId, { text });
1264
1295
  }
1265
- if (shown[this.#selected]?.key === CodeTui.freeTextKey) {
1296
+ if (shown[this.#selected]?.key === CodeTuiQuestion.freeTextKey) {
1266
1297
  this.#typing = true;
1267
1298
  this.#editor.clear();
1268
- return this.#renderNow();
1299
+ return this.#render();
1269
1300
  }
1270
- const keys = question?.multiSelect ? this.#checked.filter((key) => key !== CodeTui.freeTextKey) : [shown[this.#selected]?.key ?? ""];
1301
+ const keys = question?.multiSelect ? this.#checked.filter((key) => key !== CodeTuiQuestion.freeTextKey) : [shown[this.#selected]?.key ?? ""];
1302
+ this.#editor.clear();
1303
+ this.answer(questionId, { keys });
1304
+ }
1305
+ backToChoices() {
1306
+ this.#typing = false;
1271
1307
  this.#editor.clear();
1272
- this.#answer(questionId, { keys });
1308
+ this.#render();
1273
1309
  }
1274
- async#answer(questionId, answer) {
1310
+ async answer(questionId, answer) {
1275
1311
  this.#selected = 0;
1276
1312
  this.#checked = [];
1277
- this.#renderNow();
1313
+ this.#render();
1278
1314
  await this.#agent.answer(questionId, answer);
1279
1315
  }
1316
+ }
1317
+
1318
+ // pkgs/@akanjs/cli/code/CodeTui.tsx
1319
+ import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
1320
+
1321
+ class CodeTui {
1322
+ static frameMs = 34;
1323
+ static clipboardMs = CodeTuiPrompt.clipboardMs;
1324
+ static noticeMs = 4000;
1325
+ static chromeRows = CodeTuiFrame.chromeRows;
1326
+ static promptRuleRows = CodeTuiFrame.promptRuleRows;
1327
+ static minBodyRows = CodeTuiFrame.minBodyRows;
1328
+ static maxInputRows = CodeTuiFrame.maxInputRows;
1329
+ static title = CodeTuiFrame.title;
1330
+ static imageMark = CodeTuiPrompt.imageMark;
1331
+ static freeTextKey = CodeTuiQuestion.freeTextKey;
1332
+ static pasteOn = "\x1B[?2004h";
1333
+ static pasteOff = "\x1B[?2004l";
1334
+ #agent;
1335
+ #transcript = new CodeTranscript;
1336
+ #editor = new CodeTuiEditor2;
1337
+ #frame;
1338
+ #overlay;
1339
+ #prompt;
1340
+ #question;
1341
+ #runner;
1342
+ #listeners = new Set;
1343
+ #instance;
1344
+ #stdout;
1345
+ #anchor = null;
1346
+ #switchTo;
1347
+ #notice = "";
1348
+ #opening;
1349
+ #warnings;
1350
+ #noticeTimer = null;
1351
+ #frameTimer = null;
1352
+ #cached = null;
1353
+ #unsubscribe;
1354
+ #exiting = false;
1355
+ constructor(agent, { thinking = false, notice, warnings = [], ...streams } = {}) {
1356
+ this.#agent = agent;
1357
+ this.#opening = notice ?? "";
1358
+ this.#warnings = warnings;
1359
+ this.#stdout = streams.stdout ?? process.stdout;
1360
+ this.#frame = new CodeTuiFrame(this.#transcript, this.#stdout, thinking);
1361
+ const say = (text) => this.#say(text);
1362
+ const fail = (error) => this.#fail(error);
1363
+ const renderNow = () => this.#renderNow();
1364
+ this.#overlay = new CodeTuiOverlay(agent, this.#transcript, { render: renderNow, say });
1365
+ this.#prompt = new CodeTuiPrompt(agent, this.#transcript, this.#editor, this.#overlay, {
1366
+ render: renderNow,
1367
+ snapshot: this.#snapshot,
1368
+ say,
1369
+ fail,
1370
+ command: (line) => this.#command(line)
1371
+ });
1372
+ this.#question = new CodeTuiQuestion(agent, this.#transcript, this.#editor, renderNow);
1373
+ this.#runner = new CodeTuiCommandRunner(agent, this.#transcript, this.#overlay, {
1374
+ say,
1375
+ fail,
1376
+ leave: (exit) => {
1377
+ this.#switchTo = exit;
1378
+ this.#quit();
1379
+ }
1380
+ });
1381
+ this.#stdout.on("resize", this.#onResize);
1382
+ this.#instance = render(/* @__PURE__ */ jsxDEV2(CodeTuiApp, {
1383
+ actions: {
1384
+ subscribe: this.#subscribe,
1385
+ snapshot: this.#snapshot,
1386
+ type: this.#prompt.type,
1387
+ edit: this.#prompt.edit,
1388
+ submit: this.#submit,
1389
+ newline: this.#prompt.newline,
1390
+ paste: this.#prompt.paste,
1391
+ pasted: this.#prompt.pasted,
1392
+ complete: this.#prompt.complete,
1393
+ vertical: this.#vertical,
1394
+ scroll: this.#scroll,
1395
+ move: this.#move,
1396
+ toggle: this.#question.toggle,
1397
+ answerConfirm: this.#question.answerConfirm,
1398
+ cancel: this.#cancel,
1399
+ interrupt: this.#interrupt
1400
+ }
1401
+ }, undefined, false, undefined, this), {
1402
+ patchConsole: true,
1403
+ exitOnCtrlC: false,
1404
+ kittyKeyboard: { mode: "auto" },
1405
+ ...streams
1406
+ });
1407
+ }
1408
+ async run(seed) {
1409
+ this.#stdout.write(`${CodeTui.pasteOn}${CodeTuiMouse.on}`);
1410
+ if (this.#opening)
1411
+ this.#say(this.#opening);
1412
+ for (const warning of this.#warnings)
1413
+ this.#transcript.note("warning", warning);
1414
+ this.#unsubscribe = this.#agent.on((event) => {
1415
+ this.#transcript.apply(event);
1416
+ if (event.type === "question")
1417
+ this.#question.open(event.question);
1418
+ this.#scheduleFrame();
1419
+ });
1420
+ this.#agent.announce();
1421
+ this.#prompt.load().then(() => this.#renderNow());
1422
+ this.#prompt.watchClipboard();
1423
+ if (seed?.trim())
1424
+ this.#prompt.send(seed.trim());
1425
+ await this.#instance.waitUntilExit();
1426
+ this.#close();
1427
+ return this.#switchTo;
1428
+ }
1429
+ close() {
1430
+ this.#quit();
1431
+ }
1432
+ #close() {
1433
+ this.#prompt.unwatchClipboard();
1434
+ if (this.#frameTimer)
1435
+ clearTimeout(this.#frameTimer);
1436
+ if (this.#noticeTimer)
1437
+ clearTimeout(this.#noticeTimer);
1438
+ this.#frameTimer = null;
1439
+ this.#noticeTimer = null;
1440
+ this.#stdout.off("resize", this.#onResize);
1441
+ this.#unsubscribe?.();
1442
+ this.#farewell();
1443
+ }
1444
+ #farewell() {
1445
+ const info = this.#transcript.info;
1446
+ if (this.#switchTo || !info?.sessionId || !this.#agent.sessions().length)
1447
+ return;
1448
+ if (!this.#transcript.parts.some((part) => part.kind === "user"))
1449
+ return;
1450
+ const name = info.name ? ` (${info.name})` : "";
1451
+ this.#stdout.write(`Resume this session${name} with:
1452
+ akan code --resume ${info.sessionId}
1453
+ `);
1454
+ }
1455
+ #onResize = () => this.#renderNow();
1456
+ #subscribe = (listener) => {
1457
+ this.#listeners.add(listener);
1458
+ return () => this.#listeners.delete(listener);
1459
+ };
1460
+ #scheduleFrame() {
1461
+ if (this.#frameTimer)
1462
+ return;
1463
+ this.#frameTimer = setTimeout(() => {
1464
+ this.#frameTimer = null;
1465
+ this.#renderNow();
1466
+ }, CodeTui.frameMs);
1467
+ }
1468
+ #renderNow() {
1469
+ this.#cached = null;
1470
+ for (const listener of this.#listeners)
1471
+ listener();
1472
+ }
1473
+ static layout(frameRows, askRows, railRows = 0) {
1474
+ return CodeTuiFrame.layout(frameRows, askRows, railRows);
1475
+ }
1476
+ static frameRowsOf(terminalRows) {
1477
+ return CodeTuiFrame.frameRowsOf(terminalRows);
1478
+ }
1479
+ #snapshot = () => {
1480
+ if (this.#cached)
1481
+ return this.#cached;
1482
+ const columns = Math.max(40, this.#stdout.columns || 80);
1483
+ const frameRows = CodeTui.frameRowsOf(Math.max(10, this.#stdout.rows || 24));
1484
+ const question = this.#transcript.question;
1485
+ const approval = this.#transcript.approval;
1486
+ const mode = this.#question.typing ? "input" : CodeTuiQuestion.modeOf(question, approval);
1487
+ const subagents = this.#frame.railRows(columns);
1488
+ const ask = mode === "input" ? this.#prompt.block(columns, frameRows - subagents.length) : this.#question.block(question, frameRows - subagents.length);
1489
+ const { bodyHeight } = CodeTui.layout(frameRows, ask.rows, subagents.length);
1490
+ const width = columns - 2;
1491
+ const lines = this.#frame.lines(width);
1492
+ const end = this.#anchor === null ? lines.length : Math.min(lines.length, Math.max(bodyHeight, this.#anchor));
1493
+ const start = Math.max(0, end - bodyHeight);
1494
+ const above = start;
1495
+ const below = lines.length - end;
1496
+ this.#cached = {
1497
+ topRule: CodeTui.rule(this.#anchor === null ? "" : `\u25B2${above} \u25BC${below} paused`, this.#transcript.info?.name ?? this.#transcript.info?.sessionId.slice(0, 8) ?? "", columns),
1498
+ bottomRule: CodeTui.rule(this.#frame.queueLabel(), this.#frame.statusLabel(), columns),
1499
+ lines: lines.slice(start, end),
1500
+ above,
1501
+ below,
1502
+ following: this.#anchor === null,
1503
+ overlay: this.#overlay.block(width, bodyHeight),
1504
+ status: this.#frame.status(),
1505
+ subagents,
1506
+ mode,
1507
+ placeholder: this.#question.placeholder(),
1508
+ offered: this.#prompt.offered,
1509
+ prompt: CodeTuiQuestion.promptOf(question, approval),
1510
+ selected: ask.selected,
1511
+ checked: this.#question.checked,
1512
+ multiSelect: !!question?.multiSelect,
1513
+ notice: this.#notice,
1514
+ hint: this.#overlay.shown ? "esc close \xB7 \u2191\u2193 scroll" : this.#question.hint(mode, !!question?.multiSelect),
1515
+ columns,
1516
+ frameRows,
1517
+ bodyHeight,
1518
+ cursor: ask.caret ? { x: promptMarkWidth + ask.caret.col, y: bodyHeight + ask.above + ask.caret.row } : null,
1519
+ ...ask.snapshot
1520
+ };
1521
+ return this.#cached;
1522
+ };
1523
+ static rule(left, right, width) {
1524
+ return CodeTuiFrame.rule(left, right, width);
1525
+ }
1526
+ #vertical = (delta) => {
1527
+ if (this.#overlay.picker)
1528
+ return this.#move(delta);
1529
+ if (this.#overlay.shown)
1530
+ return this.#scroll(delta);
1531
+ this.#prompt.vertical(delta);
1532
+ };
1533
+ #scroll = (delta) => {
1534
+ if (this.#overlay.picker)
1535
+ return this.#move(Math.sign(delta));
1536
+ if (this.#overlay.shown)
1537
+ return this.#overlay.scroll(delta);
1538
+ const snapshot = this.#snapshot();
1539
+ const total = snapshot.above + snapshot.lines.length + snapshot.below;
1540
+ const rows = Math.max(1, snapshot.lines.length);
1541
+ if (total <= rows)
1542
+ return;
1543
+ const end = this.#anchor === null ? total : this.#anchor;
1544
+ const next = Math.min(total, Math.max(rows, end + Math.trunc(delta)));
1545
+ this.#anchor = next >= total ? null : next;
1546
+ this.#renderNow();
1547
+ };
1548
+ #move = (delta) => {
1549
+ if (this.#overlay.picker)
1550
+ return this.#overlay.move(delta);
1551
+ this.#question.move(delta);
1552
+ };
1553
+ #cancel = () => {
1554
+ if (this.#overlay.shown || this.#overlay.picker)
1555
+ return this.#overlay.dismiss();
1556
+ if (this.#question.typing && this.#transcript.question?.options?.length)
1557
+ return this.#question.backToChoices();
1558
+ const approval = this.#transcript.approval;
1559
+ if (approval)
1560
+ return void this.#agent.approve(approval.approvalId, false);
1561
+ const question = this.#transcript.question;
1562
+ if (question)
1563
+ return void this.#question.answer(question.questionId, {});
1564
+ if (this.#transcript.streaming)
1565
+ return void this.#agent.abort();
1566
+ if (!this.#editor.isEmpty) {
1567
+ this.#editor.clear();
1568
+ this.#renderNow();
1569
+ }
1570
+ };
1571
+ #interrupt = () => {
1572
+ if (this.#transcript.streaming) {
1573
+ this.#agent.abort();
1574
+ this.#say("interrupted \u2014 ^c again to quit");
1575
+ return;
1576
+ }
1577
+ this.#quit();
1578
+ };
1579
+ #quit() {
1580
+ if (this.#exiting)
1581
+ return;
1582
+ this.#exiting = true;
1583
+ this.#stdout.write(`${CodeTuiMouse.off}${CodeTui.pasteOff}`);
1584
+ this.#instance.clear();
1585
+ this.#instance.unmount();
1586
+ }
1587
+ #submit = () => {
1588
+ const picker = this.#overlay.picker;
1589
+ if (picker)
1590
+ return this.#resume(picker.entries[picker.at]?.id);
1591
+ const question = this.#transcript.question;
1592
+ if (question)
1593
+ return void this.#question.answerCurrent(question.questionId);
1594
+ this.#prompt.submit();
1595
+ };
1596
+ #resume(id) {
1597
+ if (!id)
1598
+ return this.#overlay.dismiss();
1599
+ if (id === this.#transcript.info?.sessionId)
1600
+ return this.#overlay.dismiss();
1601
+ this.#switchTo = { id };
1602
+ this.#quit();
1603
+ }
1280
1604
  #command(line) {
1281
1605
  const [name, ...rest] = line.slice(1).split(" ");
1282
1606
  const argument = rest.join(" ").trim();
1283
1607
  switch (name) {
1284
1608
  case "help":
1285
- return this.#open("help", CodeTuiCommands2.help());
1609
+ return this.#overlay.open("help", CodeTuiCommands2.help());
1286
1610
  case "quit":
1287
1611
  case "exit":
1288
1612
  return this.#quit();
@@ -1295,208 +1619,40 @@ class CodeTui {
1295
1619
  case "compact":
1296
1620
  return void this.#agent.compact(argument || undefined).catch((error) => this.#fail(error));
1297
1621
  case "autocompact":
1298
- return this.#setAutoCompact(argument);
1622
+ return this.#runner.setAutoCompact(argument);
1299
1623
  case "thinking":
1300
- this.#thinking = !this.#thinking;
1301
- return this.#say(this.#thinking ? "showing the model's reasoning" : "reasoning folded back to one line");
1624
+ return this.#say(this.#frame.toggleThinking() ? "showing the model's reasoning" : "reasoning folded back to one line");
1302
1625
  case "tools": {
1303
1626
  const tools = this.#transcript.info?.tools ?? [];
1304
- return this.#open("tools", `${tools.length} tools
1627
+ return this.#overlay.open("tools", `${tools.length} tools
1305
1628
 
1306
1629
  ${tools.join(" \xB7 ")}`);
1307
1630
  }
1308
1631
  case "model":
1309
- return this.#setModel(argument);
1632
+ return this.#runner.setModel(argument);
1310
1633
  case "effort":
1311
- return this.#setEffort(argument);
1634
+ return this.#runner.setEffort(argument);
1312
1635
  case "peers":
1313
- return this.#open("peers", CodeTui.#peerList(this.#agent.peers()));
1636
+ return this.#overlay.open("peers", CodeTuiCommandRunner.peerList(this.#agent.peers()));
1314
1637
  case "msg":
1315
- return this.#message(argument);
1638
+ return this.#runner.message(argument);
1316
1639
  case "fork":
1317
- return this.#fork(argument);
1640
+ return this.#runner.fork(argument);
1318
1641
  case "agents":
1319
- return this.#open("agents", this.#agentList());
1642
+ return this.#overlay.open("agents", this.#runner.agentList());
1320
1643
  case "mcp":
1321
- return this.#mcp(argument);
1644
+ return this.#runner.mcp(argument);
1322
1645
  case "name":
1323
1646
  if (!argument)
1324
- return this.#open("name", "Usage: /name <what this session is about>");
1647
+ return this.#overlay.open("name", "Usage: /name <what this session is about>");
1325
1648
  this.#agent.setName(argument);
1326
1649
  return this.#say(`session named ${argument}`);
1327
1650
  default:
1328
- return this.#open("unknown command", `There is no /${name}.
1651
+ return this.#overlay.open("unknown command", `There is no /${name}.
1329
1652
 
1330
1653
  ${CodeTuiCommands2.help()}`);
1331
1654
  }
1332
1655
  }
1333
- #agentList() {
1334
- const budget = this.#agent.profile.tools.subagent;
1335
- if (!budget)
1336
- return "Sub-agents are off in this profile.";
1337
- const column = Math.max(...Object.keys(SubagentPool2.kinds).map((kind) => kind.length)) + 2;
1338
- const kinds = Object.entries(SubagentPool2.kinds).map(([kind, spec]) => `${kind.padEnd(column)}${spec.desc}`);
1339
- return [
1340
- ...kinds,
1341
- "",
1342
- `At most ${budget.maxConcurrent} at once, ${budget.maxDepth} deep, ${budget.budget} tokens for the whole tree.`,
1343
- "",
1344
- "Ask for one in a sentence \u2014 the model calls the tool. Its reading never enters this conversation."
1345
- ].join(`
1346
- `);
1347
- }
1348
- #mcp(argument) {
1349
- const words = argument.split(" ").filter(Boolean);
1350
- const local = words.includes("--local");
1351
- const [verb, name, ...rest] = words.filter((word) => word !== "--local");
1352
- const root = this.#agent.workspaceRoot;
1353
- if (!verb)
1354
- return this.#open("mcp", CodeTuiMcp.list(this.#mcpView()));
1355
- if (verb === "reload")
1356
- return this.#reload("reconnected the MCP servers");
1357
- if (verb === "login" || verb === "logout")
1358
- return this.#mcpAuth(verb, name);
1359
- if (verb !== "add" && verb !== "remove") {
1360
- const status = this.#agent.mcpServers().find((entry) => entry.name === verb);
1361
- if (status)
1362
- return this.#open(`mcp \xB7 ${verb}`, CodeTuiMcp.tools(status));
1363
- return this.#open("mcp", [`There is no /mcp ${verb}.`, "", ...CodeTuiMcp.usage].join(`
1364
- `));
1365
- }
1366
- if (!name)
1367
- return this.#open("mcp", [`Usage:`, "", ...CodeTuiMcp.usage].join(`
1368
- `));
1369
- if (!CodeTuiMcp.namePattern.test(name))
1370
- return this.#open("mcp", `"${name}" cannot name a server: letters, digits, dash and underscore only.`);
1371
- try {
1372
- if (verb === "remove") {
1373
- const scope = WorkspaceTrust.carry(root, "mcp", () => McpServerConfig.remove(root, name, local ? "workspace" : undefined));
1374
- const remaining = McpServerConfig.declared(root).find((entry) => entry.ref.name === name);
1375
- if (!scope)
1376
- return this.#open("mcp", remaining ? `"${name}" is not declared in this repo's file; the ${remaining.scope} file declares it \u2014 /mcp remove ${name} removes it there.` : `No server named "${name}" is declared.`);
1377
- if (!remaining)
1378
- return this.#reload(`removed ${name} from the ${scope} file`);
1379
- return this.#reload(`removed ${name} from the ${scope} file \u2014 the ${remaining.scope} file still declares it, so it still applies; /mcp remove ${name} again to remove it there`);
1380
- }
1381
- const scope = local ? "workspace" : "global";
1382
- const ref = WorkspaceTrust.carry(root, "mcp", () => McpServerConfig.add(root, name, rest, scope));
1383
- const where = scope === "global" ? "every repo" : "this repo";
1384
- return this.#reload(`added ${name} \xB7 ${McpServerConfig.targetOf(ref)} \xB7 ${where}`);
1385
- } catch (error) {
1386
- this.#fail(error);
1387
- }
1388
- }
1389
- #mcpAuth(verb, name) {
1390
- const root = this.#agent.workspaceRoot;
1391
- if (!name)
1392
- return this.#open("mcp", [`Usage: /mcp ${verb} <name>`, "", ...CodeTuiMcp.usage].join(`
1393
- `));
1394
- const ref = McpServerConfig.read(root).find((entry) => entry.name === name);
1395
- if (verb === "logout") {
1396
- if (!McpTokenStore.clear(ref ?? { name }))
1397
- return this.#open("mcp", `"${name}" is not signed in.`);
1398
- return this.#reload(`signed out of ${name}`);
1399
- }
1400
- if (!ref)
1401
- return this.#open("mcp", `No server named "${name}" is declared.`);
1402
- this.#say(`signing in to ${name} \u2014 finish in the browser`);
1403
- McpSignIn.run(ref, { open: (url) => void openBrowser(url), onNotice: (message) => this.#say(message) }).then(() => this.#reload(`signed in to ${name}`)).catch((error) => this.#fail(error));
1404
- }
1405
- #mcpView() {
1406
- const root = this.#agent.workspaceRoot;
1407
- const problem = McpServerConfig.problem(root);
1408
- return {
1409
- status: this.#agent.mcpServers(),
1410
- declared: McpServerConfig.declared(root),
1411
- files: McpServerConfig.files(root),
1412
- workspaceApproved: WorkspaceTrust.isTrusted(root, "mcp"),
1413
- ...problem ? { problem } : {}
1414
- };
1415
- }
1416
- #reload(notice) {
1417
- const id = this.#transcript.info?.sessionId;
1418
- if (!id || !this.#agent.sessions().some((entry) => entry.id === id))
1419
- return this.#open("mcp", "This session is not on disk yet, so there is nothing to reopen. Say something first, or start a new `akan code`.");
1420
- this.#switchTo = { id, notice };
1421
- this.#quit();
1422
- }
1423
- static #peerList(peers) {
1424
- if (!peers.length)
1425
- return "No other akan code session is running in this workspace.";
1426
- const column = Math.max(...peers.map((peer) => peer.name.length)) + 2;
1427
- const rows = peers.map((peer) => `${peer.name.padEnd(column)}${peer.id.slice(0, 8)} ${peer.cwd}`);
1428
- return [...rows, "", "/msg <peer> <text> hands one of them a message."].join(`
1429
- `);
1430
- }
1431
- #message(argument) {
1432
- const [target, ...rest] = argument.split(" ");
1433
- const text = rest.join(" ").trim();
1434
- if (!target || !text)
1435
- return this.#open("msg", `Usage: /msg <peer> <text>
1436
-
1437
- ${CodeTui.#peerList(this.#agent.peers())}`);
1438
- try {
1439
- const peer = this.#agent.send(target, text);
1440
- this.#say(`sent to ${peer.name}`);
1441
- } catch (error) {
1442
- this.#fail(error);
1443
- }
1444
- }
1445
- #setEffort(argument) {
1446
- const levels = this.#agent.efforts();
1447
- if (!levels.length)
1448
- return this.#open("effort", "This model does no reasoning, so it has no effort to set.");
1449
- const wanted = argument.trim().toLowerCase();
1450
- if (!levels.includes(wanted))
1451
- return this.#open("effort", `Usage: /effort <level>
1452
-
1453
- now: ${this.#transcript.info?.effort ?? "unknown"}
1454
- ${levels.join(" \xB7 ")}`);
1455
- try {
1456
- this.#agent.setEffort(wanted);
1457
- this.#say(`effort ${this.#transcript.info?.effort ?? wanted}`);
1458
- } catch (error) {
1459
- this.#fail(error);
1460
- }
1461
- }
1462
- #setAutoCompact(argument) {
1463
- const percent = CodeTuiAutoCompact.parse(argument);
1464
- if (percent === undefined)
1465
- return this.#open("autocompact", CodeTuiAutoCompact.usage(this.#transcript.info));
1466
- try {
1467
- this.#agent.setAutoCompactAt(percent);
1468
- this.#say(CodeTuiAutoCompact.describe(this.#transcript.info));
1469
- } catch (error) {
1470
- this.#fail(error);
1471
- }
1472
- }
1473
- #setModel(argument) {
1474
- const wanted = argument.trim();
1475
- const [provider, ...rest] = wanted.split("/");
1476
- if (provider && rest.length)
1477
- return void this.#agent.setModel({ provider, id: rest.join("/") }).catch((error) => this.#fail(error));
1478
- const catalogue = this.#agent.catalogue();
1479
- if (wanted === "providers")
1480
- return this.#open("model \xB7 providers", CodeTuiModels.providers(catalogue));
1481
- if (!provider)
1482
- return this.#open("model", CodeTuiModels.list(catalogue));
1483
- const listing = CodeTuiModels.ofProvider(catalogue, provider);
1484
- if (listing)
1485
- return this.#open(`model \xB7 ${provider}`, listing);
1486
- return this.#open("model", [`There is no provider called "${provider}".`, "", ...CodeTuiModels.usage].join(`
1487
- `));
1488
- }
1489
- #open(title, text) {
1490
- this.#overlay = { title, text };
1491
- this.#overlayAt = 0;
1492
- this.#renderNow();
1493
- }
1494
- #dismiss() {
1495
- this.#overlay = null;
1496
- this.#overlayAt = 0;
1497
- this.#picker = null;
1498
- this.#renderNow();
1499
- }
1500
1656
  #fail(error) {
1501
1657
  this.#transcript.note("error", String(error));
1502
1658
  this.#renderNow();