lazyclaw 6.4.0 → 6.6.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.
package/commands/chat.mjs CHANGED
@@ -9,12 +9,11 @@ import {
9
9
  persistActiveModel, persistActiveProvider,
10
10
  _resolveAuthKey, _resolveBaseUrl, readVersionFromRepo,
11
11
  } from '../lib/config.mjs';
12
- import { renderRecord } from '../lib/render.mjs';
13
12
  import { ensureRegistry, requireRegistry, getRegistry } from '../lib/registry_boot.mjs';
14
13
  import { SUBCOMMANDS, parseArgs, AGENT_REG_SUBS } from '../lib/args.mjs';
15
14
  import {
16
- _attachGhostAutocomplete, _fetchModelsForProvider, _pauseChatForSubMenu,
17
- _pickModelInteractive, _pickProviderInteractive, _printChatBanner,
15
+ _attachGhostAutocomplete, _fetchModelsForProvider,
16
+ _pickProviderInteractive, _printChatBanner,
18
17
  _quickPrompt, _renderBanner, _renderV5Banner,
19
18
  } from '../tui/pickers.mjs';
20
19
  import { firstRunMode as _firstRunMode, hasConfiguredProvider } from '../first_run.mjs';
@@ -22,8 +21,11 @@ import { applyChatWindow as _applyChatWindow, estimateMessagesTokens, CHAT_WINDO
22
21
  import { makeRunTurn as _chatRunTurnFactory } from '../tui/run_turn.mjs';
23
22
  import { hudStatus as _hudStatus } from '../tui/hud.mjs';
24
23
  import { dispatchSlash as _dispatchSlash, parseSlashLine as _parseSlashLine, _makeInkApprove } from '../tui/slash_dispatcher.mjs';
25
- import { SLASH_COMMANDS } from '../tui/slash_commands.mjs';
26
24
  import { wrapInteractiveProv, makeLegacyApprove } from './chat_hardening.mjs';
25
+ import { makeLegacySlashHandler } from './chat_legacy_slash.mjs';
26
+ // Re-export so tests that import legacySlashRoute from ./chat.mjs keep working
27
+ // after the legacy slash router was extracted to ./chat_legacy_slash.mjs.
28
+ export { legacySlashRoute } from './chat_legacy_slash.mjs';
27
29
 
28
30
  // /new, /reset and /clear must signal the Ink REPL to wipe the screen +
29
31
  // scrollback via the 'NEW' sentinel (handled in tui/repl.mjs). _newReset itself
@@ -33,30 +35,10 @@ export function _isInkResetCmd(cmd) {
33
35
  return /^\/(new|reset|clear)$/i.test(String(cmd || ''));
34
36
  }
35
37
 
36
- // Legacy (non-Ink) slash routing for dispatcher-style, ctx-only commands.
37
- // The Ink REPL routes every slash through _dispatchSlash/SLASH_HANDLERS, but
38
- // the legacy readline path uses a hand-written switch (in cmdChat). This
39
- // exported helper is the wiring BOTH that switch and the regression test
40
- // drive. Returns 'EXIT' to break the loop, undefined when not owned here.
41
- export function legacySlashRoute(cmd, ctx) {
42
- switch (cmd) {
43
- // Legacy readline path has no modal picker, so BOTH /setup and /config
44
- // route to the full wizard here (the Ink path gives /config its
45
- // single-setting picker via tui/config_picker.mjs).
46
- case '/config':
47
- case '/setup':
48
- ctx.requestSetup = true;
49
- return 'EXIT';
50
- default:
51
- return undefined;
52
- }
53
- }
54
-
55
- // Dispatcher commands the legacy readline path's default branch may delegate to
56
- // _dispatchSlash. Kept to ctx-safe handlers only (no _inkCtx-only setters /
57
- // openPicker / version), so legacy doesn't silently degrade. /channels has a
58
- // lib/config fallback so it's safe; add others only after confirming ctx-safety.
59
- const LEGACY_DELEGATED_SLASHES = new Set(['/channels', '/orchestrator', '/context']);
38
+ // The legacy (non-Ink) readline slash router (legacySlashRoute,
39
+ // LEGACY_DELEGATED_SLASHES, and the ~650-line hand-written switch) lives in
40
+ // ./chat_legacy_slash.mjs now. cmdChat builds it via makeLegacySlashHandler
41
+ // (imported above) and legacySlashRoute is re-exported above for tests.
60
42
 
61
43
  export async function cmdChat(flags = {}) {
62
44
  await ensureRegistry();
@@ -545,657 +527,6 @@ export async function cmdChat(flags = {}) {
545
527
  writeFn: (chunk) => process.stdout.write(chunk),
546
528
  });
547
529
 
548
- const handleSlash = async (line) => {
549
- const cmd = line.split(/\s+/)[0];
550
- switch (cmd) {
551
- case '/help': {
552
- process.stdout.write('slash commands:\n');
553
- for (const c of SLASH_COMMANDS) process.stdout.write(` ${c.cmd.padEnd(8)} — ${c.help}\n`);
554
- return true;
555
- }
556
- case '/status': {
557
- const out = {
558
- provider: activeProvName,
559
- model: activeModel,
560
- keyMasked: getRegistry().maskApiKey(cfg['api-key']),
561
- messageCount: messages.length,
562
- };
563
- process.stdout.write(JSON.stringify(out) + '\n');
564
- return true;
565
- }
566
- case '/provider': {
567
- // `/provider <name>` switches the active provider for subsequent
568
- // turns. The conversation history stays put — the next user
569
- // message goes to the new provider with the existing context.
570
- // `/provider` (no arg) opens the family/provider/model picker so
571
- // the user can switch with arrow keys instead of memorising names.
572
- const arg = line.slice('/provider'.length).trim();
573
- if (!arg) {
574
- if (!useTerminal) {
575
- process.stdout.write(`provider: ${activeProvName}\n`);
576
- return true;
577
- }
578
- await _pauseChatForSubMenu(rl, _ghost, async () => {
579
- const picked = await _pickProviderInteractive();
580
- if (picked && picked.provider) {
581
- const next = lookupProv(picked.provider);
582
- if (!next) {
583
- process.stdout.write(`unknown provider: ${picked.provider}\n`);
584
- return;
585
- }
586
- activeProvName = picked.provider;
587
- prov = wrapInteractiveProv(next);
588
- if (picked.model) activeModel = picked.model;
589
- process.stdout.write(`provider → ${activeProvName}${picked.model ? ` · model → ${picked.model}` : ''}\n`);
590
- }
591
- });
592
- return true;
593
- }
594
- const next = lookupProv(arg);
595
- if (!next) {
596
- process.stdout.write(`unknown provider: ${arg} (known: ${Object.keys(getRegistry().PROVIDERS).join(', ')})\n`);
597
- return true;
598
- }
599
- activeProvName = arg;
600
- prov = wrapInteractiveProv(next);
601
- process.stdout.write(`provider → ${arg}\n`);
602
- return true;
603
- }
604
- case '/model': {
605
- // `/model <name>` updates the active model without touching the
606
- // provider. `/model` (no arg) opens the per-provider model picker
607
- // — same UX as setup step 3, scoped to the active provider.
608
- const arg = line.slice('/model'.length).trim();
609
- if (!arg) {
610
- if (!useTerminal) {
611
- process.stdout.write(`model: ${activeModel || '(default)'}\n`);
612
- return true;
613
- }
614
- await _pauseChatForSubMenu(rl, _ghost, async () => {
615
- const chosen = await _pickModelInteractive(activeProvName, { titlePrefix: 'LazyClaw chat —' });
616
- if (chosen === 'CANCEL' || chosen === 'BACK' || !chosen) return;
617
- activeModel = chosen;
618
- process.stdout.write(`model → ${activeModel}\n`);
619
- });
620
- return true;
621
- }
622
- // Honor unified provider/model: `/model anthropic/claude-opus-4-7`
623
- // splits and switches both.
624
- const { parseSlashProviderModel } = getRegistry();
625
- const parsed = parseSlashProviderModel(arg);
626
- if (parsed.provider) {
627
- const next = lookupProv(parsed.provider);
628
- if (!next) {
629
- process.stdout.write(`unknown provider: ${parsed.provider}\n`);
630
- return true;
631
- }
632
- activeProvName = parsed.provider;
633
- prov = wrapInteractiveProv(next);
634
- }
635
- activeModel = parsed.model || arg;
636
- process.stdout.write(`model → ${activeModel}${parsed.provider ? ` (provider → ${parsed.provider})` : ''}\n`);
637
- return true;
638
- }
639
- case '/new':
640
- case '/reset':
641
- case '/clear': {
642
- // /clear is dispatcher-only (no explicit legacy case before this),
643
- // so without it /clear fell through to `default:` → _dispatchSlash →
644
- // _newReset, which clears via ctx.set* setters that _legacyCtx does
645
- // NOT expose — returning 'cleared' while the closure's messages/
646
- // charsSent/runningUsage stayed intact (a lying no-op). Alias /clear
647
- // to the /new+/reset direct-mutation body, matching the dispatcher's
648
- // /clear → /new/reset session-reset aliasing.
649
- messages = [];
650
- charsSent = 0;
651
- runningUsage = null;
652
- if (sessionId) {
653
- const sm = await import('../sessions.mjs');
654
- sm.resetSession(sessionId, cfgDir);
655
- }
656
- process.stdout.write('cleared — new conversation\n');
657
- return true;
658
- }
659
- case '/usage': {
660
- const out = { messageCount: messages.length, charsSent };
661
- if (runningUsage) out.tokens = runningUsage;
662
- // When cfg.rates has a card for the active provider/model AND
663
- // we accumulated real usage, surface the running cost too. The
664
- // computation is local (pure arithmetic), no extra network.
665
- if (runningUsage && cfg.rates && typeof cfg.rates === 'object') {
666
- try {
667
- const { costFromUsage } = await import('../providers/rates.mjs');
668
- const r = costFromUsage(
669
- { provider: activeProvName, model: activeModel, usage: runningUsage },
670
- cfg.rates,
671
- );
672
- if (r) out.cost = r;
673
- } catch { /* never let cost-card lookup fail the slash */ }
674
- }
675
- process.stdout.write(JSON.stringify(out) + '\n');
676
- return true;
677
- }
678
- case '/skill': {
679
- // `/skill name1,name2` — replace the active system message with a
680
- // composition of the named skills. `/skill` (no arg) clears the
681
- // system message. The replacement happens in-place on the
682
- // messages array; the prior system turn (if any) is dropped so
683
- // we don't end up with two stacked system messages talking past
684
- // each other. When --session is set we persist the new system
685
- // message so the next invocation resumes with the same context.
686
- const arg = line.slice('/skill'.length).trim();
687
- const names = arg.split(',').map(s => s.trim()).filter(Boolean);
688
- const sysIdx = messages.findIndex(m => m.role === 'system');
689
- if (names.length === 0) {
690
- if (sysIdx >= 0) messages.splice(sysIdx, 1);
691
- if (sessionId) {
692
- // Persistent session: rewrite the file from scratch so the
693
- // dropped system turn doesn't linger as a stale entry.
694
- const sm = await import('../sessions.mjs');
695
- sm.resetSession(sessionId, cfgDir);
696
- for (const m of messages) sm.appendTurn(sessionId, m.role, m.content, cfgDir);
697
- }
698
- process.stdout.write('cleared system prompt (no active skills)\n');
699
- return true;
700
- }
701
- try {
702
- const sys = await (async () => {
703
- const mod = await import('../skills.mjs');
704
- return mod.composeSystemPrompt(names, cfgDir);
705
- })();
706
- if (!sys) {
707
- process.stdout.write('no skill content composed (empty input?)\n');
708
- return true;
709
- }
710
- if (sysIdx >= 0) messages[sysIdx] = { role: 'system', content: sys };
711
- else messages.unshift({ role: 'system', content: sys });
712
- if (sessionId) {
713
- const sm = await import('../sessions.mjs');
714
- sm.resetSession(sessionId, cfgDir);
715
- for (const m of messages) sm.appendTurn(sessionId, m.role, m.content, cfgDir);
716
- }
717
- process.stdout.write(`active skills: ${names.join(', ')}\n`);
718
- } catch (e) {
719
- process.stdout.write(`skill error: ${e?.message || e}\n`);
720
- }
721
- return true;
722
- }
723
- case '/loop': {
724
- // `/loop <prompt> [--max N] [--until "<regex>"]` — repeats one
725
- // user prompt against the active provider in the current session.
726
- // Default --max 3, hard cap 50. --until short-circuits when its
727
- // regex matches the latest assistant turn. Ctrl+C aborts the
728
- // current stream AND the whole loop (not just the in-flight
729
- // turn). Implementation lives in loop-engine.mjs; here we wire
730
- // it to the same provider streaming + buffered-writer used by a
731
- // normal user turn.
732
- const arg = line.slice('/loop'.length).trim();
733
- const loopMod = await import('../loop-engine.mjs');
734
- if (!arg) {
735
- process.stdout.write(`usage: /loop <prompt> [--max N] [--until "<regex>"]\n`);
736
- process.stdout.write(` default --max ${loopMod.LOOP_MAX_DEFAULT}, ceiling ${loopMod.LOOP_MAX_CEILING}\n`);
737
- process.stdout.write(` session: ${sessionId || '(none — turns will not be persisted)'}\n`);
738
- return true;
739
- }
740
- let parsed;
741
- try { parsed = loopMod.parseLoopArgs(arg); }
742
- catch (e) { process.stdout.write(`loop error: ${e?.message || e}\n`); return true; }
743
- let untilRe = null;
744
- try { untilRe = loopMod.compileUntil(parsed.until); }
745
- catch (e) { process.stdout.write(`loop error: ${e?.message || e}\n`); return true; }
746
-
747
- // Per-loop AbortController. Ctrl+C aborts the current provider
748
- // call (via signal) AND prevents the next iteration (the engine
749
- // sees signal.aborted on its loop check). Same handler shape as
750
- // the normal-turn path; symmetry keeps `/exit` clean afterwards.
751
- const loopAc = new AbortController();
752
- const onSigint = () => {
753
- loopAc.abort();
754
- process.stdout.write('\n^C interrupted — loop aborted\n');
755
- };
756
- process.on('SIGINT', onSigint);
757
-
758
- const sendOnce = async (msgs, signal) => {
759
- let acc = '';
760
- let _writeBuf = '';
761
- let _writeTimer = null;
762
- const _flush = () => {
763
- if (_writeBuf) { process.stdout.write(_writeBuf); _writeBuf = ''; }
764
- _writeTimer = null;
765
- };
766
- const _writeChunk = (s) => {
767
- _writeBuf += s;
768
- if (!_writeTimer) _writeTimer = setTimeout(_flush, 30);
769
- };
770
- try {
771
- for await (const chunk of prov.sendMessage(msgs, {
772
- apiKey: _resolveAuthKey(cfg, activeProvName),
773
- model: activeModel,
774
- sandbox: sandboxSpec,
775
- signal,
776
- onUsage: accumulateUsage,
777
- })) {
778
- _writeChunk(chunk);
779
- acc += chunk;
780
- }
781
- if (_writeTimer) clearTimeout(_writeTimer);
782
- _flush();
783
- process.stdout.write('\n');
784
- return acc;
785
- } catch (err) {
786
- if (_writeTimer) clearTimeout(_writeTimer);
787
- _flush();
788
- throw err;
789
- }
790
- };
791
-
792
- if (useTerminal) _ghost.suspend();
793
- // Capture the chat's existing system message (workspace / skill
794
- // composition) before we let the engine touch it; we restore it
795
- // after the loop so the chat continues with the same system.
796
- const _sysBefore = messages.find(m => m.role === 'system')?.content ?? null;
797
- const memMod = (parsed.useMemory || parsed.recall) ? await import('../memory.mjs') : null;
798
- const buildSystem = memMod ? (() => {
799
- // Called per iteration: memory.loadCore + recall re-read from
800
- // disk every call so a parallel writer mutating core.md /
801
- // episodic/* between iterations is reflected immediately.
802
- const parts = [];
803
- if (parsed.useMemory) {
804
- const core = memMod.loadCore(cfgDir);
805
- if (core && core.trim()) parts.push(core);
806
- }
807
- if (parsed.recall) {
808
- const text = memMod.recall(parsed.recall, { topN: 3 }, cfgDir);
809
- if (text && text.trim()) parts.push(text);
810
- }
811
- if (_sysBefore) parts.push(_sysBefore);
812
- return parts.join('\n\n---\n\n');
813
- }) : null;
814
- try {
815
- const result = await loopMod.runLoop({
816
- prompt: parsed.prompt,
817
- max: parsed.max,
818
- until: untilRe,
819
- messages,
820
- sendOnce,
821
- persist: (role, content) => persistTurn(role, content),
822
- onIteration: ({ i, max }) => {
823
- process.stderr.write(`\x1b[2m ↻ loop iteration ${i}/${max}\x1b[22m\n`);
824
- },
825
- signal: loopAc.signal,
826
- buildSystem,
827
- });
828
- charsSent += parsed.prompt.length * result.iterations;
829
- if (result.stoppedBy === 'until') {
830
- process.stderr.write(`\x1b[2m ✓ loop stopped by --until\x1b[22m\n`);
831
- } else if (result.stoppedBy === 'abort') {
832
- process.stderr.write(`\x1b[2m ⊘ loop aborted after ${result.iterations}/${parsed.max} iteration(s)\x1b[22m\n`);
833
- }
834
- } catch (err) {
835
- process.stdout.write(`loop error: ${err?.message || String(err)}\n`);
836
- } finally {
837
- process.off('SIGINT', onSigint);
838
- if (useTerminal) _ghost.resume();
839
- // Restore the chat's prior system message. The engine may have
840
- // overwritten messages[0] with the per-iter memory composition;
841
- // we put the original (workspace / skill) back so the
842
- // subsequent free-form chat turn sees the same system the user
843
- // configured before /loop ran.
844
- if (buildSystem) {
845
- const sysIdx = messages.findIndex(m => m.role === 'system');
846
- if (_sysBefore) {
847
- if (sysIdx >= 0) messages[sysIdx] = { role: 'system', content: _sysBefore };
848
- else messages.unshift({ role: 'system', content: _sysBefore });
849
- } else if (sysIdx >= 0) {
850
- messages.splice(sysIdx, 1);
851
- }
852
- }
853
- }
854
- return true;
855
- }
856
- case '/goal': {
857
- // /goal → list active goals
858
- // /goal <name> → switch chat context to goal:<name>
859
- // /goal add <name> [--desc "..."] [--cron "<spec>"]
860
- // /goal list → JSON of all goals
861
- // /goal show <name> → JSON of one
862
- // /goal close <name> [done|abandoned]
863
- const rawArg = line.slice('/goal'.length).trim();
864
- const goalsMod = await import('../goals.mjs');
865
- const loopMod = await import('../loop-engine.mjs');
866
- if (!rawArg) {
867
- const items = goalsMod.listGoals(cfgDir).filter(g => g.status === 'active');
868
- if (!items.length) { process.stdout.write('no active goals\n'); }
869
- else {
870
- for (const g of items) {
871
- process.stdout.write(` ${g.name}${g.description ? ' — ' + g.description : ''}${g.schedule ? ' (cron: ' + g.schedule + ')' : ''}\n`);
872
- }
873
- }
874
- return true;
875
- }
876
- let tokens;
877
- try { tokens = loopMod.splitArgs(rawArg); }
878
- catch (e) { process.stdout.write(`goal error: ${e?.message || e}\n`); return true; }
879
- const sub = tokens[0];
880
- const rest = tokens.slice(1);
881
- if (sub === 'add') {
882
- let name = null, desc = '', cron = null;
883
- for (let i = 0; i < rest.length; i++) {
884
- const t = rest[i];
885
- if (t === '--desc') desc = rest[++i] || '';
886
- else if (t === '--cron') cron = rest[++i] || null;
887
- else if (t.startsWith('--')) { process.stdout.write(`goal error: unknown flag ${t}\n`); return true; }
888
- else if (!name) name = t;
889
- else { process.stdout.write(`goal error: unexpected arg "${t}"\n`); return true; }
890
- }
891
- if (!name) { process.stdout.write('usage: /goal add <name> [--desc "..."] [--cron "<spec>"]\n'); return true; }
892
- try {
893
- const g = goalsMod.registerGoal({ name, description: desc, schedule: cron }, cfgDir);
894
- if (cron) {
895
- try { await (await import('../commands/automation.mjs'))._attachGoalCron(name, cron); }
896
- catch (e) { process.stdout.write(`goal warning: cron attach failed (${e?.message || e})\n`); }
897
- }
898
- process.stdout.write(`✓ goal ${g.name} added (status: active${cron ? `, cron: ${cron}` : ''})\n`);
899
- } catch (e) { process.stdout.write(`goal error: ${e?.message || e}\n`); }
900
- return true;
901
- }
902
- if (sub === 'list') {
903
- process.stdout.write(JSON.stringify(goalsMod.listGoals(cfgDir), null, 2) + '\n');
904
- return true;
905
- }
906
- if (sub === 'show') {
907
- const name = rest[0];
908
- if (!name) { process.stdout.write('usage: /goal show <name>\n'); return true; }
909
- const g = goalsMod.getGoal(name, cfgDir);
910
- if (!g) { process.stdout.write(`no goal "${name}"\n`); return true; }
911
- process.stdout.write(JSON.stringify(g, null, 2) + '\n');
912
- return true;
913
- }
914
- if (sub === 'close') {
915
- const name = rest[0];
916
- const outcome = rest[1] || 'done';
917
- if (!name) { process.stdout.write('usage: /goal close <name> [done|abandoned]\n'); return true; }
918
- try {
919
- const g = goalsMod.closeGoal(name, outcome, cfgDir);
920
- try { await (await import('../commands/automation.mjs'))._detachGoalCron(name); }
921
- catch (e) { process.stdout.write(`goal warning: cron detach failed (${e?.message || e})\n`); }
922
- process.stdout.write(`✓ goal ${g.name} closed (status: ${g.status})\n`);
923
- } catch (e) { process.stdout.write(`goal error: ${e?.message || e}\n`); }
924
- return true;
925
- }
926
- // Single-arg branch: switch context to goal:<name>.
927
- const goalName = sub;
928
- const g = goalsMod.getGoal(goalName, cfgDir);
929
- if (!g) {
930
- process.stdout.write(`no goal "${goalName}" — try: /goal add ${goalName} --desc "..."\n`);
931
- return true;
932
- }
933
- if (g.status !== 'active') {
934
- process.stdout.write(`goal "${goalName}" is ${g.status}; cannot switch\n`);
935
- return true;
936
- }
937
- // Switch: replace the chat's active session id and reload turns
938
- // from the goal's session. The provider, model, workspace, and
939
- // skill state stay put — only the conversation surface changes.
940
- sessionId = g.sessionId;
941
- activeGoalName = g.name;
942
- const prior = sessionsMod.loadTurns(sessionId, cfgDir);
943
- messages = prior.map(t => ({ role: t.role, content: t.content }));
944
- // Prepend a one-line goal note to the system message so the
945
- // model sees the current objective without us having to mutate
946
- // any persistent record on every switch.
947
- const sysIdx = messages.findIndex(m => m.role === 'system');
948
- const goalNote = `## Goal: ${g.description || g.name}`;
949
- if (sysIdx >= 0) {
950
- messages[sysIdx] = { role: 'system', content: `${goalNote}\n\n${messages[sysIdx].content}` };
951
- } else {
952
- messages.unshift({ role: 'system', content: goalNote });
953
- }
954
- process.stdout.write(`✓ switched to goal: ${g.name} (session: ${sessionId}, ${prior.length} prior turn(s))\n`);
955
- return true;
956
- }
957
- case '/memory': {
958
- const arg = line.slice('/memory'.length).trim();
959
- const memMod = await import('../memory.mjs');
960
- const tokens = arg.split(/\s+/).filter(Boolean);
961
- const which = tokens[0] || 'core';
962
- if (which === 'core') {
963
- const body = memMod.loadCore(cfgDir);
964
- process.stdout.write(body || '(empty core memory)\n');
965
- return true;
966
- }
967
- if (which === 'recent') {
968
- const items = memMod.loadRecent(20, cfgDir);
969
- process.stdout.write(JSON.stringify(items, null, 2) + '\n');
970
- return true;
971
- }
972
- if (which === 'episodic') {
973
- const topic = tokens[1];
974
- if (topic) {
975
- const body = memMod.loadEpisodic(topic, cfgDir);
976
- process.stdout.write(body || `(no episodic file "${topic}")\n`);
977
- } else {
978
- process.stdout.write(JSON.stringify(memMod.listEpisodic(cfgDir), null, 2) + '\n');
979
- }
980
- return true;
981
- }
982
- process.stdout.write('usage: /memory [core|recent|episodic [topic]]\n');
983
- return true;
984
- }
985
- case '/dream': {
986
- const memMod = await import('../memory.mjs');
987
- process.stdout.write(' ↯ dreaming…\n');
988
- try {
989
- const r = await memMod.dream(sessionId, {
990
- provider: prov,
991
- model: activeModel,
992
- apiKey: _resolveAuthKey(cfg, activeProvName),
993
- }, cfgDir);
994
- process.stdout.write(`✓ wrote ${r.topics.length} episodic file(s): ${r.topics.join(', ') || '(none)'}\n`);
995
- } catch (e) { process.stdout.write(`dream error: ${e?.message || e}\n`); }
996
- return true;
997
- }
998
- case '/agent': {
999
- const rawArg = line.slice('/agent'.length).trim();
1000
- const agentsMod = await import('../agents.mjs');
1001
- const loopMod = await import('../loop-engine.mjs');
1002
- let tokens;
1003
- try { tokens = loopMod.splitArgs(rawArg); }
1004
- catch (e) { process.stdout.write(`/agent error: ${e?.message || e}\n`); return true; }
1005
- const sub = tokens[0];
1006
- const rest = tokens.slice(1);
1007
- const aname = rest[0];
1008
- try {
1009
- if (!sub || sub === 'list') {
1010
- const agents = agentsMod.listAgents(cfgDir);
1011
- if (agents.length === 0) process.stdout.write('no agents registered. /agent add <name> [...] to create.\n');
1012
- else for (const a of agents) {
1013
- const provLine = a.model ? `${a.provider}/${a.model}` : a.provider;
1014
- process.stdout.write(`• ${a.name} — ${a.displayName} — ${provLine} — tools=[${(a.tools || []).join(',')}]\n`);
1015
- }
1016
- } else if (sub === 'show') {
1017
- if (!aname) { process.stdout.write('usage: /agent show <name> [json]\n'); return true; }
1018
- const a = agentsMod.getAgent(aname, cfgDir);
1019
- if (!a) process.stdout.write(`no agent "${aname}"\n`);
1020
- else if (rest[1] === 'json') process.stdout.write(JSON.stringify(a, null, 2) + '\n');
1021
- else process.stdout.write(renderRecord(a, { fields: ['name', 'displayName', 'provider', 'model', 'role', 'tools', 'tags', 'iconEmoji', 'memoryWrite', 'skillWrite', 'createdAt', 'updatedAt'] }) + '\n');
1022
- } else if (sub === 'add') {
1023
- if (!aname) { process.stdout.write('usage: /agent add <name> [role text…]\n'); return true; }
1024
- const roleText = rest.slice(1).join(' ').trim();
1025
- const a = agentsMod.registerAgent({ name: aname, role: roleText }, cfgDir);
1026
- process.stdout.write(`✓ added agent ${a.name} (tools=${a.tools.join(',')})\n`);
1027
- } else if (sub === 'remove' || sub === 'rm' || sub === 'delete') {
1028
- if (!aname) { process.stdout.write('usage: /agent remove <name>\n'); return true; }
1029
- agentsMod.removeAgent(aname, cfgDir);
1030
- process.stdout.write(`✓ removed agent ${aname}\n`);
1031
- } else {
1032
- process.stdout.write(`/agent: unknown sub "${sub}" — list|show|add|remove\n`);
1033
- }
1034
- } catch (e) {
1035
- process.stdout.write(`/agent error: ${e?.message || e}\n`);
1036
- }
1037
- return true;
1038
- }
1039
- case '/team': {
1040
- const rawArg = line.slice('/team'.length).trim();
1041
- const teamsMod = await import('../teams.mjs');
1042
- const loopMod = await import('../loop-engine.mjs');
1043
- let tokens;
1044
- try { tokens = loopMod.splitArgs(rawArg); }
1045
- catch (e) { process.stdout.write(`/team error: ${e?.message || e}\n`); return true; }
1046
- const sub = tokens[0];
1047
- const rest = tokens.slice(1);
1048
- const tname = rest[0];
1049
- try {
1050
- if (!sub || sub === 'list') {
1051
- const teams = teamsMod.listTeams(cfgDir);
1052
- if (teams.length === 0) process.stdout.write('no teams registered. /team add <name> --agents a,b --lead a [--channel #x]\n');
1053
- else for (const t of teams) {
1054
- const chLine = t.slackChannel ? ` — ${t.slackChannel}` : '';
1055
- process.stdout.write(`• ${t.name} — ${t.displayName} — lead=${t.lead} — agents=[${t.agents.join(',')}]${chLine}\n`);
1056
- }
1057
- } else if (sub === 'show') {
1058
- if (!tname) { process.stdout.write('usage: /team show <name>\n'); return true; }
1059
- const t = teamsMod.getTeam(tname, cfgDir);
1060
- if (!t) process.stdout.write(`no team "${tname}"\n`);
1061
- else process.stdout.write(JSON.stringify(t, null, 2) + '\n');
1062
- } else if (sub === 'add') {
1063
- // /team add <name> --agents a,b,c [--lead a] [--channel #x]
1064
- if (!tname) { process.stdout.write('usage: /team add <name> --agents a,b,c [--lead a] [--channel #x]\n'); return true; }
1065
- let agentsCsv = null, lead = null, channel = '';
1066
- for (let i = 1; i < rest.length; i++) {
1067
- const t = rest[i];
1068
- if (t === '--agents') agentsCsv = rest[++i] || '';
1069
- else if (t === '--lead') lead = rest[++i] || null;
1070
- else if (t === '--channel') channel = rest[++i] || '';
1071
- else { process.stdout.write(`/team error: unknown token "${t}"\n`); return true; }
1072
- }
1073
- if (!agentsCsv) { process.stdout.write('/team add: --agents is required\n'); return true; }
1074
- const agents = teamsMod.parseListFlag(agentsCsv);
1075
- const ch = channel ? await teamsMod.resolveSlackChannel(channel, {
1076
- botToken: process.env.SLACK_BOT_TOKEN || null,
1077
- apiBase: process.env.SLACK_API_BASE || 'https://slack.com/api',
1078
- logger: () => {},
1079
- }) : '';
1080
- const team = teamsMod.registerTeam({ name: tname, agents, lead, slackChannel: ch }, cfgDir);
1081
- process.stdout.write(`✓ added team ${team.name} (lead=${team.lead}, agents=${team.agents.join(',')})\n`);
1082
- } else if (sub === 'remove' || sub === 'rm' || sub === 'delete') {
1083
- if (!tname) { process.stdout.write('usage: /team remove <name>\n'); return true; }
1084
- teamsMod.removeTeam(tname, cfgDir);
1085
- process.stdout.write(`✓ removed team ${tname}\n`);
1086
- } else {
1087
- process.stdout.write(`/team: unknown sub "${sub}" — list|show|add|remove\n`);
1088
- }
1089
- } catch (e) {
1090
- process.stdout.write(`/team error: ${e?.message || e}\n`);
1091
- }
1092
- return true;
1093
- }
1094
- case '/handoff': {
1095
- // /handoff <target-channel> <externalId> [--note=...] — migrates the
1096
- // active thread (bound to replState.channel / replState.externalId)
1097
- // to a new channel and posts transition stubs on both sides. In the
1098
- // local-only chat REPL there is no bound channel, so we surface a
1099
- // clear error and stay in the REPL (acceptance test §F).
1100
- const parts = line.trim().split(/\s+/).slice(1);
1101
- if (parts.length < 2) {
1102
- process.stderr.write('usage: /handoff <target-channel> <externalId> [--note=...]\n');
1103
- return true;
1104
- }
1105
- const target = parts[0];
1106
- const externalId = parts[1];
1107
- const note = (parts.find(p => p.startsWith('--note=')) || '').slice(7);
1108
- try {
1109
- const { openThreads } = await import('../channels/threads.mjs');
1110
- const { runHandoff } = await import('../channels/handoff.mjs');
1111
- const threads = openThreads(cfgDir);
1112
- const replState = globalThis.__lazyclawReplState || {};
1113
- const cur = replState.channel && replState.externalId
1114
- ? threads.findByExternal(replState.channel, replState.externalId)
1115
- : null;
1116
- if (!cur) {
1117
- process.stderr.write(
1118
- `handoff: no thread bound to ${replState.channel || '(none)'}:${replState.externalId || '(none)'}\n`,
1119
- );
1120
- return true;
1121
- }
1122
- const next = await runHandoff({
1123
- threads, channels: replState.channels || {},
1124
- threadId: cur.threadId, target, externalId, note,
1125
- });
1126
- process.stdout.write(`handoff -> ${next.channel}:${next.externalId} (session ${next.sessionId})\n`);
1127
- replState.channel = next.channel;
1128
- replState.externalId = next.externalId;
1129
- } catch (e) {
1130
- process.stderr.write(`handoff failed: ${e.code || 'ERR'}: ${e.message}\n`);
1131
- }
1132
- return true;
1133
- }
1134
- case '/personality': {
1135
- // Phase G: thin slash wrapper over cmdPersonality.
1136
- const tail = line.slice('/personality'.length).trim();
1137
- const parts = tail.split(/\s+/).filter(Boolean);
1138
- await (await import('../commands/config.mjs')).cmdPersonality(parts[0] || 'list', parts[1], parts[2]);
1139
- return true;
1140
- }
1141
- case '/exit': {
1142
- // v5 Group A (C4): fire one updateUserModel call before exit so
1143
- // the Honcho-style USER.md captures the durable facts surfaced
1144
- // in this session. Wrapped in a 3-second timeout so a slow
1145
- // trainer never makes /exit hang. Best-effort: failure logs are
1146
- // suppressed so we don't disturb the clean shutdown.
1147
- try {
1148
- const turns = sessionId
1149
- ? sessionsMod.loadTurns(sessionId, cfgDir)
1150
- : messages.map((t) => ({ role: t.role, content: t.content }));
1151
- if (turns && turns.length) {
1152
- const trainer = (typeof getRegistry()?.resolveTrainer === 'function')
1153
- ? getRegistry().resolveTrainer(cfg)
1154
- : { provider: activeProvName, model: activeModel };
1155
- const userModelPromise = import('../mas/user_modeler.mjs').then((m) =>
1156
- m.updateUserModel({
1157
- sessionTurns: turns,
1158
- provider: trainer.provider,
1159
- model: trainer.model,
1160
- apiKey: _resolveAuthKey(cfg, trainer.provider),
1161
- baseUrl: _resolveBaseUrl(trainer.provider),
1162
- configDir: cfgDir,
1163
- }),
1164
- ).catch(() => null);
1165
- await Promise.race([
1166
- userModelPromise,
1167
- new Promise((resolve) => setTimeout(resolve, 3000)),
1168
- ]);
1169
- }
1170
- } catch { /* /exit must never hang or throw */ }
1171
- return 'EXIT';
1172
- }
1173
- case '/config':
1174
- case '/setup': {
1175
- // Shared legacySlashRoute wiring (tests/f-config-slash-splash.test.mjs):
1176
- // sets requestSetup + 'EXIT'; the post-loop guard runs the wizard.
1177
- return legacySlashRoute(cmd, _legacyCtx);
1178
- }
1179
- default: {
1180
- // Delegate ONLY ctx-safe dispatcher commands to the shared handler.
1181
- // _legacyCtx is intentionally thin (no setters / openPicker / version),
1182
- // so a blanket delegation would silently degrade picker- or setter-
1183
- // driven handlers (/menu, /clear, /version, …). /channels is ctx-safe
1184
- // (it has a lib/config fallback); everything else stays an honest
1185
- // "unknown slash". 'EXIT' breaks the loop; a returned string prints.
1186
- if (LEGACY_DELEGATED_SLASHES.has(cmd)) {
1187
- const { args } = _parseSlashLine(line);
1188
- const r = await _dispatchSlash(cmd, args, _legacyCtx, (s) => process.stdout.write(s));
1189
- if (r === 'EXIT') return 'EXIT';
1190
- if (typeof r === 'string' && r.length) process.stdout.write(r + '\n');
1191
- return true;
1192
- }
1193
- process.stdout.write(`unknown slash: ${cmd} (try /help)\n`);
1194
- return true;
1195
- }
1196
- }
1197
- };
1198
-
1199
530
  // Create the readline interface here — immediately before iterating, with
1200
531
  // no `await` between — so a non-TTY pipe's buffered lines reach the async
1201
532
  // iterator (see the note at the rl/_ghost declaration above).
@@ -1213,11 +544,46 @@ export async function cmdChat(flags = {}) {
1213
544
  _ghost = _attachGhostAutocomplete(rl) || _ghost;
1214
545
  rl.prompt();
1215
546
  }
547
+ // Build the legacy readline slash router now that rl/_ghost exist (the
548
+ // handler reads them at call time). It lives in ./chat_legacy_slash.mjs to
549
+ // keep this file under its size ceiling; getX/setX accessors keep cmdChat's
550
+ // mutable chat state (provider, model, messages, sessionId, …) live so a
551
+ // mid-session /provider or /goal switch takes effect on the very next turn.
552
+ const _legacyHandleSlash = makeLegacySlashHandler({
553
+ cfg,
554
+ cfgDir,
555
+ lookupProv,
556
+ persistTurn,
557
+ accumulateUsage,
558
+ legacyCtx: _legacyCtx,
559
+ sessionsMod,
560
+ useTerminal,
561
+ sandboxSpec,
562
+ rl,
563
+ ghost: _ghost,
564
+ getActiveProvName: () => activeProvName,
565
+ setActiveProvName: (v) => { activeProvName = v; },
566
+ getActiveModel: () => activeModel,
567
+ setActiveModel: (v) => { activeModel = v; },
568
+ getProv: () => prov,
569
+ setProv: (v) => { prov = v; },
570
+ getMessages: () => messages,
571
+ setMessages: (v) => { messages = v; },
572
+ getCharsSent: () => charsSent,
573
+ setCharsSent: (v) => { charsSent = v; },
574
+ getRunningUsage: () => runningUsage,
575
+ setRunningUsage: (v) => { runningUsage = v; },
576
+ getSessionId: () => sessionId,
577
+ setSessionId: (v) => { sessionId = v; },
578
+ getActiveGoalName: () => activeGoalName,
579
+ setActiveGoalName: (v) => { activeGoalName = v; },
580
+ });
581
+
1216
582
  try { for await (const line of rl) {
1217
583
  const text = line.trim();
1218
584
  if (!text) { if (useTerminal) rl.prompt(); continue; }
1219
585
  if (text.startsWith('/')) {
1220
- const r = await handleSlash(text);
586
+ const r = await _legacyHandleSlash(text);
1221
587
  if (r === 'EXIT') break;
1222
588
  if (useTerminal) rl.prompt();
1223
589
  continue;